cmds

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2023 License: Apache-2.0, BSD-2-Clause, BSD-3-Clause, + 3 more Imports: 84 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. * This source code is licensed under the Apache License Version 2.0.

Index

Constants

View Source
const JSON = "json"
View Source
const YAML = "yaml"

Variables

View Source
var (
	OsArch       = ""
	Version      = ""
	GitCommit    = ""
	BuildTime    = ""
	Branch       = ""
	DevGitCommit = ""
)
View Source
var InitCmd = &cobra.Command{
	Use:   "init",
	Short: "Init demo or dep component",
	Long:  `Init demo or dep component`,
}
View Source
var InitCommand = &cobra.Command{
	Use:   "demo",
	Short: "Init Nocalhost with demo mode",
	Long:  "Init api, web and dep component in cluster",
	Args: func(cmd *cobra.Command, args []string) error {
		if len(inits.InjectUserTemplate) > 15 {
			log.Fatal("--inject-user-template length should less then 15")
		}
		if inits.InjectUserTemplate != "" && !strings.ContainsAny(inits.InjectUserTemplate, "%d") {
			log.Fatalf("--inject-user-template does not contains %s", inits.InjectUserTemplate)
		}
		if inits.InjectUserAmount > 999 {
			log.Fatal("--inject-user-amount must less then 999")
		}
		if (len(strconv.Itoa(inits.InjectUserAmountOffset)) + len(inits.InjectUserTemplate)) > 20 {
			log.Fatal("--inject-user-offset and --inject-user-template length can not greater than 20")
		}
		switch inits.NameSpace {
		case "default":
			log.Fatal("please do not init nocalhost in default namespace")
		case "kube-system":
			log.Fatal("please do not init nocalhost in kube-system namespace")
		case "kube-public":
			log.Fatal("please do not init nocalhost in kube-public namespace")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		kubectl, err := tools.CheckThirdPartyCLI()
		mustI(err, "you should install them first(helm3 and kubectl)")
		must(common.Prepare())

		nocalhostHelmSource := app.DefaultInitHelmGitRepo
		if strings.ToLower(inits.Source) == "coding" {
			nocalhostHelmSource = app.DefaultInitHelmCODINGGitRepo
		}

		params := []string{
			"install",
			app.DefaultInitInstallApplicationName,
			"-u",
			nocalhostHelmSource,
			"--kubeconfig",
			common.KubeConfig,
			"-n",
			inits.NameSpace,
			"--type",
			app.DefaultInitHelmType,
			"--resource-path",
			app.DefaultInitHelmResourcePath,
		}

		setComponentDockerImageVersion(&params)

		if inits.Type != "" {
			if strings.ToLower(inits.Type) == "nodeport" {
				inits.Type = "NodePort"
			}
			if strings.ToLower(inits.Type) == "loadbalancer" {
				inits.Type = "LoadBalancer"
			}
			params = append(params, "--set", "service.type="+inits.Type)
		}

		params = append(params, "--set", "service.port="+strconv.Itoa(inits.Port))

		if len(inits.Set) > 0 {
			for _, set := range inits.Set {
				params = append(params, "--set", set)
			}
		}
		client, err := clientgoutils.NewClientGoUtils(common.KubeConfig, inits.NameSpace)
		log.Debugf("kubeconfig %s \n", common.KubeConfig)
		if err != nil || client == nil {
			log.Fatalf("new go client fail, err %s, or check you kubeconfig\n", err)
			return
		}

		nhctl, err := utils.GetNhctlPath()
		if err != nil {
			log.FatalE(err, "")
			return
		}

		if inits.Force {
			spinner := utils.NewSpinner(" waiting for force uninstall Nocalhost...")
			spinner.Start()
			uninstall := []string{
				"uninstall",
				app.DefaultInitInstallApplicationName,
				"--force",
				"-n",
				inits.NameSpace,
			}
			_, err = tools.ExecCommand(nil, debug, false, true, nhctl, uninstall...)
			utils.ShouldI(err, fmt.Sprintf("uninstall %s application fail", app.DefaultInitInstallApplicationName))

			if nsErr := client.CheckExistNameSpace(inits.NameSpace); nsErr == nil {

				_ = client.NameSpace(inits.NameSpace).DeleteStatefulSetAndPVC("nocalhost-mariadb")
				utils.ShouldI(
					client.DeleteNameSpace(inits.NameSpace, true),
					fmt.Sprintf("delete namespace %s faile", inits.NameSpace),
				)
			}
			if nsErr := client.CheckExistNameSpace(app.DefaultInitWaitNameSpace); nsErr == nil {
				err = client.DeleteNameSpace(app.DefaultInitWaitNameSpace, true)
				utils.ShouldI(err, fmt.Sprintf("delete namespace %s fail", app.DefaultInitWaitNameSpace))
			}
			spinner.Stop()
			coloredoutput.Success("force uninstall Nocalhost successfully \n")
		}

		log.Debugf("checking namespace %s if exist", inits.NameSpace)

		err = client.CheckExistNameSpace(inits.NameSpace)
		if err != nil {
			customLabels := map[string]string{
				"env": app.DefaultInitCreateNameSpaceLabels,
			}
			mustI(client.Labels(customLabels).CreateNameSpace(inits.NameSpace), "create namespace fail")
		}
		spinner := utils.NewSpinner(" waiting for get Nocalhost manifest...")
		spinner.Start()

		_, err = tools.ExecCommand(nil, debug, true, false, nhctl, params...)
		if err != nil {
			coloredoutput.Fail(
				"\n nhctl init fail, try to add `--force` end of command manually\n",
			)
			log.Fatal("exit init")
		}
		spinner.Stop()

		spinner = utils.NewSpinner(" waiting for Nocalhost component ready, this will take a few minutes...")
		spinner.Start()
		mustI(
			client.NameSpace(inits.NameSpace).WaitDeploymentToBeReady(app.DefaultInitWatchDeployment),
			"watch deployment timeout",
		)

		checkTime := 0
		for {
			isReady, _ := client.NameSpace(inits.NameSpace).CheckDeploymentReady(app.DefaultInitWatchWebDeployment)
			if isReady {
				break
			}
			checkTime = checkTime + 1
			if checkTime > 1500 {
				break
			}
			time.Sleep(time.Duration(200) * time.Millisecond)
		}
		spinner.Stop()
		coloredoutput.Success("Nocalhost component get ready \n")

		spinner = utils.NewSpinner(" waiting for init demo data...")
		spinner.Start()

		log.Debugf("try to find out web endpoint")
		endpoint := FindOutWebEndpoint(client)

		log.Debugf("try login and init nocalhost web(User、DevSpace and demo applications)")

		req := request.NewReq(
			fmt.Sprintf("http://%s", endpoint), common.KubeConfig, kubectl, inits.NameSpace, inits.Port,
		).Login(
			app.DefaultInitAdminUserName, app.DefaultInitAdminPassWord,
		).GetKubeConfig().AddBookInfoApplicationForThree().AddCluster().AddUser(
			app.DefaultInitUserEmail, app.DefaultInitPassword, app.DefaultInitName,
		).AddDevSpace()

		if inits.InjectUserTemplate != "" && inits.InjectUserAmount > 0 {
			_ = req.SetInjectBatchUserTemplate(inits.InjectUserTemplate).InjectBatchDevSpace(
				inits.InjectUserAmount, inits.InjectUserAmountOffset,
			)
		}
		spinner.Stop()

		coloredoutput.Success("init demo data successfully \n")

		spinner = utils.NewSpinner(" waiting for Nocalhost-dep ready, this will take a few minutes...")
		spinner.Start()
		mustI(
			client.NameSpace(app.DefaultInitWaitNameSpace).WaitDeploymentToBeReady(app.DefaultInitWaitDeployment),
			"watch deployment timeout",
		)

		setDepComponentDockerImage(kubectl, common.KubeConfig)

		spinner.Stop()

		coloredoutput.Success(
			"Nocalhost init completed. \n\n"+
				" Default user for plugin: \n"+
				" Api Server(Set on plugin): %s \n"+
				" Username: %s \n"+
				" Password: %s \n\n"+
				" Default administrator: \n"+
				" Web dashboard: %s\n"+
				" Username: %s \n"+
				" Password: %s \n\n"+
				" Now, you can setup VSCode plugin and enjoy Nocalhost! \n",
			req.BaseUrl,
			app.DefaultInitUserEmail,
			app.DefaultInitPassword,
			req.BaseUrl,
			app.DefaultInitAdminUserName,
			app.DefaultInitAdminPassWord,
		)

		must(req.IdleThePortForwardIfNeeded())
	},
}
View Source
var InitDepCommand = &cobra.Command{
	Use:   "dep",
	Short: "dep component",
	Long:  `dep component`,
	Args: func(cmd *cobra.Command, args []string) error {
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		must(common.Prepare())

		rawKubeConfig, err := ioutil.ReadFile(common.KubeConfig)
		must(errors.Wrap(err, ""))

		goClient, err := clientgo.NewAdminGoClient(rawKubeConfig)
		if err != nil || goClient == nil {
			log.Fatalf("create go client fail, err: %s, or check you kubeconfig\n", err)
		}
		clusterSetUp := setupcluster.NewSetUpCluster(goClient)
		tag := Version
		if Branch != app.DefaultNocalhostMainBranch {
			tag = DevGitCommit
		}
		_, err, _ = clusterSetUp.InitCluster(tag)
		mustI(err, "init dep component fail")

		client, err := clientgoutils.NewClientGoUtils(common.KubeConfig, app.DefaultInitWaitNameSpace)
		fmt.Printf("kubeconfig %s \n", common.KubeConfig)
		if err != nil || client == nil {
			log.Fatalf("new go client fail, err: %s, or check you kubeconfig\n", err)
			return
		}

		spinner := utils.NewSpinner(
			" waiting for nocalhost dep component ready," +
				" this will take a few minutes...",
		)
		spinner.Start()

		checkTime := 0
		for {
			isReady, _ := client.NameSpace(app.DefaultInitWaitNameSpace).
				CheckDeploymentReady(app.DefaultInitWaitDeployment)
			if isReady {
				break
			}
			checkTime = checkTime + 1
			if checkTime > 1500 {
				break
			}
			time.Sleep(time.Duration(200) * time.Millisecond)
		}
		spinner.Stop()
		log.Info(
			"nocalhost-dep has been installed, you can use `kubectl " +
				"label namespace ${namespace} env=nocalhost` enable namespace dependency injection",
		)
	},
}
View Source
var PortForwardCmd = &cobra.Command{
	Use:   "port-forward",
	Short: "Start port-forward",
	Long:  `Start port-forward`,
}
View Source
var ServerCmd = &cobra.Command{
	Use:   "serve",
	Short: "serve",
	Long:  `serve`,
	PreRun: func(*cobra.Command, []string) {
		util.InitLogger(util.Debug)
	},
	Run: func(cmd *cobra.Command, args []string) {
		c, err := pkg.Start(context.TODO(), config)
		if err != nil {
			log.Fatal(err)
		}
		if err := <-c; err != nil {
			log.Fatal(err)
		}
	},
}
View Source
var YamlCmd = &cobra.Command{
	Use:   "yaml",
	Short: "Yaml tool",
	Long:  `Yaml tool`,
}

Functions

func CompareVersion

func CompareVersion(v1, v2 string) int

func DisplayPVCs

func DisplayPVCs(pvcList []v1.PersistentVolumeClaim)

func DisplayPVCsByJson

func DisplayPVCsByJson(pvcList []v1.PersistentVolumeClaim)

func DisplayPVCsByYaml

func DisplayPVCsByYaml(pvcList []v1.PersistentVolumeClaim)

func DoGetApplicationMetas

func DoGetApplicationMetas() (appmeta.ApplicationMetas, error)

do get application metas and create default application if needed

func Execute

func Execute()

func FindOutWebEndpoint

func FindOutWebEndpoint(client *clientgoutils.ClientGoUtils) string

func GenKubeconfig

func GenKubeconfig(kube, ns string)

func ListApplicationSvc

func ListApplicationSvc(napp *app.Application)

func ListApplications

func ListApplications()

func ListApplicationsFull

func ListApplicationsFull()

func ListApplicationsJson

func ListApplicationsJson()

func ListApplicationsResult

func ListApplicationsResult() []*model.Namespace

func ListApplicationsYaml

func ListApplicationsYaml()

func SyncStatus

func SyncStatus(opt *app.SyncStatusOptions, ns, app, svc, svcType, kubeconfig string) *req.SyncthingStatus

Types

type AssociateSvcPack

type AssociateSvcPack struct {
	*dev_dir.SvcPack     `yaml:"svc_pack" json:"svc_pack"`
	Sha                  string `yaml:"sha" json:"sha"`
	KubeconfigPath       string `yaml:"kubeconfig_path" json:"kubeconfig_path"`
	Server               string `yaml:"server" json:"server"`
	SyncStatusCmd        string `yaml:"sync_status_cmd" json:"sync_status_cmd"`
	*req.SyncthingStatus `yaml:"syncthing_status" json:"syncthing_status"`
}

type CheckInfo

type CheckInfo struct {
	Status CheckInfoStatus `json:"status" yaml:"status"`
	Tips   string          `json:"tips" yaml:"tips"`
}

func CheckKubeconfig

func CheckKubeconfig(kubeconfigParams string, contextParam string) CheckInfo

# CheckKubeconfig return two strings first is the complate guide second is a simple msg

type CheckInfoStatus

type CheckInfoStatus string
var (
	SUCCESS CheckInfoStatus = "SUCCESS"
	FAIL    CheckInfoStatus = "FAIL"
)

type CommonFlags

type CommonFlags struct {
	SvcName   string
	AppName   string
	AppConfig bool
}

type ConfigEditFlags

type ConfigEditFlags struct {
	CommonFlags
	Content string

	AppConfig bool
	// contains filtered or unexported fields
}

type ConfigForPlugin

type ConfigForPlugin struct {
	Services []*profile.ServiceConfigV2 `json:"services" yaml:"services"`
}

type DevCommandType

type DevCommandType string

type ExecFlags

type ExecFlags struct {
	CommonFlags
	Commands  []string
	Container string
}

type Init

type Init struct {
	Type                   string
	Port                   int
	NameSpace              string
	Set                    []string
	Source                 string
	Force                  bool
	InjectUserTemplate     string
	InjectUserAmount       int
	InjectUserAmountOffset int
}

type PVCFlags

type PVCFlags struct {
	App  string
	Svc  string
	Name string
	Yaml bool
	Json bool
}

type PortForwardItem

type PortForwardItem struct {
	SvcName         string `json:"svcName" yaml:"svcName"`
	ServiceType     string `json:"servicetype" yaml:"servicetype"`
	Port            string `json:"port" yaml:"port"`
	Status          string `json:"status" yaml:"status"`
	Role            string `json:"role" yaml:"role"`
	Sudo            bool   `json:"sudo" yaml:"sudo"`
	DaemonServerPid int    `json:"daemonserverpid" yaml:"daemonserverpid"`
	Updated         string `json:"updated" yaml:"updated"`
	Reason          string `json:"reason" yaml:"reason"`
}

type RenderOps

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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