github.com/khulnasoft-lab/khulnasoft@v26.0.1-0.20240328202558-330a6f959fe0+incompatible/integration/plugin/logging/cmd/discard/driver.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "io" 6 "net/http" 7 "os" 8 "sync" 9 "syscall" 10 ) 11 12 type startLoggingRequest struct { 13 File string 14 } 15 16 type capabilitiesResponse struct { 17 Cap struct { 18 ReadLogs bool 19 } 20 } 21 22 type driver struct { 23 mu sync.Mutex 24 logs map[string]io.Closer 25 } 26 27 type stopLoggingRequest struct { 28 File string 29 } 30 31 func handle(mux *http.ServeMux) { 32 d := &driver{logs: make(map[string]io.Closer)} 33 mux.HandleFunc("/LogDriver.StartLogging", func(w http.ResponseWriter, r *http.Request) { 34 var req startLoggingRequest 35 if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 36 http.Error(w, err.Error(), http.StatusBadRequest) 37 return 38 } 39 40 f, err := os.OpenFile(req.File, syscall.O_RDONLY, 0o700) 41 if err != nil { 42 respond(err, w) 43 } 44 45 d.mu.Lock() 46 d.logs[req.File] = f 47 d.mu.Unlock() 48 49 go io.Copy(io.Discard, f) 50 respond(err, w) 51 }) 52 53 mux.HandleFunc("/LogDriver.StopLogging", func(w http.ResponseWriter, r *http.Request) { 54 var req stopLoggingRequest 55 if err := json.NewDecoder(r.Body).Decode(&req); err != nil { 56 http.Error(w, err.Error(), http.StatusBadRequest) 57 return 58 } 59 60 d.mu.Lock() 61 if f := d.logs[req.File]; f != nil { 62 f.Close() 63 } 64 d.mu.Unlock() 65 respond(nil, w) 66 }) 67 68 mux.HandleFunc("/LogDriver.Capabilities", func(w http.ResponseWriter, r *http.Request) { 69 json.NewEncoder(w).Encode(&capabilitiesResponse{ 70 Cap: struct{ ReadLogs bool }{ReadLogs: false}, 71 }) 72 }) 73 } 74 75 type response struct { 76 Err string 77 } 78 79 func respond(err error, w io.Writer) { 80 var res response 81 if err != nil { 82 res.Err = err.Error() 83 } 84 json.NewEncoder(w).Encode(&res) 85 }