platform

package
v0.0.0-...-2db35d6 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: MPL-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	/*
	   UtilityDir is an element of PATH that points to a directory where laitos bundled utility programs are stored. The
	   utility programs are not essential to most of laitos operations, however they come in handy in certain scenarios:
	   - statically linked "busybox" (maintenance daemon uses it to synchronise system clock)
	   - statically linked "toybox" (its rich set of utilities help with shell usage)
	*/
	UtilityDir = "/tmp/laitos-util"

	/*
	   CommonPATH is a PATH environment variable value that includes most common executable locations across Unix and Linux.
	   Be aware that, when laitos launches external programs they usually should inherit all of the environment variables from
	   parent process, which may include PATH. However, as an exception, AWS ElasticBeanstalk launches programs via a
	   "supervisord" that resets PATH variable to deliberately exclude sbin directories, therefore, it is often useful to use
	   this hard coded PATH value to launch programs.
	*/
	CommonPATH = UtilityDir + ":/opt/bin:/opt/sbin:/usr/local/bin:/usr/local/sbin:/usr/libexec:/usr/bin:/usr/sbin:/bin:/sbin"

	// CommonOSCmdTimeoutSec is the number of seconds to tolerate for running a wide range of system management utilities.
	CommonOSCmdTimeoutSec = 120
)
View Source
const (
	/*
		MaxExternalProgramOutputBytes is the maximum number of bytes (combined stdout and stderr) to keep for an
		external program for caller to retrieve.
	*/
	MaxExternalProgramOutputBytes = 1024 * 1024
)
View Source
const PowerShellInterpreterPath = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`

PowerShellInterpreterPath is the absolute path to PowerShell interpreter executable.

Variables

View Source
var (
	RegexVMRss          = regexp.MustCompile(`VmRSS:\s*(\d+)\s*kB`)        // Parse VmRss value from /proc/*/status line
	RegexMemAvailable   = regexp.MustCompile(`MemAvailable:\s*(\d+)\s*kB`) // Parse MemAvailable value from /proc/meminfo
	RegexMemTotal       = regexp.MustCompile(`MemTotal:\s*(\d+)\s*kB`)     // Parse MemTotal value from /proc/meminfo
	RegexMemFree        = regexp.MustCompile(`MemFree:\s*(\d+)\s*kB`)      // Parse MemFree value from /proc/meminfo
	RegexTotalUptimeSec = regexp.MustCompile(`(\d+).*`)                    // Parse uptime seconds from /proc/meminfo
)

Functions

func BlockUserLogin

func BlockUserLogin(userName string) (ok bool, out string)

BlockUserLogin uses many independent mechanisms to stop a user from logging into system.

func CopyNonEssentialUtilities

func CopyNonEssentialUtilities(logger *lalog.Logger)

CopyNonEssentialUtilities sets program environment PATH to a comprehensive list of common executable directories on popular OSes.

Then it copies non-essential utility programs (busybox, toybox, etc) from CWD into a temporary directory, the temporary directory is already among environment PATH.

This function may take couple of seconds to complete. Be aware that certain Linux distributions (e.g. that used by AWS ElasticBeanstalk) aggresively clears /tmp at regular interval, caller should consider invoking this function at a slow and regular interval.

func DisableInterferingResolved

func DisableInterferingResolved() (out string)

DisableInterferingResolved disables systemd-resolved service to prevent it from interfering with laitos DNS server daemon. Otherwise, systemd-resolved daemon listens on 127.0.0.53:53 and prevents laitos DNS server from listening on all network interfaces (0.0.0.0).

func DisableStopDaemon

func DisableStopDaemon(daemonNameNoSuffix string) (ok bool)

DisableStopDaemon disables a system service and prevent it from ever starting again.

func EnableStartDaemon

func EnableStartDaemon(daemonNameNoSuffix string) (ok bool)

EnableStartDaemon enables and starts a system service.

func FindNumInRegexGroup

func FindNumInRegexGroup(numRegex *regexp.Regexp, input string, groupNum int) int64

FindNumInRegexGroup uses the input regex to parse the string and then parses the decimal integer (up to 64-bit in size) specified in the group number. A gentle reminder - the entire match is at group number 0, and the first captured regex group is at number 1.

func GetDefaultShellInterpreter

func GetDefaultShellInterpreter() string

GetDefaultShellInterpreter returns absolute path to the default system shell interpreter. Returns "" if one cannot be found.

func GetLocalUserNames

func GetLocalUserNames() (ret map[string]bool)

GetLocalUserNames returns all user names from /etc/passwd (Unix-like) or local account names (Windows). It returns an empty map if the names cannot be retrieved.

func GetProgramMemoryUsageKB

func GetProgramMemoryUsageKB() int64

Return RSS memory usage of this process. Return 0 if the memory usage cannot be determined.

func GetRedactedEnviron

func GetRedactedEnviron() []string

GetRedactedEnviron returns the program's environment varibles in "Key=Value" string array similar to those returned by os.Environ. Sensitive environment variables that amy reveal API secrets or passwords will be present, though their values will be string "REDACTED".

func GetRootDiskUsageKB

func GetRootDiskUsageKB() (usedKB, freeKB, totalKB int64)

GetRootDiskUsageKB returns used and total space of the file system mounted on /. Returns 0 if they cannot be determined.

func GetSysctlInt

func GetSysctlInt(key string) (int64, error)

GetSysctlInt return integer value of a sysctl parameter corresponding to the input key.

func GetSysctlStr

func GetSysctlStr(key string) (string, error)

GetSysctlStr returns string value of a sysctl parameter corresponding to the input key.

func GetSystemLoad

func GetSystemLoad() string

Return system load information and number of processes from /proc/loadavg. Return empty string if IO error occurs.

func GetSystemMemoryUsageKB

func GetSystemMemoryUsageKB() (usedKB, totalKB int64)

Return operating system memory usage. Return 0 if the memory usage cannot be determined.

func GetSystemUptimeSec

func GetSystemUptimeSec() int64

Get system uptime in seconds. Return 0 if it cannot be determined.

func HostIsCircleCI

func HostIsCircleCI() bool

HostIsCircleCI returns true only if the host environment is on Circle CI.

func HostIsWSL

func HostIsWSL() bool

HostIsWSL returns true only if the runtime is Windows subsystem for Linux.

func HostIsWindows

func HostIsWindows() bool

HostIsWindows returns true only if the runtime is Windows native. It returns false in other cases, including Windows Subsystem For Linux.

func IncreaseSysctlInt

func IncreaseSysctlInt(key string, atLeast int64) (old int64, err error)

IncreaseSysctlInt increases sysctl parameter to the specified value. If value already exceeds, it is left untouched.

func InvokeProgram

func InvokeProgram(envVars []string, timeoutSec int, program string, args ...string) (string, error)

InvokeProgram starts an external executable with optional added environment variables, and kills it before reacing the maximum execution timeout to prevent a runaway. It returns stdout+stderr combined, the maximum size is capped to MaxExternalProgramOutputBytes.

func InvokeShell

func InvokeShell(timeoutSec int, interpreter string, content string) (out string, err error)

InvokeShell starts the shell interpreter and passes the script content to "-c" flag. Nearly all shell interpreters across Linux and Windows accept the "-c" convention. Return stdout+stderr combined, the maximum size is capped to MaxExternalProgramOutputBytes.

func IsMacOS

func IsMacOS() bool

IsMacOS returns true iff the host OS is running MacOS (darwin).

func KillProcess

func KillProcess(proc *os.Process) (success bool)

KillProcess kills the process and its child processes. The function gives the processes a second to clean up after themselves.

func LockMemory

func LockMemory()

LockMemory locks program memory to prevent swapping, protecting sensitive user data.

func SetSysctl

func SetSysctl(key, value string) (old string, err error)

SetSysctl writes a new value into sysctl parameter.

func SetTermEcho

func SetTermEcho(echo bool)

Enable or disable terminal echo.

func SetTimeZone

func SetTimeZone(zone string) error

SetTimeZone changes system time zone to the specified value, such as "UTC" or "Europe/Dublin".

func SkipIfWSL

func SkipIfWSL(t testingstub.T)

SkipIfWSL asks a test to be skipped if it is being run on Windows Subsystem For Linux.

func SkipIfWindows

func SkipIfWindows(t testingstub.T)

SkipIfWindows asks a test to be skipped if it is being run on Windows natively (not "subsystem for Linux").

func SkipTestIfCI

func SkipTestIfCI(t testingstub.T)

SkipTestIfCI asks a test to be skipped if it is being run on Circle CI.

func StartProgram

func StartProgram(envVars []string, timeoutSec int, stdout, stderr io.WriteCloser, start chan<- error, terminate <-chan struct{}, program string, args ...string) error

StartProgram starts an external process, with optionally added environment variables and timeout monitor. The function waits for the process to terminate, and then returns the error at termination (e.g. abnormal exit codde) if any.

func SwapOff

func SwapOff() error

SwapOff turns off all swap files and partitions for improved system confidentiality.

func Sync

func Sync()

Sync makes the sync syscall.

Types

type ExternalProcessStarter

type ExternalProcessStarter func([]string, int, io.WriteCloser, io.WriteCloser, chan<- error, <-chan struct{}, string, ...string) error

ExternalProcessStarter is the function signature for starting an external program.

type ProgramStatusSummary

type ProgramStatusSummary struct {
	PublicIP, HostName                         string
	ClockTime                                  time.Time
	SysUptime, ProgramUptime                   time.Duration
	SysTotalMemMB, SysUsedMemMB, ProgUsedMemMB int64
	DiskUsedMB, DiskFreeMB, DiskCapMB          int64
	SysLoad                                    string
	NumCPU, NumGoMaxProcs, NumGoroutines       int
	PID, PPID, UID, EUID, GID, EGID            int
	ExePath                                    string
	CLIFlags                                   []string
	WorkingDirPath                             string
	WorkingDirContent                          []string
	EnvironmentVars                            []string
}

ProgramStatusSummary describes the system resource usage and process environment of this instance of laitos program running live.

func GetProgramStatusSummary

func GetProgramStatusSummary(withPublicIP bool) ProgramStatusSummary

GetProgramStatusSummary returns a formatted human-readable text that describes key OS resource usage status and program environment.

func (*ProgramStatusSummary) DeserialiseFromJSON

func (summary *ProgramStatusSummary) DeserialiseFromJSON(jsonObj interface{}) error

DeserialiseFromJSON deserialises JSON properties from the input JSON object into this summary item. The primary use of this function is in test cases.

func (ProgramStatusSummary) String

func (summary ProgramStatusSummary) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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