-
Notifications
You must be signed in to change notification settings - Fork 70
/
process_evaluator.go
90 lines (72 loc) · 2.47 KB
/
process_evaluator.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
package recipes
import (
"context"
"github.com/newrelic/newrelic-cli/internal/install/execution"
"github.com/shirou/gopsutil/v3/process"
log "github.com/sirupsen/logrus"
//"github.com/newrelic/newrelic-cli/internal/install/execution"
"github.com/newrelic/newrelic-cli/internal/install/types"
)
type ProcessEvaluatorInterface interface {
GetOrLoadProcesses(ctx context.Context) []types.GenericProcess
DetectionStatus(ctx context.Context, r *types.OpenInstallationRecipe) execution.RecipeStatusType
}
type ProcessEvaluator struct {
processMatchFinder ProcessMatchFinder
processFetcher func(context.Context) []types.GenericProcess
isCached bool
cachedProcess []types.GenericProcess
}
func NewProcessEvaluator() *ProcessEvaluator {
return newProcessEvaluator(NewRegexProcessMatchFinder(), GetPsUtilCommandLines, true)
}
func newProcessEvaluator(processMatchFinder ProcessMatchFinder, processFetcher func(context.Context) []types.GenericProcess, isCached bool) *ProcessEvaluator {
return &ProcessEvaluator{
processMatchFinder: processMatchFinder,
processFetcher: processFetcher,
isCached: isCached,
cachedProcess: nil,
}
}
func GetPsUtilCommandLines(ctx context.Context) []types.GenericProcess {
pids, err := process.PidsWithContext(ctx)
if err != nil {
log.Errorf("cannot retrieve processes: %s", err)
return []types.GenericProcess{}
}
processes := []types.GenericProcess{}
for _, pid := range pids {
var psproc *process.Process
psproc, err = process.NewProcess(pid)
if err != nil {
if err != process.ErrorProcessNotRunning {
log.Debugf("cannot read pid %d: %s", pid, err)
}
continue
}
p := NewPSUtilProcess(psproc)
processes = append(processes, p)
}
return processes
}
func (pe *ProcessEvaluator) GetOrLoadProcesses(ctx context.Context) []types.GenericProcess {
if pe.isCached {
if pe.cachedProcess == nil {
pe.cachedProcess = pe.processFetcher(ctx)
}
return pe.cachedProcess
}
return pe.processFetcher(ctx)
}
func (pe *ProcessEvaluator) DetectionStatus(ctx context.Context, r *types.OpenInstallationRecipe) execution.RecipeStatusType {
if len(r.ProcessMatch) == 0 {
return execution.RecipeStatusTypes.AVAILABLE
}
processes := pe.GetOrLoadProcesses(ctx)
matches := pe.processMatchFinder.FindMatches(ctx, processes, *r)
if len(matches) == 0 {
log.Tracef("recipe %s is not matching any process", r.Name)
return execution.RecipeStatusTypes.NULL
}
return execution.RecipeStatusTypes.AVAILABLE
}