Extract privileged command wrapper into util

Without this, it makes the code a bit harder to read.

This fixes it by extracting the method.

Signed-off-by: Jean-Philippe Evrard <open-source@a.spamming.party>
This commit is contained in:
Jean-Philippe Evrard
2024-10-18 00:53:38 +02:00
parent f34864758e
commit 3bfdd76f29
4 changed files with 98 additions and 92 deletions
+12
View File
@@ -1,6 +1,7 @@
package util
import (
"fmt"
"os/exec"
log "github.com/sirupsen/logrus"
@@ -21,3 +22,14 @@ func NewCommand(name string, arg ...string) *exec.Cmd {
return cmd
}
// PrivilegedHostCommand wraps the command with nsenter.
// It allows to run a command from systemd's namespace for example (pid 1)
// This relies on hostPID:true and privileged:true to enter host mount space
// For info, rancher based need different pid, which should be user given.
// until we have a better discovery mechanism.
func PrivilegedHostCommand(pid int, command []string) []string {
cmd := []string{"/usr/bin/nsenter", fmt.Sprintf("-m/proc/%d/ns/mnt", pid), "--"}
cmd = append(cmd, command...)
return cmd
}
+31
View File
@@ -0,0 +1,31 @@
package util
import (
"reflect"
"testing"
)
func Test_buildHostCommand(t *testing.T) {
type args struct {
pid int
command []string
}
tests := []struct {
name string
args args
want []string
}{
{
name: "Ensure command will run with nsenter",
args: args{pid: 1, command: []string{"ls", "-Fal"}},
want: []string{"/usr/bin/nsenter", "-m/proc/1/ns/mnt", "--", "ls", "-Fal"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := PrivilegedHostCommand(tt.args.pid, tt.args.command); !reflect.DeepEqual(got, tt.want) {
t.Errorf("buildHostCommand() = %v, want %v", got, tt.want)
}
})
}
}