cmd

package
v0.10.0-rc.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2020 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ComponentsCmd = &cobra.Command{
	Use:   "components",
	Short: "List all Dapr components",
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			components, err := kubernetes.Components()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			table, err := gocsv.MarshalString(components)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			utils.PrintTable(table)
		}
	},
}
View Source
var ConfigurtionsCmd = &cobra.Command{
	Use:   "configurations",
	Short: "List all Dapr configurations",
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			configs, err := kubernetes.Configurations()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			table, err := gocsv.MarshalString(configs)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			utils.PrintTable(table)
		}
	},
}
View Source
var DashboardCmd = &cobra.Command{
	Use:   "dashboard",
	Short: "Start Dapr dashboard",
	Run: func(cmd *cobra.Command, args []string) {
		if dashboardVersion {
			fmt.Println(standalone.GetDashboardVersion())
			os.Exit(0)
		}

		if port < 0 {
			localPort = defaultLocalPort
		} else {
			localPort = port
		}

		if kubernetesMode {
			config, client, err := kubernetes.GetKubeConfigClient()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, "Failed to initialize kubernetes client: %s", err.Error())
				os.Exit(1)
			}

			namespaces := []string{dashboardNamespace}
			if dashboardNamespace != daprSystemNamespace {
				namespaces = append(namespaces, daprSystemNamespace)
			}
			if dashboardNamespace != defaultNamespace {
				namespaces = append(namespaces, defaultNamespace)
			}

			foundNamespace := ""
			for _, namespace := range namespaces {
				ok, _ := kubernetes.CheckPodExists(client, namespace, nil, dashboardSvc)
				if ok {
					foundNamespace = namespace
					break
				}
			}

			if foundNamespace == "" {
				ok, nspace := kubernetes.CheckPodExists(client, "", nil, dashboardSvc)

				if ok {
					print.InfoStatusEvent(os.Stdout, "Dapr dashboard found in namespace: %s. Run dapr dashboard -k -n %s to use this namespace.", nspace, nspace)

				} else {
					print.FailureStatusEvent(os.Stdout, "Failed to find Dapr dashboard in cluster. Check status of dapr dashboard in the cluster.")
				}
				os.Exit(1)
			}

			signals := make(chan os.Signal, 1)
			signal.Notify(signals, os.Interrupt)
			defer signal.Stop(signals)

			portForward, err := kubernetes.NewPortForward(
				config,
				foundNamespace,
				dashboardSvc,
				defaultHost,
				localPort,
				remotePort,
				false,
			)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, "%s\n", err)
				os.Exit(1)
			}

			if err = portForward.Init(); err != nil {
				print.FailureStatusEvent(os.Stdout, "Error in port forwarding: %s\nCheck for `dapr dashboard` running in other terminal sessions, or use the `--port` flag to use a different port.\n", err)
				os.Exit(1)
			}

			go func() {
				<-signals
				portForward.Stop()
			}()

			// url for dashboard after port forwarding
			var webURL string = fmt.Sprintf("http://%s:%d", defaultHost, localPort)

			print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Dapr dashboard found in namespace:\t%s", foundNamespace))
			print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Dapr dashboard available at:\t%s\n", webURL))

			err = browser.OpenURL(webURL)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, "Failed to start Dapr dashboard in browser automatically")
				print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Visit %s in your browser to view the dashboard", webURL))
			}

			<-portForward.GetStop()
		} else {

			standalone.RunDashboard()
		}
	},
}
View Source
var ExpiryCMD = &cobra.Command{
	Use:   "expiry",
	Short: "Checks the expiry of the root certificate",
	Run: func(cmd *cobra.Command, args []string) {
		expiry, err := kubernetes.Expiry()
		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("error getting root cert expiry: %s", err))
			return
		}

		duration := int(expiry.Sub(time.Now().UTC()).Hours())
		fmt.Println(fmt.Sprintf("Root certificate expires in %v hours. Expiry date: %s", duration, expiry.String()))
	},
}
View Source
var ExportCMD = &cobra.Command{
	Use:   "export",
	Short: "Export the root CA, issuer cert and key from Kubernetes to local files",
	Run: func(cmd *cobra.Command, args []string) {
		err := kubernetes.ExportTrustChain(exportPath)
		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("error exporting trust chain certs: %s", err))
			return
		}

		dir, _ := filepath.Abs(exportPath)
		print.SuccessStatusEvent(os.Stdout, fmt.Sprintf("Trust certs successfully exported to %s", dir))
	},
}
View Source
var InitCmd = &cobra.Command{
	Use:   "init",
	Short: "Setup dapr in Kubernetes or Standalone modes",
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("network", cmd.Flags().Lookup("network"))
		viper.BindPFlag("install-path", cmd.Flags().Lookup("install-path"))
		viper.BindPFlag("redis-host", cmd.Flags().Lookup("redis-host"))

	},
	Run: func(cmd *cobra.Command, args []string) {
		print.PendingStatusEvent(os.Stdout, "Making the jump to hyperspace...")

		if kubernetesMode {
			print.InfoStatusEvent(os.Stdout, "Note: To install Dapr using Helm, see here:  https://github.com/dapr/docs/blob/master/getting-started/environment-setup.md#using-helm-advanced\n")

			config := kubernetes.InitConfiguration{
				Namespace:  initNamespace,
				Version:    runtimeVersion,
				EnableMTLS: enableMTLS,
				EnableHA:   enableHA,
			}
			err := kubernetes.Init(config)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				return
			}
			print.SuccessStatusEvent(os.Stdout, fmt.Sprintf("Success! Dapr has been installed to namespace %s. To verify, run `dapr status -k' in your terminal. To get started, go here: https://aka.ms/dapr-getting-started", config.Namespace))
		} else {
			dockerNetwork := ""
			if !slimMode {
				dockerNetwork = viper.GetString("network")
			}
			redisHost := viper.GetString("redis-host")
			err := standalone.Init(runtimeVersion, dockerNetwork, redisHost, slimMode)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				return
			}
			print.SuccessStatusEvent(os.Stdout, "Success! Dapr is up and running. To get started, go here: https://aka.ms/dapr-getting-started")
		}
	},
}
View Source
var InvokeCmd = &cobra.Command{
	Use:   "invoke",
	Short: "Invokes a Dapr app with an optional payload (deprecated, use invokePost)",
	Run: func(cmd *cobra.Command, args []string) {
		response, err := invoke.Post(invokeAppID, invokeAppMethod, invokePayload)
		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error invoking app %s: %s", invokeAppID, err))
			return
		}

		if response != "" {
			fmt.Println(response)
		}

		print.SuccessStatusEvent(os.Stdout, "App invoked successfully")
	},
}
View Source
var ListCmd = &cobra.Command{
	Use:   "list",
	Short: "List all Dapr instances",
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			list, err := kubernetes.List()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			table, err := gocsv.MarshalString(list)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			utils.PrintTable(table)
		} else {
			list, err := standalone.List()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			if len(list) == 0 {
				fmt.Println("No Dapr instances found.")
				return
			}

			table, err := gocsv.MarshalString(list)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				os.Exit(1)
			}

			utils.PrintTable(table)
		}
	},
}
View Source
var LogsCmd = &cobra.Command{
	Use:   "logs",
	Short: "Gets Dapr sidecar logs for an app in Kubernetes",
	Run: func(cmd *cobra.Command, args []string) {
		err := kubernetes.Logs(logsAppID, podName, namespace)
		if err != nil {
			print.FailureStatusEvent(os.Stdout, err.Error())
			os.Exit(1)
		}
		print.SuccessStatusEvent(os.Stdout, "Fetched logs")
	},
}
View Source
var MTLSCmd = &cobra.Command{
	Use:   "mtls",
	Short: "Check if mTLS is enabled in a Kubernetes cluster",
	Run: func(cmd *cobra.Command, args []string) {
		enabled, err := kubernetes.IsMTLSEnabled()
		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("error checking mTLS: %s", err))
			return
		}

		status := "disabled"
		if enabled {
			status = "enabled"
		}
		fmt.Printf("Mutual TLS is %s in your Kubernetes cluster \n", status)
	},
}
View Source
var PublishCmd = &cobra.Command{
	Use:   "publish",
	Short: "Publish an event to multiple consumers",
	Run: func(cmd *cobra.Command, args []string) {
		err := publish.SendPayloadToTopic(publishTopic, publishPayload, pubsubName)
		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error publishing topic %s: %s", publishTopic, err))
			return
		}

		print.SuccessStatusEvent(os.Stdout, "Event published successfully")
	},
}
View Source
var RootCmd = &cobra.Command{
	Use:   "dapr",
	Short: "Dapr CLI",
	Long: `
	 __                
    ____/ /___ _____  _____
   / __  / __ '/ __ \/ ___/
  / /_/ / /_/ / /_/ / /    
  \__,_/\__,_/ .___/_/     
	      /_/            
									   
======================================================
A serverless runtime for hyperscale, distributed systems`,
}
View Source
var RunCmd = &cobra.Command{
	Use:   "run",
	Short: "Launches Dapr and (optionally) your app side by side",
	Long: `Runs Dapr's sidecar and (optionally) an application.

Run a Java application:
  dapr run --app-id myapp -- java -jar myapp.jar
Run a NodeJs application that listens to port 3000:
  dapr run --app-id myapp --app-port 3000 -- node myapp.js
Run a Python application:
  dapr run --app-id myapp -- python myapp.py
Run sidecar only:
  dapr run --app-id myapp
	`,
	Args: cobra.MinimumNArgs(0),
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("placement-host", cmd.Flags().Lookup("placement-host"))
	},
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) == 0 {
			fmt.Println(print.WhiteBold("WARNING: no application command found."))
		}

		if kubernetesMode {
			output, err := kubernetes.Run(&kubernetes.RunConfig{
				AppID:         appID,
				AppPort:       appPort,
				GRPCPort:      grpcPort,
				HTTPPort:      port,
				Arguments:     args,
				Image:         image,
				CodeDirectory: args[0],
			})
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				return
			}

			print.InfoStatusEvent(os.Stdout, output.Message)
		} else {
			output, err := standalone.Run(&standalone.RunConfig{
				AppID:           appID,
				AppPort:         appPort,
				HTTPPort:        port,
				GRPCPort:        grpcPort,
				ConfigFile:      configFile,
				Arguments:       args,
				EnableProfiling: enableProfiling,
				ProfilePort:     profilePort,
				LogLevel:        logLevel,
				MaxConcurrency:  maxConcurrency,
				Protocol:        protocol,
				PlacementHost:   viper.GetString("placement-host"),
				ComponentsPath:  componentsPath,
			})
			if err != nil {
				print.FailureStatusEvent(os.Stdout, err.Error())
				return
			}

			var sigCh = make(chan os.Signal, 1)
			signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)

			daprRunning := make(chan bool, 1)
			appRunning := make(chan bool, 1)

			go func() {
				print.InfoStatusEvent(
					os.Stdout,
					fmt.Sprintf(
						"Starting Dapr with id %s. HTTP Port: %v. gRPC Port: %v",
						output.AppID,
						output.DaprHTTPPort,
						output.DaprGRPCPort))

				stdErrPipe, pipeErr := output.DaprCMD.StderrPipe()
				if pipeErr != nil {
					print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error creating stderr for Dapr: %s", err.Error()))
					os.Exit(1)
				}

				stdOutPipe, pipeErr := output.DaprCMD.StdoutPipe()
				if pipeErr != nil {
					print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error creating stdout for Dapr: %s", err.Error()))
					os.Exit(1)
				}

				errScanner := bufio.NewScanner(stdErrPipe)
				outScanner := bufio.NewScanner(stdOutPipe)
				go func() {
					for errScanner.Scan() {
						fmt.Println(print.Yellow(fmt.Sprintf("== DAPR == %s\n", errScanner.Text())))
					}
				}()

				go func() {
					for outScanner.Scan() {
						fmt.Println(print.Yellow(fmt.Sprintf("== DAPR == %s\n", outScanner.Text())))
					}
				}()

				err = output.DaprCMD.Start()
				if err != nil {
					print.FailureStatusEvent(os.Stdout, err.Error())
					os.Exit(1)
				}

				daprRunning <- true
			}()

			<-daprRunning

			go func() {
				if output.AppCMD == nil {
					appRunning <- true
					return
				}

				stdErrPipe, pipeErr := output.AppCMD.StderrPipe()
				if pipeErr != nil {
					print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error creating stderr for App: %s", err.Error()))
					os.Exit(1)
				}

				stdOutPipe, pipeErr := output.AppCMD.StdoutPipe()
				if pipeErr != nil {
					print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error creating stdout for App: %s", err.Error()))
					os.Exit(1)
				}

				errScanner := bufio.NewScanner(stdErrPipe)
				outScanner := bufio.NewScanner(stdOutPipe)
				go func() {
					for errScanner.Scan() {
						fmt.Println(print.Blue(fmt.Sprintf("== APP == %s\n", errScanner.Text())))
					}
				}()

				go func() {
					for outScanner.Scan() {
						fmt.Println(print.Blue(fmt.Sprintf("== APP == %s\n", outScanner.Text())))
					}
				}()

				err = output.AppCMD.Start()
				if err != nil {
					print.FailureStatusEvent(os.Stdout, err.Error())
					os.Exit(1)
				}

				appRunning <- true
			}()

			<-appRunning

			err = metadata.Put(output.DaprHTTPPort, "cliPID", strconv.Itoa(os.Getpid()))
			if err != nil {
				print.WarningStatusEvent(os.Stdout, "Could not update sidecar metadata for cliPID: %s", err.Error())
			}

			if output.AppCMD != nil {
				appCommand := strings.Join(args, " ")
				print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Updating metadata for app command: %s", appCommand))
				err = metadata.Put(output.DaprHTTPPort, "appCommand", appCommand)
				if err != nil {
					print.WarningStatusEvent(os.Stdout, "Could not update sidecar metadata for appCommand: %s", err.Error())
				}

				print.SuccessStatusEvent(os.Stdout, "You're up and running! Both Dapr and your app logs will appear here.\n")
			} else {
				print.SuccessStatusEvent(os.Stdout, "You're up and running! Dapr logs will appear here.\n")
			}

			<-sigCh
			print.InfoStatusEvent(os.Stdout, "\nterminated signal received: shutting down")

			err = output.DaprCMD.Process.Kill()
			if err != nil {
				print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error exiting Dapr: %s", err))
			} else {
				print.SuccessStatusEvent(os.Stdout, "Exited Dapr successfully")
			}

			if output.AppCMD != nil {
				err = output.AppCMD.Process.Kill()
				if err != nil {
					print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error exiting App: %s", err))
				} else {
					print.SuccessStatusEvent(os.Stdout, "Exited App successfully")
				}
			}
		}
	},
}
View Source
var StatusCmd = &cobra.Command{
	Use:   "status",
	Short: "Shows the Dapr system services (control plane) health status.",
	Run: func(cmd *cobra.Command, args []string) {
		status, err := kubernetes.Status()
		if err != nil {
			print.FailureStatusEvent(os.Stdout, err.Error())
			os.Exit(1)
		}
		table, err := gocsv.MarshalString(status)
		if err != nil {
			print.FailureStatusEvent(os.Stdout, err.Error())
			os.Exit(1)
		}

		utils.PrintTable(table)
	},
}
View Source
var StopCmd = &cobra.Command{
	Use:   "stop",
	Short: "Stops multiple running Dapr instances and their associated apps",
	Run: func(cmd *cobra.Command, args []string) {
		if stopAppID != "" {
			args = append(args, stopAppID)
		}
		for _, appID := range args {
			err := standalone.Stop(appID)
			if err != nil {
				print.FailureStatusEvent(os.Stdout, "failed to stop app id %s: %s", appID, err)
			} else {
				print.SuccessStatusEvent(os.Stdout, "app stopped successfully: %s", appID)
			}
		}
	},
}
View Source
var UninstallCmd = &cobra.Command{
	Use:   "uninstall",
	Short: "Removes a Dapr installation",
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("network", cmd.Flags().Lookup("network"))
		viper.BindPFlag("install-path", cmd.Flags().Lookup("install-path"))
	},
	Run: func(cmd *cobra.Command, args []string) {

		var err error

		if uninstallKubernetes {
			print.InfoStatusEvent(os.Stdout, "Removing Dapr from your cluster...")
			err = kubernetes.Uninstall(uninstallNamespace)
		} else {
			print.InfoStatusEvent(os.Stdout, "Removing Dapr from your machine...")
			dockerNetwork := viper.GetString("network")
			err = standalone.Uninstall(uninstallAll, dockerNetwork)
		}

		if err != nil {
			print.FailureStatusEvent(os.Stdout, fmt.Sprintf("Error removing Dapr: %s", err))
		} else {
			print.SuccessStatusEvent(os.Stdout, "Dapr has been removed successfully")
		}
	},
}

UninstallCmd is a command from removing a Dapr installation

Functions

func Execute

func Execute(version, apiVersion string)

Execute adds all child commands to the root command

Types

This section is empty.

Jump to

Keyboard shortcuts

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