platform

package module
v1.173.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 24 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved. * SPDX-License-Identifier: Apache-2.0

* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved. * SPDX-License-Identifier: Apache-2.0

* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved. * SPDX-License-Identifier: Apache-2.0

* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved. * SPDX-License-Identifier: Apache-2.0

* Copyright (C) 2020-2026 Arm Limited or its affiliates and Contributors. All rights reserved. * SPDX-License-Identifier: Apache-2.0

Index

Constants

View Source
const (
	// PathListSeparator corresponds to the platform separator used to separate element in PATH environment variable
	// i.e. this character is used to separate filenames in a sequence of files given as a path list.
	// On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';'.
	PathListSeparator rune = os.PathListSeparator
	// PathSeparator corresponds to the platform path separator as in the system-dependent default name-separator character.
	// On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\\'.
	PathSeparator rune = os.PathSeparator
)
View Source
const (
	RootGroup    = "root"
	SudoersGroup = "sudo"
)

Variables

View Source
var (

	// UnixVariableNameRegexString defines the schema for variable names on Unix.
	// See https://www.gnu.org/software/bash/manual/bash.html#index-name and https://mywiki.wooledge.org/BashFAQ/006
	UnixVariableNameRegexString = "^[a-zA-Z_][a-zA-Z_0-9]*$"
	// WindowsVariableNameRegexString defines the schema for variable names on Windows.
	// See https://ss64.com/nt/syntax-variables.html
	WindowsVariableNameRegexString = "^[A-Za-z#$'()*+,.?@\\[\\]_`{}~][A-Za-z0-9#$'()*+,.?@\\[\\]_`{}~\\s]*$"

	// IsWindowsVariableName defines a validation rule for variable names on Windows for use with github.com/go-ozzo/ozzo-validation
	IsWindowsVariableName = validation.NewStringRuleWithError(isWindowsVarName, errVariableNameInvalid)
	// IsUnixVariableName defines a validation rule for variable names on Unix for use with github.com/go-ozzo/ozzo-validation
	IsUnixVariableName = validation.NewStringRuleWithError(isUnixVarName, errVariableNameInvalid)
	// IsVariableName defines a validation rule for variable names for use with github.com/go-ozzo/ozzo-validation
	IsVariableName = validation.NewStringRuleWithError(isVarName, errVariableNameInvalid)
)

Functions

func AddGroup

func AddGroup(ctx context.Context, groupName string) error

AddGroup creates a group if not already existing.

func AddUser

func AddUser(ctx context.Context, username, fullname, password string) error

AddUser adds a new user to the platform

func AssociateUserToGroup

func AssociateUserToGroup(ctx context.Context, username, groupName string) error

AssociateUserToGroup adds a user to a group.

func BootTime

func BootTime() (bootime time.Time, err error)

BootTime returns system uptime.

func CanCurrentUserMutateUsers added in v1.172.0

func CanCurrentUserMutateUsers() (bool, error)

CanCurrentUserMutateUsers reports whether the current process has enough privileges and platform support to create, modify, and remove local users and groups.

func ConvertError

func ConvertError(err error) error

ConvertError converts a platform error into a commonerrors

func ConvertUserGroupError

func ConvertUserGroupError(err error) error

ConvertUserGroupError converts errors related to users in common errors.

func DefineSudoCommand

func DefineSudoCommand(args ...string)

DefineSudoCommand defines the command to run to be `root` or a user with enough privileges (superuser). e.g.

  • args="sudo" to run commands as `root`
  • args="su", "tom" if `tom` has enough privileges to run the command

func DefineUser

func DefineUser(ctx context.Context, user *user.User, password string) (err error)

DefineUser adds a new user to the platform

func DeleteUser

func DeleteUser(ctx context.Context, user *user.User) (err error)

DeleteUser removes a user from the platform when the user is specified using a `user.User` structure.

func DissociateUserFromGroup

func DissociateUserFromGroup(ctx context.Context, username, groupName string) error

DissociateUserFromGroup removes a user from a group.

func ExpandFromEnvironment

func ExpandFromEnvironment(s string, recursive bool) string

ExpandFromEnvironment expands a string containing variables with values from the environment. On unix, it is equivalent to os.ExpandEnv but differs on Windows due to the following issues: - https://learn.microsoft.com/en-gb/windows/win32/api/processenv/nf-processenv-expandenvironmentstringsa?redirectedfrom=MSDN - https://github.com/golang/go/issues/43763 - https://github.com/golang/go/issues/24848

func ExpandParameter

func ExpandParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string

ExpandParameter expands a variable expressed in a string `s` with its value returned by the mapping function. If the mapping function returns a string with variables, it will expand them too if recursive is set to true.

func ExpandUnixParameter

func ExpandUnixParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string

ExpandUnixParameter expands a ${param} or $param in `s` based on the mapping function See https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html os.Expand is used under the bonnet and so, only basic parameter substitution is performed. TODO if os.Expand is not good enough, consider using other libraries such as https://github.com/ganbarodigital/go_shellexpand or https://github.com/mvdan/sh

func ExpandWindowsParameter

func ExpandWindowsParameter(s string, mappingFunc func(string) (string, bool), recursive bool) string

ExpandWindowsParameter expands a %param% in `s` based on the mapping function See https://learn.microsoft.com/en-us/previous-versions/troubleshoot/winautomation/product-documentation/best-practices/variables/percentage-character-usage-in-notations https://devblogs.microsoft.com/oldnewthing/20060823-00/?p=29993 https://github.com/golang/go/issues/24848 WARNING: currently the function only works with one parameter substitution in `s`.

func GetCurrentUser

func GetCurrentUser() (currentUser *user.User, err error)

GetCurrentUser returns information about the current platform's user and expands its home directory.

func GetDefaultHomeDirectory

func GetDefaultHomeDirectory(username string) (string, error)

GetDefaultHomeDirectory returns the default home directory for a user based on the convention listed in https://en.wikipedia.org/wiki/Home_directory#Default_home_directory_per_operating_system

func GetHomeDirectory

func GetHomeDirectory(username string) (string, error)

GetHomeDirectory returns the home directory of a user.

func GetUser

func GetUser(username string) (auser *user.User, err error)

GetUser returns information about a user and expands its home directory.

func HasGroup

func HasGroup(groupName string) (found bool, err error)

HasGroup checks whether a group exists

func HasUser

func HasUser(username string) (found bool, err error)

HasUser checks whether a user exists

func Hostname

func Hostname() (string, error)

Hostname returns the hostname.

func IsAdmin

func IsAdmin(username string) (admin bool, err error)

IsAdmin states whether the user is a superuser or not.

func IsCurrentUserAnAdmin

func IsCurrentUserAnAdmin() (admin bool, err error)

IsCurrentUserAnAdmin states whether the current user is a superuser or not.

func IsCurrentWithRootPrivileges added in v1.172.0

func IsCurrentWithRootPrivileges() (bool, error)

IsCurrentWithRootPrivileges reports whether the current process is running with elevated privileges.

func IsUserAdmin

func IsUserAdmin(user *user.User) (admin bool, err error)

IsUserAdmin states whether the user is a superuser or not. Similar to IsAdmin but may use more checks.

func IsWindows

func IsWindows() bool

IsWindows checks whether we are running on Windows or not.

func LineSeparator

func LineSeparator() string

LineSeparator returns the line separator.

func NodeName

func NodeName() (nodename string, err error)

NodeName returns the system node name (equivalent to uname -n).

func PlatformInformation

func PlatformInformation() (information string, err error)

PlatformInformation returns the platform information (equivalent to uname -s).

func RemoveGroup

func RemoveGroup(ctx context.Context, groupName string) error

RemoveGroup removes a group from the platform

func RemoveUser

func RemoveUser(ctx context.Context, username string) error

RemoveUser removes a user from the platform when only the username is known.

func RemoveWithPrivileges

func RemoveWithPrivileges(ctx context.Context, path string) (err error)

RemoveWithPrivileges removes the file or directory at path using elevated privileges (equivalent to `sudo rm -rf <path>`). The call delegates removal to helper functions that execute the removal as a privileged user.

Behaviour

  • If path is empty, the function returns nil and does nothing.
  • The function performs a minimal sanitisation of path with filepath.Clean() to normalise separators and collapse `.`/`..` elements. This is intended to reduce accidental path traversal surprises but does not enforce any allow-listing or other policy.

Security notes

  • This function requires that the current process (or the actor used by WithPrivileges) has appropriate privileges to remove the target path.
  • It intentionally performs no access-control checks, host-level policy or allow-listing. Callers are responsible for ensuring that the supplied path is expected and authorised for privileged removal.
  • Static analysis tools (gosec) flag uses of os.Stat/os.Remove on externally-supplied paths as potential path-traversal vulnerabilities (G703). The function deliberately delegates responsibility for such validation to callers and therefore uses a targeted suppression with a clear justification below. If you prefer centralised validation, implement caller-side checks (for example: enforce base directory, enforce absolute paths, or test against an allow-list) prior to calling this function.

func SubstituteParameter

func SubstituteParameter(parameter ...string) string

SubstituteParameter performs parameter substitution on all platforms. - the first element is the parameter to substitute - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.

func SubstituteParameterUnix

func SubstituteParameterUnix(parameter ...string) string

SubstituteParameterUnix performs Unix parameter substitution: See https://tldp.org/LDP/abs/html/parameter-substitution.html - the first element is the parameter to substitute - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.

func SubstituteParameterWindows

func SubstituteParameterWindows(parameter ...string) string

SubstituteParameterWindows performs Windows parameter substitution: See https://ss64.com/nt/syntax-replace.html - the first element is the parameter to substitute - if find and replace is also wanted, pass the pattern and the replacement as following arguments in that order.

func SystemInformation

func SystemInformation() (information string, err error)

SystemInformation returns the system information (equivalent to uname -a)

func Uname

func Uname() (string, error)

func UnixLineSeparator

func UnixLineSeparator() string

UnixLineSeparator returns the line separator on Unix platform.

func UpTime

func UpTime() (uptime time.Duration, err error)

UpTime returns system uptime.

func WithPrivileges

func WithPrivileges(cmd *command.CommandAsDifferentUser) (cmdWithPrivileges *command.CommandAsDifferentUser)

WithPrivileges redefines a command so that it is run with elevated privileges. For instance, on Linux, if the current user has enough privileges, the command will be run as is. Otherwise, `sudo` will be used if defined as the sudo (See `DefineSudoCommand`). Similar scenario will happen on Windows, although the elevated command is defined using `DefineSudoCommand`.

Types

type RAM

type RAM interface {
	// GetTotal returns total amount of RAM on this system
	GetTotal() uint64
	// GetAvailable returns RAM available for programs to allocate
	GetAvailable() uint64
	// GetUsed returns RAM used by programs
	GetUsed() uint64
	// GetUsedPercent returns Percentage of RAM used by programs
	GetUsedPercent() float64
	// GetFree returns kernel's notion of free memory
	GetFree() uint64
}

func GetRAM

func GetRAM() (ram RAM, err error)

type VirtualMemory

type VirtualMemory struct {
	Total       uint64
	Available   uint64
	Used        uint64
	UsedPercent float64
	Free        uint64
}

func (*VirtualMemory) GetAvailable

func (m *VirtualMemory) GetAvailable() uint64

func (*VirtualMemory) GetFree

func (m *VirtualMemory) GetFree() uint64

func (*VirtualMemory) GetTotal

func (m *VirtualMemory) GetTotal() uint64

func (*VirtualMemory) GetUsed

func (m *VirtualMemory) GetUsed() uint64

func (*VirtualMemory) GetUsedPercent

func (m *VirtualMemory) GetUsedPercent() float64

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL