code
stringlengths
11
335k
docstring
stringlengths
20
11.8k
func_name
stringlengths
1
100
language
stringclasses
1 value
repo
stringclasses
245 values
path
stringlengths
4
144
url
stringlengths
43
214
license
stringclasses
4 values
func GetRuntimeDir() (string, error) { return "", errors.New("homedir.GetRuntimeDir() is not supported on this system") }
GetRuntimeDir is unsupported on non-linux system.
GetRuntimeDir
go
balena-os/balena-engine
pkg/homedir/homedir_others.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_others.go
Apache-2.0
func StickRuntimeDirContents(files []string) ([]string, error) { return nil, errors.New("homedir.StickRuntimeDirContents() is not supported on this system") }
StickRuntimeDirContents is unsupported on non-linux system.
StickRuntimeDirContents
go
balena-os/balena-engine
pkg/homedir/homedir_others.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_others.go
Apache-2.0
func GetDataHome() (string, error) { return "", errors.New("homedir.GetDataHome() is not supported on this system") }
GetDataHome is unsupported on non-linux system.
GetDataHome
go
balena-os/balena-engine
pkg/homedir/homedir_others.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_others.go
Apache-2.0
func GetConfigHome() (string, error) { return "", errors.New("homedir.GetConfigHome() is not supported on this system") }
GetConfigHome is unsupported on non-linux system.
GetConfigHome
go
balena-os/balena-engine
pkg/homedir/homedir_others.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_others.go
Apache-2.0
func Key() string { return "USERPROFILE" }
Key returns the env var name for the user's home dir based on the platform being run on
Key
go
balena-os/balena-engine
pkg/homedir/homedir_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_windows.go
Apache-2.0
func Get() string { return os.Getenv(Key()) }
Get returns the home directory of the current user with the help of environment variables depending on the target operating system. Returned path should be used with "path/filepath" to form new paths.
Get
go
balena-os/balena-engine
pkg/homedir/homedir_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_windows.go
Apache-2.0
func GetShortcutString() string { return "%USERPROFILE%" // be careful while using in format functions }
GetShortcutString returns the string that is shortcut to user's home directory in the native shell of the platform running on.
GetShortcutString
go
balena-os/balena-engine
pkg/homedir/homedir_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_windows.go
Apache-2.0
func Key() string { return "HOME" }
Key returns the env var name for the user's home dir based on the platform being run on
Key
go
balena-os/balena-engine
pkg/homedir/homedir_unix.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_unix.go
Apache-2.0
func Get() string { home := os.Getenv(Key()) if home == "" { if u, err := user.Current(); err == nil { return u.HomeDir } } return home }
Get returns the home directory of the current user with the help of environment variables depending on the target operating system. Returned path should be used with "path/filepath" to form new paths. If linking statically with cgo enabled against glibc, ensure the osusergo build tag is used. If needing to do nss lookups, do not disable cgo or set osusergo.
Get
go
balena-os/balena-engine
pkg/homedir/homedir_unix.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_unix.go
Apache-2.0
func GetShortcutString() string { return "~" }
GetShortcutString returns the string that is shortcut to user's home directory in the native shell of the platform running on.
GetShortcutString
go
balena-os/balena-engine
pkg/homedir/homedir_unix.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_unix.go
Apache-2.0
func GetRuntimeDir() (string, error) { if xdgRuntimeDir := os.Getenv("XDG_RUNTIME_DIR"); xdgRuntimeDir != "" { return xdgRuntimeDir, nil } return "", errors.New("could not get XDG_RUNTIME_DIR") }
GetRuntimeDir returns XDG_RUNTIME_DIR. XDG_RUNTIME_DIR is typically configured via pam_systemd. GetRuntimeDir returns non-nil error if XDG_RUNTIME_DIR is not set. See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
GetRuntimeDir
go
balena-os/balena-engine
pkg/homedir/homedir_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_linux.go
Apache-2.0
func StickRuntimeDirContents(files []string) ([]string, error) { runtimeDir, err := GetRuntimeDir() if err != nil { // ignore error if runtimeDir is empty return nil, nil } runtimeDir, err = filepath.Abs(runtimeDir) if err != nil { return nil, err } var sticked []string for _, f := range files { f, err = filepath.Abs(f) if err != nil { return sticked, err } if strings.HasPrefix(f, runtimeDir+"/") { if err = stick(f); err != nil { return sticked, err } sticked = append(sticked, f) } } return sticked, nil }
StickRuntimeDirContents sets the sticky bit on files that are under XDG_RUNTIME_DIR, so that the files won't be periodically removed by the system. StickyRuntimeDir returns slice of sticked files. StickyRuntimeDir returns nil error if XDG_RUNTIME_DIR is not set. See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
StickRuntimeDirContents
go
balena-os/balena-engine
pkg/homedir/homedir_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_linux.go
Apache-2.0
func GetDataHome() (string, error) { if xdgDataHome := os.Getenv("XDG_DATA_HOME"); xdgDataHome != "" { return xdgDataHome, nil } home := os.Getenv("HOME") if home == "" { return "", errors.New("could not get either XDG_DATA_HOME or HOME") } return filepath.Join(home, ".local", "share"), nil }
GetDataHome returns XDG_DATA_HOME. GetDataHome returns $HOME/.local/share and nil error if XDG_DATA_HOME is not set. See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
GetDataHome
go
balena-os/balena-engine
pkg/homedir/homedir_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_linux.go
Apache-2.0
func GetConfigHome() (string, error) { if xdgConfigHome := os.Getenv("XDG_CONFIG_HOME"); xdgConfigHome != "" { return xdgConfigHome, nil } home := os.Getenv("HOME") if home == "" { return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") } return filepath.Join(home, ".config"), nil }
GetConfigHome returns XDG_CONFIG_HOME. GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html
GetConfigHome
go
balena-os/balena-engine
pkg/homedir/homedir_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/homedir/homedir_linux.go
Apache-2.0
func NewProgressReader(in io.ReadCloser, out Output, size int64, id, action string) *Reader { return &Reader{ in: in, out: out, size: size, id: id, action: action, rateLimiter: rate.NewLimiter(rate.Every(100*time.Millisecond), 1), } }
NewProgressReader creates a new ProgressReader.
NewProgressReader
go
balena-os/balena-engine
pkg/progress/progressreader.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progressreader.go
Apache-2.0
func (p *Reader) Close() error { if p.current < p.size { // print a full progress bar when closing prematurely p.current = p.size p.updateProgress(false) } return p.in.Close() }
Close closes the progress reader and its underlying reader.
Close
go
balena-os/balena-engine
pkg/progress/progressreader.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progressreader.go
Apache-2.0
func NewProgressSink(out Output, size int64, id, action string) *Sink { return &Sink{ out: out, Size: size, id: id, action: action, rateLimiter: rate.NewLimiter(rate.Every(100*time.Millisecond), 1), } }
NewProgressSink creates a new ProgressSink.
NewProgressSink
go
balena-os/balena-engine
pkg/progress/progresssink.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progresssink.go
Apache-2.0
func ChanOutput(progressChan chan<- Progress) Output { return chanOutput(progressChan) }
ChanOutput returns an Output that writes progress updates to the supplied channel.
ChanOutput
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func DiscardOutput() Output { return discardOutput{} }
DiscardOutput returns an Output that discards progress
DiscardOutput
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func Update(out Output, id, action string) { out.WriteProgress(Progress{ID: id, Action: action}) }
Update is a convenience function to write a progress update to the channel.
Update
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func Updatef(out Output, id, format string, a ...interface{}) { Update(out, id, fmt.Sprintf(format, a...)) }
Updatef is a convenience function to write a printf-formatted progress update to the channel.
Updatef
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func Message(out Output, id, message string) { out.WriteProgress(Progress{ID: id, Message: message}) }
Message is a convenience function to write a progress message to the channel.
Message
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func Messagef(out Output, id, format string, a ...interface{}) { Message(out, id, fmt.Sprintf(format, a...)) }
Messagef is a convenience function to write a printf-formatted progress message to the channel.
Messagef
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func Aux(out Output, a interface{}) { out.WriteProgress(Progress{Aux: a}) }
Aux sends auxiliary information over a progress interface, which will not be formatted for the UI. This is used for things such as push signing.
Aux
go
balena-os/balena-engine
pkg/progress/progress.go
https://github.com/balena-os/balena-engine/blob/master/pkg/progress/progress.go
Apache-2.0
func WithCgroup2GroupPath(g string) Opt { return func(o *opts) { o.cg2GroupPath = path.Clean(g) } }
WithCgroup2GroupPath specifies the cgroup v2 group path to inspect availability of the controllers. WithCgroup2GroupPath is expected to be used for rootless mode with systemd driver. e.g. g = "/user.slice/user-1000.slice/[email protected]"
WithCgroup2GroupPath
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func New(quiet bool, options ...Opt) *SysInfo { var opts opts for _, o := range options { o(&opts) } if cdcgroups.Mode() == cdcgroups.Unified { return newV2(quiet, &opts) } var ops []infoCollector var warnings []string sysInfo := &SysInfo{} cgMounts, err := findCgroupMountpoints() if err != nil { logrus.Warn(err) } else { ops = append(ops, []infoCollector{ applyMemoryCgroupInfo, applyCPUCgroupInfo, applyBlkioCgroupInfo, applyCPUSetCgroupInfo, applyPIDSCgroupInfo, applyDevicesCgroupInfo, }...) } ops = append(ops, []infoCollector{ applyNetworkingInfo, applyAppArmorInfo, applySeccompInfo, applyCgroupNsInfo, }...) for _, o := range ops { w := o(sysInfo, cgMounts) warnings = append(warnings, w...) } if !quiet { for _, w := range warnings { logrus.Warn(w) } } return sysInfo }
New returns a new SysInfo, using the filesystem to detect which features the kernel supports. If `quiet` is `false` warnings are printed in logs whenever an error occurs or misconfigurations are present.
New
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyMemoryCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string mountPoint, ok := cgMounts["memory"] if !ok { warnings = append(warnings, "Your kernel does not support cgroup memory limit") return warnings } info.MemoryLimit = ok info.SwapLimit = cgroupEnabled(mountPoint, "memory.memsw.limit_in_bytes") if !info.SwapLimit { warnings = append(warnings, "Your kernel does not support swap memory limit") } info.MemoryReservation = cgroupEnabled(mountPoint, "memory.soft_limit_in_bytes") if !info.MemoryReservation { warnings = append(warnings, "Your kernel does not support memory reservation") } info.OomKillDisable = cgroupEnabled(mountPoint, "memory.oom_control") if !info.OomKillDisable { warnings = append(warnings, "Your kernel does not support oom control") } info.MemorySwappiness = cgroupEnabled(mountPoint, "memory.swappiness") if !info.MemorySwappiness { warnings = append(warnings, "Your kernel does not support memory swappiness") } info.KernelMemory = cgroupEnabled(mountPoint, "memory.kmem.limit_in_bytes") if !info.KernelMemory { warnings = append(warnings, "Your kernel does not support kernel memory limit") } info.KernelMemoryTCP = cgroupEnabled(mountPoint, "memory.kmem.tcp.limit_in_bytes") if !info.KernelMemoryTCP { warnings = append(warnings, "Your kernel does not support kernel memory TCP limit") } return warnings }
applyMemoryCgroupInfo adds the memory cgroup controller information to the info.
applyMemoryCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyCPUCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string mountPoint, ok := cgMounts["cpu"] if !ok { warnings = append(warnings, "Unable to find cpu cgroup in mounts") return warnings } info.CPUShares = cgroupEnabled(mountPoint, "cpu.shares") if !info.CPUShares { warnings = append(warnings, "Your kernel does not support CPU shares") } info.CPUCfs = cgroupEnabled(mountPoint, "cpu.cfs_quota_us") if !info.CPUCfs { warnings = append(warnings, "Your kernel does not support CPU CFS scheduler") } info.CPURealtime = cgroupEnabled(mountPoint, "cpu.rt_period_us") if !info.CPURealtime { warnings = append(warnings, "Your kernel does not support CPU realtime scheduler") } return warnings }
applyCPUCgroupInfo adds the cpu cgroup controller information to the info.
applyCPUCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyBlkioCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string mountPoint, ok := cgMounts["blkio"] if !ok { warnings = append(warnings, "Unable to find blkio cgroup in mounts") return warnings } info.BlkioWeight = cgroupEnabled(mountPoint, "blkio.weight") if !info.BlkioWeight { warnings = append(warnings, "Your kernel does not support cgroup blkio weight") } info.BlkioWeightDevice = cgroupEnabled(mountPoint, "blkio.weight_device") if !info.BlkioWeightDevice { warnings = append(warnings, "Your kernel does not support cgroup blkio weight_device") } info.BlkioReadBpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.read_bps_device") if !info.BlkioReadBpsDevice { warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.read_bps_device") } info.BlkioWriteBpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.write_bps_device") if !info.BlkioWriteBpsDevice { warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.write_bps_device") } info.BlkioReadIOpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.read_iops_device") if !info.BlkioReadIOpsDevice { warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.read_iops_device") } info.BlkioWriteIOpsDevice = cgroupEnabled(mountPoint, "blkio.throttle.write_iops_device") if !info.BlkioWriteIOpsDevice { warnings = append(warnings, "Your kernel does not support cgroup blkio throttle.write_iops_device") } return warnings }
applyBlkioCgroupInfo adds the blkio cgroup controller information to the info.
applyBlkioCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyCPUSetCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string mountPoint, ok := cgMounts["cpuset"] if !ok { warnings = append(warnings, "Unable to find cpuset cgroup in mounts") return warnings } info.Cpuset = ok var err error cpus, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.cpus")) if err != nil { return warnings } info.Cpus = strings.TrimSpace(string(cpus)) mems, err := ioutil.ReadFile(path.Join(mountPoint, "cpuset.mems")) if err != nil { return warnings } info.Mems = strings.TrimSpace(string(mems)) return warnings }
applyCPUSetCgroupInfo adds the cpuset cgroup controller information to the info.
applyCPUSetCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyPIDSCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string _, ok := cgMounts["pids"] if !ok { warnings = append(warnings, "Unable to find pids cgroup in mounts") return warnings } info.PidsLimit = true return warnings }
applyPIDSCgroupInfo adds whether the pids cgroup controller is available to the info.
applyPIDSCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyDevicesCgroupInfo(info *SysInfo, cgMounts map[string]string) []string { var warnings []string _, ok := cgMounts["devices"] info.CgroupDevicesEnabled = ok return warnings }
applyDevicesCgroupInfo adds whether the devices cgroup controller is available to the info.
applyDevicesCgroupInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyNetworkingInfo(info *SysInfo, _ map[string]string) []string { var warnings []string info.IPv4ForwardingDisabled = !readProcBool("/proc/sys/net/ipv4/ip_forward") info.BridgeNFCallIPTablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-iptables") info.BridgeNFCallIP6TablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-ip6tables") return warnings }
applyNetworkingInfo adds networking information to the info.
applyNetworkingInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyAppArmorInfo(info *SysInfo, _ map[string]string) []string { var warnings []string if _, err := os.Stat("/sys/kernel/security/apparmor"); !os.IsNotExist(err) { if _, err := ioutil.ReadFile("/sys/kernel/security/apparmor/profiles"); err == nil { info.AppArmor = true } } return warnings }
applyAppArmorInfo adds whether AppArmor is enabled to the info.
applyAppArmorInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applyCgroupNsInfo(info *SysInfo, _ map[string]string) []string { var warnings []string if _, err := os.Stat("/proc/self/ns/cgroup"); !os.IsNotExist(err) { info.CgroupNamespaces = true } return warnings }
applyCgroupNsInfo adds whether cgroupns is enabled to the info.
applyCgroupNsInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func applySeccompInfo(info *SysInfo, _ map[string]string) []string { var warnings []string seccompOnce.Do(func() { // Check if Seccomp is supported, via CONFIG_SECCOMP. if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { // Make sure the kernel has CONFIG_SECCOMP_FILTER. if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { seccompEnabled = true } } }) info.Seccomp = seccompEnabled return warnings }
applySeccompInfo checks if Seccomp is supported, via CONFIG_SECCOMP.
applySeccompInfo
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_linux.go
Apache-2.0
func New(quiet bool, options ...Opt) *SysInfo { sysInfo := &SysInfo{} return sysInfo }
New returns an empty SysInfo for non linux for now.
New
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_unix.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_unix.go
Apache-2.0
func New(quiet bool, options ...Opt) *SysInfo { sysInfo := &SysInfo{} return sysInfo }
New returns an empty SysInfo for windows for now.
New
go
balena-os/balena-engine
pkg/sysinfo/sysinfo_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo_windows.go
Apache-2.0
func numCPU() int { // Gets the affinity mask for a process: The very one invoking this function. pid := unix.Getpid() var mask unix.CPUSet err := unix.SchedGetaffinity(pid, &mask) if err != nil { return 0 } return mask.Count() }
numCPU queries the system for the count of threads available for use to this process. Issues two syscalls. Returns 0 on errors. Use |runtime.NumCPU| in that case.
numCPU
go
balena-os/balena-engine
pkg/sysinfo/numcpu_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/numcpu_linux.go
Apache-2.0
func NumCPU() int { if ncpu := numCPU(); ncpu > 0 { return ncpu } return runtime.NumCPU() }
NumCPU returns the number of CPUs which are currently online
NumCPU
go
balena-os/balena-engine
pkg/sysinfo/numcpu_linux.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/numcpu_linux.go
Apache-2.0
func (c cgroupCpusetInfo) IsCpusetCpusAvailable(provided string) (bool, error) { return isCpusetListAvailable(provided, c.Cpus) }
IsCpusetCpusAvailable returns `true` if the provided string set is contained in cgroup's cpuset.cpus set, `false` otherwise. If error is not nil a parsing error occurred.
IsCpusetCpusAvailable
go
balena-os/balena-engine
pkg/sysinfo/sysinfo.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo.go
Apache-2.0
func (c cgroupCpusetInfo) IsCpusetMemsAvailable(provided string) (bool, error) { return isCpusetListAvailable(provided, c.Mems) }
IsCpusetMemsAvailable returns `true` if the provided string set is contained in cgroup's cpuset.mems set, `false` otherwise. If error is not nil a parsing error occurred.
IsCpusetMemsAvailable
go
balena-os/balena-engine
pkg/sysinfo/sysinfo.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/sysinfo.go
Apache-2.0
func popcnt(x uint64) (n byte) { x -= (x >> 1) & 0x5555555555555555 x = (x>>2)&0x3333333333333333 + x&0x3333333333333333 x += x >> 4 x &= 0x0f0f0f0f0f0f0f0f x *= 0x0101010101010101 return byte(x >> 56) }
Returns bit count of 1, used by NumCPU
popcnt
go
balena-os/balena-engine
pkg/sysinfo/numcpu_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/numcpu_windows.go
Apache-2.0
func NumCPU() int { if ncpu := numCPU(); ncpu > 0 { return ncpu } return runtime.NumCPU() }
NumCPU returns the number of CPUs which are currently online
NumCPU
go
balena-os/balena-engine
pkg/sysinfo/numcpu_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/numcpu_windows.go
Apache-2.0
func NumCPU() int { return runtime.NumCPU() }
NumCPU returns the number of CPUs
NumCPU
go
balena-os/balena-engine
pkg/sysinfo/numcpu.go
https://github.com/balena-os/balena-engine/blob/master/pkg/sysinfo/numcpu.go
Apache-2.0
func NewMiddleware(names []string, pg plugingetter.PluginGetter) *Middleware { SetPluginGetter(pg) return &Middleware{ plugins: newPlugins(names), } }
NewMiddleware creates a new Middleware with a slice of plugins names.
NewMiddleware
go
balena-os/balena-engine
pkg/authorization/middleware.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/middleware.go
Apache-2.0
func (m *Middleware) SetPlugins(names []string) { m.mu.Lock() m.plugins = newPlugins(names) m.mu.Unlock() }
SetPlugins sets the plugin used for authorization
SetPlugins
go
balena-os/balena-engine
pkg/authorization/middleware.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/middleware.go
Apache-2.0
func (m *Middleware) RemovePlugin(name string) { m.mu.Lock() defer m.mu.Unlock() plugins := m.plugins[:0] for _, authPlugin := range m.plugins { if authPlugin.Name() != name { plugins = append(plugins, authPlugin) } } m.plugins = plugins }
RemovePlugin removes a single plugin from this authz middleware chain
RemovePlugin
go
balena-os/balena-engine
pkg/authorization/middleware.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/middleware.go
Apache-2.0
func (m *Middleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { plugins := m.getAuthzPlugins() if len(plugins) == 0 { return handler(ctx, w, r, vars) } user := "" userAuthNMethod := "" // Default authorization using existing TLS connection credentials // FIXME: Non trivial authorization mechanisms (such as advanced certificate validations, kerberos support // and ldap) will be extracted using AuthN feature, which is tracked under: // https://github.com/docker/docker/pull/20883 if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { user = r.TLS.PeerCertificates[0].Subject.CommonName userAuthNMethod = "TLS" } authCtx := NewCtx(plugins, user, userAuthNMethod, r.Method, r.RequestURI) if err := authCtx.AuthZRequest(w, r); err != nil { logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err) return err } rw := NewResponseModifier(w) var errD error if errD = handler(ctx, rw, r, vars); errD != nil { logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, errD) } // There's a chance that the authCtx.plugins was updated. One of the reasons // this can happen is when an authzplugin is disabled. plugins = m.getAuthzPlugins() if len(plugins) == 0 { logrus.Debug("There are no authz plugins in the chain") return nil } authCtx.plugins = plugins if err := authCtx.AuthZResponse(rw, r); errD == nil && err != nil { logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err) return err } if errD != nil { return errD } return nil } }
WrapHandler returns a new handler function wrapping the previous one in the request chain.
WrapHandler
go
balena-os/balena-engine
pkg/authorization/middleware.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/middleware.go
Apache-2.0
func NewResponseModifier(rw http.ResponseWriter) ResponseModifier { return &responseModifier{rw: rw, header: make(http.Header)} }
NewResponseModifier creates a wrapper to an http.ResponseWriter to allow inspecting and modifying the content
NewResponseModifier
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) WriteHeader(s int) { // Use original request if hijacked if rm.hijacked { rm.rw.WriteHeader(s) return } rm.statusCode = s }
WriterHeader stores the http status code
WriteHeader
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) Header() http.Header { // Use original header if hijacked if rm.hijacked { return rm.rw.Header() } return rm.header }
Header returns the internal http header
Header
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) StatusCode() int { return rm.statusCode }
StatusCode returns the http status code
StatusCode
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) OverrideBody(b []byte) { rm.body = b }
OverrideBody replaces the body of the HTTP response
OverrideBody
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) OverrideStatusCode(statusCode int) { rm.statusCode = statusCode }
OverrideStatusCode replaces the status code of the HTTP response
OverrideStatusCode
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) OverrideHeader(b []byte) error { header := http.Header{} if err := json.Unmarshal(b, &header); err != nil { return err } rm.header = header return nil }
OverrideHeader replaces the headers of the HTTP response
OverrideHeader
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) Write(b []byte) (int, error) { if rm.hijacked { return rm.rw.Write(b) } if len(rm.body)+len(b) > maxBufferSize { rm.Flush() } rm.body = append(rm.body, b...) return len(b), nil }
Write stores the byte array inside content
Write
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) RawBody() []byte { return rm.body }
Body returns the response body
RawBody
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) Hijack() (net.Conn, *bufio.ReadWriter, error) { rm.hijacked = true rm.FlushAll() hijacker, ok := rm.rw.(http.Hijacker) if !ok { return nil, nil, fmt.Errorf("Internal response writer doesn't support the Hijacker interface") } return hijacker.Hijack() }
Hijack returns the internal connection of the wrapped http.ResponseWriter
Hijack
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) Flush() { flusher, ok := rm.rw.(http.Flusher) if !ok { logrus.Error("Internal response writer doesn't support the Flusher interface") return } rm.FlushAll() flusher.Flush() }
Flush uses the internal flush API of the wrapped http.ResponseWriter
Flush
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func (rm *responseModifier) FlushAll() error { // Copy the header for k, vv := range rm.header { for _, v := range vv { rm.rw.Header().Add(k, v) } } // Copy the status code // Also WriteHeader needs to be done after all the headers // have been copied (above). if rm.statusCode > 0 { rm.rw.WriteHeader(rm.statusCode) } var err error if len(rm.body) > 0 { // Write body var n int n, err = rm.rw.Write(rm.body) // TODO(@cpuguy83): there is now a relatively small buffer limit, instead of discarding our buffer here and // allocating again later this should just keep using the same buffer and track the buffer position (like a bytes.Buffer with a fixed size) rm.body = rm.body[n:] } // Clean previous data rm.statusCode = 0 rm.header = http.Header{} return err }
FlushAll flushes all data to the HTTP response
FlushAll
go
balena-os/balena-engine
pkg/authorization/response.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/response.go
Apache-2.0
func newPlugins(names []string) []Plugin { plugins := []Plugin{} pluginsMap := make(map[string]struct{}) for _, name := range names { if _, ok := pluginsMap[name]; ok { continue } pluginsMap[name] = struct{}{} plugins = append(plugins, newAuthorizationPlugin(name)) } return plugins }
newPlugins constructs and initializes the authorization plugins based on plugin names
newPlugins
go
balena-os/balena-engine
pkg/authorization/plugin.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/plugin.go
Apache-2.0
func SetPluginGetter(pg plugingetter.PluginGetter) { getter = pg }
SetPluginGetter sets the plugingetter
SetPluginGetter
go
balena-os/balena-engine
pkg/authorization/plugin.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/plugin.go
Apache-2.0
func GetPluginGetter() plugingetter.PluginGetter { return getter }
GetPluginGetter gets the plugingetter
GetPluginGetter
go
balena-os/balena-engine
pkg/authorization/plugin.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/plugin.go
Apache-2.0
func (a *authorizationPlugin) SetName(remote string) { a.name = remote }
Set the remote for an authz pluginv2
SetName
go
balena-os/balena-engine
pkg/authorization/plugin.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/plugin.go
Apache-2.0
func (a *authorizationPlugin) initPlugin() error { // Lazy loading of plugins a.once.Do(func() { if a.plugin == nil { var plugin plugingetter.CompatPlugin var e error if pg := GetPluginGetter(); pg != nil { plugin, e = pg.Get(a.name, AuthZApiImplements, plugingetter.Lookup) a.SetName(plugin.Name()) } else { plugin, e = plugins.Get(a.name, AuthZApiImplements) } if e != nil { a.initErr = e return } a.plugin = plugin.Client() } }) return a.initErr }
initPlugin initializes the authorization plugin if needed
initPlugin
go
balena-os/balena-engine
pkg/authorization/plugin.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/plugin.go
Apache-2.0
func createTestPlugin(t *testing.T, socketAddress string) *authorizationPlugin { client, err := plugins.NewClient("unix:///"+socketAddress, &tlsconfig.Options{InsecureSkipVerify: true}) if err != nil { t.Fatalf("Failed to create client %v", err) } return &authorizationPlugin{name: "plugin", plugin: client} }
createTestPlugin creates a new sample authorization plugin
createTestPlugin
go
balena-os/balena-engine
pkg/authorization/authz_unix_test.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz_unix_test.go
Apache-2.0
func (t *authZPluginTestServer) start() { var err error t.tmpDir, err = ioutil.TempDir("", "authz") if err != nil { t.t.Fatal(err) } r := mux.NewRouter() l, err := net.Listen("unix", t.socketAddress()) if err != nil { t.t.Fatal(err) } t.listener = l r.HandleFunc("/Plugin.Activate", t.activate) r.HandleFunc("/"+AuthZApiRequest, t.auth) r.HandleFunc("/"+AuthZApiResponse, t.auth) t.server = &httptest.Server{ Listener: l, Config: &http.Server{ Handler: r, Addr: pluginAddress, }, } t.server.Start() }
start starts the test server that implements the plugin
start
go
balena-os/balena-engine
pkg/authorization/authz_unix_test.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz_unix_test.go
Apache-2.0
func (t *authZPluginTestServer) stop() { t.server.Close() _ = os.RemoveAll(t.tmpDir) if t.listener != nil { t.listener.Close() } }
stop stops the test server that implements the plugin
stop
go
balena-os/balena-engine
pkg/authorization/authz_unix_test.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz_unix_test.go
Apache-2.0
func (t *authZPluginTestServer) auth(w http.ResponseWriter, r *http.Request) { t.recordedRequest = Request{} body, err := ioutil.ReadAll(r.Body) if err != nil { t.t.Fatal(err) } r.Body.Close() json.Unmarshal(body, &t.recordedRequest) b, err := json.Marshal(t.replayResponse) if err != nil { t.t.Fatal(err) } w.Write(b) }
auth is a used to record/replay the authentication api messages
auth
go
balena-os/balena-engine
pkg/authorization/authz_unix_test.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz_unix_test.go
Apache-2.0
func (pc *PeerCertificate) MarshalJSON() ([]byte, error) { b := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pc.Raw}) return json.Marshal(b) }
MarshalJSON returns the JSON encoded pem bytes of a PeerCertificate.
MarshalJSON
go
balena-os/balena-engine
pkg/authorization/api.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/api.go
Apache-2.0
func (pc *PeerCertificate) UnmarshalJSON(b []byte) error { var buf []byte if err := json.Unmarshal(b, &buf); err != nil { return err } derBytes, _ := pem.Decode(buf) c, err := x509.ParseCertificate(derBytes.Bytes) if err != nil { return err } *pc = PeerCertificate(*c) return nil }
UnmarshalJSON populates a new PeerCertificate struct from JSON data.
UnmarshalJSON
go
balena-os/balena-engine
pkg/authorization/api.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/api.go
Apache-2.0
func NewCtx(authZPlugins []Plugin, user, userAuthNMethod, requestMethod, requestURI string) *Ctx { return &Ctx{ plugins: authZPlugins, user: user, userAuthNMethod: userAuthNMethod, requestMethod: requestMethod, requestURI: requestURI, } }
NewCtx creates new authZ context, it is used to store authorization information related to a specific docker REST http session A context provides two method: Authenticate Request: Call authZ plugins with current REST request and AuthN response Request contains full HTTP packet sent to the docker daemon https://docs.docker.com/engine/api/ Authenticate Response: Call authZ plugins with full info about current REST request, REST response and AuthN response The response from this method may contains content that overrides the daemon response This allows authZ plugins to filter privileged content If multiple authZ plugins are specified, the block/allow decision is based on ANDing all plugin results For response manipulation, the response from each plugin is piped between plugins. Plugin execution order is determined according to daemon parameters
NewCtx
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func (ctx *Ctx) AuthZRequest(w http.ResponseWriter, r *http.Request) error { var body []byte if sendBody(ctx.requestURI, r.Header) && r.ContentLength > 0 && r.ContentLength < maxBodySize { var err error body, r.Body, err = drainBody(r.Body) if err != nil { return err } } var h bytes.Buffer if err := r.Header.Write(&h); err != nil { return err } ctx.authReq = &Request{ User: ctx.user, UserAuthNMethod: ctx.userAuthNMethod, RequestMethod: ctx.requestMethod, RequestURI: ctx.requestURI, RequestBody: body, RequestHeaders: headers(r.Header), } if r.TLS != nil { for _, c := range r.TLS.PeerCertificates { pc := PeerCertificate(*c) ctx.authReq.RequestPeerCertificates = append(ctx.authReq.RequestPeerCertificates, &pc) } } for _, plugin := range ctx.plugins { logrus.Debugf("AuthZ request using plugin %s", plugin.Name()) authRes, err := plugin.AuthZRequest(ctx.authReq) if err != nil { return fmt.Errorf("plugin %s failed with error: %s", plugin.Name(), err) } if !authRes.Allow { return newAuthorizationError(plugin.Name(), authRes.Msg) } } return nil }
AuthZRequest authorized the request to the docker daemon using authZ plugins
AuthZRequest
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func (ctx *Ctx) AuthZResponse(rm ResponseModifier, r *http.Request) error { ctx.authReq.ResponseStatusCode = rm.StatusCode() ctx.authReq.ResponseHeaders = headers(rm.Header()) if sendBody(ctx.requestURI, rm.Header()) { ctx.authReq.ResponseBody = rm.RawBody() } for _, plugin := range ctx.plugins { logrus.Debugf("AuthZ response using plugin %s", plugin.Name()) authRes, err := plugin.AuthZResponse(ctx.authReq) if err != nil { return fmt.Errorf("plugin %s failed with error: %s", plugin.Name(), err) } if !authRes.Allow { return newAuthorizationError(plugin.Name(), authRes.Msg) } } rm.FlushAll() return nil }
AuthZResponse authorized and manipulates the response from docker daemon using authZ plugins
AuthZResponse
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func drainBody(body io.ReadCloser) ([]byte, io.ReadCloser, error) { bufReader := bufio.NewReaderSize(body, maxBodySize) newBody := ioutils.NewReadCloserWrapper(bufReader, func() error { return body.Close() }) data, err := bufReader.Peek(maxBodySize) // Body size exceeds max body size if err == nil { logrus.Warnf("Request body is larger than: '%d' skipping body", maxBodySize) return nil, newBody, nil } // Body size is less than maximum size if err == io.EOF { return data, newBody, nil } // Unknown error return nil, newBody, err }
drainBody dump the body (if its length is less than 1MB) without modifying the request state
drainBody
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func sendBody(url string, header http.Header) bool { // Skip body for auth endpoint if strings.HasSuffix(url, "/auth") { return false } // body is sent only for text or json messages contentType, _, err := mime.ParseMediaType(header.Get("Content-Type")) if err != nil { return false } return contentType == "application/json" }
sendBody returns true when request/response body should be sent to AuthZPlugin
sendBody
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func headers(header http.Header) map[string]string { v := make(map[string]string) for k, values := range header { // Skip authorization headers if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "X-Registry-Config") || strings.EqualFold(k, "X-Registry-Auth") { continue } for _, val := range values { v[k] = val } } return v }
headers returns flatten version of the http headers excluding authorization
headers
go
balena-os/balena-engine
pkg/authorization/authz.go
https://github.com/balena-os/balena-engine/blob/master/pkg/authorization/authz.go
Apache-2.0
func AttachLoopDevice(sparseName string) (loop *os.File, err error) { // Try to retrieve the next available loopback device via syscall. // If it fails, we discard error and start looping for a // loopback from index 0. startIndex, err := getNextFreeLoopbackIndex() if err != nil { logrus.Debugf("Error retrieving the next available loopback: %s", err) } // OpenFile adds O_CLOEXEC sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644) if err != nil { logrus.Errorf("Error opening sparse file %s: %s", sparseName, err) return nil, ErrAttachLoopbackDevice } defer sparseFile.Close() loopFile, err := openNextAvailableLoopback(startIndex, sparseFile) if err != nil { return nil, err } // Set the status of the loopback device loopInfo := &unix.LoopInfo64{ File_name: stringToLoopName(loopFile.Name()), Offset: 0, Flags: LoFlagsAutoClear, } if err := ioctlLoopSetStatus64(loopFile.Fd(), loopInfo); err != nil { logrus.Errorf("Cannot set up loopback device info: %s", err) // If the call failed, then free the loopback device if err := ioctlLoopClrFd(loopFile.Fd()); err != nil { logrus.Error("Error while cleaning up the loopback device") } loopFile.Close() return nil, ErrAttachLoopbackDevice } return loopFile, nil }
AttachLoopDevice attaches the given sparse file to the next available loopback device. It returns an opened *os.File.
AttachLoopDevice
go
balena-os/balena-engine
pkg/loopback/attach_loopback.go
https://github.com/balena-os/balena-engine/blob/master/pkg/loopback/attach_loopback.go
Apache-2.0
func SetCapacity(file *os.File) error { if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil { logrus.Errorf("Error loopbackSetCapacity: %s", err) return ErrSetCapacity } return nil }
SetCapacity reloads the size for the loopback device.
SetCapacity
go
balena-os/balena-engine
pkg/loopback/loopback.go
https://github.com/balena-os/balena-engine/blob/master/pkg/loopback/loopback.go
Apache-2.0
func FindLoopDeviceFor(file *os.File) *os.File { var stat unix.Stat_t err := unix.Stat(file.Name(), &stat) if err != nil { return nil } targetInode := stat.Ino // the type is 32bit on mips targetDevice := uint64(stat.Dev) // nolint: unconvert for i := 0; true; i++ { path := fmt.Sprintf("/dev/loop%d", i) file, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { if os.IsNotExist(err) { return nil } // Ignore all errors until the first not-exist // we want to continue looking for the file continue } dev, inode, err := getLoopbackBackingFile(file) if err == nil && dev == targetDevice && inode == targetInode { return file } file.Close() } return nil }
FindLoopDeviceFor returns a loopback device file for the specified file which is backing file of a loop back device.
FindLoopDeviceFor
go
balena-os/balena-engine
pkg/loopback/loopback.go
https://github.com/balena-os/balena-engine/blob/master/pkg/loopback/loopback.go
Apache-2.0
func runtimeArchitecture() (string, error) { utsname := &unix.Utsname{} if err := unix.Uname(utsname); err != nil { return "", err } return string(utsname.Machine[:bytes.IndexByte(utsname.Machine[:], 0)]), nil }
runtimeArchitecture gets the name of the current architecture (x86, x86_64, i86pc, sun4v, ...)
runtimeArchitecture
go
balena-os/balena-engine
pkg/platform/architecture_unix.go
https://github.com/balena-os/balena-engine/blob/master/pkg/platform/architecture_unix.go
Apache-2.0
func runtimeArchitecture() (string, error) { var sysinfo systeminfo syscall.Syscall(procGetSystemInfo.Addr(), 1, uintptr(unsafe.Pointer(&sysinfo)), 0, 0) switch sysinfo.wProcessorArchitecture { case ProcessorArchitecture64, ProcessorArchitectureIA64: return "x86_64", nil case ProcessorArchitecture32: return "i686", nil case ProcessorArchitectureArm: return "arm", nil default: return "", fmt.Errorf("Unknown processor architecture") } }
runtimeArchitecture gets the name of the current architecture (x86, x86_64, …)
runtimeArchitecture
go
balena-os/balena-engine
pkg/platform/architecture_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/platform/architecture_windows.go
Apache-2.0
func NumProcs() uint32 { var sysinfo systeminfo syscall.Syscall(procGetSystemInfo.Addr(), 1, uintptr(unsafe.Pointer(&sysinfo)), 0, 0) return sysinfo.dwNumberOfProcessors }
NumProcs returns the number of processors on the system
NumProcs
go
balena-os/balena-engine
pkg/platform/architecture_windows.go
https://github.com/balena-os/balena-engine/blob/master/pkg/platform/architecture_windows.go
Apache-2.0
func LogInit(logger DevmapperLogger) { dmLogger = logger }
LogInit changes the logging callback called after processing libdm logs for error message information. The default logger simply forwards all logs to logrus. Calling LogInit(nil) disables the calling of callbacks.
LogInit
go
balena-os/balena-engine
pkg/devicemapper/devmapper_log.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper_log.go
Apache-2.0
func DevmapperLogCallback(level C.int, file *C.char, line, dmErrnoOrClass C.int, message *C.char) { msg := C.GoString(message) // Track what errno libdm saw, because the library only gives us 0 or 1. if level < LogLevelDebug { if strings.Contains(msg, "busy") { dmSawBusy = true } if strings.Contains(msg, "File exists") { dmSawExist = true } if strings.Contains(msg, "No such device or address") { dmSawEnxio = true } if strings.Contains(msg, "No data available") { dmSawEnoData = true } } if dmLogger != nil { dmLogger.DMLog(int(level), C.GoString(file), int(line), int(dmErrnoOrClass), msg) } }
DevmapperLogCallback exports the devmapper log callback for cgo. Note that because we are using callbacks, this function will be called for *every* log in libdm (even debug ones because there's no way of setting the verbosity level for an external logging callback). export DevmapperLogCallback
DevmapperLogCallback
go
balena-os/balena-engine
pkg/devicemapper/devmapper_log.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper_log.go
Apache-2.0
func (l DefaultLogger) DMLog(level int, file string, line, dmError int, message string) { if level <= l.Level { // Forward the log to the correct logrus level, if allowed by dmLogLevel. logMsg := fmt.Sprintf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) switch level { case LogLevelFatal, LogLevelErr: logrus.Error(logMsg) case LogLevelWarn: logrus.Warn(logMsg) case LogLevelNotice, LogLevelInfo: logrus.Info(logMsg) case LogLevelDebug: logrus.Debug(logMsg) default: // Don't drop any "unknown" levels. logrus.Info(logMsg) } } }
DMLog is the logging callback containing all of the information from devicemapper. The interface is identical to the C libdm counterpart.
DMLog
go
balena-os/balena-engine
pkg/devicemapper/devmapper_log.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper_log.go
Apache-2.0
func registerLogCallback() { LogWithErrnoInit() }
registerLogCallback registers our own logging callback function for libdm (which is DevmapperLogCallback). Because libdm only gives us {0,1} error codes we need to parse the logs produced by libdm (to set dmSawBusy and so on). Note that by registering a callback using DevmapperLogCallback, libdm will no longer output logs to stderr so we have to log everything ourselves. None of this handling is optional because we depend on log callbacks to parse the logs, and if we don't forward the log information we'll be in a lot of trouble when debugging things.
registerLogCallback
go
balena-os/balena-engine
pkg/devicemapper/devmapper_log.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper_log.go
Apache-2.0
func DeviceIDExists(err error) bool { return fmt.Sprint(err) == fmt.Sprint(ErrDeviceIDExists) }
DeviceIDExists returns whether error conveys the information about device Id already exist or not. This will be true if device creation or snap creation operation fails if device or snap device already exists in pool. Current implementation is little crude as it scans the error string for exact pattern match. Replacing it with more robust implementation is desirable.
DeviceIDExists
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func TaskCreateNamed(t TaskType, name string) (*Task, error) { task := TaskCreate(t) if task == nil { return nil, fmt.Errorf("devicemapper: Can't create task of type %d", int(t)) } if err := task.setName(name); err != nil { return nil, fmt.Errorf("devicemapper: Can't set task name %s", name) } return task, nil }
TaskCreateNamed is a convenience function for TaskCreate when a name will be set on the task as well
TaskCreateNamed
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func TaskCreate(tasktype TaskType) *Task { Ctask := DmTaskCreate(int(tasktype)) if Ctask == nil { return nil } task := &Task{unmanaged: Ctask} runtime.SetFinalizer(task, (*Task).destroy) return task }
TaskCreate initializes a devicemapper task of tasktype
TaskCreate
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func UdevWait(cookie *uint) error { if res := DmUdevWait(*cookie); res != 1 { logrus.Debugf("devicemapper: Failed to wait on udev cookie %d, %d", *cookie, res) return ErrUdevWait } return nil }
UdevWait waits for any processes that are waiting for udev to complete the specified cookie.
UdevWait
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func SetDevDir(dir string) error { if res := DmSetDevDir(dir); res != 1 { logrus.Debug("devicemapper: Error dm_set_dev_dir") return ErrSetDevDir } return nil }
SetDevDir sets the dev folder for the device mapper library (usually /dev).
SetDevDir
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func GetLibraryVersion() (string, error) { var version string if res := DmGetLibraryVersion(&version); res != 1 { return "", ErrGetLibraryVersion } return version, nil }
GetLibraryVersion returns the device mapper library version.
GetLibraryVersion
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func UdevSyncSupported() bool { return DmUdevGetSyncSupport() != 0 }
UdevSyncSupported returns whether device-mapper is able to sync with udev This is essential otherwise race conditions can arise where both udev and device-mapper attempt to create and destroy devices.
UdevSyncSupported
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func UdevSetSyncSupport(enable bool) bool { if enable { DmUdevSetSyncSupport(1) } else { DmUdevSetSyncSupport(0) } return UdevSyncSupported() }
UdevSetSyncSupport allows setting whether the udev sync should be enabled. The return bool indicates the state of whether the sync is enabled.
UdevSetSyncSupport
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func CookieSupported() bool { return DmCookieSupported() != 0 }
CookieSupported returns whether the version of device-mapper supports the use of cookie's in the tasks. This is largely a lower level call that other functions use.
CookieSupported
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func RemoveDevice(name string) error { task, err := TaskCreateNamed(deviceRemove, name) if task == nil { return err } cookie := new(uint) if err := task.setCookie(cookie, 0); err != nil { return fmt.Errorf("devicemapper: Can not set cookie: %s", err) } defer UdevWait(cookie) dmSawBusy = false // reset before the task is run dmSawEnxio = false if err = task.run(); err != nil { if dmSawBusy { return ErrBusy } if dmSawEnxio { return ErrEnxio } return fmt.Errorf("devicemapper: Error running RemoveDevice %s", err) } return nil }
RemoveDevice is a useful helper for cleaning up a device.
RemoveDevice
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func RemoveDeviceDeferred(name string) error { logrus.Debugf("devicemapper: RemoveDeviceDeferred START(%s)", name) defer logrus.Debugf("devicemapper: RemoveDeviceDeferred END(%s)", name) task, err := TaskCreateNamed(deviceRemove, name) if task == nil { return err } if err := DmTaskDeferredRemove(task.unmanaged); err != 1 { return ErrTaskDeferredRemove } // set a task cookie and disable library fallback, or else libdevmapper will // disable udev dm rules and delete the symlink under /dev/mapper by itself, // even if the removal is deferred by the kernel. cookie := new(uint) flags := uint16(DmUdevDisableLibraryFallback) if err := task.setCookie(cookie, flags); err != nil { return fmt.Errorf("devicemapper: Can not set cookie: %s", err) } // libdevmapper and udev relies on System V semaphore for synchronization, // semaphores created in `task.setCookie` will be cleaned up in `UdevWait`. // So these two function call must come in pairs, otherwise semaphores will // be leaked, and the limit of number of semaphores defined in `/proc/sys/kernel/sem` // will be reached, which will eventually make all following calls to 'task.SetCookie' // fail. // this call will not wait for the deferred removal's final executing, since no // udev event will be generated, and the semaphore's value will not be incremented // by udev, what UdevWait is just cleaning up the semaphore. defer UdevWait(cookie) dmSawEnxio = false if err = task.run(); err != nil { if dmSawEnxio { return ErrEnxio } return fmt.Errorf("devicemapper: Error running RemoveDeviceDeferred %s", err) } return nil }
RemoveDeviceDeferred is a useful helper for cleaning up a device, but deferred.
RemoveDeviceDeferred
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0
func CancelDeferredRemove(deviceName string) error { task, err := TaskCreateNamed(deviceTargetMsg, deviceName) if task == nil { return err } if err := task.setSector(0); err != nil { return fmt.Errorf("devicemapper: Can't set sector %s", err) } if err := task.setMessage(fmt.Sprintf("@cancel_deferred_remove")); err != nil { return fmt.Errorf("devicemapper: Can't set message %s", err) } dmSawBusy = false dmSawEnxio = false if err := task.run(); err != nil { // A device might be being deleted already if dmSawBusy { return ErrBusy } else if dmSawEnxio { return ErrEnxio } return fmt.Errorf("devicemapper: Error running CancelDeferredRemove %s", err) } return nil }
CancelDeferredRemove cancels a deferred remove for a device.
CancelDeferredRemove
go
balena-os/balena-engine
pkg/devicemapper/devmapper.go
https://github.com/balena-os/balena-engine/blob/master/pkg/devicemapper/devmapper.go
Apache-2.0