Debian Codegraph @

pkg/utils/sysctl/sysctl_linux.go

raw symbols SCIP
1 // Copyright 2016 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package sysctl
16
17 import (
18 "fmt"
19 "os"
20 "path/filepath"
21 "strings"
22 )
23
24 // Sysctl provides a method to set/get values from /proc/sys - in linux systems
25 // new interface to set/get values of variables formerly handled by sysctl syscall
26 // If optional `params` have only one string value - this function will
27 // set this value into corresponding sysctl variable
28 func Sysctl(name string, params ...string) (string, error) {
29 if len(params) > 1 {
30 return "", fmt.Errorf("unexcepted additional parameters")
31 } else if len(params) == 1 {
32 return setSysctl(name, params[0])
33 }
34 return getSysctl(name)
35 }
36
37 func getSysctl(name string) (string, error) {
38 fullName := filepath.Join("/proc/sys", toNormalName(name))
39 data, err := os.ReadFile(fullName)
40 if err != nil {
41 return "", err
42 }
43
44 return string(data[:len(data)-1]), nil
45 }
46
47 func setSysctl(name, value string) (string, error) {
48 fullName := filepath.Join("/proc/sys", toNormalName(name))
49 if err := os.WriteFile(fullName, []byte(value), 0o644); err != nil {
50 return "", err
51 }
52
53 return getSysctl(name)
54 }
55
56 // Normalize names by using slash as separator
57 // Sysctl names can use dots or slashes as separator:
58 // - if dots are used, dots and slashes are interchanged.
59 // - if slashes are used, slashes and dots are left intact.
60 // Separator in use is determined by first occurrence.
61 func toNormalName(name string) string {
62 interchange := false
63 for _, c := range name {
64 if c == '.' {
65 interchange = true
66 break
67 }
68 if c == '/' {
69 break
70 }
71 }
72
73 if interchange {
74 r := strings.NewReplacer(".", "/", "/", ".")
75 return r.Replace(name)
76 }
77 return name
78 }