|
| 1 | +package server |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "net/http/pprof" |
| 8 | + _ "net/http/pprof" |
| 9 | + |
| 10 | + "github.com/Azure/azure-container-networking/log" |
| 11 | + |
| 12 | + "github.com/Azure/azure-container-networking/npm/http/api" |
| 13 | + "github.com/Azure/azure-container-networking/npm/metrics" |
| 14 | + |
| 15 | + "github.com/Azure/azure-container-networking/npm" |
| 16 | + "github.com/gorilla/mux" |
| 17 | +) |
| 18 | + |
| 19 | +var ( |
| 20 | + DefaultHTTPListeningAddress = fmt.Sprintf("%s:%s", api.DefaultListeningIP, api.DefaultHttpPort) |
| 21 | +) |
| 22 | + |
| 23 | +type NPMRestServer struct { |
| 24 | + listeningAddress string |
| 25 | + server *http.Server |
| 26 | + router *mux.Router |
| 27 | +} |
| 28 | + |
| 29 | +func (n *NPMRestServer) NPMRestServerListenAndServe(npMgr *npm.NetworkPolicyManager) { |
| 30 | + n.router = mux.NewRouter() |
| 31 | + |
| 32 | + //prometheus handlers |
| 33 | + n.router.Handle(api.NodeMetricsPath, metrics.GetHandler(true)) |
| 34 | + n.router.Handle(api.ClusterMetricsPath, metrics.GetHandler(false)) |
| 35 | + |
| 36 | + // ACN CLI debug handlerss |
| 37 | + n.router.Handle(api.NPMMgrPath, n.GetNpmMgr(npMgr)).Methods(http.MethodGet) |
| 38 | + |
| 39 | + n.router.PathPrefix("/debug/").Handler(http.DefaultServeMux) |
| 40 | + n.router.HandleFunc("/debug/pprof/", pprof.Index) |
| 41 | + n.router.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) |
| 42 | + n.router.HandleFunc("/debug/pprof/profile", pprof.Profile) |
| 43 | + n.router.HandleFunc("/debug/pprof/symbol", pprof.Symbol) |
| 44 | + n.router.HandleFunc("/debug/pprof/trace", pprof.Trace) |
| 45 | + |
| 46 | + // use default listening address if none is specified |
| 47 | + if n.listeningAddress == "" { |
| 48 | + n.listeningAddress = DefaultHTTPListeningAddress |
| 49 | + } |
| 50 | + |
| 51 | + srv := &http.Server{ |
| 52 | + Handler: n.router, |
| 53 | + Addr: n.listeningAddress, |
| 54 | + } |
| 55 | + |
| 56 | + log.Logf("Starting NPM HTTP API on %s... ", n.listeningAddress) |
| 57 | + log.Errorf("Failed to start NPM HTTP Server with error: %+v", srv.ListenAndServe()) |
| 58 | +} |
| 59 | + |
| 60 | +func NewNpmRestServer(listeningAddress string) *NPMRestServer { |
| 61 | + return &NPMRestServer{ |
| 62 | + listeningAddress: listeningAddress, |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func (n *NPMRestServer) GetNpmMgr(npMgr *npm.NetworkPolicyManager) http.Handler { |
| 67 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 68 | + npMgr.Lock() |
| 69 | + err := json.NewEncoder(w).Encode(npMgr) |
| 70 | + if err != nil { |
| 71 | + http.Error(w, err.Error(), 500) |
| 72 | + return |
| 73 | + } |
| 74 | + npMgr.Unlock() |
| 75 | + }) |
| 76 | +} |
0 commit comments