-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
285 lines (237 loc) · 6.57 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"syscall"
"github.com/gorilla/mux"
consul "github.com/hashicorp/consul/api"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
)
var consulClient *consul.Client
const serviceName = "carbonifer-stress"
const exposedPort = 8080
var stressCmd *exec.Cmd
var stderr bytes.Buffer
type Stats struct {
CPU float64 `json:"cpu"`
Memory uint64 `json:"memory"`
Storage uint64 `json:"storage"`
}
func setupConsulClient() {
consulAgent := "consul-agent:8500"
// Read environment variable if available
if consulAgentEnv, ok := os.LookupEnv("CONSUL_AGENT"); ok {
consulAgent = consulAgentEnv
}
consulConfig := consul.DefaultConfig()
consulConfig.Address = consulAgent
var err error
consulClient, err = consul.NewClient(consulConfig)
if err != nil {
log.Fatal("Failed to connect to consul: ", err)
}
}
func registerService() {
reg := &consul.AgentServiceRegistration{
ID: serviceName,
Name: serviceName,
Port: exposedPort,
}
err := consulClient.Agent().ServiceRegister(reg)
if err != nil {
log.Fatal("Failed to register service: ", err)
}
}
func getInstances() []string {
services, _, err := consulClient.Catalog().Service(serviceName, "", nil)
if err != nil {
log.Println("Failed to get services: ", err)
return nil
}
instances := make([]string, len(services))
for i, service := range services {
instances[i] = service.Address // Using service.Address instead of service.ServiceAddress
}
return instances
}
func getStats() (*Stats, error) {
stats := &Stats{}
cpuPercent, err := cpu.Percent(0, false)
if err != nil {
return nil, err
}
if len(cpuPercent) > 0 {
stats.CPU = cpuPercent[0]
}
virtualMemory, err := mem.VirtualMemory()
if err != nil {
return nil, err
}
stats.Memory = virtualMemory.Used
diskUsage, err := disk.Usage("/")
if err != nil {
return nil, err
}
stats.Storage = diskUsage.Used
return stats, nil
}
func stopAllStressProcesses() {
out, err := exec.Command("pgrep", "-f", "stress-ng").Output()
if err != nil {
log.Printf("Error getting stress-ng process PIDs: %v", err)
return
}
pids := strings.Fields(string(out))
for _, pidStr := range pids {
pid, err := strconv.Atoi(pidStr)
if err != nil {
log.Printf("Error converting PID to integer: %v", err)
continue
}
// Send SIGTERM signal to the process
err = syscall.Kill(pid, syscall.SIGTERM)
if err != nil {
log.Printf("Error stopping stress-ng process with PID %d: %v", pid, err)
continue
}
}
}
func stressHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Calling /stress...\n")
vars := mux.Vars(r)
instance := vars["instance"]
cpu, _ := strconv.Atoi(r.URL.Query().Get("cpu"))
ram, _ := strconv.Atoi(r.URL.Query().Get("ram"))
storage, _ := strconv.Atoi(r.URL.Query().Get("storage"))
// If instance is empty, apply stress to the current instance
if instance == "" {
// Stop any running stress-ng process
if stressCmd != nil && stressCmd.Process != nil && stressCmd.ProcessState == nil {
log.Println("Stopping existing stress-ng process...")
stopAllStressProcesses()
}
// If cpu is 0, do not start a new stress-ng process
if cpu == 0 && ram == 0 && storage == 0 {
fmt.Fprintf(w, "No stress applied, current stress-ng process stopped\n")
return
}
cmdStr := "stress-ng"
cmdStr += fmt.Sprintf(" --cpu 0 --cpu-load %d", cpu)
if ram > 0 {
cmdStr += fmt.Sprintf(" --vm %d --vm-bytes %dM", ram, ram)
}
if storage > 0 {
cmdStr += fmt.Sprintf(" --hdd %d --hdd-bytes %dM", storage, storage)
}
stressCmd = exec.Command("sh", "-c", cmdStr)
stressCmd.Stderr = &stderr
err := stressCmd.Start()
if err != nil {
log.Printf("Error stressing current instance: %v", err)
log.Printf("Stderr: %s", stderr.String())
return
}
go func() {
err := stressCmd.Wait()
if err != nil {
log.Printf("stress-ng command finished with error: %v", err)
} else {
log.Println("stress-ng command finished successfully")
}
}()
fmt.Fprintf(w, "Applied stress on current instance\n")
} else {
// Forward the stress request to the specified instance
url := fmt.Sprintf("http://%s/stress?", instance)
if r.URL.Query().Get("cpu") != "" {
url += fmt.Sprintf("cpu=%d&", cpu)
}
if r.URL.Query().Get("ram") != "" {
url += fmt.Sprintf("ram=%d&", ram)
}
if r.URL.Query().Get("storage") != "" {
url += fmt.Sprintf("storage=%d", storage)
}
resp, err := http.Get(url)
if err != nil {
log.Printf("Error stressing instance %s: %v", instance, err)
return
}
// Forward the response from the other instance
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Fprintf(w, "Applied stress on instance: %s\n", instance)
_, err = w.Write(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func usageHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
instance := vars["instance"]
if instance == "" {
// Return current stress info
stats, err := getStats()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response, err := json.Marshal(stats)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, err = w.Write(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
resp, err := http.Get(fmt.Sprintf("http://%s/usage", instance))
if err != nil {
log.Printf("Error stressing instance %s: %v", instance, err)
return
}
// Forward the response from the other instance
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
_, err = w.Write(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func instancesHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Callng /instances...\n")
instances := getInstances()
fmt.Fprintf(w, "Instances: %s\n", strings.Join(instances, ", "))
}
func main() {
log.Println("Registering service...")
setupConsulClient()
registerService()
log.Println("Starting server...")
router := mux.NewRouter()
router.HandleFunc("/instances", instancesHandler)
router.HandleFunc("/stress/{instance}", stressHandler)
router.HandleFunc("/stress", stressHandler)
router.HandleFunc("/usage/{instance}", usageHandler)
router.HandleFunc("/usage", usageHandler)
err := http.ListenAndServe(fmt.Sprintf(":%v", exposedPort), router)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}