-
Notifications
You must be signed in to change notification settings - Fork 0
/
combined.go
342 lines (300 loc) · 8.92 KB
/
combined.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
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"regexp"
"sort"
"strconv"
"strings"
elasticsearch "github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
)
type SystemInfo struct {
CPUInfo CPUInfo `json:"CPUInfo"`
ProcessInfo []ProcessInfo `json:"ProcessInfo"`
DiskInfo []DiskInfo `json:"DiskInfo"`
}
type ProcessInfo struct {
PID int `json:"PID"`
User string `json:"User"`
PR int `json:"PR"`
NI int `json:"NI"`
VIRT int64 `json:"VIRT"`
RES int64 `json:"RES"`
SHR int64 `json:"SHR"`
S string `json:"S"`
CPU float64 `json:"%CPU"`
MEM float64 `json:"%MEM"`
Time string `json:"TIME+"`
Command string `json:"COMMAND"`
}
type CPUInfo struct {
Architecture string `json:"Architecture"`
CPUOpModes string `json:"CPUOpModes"`
ByteOrder string `json:"ByteOrder"`
CPUs int `json:"CPUs"`
ThreadsPerCore int `json:"ThreadsPerCore"`
CoresPerSocket int `json:"CoresPerSocket"`
Sockets int `json:"Sockets"`
NUMANodes int `json:"NUMANodes"`
VendorID string `json:"VendorID"`
CPUFamily int `json:"CPUFamily"`
Model int `json:"Model"`
ModelName string `json:"ModelName"`
CPUMHz float64 `json:"CPUMHz"`
BogoMIPS float64 `json:"BogoMIPS"`
HypervisorVendor string `json:"HypervisorVendor"`
VirtualizationType string `json:"VirtualizationType"`
L1DCache string `json:"L1DCache"`
L1ICache string `json:"L1ICache"`
L2Cache string `json:"L2Cache"`
L3Cache string `json:"L3Cache"`
NUMANode0CPUs string `json:"NUMANode0CPUs"`
Flags string `json:"Flags"`
}
type DiskInfo struct {
Filesystem string `json:"Filesystem"`
Size string `json:"Size"`
Used string `json:"Used"`
Avail string `json:"Avail"`
UsePercent string `json:"UsePercent"`
MountedOn string `json:"MountedOn"`
}
func readAndParseCPUInfo(scanner *bufio.Scanner) (CPUInfo, error) {
var cpuInfo CPUInfo
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
key := fields[0]
value := strings.Join(fields[1:], " ")
switch key {
case "Architecture:":
cpuInfo.Architecture = value
case "CPUOpModes":
cpuInfo.CPUOpModes = value
case "Byte":
cpuInfo.ByteOrder = value
case "CPU(s):":
cpuInfo.CPUs, _ = strconv.Atoi(value)
case "Thread(s)":
cpuInfo.ThreadsPerCore, _ = strconv.Atoi(value)
case "Core(s)":
cpuInfo.CoresPerSocket, _ = strconv.Atoi(value)
case "Socket(s):":
cpuInfo.Sockets, _ = strconv.Atoi(value)
case "NUMANode0CPUs ":
cpuInfo.NUMANodes, _ = strconv.Atoi(value)
case "VendorID ":
cpuInfo.VendorID = value
case "CPUFamily":
cpuInfo.CPUFamily, _ = strconv.Atoi(value)
case "Model:":
cpuInfo.Model, _ = strconv.Atoi(value)
case "ModelName":
cpuInfo.ModelName = value
case "CPUMHz":
cpuInfo.CPUMHz, _ = strconv.ParseFloat(value, 64)
case "BogoMIPS:":
cpuInfo.BogoMIPS, _ = strconv.ParseFloat(value, 64)
case "HypervisorVendor":
cpuInfo.HypervisorVendor = value
case "VirtualizationType ":
cpuInfo.VirtualizationType = value
case "L1DCache":
cpuInfo.L1DCache = value
case "L1ICache":
cpuInfo.L1ICache = value
case "L2Cache":
cpuInfo.L2Cache = value
case "L3Cache":
cpuInfo.L3Cache = value
case "NUMANode0CPUs":
cpuInfo.NUMANode0CPUs = value
case "Flags:":
cpuInfo.Flags = value
}
}
if err := scanner.Err(); err != nil {
return CPUInfo{}, err
}
return cpuInfo, nil
}
func readAndParseTopOutput(scanner *bufio.Scanner) ([]ProcessInfo, error) {
var processInfoList []ProcessInfo
processInfoRegex := regexp.MustCompile(`^\s*(\d+)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+([\d.]+)\s+([\d.]+)\s+(\S+)\s+(.*)$`)
for scanner.Scan() {
line := scanner.Text()
if match := processInfoRegex.FindStringSubmatch(line); len(match) == 13 {
pid, _ := strconv.Atoi(match[1])
pr, _ := strconv.Atoi(match[3])
ni, _ := strconv.Atoi(match[4])
virt, _ := strconv.ParseInt(match[5], 10, 64)
res, _ := strconv.ParseInt(match[6], 10, 64)
shr, _ := strconv.ParseInt(match[7], 10, 64)
cpu, _ := strconv.ParseFloat(match[9], 64)
mem, _ := strconv.ParseFloat(match[10], 64)
processInfo := ProcessInfo{
PID: pid,
User: match[2],
PR: pr,
NI: ni,
VIRT: virt,
RES: res,
SHR: shr,
S: match[8],
CPU: cpu,
MEM: mem,
Time: match[11],
Command: match[12],
}
processInfoList = append(processInfoList, processInfo)
}
}
return processInfoList, nil
}
func readAndParseDiskInfo(scanner *bufio.Scanner) ([]DiskInfo, error) {
var diskInfolist []DiskInfo
diskInfoRegex := regexp.MustCompile(`^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*$`)
for scanner.Scan() {
line := scanner.Text()
if match := diskInfoRegex.FindStringSubmatch(line); len(match) == 7 {
diskInfo := DiskInfo{
Filesystem: match[1],
Size: match[2],
Used: match[3],
Avail: match[4],
UsePercent: match[5],
MountedOn: match[6],
}
diskInfolist = append(diskInfolist, diskInfo)
}
}
return diskInfolist, nil
}
func writeToJSONFile(filename string, content string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(content)
if err != nil {
return err
}
return nil
}
func runCommand(command string) (string, error) {
cmd := exec.Command("bash", "-c", command)
output, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("command '%s' failed with error: %v", command, err)
}
return string(output), nil
}
func indexSystemInfoToElasticsearch(es *elasticsearch.Client, systemInfo SystemInfo) error {
jsonData, err := json.MarshalIndent(systemInfo, "", " ")
if err != nil {
return err
}
// Prepare the bulk data for Elasticsearch
bulkRequest := esapi.IndexRequest{
Index: "unique",
DocumentID: "",
Body: bytes.NewReader(jsonData),
Refresh: "true",
}
// Send the document to Elasticsearch
res, err := bulkRequest.Do(context.Background(), es)
if err != nil {
return err
}
defer res.Body.Close()
if res.IsError() {
var e map[string]interface{}
err := json.NewDecoder(res.Body).Decode(&e)
if err != nil {
return err
}
return fmt.Errorf("error indexing document: %v", e)
}
fmt.Println("Indexed document:", string(jsonData))
return nil
}
func main() {
// Set up the Elasticsearch client
cfg := elasticsearch.Config{
Addresses: []string{"http://localhost:9200"},
}
es, err := elasticsearch.NewClient(cfg)
if err != nil {
fmt.Println("Error creating Elasticsearch client:", err)
return
}
cpuCommand, err := runCommand("lscpu")
if err != nil {
fmt.Println("Error running 'lscpu' command:", err)
return
}
cpuInfo, err := readAndParseCPUInfo(bufio.NewScanner(strings.NewReader(cpuCommand)))
if err != nil {
fmt.Println("Error parsing CPU info:", err)
return
}
topCommand, err := runCommand("top -n 3 -b")
if err != nil {
fmt.Println("Error running 'top' command:", err)
return
}
processInfoList, err := readAndParseTopOutput(bufio.NewScanner(strings.NewReader(topCommand)))
if err != nil {
fmt.Println("Error parsing top output:", err)
return
}
sort.Slice(processInfoList, func(i, j int) bool {
return processInfoList[i].CPU > processInfoList[j].CPU
})
if len(processInfoList) > 10 {
processInfoList = processInfoList[:10]
}
diskCommand, err := runCommand("df -h")
if err != nil {
fmt.Println("Error running 'df' command:", err)
return
}
diskInfoList, err := readAndParseDiskInfo(bufio.NewScanner(strings.NewReader(diskCommand)))
if err != nil {
fmt.Println("Error parsing disk info:", err)
return
}
systemInfo := SystemInfo{
CPUInfo: cpuInfo,
ProcessInfo: processInfoList,
DiskInfo: diskInfoList,
}
// Index the system information to Elasticsearch
err = indexSystemInfoToElasticsearch(es, systemInfo)
if err != nil {
fmt.Println("Error indexing system info to Elasticsearch:", err)
return
}
// Optionally, write the system information to a JSON file
jsonData, err := json.MarshalIndent(systemInfo, "", " ")
if err != nil {
fmt.Println("Error marshalling system info to JSON:", err)
return
}
err = writeToJSONFile("system_info.json", string(jsonData))
if err != nil {
fmt.Println("Error writing system info to file:", err)
return
}
fmt.Println("Output successfully written to system_info.json")
}