utils

package
v0.0.0-...-8c59050 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: AGPL-3.0 Imports: 85 Imported by: 2

Documentation

Index

Constants

View Source
const (
	CPUType           = "cpu"         // force to use CPU, no GPU
	NvidiaCardType    = "nvidia"      // handling by HAMi
	AmdGpuCardType    = "amd-gpu"     //
	AmdApuCardType    = "amd-apu"     // AMD APU with integrated GPU , AI Max 395 etc.
	GB10ChipType      = "nvidia-gb10" // NVIDIA GB10 Superchip & unified system memory
	StrixHaloChipType = "strix-halo"  // AMD Strix Halo GPU & unified system memory
)
View Source
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
	XClientIP     = "x-client-ip"
)
View Source
const (
	// CharSetAlphabeticLower are literally just valid alphabetic lowercase printable ASCII chars.
	CharSetAlphabeticLower = "abcdefghijklmnopqrstuvwxyz"

	// CharSetAlphabeticUpper are literally just valid alphabetic uppercase printable ASCII chars.
	CharSetAlphabeticUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// CharSetAlphabetic are literally just valid alphabetic printable ASCII chars.
	CharSetAlphabetic = CharSetAlphabeticLower + CharSetAlphabeticUpper

	// CharSetNumeric are literally just valid numeric chars.
	CharSetNumeric = "0123456789"

	// CharSetNumericHex are literally just valid hexadecimal printable ASCII chars.
	CharSetNumericHex = CharSetNumeric + "ABCDEF"

	// CharSetSymbolic are literally just valid symbolic printable ASCII chars.
	CharSetSymbolic = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

	// CharSetSymbolicRFC3986Unreserved are RFC3986 unreserved symbol characters.
	// See https://datatracker.ietf.org/doc/html/rfc3986#section-2.3.
	CharSetSymbolicRFC3986Unreserved = "-._~"

	// CharSetAlphaNumeric are literally just valid alphanumeric printable ASCII chars.
	CharSetAlphaNumeric = CharSetAlphabetic + CharSetNumeric

	// CharSetASCII are literally just valid printable ASCII chars.
	CharSetASCII = CharSetAlphabetic + CharSetNumeric + CharSetSymbolic

	// CharSetRFC3986Unreserved are RFC3986 unreserved characters.
	// See https://datatracker.ietf.org/doc/html/rfc3986#section-2.3.
	CharSetRFC3986Unreserved = CharSetAlphabetic + CharSetNumeric + CharSetSymbolicRFC3986Unreserved

	// CharSetUnambiguousUpper  are a set of unambiguous uppercase characters.
	CharSetUnambiguousUpper = "ABCDEFGHJKLMNOPQRTUVWYXZ2346789"
)
View Source
const CalicoTunnelAddrAnnotation = "projectcalico.org/IPv4IPIPTunnelAddr"

CalicoTunnelAddrAnnotation annotation key for calico tunnel address.

View Source
const (
	// DefaultN is the default value of n.
	DefaultN = 72
)
View Source
const DefaultRegistry = "https://registry-1.docker.io"
View Source
const (
	NodeGPUTypeLabel = "gpu.bytetrade.io/type"
)

Variables

View Source
var ArchNameMap = map[int64]string{
	2:  "Kepler",
	3:  "Maxwell",
	4:  "Pascal",
	5:  "Volta",
	6:  "Turing",
	7:  "Ampere",
	8:  "Ada Lovelace",
	9:  "Hopper",
	10: "Blackwell",
}
View Source
var ErrUnPadding = errors.New("UnPadding error")

Functions

func AesDecrypt

func AesDecrypt(crypted, key []byte) ([]byte, error)

AesDecrypt decrypts the given ciphertext using AES encryption with the specified key.

func AesEncrypt

func AesEncrypt(origin, key []byte) ([]byte, error)

AesEncrypt encrypts the given plaintext using AES encryption with the specified key.

func AggregateErrs

func AggregateErrs(errs []error) error

AggregateErrs aggregates a slice of errors into a single error.

func AppNamespace

func AppNamespace(app, owner, ns string) (string, error)

AppNamespace returns the namespace of an application.

func CheckSSLCertificate

func CheckSSLCertificate(cert, key []byte, hostname string) error

CheckSSLCertificate checks the validity of an SSL certificate and private key for a given hostname.

func DecodeNodeGPU

func DecodeNodeGPU(str string) ([]api.GPUInfo, error)

func EnvNameToResourceName

func EnvNameToResourceName(envName string) (string, error)

EnvNameToResourceName validates and converts an env name to a k8s resource name. - must start with a letter - allowed chars: letters, digits, underscore - output: lowercase, underscores converted to hyphens

func EnvOrDefault

func EnvOrDefault(name, def string) string

func ExtractGPUVersion

func ExtractGPUVersion(gpuName string) string

func FindOwnerUser

func FindOwnerUser(ctrlClient client.Client, user *iamv1alpha2.User) (*iamv1alpha2.User, error)

func FmtAppName

func FmtAppName(name, namespace string) string

FmtAppName returns application name.

func GetAllGpuTypesFromNodes

func GetAllGpuTypesFromNodes(nodes *corev1.NodeList) (map[string]struct{}, error)

func GetAllNodesPodCIDRs

func GetAllNodesPodCIDRs() (cidrs []string)

GetAllNodesPodCIDRs returns all node pod's cidr.

func GetAllNodesTunnelIPCIDRs

func GetAllNodesTunnelIPCIDRs() (cidrs []string)

GetAllNodesTunnelIPCIDRs returns all node tunnel's ip cidr.

func GetClient

func GetClient() (*versioned.Clientset, error)

GetClient returns versioned ClientSet.

func GetDeploymentName

func GetDeploymentName(pod *corev1.Pod) string

func GetDeviceName

func GetDeviceName() (string, error)

func GetMirrorsEndpoint

func GetMirrorsEndpoint() (ep []string)

func GetMyExternalIPAddr

func GetMyExternalIPAddr() string

GetMyExternalIPAddr get my network outgoing ip address

func GetNodeInfo

func GetNodeInfo(ctx context.Context) (ret []api.NodeInfo, err error)

func GetRandomCharacters

func GetRandomCharacters() (r string)

func GetRefFromResourceList

func GetRefFromResourceList(chartPath string, values map[string]interface{}, images []string) (refs []v1alpha1.Ref, err error)

func GetResourceListFromChart

func GetResourceListFromChart(chartPath string, values map[string]interface{}) (resources kube.ResourceList, err error)

func GetServerServiceAccountToken

func GetServerServiceAccountToken() (string, error)

func GetTerminus

func GetTerminus(ctx context.Context, ctrlClient client.Client) (*sysv1alpha1.Terminus, error)

func GetTerminusVersion

func GetTerminusVersion(ctx context.Context, config *rest.Config) (*sysv1alpha1.Terminus, error)

func GetUserServiceAccountToken

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

func InitAction

func InitAction() (*action.Install, error)

func IsNodeReady

func IsNodeReady(node *corev1.Node) bool

func IsPortAvailable

func IsPortAvailable(protocol string, port int) bool

func ListToMap

func ListToMap[K comparable, T any](list []T, keyFunc func(T) K) map[K]T

func MatchVersion

func MatchVersion(version, constraint string) bool

MatchVersion check if the version satisfies the constraint.

func Md5String

func Md5String(s string) string

Md5String returns md5 for a string.

func MessageToAny

func MessageToAny(msg proto.Message) *anypb.Any

MessageToAny converts from proto message to proto Any

func MessageToAnyWithError

func MessageToAnyWithError(msg proto.Message) (*anypb.Any, error)

MessageToAnyWithError converts from proto message to proto Any

func NewNatsConn

func NewNatsConn() (*nats.Conn, error)

func Pbkdf2Crypto

func Pbkdf2Crypto(password string) (hash string, err error)

func PrettyJSON

func PrettyJSON(v any) string

PrettyJSON print pretty json.

func PublishEvent

func PublishEvent(nc *nats.Conn, subject string, data interface{}) error

func RandString

func RandString() string

RandString returns random string with 64 char length.

func RemoteIP

func RemoteIP(req *http.Request) string

RemoteIP extracts the remote IP address from the provided http.Request object.

func RenderManifest

func RenderManifest(filepath, owner, admin string, isAdmin bool) (string, error)

func RenderManifestFromContent

func RenderManifestFromContent(content []byte, owner, admin string, isAdmin bool) (string, error)

func ReplacedImageRef

func ReplacedImageRef(mirrorsEndpoint []string, oldImageRef string, checkConnection bool) (string, bool)

ReplacedImageRef return replaced image ref and true if mirror is support http

func SubnetSplit

func SubnetSplit(n int) map[string]*net.IPNet

func ToJSON

func ToJSON(msg proto.Message) (string, error)

ToJSON marshals a proto to canonical JSON

func ToJSONMap

func ToJSONMap(msg proto.Message) (map[string]any, error)

ToJSONMap converts a proto message to a generic map using canonical JSON encoding JSON encoding is specified here: https://developers.google.com/protocol-buffers/docs/proto3#json

func ToJSONWithIndent

func ToJSONWithIndent(msg proto.Message, indent string) (string, error)

ToJSONWithIndent marshals a proto to canonical JSON with pretty printed string

func ToJSONWithOptions

func ToJSONWithOptions(msg proto.Message, indent string, enumsAsInts bool) (string, error)

ToJSONWithOptions marshals a proto to canonical JSON with options to indent and print enums' int values

func ToYAML

func ToYAML(msg proto.Message) (string, error)

ToYAML marshals a proto to canonical YAML

func UserspaceName

func UserspaceName(user string) string

UserspaceName returns user-space namespace for a user.

Types

type Cryptographical

type Cryptographical struct{}

Cryptographical is the production random.Provider which uses crypto/rand.

func (*Cryptographical) Bytes

func (r *Cryptographical) Bytes() (data []byte)

Bytes returns random data as bytes with the standard random.DefaultN length and can contain any byte values (including unreadable byte values). If an error is returned from the random read this function ignores it.

func (*Cryptographical) BytesCustom

func (r *Cryptographical) BytesCustom(n int, charset []byte) (data []byte)

BytesCustom returns random data as bytes with n length and can contain only byte values from the provided values. If n is less than 1 then DefaultN is used instead. If an error is returned from the random read this function ignores it.

func (*Cryptographical) BytesCustomErr

func (r *Cryptographical) BytesCustomErr(n int, charset []byte) (data []byte, err error)

BytesCustomErr returns random data as bytes with n length and can contain only byte values from the provided values. If n is less than 1 then DefaultN is used instead. If an error is returned from the random read this function returns it.

func (*Cryptographical) BytesErr

func (r *Cryptographical) BytesErr() (data []byte, err error)

BytesErr returns random data as bytes with the standard random.DefaultN length and can contain any byte values (including unreadable byte values). If an error is returned from the random read this function returns it.

func (*Cryptographical) Int

func (r *Cryptographical) Int(max *big.Int) (value *big.Int)

Int returns a random *big.Int with a maximum of max.

func (*Cryptographical) IntErr

func (r *Cryptographical) IntErr(max *big.Int) (value *big.Int, err error)

IntErr returns a random *big.Int error combination with a maximum of max.

func (*Cryptographical) Intn

func (r *Cryptographical) Intn(n int) (value int)

Intn returns a random int with a maximum of n.

func (*Cryptographical) IntnErr

func (r *Cryptographical) IntnErr(n int) (value int, err error)

IntnErr returns a random int error combination with a maximum of n.

func (*Cryptographical) Prime

func (r *Cryptographical) Prime(bits int) (prime *big.Int, err error)

Prime returns a number of the given bit length that is prime with high probability. Prime will return error for any error returned by rand.Read or if bits < 2.

func (*Cryptographical) Read

func (r *Cryptographical) Read(p []byte) (n int, err error)

Read implements the io.Reader interface.

func (*Cryptographical) StringCustom

func (r *Cryptographical) StringCustom(n int, characters string) (data string)

StringCustom is an overload of BytesCustom which takes a characters string and returns a string.

func (*Cryptographical) StringCustomErr

func (r *Cryptographical) StringCustomErr(n int, characters string) (data string, err error)

StringCustomErr is an overload of BytesCustomWithErr which takes a characters string and returns a string.

type Event

type Event struct {
	EventID          string                    `json:"eventID"`
	CreateTime       time.Time                 `json:"createTime"`
	Name             string                    `json:"name"`
	RawAppName       string                    `json:"rawAppName"`
	Type             string                    `json:"type"`
	OpType           string                    `json:"opType,omitempty"`
	OpID             string                    `json:"opID,omitempty"`
	State            string                    `json:"state"`
	Progress         string                    `json:"progress,omitempty"`
	User             string                    `json:"user"`
	EntranceStatuses []v1alpha1.EntranceStatus `json:"entranceStatuses,omitempty"`
	Title            string                    `json:"title,omitempty"`
	Icon             string                    `json:"icon,omitempty"`
	Reason           string                    `json:"reason,omitempty"`
	Message          string                    `json:"message,omitempty"`
	SharedEntrances  []v1alpha1.Entrance       `json:"sharedEntrances,omitempty"`
}

type EventParams

type EventParams struct {
	Owner            string
	Name             string
	OpType           string
	OpID             string
	State            string
	Progress         string
	EntranceStatuses []v1alpha1.EntranceStatus
	RawAppName       string
	Type             string // "app" (default) or "middleware"
	Title            string
	Reason           string
	Message          string
	SharedEntrances  []v1alpha1.Entrance
	Icon             string
}

EventParams defines parameters to publish an app-related event

type SnakeCaseMarshaller

type SnakeCaseMarshaller struct {
	Value interface{}
}

SnakeCaseMarshaller is a struct that contains a field `Value`. This struct is intended to implement custom JSON marshalling by converting the field names in `Value` from camelCase or PascalCase to snake_case which is often used in JSON keys.

func (SnakeCaseMarshaller) MarshalJSON

func (sc SnakeCaseMarshaller) MarshalJSON() ([]byte, error)

MarshalJSON implements the marshalling to JSON for the SnakeCaseMarshaller. This method overrides the standard marshalling behavior to convert the field names of the 'Value' to snake_case.

type SystemStatusResponse

type SystemStatusResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		TerminusdState            string `json:"terminusdState"`
		TerminusState             string `json:"terminusState"`
		TerminusName              string `json:"terminusName"`
		TerminusVersion           string `json:"terminusVersion"`
		InstalledTime             int64  `json:"installedTime"`
		InitializedTime           int64  `json:"initializedTime"`
		OlaresdVersion            string `json:"olaresdVersion"`
		DeviceName                string `json:"device_name"`
		HostName                  string `json:"host_name"`
		OsType                    string `json:"os_type"`
		OsArch                    string `json:"os_arch"`
		OsInfo                    string `json:"os_info"`
		OsVersion                 string `json:"os_version"`
		CpuInfo                   string `json:"cpu_info"`
		GpuInfo                   string `json:"gpu_info"`
		Memory                    string `json:"memory"`
		Disk                      string `json:"disk"`
		WifiConnected             bool   `json:"wifiConnected"`
		WiredConnected            bool   `json:"wiredConnected"`
		HostIp                    string `json:"hostIp"`
		ExternalIp                string `json:"externalIp"`
		InstallingState           string `json:"installingState"`
		InstallingProgress        string `json:"installingProgress"`
		UninstallingState         string `json:"uninstallingState"`
		UninstallingProgress      string `json:"uninstallingProgress"`
		UpgradingTarget           string `json:"upgradingTarget"`
		UpgradingRetryNum         int    `json:"upgradingRetryNum"`
		UpgradingState            string `json:"upgradingState"`
		UpgradingStep             string `json:"upgradingStep"`
		UpgradingProgress         string `json:"upgradingProgress"`
		UpgradingError            string `json:"upgradingError"`
		UpgradingDownloadState    string `json:"upgradingDownloadState"`
		UpgradingDownloadStep     string `json:"upgradingDownloadStep"`
		UpgradingDownloadProgress string `json:"upgradingDownloadProgress"`
		UpgradingDownloadError    string `json:"upgradingDownloadError"`
		CollectingLogsState       string `json:"collectingLogsState"`
		CollectingLogsError       string `json:"collectingLogsError"`
		DefaultFrpServer          string `json:"defaultFrpServer"`
		FrpEnable                 string `json:"frpEnable"`
	} `json:"data"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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