summaryrefslogtreecommitdiff
path: root/internal/flags/flags.go
blob: fda921d4c322f6f637e00a5819210f7ed62e5250 (plain)
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
package flags

import (
	"flag"
	"fmt"
	"os"
	"regexp"
	"slices"
	"strings"
	"sync"

	bpf "github.com/aquasecurity/libbpfgo"
)

var singleton Flags
var once sync.Once

var validCollapsedFields = []string{
	"path",
	"comm",
	"tracepoint",
	"pid",
	"tid",
	"flags",
}

var validCollapsedCounts = []string{
	"count",
	"duration",
	"durationToPrev",
	"bytes",
}

func Get() Flags {
	return singleton
}

type Flags struct {
	PidFilter    int
	TidFilter    int
	EventMapSize int
	CommFilter   string
	PathFilter   string
	PprofEnable  bool
	Duration     int

	// Tracepints flags
	TracepointsToAttach  []*regexp.Regexp
	TracepointsToExclude []*regexp.Regexp

	// Flamegraph flags
	FlamegraphEnable bool
	FlamegraphName   string

	// To convert ior data into collapsed format
	IorDataFile     string
	CollapsedFields []string
	CountField      string

	// To generate the Flamegraph SVGs
	FlamegraphTool string
}

func Parse() {
	once.Do(func() {
		parse()
	})
}

func parse() {
	version := flag.Bool("version", false, "Print version")

	flag.IntVar(&singleton.PidFilter, "pid", -1, "Filter for processes ID")
	flag.IntVar(&singleton.TidFilter, "tid", -1, "Filter for thread ID")
	flag.IntVar(&singleton.EventMapSize, "mapSize", 4096*16, "BPF FD event ring buffer map size")
	flag.IntVar(&singleton.Duration, "duration", 60, "Probe duration in seconds")

	flag.StringVar(&singleton.CommFilter, "comm", "", "Command to filter for")
	flag.StringVar(&singleton.PathFilter, "path", "", "Path to filter for")

	flag.BoolVar(&singleton.PprofEnable, "pprof", false, "Enable profiling")

	tracepointsToAttach := flag.String("tps", "", "Comma separated list regexes for tracepoints to load")
	tracepointsToExclude := flag.String("tpsExclude", "", "Comma separated list regexes for tracepoints to exclude")

	flag.BoolVar(&singleton.FlamegraphEnable, "flamegraph", false, "Enable flamegraph builder")
	flag.StringVar(&singleton.FlamegraphName, "name", "default", "Name of the flamegraph, used to generate the SVG file")

	flag.StringVar(&singleton.IorDataFile, "ior", "", "IOR data file to convert into collapsed format")
	fields := flag.String("fields", "",
		fmt.Sprintf("Comma separated list of fields to collapse, valid are: %v", validCollapsedFields))
	flag.StringVar(&singleton.CountField, "count", "count",
		fmt.Sprintf("Count field to collaps, valid are: %v", validCollapsedCounts))

	// https://github.com/brendangregg/FlameGraph
	flag.StringVar(&singleton.FlamegraphTool, "flamegraphTool",
		os.Getenv("HOME")+"/git/FlameGraph/flamegraph.pl", "Path to the flamegraph tool (e.g. flamegraph.pl or inferno-flamegraph)")
	flag.Parse()

	if *version {
		PrintVersion()
		os.Exit(0)
	}

	singleton.TracepointsToAttach = extractTracepointFlags(*tracepointsToAttach)
	singleton.TracepointsToExclude = extractTracepointFlags(*tracepointsToExclude)

	if *fields == "" {
		singleton.CollapsedFields = []string{"pid", "path", "tracepoint"}
	} else {
		singleton.CollapsedFields = strings.Split(*fields, ",")
	}

	for _, field := range singleton.CollapsedFields {
		if !slices.Contains(validCollapsedFields, field) {
			fmt.Println("Invalid field for collapse:", field)
			os.Exit(2)
		}
	}

	if !slices.Contains(validCollapsedCounts, singleton.CountField) {
		fmt.Println("Invalid count field:", singleton.CountField)
		os.Exit(2)
	}
}

func extractTracepointFlags(tracepoints string) (regexes []*regexp.Regexp) {
	if len(tracepoints) == 0 {
		return regexes
	}
	for _, name := range strings.Split(tracepoints, ",") {
		re, err := regexp.Compile(name)
		if err != nil {
			fmt.Println("Unable to compile regex", name, ": ", err)
			os.Exit(2)
		}
		regexes = append(regexes, re)
	}
	return regexes
}

func (flags Flags) ShouldIAttachTracepoint(tracepointName string) bool {
	for _, re := range flags.TracepointsToExclude {
		if re.MatchString(tracepointName) {
			fmt.Println("Not attaching", tracepointName, "as excluded")
			return false
		}
	}
	if len(flags.TracepointsToAttach) == 0 {
		fmt.Println("Attaching", tracepointName, "as none are explicitly incluced")
		return true
	}
	for _, re := range flags.TracepointsToAttach {
		if re.MatchString(tracepointName) {
			fmt.Println("Attaching", tracepointName, "as included")
			return true
		}
	}

	fmt.Println("Not attaching", tracepointName, "as not includedd")
	return false
}

func (flags Flags) SetBPF(bpfModule *bpf.Module) error {
	// Ignore `ior` process itself from the filter
	if err := bpfModule.InitGlobalVariable("IOR_PID_FILTER", uint32(os.Getpid())); err != nil {
		return fmt.Errorf("unable set IOR_PID_FILTER: %w", err)
	}

	fmt.Println("Setting PID_FILTER to", flags.PidFilter)
	if err := bpfModule.InitGlobalVariable("PID_FILTER", uint32(flags.PidFilter)); err != nil {
		return fmt.Errorf("unable to set up PID_FILTER global variable: %w", err)
	}

	fmt.Println("Setting TID_FILTER to", flags.TidFilter)
	if err := bpfModule.InitGlobalVariable("TID_FILTER", uint32(flags.TidFilter)); err != nil {
		return fmt.Errorf("unable to set up TID_FILTER global variable: %w", err)
	}

	return nil
}

func (flags Flags) ResizeBPFMaps(bpfModule *bpf.Module) error {
	if err := resizeBPFMap(bpfModule, "event_map", uint32(flags.EventMapSize)); err != nil {
		return fmt.Errorf("event_map: %w", err)
	}
	return nil
}

func resizeBPFMap(module *bpf.Module, name string, size uint32) error {
	m, err := module.GetMap(name)
	if err != nil {
		return err
	}

	if err = m.SetMaxEntries(size); err != nil {
		return err
	}

	if actual := m.MaxEntries(); actual != size {
		return fmt.Errorf("map resize to %d failed, expected %v, actual %v", size, size, actual)
	}

	return nil
}