driver.go 1.6 KB

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