blob: 583a1dc7edc670a9205a350e0a225fb5c204ed20 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Tim Windelschmidtd9f1f1e2023-10-31 15:44:35 +01004package sysctl
5
6import (
7 "fmt"
8 "os"
9 "path"
10 "strings"
11)
12
13// Options contains sysctl options to apply
14type 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.
18func (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}