-
Notifications
You must be signed in to change notification settings - Fork 69
/
psutil_discoverer.go
110 lines (86 loc) · 2.26 KB
/
psutil_discoverer.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
package discovery
import (
"context"
"fmt"
"reflect"
"github.com/shirou/gopsutil/host"
"github.com/shirou/gopsutil/process"
log "github.com/sirupsen/logrus"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
type PSUtilDiscoverer struct {
processFilterer ProcessFilterer
}
func NewPSUtilDiscoverer(f ProcessFilterer) *PSUtilDiscoverer {
d := PSUtilDiscoverer{
processFilterer: f,
}
return &d
}
func (p *PSUtilDiscoverer) Discover(ctx context.Context) (*types.DiscoveryManifest, error) {
i, err := host.InfoWithContext(ctx)
if err != nil {
return nil, err
}
m := types.DiscoveryManifest{
Hostname: i.Hostname,
KernelArch: i.KernelArch,
KernelVersion: i.KernelVersion,
OS: i.OS,
Platform: i.Platform,
PlatformFamily: i.PlatformFamily,
PlatformVersion: i.PlatformVersion,
}
m = filterValues(m)
pids, err := process.PidsWithContext(ctx)
if err != nil {
return nil, fmt.Errorf("cannot retrieve processes: %s", err)
}
processes := []types.GenericProcess{}
for _, pid := range pids {
var pp *process.Process
pp, err = process.NewProcess(pid)
if err != nil {
log.Debugf("cannot read pid %d: %s", pid, err)
continue
}
processes = append(processes, PSUtilProcess(*pp))
}
filtered, err := p.processFilterer.filter(ctx, processes)
if err != nil {
return nil, err
}
for _, p := range filtered {
m.AddProcess(p)
}
return &m, nil
}
func filterValues(m types.DiscoveryManifest) types.DiscoveryManifest {
if !isValidOpenInstallationPlatform(m.Platform) {
m.Platform = ""
}
if !isValidOpenInstallationPlatformFamily(m.PlatformFamily) {
m.PlatformFamily = ""
}
return m
}
func isValidOpenInstallationPlatform(platform string) bool {
s := reflect.ValueOf(&types.OpenInstallationPlatformTypes).Elem()
for i := 0; i < s.NumField(); i++ {
v := s.Field(i).Interface().(types.OpenInstallationPlatform)
if string(v) == platform {
return true
}
}
return false
}
func isValidOpenInstallationPlatformFamily(platformFamily string) bool {
s := reflect.ValueOf(&types.OpenInstallationPlatformFamilyTypes).Elem()
for i := 0; i < s.NumField(); i++ {
v := s.Field(i).Interface().(types.OpenInstallationPlatformFamily)
if string(v) == platformFamily {
return true
}
}
return false
}