-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathnginx_process_parser.go
More file actions
415 lines (334 loc) · 10.2 KB
/
nginx_process_parser.go
File metadata and controls
415 lines (334 loc) · 10.2 KB
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
// Copyright (c) F5, Inc.
//
// This source code is licensed under the Apache License, Version 2.0 license found in the
// LICENSE file in the root directory of this source tree.
package instance
import (
"bufio"
"bytes"
"context"
"fmt"
"log/slog"
"os"
"path"
"regexp"
"sort"
"strings"
mpi "github.com/nginx/agent/v3/api/grpc/mpi/v1"
"github.com/nginx/agent/v3/internal/datasource/host/exec"
"github.com/nginx/agent/v3/pkg/id"
"github.com/nginx/agent/v3/pkg/nginxprocess"
)
const (
withWithPrefix = "with-"
withModuleSuffix = "module"
keyValueLen = 2
flagLen = 1
)
type (
NginxProcessParser struct {
executer exec.ExecInterface
}
Info struct {
ConfigureArgs map[string]interface{}
Version string
Prefix string
ConfPath string
ExePath string
LoadableModules []string
DynamicModules []string
ProcessID int32
}
)
var (
_ processParser = (*NginxProcessParser)(nil)
versionRegex = regexp.MustCompile(`(?P<name>\S+)\/(?P<version>.*)`)
)
func NewNginxProcessParser() *NginxProcessParser {
return &NginxProcessParser{
executer: &exec.Exec{},
}
}
// cognitive complexity of 16 because of the if statements in the for loop
// don't think can be avoided due to the need for continue
// nolint: revive
func (npp *NginxProcessParser) Parse(ctx context.Context, processes []*nginxprocess.Process) map[string]*mpi.Instance {
instanceMap := make(map[string]*mpi.Instance) // key is instanceID
workers := make(map[int32][]*mpi.InstanceChild) // key is ppid of process
processesByPID := convertToMap(processes)
for _, proc := range processesByPID {
if proc.IsWorker() {
// Here we are determining if the worker process has a master
if masterProcess, ok := processesByPID[proc.PPID]; ok {
workers[masterProcess.PID] = append(workers[masterProcess.PID],
&mpi.InstanceChild{ProcessId: proc.PID})
continue
}
nginxInfo, err := npp.getInfo(ctx, proc)
if err != nil {
slog.DebugContext(ctx, "Unable to get NGINX info", "pid", proc.PID, "error", err)
continue
}
// set instance process ID to 0 as there is no master process
nginxInfo.ProcessID = 0
instance := convertInfoToInstance(*nginxInfo)
if foundInstance, ok := instanceMap[instance.GetInstanceMeta().GetInstanceId()]; ok {
foundInstance.GetInstanceRuntime().InstanceChildren = append(foundInstance.GetInstanceRuntime().
GetInstanceChildren(), &mpi.InstanceChild{ProcessId: proc.PID})
continue
}
instance.GetInstanceRuntime().InstanceChildren = append(instance.GetInstanceRuntime().
GetInstanceChildren(), &mpi.InstanceChild{ProcessId: proc.PID})
instanceMap[instance.GetInstanceMeta().GetInstanceId()] = instance
continue
}
// check if proc is a master process, process is not a worker but could be cache manager etc
if proc.IsMaster() {
nginxInfo, err := npp.getInfo(ctx, proc)
if err != nil {
slog.DebugContext(ctx, "Unable to get NGINX info", "pid", proc.PID, "error", err)
continue
}
instance := convertInfoToInstance(*nginxInfo)
instanceMap[instance.GetInstanceMeta().GetInstanceId()] = instance
}
}
for _, instance := range instanceMap {
if val, ok := workers[instance.GetInstanceRuntime().GetProcessId()]; ok {
instance.InstanceRuntime.InstanceChildren = val
}
}
return instanceMap
}
func (npp *NginxProcessParser) getInfo(ctx context.Context, proc *nginxprocess.Process) (*Info, error) {
exePath := proc.Exe
if exePath == "" {
exePath = npp.getExe(ctx)
if exePath == "" {
return nil, fmt.Errorf("unable to find NGINX exe for process %d", proc.PID)
}
}
confPath := getConfPathFromCommand(proc.Cmd)
var nginxInfo *Info
outputBuffer, err := npp.executer.RunCmd(ctx, exePath, "-V")
if err != nil {
return nil, err
}
nginxInfo = parseNginxVersionCommandOutput(ctx, outputBuffer)
nginxInfo.ExePath = exePath
nginxInfo.ProcessID = proc.PID
if confPath != "" {
nginxInfo.ConfPath = confPath
} else {
nginxInfo.ConfPath = getNginxConfPath(ctx, nginxInfo)
}
loadableModules := getLoadableModules(nginxInfo)
nginxInfo.LoadableModules = loadableModules
nginxInfo.DynamicModules = getDynamicModules(nginxInfo)
return nginxInfo, err
}
func (npp *NginxProcessParser) getExe(ctx context.Context) string {
exePath := ""
out, commandErr := npp.executer.RunCmd(ctx, "sh", "-c", "command -v nginx")
if commandErr == nil {
exePath = strings.TrimSuffix(out.String(), "\n")
}
if exePath == "" {
exePath = npp.defaultToNginxCommandForProcessPath()
}
if strings.Contains(exePath, "(deleted)") {
exePath = sanitizeExeDeletedPath(exePath)
}
return exePath
}
func (npp *NginxProcessParser) defaultToNginxCommandForProcessPath() string {
exePath, err := npp.executer.FindExecutable("nginx")
if err != nil {
return ""
}
return exePath
}
func sanitizeExeDeletedPath(exe string) string {
firstSpace := strings.Index(exe, "(deleted)")
if firstSpace != -1 {
return strings.TrimSpace(exe[0:firstSpace])
}
return strings.TrimSpace(exe)
}
func convertInfoToInstance(nginxInfo Info) *mpi.Instance {
var instanceRuntime *mpi.InstanceRuntime
nginxType := mpi.InstanceMeta_INSTANCE_TYPE_NGINX
version := nginxInfo.Version
if !strings.Contains(nginxInfo.Version, "plus") {
instanceRuntime = &mpi.InstanceRuntime{
ProcessId: nginxInfo.ProcessID,
BinaryPath: nginxInfo.ExePath,
ConfigPath: nginxInfo.ConfPath,
Details: &mpi.InstanceRuntime_NginxRuntimeInfo{
NginxRuntimeInfo: &mpi.NGINXRuntimeInfo{
StubStatus: &mpi.APIDetails{
Location: "",
Listen: "",
},
AccessLogs: []string{},
ErrorLogs: []string{},
LoadableModules: nginxInfo.LoadableModules,
DynamicModules: nginxInfo.DynamicModules,
},
},
}
} else {
instanceRuntime = &mpi.InstanceRuntime{
ProcessId: nginxInfo.ProcessID,
BinaryPath: nginxInfo.ExePath,
ConfigPath: nginxInfo.ConfPath,
Details: &mpi.InstanceRuntime_NginxPlusRuntimeInfo{
NginxPlusRuntimeInfo: &mpi.NGINXPlusRuntimeInfo{
StubStatus: &mpi.APIDetails{
Location: "",
Listen: "",
},
AccessLogs: []string{},
ErrorLogs: []string{},
LoadableModules: nginxInfo.LoadableModules,
DynamicModules: nginxInfo.DynamicModules,
PlusApi: &mpi.APIDetails{
Location: "",
Listen: "",
},
},
},
}
nginxType = mpi.InstanceMeta_INSTANCE_TYPE_NGINX_PLUS
version = nginxInfo.Version
}
return &mpi.Instance{
InstanceMeta: &mpi.InstanceMeta{
InstanceId: id.Generate("%s_%s_%s", nginxInfo.ExePath, nginxInfo.ConfPath, nginxInfo.Prefix),
InstanceType: nginxType,
Version: version,
},
InstanceRuntime: instanceRuntime,
}
}
func parseNginxVersionCommandOutput(ctx context.Context, output *bytes.Buffer) *Info {
nginxInfo := &Info{}
scanner := bufio.NewScanner(output)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
switch {
case strings.HasPrefix(line, "nginx version"):
nginxInfo.Version = parseNginxVersion(line)
case strings.HasPrefix(line, "configure arguments"):
nginxInfo.ConfigureArgs = parseConfigureArguments(line)
}
}
nginxInfo.Prefix = getNginxPrefix(ctx, nginxInfo)
return nginxInfo
}
func parseNginxVersion(line string) string {
return strings.TrimPrefix(versionRegex.FindString(line), "nginx/")
}
func parseConfigureArguments(line string) map[string]interface{} {
// need to check for empty strings
flags := strings.Split(line[len("configure arguments:"):], " --")
result := make(map[string]interface{})
for _, flag := range flags {
vals := strings.Split(flag, "=")
if isFlag(vals) {
result[vals[0]] = true
} else if isKeyValueFlag(vals) {
result[vals[0]] = vals[1]
}
}
return result
}
func getNginxPrefix(ctx context.Context, nginxInfo *Info) string {
var prefix string
if nginxInfo.ConfigureArgs["prefix"] != nil {
var ok bool
prefix, ok = nginxInfo.ConfigureArgs["prefix"].(string)
if !ok {
slog.DebugContext(ctx, "Failed to cast nginxInfo prefix to string")
}
} else {
prefix = "/usr/local/nginx"
}
return prefix
}
func getNginxConfPath(ctx context.Context, nginxInfo *Info) string {
var confPath string
if nginxInfo.ConfigureArgs["conf-path"] != nil {
var ok bool
confPath, ok = nginxInfo.ConfigureArgs["conf-path"].(string)
if !ok {
slog.DebugContext(ctx, "failed to cast nginxInfo conf-path to string")
}
} else {
confPath = path.Join(nginxInfo.Prefix, "/conf/nginx.conf")
}
return confPath
}
func isFlag(vals []string) bool {
return len(vals) == flagLen && vals[0] != ""
}
func isKeyValueFlag(vals []string) bool {
return len(vals) == keyValueLen
}
func getLoadableModules(nginxInfo *Info) (modules []string) {
var err error
if mp, ok := nginxInfo.ConfigureArgs["modules-path"]; ok {
modulePath, pathOK := mp.(string)
if !pathOK {
slog.Debug("Error parsing modules-path")
return modules
}
modules, err = readDirectory(modulePath, ".so")
if err != nil {
slog.Debug("Error reading module dir", "dir", modulePath, "error", err)
return modules
}
sort.Strings(modules)
return modules
}
return modules
}
func getDynamicModules(nginxInfo *Info) (modules []string) {
configArgs := nginxInfo.ConfigureArgs
for arg := range configArgs {
if strings.HasPrefix(arg, withWithPrefix) && strings.HasSuffix(arg, withModuleSuffix) {
modules = append(modules, strings.TrimPrefix(arg, withWithPrefix))
}
}
sort.Strings(modules)
return modules
}
// readDirectory returns a list of all files in the directory which match the extension
func readDirectory(dir, extension string) (files []string, err error) {
dirInfo, err := os.ReadDir(dir)
if err != nil {
return files, fmt.Errorf("read directory %s, %w", dir, err)
}
for _, file := range dirInfo {
files = append(files, strings.ReplaceAll(file.Name(), extension, ""))
}
return files, err
}
func convertToMap(processes []*nginxprocess.Process) map[int32]*nginxprocess.Process {
processesByPID := make(map[int32]*nginxprocess.Process)
for _, p := range processes {
processesByPID[p.PID] = p
}
return processesByPID
}
func getConfPathFromCommand(command string) string {
commands := strings.Split(command, " ")
for i, command := range commands {
if command == "-c" {
if i < len(commands)-1 {
return commands[i+1]
}
}
}
return ""
}