utils

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2025 License: AGPL-3.0 Imports: 30 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:                         false,
			WaitForUpdateCheck:            false,
			DisableViamServer:             false,
			DisableNetworkConfiguration:   false,
			DisableSystemConfiguration:    false,
			ViamServerStartTimeoutMinutes: Timeout(time.Minute * 10),
		},
		SystemConfiguration{
			LoggingJournaldSystemMaxUseMegabytes:  512,
			LoggingJournaldRuntimeMaxUseMegabytes: 512,
			OSAutoUpgradeType:                     "",
		},
		NetworkConfiguration{
			Manufacturer:                        "viam",
			Model:                               "custom",
			FragmentID:                          "",
			HotspotInterface:                    "",
			HotspotPrefix:                       "viam-setup",
			HotspotPassword:                     "viamsetup",
			DisableCaptivePortalRedirect:        false,
			TurnOnHotspotIfWifiHasNoInternet:    false,
			WifiPowerSave:                       nil,
			OfflineBeforeStartingHotspotMinutes: Timeout(time.Minute * 2),
			UserIdleMinutes:                     Timeout(time.Minute * 5),
			RetryConnectionTimeoutMinutes:       Timeout(time.Minute * 10),
			DeviceRebootAfterOfflineMinutes:     Timeout(0),
			HotspotSSID:                         "",
		},
		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"}
)

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) (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 SaveConfigToCache

func SaveConfigToCache(cfg AgentConfig) error

func SyncFS

func SyncFS(syncPath string) (errRet error)

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                         bool    `json:"debug,omitempty"`
	WaitForUpdateCheck            bool    `json:"wait_for_update_check,omitempty"`
	DisableViamServer             bool    `json:"disable_viam_server,omitempty"`
	DisableNetworkConfiguration   bool    `json:"disable_network_configuration,omitempty"`
	DisableSystemConfiguration    bool    `json:"disable_system_configuration,omitempty"`
	ViamServerStartTimeoutMinutes Timeout `json:"viam_server_start_timeout_minutes,omitempty"`
}

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, isError, uploadAll bool) *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 Manufacturer
	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 bool `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 bool `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 *bool `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"`
}

func LoadOldProvisioningConfig

func LoadOldProvisioningConfig() (*NetworkConfiguration, error)

type NetworkDefinition

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

	// name of interface, ex: "wlan0", "eth0", "enp14s0", etc.
	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 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"`

	// 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

Jump to

Keyboard shortcuts

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