Skip to content

Commit

Permalink
refactor for simpler function
Browse files Browse the repository at this point in the history
  • Loading branch information
grcevski committed Sep 4, 2024
1 parent 028bd05 commit 146b064
Showing 1 changed file with 26 additions and 22 deletions.
48 changes: 26 additions & 22 deletions pkg/beyla/os.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,26 @@ func (e osCapabilitiesError) Error() string {
return sb.String()
}

func testAndSet(caps *helpers.OSCapabilities, capError *osCapabilitiesError, c helpers.OSCapability) {
if !caps.Has(c) {
capError.Set(c)
}
}

func checkCapabilitiesForSetOptions(config *Config, caps *helpers.OSCapabilities, capError *osCapabilitiesError) {
if config.Enabled(FeatureAppO11y) {
testAndSet(caps, capError, unix.CAP_CHECKPOINT_RESTORE)
testAndSet(caps, capError, unix.CAP_SYS_PTRACE)
}

if config.Enabled(FeatureNetO11y) {
// test for net raw only if we don't have net admin
if !caps.Has(unix.CAP_NET_ADMIN) {
testAndSet(caps, capError, unix.CAP_NET_RAW)
}
}
}

func CheckOSCapabilities(config *Config) error {
caps, err := helpers.GetCurrentProcCapabilities()

Expand All @@ -78,17 +98,11 @@ func CheckOSCapabilities(config *Config) error {

var capError osCapabilitiesError

testAndSet := func(c helpers.OSCapability) {
if !caps.Has(c) {
capError.Set(c)
}
}

major, minor := kernelVersion()

// below kernels 5.8 all BPF permissions were bundled under SYS_ADMIN
if (major == 5 && minor < 8) || (major < 5) {
testAndSet(unix.CAP_SYS_ADMIN)
testAndSet(caps, &capError, unix.CAP_SYS_ADMIN)

if capError.Empty() {
return nil
Expand All @@ -103,26 +117,16 @@ func CheckOSCapabilities(config *Config) error {
}

// core capabilities
testAndSet(unix.CAP_BPF)
testAndSet(unix.CAP_PERFMON)
testAndSet(unix.CAP_DAC_READ_SEARCH)
testAndSet(caps, &capError, unix.CAP_BPF)
testAndSet(caps, &capError, unix.CAP_PERFMON)
testAndSet(caps, &capError, unix.CAP_DAC_READ_SEARCH)

// CAP_SYS_RESOURCE is only required on kernels < 5.11
if (major == 5 && minor < 11) || (major < 5) {
testAndSet(unix.CAP_SYS_RESOURCE)
}

if config.Enabled(FeatureAppO11y) {
testAndSet(unix.CAP_CHECKPOINT_RESTORE)
testAndSet(unix.CAP_SYS_PTRACE)
testAndSet(caps, &capError, unix.CAP_SYS_RESOURCE)
}

if config.Enabled(FeatureNetO11y) {
// test for net raw only if we don't have net admin
if !caps.Has(unix.CAP_NET_ADMIN) {
testAndSet(unix.CAP_NET_RAW)
}
}
checkCapabilitiesForSetOptions(config, caps, &capError)

if capError.Empty() {
return nil
Expand Down

0 comments on commit 146b064

Please sign in to comment.