Tim Windelschmidt | d9f1f1e | 2023-10-31 15:44:35 +0100 | [diff] [blame^] | 1 | package sysctl |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "path" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | // Options contains sysctl options to apply |
| 11 | type 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. |
| 15 | func (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 | } |