Documentation
¶
Overview ¶
Package utils contains helper functions shared between the main agent and subsystems
Index ¶
- Variables
- func AtomicCopy(dst, src string) error
- func CheckIfSame(path1, path2 string) (bool, error)
- func ConvertStruct[T any](proto *structpb.Struct) (T, error)
- func CreatePartialPath(rawURL string) string
- func DecompressFile(inPath string) (outPath string, errRet error)
- func DownloadFile(ctx context.Context, rawURL string, logger logging.Logger) (string, error)
- func ForceSymlink(orig, symlink string) error
- func FuzzTime(duration time.Duration, pct float64) time.Duration
- func GetFileSum(filepath string) (outSum []byte, errRet error)
- func GetLastModified(ctx context.Context, rawURL string, logger logging.Logger) time.Time
- func GetRevision() string
- func GetVersion() string
- func GoArchToOSArch(goarch string) string
- func InitPaths() error
- func KillTree(pid int) error
- func MockAndCreateViamDirs(t *testing.T) string
- func MockBuildInfo(t *testing.T, version, revision string)
- func MockViamDirs(t *testing.T) string
- func PlatformProcSettings(cmd *exec.Cmd)
- func Recover(logger logging.Logger, inner func(r any))
- func SaveConfigToCache(cfg AgentConfig) error
- func SignalForTermination(pid int) error
- func SyncFS(syncPath string) (errRet error)
- func Touch(t *testing.T, path string)
- func WriteFileIfNew(outPath string, data []byte) (bool, error)
- type AdditionalNetworks
- type AdvancedSettings
- type AgentConfig
- type Health
- type MatchingLogger
- type NetworkConfiguration
- type NetworkDefinition
- type OldProvisioningConfig
- type SafeBuffer
- type SystemConfiguration
- type Timeout
- type Tribool
- type ViamDirsData
Constants ¶
This section is empty.
Variables ¶
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 )
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" )
var ( // versions embedded at build time. Version = "" GitRevision = "" ViamDirs ViamDirsData HealthCheckTimeout = time.Minute )
Functions ¶
func AtomicCopy ¶ added in v0.22.0
AtomicCopy implements a best effort to atomically copy the file at src to dst. It does this by copying first to a temporary file in the same directory as dst, then renaming that file to the final expected path.
func CheckIfSame ¶
CheckIfSame returns true if os.Samefile is true after EvalSymlinks.
func CreatePartialPath ¶ added in v0.23.0
CreatePartialPath makes a path under cachedir/part. These get cleaned up by CleanPartials.
func DecompressFile ¶
DecompressFile extracts a compressed file and returns the path to the extracted file.
func DownloadFile ¶
DownloadFile downloads or copies a file into the cache directory and returns a path to the file. If this is an http/s URL, you must check the checksum of the result; the partial logic does not check etags.
func ForceSymlink ¶
func GetFileSum ¶
func GetLastModified ¶ added in v0.23.1
GetLastModified retrieves the 'Last-Modified' header from a url via a HEAD request. If there is any issue (e.g. not present, retreiving, parsing), it will return a default time.Time{}.
func GetRevision ¶
func GetRevision() string
GetRevision returns the git revision embedded at build time.
func GoArchToOSArch ¶ added in v0.22.0
GoArchToOSArch translates CPU architecture IDs used by Go such as "arm64" to architucture IDs used by operating systems and their package managers, such as "aarch64". It returns an empty string for unknown architectures.
func MockAndCreateViamDirs ¶ added in v0.22.2
MockAndCreateViamDirs calls MockViamDirs, then creates all those directories. It returns the temporary directory that is the parent of the viam directory.
func MockBuildInfo ¶ added in v0.22.2
func MockViamDirs ¶ added in v0.17.0
MockViamDirs replaces utils.ViamDirs members with paths in t.TempDir for duration of test. It returns the temporary directory that is the parent of the viam directory.
func PlatformProcSettings ¶ added in v0.16.0
func SaveConfigToCache ¶
func SaveConfigToCache(cfg AgentConfig) error
func SignalForTermination ¶ added in v0.18.0
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 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, isStdOut 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.
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) Reset ¶ added in v0.17.0
func (sb *SafeBuffer) Reset()
func (*SafeBuffer) String ¶ added in v0.17.0
func (sb *SafeBuffer) String() string
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 ¶
Timeout allows parsing golang-style durations (1h20m30s) OR minutes-as-float from/to json.
func (Timeout) MarshalJSON ¶
func (*Timeout) UnmarshalJSON ¶
type Tribool ¶ added in v0.18.0
type Tribool int