-
Notifications
You must be signed in to change notification settings - Fork 434
/
server.go
92 lines (78 loc) · 2.52 KB
/
server.go
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
86
87
88
89
90
91
92
package daemon
import (
"fmt"
"net/http"
"time"
"github.com/emicklei/go-restful/v3"
"k8s.io/klog/v2"
"github.com/kubeovn/kube-ovn/pkg/request"
)
const (
requestLogFormat = "[%s] Incoming %s %s %s request"
responseLogFormat = "[%s] Outgoing response %s %s with %d status code in %vms"
)
// RunServer runs the cniserver
func RunServer(config *Configuration, controller *Controller) {
nodeName = config.NodeName
csh := createCniServerHandler(config, controller)
server := http.Server{
Handler: createHandler(csh),
ReadHeaderTimeout: 3 * time.Second,
}
listener, cleanFunc, err := listen(config.BindSocket)
if err != nil {
return
}
defer cleanFunc()
klog.Infof("start listen on %s", config.BindSocket)
klog.Fatal(server.Serve(listener))
}
func createHandler(csh *cniServerHandler) http.Handler {
wsContainer := restful.NewContainer()
wsContainer.EnableContentEncoding(true)
ws := new(restful.WebService)
ws.Path("/api/v1").
Consumes(restful.MIME_JSON).
Produces(restful.MIME_JSON)
wsContainer.Add(ws)
ws.Route(
ws.POST("/add").
To(csh.handleAdd).
Reads(request.CniRequest{}))
ws.Route(
ws.POST("/del").
To(csh.handleDel).
Reads(request.CniRequest{}))
ws.Filter(requestAndResponseLogger)
return wsContainer
}
// web-service filter function used for request and response logging.
func requestAndResponseLogger(request *restful.Request, response *restful.Response,
chain *restful.FilterChain) {
klog.Infof(formatRequestLog(request))
start := time.Now()
chain.ProcessFilter(request, response)
elapsed := float64((time.Since(start)) / time.Millisecond)
cniOperationHistogram.WithLabelValues(
nodeName,
getRequestURI(request),
fmt.Sprintf("%d", response.StatusCode())).Observe(elapsed / 1000)
klog.Infof(formatResponseLog(response, request, elapsed))
}
// formatRequestLog formats request log string.
func formatRequestLog(request *restful.Request) string {
return fmt.Sprintf(requestLogFormat, time.Now().Format(time.RFC3339), request.Request.Proto,
request.Request.Method, getRequestURI(request))
}
// formatResponseLog formats response log string.
func formatResponseLog(response *restful.Response, request *restful.Request, reqTime float64) string {
return fmt.Sprintf(responseLogFormat, time.Now().Format(time.RFC3339),
request.Request.Method, getRequestURI(request), response.StatusCode(), reqTime)
}
// getRequestURI get the request uri
func getRequestURI(request *restful.Request) (uri string) {
if request.Request.URL != nil {
uri = request.Request.URL.RequestURI()
}
return
}