blob: b5e1e360e6dc68417c17e611acf4c1cd09559a73 [file] [log] [blame]
Tim Windelschmidtd9f1f1e2023-10-31 15:44:35 +01001package sysctl
2
3import (
4 "fmt"
5 "os"
6 "path"
7 "strings"
8)
9
10// Options contains sysctl options to apply
11type Options map[string]string
12
13// Apply attempts to apply all options in Options. It aborts on the first
14// one which returns an error when applying.
15func (o Options) Apply() error {
16 for name, value := range o {
17 filePath := path.Join("/proc/sys/", strings.ReplaceAll(name, ".", "/"))
18 optionFile, err := os.OpenFile(filePath, os.O_WRONLY, 0)
19 if err != nil {
20 return fmt.Errorf("failed to set option %v: %w", name, err)
21 }
22 if _, err := optionFile.WriteString(value + "\n"); err != nil {
23 optionFile.Close()
24 return fmt.Errorf("failed to set option %v: %w", name, err)
25 }
26 optionFile.Close() // In a loop, defer'ing could open a lot of FDs
27 }
28 return nil
29}