runner.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. package main
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "flag"
  7. "fmt"
  8. "log"
  9. "log/slog"
  10. "math"
  11. "net"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/ollama/ollama/api"
  22. "github.com/ollama/ollama/llama"
  23. )
  24. // input is an element of the prompt to process, either
  25. // a token or an embedding (e.g. generated from a vision projector)
  26. type input struct {
  27. token int
  28. // embd is an image embedding
  29. // important to note, embd contains a series of embeddings, all backed
  30. // by a single float* buffer
  31. // TODO (jmorganca):
  32. embd *llama.LlavaImageEmbed
  33. }
  34. type Sequence struct {
  35. // number of tokens evaluated
  36. nPast int
  37. // batch index
  38. iBatch int
  39. // number of tokens predicted so far
  40. numPredicted int
  41. // prompt inputs left to evaluate
  42. inputs []input
  43. // channel to send responses over
  44. responses chan string
  45. // number of tokens to predict
  46. numPredict int
  47. samplingCtx *llama.SamplingContext
  48. // channel to send back the embedding if embedding only
  49. embedding chan []float32
  50. // stop sequences
  51. stop []string
  52. // true if an embedding are to be returned instead of text generation
  53. embeddingOnly bool
  54. doneReason string
  55. pieces []string
  56. // Metrics
  57. t_start_process_prompt time.Time
  58. t_start_genereration time.Time
  59. n_decoded int
  60. n_prompt_tokens int
  61. }
  62. // prompt returns true if the prompt is still being processed
  63. // TODO (jmorganca): clean up this logic
  64. func (s *Sequence) isPromptProcessing() bool {
  65. var total int
  66. for _, i := range s.inputs {
  67. if i.embd == nil {
  68. total++
  69. continue
  70. }
  71. total += i.embd.Tokens()
  72. }
  73. return s.nPast < total-1
  74. }
  75. // inputs processes the prompt and images into a list of inputs
  76. // by splitting the prompt on [img-<n>] tags, tokenizing text and
  77. // generating image embeddings for each image
  78. func (s *Server) inputs(prompt string, images []string) ([]input, error) {
  79. var inputs []input
  80. re := regexp.MustCompile(`\[img-(\d+)\]`)
  81. parts := re.Split(prompt, -1)
  82. matches := re.FindAllStringSubmatch(prompt, -1)
  83. for i, part := range parts {
  84. // text - tokenize
  85. if strings.TrimSpace(part) != "" {
  86. tokens, err := s.lc.Model().Tokenize(prompt, false, true)
  87. if err != nil {
  88. return nil, err
  89. }
  90. for _, t := range tokens {
  91. inputs = append(inputs, input{token: t})
  92. }
  93. }
  94. // image - generate image embedding
  95. if i < len(matches) {
  96. n, _ := strconv.Atoi(matches[i][1])
  97. if n < 0 || n >= len(images) {
  98. return nil, fmt.Errorf("invalid image index: %d", n)
  99. }
  100. decoded, err := base64.StdEncoding.DecodeString(images[n])
  101. if err != nil {
  102. // TODO (jmorganca): return an error?
  103. slog.Error("Failed to decode image", "error", err)
  104. return nil, err
  105. }
  106. // Vision models can not be used concurrently
  107. s.clip.mu.Lock()
  108. // todo: check for duplicates so we don't encode the same image twice
  109. slog.Info("encoding image", "n", n)
  110. embd := llama.NewLlavaImageEmbed(s.clip.cc, decoded)
  111. s.clip.mu.Unlock()
  112. inputs = append(inputs, input{embd: embd})
  113. }
  114. }
  115. return inputs, nil
  116. }
  117. func (s *Server) NewSequence(prompt string, images []string, numPredict int, stop []string, params *llama.SamplingParams, embedding bool) (*Sequence, error) {
  118. inputs, err := s.inputs(prompt, images)
  119. if err != nil {
  120. return nil, fmt.Errorf("failed to process inputs: %w", err)
  121. }
  122. var sc *llama.SamplingContext
  123. if params != nil {
  124. sc = llama.NewSamplingContext(*params)
  125. for _, t := range inputs {
  126. if t.embd == nil {
  127. sc.Accept(s.lc, t.token, false)
  128. }
  129. }
  130. }
  131. return &Sequence{
  132. inputs: inputs,
  133. n_prompt_tokens: len(inputs),
  134. responses: make(chan string, 1),
  135. embedding: make(chan []float32, 1),
  136. samplingCtx: sc,
  137. embeddingOnly: embedding,
  138. stop: stop,
  139. }, nil
  140. }
  141. type clip struct {
  142. cc *llama.ClipContext
  143. mu sync.Mutex
  144. }
  145. type Server struct {
  146. model *llama.Model
  147. lc *llama.Context
  148. // required for image embeddings
  149. clip clip
  150. // batchSize is the number of tokens or image embeddings
  151. // to process in a batch
  152. batchSize int
  153. // parallel is the number of parallel requests to handle
  154. parallel int
  155. // seqs is the list of parallel sequences being evaluated
  156. // TODO (jmorganca): this can probably be moved into run()
  157. seqs []*Sequence
  158. // context window size
  159. numCtx int
  160. mu sync.Mutex
  161. cond *sync.Cond
  162. progress float32
  163. status string
  164. }
  165. // waiting is true if there are no sequences to process
  166. func (s *Server) waiting() bool {
  167. for _, item := range s.seqs {
  168. if item != nil {
  169. return false
  170. }
  171. }
  172. return true
  173. }
  174. // processImage processes an image embedding if it's next in any sequence
  175. func (s *Server) processImage() bool {
  176. for i, seq := range s.seqs {
  177. fmt.Println("seq", i, "inputs", len(seq.inputs))
  178. if len(seq.inputs) > 0 && seq.inputs[0].embd != nil {
  179. slog.Info("processing image", "seq", i, "nPast", seq.nPast)
  180. llama.LlavaEvalImageEmbed(s.lc, seq.inputs[0].embd, s.batchSize, &seq.nPast)
  181. llama.LlavaImageEmbedFree(seq.inputs[0].embd)
  182. seq.iBatch = seq.inputs[0].embd.Tokens() - 1
  183. seq.inputs = seq.inputs[1:]
  184. return true
  185. }
  186. }
  187. return false
  188. }
  189. func (s *Server) run(ctx context.Context) {
  190. batch := llama.NewBatch(s.batchSize, 0, s.parallel)
  191. defer batch.Free()
  192. for {
  193. select {
  194. case <-ctx.Done():
  195. return
  196. default:
  197. slog.Info("Processing batch", "seqs", len(s.seqs))
  198. s.mu.Lock()
  199. for s.waiting() {
  200. s.cond.Wait()
  201. }
  202. s.mu.Unlock()
  203. // first process an image embedding if is it next on any sequence
  204. // TODO (jmorganca): this will block calls to `Decode` below
  205. // until images are processed
  206. if s.processImage() {
  207. continue
  208. }
  209. // create a token batch to process
  210. for i, seq := range s.seqs {
  211. if seq == nil {
  212. continue
  213. }
  214. hitLimit := seq.numPredict > 0 && seq.numPredicted > seq.numPredict
  215. // if past the num predict limit
  216. // TODO (jmorganca): should context shift
  217. if hitLimit || seq.nPast > s.numCtx {
  218. seq.doneReason = "limit"
  219. close(seq.responses)
  220. s.lc.KvCacheSeqRm(i, 0, -1)
  221. s.seqs[i] = nil
  222. continue
  223. }
  224. if seq.t_start_process_prompt.IsZero() {
  225. seq.t_start_process_prompt = time.Now()
  226. }
  227. for j, t := range seq.inputs {
  228. // break if this is an image embedding to be handled in a follow up batch
  229. if t.embd != nil {
  230. break
  231. }
  232. if j > s.batchSize {
  233. break
  234. }
  235. slog.Info("adding token to batch", "token", t.token, "seq", i)
  236. batch.Add(t.token, seq.nPast, []int{i}, !seq.isPromptProcessing())
  237. seq.nPast++
  238. }
  239. seq.iBatch = batch.NumTokens() - 1
  240. }
  241. if batch.NumTokens() > 0 {
  242. err := s.lc.Decode(batch)
  243. if err != nil {
  244. slog.Error("failed to decode batch", "error", err)
  245. // TODO (jmorganca): handle this better by returning an error
  246. panic(err)
  247. }
  248. }
  249. // sample and send responses
  250. for i, seq := range s.seqs {
  251. if seq == nil {
  252. continue
  253. }
  254. // don't sample while prompt processing
  255. if seq.isPromptProcessing() {
  256. if batch.NumTokens() > 0 {
  257. seq.inputs = seq.inputs[batch.NumTokens():]
  258. } else {
  259. // image case
  260. // TODO (jmorganca): simplify this
  261. seq.inputs = seq.inputs[1:]
  262. }
  263. continue
  264. }
  265. // if done processing the prompt, send an embedding
  266. if seq.embeddingOnly {
  267. embd := s.lc.GetEmbeddingsSeq(i)
  268. if embd == nil {
  269. embd = s.lc.GetEmbeddingsIth(seq.iBatch)
  270. }
  271. seq.embedding <- embd
  272. close(seq.embedding)
  273. s.lc.KvCacheSeqRm(i, 0, -1)
  274. s.seqs[i] = nil
  275. continue
  276. }
  277. token := seq.samplingCtx.Sample(s.lc, nil, seq.iBatch)
  278. seq.samplingCtx.Accept(s.lc, token, true)
  279. seq.n_decoded += 1
  280. if seq.n_decoded == 1 {
  281. seq.t_start_genereration = time.Now()
  282. }
  283. piece := s.model.TokenToPiece(token)
  284. seq.numPredicted++
  285. slog.Debug("sampled", "piece", piece)
  286. // if it's an end of sequence token, break
  287. // TODO: just end this sequence
  288. if s.model.TokenIsEog(token) {
  289. // TODO: end the sequence instead of quitting the pool
  290. s.lc.KvCacheSeqRm(i, 0, -1)
  291. // TODO (jmorganca): we should send this back
  292. // as it's important for the /api/generate context
  293. // seq.responses <- piece
  294. seq.doneReason = "stop"
  295. close(seq.responses)
  296. seq.samplingCtx.Free()
  297. s.seqs[i] = nil
  298. continue
  299. }
  300. seq.inputs = []input{{token: token}}
  301. seq.pieces = append(seq.pieces, piece)
  302. sequence := strings.Join(seq.pieces, "")
  303. if ok, stop := findStop(sequence, seq.stop); ok {
  304. slog.Info("hit stop token", "stop", seq.stop)
  305. truncated := truncateStop(seq.pieces, stop)
  306. for _, p := range truncated {
  307. seq.responses <- p
  308. }
  309. s.lc.KvCacheSeqRm(i, 0, -1)
  310. seq.doneReason = "stop"
  311. close(seq.responses)
  312. seq.samplingCtx.Free()
  313. s.seqs[i] = nil
  314. continue
  315. }
  316. if maybeStop(sequence, seq.stop) {
  317. continue
  318. }
  319. for _, p := range seq.pieces {
  320. seq.responses <- p
  321. }
  322. seq.pieces = []string{}
  323. }
  324. batch.Clear()
  325. }
  326. }
  327. }
  328. // TODO (jmorganca): use structs from the api package to avoid duplication
  329. // this way the api acts as a proxy instead of using a different api for the
  330. // runner
  331. type CompletionRequest struct {
  332. Prompt string `json:"prompt"`
  333. Images []string `json:"images"`
  334. Grammar string `json:"grammar"`
  335. Stop []string `json:"stop"`
  336. api.Options
  337. }
  338. type Timings struct {
  339. PredictedN int `json:"predicted_n"`
  340. PredictedMS float64 `json:"predicted_ms"`
  341. PromptN int `json:"prompt_n"`
  342. PromptMS float64 `json:"prompt_ms"`
  343. }
  344. type CompletionResponse struct {
  345. Content string `json:"content"`
  346. Stop bool `json:"stop"`
  347. Model string `json:"model,omitempty"`
  348. Prompt string `json:"prompt,omitempty"`
  349. StoppedLimit bool `json:"stopped_limit,omitempty"`
  350. PredictedN int `json:"predicted_n,omitempty"`
  351. PredictedMS float64 `json:"predicted_ms,omitempty"`
  352. PromptN int `json:"prompt_n,omitempty"`
  353. PromptMS float64 `json:"prompt_ms,omitempty"`
  354. Timings Timings `json:"timings"`
  355. }
  356. func (s *Server) completion(w http.ResponseWriter, r *http.Request) {
  357. var req CompletionRequest
  358. req.Options = api.DefaultOptions()
  359. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  360. http.Error(w, "Bad request", http.StatusBadRequest)
  361. return
  362. }
  363. // Set the headers to indicate streaming
  364. w.Header().Set("Content-Type", "application/json")
  365. w.Header().Set("Transfer-Encoding", "chunked")
  366. w.WriteHeader(http.StatusOK)
  367. var samplingParams llama.SamplingParams
  368. samplingParams.TopK = req.TopK
  369. samplingParams.TopP = req.TopP
  370. samplingParams.TfsZ = req.TFSZ
  371. samplingParams.TypicalP = req.TypicalP
  372. samplingParams.Temp = req.Temperature
  373. samplingParams.PenaltyRepeat = req.RepeatPenalty
  374. samplingParams.PenaltyFreq = req.FrequencyPenalty
  375. samplingParams.PenaltyPresent = req.PresencePenalty
  376. samplingParams.Mirostat = req.Mirostat
  377. samplingParams.MirostatTau = req.MirostatTau
  378. samplingParams.MirostatEta = req.MirostatEta
  379. samplingParams.PenalizeNl = req.PenalizeNewline
  380. samplingParams.Seed = uint32(req.Seed)
  381. samplingParams.Grammar = req.Grammar
  382. seq, err := s.NewSequence(req.Prompt, req.Images, req.NumPredict, req.Stop, &samplingParams, false)
  383. if err != nil {
  384. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  385. return
  386. }
  387. // TODO (jmorganca): add to sequence queue instead of
  388. // failing if a slot isn't available
  389. s.mu.Lock()
  390. for i, sq := range s.seqs {
  391. if sq == nil {
  392. s.seqs[i] = seq
  393. s.cond.Signal()
  394. break
  395. }
  396. }
  397. s.mu.Unlock()
  398. // stream the response
  399. for content := range seq.responses {
  400. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  401. Content: content,
  402. }); err != nil {
  403. http.Error(w, fmt.Sprintf("failed to encode response: %v", err), http.StatusInternalServerError)
  404. return
  405. }
  406. flusher, ok := w.(http.Flusher)
  407. if !ok {
  408. http.Error(w, "could not get flusher", http.StatusInternalServerError)
  409. return
  410. }
  411. flusher.Flush()
  412. }
  413. // Send the stop
  414. if err := json.NewEncoder(w).Encode(&CompletionResponse{
  415. Stop: true,
  416. Timings: Timings{
  417. PromptN: seq.n_prompt_tokens,
  418. PromptMS: float64(seq.t_start_genereration.Sub(seq.t_start_process_prompt).Milliseconds()),
  419. PredictedN: seq.n_decoded,
  420. PredictedMS: float64(time.Since(seq.t_start_genereration).Milliseconds()),
  421. },
  422. }); err != nil {
  423. http.Error(w, fmt.Sprintf("failed to encode final response: %v", err), http.StatusInternalServerError)
  424. return
  425. }
  426. flusher, ok := w.(http.Flusher)
  427. if !ok {
  428. http.Error(w, "could not get flusher", http.StatusInternalServerError)
  429. return
  430. }
  431. flusher.Flush()
  432. }
  433. type EmbeddingRequest struct {
  434. Content []string `json:"content"`
  435. }
  436. type EmbeddingResponse struct {
  437. Embedding [][]float32 `json:"embedding"`
  438. }
  439. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  440. func (s *Server) embeddings(w http.ResponseWriter, r *http.Request) {
  441. var req EmbeddingRequest
  442. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  443. http.Error(w, "Bad request", http.StatusBadRequest)
  444. return
  445. }
  446. w.Header().Set("Content-Type", "application/json")
  447. slog.Debug("embedding request", "content", req.Content)
  448. seqs := make([]*Sequence, len(req.Content))
  449. embeddings := make([][]float32, len(req.Content))
  450. var processed int
  451. var err error
  452. for i, content := range req.Content {
  453. seqs[i], err = s.NewSequence(content, nil, 0, nil, nil, true)
  454. if err != nil {
  455. http.Error(w, fmt.Sprintf("Failed to create new sequence: %v", err), http.StatusInternalServerError)
  456. return
  457. }
  458. }
  459. // TODO - refactor to go routines to add seq's and drain the responses
  460. // so we don't stall until each set is iterated through
  461. for processed < len(seqs) {
  462. s.mu.Lock()
  463. for i, sq := range s.seqs {
  464. if processed >= len(seqs) {
  465. break
  466. }
  467. if sq == nil {
  468. s.seqs[i] = seqs[processed]
  469. processed += 1
  470. }
  471. }
  472. s.cond.Signal()
  473. s.mu.Unlock()
  474. for i := range processed {
  475. embeddings[i] = <-seqs[i].embedding
  476. }
  477. }
  478. if err := json.NewEncoder(w).Encode(&EmbeddingResponse{
  479. Embedding: embeddings,
  480. }); err != nil {
  481. log.Println("Failed to encode result:", err)
  482. return
  483. }
  484. }
  485. type HealthResponse struct {
  486. Status string `json:"status"`
  487. Progress float32 `json:"progress"`
  488. }
  489. // TODO (jmorganca): is it safe to do this concurrently with decoding?
  490. func (s *Server) health(w http.ResponseWriter, r *http.Request) {
  491. w.Header().Set("Content-Type", "application/json")
  492. if err := json.NewEncoder(w).Encode(&HealthResponse{
  493. Status: s.status,
  494. Progress: s.progress,
  495. }); err != nil {
  496. log.Println("Failed to encode result:", err)
  497. return
  498. }
  499. }
  500. func main() {
  501. mpath := flag.String("model", "", "Path to model binary file")
  502. ppath := flag.String("mmproj", "", "Path to projector binary file")
  503. parallel := flag.Int("parallel", 1, "Number of sequences to handle simultaneously")
  504. batchSize := flag.Int("batch-size", 512, "Batch size")
  505. nGpuLayers := flag.Int("n-gpu-layers", 0, "Number of layers to offload to GPU")
  506. mainGpu := flag.Int("main-gpu", 0, "Main GPU")
  507. flashAttention := flag.Bool("flash-attn", false, "Enable flash attention")
  508. numCtx := flag.Int("ctx-size", 2048, "Context (or KV cache) size")
  509. lpath := flag.String("lora", "", "Path to lora layer file")
  510. port := flag.Int("port", 8080, "Port to expose the server on")
  511. threads := flag.Int("threads", runtime.NumCPU(), "Number of threads to use during generation")
  512. // TODO not yet implemented but wired to keep the parsing aligned
  513. embedding := flag.Bool("embedding", false, "enable embedding vector output (default: disabled)")
  514. logDisable := flag.Bool("log-disable", false, "disables logging to a file")
  515. verbose := flag.Bool("verbose", false, "verbose output (default: disabled)")
  516. f32 := flag.Bool("memory-f32", false, "use f32 instead of f16 for memory key+value (default: disabled) not recommended: doubles context memory required and no measurable increase in quality")
  517. noMmap := flag.Bool("no-mmap", false, "do not memory-map model (slower load but may reduce pageouts if not using mlock)")
  518. mlock := flag.Bool("mlock", false, "force system to keep model in RAM rather than swapping or compressing")
  519. tensorSplit := flag.String("tensor-split", "", "fraction of the model to offload to each GPU, comma-separated list of proportions")
  520. flag.Parse()
  521. level := slog.LevelInfo
  522. if *verbose {
  523. level = slog.LevelDebug
  524. }
  525. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  526. Level: level,
  527. AddSource: true,
  528. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  529. if attr.Key == slog.SourceKey {
  530. source := attr.Value.Any().(*slog.Source)
  531. source.File = filepath.Base(source.File)
  532. }
  533. return attr
  534. },
  535. })
  536. slog.SetDefault(slog.New(handler))
  537. // TODO actually implement...
  538. if *embedding {
  539. slog.Warn("embeddings not yet support")
  540. }
  541. if *logDisable {
  542. slog.Info("ignoring --log-disable")
  543. }
  544. if *f32 {
  545. slog.Warn("memory-f32 not yet supported")
  546. }
  547. if *noMmap {
  548. slog.Warn("no-mmap not yet supported")
  549. }
  550. if *mlock {
  551. slog.Warn("mlock not yet supported")
  552. }
  553. if *tensorSplit != "" {
  554. slog.Warn("tensor-split not yet implemented")
  555. }
  556. server := &Server{
  557. numCtx: *numCtx,
  558. batchSize: *batchSize,
  559. parallel: *parallel,
  560. seqs: make([]*Sequence, *parallel),
  561. status: "loading",
  562. }
  563. // load the model
  564. llama.BackendInit()
  565. params := llama.NewModelParams(*nGpuLayers, *mainGpu, func(progress float32) {
  566. slog.Debug("Loading model", "progress %", math.Round(float64(progress*100)))
  567. server.progress = progress
  568. })
  569. server.model = llama.LoadModelFromFile(*mpath, params)
  570. if *lpath != "" {
  571. err := server.model.ApplyLoraFromFile(*lpath, 1.0, "", *threads)
  572. if err != nil {
  573. panic(err)
  574. }
  575. }
  576. ctxParams := llama.NewContextParams(*numCtx, *threads, *flashAttention)
  577. server.lc = llama.NewContextWithModel(server.model, ctxParams)
  578. if *ppath != "" {
  579. server.clip.cc = llama.NewClipContext(*ppath)
  580. }
  581. server.cond = sync.NewCond(&server.mu)
  582. ctx, cancel := context.WithCancel(context.Background())
  583. go server.run(ctx)
  584. addr := "127.0.0.1:" + strconv.Itoa(*port)
  585. listener, err := net.Listen("tcp", addr)
  586. if err != nil {
  587. fmt.Println("Listen error:", err)
  588. return
  589. }
  590. defer listener.Close()
  591. mux := http.NewServeMux()
  592. mux.HandleFunc("/embedding", server.embeddings)
  593. mux.HandleFunc("/completion", server.completion)
  594. mux.HandleFunc("/health", server.health)
  595. httpServer := http.Server{
  596. Handler: mux,
  597. }
  598. server.status = "ok"
  599. log.Println("Server listening on", addr)
  600. if err := httpServer.Serve(listener); err != nil {
  601. log.Fatal("server error:", err)
  602. }
  603. cancel()
  604. }