utils

package
v0.21.2 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2025 License: AGPL-3.0 Imports: 38 Imported by: 0

Documentation

Overview

Package utils contains helper functions shared between the main agent and subsystems

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultConfiguration = AgentConfig{
		AdvancedSettings{
			Debug:                         Tribool(0),
			WaitForUpdateCheck:            Tribool(0),
			DisableViamServer:             Tribool(0),
			DisableNetworkConfiguration:   Tribool(0),
			DisableSystemConfiguration:    Tribool(0),
			ViamServerStartTimeoutMinutes: Timeout(time.Minute * 10),
			ViamServerExtraEnvVars:        nil,
		},
		SystemConfiguration{
			LoggingJournaldSystemMaxUseMegabytes:  512,
			LoggingJournaldRuntimeMaxUseMegabytes: 512,
			ForwardSystemLogs:                     "",
			OSAutoUpgradeType:                     "",
		},
		NetworkConfiguration{
			Manufacturer:                        "viam",
			Model:                               "custom",
			FragmentID:                          "",
			HotspotInterface:                    "",
			HotspotPrefix:                       "viam-setup",
			HotspotPassword:                     "viamsetup",
			DisableCaptivePortalRedirect:        Tribool(0),
			TurnOnHotspotIfWifiHasNoInternet:    Tribool(0),
			WifiPowerSave:                       Tribool(0),
			OfflineBeforeStartingHotspotMinutes: Timeout(time.Minute * 2),
			UserIdleMinutes:                     Timeout(time.Minute * 5),
			RetryConnectionTimeoutMinutes:       Timeout(time.Minute * 10),
			DeviceRebootAfterOfflineMinutes:     Timeout(0),
			HotspotSSID:                         "",
			DisableBTProvisioning:               Tribool(0),
			DisableWifiProvisioning:             Tribool(0),
			BluetoothTrustAll:                   Tribool(0),
		},
		AdditionalNetworks{},
	}

	// Can be overwritten via cli arguments.
	AppConfigFilePath     = "/etc/viam.json"
	DefaultsFilePath      = "/etc/viam-defaults.json"
	CLIDebug              = false
	CLIWaitForUpdateCheck = false
)
View Source
var (
	DefaultOldProvisioningConfig = OldProvisioningConfig{
		Manufacturer:                    "viam",
		Model:                           "custom",
		FragmentID:                      "",
		HotspotPrefix:                   "viam-setup",
		HotspotPassword:                 "viamsetup",
		DisableDNSRedirect:              false,
		RoamingMode:                     false,
		OfflineTimeout:                  Timeout(time.Minute * 2),
		UserTimeout:                     Timeout(time.Minute * 5),
		FallbackTimeout:                 Timeout(time.Minute * 10),
		WifiPowerSave:                   nil,
		DeviceRebootAfterOfflineMinutes: Timeout(0),
	}
	OldProvisioningConfigFilePath = "/etc/viam-provisioning.json"
)
View Source
var (
	// versions embedded at build time.
	Version     = ""
	GitRevision = ""

	ViamDirs = map[string]string{"viam": "/opt/viam"}

	HealthCheckTimeout = time.Minute
)

Functions

func CheckIfSame

func CheckIfSame(path1, path2 string) (bool, error)

func ConvertStruct

func ConvertStruct[T any](proto *structpb.Struct) (T, error)

func DecompressFile

func DecompressFile(inPath string) (outPath string, errRet error)

DecompressFile extracts a compressed file and returns the path to the extracted file.

func DownloadFile

func DownloadFile(ctx context.Context, rawURL string, logger logging.Logger) (outPath string, errRet error)

DownloadFile downloads a file into the cache directory and returns a path to the file.

func ForceSymlink(orig, symlink string) error

func FuzzTime

func FuzzTime(duration time.Duration, pct float64) time.Duration

func GetFileSum

func GetFileSum(filepath string) (outSum []byte, errRet error)

func GetRevision

func GetRevision() string

GetRevision returns the git revision embedded at build time.

func GetVersion

func GetVersion() string

GetVersion returns the version embedded at build time.

func InitPaths

func InitPaths() error

func KillTree added in v0.16.0

func KillTree(pid int) error

KillTree sends SIGKILL to the process group.

func MockViamDirs added in v0.17.0

func MockViamDirs(t *testing.T)

MockViamDirs replaces utils.ViamDirs entries with t.TempDir for duration of test.

func PlatformProcSettings added in v0.16.0

func PlatformProcSettings(cmd *exec.Cmd)

func Recover added in v0.17.0

func Recover(logger logging.Logger, inner func(r any))

func SaveConfigToCache

func SaveConfigToCache(cfg AgentConfig) error

func SignalForTermination added in v0.18.0

func SignalForTermination(pid int) error

func SyncFS

func SyncFS(syncPath string) (errRet error)

func Touch added in v0.17.0

func Touch(t *testing.T, path string)

Touch is equivalent to unix touch; creates an empty file at path.

func WriteFileIfNew

func WriteFileIfNew(outPath string, data []byte) (bool, error)

WriteFileIfNew returns true if contents changed and a write happened.

Types

type AdditionalNetworks

type AdditionalNetworks map[string]NetworkDefinition

type AdvancedSettings

type AdvancedSettings struct {
	Debug                         Tribool           `json:"debug,omitempty"`
	WaitForUpdateCheck            Tribool           `json:"wait_for_update_check,omitempty"`
	DisableViamServer             Tribool           `json:"disable_viam_server,omitempty"`
	DisableNetworkConfiguration   Tribool           `json:"disable_network_configuration,omitempty"`
	DisableSystemConfiguration    Tribool           `json:"disable_system_configuration,omitempty"`
	ViamServerStartTimeoutMinutes Timeout           `json:"viam_server_start_timeout_minutes,omitempty"`
	ViamServerExtraEnvVars        map[string]string `json:"viam_server_env,omitempty"`
}

func (AdvancedSettings) GetDisableNetworkConfiguration added in v0.16.0

func (as AdvancedSettings) GetDisableNetworkConfiguration() bool

GetDisableNetworkConfiguration is a wrapper which force-disables on some OSes.

func (AdvancedSettings) GetDisableSystemConfiguration added in v0.16.0

func (as AdvancedSettings) GetDisableSystemConfiguration() bool

GetDisableSystemConfiguration is a wrapper which force-disables on some OSes.

type AgentConfig

type AgentConfig struct {
	AdvancedSettings     AdvancedSettings     `json:"advanced_settings,omitempty"`
	SystemConfiguration  SystemConfiguration  `json:"system_configuration,omitempty"`
	NetworkConfiguration NetworkConfiguration `json:"network_configuration,omitempty"`
	AdditionalNetworks   AdditionalNetworks   `json:"additional_networks,omitempty"`
}

func ApplyCLIArgs

func ApplyCLIArgs(cfg AgentConfig) AgentConfig

func DefaultConfig

func DefaultConfig() AgentConfig

func LoadConfigFromCache

func LoadConfigFromCache() (AgentConfig, error)

func ProtoToConfig

func ProtoToConfig(proto *pb.DeviceAgentConfigResponse) (AgentConfig, error)

func StackConfigs

func StackConfigs(proto *pb.DeviceAgentConfigResponse) (AgentConfig, error)

type Health added in v0.17.0

type Health struct {
	Timeout time.Duration
	// contains filtered or unexported fields
}

func NewHealth added in v0.17.0

func NewHealth() *Health

func (*Health) IsHealthy added in v0.17.0

func (h *Health) IsHealthy() bool

func (*Health) MarkGood added in v0.17.0

func (h *Health) MarkGood()

func (*Health) Sleep added in v0.17.0

func (h *Health) Sleep(ctx context.Context, timeout time.Duration) bool

type MatchingLogger

type MatchingLogger struct {
	// contains filtered or unexported fields
}

MatchingLogger provides a logger that also allows sending regex matched lines to a channel.

func NewMatchingLogger

func NewMatchingLogger(logger logging.Logger, isError, uploadAll bool, unstructuredLoggerName string) *MatchingLogger

NewMatchingLogger returns a MatchingLogger.

func (*MatchingLogger) AddMatcher

func (l *MatchingLogger) AddMatcher(name string, regex *regexp.Regexp, mask bool) (<-chan []string, error)

AddMatcher adds a named regex to filter from results and return to a channel, optionally masking it from normal logging.

func (*MatchingLogger) DeleteMatcher

func (l *MatchingLogger) DeleteMatcher(name string)

DeleteMatcher removes a previously added matcher.

func (*MatchingLogger) Write

func (l *MatchingLogger) Write(p []byte) (int, error)

Write takes input and filters it against each defined matcher, before logging it.

type NetworkConfiguration

type NetworkConfiguration struct {
	// Things typically set in viam-defaults.json
	Manufacturer string `json:"manufacturer,omitempty"`
	Model        string `json:"model,omitempty"`
	FragmentID   string `json:"fragment_id,omitempty"`

	// The interface to use for hotspot/provisioning/wifi management. Ex: "wlan0"
	// Defaults to the first discovered 802.11 device
	HotspotInterface string `json:"hotspot_interface,omitempty"`
	// The prefix to prepend to the hotspot name.
	HotspotPrefix string `json:"hotspot_prefix,omitempty"`
	// Normally left blank, and computed from HotspotPrefix and Hostname
	HotspotSSID string `json:"hotspot_ssid,omitempty"`
	// Password required to connect to the hotspot.
	HotspotPassword string `json:"hotspot_password,omitempty"`
	// If true, mobile (phone) users connecting to the hotspot won't be automatically redirected to the web portal.
	DisableCaptivePortalRedirect Tribool `json:"disable_captive_portal_redirect,omitempty"`

	// When true, will try all known networks looking for internet (global) connectivity.
	// Otherwise, will only try the primary wifi network and consider that sufficient if connected (regardless of global connectivity.)
	TurnOnHotspotIfWifiHasNoInternet Tribool `json:"turn_on_hotspot_if_wifi_has_no_internet,omitempty"`

	// If set, will explicitly enable or disable power save for all wifi connections managed by NetworkManager.
	WifiPowerSave Tribool `json:"wifi_power_save,omitempty"`

	// How long without a connection before starting provisioning (hotspot) mode.
	OfflineBeforeStartingHotspotMinutes Timeout `json:"offline_before_starting_hotspot_minutes,omitempty"`

	// How long since the last user interaction (via GRPC/app or web portal) before the state machine can resume.
	UserIdleMinutes Timeout `json:"user_idle_minutes,omitempty"`

	// If not "online", always drop out of hotspot mode and retry everything after this time limit.
	RetryConnectionTimeoutMinutes Timeout `json:"retry_connection_timeout_minutes,omitempty"`

	// If set, will reboot the device after it has been offline for this duration
	// 0, default, will disable this feature.
	DeviceRebootAfterOfflineMinutes Timeout `json:"device_reboot_after_offline_minutes,omitempty"`

	// Disable flags for provisioning types.
	DisableBTProvisioning   Tribool `json:"disable_bt_provisioning,omitempty"`
	DisableWifiProvisioning Tribool `json:"disable_wifi_provisioning,omitempty"`

	// Accepts all BT pairing requests (for tethering) without requiring devices to be added via provisioning.
	BluetoothTrustAll Tribool `json:"bluetooth_trust_all,omitempty"`
}

func LoadOldProvisioningConfig

func LoadOldProvisioningConfig() (*NetworkConfiguration, error)

type NetworkDefinition

type NetworkDefinition struct {
	// "wifi", "wired", "bluetooth"
	Type string `json:"type,omitempty"`

	// name of interface, ex: "wlan0", "eth0", "enp14s0", etc.
	// for bluetooth tethering connections, uppercase hex, ex: "A1:B2:C3:11:22:3F"
	Interface string `json:"interface,omitempty"`

	// Wifi Settings
	SSID string `json:"ssid,omitempty"`
	PSK  string `json:"psk,omitempty"`

	// Autoconnect Priority (primarily for wifi)
	// higher values are preferred/tried first
	// defaults to 0, but wifi networks added via hotspot are set to 999 when not in roaming mode
	Priority int32 `json:"priority,omitempty"`

	// CIDR format address, ex: 192.168.0.1/24
	// If unset, will default to "auto" (dhcp)
	IPv4Address string `json:"ipv4_address,omitempty"`
	IPv4Gateway string `json:"ipv4_gateway,omitempty"`

	// optional
	IPv4DNS []string `json:"ipv4_dns,omitempty"`

	// optional, 0 or -1 is default
	// lower values are preferred (lower "cost")
	// wired networks default to 100
	// wireless networks default to 600
	IPv4RouteMetric int64 `json:"ipv4_route_metric,omitempty"`
}

type OldProvisioningConfig

type OldProvisioningConfig struct {
	// Things typically set in agent-provisioning.json
	Manufacturer string `json:"manufacturer"`
	Model        string `json:"model"`
	FragmentID   string `json:"fragment_id"`

	// The interface to use for hotspot/provisioning/wifi management. Ex: "wlan0"
	// Defaults to the first discovered 802.11 device
	HotspotInterface string `json:"hotspot_interface"`
	// The prefix to prepend to the hotspot name.
	HotspotPrefix string `json:"hotspot_prefix"`
	// Password required to connect to the hotspot.
	HotspotPassword string `json:"hotspot_password"`
	// If true, mobile (phone) users connecting to the hotspot won't be automatically redirected to the web portal.
	DisableDNSRedirect bool `json:"disable_dns_redirect"`

	// How long without a connection before starting provisioning (hotspot) mode.
	OfflineTimeout Timeout `json:"offline_timeout"`

	// How long since the last user interaction (via GRPC/app or web portal) before the state machine can resume.
	UserTimeout Timeout `json:"user_timeout"`

	// If not "online", always drop out of hotspot mode and retry everything after this time limit.
	FallbackTimeout Timeout `json:"fallback_timeout"`

	// When true, will try all known networks looking for internet (global) connectivity.
	// Otherwise, will only try the primary wifi network and consider that sufficient if connected (regardless of global connectivity.)
	RoamingMode bool `json:"roaming_mode"`

	// If set, will explicitly enable or disable power save for all wifi connections managed by NetworkManager.
	WifiPowerSave *bool `json:"wifi_power_save"`

	// If set, will reboot the device after it has been offline for this duration
	// 0, default, will disable this feature.
	DeviceRebootAfterOfflineMinutes Timeout `json:"device_reboot_after_offline_minutes"`
}

OldProvisioningConfig represents the json configurations parsed from either agent-provisioning.json.

type SafeBuffer added in v0.17.0

type SafeBuffer struct {
	// contains filtered or unexported fields
}

func (*SafeBuffer) Len added in v0.17.0

func (sb *SafeBuffer) Len() int

func (*SafeBuffer) Read added in v0.17.0

func (sb *SafeBuffer) Read(p []byte) (n int, err error)

func (*SafeBuffer) Reset added in v0.17.0

func (sb *SafeBuffer) Reset()

func (*SafeBuffer) String added in v0.17.0

func (sb *SafeBuffer) String() string

func (*SafeBuffer) Write added in v0.17.0

func (sb *SafeBuffer) Write(p []byte) (n int, err error)

type SystemConfiguration

type SystemConfiguration struct {
	// can set either to -1 to disable, defaults to 512M (when int is 0)
	LoggingJournaldSystemMaxUseMegabytes  int `json:"logging_journald_system_max_use_megabytes,omitempty"`
	LoggingJournaldRuntimeMaxUseMegabytes int `json:"logging_journald_runtime_max_use_megabytes,omitempty"`

	// Enable forwarding of system logs (journald) to the cloud (disabled by default)
	// A comma-separated list of SYSLOG_IDENTIFIERs, optionally prefixed with "-" to exclude
	// "all" is a special keyword to log everything
	// Ex: "kernel,tailscaled,NetworkManager" or "all,-gdm,-tailscaled"
	ForwardSystemLogs string `json:"forward_system_logs,omitempty"`

	// UpgradeType can be
	// Empty/missing ("") to make no changes
	// "disable" (or "disabled") to disable auto-upgrades
	// "security" to enable ONLY security upgrades
	// "all" to enable upgrades from all configured sources
	OSAutoUpgradeType string `json:"os_auto_upgrade_type,omitempty"`
}

type Timeout

type Timeout time.Duration

Timeout allows parsing golang-style durations (1h20m30s) OR minutes-as-float from/to json.

func (Timeout) MarshalJSON

func (t Timeout) MarshalJSON() ([]byte, error)

func (*Timeout) UnmarshalJSON

func (t *Timeout) UnmarshalJSON(b []byte) error

type Tribool added in v0.18.0

type Tribool int

func (Tribool) Get added in v0.18.0

func (b Tribool) Get() bool

func (Tribool) IsSet added in v0.18.0

func (b Tribool) IsSet() bool

func (Tribool) MarshalJSON added in v0.18.0

func (b Tribool) MarshalJSON() ([]byte, error)

func (*Tribool) UnmarshalJSON added in v0.18.0

func (b *Tribool) UnmarshalJSON(data []byte) error

Jump to

Keyboard shortcuts

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