github.com/apptainer/singularity@v3.1.1+incompatible/pkg/util/sysctl/sysctl_linux.go (about) 1 // Copyright (c) 2018, Sylabs Inc. All rights reserved. 2 // This software is licensed under a 3-clause BSD license. Please consult the 3 // LICENSE.md file distributed with the sources of this project regarding your 4 // rights to use or distribute this software. 5 6 package sysctl 7 8 import ( 9 "fmt" 10 "io/ioutil" 11 "os" 12 "path/filepath" 13 "strings" 14 ) 15 16 const procSys = "/proc/sys" 17 18 func convertKey(key string) string { 19 return strings.Replace(strings.TrimSpace(key), ".", string(os.PathSeparator), -1) 20 } 21 22 func getPath(key string) (string, error) { 23 path := filepath.Join(procSys, convertKey(key)) 24 if _, err := os.Stat(path); err != nil { 25 return "", err 26 } 27 return path, nil 28 } 29 30 // Get retrieves and returns sysctl key value 31 func Get(key string) (string, error) { 32 var path string 33 34 path, err := getPath(key) 35 if err != nil { 36 return "", fmt.Errorf("can't retrieve key %s: %s", key, err) 37 } 38 39 value, err := ioutil.ReadFile(path) 40 if err != nil { 41 return "", fmt.Errorf("can't retrieve value for key %s: %s", key, err) 42 } 43 44 return strings.TrimSuffix(string(value), "\n"), nil 45 } 46 47 // Set sets value for sysctl key value 48 func Set(key string, value string) error { 49 var path string 50 51 path, err := getPath(key) 52 if err != nil { 53 return fmt.Errorf("can't retrieve key %s: %s", key, err) 54 } 55 56 return ioutil.WriteFile(path, []byte(value), 0000) 57 }