| 1 |
/* |
| 2 |
Copyright 2022 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package routes |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"net" |
| 22 |
"net/http" |
| 23 |
"net/http/pprof" |
| 24 |
"os" |
| 25 |
"path" |
| 26 |
) |
| 27 |
|
| 28 |
// DebugSocket installs profiling and debugflag as a Unix-Domain socket. |
| 29 |
type DebugSocket struct { |
| 30 |
path string |
| 31 |
mux *http.ServeMux |
| 32 |
} |
| 33 |
|
| 34 |
// NewDebugSocket creates a new DebugSocket for the given path. |
| 35 |
func NewDebugSocket(path string) *DebugSocket { |
| 36 |
return &DebugSocket{ |
| 37 |
path: path, |
| 38 |
mux: http.NewServeMux(), |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
// InstallProfiling installs profiling endpoints in the socket. |
| 43 |
func (s *DebugSocket) InstallProfiling() { |
| 44 |
s.mux.HandleFunc("/debug/pprof", redirectTo("/debug/pprof/")) |
| 45 |
s.mux.HandleFunc("/debug/pprof/", pprof.Index) |
| 46 |
s.mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) |
| 47 |
s.mux.HandleFunc("/debug/pprof/profile", pprof.Profile) |
| 48 |
s.mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) |
| 49 |
s.mux.HandleFunc("/debug/pprof/trace", pprof.Trace) |
| 50 |
} |
| 51 |
|
| 52 |
// InstallDebugFlag installs debug flag endpoints in the socket. |
| 53 |
func (s *DebugSocket) InstallDebugFlag(flag string, handler func(http.ResponseWriter, *http.Request)) { |
| 54 |
f := DebugFlags{} |
| 55 |
s.mux.HandleFunc("/debug/flags", f.Index) |
| 56 |
s.mux.HandleFunc("/debug/flags/", f.Index) |
| 57 |
|
| 58 |
url := path.Join("/debug/flags", flag) |
| 59 |
s.mux.HandleFunc(url, handler) |
| 60 |
|
| 61 |
f.addFlag(flag) |
| 62 |
} |
| 63 |
|
| 64 |
// Run starts the server and waits for stopCh to be closed to close the server. |
| 65 |
func (s *DebugSocket) Run(stopCh <-chan struct{}) error { |
| 66 |
if err := os.Remove(s.path); err != nil && !os.IsNotExist(err) { |
| 67 |
return fmt.Errorf("failed to remove (%v): %v", s.path, err) |
| 68 |
} |
| 69 |
|
| 70 |
l, err := net.Listen("unix", s.path) |
| 71 |
if err != nil { |
| 72 |
return fmt.Errorf("listen error (%v): %v", s.path, err) |
| 73 |
} |
| 74 |
defer l.Close() |
| 75 |
|
| 76 |
srv := http.Server{Handler: s.mux} |
| 77 |
go func() { |
| 78 |
<-stopCh |
| 79 |
srv.Close() |
| 80 |
}() |
| 81 |
return srv.Serve(l) |
| 82 |
} |