master
go 78 lines 2.15 KB
Raw
1 package corehttp
2
3 import (
4 "net"
5 "net/http"
6 "runtime"
7 "strconv"
8
9 core "github.com/ipfs/kubo/core"
10 )
11
12 // MutexFractionOption allows to set runtime.SetMutexProfileFraction via HTTP
13 // using POST request with parameter 'fraction'.
14 func MutexFractionOption(path string) ServeOption {
15 return func(_ *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
16 mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
17 if r.Method != http.MethodPost {
18 http.Error(w, "only POST allowed", http.StatusMethodNotAllowed)
19 return
20 }
21 if err := r.ParseForm(); err != nil {
22 http.Error(w, err.Error(), http.StatusBadRequest)
23 return
24 }
25
26 asfr := r.Form.Get("fraction")
27 if len(asfr) == 0 {
28 http.Error(w, "parameter 'fraction' must be set", http.StatusBadRequest)
29 return
30 }
31
32 fr, err := strconv.Atoi(asfr)
33 if err != nil {
34 http.Error(w, err.Error(), http.StatusBadRequest)
35 return
36 }
37 log.Infof("Setting MutexProfileFraction to %d", fr)
38 runtime.SetMutexProfileFraction(fr)
39 })
40
41 return mux, nil
42 }
43 }
44
45 // BlockProfileRateOption allows to set runtime.SetBlockProfileRate via HTTP
46 // using POST request with parameter 'rate'.
47 // The profiler tries to sample 1 event every <rate> nanoseconds.
48 // If rate == 1, then the profiler samples every blocking event.
49 // To disable, set rate = 0.
50 func BlockProfileRateOption(path string) ServeOption {
51 return func(_ *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
52 mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
53 if r.Method != http.MethodPost {
54 http.Error(w, "only POST allowed", http.StatusMethodNotAllowed)
55 return
56 }
57 if err := r.ParseForm(); err != nil {
58 http.Error(w, err.Error(), http.StatusBadRequest)
59 return
60 }
61
62 rateStr := r.Form.Get("rate")
63 if len(rateStr) == 0 {
64 http.Error(w, "parameter 'rate' must be set", http.StatusBadRequest)
65 return
66 }
67
68 rate, err := strconv.Atoi(rateStr)
69 if err != nil {
70 http.Error(w, err.Error(), http.StatusBadRequest)
71 return
72 }
73 log.Infof("Setting BlockProfileRate to %d", rate)
74 runtime.SetBlockProfileRate(rate)
75 })
76 return mux, nil
77 }
78 }