Documentation
¶
Overview ¶
Package utils provides common utility functions for the daemon.
Index ¶
- Constants
- Variables
- func AddMountRecord(filePath string, record MountRecord) error
- func BatchGenSharedAppEntranceURL(ctx context.Context, app *appv1alpha1.Application) ([]appcfg.Entrance, error)
- func CheckInterfaceIPv4Connectivity(ctx context.Context, interfaceName string) bool
- func CheckInterfaceIPv6Connectivity(ctx context.Context, interfaceName string) bool
- func CheckOverlayGatewayStatus(ctx context.Context) error
- func CheckSystemComponents(ctx context.Context) error
- func ConnectWifi(ctx context.Context, ssid, password string) error
- func CopyFile(src, dst string) error
- func CreateBridgeConnection(ctx context.Context) error
- func CreateTgzPackage(sourceDir, tgzFilename string) error
- func DetectdHddDevices(ctx context.Context) (usbDevs []storageDevice, err error)
- func DetectdUsbDevices(ctx context.Context) (usbDevs []storageDevice, err error)
- func EnableWifi(ctx context.Context) error
- func FilterArray[T any](items []T, fn func(T) bool) []T
- func FilterBySerial(serial string) func(dev storageDevice) bool
- func FindProcByName(ctx context.Context, name string) ([]*process.Process, error)
- func ForceMountHdd(ctx context.Context)
- func GetAdminUser(ctx context.Context) (*unstructured.Unstructured, error)
- func GetAdminUserJws(ctx context.Context) (string, error)
- func GetAdminUserTerminusName(ctx context.Context) (string, error)
- func GetAllDevice(ctx context.Context) (map[string]Device, error)
- func GetApixClient() (apixclientset.Interface, error)
- func GetAppClientSet() (versioned.Clientset, error)
- func GetApplicationSettings(ctx context.Context, appName, option string) (string, error)
- func GetApplicationUrlAll(ctx context.Context) ([]string, error)
- func GetBaseDirFromReleaseFile() (string, error)
- func GetCPUName() string
- func GetClusterHttpClient() *http.Client
- func GetConfig() (*rest.Config, error)
- func GetDataFromReleaseFile() (map[string]string, error)
- func GetDeviceName() *string
- func GetDiskAvailableSpace(path string) (uint64, error)
- func GetDiskSize() (uint64, error)
- func GetDiskTotalBytesForPath(path string) (uint64, error)
- func GetDynamicClient() (dynamic.Interface, error)
- func GetEthernetConnection(ctx context.Context) (iface, ifUUID, connection string, err error)
- func GetGpuInfo() ([]string, error)
- func GetInterfaceTraffic(iface string) (rxBytes, txBytes float64, err error)
- func GetKubeClient() (kubernetes.Interface, error)
- func GetMasterNodeIpInCluster(ctx context.Context, client kubernetes.Interface) (string, error)
- func GetMountedPoints(ctx context.Context) ([]string, error)
- func GetNodeFilesystemTotalSize() (uint64, error)
- func GetNodesPressure(ctx context.Context, client kubernetes.Interface) (map[string][]NodePressure, error)
- func GetOlaresNameFromReleaseFile() (string, error)
- func GetPodStatus(pod *corev1.Pod) string
- func GetSystemPendingShutdowm() (mode string, shuttingdown bool, err error)
- func GetTerminusInfo(ctx context.Context, client dynamic.Interface) (*sysv1.Terminus, error)
- func GetTerminusInitializedTime(ctx context.Context, client kubernetes.Interface) (*int64, error)
- func GetTerminusInstalledTime(ctx context.Context, client kubernetes.Interface) (*int64, error)
- func GetTerminusVersion(ctx context.Context, client dynamic.Interface) (*string, error)
- func GetThisNodeName(ctx context.Context, client kubernetes.Interface) (nodeName, nodeIp, nodeRole string, err error)
- func GetUserRole(ctx context.Context, username string, client dynamic.Interface) (string, error)
- func GetUserspacePvcHostPath(ctx context.Context, user string, client kubernetes.Interface) (string, error)
- func GetWifiDevice(ctx context.Context) (map[string]Device, error)
- func GetWorkloadNameFromPod(pod *corev1.Pod) string
- func InitInformers(ctx context.Context)
- func IsBrokenMount(path string) bool
- func IsCifsInvalid(mountPoint *mountutils.MountPoint) bool
- func IsDarwin() bool
- func IsDefaultSSHPassword() bool
- func IsEmptyDir(name string) (bool, error)
- func IsIpChanged(ctx context.Context, installed bool) bool
- func IsLinux() bool
- func IsManagedMount(mountPath string) bool
- func IsMasterNode(n *corev1.Node) bool
- func IsNfsInvalid(mountPoint *mountutils.MountPoint) bool
- func IsNodeReady(n *corev1.Node) bool
- func IsPodReady(pod *corev1.Pod) bool
- func IsTerminusInitialized(ctx context.Context, client dynamic.Interface) (initialized bool, failed bool, err error)
- func IsTerminusInitializing(ctx context.Context) (bool, error)
- func IsTerminusRunning(ctx context.Context, client kubernetes.Interface) (bool, error)
- func IsValidDomain(s string) bool
- func IsValidIP(s string) bool
- func IsWSL() bool
- func IsWindows() bool
- func ListApplications(ctx context.Context) ([]*appv1alpha1.Application, error)
- func ListDaemonSets(ctx context.Context) ([]*appsv1.DaemonSet, error)
- func ListDeployments(ctx context.Context) ([]*appsv1.Deployment, error)
- func ListNamespaces(ctx context.Context) ([]string, error)
- func ListNfsDriver(ctx context.Context, nfsServer string) ([]nfsSharedPath, error)
- func ListNodes(ctx context.Context) ([]*corev1.Node, error)
- func ListPods(ctx context.Context) ([]*corev1.Pod, error)
- func ListSambaSharenames(ctx context.Context, server string, username string, password string) ([]string, error)
- func ListStatefulSets(ctx context.Context) ([]*appsv1.StatefulSet, error)
- func ListUsers(ctx context.Context, filters ...Filter) ([]*unstructured.Unstructured, error)
- func ListenNetworkCarrierChanges(ctx context.Context, downCallback func()) error
- func ManagedAllDevices(ctx context.Context) (map[string]Device, error)
- func ManagedDeviceStatus(ctx context.Context) (map[string]Device, error)
- func MaskFromCIDR(bits int) (string, error)
- func MasterNodeIp(installed bool) (addr string, err error)
- func MonitorUsbDevice(ctx context.Context, cb func(action, serial string) error) error
- func MountNfsDriver(ctx context.Context, mountBaseDir, mountPath string, nfsServer, nfsPath string) error
- func MountSambaDriver(ctx context.Context, mountBaseDir string, smbPath string, user, pwd string) error
- func MountUsbDevice(ctx context.Context, mountBaseDir string, dev []storageDevice) (mountedPath []string, err error)
- func MountedHddPath(ctx context.Context) ([]string, error)
- func MountedPath(ctx context.Context) ([]mountedPath, error)
- func MountedSambaPath(ctx context.Context) ([]mountedPath, error)
- func MountedUsbPath(ctx context.Context) ([]string, error)
- func MoveFile(sourcePath, destPath string) error
- func NotifyBrokenMounts(ctx context.Context)
- func NotifyNetworkChanged()
- func ProcessExists(pid int) (bool, error)
- func RegisterNetworkChangedNotify() func() bool
- func RemoveMountRecord(filePath string, mountPoint string) error
- func ResetBridgeConnection(ctx context.Context) error
- func RestartOverlayGatewaySupportedApps(ctx context.Context, apps []OverlayGatewaySupportedApp) error
- func SetSSHPassword(user, password string) error
- func SubpathOfMountedPath(path string) func(mountedPath) bool
- func SystemStartLessThan(minute time.Duration) (bool, error)
- func TokenVerify(baseURL, accessToken, validToken string) (map[string]interface{}, error)
- func UmountNfsDriver(ctx context.Context, mountDir string) error
- func UmountOrRecordBrokenMounts(ctx context.Context, baseDir string) error
- func UmountSambaDriver(ctx context.Context, mountDir string) error
- func UmountUsbDevice(ctx context.Context, path string) error
- func UpdateApplicationSettings(ctx context.Context, appResourceName string, option string, value string) error
- func UpdateNetworkTraffic(ctx context.Context)
- func WifiName() *string
- type BridgeConnection
- type Device
- type DeviceType
- type FilesystemStat
- type Filter
- type MountRecord
- type MountedPathDetail
- type NetworkTraffic
- type NetworkTrafficRate
- type NodePressure
- type OverlayGatewaySupportedApp
- type SignedRequest
- type UnderlayNetwork
- type ValidToken
Constants ¶
const ( LLDAPPort = 17170 LLDAPServer = "lldap-service.os-platform.svc.cluster.local" Owner string = "owner" Admin string = "admin" Normal string = "normal" )
const CHECK_CONNECTIVITY_URL = "http://connectivity-check.ubuntu.com/"
const (
RoleOwner = "owner"
)
Variables ¶
var ( UserSchemeGroupVersion = schema.GroupVersion{Group: "iam.kubesphere.io", Version: "v1alpha2"} UserGVR = schema.GroupVersionResource{ Group: UserSchemeGroupVersion.Group, Version: UserSchemeGroupVersion.Version, Resource: "users", } )
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 CheckSystemComponents ¶
CheckSystemComponents reports why the Olares system components are not ready, or nil when they all are.
func CreateBridgeConnection ¶
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 DetectdHddDevices ¶
func DetectdUsbDevices ¶
func EnableWifi ¶
func FilterArray ¶
FilterArray returns a new slice containing only the items from the input slice for which the provided function returns true.
func FilterBySerial ¶
func FindProcByName ¶
func ForceMountHdd ¶
func GetAdminUser ¶
func GetAdminUser(ctx context.Context) (*unstructured.Unstructured, error)
func GetApixClient ¶
func GetApixClient() (apixclientset.Interface, error)
func GetAppClientSet ¶
func GetApplicationSettings ¶
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 GetDataFromReleaseFile ¶
func GetDeviceName ¶
func GetDeviceName() *string
func GetDiskAvailableSpace ¶
func GetDiskSize ¶
func GetDiskTotalBytesForPath ¶
Comprehensive: given a path (mount point or path), return the total bytes of the associated physical device
func GetDynamicClient ¶
func GetEthernetConnection ¶
get ethernet connection
func GetGpuInfo ¶
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 GetKubeClient ¶
func GetKubeClient() (kubernetes.Interface, error)
func GetMountedPoints ¶
GetMountedPoints returns a list of currently mounted path strings.
func GetNodesPressure ¶
func GetNodesPressure(ctx context.Context, client kubernetes.Interface) (map[string][]NodePressure, error)
func GetPodStatus ¶
GetPodStatus returns a kubectl-like status string for a pod because the pod.Status.Phase field is unreliable
func GetSystemPendingShutdowm ¶
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:
- logind's ScheduledShutdown property (timed shutdowns), and
- 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 GetTerminusVersion ¶
func GetThisNodeName ¶
func GetUserRole ¶
func GetUserspacePvcHostPath ¶
func GetWorkloadNameFromPod ¶
func InitInformers ¶
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 IsCifsInvalid ¶
func IsCifsInvalid(mountPoint *mountutils.MountPoint) bool
func IsDefaultSSHPassword ¶
func IsDefaultSSHPassword() bool
func IsEmptyDir ¶
func IsManagedMount ¶
func IsMasterNode ¶
func IsNfsInvalid ¶
func IsNfsInvalid(mountPoint *mountutils.MountPoint) bool
func IsNodeReady ¶
func IsPodReady ¶
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 IsTerminusRunning ¶
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 ¶
IsValidDomain reports whether s is a syntactically valid domain name.
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 ¶
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 ¶
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 ListNodes ¶
ListNodes returns all nodes, preferring the synced informer cache and falling back to a live List while the cache is warming up.
func ListPods ¶
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 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 ManagedDeviceStatus ¶
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 MasterNodeIp ¶
func MonitorUsbDevice ¶
func MountNfsDriver ¶
func MountSambaDriver ¶
func MountSambaDriver(ctx context.Context, mountBaseDir string, smbPath string, user, pwd string) error
apt install cifs-utils
func MountUsbDevice ¶
func MountedPath ¶
func MountedSambaPath ¶
func NotifyBrokenMounts ¶
func NotifyNetworkChanged ¶
func NotifyNetworkChanged()
func ProcessExists ¶
func RegisterNetworkChangedNotify ¶
func RegisterNetworkChangedNotify() func() bool
func RemoveMountRecord ¶
func ResetBridgeConnection ¶
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 SubpathOfMountedPath ¶
func TokenVerify ¶
func UmountUsbDevice ¶
umount mount point if it's an usb device and remove the mount point path
func UpdateNetworkTraffic ¶
Types ¶
type BridgeConnection ¶
func FindBridgeConnection ¶
func FindBridgeConnection(ctx context.Context) (*BridgeConnection, error)
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 ¶
type NetworkTraffic ¶
type NetworkTrafficRate ¶
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"`
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 ¶
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 ¶
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
Source Files
¶
- cluster_api.go
- disk.go
- drivers.go
- drivers_linux.go
- drivers_types.go
- filesystem.go
- fs.go
- gpu_info.go
- gpu_linux.go
- informers.go
- jws.go
- k8s.go
- k8s_types.go
- mount_store.go
- network_common.go
- network_linux.go
- network_types.go
- nm_checkpoint_linux.go
- notify.go
- package.go
- pod_status.go
- processes.go
- ssh_linux.go
- system.go
- system_components.go
- utils.go
- wifi.go