common

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2024 License: Apache-2.0 Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KubeCfgFile default kube config file path.
	KubeCfgFile = ".kube/config"
	// KubeCfgTempName default temp kube config file name prefix.
	KubeCfgTempName = "autok3s-temp-*"
	// K3sManifestsDir k3s manifests dir.
	K3sManifestsDir = "/var/lib/rancher/k3s/server/manifests/autok3s"
	// MasterInstanceName master instance name.
	MasterInstanceName = "autok3s.%s.master"
	// WorkerInstanceName worker instance name.
	WorkerInstanceName = "autok3s.%s.worker"
	// TagClusterPrefix cluster's tag prefix.
	TagClusterPrefix = "autok3s-"
	// StatusRunning instance running status.
	StatusRunning = "Running"
	// StatusCreating instance creating status.
	StatusCreating = "Creating"
	// StatusMissing instance missing status.
	StatusMissing = "Missing"
	// StatusFailed instance failed status.
	StatusFailed = "Failed"
	// StatusUpgrading instance upgrading status.
	StatusUpgrading = "Upgrading"
	// StatusRemoving instance removing status.
	StatusRemoving = "Removing"
	// StatusUnknown instance unknown status
	StatusUnknown = "Unknown"
	// UsageInfoTitle usage info title.
	UsageInfoTitle = "=========================== Prompt Info ==========================="
	// UsageContext usage info context.
	UsageContext = "Use 'autok3s kubectl config use-context %s'"
	// UsagePods usage  info pods.
	UsagePods = "Use 'autok3s kubectl get pods -A' get POD status`"
	// DBFolder default database dir.
	DBFolder = ".db"
	// DBFile default database file.
	DBFile = "autok3s.db"
)
View Source
const HelmDashboardCommand = "helm-dashboard"
View Source
const (
	KubeExplorerCommand = "kube-explorer"
)

Variables

View Source
var (
	// IsCLI means that you are not running serve command.
	IsCLI = true
	// Debug used to enable log debug level.
	Debug = false
	// CfgPath default config file dir.
	CfgPath = filepath.Join(utils.UserHome(), ".autok3s")
	// Backoff default backoff variable, retry 20 times, total 570 seconds.
	Backoff = wait.Backoff{
		Duration: 30 * time.Second,
		Factor:   1,
		Steps:    20,
	}
	// DefaultDB default database store.
	DefaultDB         *Store
	ExplorerWatchers  map[string]context.CancelFunc
	DashboardCanceled context.CancelFunc

	FileManager *ConfigFileManager
)
View Source
var DefaultRancherManifest = `` /* 1417-byte string literal not displayed */
View Source
var DefaultTemplates = map[string]interface{}{
	"aws": aws.Options{
		AMI:                    "ami-0c7217cdde317cfec",
		InstanceType:           "t3a.medium",
		VolumeType:             "gp3",
		RootSize:               "16",
		Region:                 "us-east-1",
		Zone:                   "us-east-1a",
		RequestSpotInstance:    false,
		CloudControllerManager: false,
	},
	"alibaba": alibaba.Options{
		Image:                   "ubuntu_22_04_x64_20G_alibase_20230613.vhd",
		InstanceType:            "ecs.e-c1m2.large",
		InternetMaxBandwidthOut: "5",
		DiskCategory:            "cloud_essd",
		DiskSize:                "40",
		EIP:                     false,
		CloudControllerManager:  false,
		Region:                  "cn-hangzhou",
		Zone:                    "cn-hangzhou-i",
		SpotStrategy:            "NoSpot",
		SpotDuration:            1,
	},
	"tencent": tencent.Options{
		ImageID:                 "img-487zeit5",
		InstanceType:            "S5.MEDIUM4",
		InstanceChargeType:      "POSTPAID_BY_HOUR",
		InternetMaxBandwidthOut: "5",
		SystemDiskType:          "CLOUD_SSD",
		SystemDiskSize:          "50",
		Region:                  "ap-guangzhou",
		Zone:                    "ap-guangzhou-6",
		PublicIPAssignedEIP:     false,
		Spot:                    false,
		CloudControllerManager:  false,
	},
	"google": google.Options{
		Region:       "us-central1",
		Zone:         "us-central1-b",
		MachineType:  "e2-medium",
		MachineImage: "ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20230727",
		DiskType:     "pd-balanced",
		DiskSize:     10,
		VMNetwork:    "default",
		Scopes:       "https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/cloud-platform",
	},
}

Functions

func AssembleManifest added in v0.9.0

func AssembleManifest(values map[string]interface{}, manifest string, templateFunc template.FuncMap) ([]byte, error)

func CheckCommandExist added in v0.4.4

func CheckCommandExist(cmd string) error

func ConvertToCluster added in v0.5.0

func ConvertToCluster(state *ClusterState, nodeInfo bool) types.Cluster

func DisableExplorer added in v0.4.4

func DisableExplorer(config string) error

DisableExplorer will stop kube-explorer server for specified K3s cluster

func EnableExplorer added in v0.4.4

func EnableExplorer(ctx context.Context, config string) (int, error)

EnableExplorer will start kube-explorer with random port for specified K3s cluster

func GenerateValues added in v0.9.0

func GenerateValues(setValues map[string]string, defaultValues map[string]string) (map[string]interface{}, error)

func GetAPIObject added in v0.6.0

func GetAPIObject(v interface{}) *apitypes.APIObject

func GetClusterContextPath added in v0.7.0

func GetClusterContextPath(clusterName string) string

func GetClusterLogFilePath added in v0.8.0

func GetClusterLogFilePath(clusterName string) string

func GetClusterPath added in v0.3.0

func GetClusterPath(clusterName, providerName string) string

GetClusterPath returns default cluster path.

func GetDB added in v0.4.0

func GetDB() (*gorm.DB, error)

GetDB open and returns database.

func GetDataSource added in v0.4.0

func GetDataSource() string

GetDataSource return default database file path.

func GetDefaultSSHKeyPath added in v0.3.0

func GetDefaultSSHKeyPath(clusterName, providerName string) string

GetDefaultSSHKeyPath returns default ssh key path.

func GetDefaultSSHPublicKeyPath added in v0.4.1

func GetDefaultSSHPublicKeyPath(clusterName, providerName string) string

GetDefaultSSHPublicKeyPath returns default public key path.

func GetLogFile added in v0.4.0

func GetLogFile(clusterName string) (logFile *os.File, err error)

GetLogFile open and return log file.

func GetOldLogPath added in v0.7.0

func GetOldLogPath() string

GetOldLogPath returns old log path.

func GetTelemetryEnable added in v0.5.2

func GetTelemetryEnable() *bool

func GetUUID added in v0.5.2

func GetUUID() string

func InitDashboard added in v0.9.0

func InitDashboard(ctx context.Context)

func InitExplorer added in v0.4.4

func InitExplorer(ctx context.Context)

InitExplorer will start kube-explorer server for all K3s clusters which enabled explorer setting

func InitLogger added in v0.5.2

func InitLogger(logger *logrus.Logger)

func InitStorage added in v0.4.0

func InitStorage(ctx context.Context) error

InitStorage initializes database storage.

func MetricsPrompt added in v0.5.2

func MetricsPrompt(cmd *cobra.Command)

func MoveLogs added in v0.7.0

func MoveLogs() error

func NewLogger

func NewLogger(w *os.File) (logger *logrus.Logger)

NewLogger returns new logger struct.

func SetTelemetryStatus added in v0.5.2

func SetTelemetryStatus(enable bool) error

func SetupNewInstall added in v0.5.2

func SetupNewInstall() (er error)

func SetupPrometheusMetrics added in v0.5.2

func SetupPrometheusMetrics(version string)

func StartHelmDashboard added in v0.9.0

func StartHelmDashboard(ctx context.Context, port string) error

func StartKubeExplorer added in v0.4.4

func StartKubeExplorer(ctx context.Context, config string, port int) error

StartKubeExplorer start kube-explorer server listen on specified port

func SwitchDashboard added in v0.9.0

func SwitchDashboard(ctx context.Context, enabled string) error

func ValidateName added in v0.9.0

func ValidateName(name string) error

Types

type Addon added in v0.9.0

type Addon struct {
	Name        string          `json:"name" gorm:"primaryKey;not null" wrangler:"required,noupdate"`
	Description string          `json:"description,omitempty"`
	Manifest    []byte          `json:"manifest" gorm:"type:bytes" wrangler:"required"`
	Values      types.StringMap `json:"values,omitempty" gorm:"type:stringMap"`
}

func (Addon) GetID added in v0.9.0

func (a Addon) GetID() string

type Broadcaster added in v0.4.0

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

Broadcaster sends events to multiple subscribers.

func NewBroadcaster added in v0.4.0

func NewBroadcaster() *Broadcaster

NewBroadcaster returns new broadcaster struct.

func (*Broadcaster) Broadcast added in v0.4.0

func (b *Broadcaster) Broadcast(v interface{})

Broadcast events to each subscriber.

func (*Broadcaster) Close added in v0.4.0

func (b *Broadcaster) Close()

Close all subscribers.

func (*Broadcaster) Evict added in v0.4.0

func (b *Broadcaster) Evict(s Subscriber)

Evict specified subscriber.

func (*Broadcaster) Register added in v0.4.0

func (b *Broadcaster) Register(sf subscriberFunc) Subscriber

Register helps init subscriber with specified subscribe function.

type ClusterState added in v0.4.0

type ClusterState struct {
	types.Metadata `json:",inline" mapstructure:",squash" gorm:"embedded"`
	Options        []byte `json:"options,omitempty" gorm:"type:bytes"`
	Status         string `json:"status" yaml:"status"`
	Standalone     bool   `json:"standalone" yaml:"standalone" gorm:"type:bool"`
	MasterNodes    []byte `json:"master-nodes,omitempty" gorm:"type:bytes"`
	WorkerNodes    []byte `json:"worker-nodes,omitempty" gorm:"type:bytes"`
	types.SSH      `json:",inline" mapstructure:",squash" gorm:"embedded"`
}

ClusterState cluster state struct.

func (*ClusterState) SchemaID added in v0.6.0

func (c *ClusterState) SchemaID() string

func (*ClusterState) ToAPIObject added in v0.6.0

func (c *ClusterState) ToAPIObject() *apitypes.APIObject

type ConfigFileManager added in v0.4.2

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

ConfigFileManager struct for config file manager.

func (*ConfigFileManager) ClearCfgByContext added in v0.4.7

func (c *ConfigFileManager) ClearCfgByContext(context string) error

ClearCfgByContext clear kube config by specified context.

func (*ConfigFileManager) MergeCfg added in v0.4.2

func (c *ConfigFileManager) MergeCfg(context string, configAccess clientcmd.ConfigAccess) (*api.Config, error)

MergeCfg merges kubectl config file.

func (*ConfigFileManager) OverwriteCfg added in v0.4.2

func (c *ConfigFileManager) OverwriteCfg(path string, context string, cfg func(string, clientcmd.ConfigAccess) (*api.Config, error)) error

OverwriteCfg overwrites kubectl config file.

func (*ConfigFileManager) RemoveCfg added in v0.4.2

func (c *ConfigFileManager) RemoveCfg(context string, configAccess clientcmd.ConfigAccess) (*api.Config, error)

RemoveCfg removes kubectl config file.

func (*ConfigFileManager) SaveCfg added in v0.4.7

func (c *ConfigFileManager) SaveCfg(context, tempFile string) error

SaveCfg save kube config file.

type Credential added in v0.4.0

type Credential struct {
	ID       int    `json:"id" gorm:"type:integer;primaryKey;not null;autoIncrement"`
	Provider string `json:"provider" gorm:"not null"`
	Secrets  []byte `json:"secrets,omitempty" gorm:"type:bytes"`
}

Credential credential struct.

func (*Credential) GetID added in v0.6.0

func (c *Credential) GetID() string

type DBSettingProvider added in v0.5.2

type DBSettingProvider struct{}

func (*DBSettingProvider) Get added in v0.5.2

func (p *DBSettingProvider) Get(name string) string

func (*DBSettingProvider) Set added in v0.5.2

func (p *DBSettingProvider) Set(name, value string) error

func (*DBSettingProvider) SetAll added in v0.5.2

func (p *DBSettingProvider) SetAll(settings map[string]settings.Setting) error

func (*DBSettingProvider) SetIfUnset added in v0.5.2

func (p *DBSettingProvider) SetIfUnset(name, value string) error

type Explorer added in v0.4.4

type Explorer struct {
	ContextName string `json:"context-name" gorm:"primaryKey;not null"`
	Enabled     bool   `json:"enabled" gorm:"type:bool"`
	Port        int    `json:"port"`
}

Explorer struct

func (*Explorer) GetID added in v0.6.0

func (e *Explorer) GetID() string

type IIDObject added in v0.6.0

type IIDObject interface {
	GetID() string
}

type ISchemaObject added in v0.6.0

type ISchemaObject interface {
	IIDObject
	SchemaID() string
	ToAPIObject() *apitypes.APIObject
}

type LogEvent added in v0.4.3

type LogEvent struct {
	Name        string
	ContextType string
	ContextName string
}

LogEvent log event struct.

type Package added in v0.6.0

type Package struct {
	Name       string            `json:"name,omitempty" gorm:"primaryKey;->;<-:create" wrangler:"required,noupdate"`
	K3sVersion string            `json:"k3sVersion,omitempty" wrangler:"required"`
	Archs      types.StringArray `json:"archs,omitempty" gorm:"type:text" wrangler:"required"`
	FilePath   string            `json:"filePath,omitempty" wrangler:"nocreate,noupdate"`
	State      State             `json:"state,omitempty" wrangler:"nocreate,noupdate"`
}

func (Package) GetID added in v0.6.0

func (p Package) GetID() string

type SSHKey added in v0.7.0

type SSHKey struct {
	Name        string `json:"name" gorm:"primaryKey;not null" wrangler:"required"`
	GenerateKey bool   `json:"generate-key,omitempty" gorm:"-:all" wrangler:"writeOnly,noupdate"`
	HasPassword bool   `json:"has-password" wrangler:"nocreate,noupdate"`

	SSHPassphrase string `json:"ssh-passphrase,omitempty" gorm:"-:all" wrangler:"type=password,nullable"`
	Bits          int    `json:"bits,omitempty" gorm:"-:all" wrangler:"default=2048,nullable"`

	SSHCert      string `json:"ssh-cert,omitempty" yaml:"ssh-cert,omitempty" wrangler:"nullable"`
	SSHKey       string `json:"ssh-key,omitempty" yaml:"ssh-key,omitempty" wrangler:"writeOnly,nullable"`
	SSHPublicKey string `json:"ssh-key-public,omitempty" yaml:"ssh-key-public,omitempty" wrangler:"nullable"`
}

func (SSHKey) GetID added in v0.7.0

func (s SSHKey) GetID() string

type Setting added in v0.5.0

type Setting struct {
	Name  string `json:"name" gorm:"primaryKey;not null"`
	Value string `json:"value"`
}

Setting struct

func (*Setting) GetID added in v0.6.0

func (s *Setting) GetID() string

type State added in v0.6.0

type State string
const (
	// PackageActive is the state after package downloaded
	PackageActive State = "Active"
	// PackageOutOfSync is the state when downloading package fails
	PackageOutOfSync State = "OutOfSync"
	// PackageDownloading is the state when downloading packages
	PackageDownloading State = "Downloading"
	// PackageVerifying is the state when verifying packages
	PackageVerifying State = "Verifying"
	// PackageValidating is the state when validating k3s version
	PackageValidating State = "Validating"
)

type Store added in v0.4.0

type Store struct {
	*gorm.DB
	// contains filtered or unexported fields
}

Store holds broadcaster's API state.

func NewClusterDB added in v0.4.0

func NewClusterDB(ctx context.Context) (*Store, error)

NewClusterDB new cluster store.

func (*Store) BroadcastObject added in v0.4.3

func (d *Store) BroadcastObject(obj interface{})

BroadcastObject broadcast object.

func (*Store) CreateCredential added in v0.4.0

func (d *Store) CreateCredential(cred *Credential) error

CreateCredential create credential.

func (*Store) CreateTemplate added in v0.4.0

func (d *Store) CreateTemplate(template *Template) error

CreateTemplate create template.

func (*Store) DeleteAddon added in v0.9.0

func (s *Store) DeleteAddon(name string) error

func (*Store) DeleteCluster added in v0.4.0

func (d *Store) DeleteCluster(name, provider string) error

DeleteCluster delete cluster.

func (*Store) DeleteCredential added in v0.4.0

func (d *Store) DeleteCredential(id int) error

DeleteCredential delete credential by ID.

func (*Store) DeleteExplorer added in v0.4.4

func (d *Store) DeleteExplorer(clusterID string) error

DeleteExplorer remove explorer setting for specified cluster

func (*Store) DeletePackage added in v0.6.0

func (s *Store) DeletePackage(name string) error

func (*Store) DeleteSSHKey added in v0.7.0

func (s *Store) DeleteSSHKey(name string) error

func (*Store) DeleteTemplate added in v0.4.0

func (d *Store) DeleteTemplate(name, provider string) error

DeleteTemplate delete template.

func (*Store) FindCluster added in v0.4.0

func (d *Store) FindCluster(name, provider string) ([]*ClusterState, error)

FindCluster find cluster.

func (*Store) GetAddon added in v0.9.0

func (s *Store) GetAddon(name string) (*Addon, error)

func (*Store) GetCluster added in v0.4.0

func (d *Store) GetCluster(name, provider string) (*ClusterState, error)

GetCluster get cluster.

func (*Store) GetClusterByID added in v0.4.0

func (d *Store) GetClusterByID(contextName string) (*ClusterState, error)

GetClusterByID get cluster by ID.

func (*Store) GetCredential added in v0.4.0

func (d *Store) GetCredential(id int) (*Credential, error)

GetCredential get credential by ID.

func (*Store) GetCredentialByProvider added in v0.4.0

func (d *Store) GetCredentialByProvider(provider string) ([]*Credential, error)

GetCredentialByProvider get credential by provider.

func (*Store) GetExplorer added in v0.4.4

func (d *Store) GetExplorer(clusterID string) (*Explorer, error)

GetExplorer return explorer setting for specified cluster

func (*Store) GetSetting added in v0.5.0

func (d *Store) GetSetting(name string) (*Setting, error)

GetSetting return specified setting by name

func (*Store) GetTemplate added in v0.4.0

func (d *Store) GetTemplate(name, provider string) (*Template, error)

GetTemplate get template.

func (*Store) ListAddon added in v0.9.0

func (s *Store) ListAddon() ([]*Addon, error)

func (*Store) ListCluster added in v0.4.0

func (d *Store) ListCluster(provider string) ([]*ClusterState, error)

ListCluster list cluster.

func (*Store) ListCredential added in v0.4.0

func (d *Store) ListCredential() ([]*Credential, error)

ListCredential list credential.

func (*Store) ListExplorer added in v0.4.4

func (d *Store) ListExplorer() ([]*Explorer, error)

ListExplorer return all kube-explorer settings

func (*Store) ListPackages added in v0.6.0

func (s *Store) ListPackages(name *string) ([]Package, error)

func (*Store) ListSSHKey added in v0.7.0

func (s *Store) ListSSHKey(name *string) ([]*SSHKey, error)

func (*Store) ListSettings added in v0.5.0

func (d *Store) ListSettings() ([]*Setting, error)

ListSettings list all settings

func (*Store) ListTemplates added in v0.4.0

func (d *Store) ListTemplates() ([]*Template, error)

ListTemplates list template.

func (*Store) Log added in v0.4.0

func (d *Store) Log(apiOp *apitypes.APIRequest, t string, input chan *LogEvent)

Log subscribe log.

func (*Store) PackageExists added in v0.6.0

func (s *Store) PackageExists(name string) error

package exists will return error if not exists or error

func (*Store) Register added in v0.4.0

func (d *Store) Register()

Register register gorm create/update hook.

func (*Store) SSHKeyExists added in v0.7.0

func (s *Store) SSHKeyExists(name string) (bool, error)

package exists will return error if not exists or error

func (*Store) SaveAddon added in v0.9.0

func (s *Store) SaveAddon(addon *Addon) error

func (*Store) SaveCluster added in v0.4.0

func (d *Store) SaveCluster(cluster *types.Cluster) error

SaveCluster save cluster.

func (*Store) SaveClusterState added in v0.4.0

func (d *Store) SaveClusterState(state *ClusterState) error

SaveClusterState save cluster state.

func (*Store) SaveExplorer added in v0.4.4

func (d *Store) SaveExplorer(exp *Explorer) error

SaveExplorer save cluster kube-explorer settings

func (*Store) SavePackage added in v0.6.0

func (s *Store) SavePackage(pkg Package) error

func (*Store) SaveSSHKey added in v0.7.0

func (s *Store) SaveSSHKey(sshkey SSHKey) error

func (*Store) SaveSetting added in v0.5.0

func (d *Store) SaveSetting(s *Setting) error

SaveSetting save settings

func (*Store) UpdateCredential added in v0.4.0

func (d *Store) UpdateCredential(cred *Credential) error

UpdateCredential update credential.

func (*Store) UpdateTemplate added in v0.4.0

func (d *Store) UpdateTemplate(template *Template) error

UpdateTemplate update template.

func (*Store) Watch added in v0.6.0

func (d *Store) Watch(apiOp *apitypes.APIRequest, schema *apitypes.APISchema) chan apitypes.APIEvent

type Subscriber added in v0.4.0

type Subscriber chan interface{}

Subscriber interface chan.

type Template added in v0.4.0

type Template struct {
	types.Metadata `json:",inline" mapstructure:",squash" gorm:"embedded"`
	Options        []byte `json:"options,omitempty" gorm:"type:bytes"`
	types.SSH      `json:",inline" mapstructure:",squash" gorm:"embedded"`
	IsDefault      bool `json:"is-default" gorm:"type:bool"`
}

Template template struct.

func (*Template) SchemaID added in v0.6.0

func (t *Template) SchemaID() string

func (*Template) ToAPIObject added in v0.6.0

func (t *Template) ToAPIObject() *apitypes.APIObject

Jump to

Keyboard shortcuts

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