cmd

package
v1.13.0 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AnnotateCmd = &cobra.Command{
	Use:   "annotate [flags] CONFIG-FILE",
	Short: "Add dapr annotations to a Kubernetes configuration. Supported platforms: Kubernetes",
	Example: `
# Annotate the first deployment found in the input
kubectl get deploy -l app=node -o yaml | dapr annotate -k - | kubectl apply -f -

# Annotate multiple deployments by name in a chain
kubectl get deploy -o yaml | dapr annotate -k -r nodeapp - | dapr annotate -k -r pythonapp - | kubectl apply -f -

# Annotate deployment in a specific namespace from file or directory by name
dapr annotate -k -r nodeapp -n namespace mydeploy.yaml | kubectl apply -f -

# Annotate deployment from url by name
dapr annotate -k -r nodeapp --log-level debug https://raw.githubusercontent.com/dapr/quickstarts/master/tutorials/hello-kubernetes/deploy/node.yaml | kubectl apply -f -

--------------------------------------------------------------------------------
WARNING: If an app id is not provided, we will generate one using the format '<namespace>-<kind>-<name>'.
--------------------------------------------------------------------------------
`,
	Run: func(cmd *cobra.Command, args []string) {
		if !kubernetesMode {
			print.FailureStatusEvent(os.Stderr, "annotate command is only supported for Kubernetes, please provide the -k flag")
			os.Exit(1)
		}

		if len(args) < 1 {
			print.FailureStatusEvent(os.Stderr, "please specify a Kubernetes resource file")
			os.Exit(1)
		}

		input, err := readInput(args[0])
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}

		var config kubernetes.K8sAnnotatorConfig
		if annotateTargetResource != "" {
			config = kubernetes.K8sAnnotatorConfig{
				TargetResource: &annotateTargetResource,
			}
			if annotateTargetNamespace != "" {
				config.TargetNamespace = &annotateTargetNamespace
			}
		} else {
			if annotateTargetNamespace != "" {

				print.FailureStatusEvent(os.Stderr, "--resource is required when --namespace is provided.")
				os.Exit(1)
			}
		}
		annotator := kubernetes.NewK8sAnnotator(config)
		opts := getOptionsFromFlags()
		if err := annotator.Annotate(input, os.Stdout, opts); err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}
	},
}
View Source
var BuildInfoCmd = &cobra.Command{
	Use:   "build-info",
	Short: "Print build info of Dapr CLI and runtime",
	Example: `
# Print build info
dapr build-info
`,
	Run: func(cmd *cobra.Command, args []string) {
		out, err := standalone.GetBuildInfo(daprRuntimePath, cliVersion)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, "Error getting build info: %s", err.Error())
			os.Exit(1)
		}
		fmt.Println(out)
	},
}
View Source
var ComponentsCmd = &cobra.Command{
	Use:   "components",
	Short: "List all Dapr components. Supported platforms: Kubernetes",
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			print.WarningStatusEvent(os.Stdout, "In future releases, this command will only query the \"default\" namespace by default. Please use the --namespace flag for a specific namespace, or the --all-namespaces (-A) flag for all namespaces.")
			if allNamespaces {
				resourceNamespace = meta_v1.NamespaceAll
			} else if resourceNamespace == "" {
				resourceNamespace = meta_v1.NamespaceAll
			}
			err := kubernetes.PrintComponents(componentsName, resourceNamespace, componentsOutputFormat)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
	Example: `
# List Dapr components in all namespaces in Kubernetes mode
dapr components -k

# List Dapr components in specific namespace in Kubernetes mode
dapr components -k --namespace default

# Print specific Dapr component in Kubernetes mode
dapr components -k -n target

# List Dapr components in all namespaces in Kubernetes mode
dapr components -k --all-namespaces
`,
}
View Source
var ConfigurationsCmd = &cobra.Command{
	Use:   "configurations",
	Short: "List all Dapr configurations. Supported platforms: Kubernetes",
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			print.WarningStatusEvent(os.Stdout, "In future releases, this command will only query the \"default\" namespace by default. Please use the --namespace flag for a specific namespace, or the --all-namespaces (-A) flag for all namespaces.")
			if allNamespaces {
				resourceNamespace = meta_v1.NamespaceAll
			} else if resourceNamespace == "" {
				resourceNamespace = meta_v1.NamespaceAll
			}
			err := kubernetes.PrintConfigurations(configurationName, resourceNamespace, configurationOutputFormat)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
	Example: `
# List Dapr configurations in all namespaces in Kubernetes mode
dapr configurations -k

# List Dapr configurations in specific namespace in Kubernetes mode
dapr configurations -k --namespace default

# Print specific Dapr configuration in Kubernetes mode
dapr configurations -k -n target

# List Dapr configurations in all namespaces in Kubernetes mode
dapr configurations -k --all-namespaces
`,
}
View Source
var DashboardCmd = &cobra.Command{
	Use:   "dashboard",
	Short: "Start Dapr dashboard. Supported platforms: Kubernetes and self-hosted",
	Example: `
# Start dashboard locally
dapr dashboard

# Start dashboard locally in a specified port
dapr dashboard -p 9999

# Start dashboard locally on a random port which is free.
dapr dashboard -p 0

# Port forward to dashboard in Kubernetes
dapr dashboard -k

# Port forward to dashboard in Kubernetes on all addresses in a specified port
dapr dashboard -k -p 9999 -a 0.0.0.0

# Port forward to dashboard in Kubernetes using a port
dapr dashboard -k -p 9999

# Port forward to dashboard in Kubernetes using a random port which is free.
dapr dashboard -k -p 0
`,
	Run: func(cmd *cobra.Command, args []string) {
		if dashboardVersionCmd {
			dashboardVer, err := standalone.GetDashboardVersion(daprRuntimePath)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Failed to get Dapr install directory: %v", err)
				os.Exit(1)
			}

			fmt.Println(dashboardVer)
			os.Exit(0)
		}

		if !utils.IsAddressLegal(dashboardHost) {
			print.FailureStatusEvent(os.Stdout, "Invalid address: %s", dashboardHost)
			os.Exit(1)
		}

		if dashboardLocalPort < 0 {
			print.FailureStatusEvent(os.Stderr, "Invalid port: %v", dashboardLocalPort)
			os.Exit(1)
		}

		if err := utils.CheckIfPortAvailable(dashboardLocalPort); err != nil {
			print.FailureStatusEvent(os.Stderr, "Please select a different port with %q flag: %s", "-p", err)
			print.InfoStatusEvent(os.Stdout, "You can also use port 0 to select a random free port.")
			os.Exit(1)
		}

		if kubernetesMode {
			config, client, err := kubernetes.GetKubeConfigClient()
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "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.Stderr, "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,
				dashboardHost,
				dashboardLocalPort,
				remotePort,
				false,
			)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "%s\n", err)
				os.Exit(1)
			}

			if err = portForward.Init(); err != nil {
				print.FailureStatusEvent(os.Stderr, "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()
			}()

			webURL := fmt.Sprintf("http://%s", net.JoinHostPort(dashboardHost, fmt.Sprint(portForward.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.Stderr, "Failed to start Dapr dashboard in browser automatically")
				print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Visit %s in your browser to view the dashboard", webURL))
			}

			<-portForward.GetStop()
		} else {

			dashboardCmd, err := standalone.NewDashboardCmd(daprRuntimePath, dashboardLocalPort)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Failed to get Dapr install	directory: %v", err)
			} else {
				err = dashboardCmd.Run()
				if err != nil {
					print.FailureStatusEvent(os.Stderr, "Dapr dashboard failed to run: %v", err)
				}
			}
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			kubernetes.CheckForCertExpiry()
		}
	},
}
View Source
var ExpiryCMD = &cobra.Command{
	Use:   "expiry",
	Short: "Checks the expiry of the root certificate",
	Example: `
# Check expiry of Kubernetes certs
dapr mtls expiry
`,
	Run: func(cmd *cobra.Command, args []string) {
		expiry, err := kubernetes.Expiry()
		if err != nil {
			print.FailureStatusEvent(os.Stderr, fmt.Sprintf("error getting root cert expiry: %s", err))
			return
		}

		duration := int(expiry.Sub(time.Now().UTC()).Hours())
		fmt.Printf("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",
	Example: `
# Export certs to local folder 
dapr mtls export -o ./certs
`,
	Run: func(cmd *cobra.Command, args []string) {
		err := kubernetes.ExportTrustChain(exportPath)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, fmt.Sprintf("error exporting trust chain certs: %s", err))
			os.Exit(1)
		}

		dir, _ := filepath.Abs(exportPath)
		print.SuccessStatusEvent(os.Stdout, fmt.Sprintf("Trust certs successfully exported to %s", dir))
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
}
View Source
var InitCmd = &cobra.Command{
	Use:   "init",
	Short: "Install Dapr on supported hosting platforms. Supported platforms: Kubernetes and self-hosted",
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("network", cmd.Flags().Lookup("network"))
		viper.BindPFlag("image-registry", cmd.Flags().Lookup("image-registry"))

		runtimeVersion = getConfigurationValue("runtime-version", cmd)
		dashboardVersion = getConfigurationValue("dashboard-version", cmd)
		containerRuntime = getConfigurationValue("container-runtime", cmd)
	},
	Example: `
# Initialize Dapr in self-hosted mode
dapr init

# Initialize Dapr in self-hosted mode with a provided docker image registry. Image looked up as <registry-url>/<image>.
# Check docs or README for more information on the format of the image path that is required.
dapr init --image-registry <registry-url>

# Initialize Dapr in Kubernetes
dapr init -k

# Initialize Dapr in Kubernetes in dev mode
dapr init -k --dev

# Initialize Dapr in Kubernetes and wait for the installation to complete (default timeout is 300s/5m)
dapr init -k --wait --timeout 600

# Initialize particular Dapr runtime in self-hosted mode
dapr init --runtime-version 0.10.0

# Initialize particular Dapr runtime in Kubernetes
dapr init -k --runtime-version 0.10.0

# Initialize Dapr in slim self-hosted mode
dapr init -s

# Initialize Dapr from a directory (installer-bundle installation) (Preview feature)
dapr init --from-dir <path-to-directory>

# Initialize dapr with a particular image variant. Allowed values: "mariner"
dapr init --image-variant <variant>

# Initialize Dapr inside a ".dapr" directory present in a non-default location
# Folder .dapr will be created in folder pointed to by <path-to-install-directory>
dapr init --runtime-path <path-to-install-directory>

# See more at: https://docs.dapr.io/getting-started/
`,
	Run: func(cmd *cobra.Command, args []string) {
		print.PendingStatusEvent(os.Stdout, "Making the jump to hyperspace...")
		imageRegistryFlag := strings.TrimSpace(viper.GetString("image-registry"))

		if kubernetesMode {
			print.InfoStatusEvent(os.Stdout, "Note: To install Dapr using Helm, see here: https://docs.dapr.io/getting-started/install-dapr-kubernetes/#install-with-helm-advanced\n")
			imageRegistryURI := ""
			var err error

			if len(strings.TrimSpace(daprRuntimePath)) != 0 {
				print.FailureStatusEvent(os.Stderr, "--runtime-path is only valid for self-hosted mode")
				os.Exit(1)
			}

			if len(imageRegistryFlag) != 0 {
				warnForPrivateRegFeat()
				imageRegistryURI = imageRegistryFlag
			} else {
				imageRegistryURI, err = kubernetes.GetImageRegistry()
			}
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
			if err = verifyCustomCertFlags(cmd); err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}

			config := kubernetes.InitConfiguration{
				Namespace:                 initNamespace,
				Version:                   runtimeVersion,
				DashboardVersion:          dashboardVersion,
				EnableMTLS:                enableMTLS,
				EnableHA:                  enableHA,
				EnableDev:                 devMode,
				Args:                      values,
				Wait:                      wait,
				Timeout:                   timeout,
				ImageRegistryURI:          imageRegistryURI,
				ImageVariant:              imageVariant,
				RootCertificateFilePath:   strings.TrimSpace(caRootCertificateFile),
				IssuerCertificateFilePath: strings.TrimSpace(issuerPublicCertificateFile),
				IssuerPrivateKeyFilePath:  strings.TrimSpace(issuerPrivateKeyFile),
			}
			err = kubernetes.Init(config)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
			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 := ""
			imageRegistryURI := ""
			if !slimMode {
				dockerNetwork = viper.GetString("network")
				imageRegistryURI = imageRegistryFlag
			}

			if len(strings.TrimSpace(imageRegistryURI)) != 0 && len(strings.TrimSpace(fromDir)) != 0 {
				print.FailureStatusEvent(os.Stderr, "both --image-registry and --from-dir flags cannot be given at the same time")
				os.Exit(1)
			}
			if len(strings.TrimSpace(fromDir)) != 0 {
				print.WarningStatusEvent(os.Stdout, "Local bundle installation using --from-dir flag is currently a preview feature and is subject to change. It is only available from CLI version 1.7 onwards.")
			}
			if len(imageRegistryURI) != 0 {
				warnForPrivateRegFeat()
			}

			if !utils.IsValidContainerRuntime(containerRuntime) {
				print.FailureStatusEvent(os.Stdout, "Invalid container runtime. Supported values are docker and podman.")
				os.Exit(1)
			}
			err := standalone.Init(runtimeVersion, dashboardVersion, dockerNetwork, slimMode, imageRegistryURI, fromDir, containerRuntime, imageVariant, daprRuntimePath)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
			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: "Invoke a method on a given Dapr application. Supported platforms: Self-hosted",
	Example: `
# Invoke a sample method on target app with POST Verb
dapr invoke --app-id target --method sample --data '{"key":"value"}

# Invoke a sample method on target app with GET Verb
dapr invoke --app-id target --method sample --verb GET

# Invoke a sample method on target app with GET Verb using Unix domain socket
dapr invoke --unix-domain-socket --app-id target --method sample --verb GET
`,
	Run: func(cmd *cobra.Command, args []string) {
		bytePayload := []byte{}
		var err error
		if invokeDataFile != "" && invokeData != "" {
			print.FailureStatusEvent(os.Stderr, "Only one of --data and --data-file allowed in the same invoke command")
			os.Exit(1)
		}

		if invokeDataFile != "" {
			bytePayload, err = os.ReadFile(invokeDataFile)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Error reading payload from '%s'. Error: %s", invokeDataFile, err)
				os.Exit(1)
			}
		} else if invokeData != "" {
			bytePayload = []byte(invokeData)
		}
		client := standalone.NewClient()

		if invokeSocket != "" {
			if runtime.GOOS == string(windowsOsType) {
				print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")
				os.Exit(1)
			} else {
				print.WarningStatusEvent(os.Stdout, "Unix domain sockets are currently a preview feature")
			}
		}

		response, err := client.Invoke(invokeAppID, invokeAppMethod, bytePayload, invokeVerb, invokeSocket)
		if err != nil {
			err = fmt.Errorf("error invoking app %s: %w", invokeAppID, err)
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}

		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. Supported platforms: Kubernetes and self-hosted",
	Example: `
# List Dapr instances in self-hosted mode
dapr list

# List Dapr instances in all namespaces in Kubernetes mode
dapr list -k

# List Dapr instances in a specific namespace in Kubernetes mode
dapr list -k --namespace default

# List Dapr instances in all namespaces in  Kubernetes mode
dapr list -k --all-namespaces
`,
	PreRun: func(cmd *cobra.Command, args []string) {
		if outputFormat != "" && outputFormat != "json" && outputFormat != "yaml" && outputFormat != "table" {
			print.FailureStatusEvent(os.Stdout, "An invalid output format was specified.")
			os.Exit(1)
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			print.WarningStatusEvent(os.Stdout, "In future releases, this command will only query the \"default\" namespace by default. Please use the --namespace flag for a specific namespace, or the --all-namespaces (-A) flag for all namespaces.")
			if allNamespaces {
				resourceNamespace = meta_v1.NamespaceAll
			} else if resourceNamespace == "" {
				resourceNamespace = meta_v1.NamespaceAll
			}

			list, err := kubernetes.List(resourceNamespace)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}

			outputList(list, len(list))
		} else {
			list, err := standalone.List()
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}

			outputList(list, len(list))
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		if kubernetesMode {
			kubernetes.CheckForCertExpiry()
		}
	},
}
View Source
var LogsCmd = &cobra.Command{
	Use:   "logs",
	Short: "Get Dapr sidecar logs for an application. Supported platforms: Kubernetes",
	Example: `
# Get logs of sample app from target pod in custom namespace
dapr logs -k --app-id sample --pod-name target --namespace custom
`,
	Run: func(cmd *cobra.Command, args []string) {
		err := kubernetes.Logs(logsAppID, podName, namespace)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}
		print.SuccessStatusEvent(os.Stdout, "Fetched logs")
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
}
View Source
var MTLSCmd = &cobra.Command{
	Use:   "mtls",
	Short: "Check if mTLS is enabled. Supported platforms: Kubernetes",
	Example: `
# Check if mTLS is enabled
dapr mtls -k
`,
	Run: func(cmd *cobra.Command, args []string) {
		enabled, err := kubernetes.IsMTLSEnabled()
		if err != nil {
			print.FailureStatusEvent(os.Stderr, fmt.Sprintf("error checking mTLS: %s", err))
			os.Exit(1)
		}

		status := "disabled"
		if enabled {
			status = "enabled"
		}
		fmt.Printf("Mutual TLS is %s in your Kubernetes cluster \n", status)
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
}
View Source
var PublishCmd = &cobra.Command{
	Use:   "publish",
	Short: "Publish a pub-sub event. Supported platforms: Self-hosted",
	Example: `
# Publish to sample topic in target pubsub via a publishing app
dapr publish --publish-app-id myapp --pubsub target --topic sample --data '{"key":"value"}'

# Publish to sample topic in target pubsub via a publishing app using Unix domain socket
dapr publish --enable-domain-socket --publish-app-id myapp --pubsub target --topic sample --data '{"key":"value"}'

# Publish to sample topic in target pubsub via a publishing app without cloud event
dapr publish --publish-app-id myapp --pubsub target --topic sample --data '{"key":"value"}' --metadata '{"rawPayload":"true","ttlInSeconds":"10"}'
`,
	Run: func(cmd *cobra.Command, args []string) {
		bytePayload := []byte{}
		var err error
		if publishPayloadFile != "" && publishPayload != "" {
			print.FailureStatusEvent(os.Stderr, "Only one of --data and --data-file allowed in the same publish command")
			os.Exit(1)
		}

		if publishPayloadFile != "" {
			bytePayload, err = os.ReadFile(publishPayloadFile)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Error reading payload from '%s'. Error: %s", publishPayloadFile, err)
				os.Exit(1)
			}
		} else if publishPayload != "" {
			bytePayload = []byte(publishPayload)
		}

		client := standalone.NewClient()

		if publishSocket != "" {
			if runtime.GOOS == string(windowsOsType) {
				print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")
				os.Exit(1)
			} else {
				print.WarningStatusEvent(os.Stdout, "Unix domain sockets are currently a preview feature")
			}
		}

		metadata := make(map[string]interface{})
		if publishMetadata != "" {
			err = json.Unmarshal([]byte(publishMetadata), &metadata)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Error parsing metadata as JSON. Error: %s", err)
				os.Exit(1)
			}
		}

		err = client.Publish(publishAppID, pubsubName, publishTopic, bytePayload, publishSocket, metadata)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error publishing topic %s: %s", publishTopic, err))
			os.Exit(1)
		}

		print.SuccessStatusEvent(os.Stdout, "Event published successfully")
	},
}
View Source
var RootCmd = &cobra.Command{
	Use:   "dapr",
	Short: "Dapr CLI",
	Long: `
	  __
     ____/ /___ _____  _____
    / __  / __ '/ __ \/ ___/
   / /_/ / /_/ / /_/ / /
   \__,_/\__,_/ .___/_/
	     /_/

===============================
Distributed Application Runtime`,
	Run: func(cmd *cobra.Command, _ []string) {
		if versionFlag {
			printVersion()
		} else {
			cmd.Help()
		}
	},
}
View Source
var RunCmd = &cobra.Command{
	Use:   "run",
	Short: "Run Dapr and (optionally) your application side by side. Supported platforms: Self-hosted",
	Example: `
# Run a .NET application
dapr run --app-id myapp --app-port 5000 -- dotnet run

# 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

# Run a gRPC application written in Go (listening on port 3000)
dapr run --app-id myapp --app-port 3000 --app-protocol grpc -- go run main.go

# Run a gRPC application written in Go (listening on port 3000) with a different app channel address
dapr run --app-id myapp --app-port 3000 --app-channel-address localhost --app-protocol grpc -- go run main.go


# Run sidecar only specifying dapr runtime installation directory
dapr run --app-id myapp --runtime-path /usr/local/dapr

# Run multiple apps by providing path of a run config file
dapr run --run-file dapr.yaml

# Run multiple apps by providing a directory path containing the run config file(dapr.yaml)
dapr run --run-file /path/to/directory

# Run multiple apps by providing config via stdin
cat dapr.template.yaml | envsubst | dapr run --run-file -

# Run multiple apps in Kubernetes by proficing path of a run config file
dapr run --run-file dapr.yaml -k

# Run multiple apps in Kubernetes by providing a directory path containing the run config file(dapr.yaml)
dapr run --run-file /path/to/directory -k
  `,
	Args: cobra.MinimumNArgs(0),
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("placement-host-address", cmd.Flags().Lookup("placement-host-address"))
	},
	Run: func(cmd *cobra.Command, args []string) {
		if len(runFilePath) > 0 {
			runConfigFilePath, err := getRunFilePath(runFilePath)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Failed to get run file path: %v", err)
				os.Exit(1)
			}
			executeRunWithAppsConfigFile(runConfigFilePath, enableRunK8s)
			return
		}
		if len(args) == 0 {
			fmt.Println(print.WhiteBold("WARNING: no application command found."))
		}

		daprDirPath, err := standalone.GetDaprRuntimePath(daprRuntimePath)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, "Failed to get Dapr install directory: %v", err)
			os.Exit(1)
		}

		if configFile == "" {
			configFile = standalone.GetDaprConfigPath(daprDirPath)
		}

		if componentsPath == "" {
			componentsPath = standalone.GetDaprComponentsPath(daprDirPath)
		}

		if unixDomainSocket != "" {

			if runtime.GOOS == string(windowsOsType) {
				print.FailureStatusEvent(os.Stderr, "The unix-domain-socket option is not supported on Windows")
				os.Exit(1)
			} else {

				print.WarningStatusEvent(os.Stdout, "Unix domain sockets are currently a preview feature")
				port = 0
				grpcPort = 0
			}
		}

		sharedRunConfig := &standalone.SharedRunConfig{
			ConfigFile:         configFile,
			EnableProfiling:    enableProfiling,
			LogLevel:           logLevel,
			MaxConcurrency:     maxConcurrency,
			AppProtocol:        protocol,
			PlacementHostAddr:  viper.GetString("placement-host-address"),
			ComponentsPath:     componentsPath,
			ResourcesPaths:     resourcesPaths,
			AppSSL:             appSSL,
			MaxRequestBodySize: maxRequestBodySize,
			HTTPReadBufferSize: readBufferSize,
			EnableAppHealth:    enableAppHealth,
			AppHealthPath:      appHealthPath,
			AppHealthInterval:  appHealthInterval,
			AppHealthTimeout:   appHealthTimeout,
			AppHealthThreshold: appHealthThreshold,
			EnableAPILogging:   enableAPILogging,
			APIListenAddresses: apiListenAddresses,
			DaprdInstallPath:   daprRuntimePath,
		}
		output, err := runExec.NewOutput(&standalone.RunConfig{
			AppID:             appID,
			AppChannelAddress: appChannelAddress,
			AppPort:           appPort,
			HTTPPort:          port,
			GRPCPort:          grpcPort,
			ProfilePort:       profilePort,
			Command:           args,
			MetricsPort:       metricsPort,
			UnixDomainSocket:  unixDomainSocket,
			InternalGRPCPort:  internalGRPCPort,
			SharedRunConfig:   *sharedRunConfig,
		})
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}

		sigCh := make(chan os.Signal, 1)
		daprsyscall.SetupShutdownNotify(sigCh)

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

		go func() {
			var startInfo string
			if unixDomainSocket != "" {
				startInfo = fmt.Sprintf(
					"Starting Dapr with id %s. HTTP Socket: %v. gRPC Socket: %v.",
					output.AppID,
					utils.GetSocket(unixDomainSocket, output.AppID, "http"),
					utils.GetSocket(unixDomainSocket, output.AppID, "grpc"))
			} else {
				startInfo = fmt.Sprintf(
					"Starting Dapr with id %s. HTTP Port: %v. gRPC Port: %v",
					output.AppID,
					output.DaprHTTPPort,
					output.DaprGRPCPort)
			}
			print.InfoStatusEvent(os.Stdout, startInfo)

			output.DaprCMD.Stdout = os.Stdout
			output.DaprCMD.Stderr = os.Stderr

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

			go func() {
				daprdErr := output.DaprCMD.Wait()

				if daprdErr != nil {
					output.DaprErr = daprdErr
					print.FailureStatusEvent(os.Stderr, "The daprd process exited with error code: %s", daprdErr.Error())
				} else {
					print.SuccessStatusEvent(os.Stdout, "Exited Dapr successfully")
				}
				sigCh <- os.Interrupt
			}()

			if appPort <= 0 {

				sidecarUp := true

				if unixDomainSocket != "" {
					httpSocket := utils.GetSocket(unixDomainSocket, output.AppID, "http")
					print.InfoStatusEvent(os.Stdout, "Checking if Dapr sidecar is listening on HTTP socket %v", httpSocket)
					err = utils.IsDaprListeningOnSocket(httpSocket, time.Duration(runtimeWaitTimeoutInSeconds)*time.Second)
					if err != nil {
						sidecarUp = false
						print.WarningStatusEvent(os.Stdout, "Dapr sidecar is not listening on HTTP socket: %s", err.Error())
					}

					grpcSocket := utils.GetSocket(unixDomainSocket, output.AppID, "grpc")
					print.InfoStatusEvent(os.Stdout, "Checking if Dapr sidecar is listening on GRPC socket %v", grpcSocket)
					err = utils.IsDaprListeningOnSocket(grpcSocket, time.Duration(runtimeWaitTimeoutInSeconds)*time.Second)
					if err != nil {
						sidecarUp = false
						print.WarningStatusEvent(os.Stdout, "Dapr sidecar is not listening on GRPC socket: %s", err.Error())
					}

				} else {
					print.InfoStatusEvent(os.Stdout, "Checking if Dapr sidecar is listening on HTTP port %v", output.DaprHTTPPort)
					err = utils.IsDaprListeningOnPort(output.DaprHTTPPort, time.Duration(runtimeWaitTimeoutInSeconds)*time.Second)
					if err != nil {
						sidecarUp = false
						print.WarningStatusEvent(os.Stdout, "Dapr sidecar is not listening on HTTP port: %s", err.Error())
					}

					print.InfoStatusEvent(os.Stdout, "Checking if Dapr sidecar is listening on GRPC port %v", output.DaprGRPCPort)
					err = utils.IsDaprListeningOnPort(output.DaprGRPCPort, time.Duration(runtimeWaitTimeoutInSeconds)*time.Second)
					if err != nil {
						sidecarUp = false
						print.WarningStatusEvent(os.Stdout, "Dapr sidecar is not listening on GRPC port: %s", err.Error())
					}
				}

				if sidecarUp {
					print.InfoStatusEvent(os.Stdout, "Dapr sidecar is up and running.")
				} else {
					print.WarningStatusEvent(os.Stdout, "Dapr sidecar might not be responding.")
				}
			}

			daprRunning <- true
		}()

		<-daprRunning

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

			stdErrPipe, pipeErr := output.AppCMD.StderrPipe()
			if pipeErr != nil {
				print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error creating stderr for App: %s", err.Error()))
				appRunning <- false
				return
			}

			stdOutPipe, pipeErr := output.AppCMD.StdoutPipe()
			if pipeErr != nil {
				print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error creating stdout for App: %s", err.Error()))
				appRunning <- false
				return
			}

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

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

			err = output.AppCMD.Start()
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				appRunning <- false
				return
			}

			go func() {
				appErr := output.AppCMD.Wait()

				if appErr != nil {
					output.AppErr = appErr
					print.FailureStatusEvent(os.Stderr, "The App process exited with error code: %s", appErr.Error())
				} else {
					print.SuccessStatusEvent(os.Stdout, "Exited App successfully")
				}
				sigCh <- os.Interrupt
			}()

			appRunning <- true
		}()

		appRunStatus := <-appRunning
		if !appRunStatus {

			err = output.DaprCMD.Process.Kill()
			if err != nil {
				print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Start App failed, try to stop Dapr Error: %s", err))
			} else {
				print.SuccessStatusEvent(os.Stdout, "Start App failed, try to stop Dapr successfully")
			}
			os.Exit(1)
		}

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

		if output.AppCMD != nil {
			if output.AppCMD.Process != nil {
				print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Updating metadata for appPID: %d", output.AppCMD.Process.Pid))
				err = metadata.Put(output.DaprHTTPPort, "appPID", strconv.Itoa(output.AppCMD.Process.Pid), output.AppID, unixDomainSocket)
				if err != nil {
					print.WarningStatusEvent(os.Stdout, "Could not update sidecar metadata for appPID: %s", err.Error())
				}
			}

			appCommand := strings.Join(args, " ")
			print.InfoStatusEvent(os.Stdout, fmt.Sprintf("Updating metadata for app command: %s", appCommand))
			err = metadata.Put(output.DaprHTTPPort, "appCommand", appCommand, output.AppID, unixDomainSocket)
			if err != nil {
				print.WarningStatusEvent(os.Stdout, "Could not update sidecar metadata for appCommand: %s", err.Error())
			} else {
				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")

		exitWithError := false

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

		if output.AppErr != nil {
			exitWithError = true
			print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error exiting App: %s", output.AppErr))
		} else if output.AppCMD != nil && (output.AppCMD.ProcessState == nil || !output.AppCMD.ProcessState.Exited()) {
			err = output.AppCMD.Process.Kill()
			if err != nil {
				exitWithError = true
				print.FailureStatusEvent(os.Stderr, fmt.Sprintf("Error exiting App: %s", err))
			} else {
				print.SuccessStatusEvent(os.Stdout, "Exited App successfully")
			}
		}

		if unixDomainSocket != "" {
			for _, s := range []string{"http", "grpc"} {
				os.Remove(utils.GetSocket(unixDomainSocket, output.AppID, s))
			}
		}

		if exitWithError {
			os.Exit(1)
		}
	},
}
View Source
var StatusCmd = &cobra.Command{
	Use:   "status",
	Short: "Show the health status of Dapr services. Supported platforms: Kubernetes",
	Example: `
# Get status of Dapr services from Kubernetes
dapr status -k 
`,
	Run: func(cmd *cobra.Command, args []string) {
		sc, err := kubernetes.NewStatusClient()
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}
		status, err := sc.Status()
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}
		if len(status) == 0 {
			print.FailureStatusEvent(os.Stderr, "No status returned. Is Dapr initialized in your cluster?")
			os.Exit(1)
		}
		table, err := gocsv.MarshalString(status)
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}

		utils.PrintTable(table)
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
}
View Source
var StopCmd = &cobra.Command{
	Use:   "stop",
	Short: "Stop Dapr instances and their associated apps. Supported platforms: Self-hosted",
	Example: `
# Stop Dapr application
dapr stop --app-id <ID>

# Stop multiple apps by providing a run config file
dapr stop --run-file dapr.yaml

# Stop multiple apps by providing a directory path containing the run config file(dapr.yaml)
dapr stop --run-file /path/to/directory

# Stop and delete Kubernetes deployment of multiple apps by providing a run config file
dapr stop --run-file dapr.yaml -k

# Stop and delete Kubernetes deployment of multiple apps by providing a directory path containing the run config file(dapr.yaml)
dapr stop --run-file /path/to/directory -k
`,
	Run: func(cmd *cobra.Command, args []string) {
		var err error
		if len(runFilePath) > 0 {
			runFilePath, err = getRunFilePath(runFilePath)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Failed to get run file path: %v", err)
				os.Exit(1)
			}
			if !stopK8s {
				err = executeStopWithRunFile(runFilePath)
				if err != nil {
					print.FailureStatusEvent(os.Stderr, "Failed to stop Dapr and app processes: %s", err)
				} else {
					print.SuccessStatusEvent(os.Stdout, "Dapr and app processes stopped successfully")
				}
				return
			}
			config, _, cErr := getRunConfigFromRunFile(runFilePath)
			if cErr != nil {
				print.FailureStatusEvent(os.Stderr, "Failed to parse run template file %q: %s", runFilePath, cErr.Error())
			}
			err = kubernetes.Stop(runFilePath, config)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "Error stopping deployments from multi-app run template: %v", err)
			}
		}
		if stopAppID != "" {
			args = append(args, stopAppID)
		}
		apps, err := standalone.List()
		if err != nil {
			print.FailureStatusEvent(os.Stderr, "failed to get list of apps started by dapr : %s", err)
			os.Exit(1)
		}
		cliPIDToNoOfApps := standalone.GetCLIPIDCountMap(apps)
		for _, appID := range args {
			err = standalone.Stop(appID, cliPIDToNoOfApps, apps)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, "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: "Uninstall Dapr runtime. Supported platforms: Kubernetes and self-hosted",
	Example: `
# Uninstall from self-hosted mode
dapr uninstall

# Uninstall from self-hosted mode and remove .dapr directory, Redis, Placement and Zipkin containers
dapr uninstall --all

# Uninstall from Kubernetes
dapr uninstall -k

# Uninstall from Kubernetes and remove CRDs
dapr uninstall -k --all

# Uninstall from Kubernetes remove dev deployments of Redis, Zipkin
dapr uninstall -k --dev

# Uninstall from Kubernetes remove dev deployments of Redis, Zipkin and CRDs
dapr uninstall -k --dev --all

# Uninstall Dapr from non-default install directory
# This will remove the .dapr directory present in the path <path-to-install-directory>
dapr uninstall --runtime-path <path-to-install-directory>
`,
	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 {
			if len(strings.TrimSpace(daprRuntimePath)) != 0 {
				print.FailureStatusEvent(os.Stderr, "--runtime-path is only valid for self-hosted mode")
				os.Exit(1)
			}

			print.InfoStatusEvent(os.Stdout, "Removing Dapr from your cluster...")
			err = kubernetes.Uninstall(uninstallNamespace, uninstallAll, uninstallDev, timeout)
		} else {
			if !utils.IsValidContainerRuntime(uninstallContainerRuntime) {
				print.FailureStatusEvent(os.Stdout, "Invalid container runtime. Supported values are docker and podman.")
				os.Exit(1)
			}
			print.InfoStatusEvent(os.Stdout, "Removing Dapr from your machine...")
			dockerNetwork := viper.GetString("network")
			err = standalone.Uninstall(uninstallAll, dockerNetwork, uninstallContainerRuntime, daprRuntimePath)
		}

		if err != nil {
			print.FailureStatusEvent(os.Stderr, 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.

View Source
var UpgradeCmd = &cobra.Command{
	Use:   "upgrade",
	Short: "Upgrades or downgrades a Dapr control plane installation in a cluster. Supported platforms: Kubernetes",
	PreRun: func(cmd *cobra.Command, args []string) {
		viper.BindPFlag("image-registry", cmd.Flags().Lookup("image-registry"))
	},
	Example: `
# Upgrade Dapr in Kubernetes
dapr upgrade -k

# See more at: https://docs.dapr.io/getting-started/
`,
	Run: func(cmd *cobra.Command, args []string) {
		imageRegistryFlag := strings.TrimSpace(viper.GetString("image-registry"))
		imageRegistryURI := ""
		var err error

		if len(imageRegistryFlag) != 0 {
			warnForPrivateRegFeat()
			imageRegistryURI = imageRegistryFlag
		} else {
			imageRegistryURI, err = kubernetes.GetImageRegistry()
		}
		if err != nil {
			print.FailureStatusEvent(os.Stderr, err.Error())
			os.Exit(1)
		}
		err = kubernetes.Upgrade(kubernetes.UpgradeConfig{
			RuntimeVersion:   upgradeRuntimeVersion,
			DashboardVersion: upgradeDashboardVersion,
			Args:             values,
			Timeout:          timeout,
			ImageRegistryURI: imageRegistryURI,
			ImageVariant:     upgradeImageVariant,
		})
		if err != nil {
			print.FailureStatusEvent(os.Stderr, "Failed to upgrade Dapr: %s", err)
			os.Exit(1)
		}
		print.SuccessStatusEvent(os.Stdout, "Dapr control plane successfully upgraded to version %s. Make sure your deployments are restarted to pick up the latest sidecar version.", upgradeRuntimeVersion)
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		kubernetes.CheckForCertExpiry()
	},
}
View Source
var VersionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the Dapr runtime and CLI version",
	Example: `
# Version for Dapr
dapr version --output json
`,
	Run: func(cmd *cobra.Command, args []string) {
		if output != "" && output != "json" {
			print.FailureStatusEvent(os.Stdout, "An invalid output format was specified.")
			os.Exit(1)
		}
		switch output {
		case "":

			fmt.Printf(cliVersionTemplateString, daprVer.CliVersion, daprVer.RuntimeVersion)
		case "json":

			b, err := json.Marshal(daprVer)
			if err != nil {
				print.FailureStatusEvent(os.Stderr, err.Error())
				os.Exit(1)
			}
			fmt.Printf("%s\n", string(b))
		default:

			os.Exit(1)
		}
	},
}

Functions

func Execute

func Execute(version, apiVersion string)

Execute adds all child commands to the root command.

func RenewCertificateCmd added in v1.7.0

func RenewCertificateCmd() *cobra.Command

Types

This section is empty.

Jump to

Keyboard shortcuts

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