utils

package
v0.0.0-...-1f91193 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: AGPL-3.0 Imports: 86 Imported by: 0

Documentation

Overview

Package utils provides common utility functions for the daemon.

Index

Constants

View Source
const (
	LLDAPPort   = 17170
	LLDAPServer = "lldap-service.os-platform.svc.cluster.local"

	Owner  string = "owner"
	Admin  string = "admin"
	Normal string = "normal"
)
View Source
const CHECK_CONNECTIVITY_URL = "http://connectivity-check.ubuntu.com/"
View Source
const (
	RoleOwner = "owner"
)

Variables

View Source
var (
	UserSchemeGroupVersion = schema.GroupVersion{Group: "iam.kubesphere.io", Version: "v1alpha2"}

	UserGVR = schema.GroupVersionResource{
		Group:    UserSchemeGroupVersion.Group,
		Version:  UserSchemeGroupVersion.Version,
		Resource: "users",
	}
)
View Source
var AllNetworkDeviceTraffic = make(map[string]*NetworkTrafficRate)

Functions

func AddMountRecord

func AddMountRecord(filePath string, record MountRecord) error

func BatchGenSharedAppEntranceURL

func BatchGenSharedAppEntranceURL(ctx context.Context, app *appv1alpha1.Application) ([]appcfg.Entrance, error)

func CheckInterfaceIPv4Connectivity

func CheckInterfaceIPv4Connectivity(ctx context.Context, interfaceName string) bool

func CheckInterfaceIPv6Connectivity

func CheckInterfaceIPv6Connectivity(ctx context.Context, interfaceName string) bool

func CheckOverlayGatewayStatus

func CheckOverlayGatewayStatus(ctx context.Context) error

func CheckSystemComponents

func CheckSystemComponents(ctx context.Context) error

CheckSystemComponents reports why the Olares system components are not ready, or nil when they all are.

func ConnectWifi

func ConnectWifi(ctx context.Context, ssid, password string) error

func CopyFile

func CopyFile(src, dst string) error

func CreateBridgeConnection

func CreateBridgeConnection(ctx context.Context) error

CreateBridgeConnection atomically switches the node's primary networking from the physical ethernet interface onto the br-olares bridge. It either fully succeeds (bridge active with an IPv4 address) or rolls back to the original physical connection and returns an error; it never leaves a half-bridged state or leftover/duplicate NetworkManager profiles behind.

func CreateTgzPackage

func CreateTgzPackage(sourceDir, tgzFilename string) error

func DetectdHddDevices

func DetectdHddDevices(ctx context.Context) (usbDevs []storageDevice, err error)

func DetectdUsbDevices

func DetectdUsbDevices(ctx context.Context) (usbDevs []storageDevice, err error)

func EnableWifi

func EnableWifi(ctx context.Context) error

func FilterArray

func FilterArray[T any](items []T, fn func(T) bool) []T

FilterArray returns a new slice containing only the items from the input slice for which the provided function returns true.

func FilterBySerial

func FilterBySerial(serial string) func(dev storageDevice) bool

func FindProcByName

func FindProcByName(ctx context.Context, name string) ([]*process.Process, error)

func ForceMountHdd

func ForceMountHdd(ctx context.Context)

func GetAdminUser

func GetAdminUser(ctx context.Context) (*unstructured.Unstructured, error)

func GetAdminUserJws

func GetAdminUserJws(ctx context.Context) (string, error)

func GetAdminUserTerminusName

func GetAdminUserTerminusName(ctx context.Context) (string, error)

func GetAllDevice

func GetAllDevice(ctx context.Context) (map[string]Device, error)

func GetApixClient

func GetApixClient() (apixclientset.Interface, error)

func GetAppClientSet

func GetAppClientSet() (versioned.Clientset, error)

func GetApplicationSettings

func GetApplicationSettings(ctx context.Context, appName, option string) (string, error)

func GetApplicationUrlAll

func GetApplicationUrlAll(ctx context.Context) ([]string, error)

func GetBaseDirFromReleaseFile

func GetBaseDirFromReleaseFile() (string, error)

func GetCPUName

func GetCPUName() string

GetCPUName returns the CPU brand name. The result is static for the lifetime of the process, so it is cached to avoid the lscpu/dmidecode fallbacks below running on every status tick. An empty result (e.g. a transient boot-time failure) is not cached, so a later tick can still populate it.

func GetClusterHttpClient

func GetClusterHttpClient() *http.Client

func GetConfig

func GetConfig() (*rest.Config, error)

GetConfig returns the cached rest.Config, loading it once on first success.

func GetDataFromReleaseFile

func GetDataFromReleaseFile() (map[string]string, error)

func GetDeviceName

func GetDeviceName() *string

func GetDiskAvailableSpace

func GetDiskAvailableSpace(path string) (uint64, error)

func GetDiskSize

func GetDiskSize() (uint64, error)

func GetDiskTotalBytesForPath

func GetDiskTotalBytesForPath(path string) (uint64, error)

Comprehensive: given a path (mount point or path), return the total bytes of the associated physical device

func GetDynamicClient

func GetDynamicClient() (dynamic.Interface, error)

func GetEthernetConnection

func GetEthernetConnection(ctx context.Context) (iface, ifUUID, connection string, err error)

get ethernet connection

func GetGpuInfo

func GetGpuInfo() ([]string, error)

GetGpuInfo returns descriptions for all detected GPUs. GPUs are not hot-plugged at runtime, but scanning the PCI bus via ghw on every status tick is expensive. A non-empty result is cached for the process lifetime; an empty scan is retried at most once per gpuEmptyRescanInterval, and a failed scan is retried on the next call. The returned slice is never nil.

func GetInterfaceTraffic

func GetInterfaceTraffic(iface string) (rxBytes, txBytes float64, err error)

func GetKubeClient

func GetKubeClient() (kubernetes.Interface, error)

func GetMasterNodeIpInCluster

func GetMasterNodeIpInCluster(ctx context.Context, client kubernetes.Interface) (string, error)

func GetMountedPoints

func GetMountedPoints(ctx context.Context) ([]string, error)

GetMountedPoints returns a list of currently mounted path strings.

func GetNodeFilesystemTotalSize

func GetNodeFilesystemTotalSize() (uint64, error)

func GetNodesPressure

func GetNodesPressure(ctx context.Context, client kubernetes.Interface) (map[string][]NodePressure, error)

func GetOlaresNameFromReleaseFile

func GetOlaresNameFromReleaseFile() (string, error)

func GetPodStatus

func GetPodStatus(pod *corev1.Pod) string

GetPodStatus returns a kubectl-like status string for a pod because the pod.Status.Phase field is unreliable

func GetSystemPendingShutdowm

func GetSystemPendingShutdowm() (mode string, shuttingdown bool, err error)

GetSystemPendingShutdowm reports whether the system is about to shut down or reboot, and in which mode ("reboot" or "shutdown").

Relying on /run/systemd/shutdown/scheduled alone is not enough: that file is only created by systemd-logind for *delayed* shutdowns (e.g. `shutdown +5`). Immediate commands such as `reboot`, `reboot now`, `poweroff` or `shutdown now` go straight through logind and never create it. Instead we query systemd over D-Bus, combining:

  1. logind's ScheduledShutdown property (timed shutdowns), and
  2. pending systemd jobs for the shutdown target units (immediate and in-progress shutdowns).

The legacy file-based check is kept as a fallback when D-Bus is unavailable.

func GetTerminusInfo

func GetTerminusInfo(ctx context.Context, client dynamic.Interface) (*sysv1.Terminus, error)

func GetTerminusInitializedTime

func GetTerminusInitializedTime(ctx context.Context, client kubernetes.Interface) (*int64, error)

func GetTerminusInstalledTime

func GetTerminusInstalledTime(ctx context.Context, client kubernetes.Interface) (*int64, error)

func GetTerminusVersion

func GetTerminusVersion(ctx context.Context, client dynamic.Interface) (*string, error)

func GetThisNodeName

func GetThisNodeName(ctx context.Context, client kubernetes.Interface) (nodeName, nodeIp, nodeRole string, err error)

func GetUserRole

func GetUserRole(ctx context.Context, username string, client dynamic.Interface) (string, error)

func GetUserspacePvcHostPath

func GetUserspacePvcHostPath(ctx context.Context, user string, client kubernetes.Interface) (string, error)

func GetWifiDevice

func GetWifiDevice(ctx context.Context) (map[string]Device, error)

func GetWorkloadNameFromPod

func GetWorkloadNameFromPod(pod *corev1.Pod) string

func InitInformers

func InitInformers(ctx context.Context)

InitInformers stores the lifecycle context for the shared informers. It should be called once at startup before the informers are used. The factories themselves are started lazily on first access, once the cluster is reachable.

func IsBrokenMount

func IsBrokenMount(path string) bool

func IsCifsInvalid

func IsCifsInvalid(mountPoint *mountutils.MountPoint) bool

func IsDarwin

func IsDarwin() bool

func IsDefaultSSHPassword

func IsDefaultSSHPassword() bool

func IsEmptyDir

func IsEmptyDir(name string) (bool, error)

func IsIpChanged

func IsIpChanged(ctx context.Context, installed bool) bool

func IsLinux

func IsLinux() bool

func IsManagedMount

func IsManagedMount(mountPath string) bool

func IsMasterNode

func IsMasterNode(n *corev1.Node) bool

func IsNfsInvalid

func IsNfsInvalid(mountPoint *mountutils.MountPoint) bool

func IsNodeReady

func IsNodeReady(n *corev1.Node) bool

func IsPodReady

func IsPodReady(pod *corev1.Pod) bool

IsPodReady checks if a pod is fully ready (all containers ready)

func IsTerminusInitialized

func IsTerminusInitialized(ctx context.Context, client dynamic.Interface) (initialized bool, failed bool, err error)

IsTerminusInitialized reports whether the owner user finished initialization. The client argument is retained for signature compatibility; user reads now go through the shared informer cache.

func IsTerminusInitializing

func IsTerminusInitializing(ctx context.Context) (bool, error)

func IsTerminusRunning

func IsTerminusRunning(ctx context.Context, client kubernetes.Interface) (bool, error)

IsTerminusRunning reports whether every Olares system component is ready, comparing the ready replicas of their Deployments, StatefulSets and DaemonSets against the desired ones. The client argument is retained for signature compatibility; reads go through the shared informer caches.

A component that is merely unready yields (false, nil). An error is only returned when the cluster cannot be read, which the caller treats as a harder failure than a component still coming up.

func IsValidDomain

func IsValidDomain(s string) bool

IsValidDomain reports whether s is a syntactically valid domain name.

func IsValidIP

func IsValidIP(s string) bool

IsValidIP reports whether s is a valid IPv4 or IPv6 address.

func IsWSL

func IsWSL() bool

func IsWindows

func IsWindows() bool

func ListApplications

func ListApplications(ctx context.Context) ([]*appv1alpha1.Application, error)

ListApplications returns all Application CRs. Objects served from the informer cache are read-only and shared, so callers that mutate must DeepCopy first.

func ListDaemonSets

func ListDaemonSets(ctx context.Context) ([]*appsv1.DaemonSet, error)

ListDaemonSets returns all daemonsets across namespaces, preferring the synced informer cache and falling back to a live List while warming up.

func ListDeployments

func ListDeployments(ctx context.Context) ([]*appsv1.Deployment, error)

ListDeployments returns all deployments across namespaces, preferring the synced informer cache and falling back to a live List while warming up.

func ListNamespaces

func ListNamespaces(ctx context.Context) ([]string, error)

ListNamespaces returns the names of all namespaces, preferring the synced informer cache and falling back to a live List while the cache is warming up.

func ListNfsDriver

func ListNfsDriver(ctx context.Context, nfsServer string) ([]nfsSharedPath, error)

func ListNodes

func ListNodes(ctx context.Context) ([]*corev1.Node, error)

ListNodes returns all nodes, preferring the synced informer cache and falling back to a live List while the cache is warming up.

func ListPods

func ListPods(ctx context.Context) ([]*corev1.Pod, error)

ListPods returns all pods across namespaces, preferring the synced informer cache and falling back to a live List while the cache is warming up (or when informers were never initialized, e.g. in tests).

Cache reads are eventually consistent and may lag the API server by a watch cycle; the live fallback only covers the not-yet-synced case, not a synced-but-stale cache.

func ListSambaSharenames

func ListSambaSharenames(ctx context.Context, server string, username string, password string) ([]string, error)

func ListStatefulSets

func ListStatefulSets(ctx context.Context) ([]*appsv1.StatefulSet, error)

ListStatefulSets returns all statefulsets across namespaces, preferring the synced informer cache and falling back to a live List while warming up.

func ListUsers

func ListUsers(ctx context.Context, filters ...Filter) ([]*unstructured.Unstructured, error)

ListUsers returns user CRs matching the given filters. The client argument is retained for signature compatibility; reads come from the shared informer cache. The returned objects are shared read-only cache references, so callers must DeepCopy before mutating.

func ListenNetworkCarrierChanges

func ListenNetworkCarrierChanges(ctx context.Context, downCallback func()) error

func ManagedAllDevices

func ManagedAllDevices(ctx context.Context) (map[string]Device, error)

func ManagedDeviceStatus

func ManagedDeviceStatus(ctx context.Context) (map[string]Device, error)

ManagedDeviceStatus enumerates network devices with a single `nmcli device status` call and, in the same pass, switches any unmanaged device to managed. It deliberately skips the per-device `nmcli device show` / `nmcli connection show` fan-out (i.e. it does not populate IP/gateway/DNS/ method fields), because the frequent state-polling path only needs Name/Type/State/Connection. This replaces the previous back-to-back ManagedAllDevices + GetAllDevice calls, which together spawned ~(4 + 8M) bash/nmcli processes per poll (M = device count) and kept NetworkManager busy.

func MaskFromCIDR

func MaskFromCIDR(bits int) (string, error)

func MasterNodeIp

func MasterNodeIp(installed bool) (addr string, err error)

func MonitorUsbDevice

func MonitorUsbDevice(ctx context.Context, cb func(action, serial string) error) error

func MountNfsDriver

func MountNfsDriver(ctx context.Context, mountBaseDir, mountPath string, nfsServer, nfsPath string) error

func MountSambaDriver

func MountSambaDriver(ctx context.Context, mountBaseDir string, smbPath string, user, pwd string) error

apt install cifs-utils

func MountUsbDevice

func MountUsbDevice(ctx context.Context, mountBaseDir string, dev []storageDevice) (mountedPath []string, err error)

func MountedHddPath

func MountedHddPath(ctx context.Context) ([]string, error)

func MountedPath

func MountedPath(ctx context.Context) ([]mountedPath, error)

func MountedSambaPath

func MountedSambaPath(ctx context.Context) ([]mountedPath, error)

func MountedUsbPath

func MountedUsbPath(ctx context.Context) ([]string, error)

func MoveFile

func MoveFile(sourcePath, destPath string) error

func NotifyBrokenMounts

func NotifyBrokenMounts(ctx context.Context)

func NotifyNetworkChanged

func NotifyNetworkChanged()

func ProcessExists

func ProcessExists(pid int) (bool, error)

func RegisterNetworkChangedNotify

func RegisterNetworkChangedNotify() func() bool

func RemoveMountRecord

func RemoveMountRecord(filePath string, mountPoint string) error

func ResetBridgeConnection

func ResetBridgeConnection(ctx context.Context) error

ResetBridgeConnection tears down the overlay bridge and restores the original physical connection. It operates by UUID so that duplicate/leftover profiles are fully cleaned up, leaving no residual br-olares* profiles behind.

func RestartOverlayGatewaySupportedApps

func RestartOverlayGatewaySupportedApps(ctx context.Context, apps []OverlayGatewaySupportedApp) error

func SetSSHPassword

func SetSSHPassword(user, password string) error

func SubpathOfMountedPath

func SubpathOfMountedPath(path string) func(mountedPath) bool

func SystemStartLessThan

func SystemStartLessThan(minute time.Duration) (bool, error)

func TokenVerify

func TokenVerify(baseURL, accessToken, validToken string) (map[string]interface{}, error)

func UmountNfsDriver

func UmountNfsDriver(ctx context.Context, mountDir string) error

func UmountOrRecordBrokenMounts

func UmountOrRecordBrokenMounts(ctx context.Context, baseDir string) error

func UmountSambaDriver

func UmountSambaDriver(ctx context.Context, mountDir string) error

func UmountUsbDevice

func UmountUsbDevice(ctx context.Context, path string) error

umount mount point if it's an usb device and remove the mount point path

func UpdateApplicationSettings

func UpdateApplicationSettings(ctx context.Context, appResourceName string, option string, value string) error

func UpdateNetworkTraffic

func UpdateNetworkTraffic(ctx context.Context)

func WifiName

func WifiName() *string

Types

type BridgeConnection

type BridgeConnection struct {
	BridgeName  string
	SlaveName   string
	Active      bool
	Ipv4Address string
}

func FindBridgeConnection

func FindBridgeConnection(ctx context.Context) (*BridgeConnection, error)

type Device

type Device struct {
	Name        string
	Type        string
	State       string
	Connection  string
	Ipv4Gateway string
	Ipv6Gateway string
	Ipv4DNS     string
	Ipv6DNS     string
	Ipv4Address string
	Ipv4Mask    string
	Ipv6Address string
	Method      string
}

type DeviceType

type DeviceType string
const (
	USB DeviceType = "usb"
	HDD DeviceType = "hdd"
	SMB DeviceType = "smb"
	NFS DeviceType = "nfs"
)

type FilesystemStat

type FilesystemStat struct {
	Device     string
	MountPoint string
	FSType     string
	SizeBytes  uint64
	FreeBytes  uint64
	AvailBytes uint64
	Files      uint64
	FilesFree  uint64
	ReadOnly   bool
}

FilesystemStat represents capacity and inode stats for a mounted filesystem.

func GetFilesystemStats

func GetFilesystemStats() ([]FilesystemStat, error)

GetFilesystemStats returns filesystem stats for all mounts, filtered by built-in regex patterns.

type Filter

type Filter func(u *unstructured.Unstructured) bool

type MountRecord

type MountRecord struct {
	Type       DeviceType `json:"type"`
	MountPoint string     `json:"mountPoint"`

	// SMB fields
	SmbPath  string `json:"smbPath,omitempty"`
	User     string `json:"user,omitempty"`
	Password string `json:"password,omitempty"`

	// NFS fields
	Server    string `json:"server,omitempty"`
	NfsPath   string `json:"nfsPath,omitempty"`
	MountName string `json:"mountName,omitempty"`
}

func LoadMountRecords

func LoadMountRecords(filePath string) ([]MountRecord, error)

type MountedPathDetail

type MountedPathDetail struct {
	disk.UsageStat `json:",inline"`
	Type           string `json:"type"`
	Invalid        bool   `json:"invalid"`
	IDSerial       string `json:"id_serial"`
	IDSerialShort  string `json:"id_serial_short"`
	PartitionUUID  string `json:"partition_uuid"`
	Device         string `json:"device"`
	ReadOnly       bool   `json:"read_only"`
}

func GetMountedPathDetail

func GetMountedPathDetail(ctx context.Context, mutate func(*disk.UsageStat) *disk.UsageStat) ([]*MountedPathDetail, error)

type NetworkTraffic

type NetworkTraffic struct {
	Interface string
	RxBytes   uint64
	TxBytes   uint64
}

type NetworkTrafficRate

type NetworkTrafficRate struct {
	Interface  string
	RxBytes    uint64
	TxBytes    uint64
	RxRate     float64
	TxRate     float64
	UpdateTime time.Time
}

type NodePressure

type NodePressure = clistate.NodePressure

NodePressure is a daemon-local alias of the canonical wire type shared with the olares-cli module. The Type field is plain string rather than corev1.NodeConditionType because the JSON wire format uses a string anyway and the cli module avoids depending on k8s.io/api/core/v1.

type OverlayGatewaySupportedApp

type OverlayGatewaySupportedApp struct {
	AppResourceName  string            `json:"app_resource_name"`
	AppName          string            `json:"app_name"`
	Enabled          bool              `json:"enabled"`
	Owner            string            `json:"owner"`
	SharedApp        bool              `json:"shared_app"`
	Namespace        string            `json:"namespace"`
	AppID            string            `json:"app_id"`
	UnderlayNetworks []UnderlayNetwork `json:"underlay_networks"`
}

func GetOverlayGatewaySupportedApps

func GetOverlayGatewaySupportedApps(ctx context.Context, user string) ([]OverlayGatewaySupportedApp, error)

type SignedRequest

type SignedRequest struct {
	OlaresID string
	Body     any
}

SignedRequest is a verified JWS: who signed it, and what their key covered.

Body matters as much as OlaresID. A route that reads only the identity treats every signature as a bearer credential for everything that identity may do; the body is where a caller says which single operation it signed for, so a dangerous route can insist on being named.

func ValidateJWSDetail

func ValidateJWSDetail(token string) (SignedRequest, error)

ValidateJWSDetail verifies a JWS and reports both who signed it and what their key covered.

type UnderlayNetwork

type UnderlayNetwork struct {
	IP    string                     `json:"ip"`
	Ports []manifest.OverlayEntrance `json:"ports"`
}

type ValidToken

type ValidToken struct {
	Username string
	Groups   []string
}

func AccessTokenValidate

func AccessTokenValidate(token string) (valid bool, tokenData *ValidToken, err error)

func (*ValidToken) IsAdmin

func (t *ValidToken) IsAdmin() bool

func (*ValidToken) IsOwner

func (t *ValidToken) IsOwner() bool

Jump to

Keyboard shortcuts

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