| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame^] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Tim Windelschmidt | d9f1f1e | 2023-10-31 15:44:35 +0100 | [diff] [blame] | 4 | package sysctl |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path" |
| 10 | "strings" |
| 11 | ) |
| 12 | |
| 13 | // Options contains sysctl options to apply |
| 14 | type Options map[string]string |
| 15 | |
| 16 | // Apply attempts to apply all options in Options. It aborts on the first |
| 17 | // one which returns an error when applying. |
| 18 | func (o Options) Apply() error { |
| 19 | for name, value := range o { |
| 20 | filePath := path.Join("/proc/sys/", strings.ReplaceAll(name, ".", "/")) |
| 21 | optionFile, err := os.OpenFile(filePath, os.O_WRONLY, 0) |
| 22 | if err != nil { |
| 23 | return fmt.Errorf("failed to set option %v: %w", name, err) |
| 24 | } |
| 25 | if _, err := optionFile.WriteString(value + "\n"); err != nil { |
| 26 | optionFile.Close() |
| 27 | return fmt.Errorf("failed to set option %v: %w", name, err) |
| 28 | } |
| 29 | optionFile.Close() // In a loop, defer'ing could open a lot of FDs |
| 30 | } |
| 31 | return nil |
| 32 | } |