/
tools.go
92 lines (77 loc) · 1.68 KB
/
tools.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 backend
import (
"encoding/json"
"net/http"
"runtime"
"time"
)
// Force garbage collection
func (a *API) getRunGC(resp http.ResponseWriter, req *http.Request) {
runtime.GC()
resp.Header().Set("Content-Type", "application/json")
_, _ = resp.Write([]byte("Garbage collector was run"))
}
// Allocate a lot of memory
func (a *API) postAllocMem(resp http.ResponseWriter, req *http.Request) {
params := struct {
Size int
}{
Size: 100,
}
err := json.NewDecoder(req.Body).Decode(¶ms)
if err != nil {
http.Error(resp, err.Error(), http.StatusBadRequest)
return
}
if params.Size < 1 {
params.Size = 1
}
if params.Size > 400 {
params.Size = 400
}
var buffer = make([]string, params.Size*1024*1024)
for e := range buffer {
buffer[e] = "#"
}
resp.Header().Set("Content-Type", "application/json")
_, _ = resp.Write([]byte("Memory was allocated"))
}
// Force max CPU load for a number of seconds
func (a *API) postForceCPU(resp http.ResponseWriter, req *http.Request) {
params := struct {
Seconds int
}{
Seconds: 1,
}
err := json.NewDecoder(req.Body).Decode(¶ms)
if err != nil {
http.Error(resp, err.Error(), http.StatusBadRequest)
return
}
if params.Seconds < 1 {
params.Seconds = 1
}
if params.Seconds > 10 {
params.Seconds = 10
}
n := runtime.NumCPU()
runtime.GOMAXPROCS(n)
quit := make(chan bool)
for i := 0; i < n; i++ {
go func() {
for {
select {
case <-quit:
return
default: //nolint
}
}
}()
}
time.Sleep(time.Duration(params.Seconds) * time.Second)
for i := 0; i < n; i++ {
quit <- true
}
resp.Header().Set("Content-Type", "application/json")
_, _ = resp.Write([]byte("CPU load was forced"))
}