-
Notifications
You must be signed in to change notification settings - Fork 34
/
asup.go
450 lines (395 loc) · 10.6 KB
/
asup.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
package collector
import (
"cmp"
"context"
"crypto/sha1" //nolint:gosec // used for sha1sum not for security
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/netapp/harvest/v2/cmd/harvest/version"
"github.com/netapp/harvest/v2/pkg/conf"
"github.com/netapp/harvest/v2/pkg/logging"
"github.com/netapp/harvest/v2/pkg/matrix"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/process"
"os"
"os/exec"
"path"
"regexp"
"slices"
"time"
)
type Payload struct {
Target *TargetInfo
Harvest *harvestInfo
Platform *platformInfo
Nodes *InstanceInfo `json:"Nodes,omitempty"`
Volumes *InstanceInfo `json:"Volumes,omitempty"`
Tenants *InstanceInfo `json:"Tenants,omitempty"`
Collectors *[]AsupCollector
path string
}
type TargetInfo struct {
Version string
Model string
Serial string
Ping float64
ClusterUUID string
}
type ID struct {
SerialNumber string `json:"serial-number"`
SystemID string `json:"system-id"`
}
type InstanceInfo struct {
Count int64
DataPoints int64
PollTime int64
APITime int64
ParseTime int64
PluginTime int64
Ids []ID `json:"Ids,omitempty"` // revive:disable-line var-naming
}
type Process struct {
Pid int32
User string
Ppid int32
Ctime int64
RssBytes uint64
Threads int32
Cmdline string
}
type platformInfo struct {
OS string
Arch string
Memory struct {
TotalKb uint64
AvailableKb uint64
UsedKb uint64
}
CPUs uint8
NumProcesses uint64
Processes []Process
}
type harvestInfo struct {
HostHash string
UUID string
Version string
Release string
Commit string
BuildDate string
NumClusters uint8
NumPollers uint64
NumExporters uint64
NumPortRange uint64
}
type Counters struct {
Count int
List []string
}
type Schedule struct {
Name string
Schedule string
}
type AsupCollector struct {
Name string
Query string
BatchSize string `json:"BatchSize,omitempty"`
ClientTimeout string
Schedules []Schedule
Exporters []string
Counters Counters
InstanceInfo *InstanceInfo `json:"InstanceInfo,omitempty"`
}
const (
workingDir = "asup"
HundredMB = 104_857_600
)
func (p *Payload) AddCollectorAsup(a AsupCollector) {
if p.Collectors == nil {
p.Collectors = &[]AsupCollector{}
}
*p.Collectors = append(*p.Collectors, a)
}
func SendAutosupport(collectors []Collector, status *matrix.Matrix, pollerName string) error {
var (
msg *Payload
err error
)
if msg, err = BuildAndWriteAutoSupport(collectors, status, pollerName); err != nil {
return fmt.Errorf("failed to build ASUP message poller:%s %w", pollerName, err)
}
if err = sendAsupMessage(msg); err != nil {
return fmt.Errorf("failed to send ASUP message poller:%s %w", pollerName, err)
}
return nil
}
// This function forks the autosupport binary
func sendAsupMessage(msg *Payload) error {
err := sendAsupVia(msg, "./autosupport/asup")
if errors.Is(err, os.ErrNotExist) {
err = sendAsupVia(msg, "../harvest-private/harvest-asup/bin/asup")
}
if err != nil {
return err
}
return nil
}
func sendAsupVia(msg *Payload, asupExecPath string) error {
asupTimeOutLimit := 10 * time.Second
// Invoke autosupport binary
cont, cancel := context.WithTimeout(context.Background(), asupTimeOutLimit)
defer cancel()
logging.Get().Info().
Str("payloadPath", msg.path).
Msg("Fork autosupport binary.")
exitStatus := 0
err := exec.CommandContext(cont, asupExecPath, "--payload", msg.path, "--working-dir", workingDir).Run() //nolint:gosec
if err != nil {
var exitError *exec.ExitError
if ok := errors.Is(err, exitError); ok {
exitStatus = exitError.ExitCode()
}
}
// make sure to timeout after x minutes, kill that process
if errors.Is(cont.Err(), context.DeadlineExceeded) {
return fmt.Errorf("autosupport call to %s timed out:%w", asupExecPath, err)
}
if err != nil {
return err
}
logging.Get().Info().
Str("payloadPath", msg.path).
Int("exitStatus", exitStatus).
Msg("Autosupport binary forked successfully.")
return nil
}
func BuildAndWriteAutoSupport(collectors []Collector, status *matrix.Matrix, pollerName string) (*Payload, error) {
var (
msg *Payload
arch string
cpus uint8
numPortRange uint64
)
// add info about the platform (where Harvest is running)
arch, cpus = getCPUInfo()
msg = &Payload{
Platform: &platformInfo{
Arch: arch,
CPUs: cpus,
OS: getOSName(),
},
Target: &TargetInfo{
Ping: status.LazyValueFloat64("ping", "host"),
},
}
attachMemory(msg)
// give each collector the opportunity to attach autosupport information
for _, c := range collectors {
c.CollectAutoSupport(msg)
}
// count the number of Prometheus exporters with portRange
for _, e := range conf.Config.Exporters {
if e.PortRange != nil {
numPortRange++
}
}
hostname, _ := os.Hostname()
// add harvest release info
msg.Harvest = &harvestInfo{
// harvest uuid creation from sha1 of cluster uuid
UUID: sha1Sum(msg.Target.ClusterUUID),
Version: version.VERSION,
Release: version.Release,
Commit: version.Commit,
BuildDate: version.BuildDate,
HostHash: sha1Sum(hostname),
NumClusters: 1,
NumPollers: uint64(len(conf.Config.Pollers)),
NumExporters: uint64(len(conf.Config.Exporters)),
NumPortRange: numPortRange,
}
payloadPath, err := writeAutoSupport(msg, pollerName)
if err != nil {
return nil, err
}
msg.path = payloadPath
return msg, nil
}
func writeAutoSupport(msg *Payload, pollerName string) (string, error) {
var (
payloadPath string
err error
)
if payloadPath, err = getPayloadPath(workingDir, pollerName); err != nil {
return "", err
}
// name of the file: {poller_name}_payload.json
var perm os.FileMode = 0600
file, err := os.OpenFile(payloadPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, perm)
if err != nil {
return "", fmt.Errorf("autosupport failed to open payloadPath:%s %w", payloadPath, err)
}
defer func(file *os.File) {
_ = file.Close()
}(file)
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err = encoder.Encode(msg); err != nil {
return "", fmt.Errorf("autosupport failed to encode payloadPath:%s %w", payloadPath, err)
}
return payloadPath, nil
}
var psAllowListRe = regexp.MustCompile(`harvest|poller|grafana|prometheus|influxdb|netapp`)
func attachMemory(msg *Payload) {
virtualMemory, err := mem.VirtualMemory()
if err != nil {
return
}
msg.Platform.Memory.TotalKb = virtualMemory.Total / 1024
msg.Platform.Memory.AvailableKb = virtualMemory.Available / 1024
msg.Platform.Memory.UsedKb = virtualMemory.Used / 1024
// Include basic ps information for processes that pass the allow list
// This is similar to ps -ww -eo user,pid,ppid,stime,nlwp,rss,cmd
processes, err := process.Processes()
if err != nil {
return
}
msg.Platform.NumProcesses = uint64(len(processes))
msg.Platform.Processes = make([]Process, 0)
for _, p := range processes {
name, err := p.Name()
if err != nil {
continue
}
pp := Process{
Pid: p.Pid,
}
memInfo, err := p.MemoryInfo()
if err == nil {
pp.RssBytes = memInfo.RSS
}
// Ignore processes that:
// - don't pass the allowList, unless the process is using more that 100MB of memory
// - have no cmdline (these are not interesting)
if !psAllowListRe.MatchString(name) {
if pp.RssBytes < HundredMB {
continue
}
}
cmdline, err := p.Cmdline()
if err != nil {
continue
}
pp.Cmdline = cmdline
if cmdline == "" {
continue
}
username, err := p.Username()
if err == nil {
pp.User = username
}
ppid, err := p.Ppid()
if err == nil {
pp.Ppid = ppid
}
ctime, err := p.CreateTime()
if err == nil {
pp.Ctime = ctime
}
threads, err := p.NumThreads()
if err == nil {
pp.Threads = threads
}
msg.Platform.Processes = append(msg.Platform.Processes, pp)
}
// keep at most 100, ordered by size descending
if len(msg.Platform.Processes) > 100 {
slices.SortStableFunc(msg.Platform.Processes, func(a, b Process) int {
return cmp.Compare(b.RssBytes, a.RssBytes)
})
msg.Platform.Processes = msg.Platform.Processes[:100]
}
// sort processes by pid
slices.SortStableFunc(msg.Platform.Processes, func(a, b Process) int {
return cmp.Compare(a.Pid, b.Pid)
})
}
func getCPUInfo() (string, uint8) {
var (
arch string
cpuCount int
cpuInfo []cpu.InfoStat
hostInfo *host.InfoStat
err error
)
if cpuInfo, err = cpu.Info(); err == nil {
if cpuInfo != nil {
cpuCount = len(cpuInfo)
}
}
if hostInfo, err = host.Info(); err == nil {
if hostInfo != nil {
arch = hostInfo.Platform
}
}
return arch, uint8(cpuCount)
}
func getOSName() string {
info, err := host.Info()
if err != nil {
return ""
}
return info.OS
}
// Gives asup payload json file path based on input.
// Ex. asupDir = asup, pollerName = poller-1
// o/p would be asup/payload/poller-1_payload.json
func getPayloadPath(asupDir string, pollerName string) (string, error) {
payloadDir := path.Join(asupDir, "payload")
// name of the file: {poller_name}_payload.json
var perm os.FileMode = 0750
err := checkAndDeleteIfPermissionsMismatch(workingDir, perm)
if err != nil {
logging.Get().Warn().Err(err).Send()
}
err = checkAndDeleteIfPermissionsMismatch(payloadDir, perm)
if err != nil {
logging.Get().Warn().Err(err).Send()
}
// Create the asup payload directory if needed
if _, err := os.Stat(payloadDir); os.IsNotExist(err) {
if err = os.MkdirAll(payloadDir, perm); err != nil {
return "", fmt.Errorf("could not create asup payload directory %s: %w", payloadDir, err)
}
}
return path.Join(payloadDir, fmt.Sprintf("%s_%s", pollerName, "payload.json")), nil
}
func sha1Sum(s string) string {
hash := sha1.New() //nolint:gosec // using sha1 for a hash, not a security risk
hash.Write([]byte(s))
return hex.EncodeToString(hash.Sum(nil))
}
// checkAndDeleteIfPermissionsMismatch checks if the permissions of the file or directory at the given path
// match the required permissions. If they don't match, it deletes the file or directory.
func checkAndDeleteIfPermissionsMismatch(aPath string, requiredFileMode os.FileMode) error {
// Get the file or directory information
fileInfo, err := os.Stat(aPath)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("error checking permissions: %w", err)
}
// Check if the current permissions match the required permissions
currentPermissions := fileInfo.Mode().Perm()
if currentPermissions != requiredFileMode {
err = os.RemoveAll(aPath)
if err != nil {
return fmt.Errorf("error deleting file or directory: %w", err)
}
}
return nil
}