This repository has been archived by the owner on Nov 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
sma-monitoringagent.go
517 lines (426 loc) · 13.4 KB
/
sma-monitoringagent.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
/**
* @package sma-monitoring-agent
* @copyright sma-monitoring-agent contributors
* @license GNU Affero General Public License (https://www.gnu.org/licenses/agpl-3.0.de.html)
* @authors https://github.com/continentale/sma-monitoring-agent/graphs/contributors
* @todo lots of documentation
*
*
* Windows Monitoring Agent with REST-API
*/
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strings"
"syscall"
"time"
"github.com/StackExchange/wmi"
"github.com/itcomusic/winsvc"
"github.com/shirou/gopsutil/cpu"
"gopkg.in/ini.v1"
)
var (
// Version displays the current version of the agent. Ususally it is overwritten within the build pipeline
Version = "1.0.0"
// BuildTime is the time the program is build. Usually it is overwritten within the build pipeline
BuildTime = "2015-08-01 UTC"
// GitHash is the git commit hash from the build. Usually it is overwritten within the build pipeline
GitHash = ""
endpointMemoryMap map[string]map[string]string
)
// Check displays a nagios compliant check as a struct
type Check struct {
Output string
InMemoryValue string
ExitCode int
}
type Win32_LogicalDisk struct {
Name string
FreeSpace string
Size string
}
type Win32_Process struct {
Name string
Caption string
}
type Win32_Processor struct {
LoadPercentage int
Name string
}
type Win32_Service struct {
Caption string
Name string
State string
}
type Win32_OperatingSystem struct {
TotalVisibleMemorySize int
FreePhysicalMemory int
TotalVirtualMemorySize int
FreeVirtualMemory int
}
// AgentVersion contains all relevant information about git commit and versioning of the program for a specific time. Usually it is filled in a pipeline
type AgentVersion struct {
Version string
BuildTime string
GitHash string
}
type Win32_ComputerSystem struct {
Model string
Manufacturer string
Name string
Domain string
NumberOfProcessors int
NumberOfLogicalProcessors int
TotalPhysicalMemory int
}
type Inventory struct {
Model string
Manufacturer string
Name string
Domain string
NumberOfProcessors int
NumberOfLogicalProcessors int
TotalPhysicalMemory int
IdentifyingNumber string
}
type Win32_ComputerSystemProduct struct {
IdentifyingNumber string
}
type CoreUsage struct {
CPUType []cpu.InfoStat
Usage []float64
}
type Application struct {
srv *http.Server
}
/*
* Function to validate authorization ouf our REST-API.
* uses the useSecret param in agent.ini
*/
func isAuthorized(endpoint func(w http.ResponseWriter, r *http.Request)) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg := LoadIni()
if useSecret, _ := cfg.Section("server").Key("useSecret").Bool(); useSecret {
secret := cfg.Section("server").Key("secret").String()
if len(r.Header["Token"]) == 0 || secret != r.Header["Token"][0] {
w.Write([]byte("Not Authorized"))
return
}
endpoint(w, r)
} else {
endpoint(w, r)
}
})
}
// DiskUsage is used to dertermine the current disk usage via WMI.
// Data source is Win32_LogicalDisk
// default filter is fixed disk with MediaType 12
func DiskUsage(w http.ResponseWriter, r *http.Request) {
var dst []Win32_LogicalDisk
dl := r.URL.Query()["name"]
qu := "WHERE MediaType ='12'"
if len(dl) > 0 {
qu = "WHERE Name LIKE'%" + dl[0] + "%'"
}
q := wmi.CreateQuery(&dst, qu)
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
var jsonData []byte
jsonData, err = json.Marshal(dst)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// ProcessList is used to dertermine if a program is running
// Data source is WMI Win32_Process
// without filter all processes are shown
// it's possible to filter via Name attribute, wildcards allowed
func ProcessList(w http.ResponseWriter, r *http.Request) {
var dst []Win32_Process
dl := r.URL.Query()["name"]
qu := ""
if len(dl) > 0 {
qu = "WHERE Name LIKE '%" + dl[0] + "%'"
}
q := wmi.CreateQuery(&dst, qu)
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
var jsonData []byte
jsonData, err = json.Marshal(dst)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// WinService shows status of windows services.
// data source is WMI Win32_Service
// if no param is set all services with type Autostart will be validated
func WinService(w http.ResponseWriter, r *http.Request) {
var dst []Win32_Service
dl := r.URL.Query()["name"]
qu := "WHERE StartMode LIKE '%Auto%'"
if len(dl) > 0 {
qu = "WHERE Name='" + dl[0] + "'"
}
q := wmi.CreateQuery(&dst, qu)
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
var jsonData []byte
jsonData, err = json.Marshal(dst)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// MemoryUsage shows memory usage statistics.
// data source is WMI Win32_OperatingSystem
func MemoryUsage(w http.ResponseWriter, r *http.Request) {
var dst []Win32_OperatingSystem
q := wmi.CreateQuery(&dst, "")
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
var jsonData []byte
jsonData, err = json.Marshal(dst)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// InventoryService collects basic system information
// primary data source is WMI Win32_ComputerSystem
// used to provide basic inventory data
func InventoryService(w http.ResponseWriter, r *http.Request) {
var dst []Win32_ComputerSystem
q := wmi.CreateQuery(&dst, "")
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
dst[0].Model = strings.Trim(dst[0].Model, " ")
dst[0].Manufacturer = strings.Trim(dst[0].Manufacturer, " ")
var dstp []Win32_ComputerSystemProduct
qp := wmi.CreateQuery(&dstp, "")
errp := wmi.Query(qp, &dstp)
if errp != nil {
log.Fatal(errp)
}
dstp[0].IdentifyingNumber = strings.Trim(dstp[0].IdentifyingNumber, " ")
inventory := Inventory{dst[0].Model, dst[0].Manufacturer, dst[0].Name, dst[0].Domain, dst[0].NumberOfProcessors, dst[0].NumberOfLogicalProcessors, dst[0].TotalPhysicalMemory, dstp[0].IdentifyingNumber}
var jsonData []byte
jsonData, err = json.Marshal(inventory)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
dst = nil
dstp = nil
}
// CPUUsage shows CPU usage statistics.
// data source is WMI Win32_Processor
func CPUUsage(w http.ResponseWriter, r *http.Request) {
var dst []Win32_Processor
q := wmi.CreateQuery(&dst, "")
err := wmi.Query(q, &dst)
if err != nil {
log.Fatal(err)
}
var jsonData []byte
jsonData, err = json.Marshal(dst)
if err != nil {
log.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// CPUUsageByCore shows detailed CPU usage statistics.
// currently beta, can fail with multi cpu systems and a lot of cores..
func CPUUsageByCore(w http.ResponseWriter, r *http.Request) {
cpuStat, _ := cpu.Info()
percentage, _ := cpu.Percent(0, true)
space := regexp.MustCompile(`\s+`)
cpuStat[0].ModelName = space.ReplaceAllString(cpuStat[0].ModelName, " ")
usage := &CoreUsage{
CPUType: cpuStat,
Usage: percentage}
jsonData, _ := json.Marshal(usage)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// ShowVersion displays the agent version
func ShowVersion(w http.ResponseWriter, r *http.Request) {
agent := AgentVersion{Version: Version, BuildTime: BuildTime, GitHash: GitHash}
jsonData, _ := json.Marshal(agent)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func main() {
endpointMemoryMap = make(map[string]map[string]string)
winsvc.Run(func(ctx context.Context) {
app := New()
if err := app.Run(ctx); err != nil {
log.Printf("[ERROR] rest terminated with error, %s", err)
return
}
log.Printf("[WARN] rest terminated")
})
// service has been just stopped, but process of the go has not stopped yet
// that is why recommendation is to not write any logic
}
// New contains the windows service logic
func New() *Application {
cfg := LoadIni()
port := cfg.Section("server").Key("port").String()
mux := http.NewServeMux()
server := &http.Server{
Addr: "0.0.0.0:" + port,
Handler: mux,
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
agent := AgentVersion{Version: Version, BuildTime: BuildTime, GitHash: GitHash}
jsonData := []byte(`{"Output":"SMA-MonitoringAgent ` + agent.Version + `","ExitCode":0}`)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
})
mux.Handle("/api/diskusage", isAuthorized(DiskUsage))
mux.Handle("/api/cpuusage", isAuthorized(CPUUsage))
mux.Handle("/api/cpuusagebycore", isAuthorized(CPUUsageByCore))
mux.Handle("/api/memoryusage", isAuthorized(MemoryUsage))
mux.Handle("/api/processlist", isAuthorized(ProcessList))
mux.Handle("/api/services", isAuthorized(WinService))
mux.Handle("/api/systeminfo", isAuthorized(InventoryService))
mux.Handle("/api/exec", isAuthorized(ExecuteScript))
mux.Handle("/api/version", isAuthorized(ShowVersion))
return &Application{srv: server}
}
// Run starts the api-web-server.
func (a *Application) Run(ctx context.Context) error {
log.Print("[INFO] started REST-API server version: " + Version)
go func() {
defer log.Print("[WARN] shutdown REST-API server")
// shutdown on context cancellation
<-ctx.Done()
c, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
a.srv.Shutdown(c)
}()
// load config file and place all relevant data in variables for easy use
cfg := LoadIni()
port := cfg.Section("server").Key("port").String()
protocol := cfg.Section("server").Key("protocol").String()
cert := cfg.Section("server").Key("certificate").String()
privkey := cfg.Section("server").Key("privatekey").String()
// start webserver
log.Println("[INFO] started http server on port: " + port)
if protocol == "https" {
return a.srv.ListenAndServeTLS(cert, privkey)
}
return a.srv.ListenAndServe()
}
func parseCommandArgs(url, name string, arguments []string) []string {
cfg := LoadIni()
// run through all url arguments => specified with args
for i := range arguments {
// if args begins with $ then it needs more parsing
if arguments[i][0] == '$' {
param := cfg.Section(name).Key(strings.Replace(arguments[i], "$", "", -1)).String()
if param == "DATE" || param == "JSON" {
// param is true or json get value from memory
arguments[i] = endpointMemoryMap[url][strings.Replace(arguments[i], "$", "", -1)]
} else if strings.Replace(arguments[i], "$", "", -1) == cfg.Section(name).Key(arguments[i][1:len(arguments[i])-1]).String() {
// Variable Name is the type. Get single value from the json
tmpMap := make(map[string]string)
err := json.Unmarshal([]byte(endpointMemoryMap[url]["JSON"]), &tmpMap)
if err != nil {
log.Println("Failed to unmarshal JSON:", err)
}
arguments[i] = tmpMap[arguments[i][1:len(arguments[i])-1]]
} else {
// get value from the key
arguments[i] = param
}
}
}
return arguments
}
// ExecuteScript runs local placed scripts as a custom executor
func ExecuteScript(w http.ResponseWriter, r *http.Request) {
var waitStatus syscall.WaitStatus
name := r.URL.Query().Get("name")
cfg := LoadIni()
yes := cfg.Section("commands").HasKey(name)
var check Check
if yes {
params := cfg.Section("commands").Key(name).String()
params = "/c " + params
args := strings.Fields(params)
arguments := r.URL.Query()["args"]
if r.URL.Query().Get("variables") == "true" {
parseCommandArgs(r.URL.String(), name, arguments)
}
args = append(args, arguments...)
cmd := exec.Command("cmd", args...)
out, err := cmd.CombinedOutput()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
} else {
waitStatus = exitError.Sys().(syscall.WaitStatus)
}
} else {
waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
}
outString := string(out)
check.Output = outString
check.ExitCode = waitStatus.ExitStatus()
if strings.Index(outString, "{{") != -1 && strings.Index(outString, "}}") != -1 {
check.InMemoryValue = outString[strings.Index(outString, "{{")+1 : strings.LastIndex(outString, "}}")+1]
}
jsonData, _ := json.Marshal(check)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
} else {
jsonData := []byte(`{"Output":"Command does not exist","ExitCode":3}`)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
// set arguments only when URL-Parameter is given
if r.URL.Query().Get("variables") == "true" {
if _, isSet := endpointMemoryMap[r.URL.String()]["DATE"]; !isSet {
endpointMemoryMap[r.URL.String()] = make(map[string]string)
}
endpointMemoryMap[r.URL.String()]["JSON"] = check.InMemoryValue
endpointMemoryMap[r.URL.String()]["DATE"] = fmt.Sprint(time.Now().Unix())
}
}
// LoadIni is used to load the agent.ini file
// os variable AGENT_INI_PATH can be used to load it from a custom location.
func LoadIni() (cfg *ini.File) {
path := os.Getenv("AGENT_INI_PATH")
cfg, err := ini.Load(path + "agent.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
return cfg
}