summaryrefslogtreecommitdiff
path: root/integration/plugin/logging/cmd/discard/driver.go
blob: bbdebaf443bdc40255463795b38248b8db67695f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main

import (
	"encoding/json"
	"io"
	"net/http"
	"os"
	"sync"
	"syscall"
)

type startLoggingRequest struct {
	File string
}

type capabilitiesResponse struct {
	Cap struct {
		ReadLogs bool
	}
}

type driver struct {
	mu   sync.Mutex
	logs map[string]io.Closer
}

type stopLoggingRequest struct {
	File string
}

func handle(mux *http.ServeMux) {
	d := &driver{logs: make(map[string]io.Closer)}
	mux.HandleFunc("/LogDriver.StartLogging", func(w http.ResponseWriter, r *http.Request) {
		var req startLoggingRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		f, err := os.OpenFile(req.File, syscall.O_RDONLY, 0700)
		if err != nil {
			respond(err, w)
		}

		d.mu.Lock()
		d.logs[req.File] = f
		d.mu.Unlock()

		go io.Copy(io.Discard, f)
		respond(err, w)
	})

	mux.HandleFunc("/LogDriver.StopLogging", func(w http.ResponseWriter, r *http.Request) {
		var req stopLoggingRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		d.mu.Lock()
		if f := d.logs[req.File]; f != nil {
			f.Close()
		}
		d.mu.Unlock()
		respond(nil, w)
	})

	mux.HandleFunc("/LogDriver.Capabilities", func(w http.ResponseWriter, r *http.Request) {
		json.NewEncoder(w).Encode(&capabilitiesResponse{
			Cap: struct{ ReadLogs bool }{ReadLogs: false},
		})
	})
}

type response struct {
	Err string
}

func respond(err error, w io.Writer) {
	var res response
	if err != nil {
		res.Err = err.Error()
	}
	json.NewEncoder(w).Encode(&res)
}