util

package
v0.0.0-...-a3728ec Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2023 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SealosNamespace = "sealos-system"
	ClusterInfo    = "cluster-info"
	URLConfig      = "url-config"
	LicenseHistory = "license-history"
	LicenseName    = "license"
)
View Source
const (
	ContentType      = "Content-Type"
	ContentTypePlain = "text/plain"
	ContentTypeHTML  = "text/html"
	ContentTypeJSON  = "application/json"
)
View Source
const (
	CollectorURL      = "CollectorURL"
	NotificationURL   = "NotificationURL"
	RegisterURL       = "RegisterURL"
	CloudSyncURL      = "CloudSyncURL"
	LicenseMonitorURL = "LicenseMonitorURL"
	NetworkProbeURL   = "NetworkProbeURL"
)
View Source
const (
	Sealos                     string = "Sealos Cloud"
	ClusterCapacityNoticeTitle string = "Attention: Cluster Capacity Alert"
	LicenseNoticeTitle         string = "Attention: License Issue"
	InvalidLicenseMessage      string = "The license provided appears to be invalid. Please verify and try again."
	ExpiredLicenseMessage      string = "The license provided has expired. Please renew and try again."
	ValidLicenseMessage        string = "Your license has been successfully activated and is now ready for use. Enjoy your Sealos experience!"
	DuplicateLicenseMessage    string = "The license provided has already been activated. Please use a different license."
	RechargeFailedMessage      string = "License recharge operation failed."
)
View Source
const (
	CreatTimeField = "iat"
	AmountField    = "amt"
	NodeField      = "nod"
	CPUField       = "cpu"
	DurationField  = "tte"
	AddNodeField   = "and"
	AddCPUField    = "adc"
)
View Source
const (
	PeriodicPolicy          = "Periodic"
	PeriodicWithProbePolicy = "PeriodicWithProbe"
	OncePolicy              = "Once"
	OnceWithProbePolicy     = "OnceWithProbe"
)
View Source
const (
	Collector     task = "Collector"
	DataSync      task = "DataSync"
	Init          task = "Init"
	Register      task = "Register"
	Notice        task = "Notice"
	NoticeCleanup task = "NoticeCleanup"
	NetWorkConfig task = "NetWorkConfig"
	MemoryCleanup task = "MemoryCleanup"
)
View Source
const DefaultColForLicense = "license"
View Source
const MaxRetryForConnectDB = 5
View Source
const NoticeFrom = "Sealos Cloud"

Variables

View Source
var Key = "asdhjkwqdaskdjhqjwdakxausdasdajs"

Functions

func BuildForRunnable

func BuildForRunnable(ctx context.Context, client client.Client, options Options) []manager.Runnable

This file provided a framework which can be used to build a runnable task. With this framework, developers can easily build a runnable task and add it to the manager.

func CheckLicenseExists

func CheckLicenseExists(dbCol LicenseDB, uid string, token string) (bool, error)

func ContainsFields

func ContainsFields(data map[string]interface{}, fields ...string) bool

func Convert

func Convert(body []byte, content interface{}) error

func GetConfigFromConfigMap

func GetConfigFromConfigMap(expectName string,
	configMap *corev1.ConfigMap) (map[string]string, error)

func GetUID

func GetUID(ctx context.Context, client client.Client) (string, error)

func GetUIDURL

func GetUIDURL(ctx context.Context, client client.Client) (string, map[string]string, error)

func GetURL

func GetURL(ctx context.Context, client client.Client) (map[string]string, error)

func GetYesterdayAndTodayMidnight

func GetYesterdayAndTodayMidnight() (time.Time, time.Time)

func InterfaceToInt64

func InterfaceToInt64(value interface{}) (int64, error)

func IsConfigMapChanged

func IsConfigMapChanged(expect map[string]string, cm *corev1.ConfigMap) bool

func IsLicenseValid

func IsLicenseValid(license issuerv1.License) (map[string]interface{}, bool)

func IsSuccessfulStatusCode

func IsSuccessfulStatusCode(statusCode int) bool

func LicenseCheckOnExternalNetwork

func LicenseCheckOnExternalNetwork(ctx context.Context, client client.Client, license issuerv1.License) (map[string]interface{}, bool)

func LicenseCheckOnInternalNetwork

func LicenseCheckOnInternalNetwork(license issuerv1.License) (map[string]interface{}, bool)

func Once

func Once(_ context.Context, _ time.Duration, t Task) error

Once func is used to run a task only once.

func OnceWithProbe

func OnceWithProbe(ctx context.Context, period time.Duration, t Task) error

OnceWithProbe func is used to run a task only once.

func Periodic

func Periodic(ctx context.Context, period time.Duration, t Task) error

Periodic func is used to run a task periodically.

func PeriodicWithProbe

func PeriodicWithProbe(ctx context.Context, period time.Duration, t Task) error

func Push

func Push(url string, content interface{}) error

The Push method is used to handle one-way interaction, that is, there is no need to obtain information from the cloud, only need to send information to the cloud.

func RechargeByLicense

func RechargeByLicense(ctx context.Context, client client.Client, account accountv1.Account, payload map[string]interface{}) error

func RecordLicense

func RecordLicense(dbCol LicenseDB, license License) error

Types

type ClusterResource

type ClusterResource struct {
	Nodes  string `json:"nodes"`
	CPU    string `json:"cpu"`
	GPU    string `json:"gpu"`
	Memory string `json:"memery"`
	Disk   string `json:"disk"`
}

type Collect

type Collect struct {
	ClusterResource   ClusterResource
	DailyClusterUsage DailyClusterUsage
	CollectorInfo     CollectorInfo
	// contains filtered or unexported fields
}

func NewCollect

func NewCollect(o OptionsReadOnly) *Collect

type CollectorInfo

type CollectorInfo struct {
	UID             string            `json:"uid"`
	InfoType        TypeInfo          `json:"infoType"`
	DailyUsage      DailyClusterUsage `json:"dailyUsage,omitempty"`
	ClusterResource ClusterResource   `json:"clusterResource,omitempty"`
}

type Config

type Config struct {
	CollectorURL      string `json:"CollectorURL"`
	NotificationURL   string `json:"NotificationURL"`
	RegisterURL       string `json:"RegisterURL"`
	CloudSyncURL      string `json:"CloudSyncURL"`
	LicenseMonitorURL string `json:"LicenseMonitorURL"`
}

type DBOptions

type DBOptions struct {
	// The MongoOptions is used to store options for the MongoDB database.
	MongoOptions MongoOptions
}

type DailyClusterUsage

type DailyClusterUsage struct {
	Date          Date      `json:"date"`
	TotalUsageFee float64   `json:"totalUsageFee"`
	HourlyUsage   []float64 `json:"hourlyUsage"`
}

type DataSycn

type DataSycn struct {
}

func NewDataSync

func NewDataSync() *DataSycn

type Date

type Date string

type EnvOptions

type EnvOptions struct {

	// The MongoURI is used to connect to the MongoDB database.
	MongoURI string

	// The SaltKey is used to encrypt the password for pre-registered users.
	SaltKey string

	// Namespace
	Namespace string
}

The EnvOptions is used to store environment variables.

type FilterFunc

type FilterFunc func(string) bool

type Flag

type Flag struct {
	// contains filtered or unexported fields
}

func (*Flag) Completed

func (f *Flag) Completed()

func (*Flag) Probe

func (f *Flag) Probe() bool

type HTTPBody

type HTTPBody struct {
	ContentType string
	StatusCode  int
	Body        []byte
}

type HTTPResponse

type HTTPResponse struct {
	ContentType string
	StatusCode  int
	Body        []byte
}

func CommunicateWithCloud

func CommunicateWithCloud(method string, url string, content interface{}) (HTTPResponse, error)

func Get

func Get(url string) (HTTPResponse, error)

The Get method is used to handle "GET" request.

func Pull

func Pull(url string, content interface{}) (HTTPResponse, error)

The Pull method is used to handle two-way interaction, that is, there is a need to obtain information from the cloud, and then send information to the cloud.

type HashMap

type HashMap[T comparable] struct {
	// contains filtered or unexported fields
}

func (*HashMap[T]) Add

func (hs *HashMap[T]) Add(item T)

func (*HashMap[T]) Find

func (hs *HashMap[T]) Find(item T) bool

func (*HashMap[T]) Remove

func (hs *HashMap[T]) Remove()

type InitProbe

type InitProbe interface {
	Probe
	Completed()
}

func GetInitProbe

func GetInitProbe() InitProbe

type InitTask

type InitTask struct {
	// contains filtered or unexported fields
}

The following code is used to implement the instance of sub-task which is used to initialize the cluster uuid and preset root user for mongoDB

func NewInitTask

func NewInitTask(o OptionsReadOnly) *InitTask

type License

type License struct {
	UID        string                 `bson:"uid"`
	Token      string                 `bson:"token"`
	CreateTime string                 `bson:"createTime"`
	Payload    map[string]interface{} `bson:"payload"`
}

func NewLicense

func NewLicense(uid string, token string, payload map[string]interface{}) License

type LicenseDB

type LicenseDB interface {
	Record(license License) error
	QueryByUID(ns string, st int64, ed int64) ([]LicenseResult, error)

	IsExisted(uid string, token string) (bool, error)
	Disconnect() error
}

func NewLicenseDB

func NewLicenseDB(uri string) (LicenseDB, error)

type LicenseMonitorRequest

type LicenseMonitorRequest struct {
	UID   string `json:"uid"`
	Token string `json:"token"`
}

type LicenseMonitorResponse

type LicenseMonitorResponse struct {
	Key string `json:"key"`
}

type LicenseResult

type LicenseResult struct {
	License License `bson:"license"`
}

type Map

type Map[T any] interface {
	Find(T) bool
	Add(T)
	Remove()
}

func GetHashMap

func GetHashMap() Map[string]

func NewHashMap

func NewHashMap[T comparable]() Map[T]

type Memory

type Memory[T any] interface {
	Remove()
}

type MemoryClean

type MemoryClean struct {
	MM1 Memory[string]
}

func NewMemoryCleaner

func NewMemoryCleaner() *MemoryClean

type MongoOptions

type MongoOptions struct {
	// The MongoURI is used to connect to the MongoDB database.
	MongoURI string
	// The UserDB is the db reference of the MongoDB database.
	UserDB string
	// The UserCol is the collection of the UserDB to store user information.
	UserCol string
}

type NetWorkOptions

type NetWorkOptions struct {
	// EnableExternalNetWork is used to distinguish between
	// external and internal networks.
	EnableExternalNetWork bool
}

type NetworkConfig

type NetworkConfig struct {
	// contains filtered or unexported fields
}

func NewNetworkConfig

func NewNetworkConfig() *NetworkConfig

type NetworkProbe

type NetworkProbe interface {
	Probe
	ProbeForNetWork(url string)
}

func GetNetworkProbe

func GetNetworkProbe() NetworkProbe

type NoticeCleaner

type NoticeCleaner struct {
	// contains filtered or unexported fields
}

the NoticeCleaner task is used to clean the notification in the cluster periodically.

func NewNoticeCleaner

func NewNoticeCleaner() *NoticeCleaner

type NoticeWork

type NoticeWork struct {
	// contains filtered or unexported fields
}

the NoticeWork task is used to get the notification from the cloud. And then send the notification to the cluster.

func NewNotice

func NewNotice() *NoticeWork

type NotificationRequest

type NotificationRequest struct {
	UID       string `json:"uid"`
	Timestamp int64  `json:"timestamp"`
}

type NotificationResponse

type NotificationResponse struct {
	ID        string `json:"_id"`
	Type      string `json:"msgType"`
	Title     string `json:"title"`
	Message   string `json:"message"`
	Timestamp int64  `json:"timestamp"`
}

type OperatorOptions

type OperatorOptions struct {
	// The EnvOptions is used to store environment variables.
	EnvOptions EnvOptions
	// The DBOptions is used to store options for the database.
	DBOptions DBOptions
	// The RunnableOptions is used to store options for the Runnable instance
	RunnableOptions RunnableOptions
	// The NetWorkOptions is used to store options for the NetWork instance
	NetWorkOptions NetWorkOptions
}

The OperatorOptions struct is used to make configuration options available to licenseissuer operators.

func NewOptions

func NewOptions() *OperatorOptions

func (*OperatorOptions) GetDBOptions

func (o *OperatorOptions) GetDBOptions() DBOptions

func (*OperatorOptions) GetDefaultPeriod

func (o *OperatorOptions) GetDefaultPeriod() time.Duration

func (*OperatorOptions) GetEnvOptions

func (o *OperatorOptions) GetEnvOptions() EnvOptions

func (*OperatorOptions) GetNetWorkOptions

func (o *OperatorOptions) GetNetWorkOptions() NetWorkOptions

func (*OperatorOptions) GetPeriod

func (o *OperatorOptions) GetPeriod(tkname task) time.Duration

func (*OperatorOptions) GetPolicy

func (o *OperatorOptions) GetPolicy(tkname task) string

func (*OperatorOptions) GetRunnableOptions

func (o *OperatorOptions) GetRunnableOptions() RunnableOptions

func (*OperatorOptions) SetNetworkConfig

func (o *OperatorOptions) SetNetworkConfig(flag bool)

type Options

type Options interface {
	OptionsReadOnly
	OptionsReadWrite
}

A interface for options to implement read-only access.

func GetOptions

func GetOptions() Options

GetOptions returns the singleton instance of Options.

type OptionsReadOnly

type OptionsReadOnly interface {
	GetPolicy(name task) string
	GetPeriod(name task) time.Duration
	GetDefaultPeriod() time.Duration
	GetEnvOptions() EnvOptions
	GetNetWorkOptions() NetWorkOptions
	GetRunnableOptions() RunnableOptions
	GetDBOptions() DBOptions
}

func GetOptionsReadOnly

func GetOptionsReadOnly() OptionsReadOnly

GetOptionsReadOnly returns the singleton instance of OptionsReadOnly.

type OptionsReadWrite

type OptionsReadWrite interface {
	SetNetworkConfig(flag bool)
}

func GetOptionsReadWrite

func GetOptionsReadWrite() OptionsReadWrite

GetOptionsReadWrite returns the singleton instance of OptionsReadWrite.

type Probe

type Probe interface {
	Probe() bool
}

Probe is an interface for a probe check

func ProbeFor

func ProbeFor(taskType task) []Probe

ProbeFor return the Probe interface for the given task type

func ProbeForInit

func ProbeForInit() Probe

func ProbeForNetWork

func ProbeForNetWork() Probe

func ProbeForRegister

func ProbeForRegister() Probe

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

func (*Reader) Add

func (r *Reader) Add(obj client.Object, id types.NamespacedName)

func (*Reader) Read

func (r *Reader) Read(ctx context.Context, client client.Client) error

type RegisterProbe

type RegisterProbe interface {
	Probe
	SetFlag(flag bool)
}

func GetRegisterProbe

func GetRegisterProbe() RegisterProbe

type RegisterRequest

type RegisterRequest struct {
	UID string `json:"uid"`
}

type RegisterWork

type RegisterWork struct {
	// contains filtered or unexported fields
}

func NewRegister

func NewRegister() *RegisterWork

type RunnableOptions

type RunnableOptions struct {
	// The Policy is configured the task of framework.
	// --> Once: The task is executed only once.
	// --> Periodic: The task is executed periodically.
	Policy map[task]string
	// The Period is configured the period of the task
	// if empty, use the default period.
	Period        map[task]time.Duration
	DefaultPeriod time.Duration
}

type SyncRequest

type SyncRequest struct {
	UID string `json:"uid"`
}

type SyncResponse

type SyncResponse struct {
	Config `json:",inline"`
}

type Task

type Task interface {
	Run() error
	Log() *logr.Logger
	Probe() bool
}

TaskInstance implements the Task interface.

type TaskFunc

type TaskFunc func(context.Context) error

allow the user to define their own runnable task

type TaskInstance

type TaskInstance struct {
	client.Client
	// contains filtered or unexported fields
}

The TaskInstance struct is used to store the task information.

func (*TaskInstance) Log

func (ti *TaskInstance) Log() *logr.Logger

func (*TaskInstance) Probe

func (ti *TaskInstance) Probe() bool

func (*TaskInstance) Run

func (ti *TaskInstance) Run() error

func (*TaskInstance) Start

func (ti *TaskInstance) Start(ctx context.Context) error

type TaskPool

type TaskPool struct {
	client.Client
	// contains filtered or unexported fields
}

The TaskPool struct is used to build a task.

func NewTaskBuilder

func NewTaskBuilder(ctx context.Context, client client.Client, options Options) *TaskPool

type TotalNodesResource

type TotalNodesResource struct {
	TotalNodes      string
	TotalPVCapacity resource.Quantity
	TotalMemory     resource.Quantity
	TotalCPU        resource.Quantity
	// contains filtered or unexported fields
}

type TypeInfo

type TypeInfo string
const (
	ResourceOnCluster TypeInfo = "ClusterResource"
	DailyUsage        TypeInfo = "DailyUsage"
)

Jump to

Keyboard shortcuts

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