-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmd.go
598 lines (535 loc) · 15.8 KB
/
cmd.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
package cmd
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"github.com/arctir/proctor/platforms/github"
"github.com/arctir/proctor/plib"
"github.com/arctir/proctor/source"
"github.com/arctir/proctor/ui"
"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
const (
timeDateFormat = "2006-01-02 15:04"
)
// SetupCLI constructs the cobra hierachry to create the proctor CLI.
//
// Do not use this function in other Go pacakges. Instead, you should look to
// import the libraries used in the cmd packge directly. For example, [plib].
//
// [plib]: https://github.com/arctir/proctor/tree/main/plib
func SetupCLI() *cobra.Command {
proctorCmd.AddCommand(uiCmd)
proctorCmd.AddCommand(processCmd)
proctorCmd.AddCommand(sourceCmd)
sourceCmd.AddCommand(commitCmd)
sourceCmd.AddCommand(artifactsCmd)
artifactsCmd.AddCommand(artifactsListCmd)
artifactsCmd.AddCommand(artifactsGetCmd)
commitCmd.AddCommand(contribListCmd)
commitCmd.AddCommand(contribDiffCmd)
processCmd.AddCommand(listCmd)
processCmd.AddCommand(getCmd)
processCmd.AddCommand(treeCmd)
processCmd.AddCommand(fpCmd)
return proctorCmd
}
// runProctor defines what should occur when `proctor ...` is run.
func runProctor(cmd *cobra.Command, args []string) {
// if proctor is run without a command (argument), print help.
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
}
// runProcess defines what should occur when `proctor process ...` is run.
func runProcess(cmd *cobra.Command, args []string) {
// if proctor is run without a command (argument), print help.
if len(args) == 0 {
cmd.Help()
os.Exit(0)
}
}
// runUI defines the behavior of running:
// `proctor ui ...`
func runUI(cmd *cobra.Command, args []string) {
ui.New().RunUI()
}
// runListProcesses defines the behavior of running:
// `proctor process ls ...`
func runListProcesses(cmd *cobra.Command, args []string) {
opts := newProctorOptions(cmd.Flags())
ps, err := createInspectorAndGetProcesses(opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("process collection failed: %s", err))
}
out, err := createListOutput(ps, opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("failed creating output for retrieved processes: %s", err))
}
output(out)
}
// runGetProcess defines the behavior of running:
// `proctor process get ...`
func runGetProcess(cmd *cobra.Command, args []string) {
fs := cmd.Flags()
opts := newProctorOptions(cmd.Flags())
ps, err := createInspectorAndGetProcesses(opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("process collection failed: %s", err))
}
// use flags to determine how to resolve process(es)
id, _ := fs.GetInt(idFlag)
name, _ := fs.GetString(nameFlag)
var out []byte
switch {
case id != 0:
p := ps[id]
out, err = createSingleOutput(p, opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("failed creating output for process: %s", err))
}
case name != "":
matchedPs := findAllProcessesWithName(name, ps)
out, err = createListOutput(matchedPs, opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("failed creating output for processes: %s", err))
}
default:
cmd.Help()
}
output(out)
}
// runTreeProcess defines the behavior of running:
// `proctor process tree ...`
func runTreeProcess(cmd *cobra.Command, args []string) {
pid, err := parseID(args)
if err != nil {
outputErrorAndFail(fmt.Sprintf("please pass a valid pid (int); we received: %s", args[0]))
}
opts := newProctorOptions(cmd.Flags())
ps, err := createInspectorAndGetProcesses(opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("process collection failed: %s", err))
}
if ps[pid] == nil {
outputErrorAndFail(fmt.Sprintf("failed to find process with id: %d", pid))
}
// collect all processes from the specified and recursively to every parent.
relatedPs := []plib.Process{}
relatedPs = append(relatedPs, *ps[pid])
currentParentPid := ps[pid].ParentProcess
for {
// we've reached the root (likely the init system).
if currentParentPid == 0 {
break
}
// if we can't resolve details about the parent process, stop gathering the
// hierarchy.
if ps[currentParentPid] == nil {
break
}
relatedPs = append(relatedPs, *ps[currentParentPid])
currentParentPid = ps[currentParentPid].ParentProcess
}
o, err := createSliceListOutput(relatedPs, opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("failed creating output for processes: %s", err))
}
output(o)
}
// runFingerPrintProcess defines the behavior for running:
// `proctor process finger-print ...`
func runFingerPrintProcess(cmd *cobra.Command, args []string) {
pid, err := parseID(args)
if err != nil {
outputErrorAndFail(fmt.Sprintf("please pass a valid pid (int); we received: %s", args[0]))
}
opts := newProctorOptions(cmd.Flags())
ps, err := createInspectorAndGetProcesses(opts)
if err != nil {
outputErrorAndFail(fmt.Sprintf("process collection failed: %s", err))
}
if ps[pid] == nil {
outputErrorAndFail(fmt.Sprintf("failed to find process with id: %d", pid))
}
if ps[pid].BinarySHA == "" {
outputErrorAndFail(fmt.Sprintf("process %d is missing details about its binary binary checksum.", pid))
}
combinedHashes := ps[pid].BinarySHA
// collect all processes from the specified and recursively to every parent.
currentParentPid := ps[pid].ParentProcess
for {
// we've reached the root (likely the init system).
if currentParentPid == 0 {
break
}
// if we can't resolve details about the parent process, there may be an
// issue with permission and the finger print will not be valid.
if ps[currentParentPid] == nil {
outputErrorAndFail(fmt.Sprintf("could not gather details on parent process: %d and thus could not generate a finger print. error: %s", currentParentPid, err))
}
combinedHashes += ps[currentParentPid].BinarySHA
currentParentPid = ps[currentParentPid].ParentProcess
}
fp := sha256.Sum256([]byte(combinedHashes))
output([]byte(hex.EncodeToString(fp[:])))
}
// parseID is a helper function to determine if the first argument passed to
// the command is a valid ID (int).
func parseID(args []string) (int, error) {
// user must specify an ID
if len(args) < 1 {
return 0, fmt.Errorf("please provide a pid (int)")
}
pid, err := strconv.Atoi(args[0])
if err != nil {
return 0, err
}
return pid, nil
}
// createInspectorAndGetProcesses is a helper function since most CLI commands will need table:
// 1. Create a new LinuxInspector
// 2. Setup configuration
// 3. Retrieve a list of processes
func createInspectorAndGetProcesses(opts proctorOpts) (plib.Processes, error) {
conf := plib.InspectorConfig{
LinuxConfig: plib.LinuxInspectorConfig{
IncludeKernel: opts.includeKernel,
IncludePermissionIssues: opts.includePermIssue,
},
}
insp, err := plib.NewInspector(conf)
if err != nil {
return nil, fmt.Errorf("failed setting up library to retrieve processes: %s", err)
}
// if reset cache was set, clear the cache before attempting to load processes
if opts.resetCache {
insp.ClearProcessCache()
}
ps, err := insp.GetProcesses()
if err != nil {
return nil, fmt.Errorf("failed retrieving processes via Linux APIs: %s", err)
}
return ps, nil
}
// findAllProcessesWithName looks through all processes (ps) and find any
// process where the [plib.Process]'s CommandName is equal to the provided
// name. Since there can be multiple processes with the same command name, this
// returns another processes (map/list).
func findAllProcessesWithName(name string, ps plib.Processes) plib.Processes {
matchedPs := plib.Processes{}
for _, p := range ps {
if p.CommandName == name {
matchedPs[p.ID] = p
}
}
return matchedPs
}
func output(out []byte) {
fmt.Printf("%s", out)
}
func outputErrorAndFail(msg string) {
fmt.Println(msg)
// exit(1) is the catchall for general errors.
os.Exit(1)
}
func createSingleOutput(ps *plib.Process, opts proctorOpts) ([]byte, error) {
var out []byte
switch opts.outType {
case jsonOut:
out = createJSONSingleOutput(ps)
default:
out = createTableSingleOutput(ps)
}
return out, nil
}
func createSliceListOutput(ps []plib.Process, opts proctorOpts) ([]byte, error) {
var out []byte
switch opts.outType {
case jsonOut:
out = createJSONSliceListOutput(ps)
default:
out = createTableSliceListOutput(ps)
}
return out, nil
}
func createListOutput(ps plib.Processes, opts proctorOpts) ([]byte, error) {
var out []byte
switch opts.outType {
case jsonOut:
out = createJSONListOutput(ps)
default:
out = createTableListOutput(ps)
}
return out, nil
}
func createJSONSliceListOutput(ps []plib.Process) []byte {
out, _ := json.Marshal(ps)
return out
}
func createJSONListOutput(ps plib.Processes) []byte {
out, _ := json.Marshal(ps)
return out
}
func createJSONSingleOutput(ps *plib.Process) []byte {
out, _ := json.Marshal(ps)
return out
}
func createTableSingleOutput(p *plib.Process) []byte {
if p == nil {
return []byte{}
}
psToReturn := []string{
strconv.Itoa(p.ID),
p.CommandName,
p.CommandPath,
p.BinarySHA,
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"PID", "name", "location", "SHA"})
table.Append(psToReturn)
table.Render()
return buf.Bytes()
}
// newCommitTableOutput takes a list of commits and create a table output
// represented in bytes. It offers a lengthLimit argument which allows
// limitting the amount of bytes used when printing in the table.
func newCommitTableOutput(commits []source.Commit, lengthLimit int) []byte {
listOfCommits := [][]string{}
for _, c := range commits {
truncatedMsg := []byte{}
if len(c.Message) > lengthLimit {
truncatedMsg = c.Message[:lengthLimit]
} else {
truncatedMsg = c.Message
}
truncatedAuthor := []byte(c.Author.Email)
if len(truncatedAuthor) > lengthLimit {
truncatedAuthor = truncatedAuthor[:lengthLimit]
}
finalCommitMsg := strings.ReplaceAll(string(truncatedMsg), "\n", " ")
listOfCommits = append(listOfCommits, []string{
c.Hash.String(),
finalCommitMsg,
string(truncatedAuthor),
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"SHA", "Message", "Author"})
table.AppendBulk(listOfCommits)
table.Render()
return buf.Bytes()
}
// newCommitDiffTableOutput takes a list of commits and create a table output
// represented in bytes. It offers a lengthLimit argument which allows
// limitting the amount of bytes used when printing in the table.
func newCommitDiffTableOutput(commitsOnlyIn1 []source.Commit, tag1 string, commitsOnlyIn2 []source.Commit, tag2 string, lengthLimit int) []byte {
listOfCommits1 := [][]string{}
listOfCommits2 := [][]string{}
for _, c := range commitsOnlyIn1 {
truncatedMsg := []byte{}
if len(c.Message) > lengthLimit {
truncatedMsg = c.Message[:lengthLimit]
} else {
truncatedMsg = c.Message
}
truncatedAuthor := []byte(c.Author.Email)
if len(truncatedAuthor) > lengthLimit {
truncatedAuthor = truncatedAuthor[:lengthLimit]
}
finalCommitMsg := strings.ReplaceAll(string(truncatedMsg), "\n", " ")
listOfCommits1 = append(listOfCommits1, []string{
c.Hash.String(),
finalCommitMsg,
string(truncatedAuthor),
c.Date.Format(timeDateFormat),
})
}
for _, c := range commitsOnlyIn2 {
truncatedMsg := []byte{}
if len(c.Message) > lengthLimit {
truncatedMsg = c.Message[:lengthLimit]
} else {
truncatedMsg = c.Message
}
truncatedAuthor := []byte(c.Author.Email)
if len(truncatedAuthor) > lengthLimit {
truncatedAuthor = truncatedAuthor[:lengthLimit]
}
finalCommitMsg := strings.ReplaceAll(string(truncatedMsg), "\n", " ")
listOfCommits2 = append(listOfCommits2, []string{
c.Hash.String(),
finalCommitMsg,
string(truncatedAuthor),
c.Date.Format(timeDateFormat),
})
}
var buf bytes.Buffer
// header commit 1
table := tablewriter.NewWriter(&buf)
table.Append([]string{fmt.Sprintf("commits only in %s", tag1)})
table.Render()
// commit 1 table
table = tablewriter.NewWriter(&buf)
table.SetHeader([]string{"SHA", "Message", "Author", "Timestamp"})
table.AppendBulk(listOfCommits1)
table.Render()
// header commit 2
table = tablewriter.NewWriter(&buf)
table.Append([]string{fmt.Sprintf("commits only in %s", tag2)})
table.Render()
// commit 2 table
table = tablewriter.NewWriter(&buf)
table.SetHeader([]string{"SHA", "Message", "Author", "Timestamp"})
table.AppendBulk(listOfCommits2)
table.Render()
return buf.Bytes()
}
func newAuthorTableOutput(authors []authorWrapper) []byte {
listOfAuthors := [][]string{}
for _, a := range authors {
listOfAuthors = append(listOfAuthors, []string{
strconv.Itoa(a.commitCount),
a.Name,
a.Email,
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"Commits", "Name", "Email"})
table.AppendBulk(listOfAuthors)
table.SetAutoWrapText(false)
table.Render()
return buf.Bytes()
}
func newArtifactListTableOutput(releases []github.Release) []byte {
listOfArtifacts := [][]string{}
for _, r := range releases {
count := len(r.Artifacts)
listOfArtifacts = append(listOfArtifacts, []string{
r.Name,
r.Tag,
strconv.Itoa(count),
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"Tag", "Title", "Artifacts"})
table.AppendBulk(listOfArtifacts)
table.SetAutoWrapText(false)
table.Render()
return buf.Bytes()
}
func newArtifactGetTableOutput(releases []github.Artifact) []byte {
listOfArtifacts := [][]string{}
for _, r := range releases {
listOfArtifacts = append(listOfArtifacts, []string{
r.Name,
r.ContentType,
r.URL,
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"Assset", "Content-Type", "URL"})
table.AppendBulk(listOfArtifacts)
table.SetAutoWrapText(false)
table.Render()
return buf.Bytes()
}
func createTableListOutput(ps plib.Processes) []byte {
listOfPs := [][]string{}
for _, p := range ps {
listOfPs = append(listOfPs, []string{
strconv.Itoa(p.ID),
p.CommandName,
p.CommandPath,
p.BinarySHA,
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"PID", "name", "location", "SHA"})
table.AppendBulk(listOfPs)
table.Render()
return buf.Bytes()
}
func createTableSliceListOutput(ps []plib.Process) []byte {
listOfPs := [][]string{}
for _, p := range ps {
listOfPs = append(listOfPs, []string{
strconv.Itoa(p.ID),
p.CommandName,
p.CommandPath,
p.BinarySHA,
})
}
var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader([]string{"PID", "name", "location", "SHA"})
table.AppendBulk(listOfPs)
table.Render()
return buf.Bytes()
}
// sourceOpts provides details on how source-related details should be
// retrieved
type sourceOpts struct {
retrieveOnlyAuthors bool
// used when you want to limit commit retrieval to a single tag
singleTag string
// used when you want to compare commits between 2 tags, required tagTwo to
// be set.
tagOne string
// used when you want to compare commits between 2 tags, required tagOne to
// be set.
tagTwo string
}
func newSourceOptions(fs *pflag.FlagSet) sourceOpts {
roa, _ := fs.GetBool(authorsFlag)
singleTag, _ := fs.GetString(tagFlag)
t1, _ := fs.GetString(tagOneFlag)
t2, _ := fs.GetString(tagTwoFlag)
return sourceOpts{
retrieveOnlyAuthors: roa,
singleTag: singleTag,
tagOne: t1,
tagTwo: t2,
}
}
func newProctorOptions(fs *pflag.FlagSet) proctorOpts {
ot := resolveOutputType(fs)
fko, _ := fs.GetBool(includeKernelFlag)
ipi, _ := fs.GetBool(includePermIssueFlag)
rc, _ := fs.GetBool(resetCacheFlag)
return proctorOpts{
outType: ot,
includeKernel: fko,
includePermIssue: ipi,
resetCache: rc,
}
}
func resolveOutputType(fs *pflag.FlagSet) outputType {
of, err := fs.GetString(outputFlag)
// default if there are ever issues finding flag
if err != nil {
return tableOut
}
switch of {
case "json":
return jsonOut
case "table":
return tableOut
}
// default OutputType
return tableOut
}