Esempio n. 1
0
package config

import (
	"fmt"
	"io"

	"github.com/spf13/cobra"
	"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

var (
	delete_context_example = templates.Examples(`
		# Delete the context for the minikube cluster
		kubectl config delete-context minikube`)
)

func NewCmdConfigDeleteContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "delete-context NAME",
		Short:   "Delete the specified context from the kubeconfig",
		Long:    "Delete the specified context from the kubeconfig",
		Example: delete_context_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := runDeleteContext(out, configAccess, cmd)
			cmdutil.CheckErr(err)
		},
	}
Esempio n. 2
0
	run_example = templates.Examples(`
		# Start a single instance of nginx.
		kubectl run nginx --image=nginx

		# Start a single instance of hazelcast and let the container expose port 5701 .
		kubectl run hazelcast --image=hazelcast --port=5701

		# Start a single instance of hazelcast and set environment variables "DNS_DOMAIN=cluster" and "POD_NAMESPACE=default" in the container.
		kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"

		# Start a replicated instance of nginx.
		kubectl run nginx --image=nginx --replicas=5

		# Dry run. Print the corresponding API objects without creating them.
		kubectl run nginx --image=nginx --dry-run

		# Start a single instance of nginx, but overload the spec of the deployment with a partial set of values parsed from JSON.
		kubectl run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'

		# Start a pod of busybox and keep it in the foreground, don't restart it if it exits.
		kubectl run -i -t busybox --image=busybox --restart=Never

		# Start the nginx container using the default command, but use custom arguments (arg1 .. argN) for that command.
		kubectl run nginx --image=nginx -- <arg1> <arg2> ... <argN>

		# Start the nginx container using a different command and custom arguments.
		kubectl run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>

		# Start the perl container to compute π to 2000 places and print it out.
		kubectl run pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'

		# Start the cron job to compute π to 2000 places and print it out every 5 minutes.
		kubectl run pi --schedule="0/5 * * * ?" --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)'`)
		will first check for an exact match on TYPE and NAME_PREFIX. If no such resource
		exists, it will output details for every resource that has a name prefixed with NAME_PREFIX.

		` + valid_resources)

	describe_example = templates.Examples(`
		# Describe a node
		kubectl describe nodes kubernetes-node-emt8.c.myproject.internal

		# Describe a pod
		kubectl describe pods/nginx

		# Describe a pod identified by type and name in "pod.json"
		kubectl describe -f pod.json

		# Describe all pods
		kubectl describe pods

		# Describe pods by label name=myLabel
		kubectl describe po -l name=myLabel

		# Describe all pods managed by the 'frontend' replication controller (rc-created pods
		# get the name of the rc as a prefix in the pod the name).
		kubectl describe pods frontend`)
)

func NewCmdDescribe(f cmdutil.Factory, out, cmdErr io.Writer) *cobra.Command {
	options := &resource.FilenameOptions{}
	describerSettings := &kubectl.DescriberSettings{}
Esempio n. 4
0
	Infos   []*resource.Info

	Out io.Writer
}

var (
	pause_long = templates.LongDesc(`
		Mark the provided resource as paused

		Paused resources will not be reconciled by a controller.
		Use \"kubectl rollout resume\" to resume a paused resource.
		Currently only deployments support being paused.`)

	pause_example = templates.Examples(`
		# Mark the nginx deployment as paused. Any current state of
		# the deployment will continue its function, new updates to the deployment will not
		# have an effect as long as the deployment is paused.
		kubectl rollout pause deployment/nginx`)
)

func NewCmdRolloutPause(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &PauseConfig{}

	validArgs := []string{"deployment"}
	argAliases := kubectl.ResourceAliases(validArgs)

	cmd := &cobra.Command{
		Use:     "pause RESOURCE",
		Short:   "Mark the provided resource as paused",
		Long:    pause_long,
		Example: pause_example,
Esempio n. 5
0
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/runtime/schema"
)

var (
	create_long = templates.LongDesc(`
		Create a resource by filename or stdin.

		JSON and YAML formats are accepted.`)

	create_example = templates.Examples(`
		# Create a pod using the data in pod.json.
		kubectl create -f ./pod.json

		# Create a pod based on the JSON passed into stdin.
		cat pod.json | kubectl create -f -

		# Edit the data in docker-registry.yaml in JSON using the v1 API format then create the resource using the edited data.
		kubectl create -f docker-registry.yaml --edit --output-version=v1 -o json`)
)

func NewCmdCreate(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
	options := &resource.FilenameOptions{}

	cmd := &cobra.Command{
		Use:     "create -f FILENAME",
		Short:   "Create a resource by filename or stdin",
		Long:    create_long,
		Example: create_example,
		Run: func(cmd *cobra.Command, args []string) {
type createContextOptions struct {
	configAccess clientcmd.ConfigAccess
	name         string
	cluster      flag.StringFlag
	authInfo     flag.StringFlag
	namespace    flag.StringFlag
}

var (
	create_context_long = templates.LongDesc(`
		Sets a context entry in kubeconfig

		Specifying a name that already exists will merge new fields on top of existing values for those fields.`)

	create_context_example = templates.Examples(`
		# Set the user field on the gce context entry without touching other values
		kubectl config set-context gce --user=cluster-admin`)
)

func NewCmdConfigSetContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &createContextOptions{configAccess: configAccess}

	cmd := &cobra.Command{
		Use:     fmt.Sprintf("set-context NAME [--%v=cluster_nickname] [--%v=user_nickname] [--%v=namespace]", clientcmd.FlagClusterName, clientcmd.FlagAuthInfoName, clientcmd.FlagNamespace),
		Short:   "Sets a context entry in kubeconfig",
		Long:    create_context_long,
		Example: create_context_example,
		Run: func(cmd *cobra.Command, args []string) {
			if !options.complete(cmd) {
				return
			}
Esempio n. 7
0
var (
	image_resources = `
  	pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs)`

	image_long = templates.LongDesc(`
		Update existing container image(s) of resources.

		Possible resources include (case insensitive):
		` + image_resources)

	image_example = templates.Examples(`
		# Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
		kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1

		# Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
		kubectl set image deployments,rc nginx=nginx:1.9.1 --all

		# Update image of all containers of daemonset abc to 'nginx:1.9.1'
		kubectl set image daemonset abc *=nginx:1.9.1

		# Print result (in yaml format) of updating nginx container image from local file, without hitting the server
		kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml`)
)

func NewCmdImage(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
	options := &ImageOptions{
		Out: out,
		Err: err,
	}

	cmd := &cobra.Command{
		Use:     "image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N",
Esempio n. 8
0
	// joining API server. See `apis/federation.ClusterSpec` for
	// details.
	// TODO(madhusudancs): Make this value customizable.
	defaultClientCIDR = "0.0.0.0/0"
)

var (
	join_long = templates.LongDesc(`
		Join a cluster to a federation.

        Current context is assumed to be a federation API
        server. Please use the --context flag otherwise.`)
	join_example = templates.Examples(`
		# Join a cluster to a federation by specifying the
		# cluster name and the context name of the federation
		# control plane's host cluster. Cluster name must be
		# a valid RFC 1123 subdomain name. Cluster context
		# must be specified if the cluster name is different
		# than the cluster's context in the local kubeconfig.
		kubectl join foo --host-cluster-context=bar`)
)

// NewCmdJoin defines the `join` command that joins a cluster to a
// federation.
func NewCmdJoin(f cmdutil.Factory, cmdOut io.Writer, config util.AdminConfig) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "join CLUSTER_NAME --host-cluster-context=HOST_CONTEXT",
		Short:   "Join a cluster to a federation",
		Long:    join_long,
		Example: join_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := joinFederation(f, cmdOut, config, cmd, args)
Esempio n. 9
0
	coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/client/unversioned/remotecommand"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	remotecommandserver "k8s.io/kubernetes/pkg/kubelet/server/remotecommand"
	"k8s.io/kubernetes/pkg/util/interrupt"
	"k8s.io/kubernetes/pkg/util/term"
)

var (
	exec_example = templates.Examples(`
		# Get output from running 'date' from pod 123456-7890, using the first container by default
		kubectl exec 123456-7890 date

		# Get output from running 'date' in ruby-container from pod 123456-7890
		kubectl exec 123456-7890 -c ruby-container date

		# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890
		# and sends stdout/stderr from 'bash' back to the client
		kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il`)
)

const (
	execUsageStr = "expected 'exec POD_NAME COMMAND [ARG1] [ARG2] ... [ARGN]'.\nPOD_NAME and COMMAND are required arguments for the exec command"
)

func NewCmdExec(f cmdutil.Factory, cmdIn io.Reader, cmdOut, cmdErr io.Writer) *cobra.Command {
	options := &ExecOptions{
		StreamOptions: StreamOptions{
			In:  cmdIn,
			Out: cmdOut,
Esempio n. 10
0
	replace_long = templates.LongDesc(`
		Replace a resource by filename or stdin.

		JSON and YAML formats are accepted. If replacing an existing resource, the
		complete resource spec must be provided. This can be obtained by

		    $ kubectl get TYPE NAME -o yaml

		Please refer to the models in https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html to find if a field is mutable.`)

	replace_example = templates.Examples(`
		# Replace a pod using the data in pod.json.
		kubectl replace -f ./pod.json

		# Replace a pod based on the JSON passed into stdin.
		cat pod.json | kubectl replace -f -

		# Update a single-container pod's image version (tag) to v4
		kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -

		# Force replace, delete and then re-create the resource
		kubectl replace --force -f ./pod.json`)
)

func NewCmdReplace(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &resource.FilenameOptions{}

	cmd := &cobra.Command{
		Use: "replace -f FILENAME",
		// update is deprecated.
		Aliases: []string{"update"},
		Short:   "Replace a resource by filename or stdin",
Esempio n. 11
0
		of the --template flag, you can filter the attributes of the fetched resource(s).`)

	get_example = templates.Examples(`
		# List all pods in ps output format.
		kubectl get pods

		# List all pods in ps output format with more information (such as node name).
		kubectl get pods -o wide

		# List a single replication controller with specified NAME in ps output format.
		kubectl get replicationcontroller web

		# List a single pod in JSON output format.
		kubectl get -o json pod web-pod-13je7

		# List a pod identified by type and name specified in "pod.yaml" in JSON output format.
		kubectl get -f pod.yaml -o json

		# Return only the phase value of the specified pod.
		kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}

		# List all replication controllers and services together in ps output format.
		kubectl get rc,services

		# List one or more resources by their type and names.
		kubectl get rc/web service/frontend pods/web-pod-13je7

		# List all resources with different types.
		kubectl get all`)
)
Esempio n. 12
0
	ResourceName string
	Selector     string
	NodeClient   coreclient.NodesGetter
	Client       *metricsutil.HeapsterMetricsClient
	Printer      *metricsutil.TopCmdPrinter
}

var (
	topNodeLong = templates.LongDesc(`
		Display Resource (CPU/Memory/Storage) usage of nodes.

		The top-node command allows you to see the resource consumption of nodes.`)

	topNodeExample = templates.Examples(`
		  # Show metrics for all nodes
		  kubectl top node

		  # Show metrics for a given node
		  kubectl top node NODE_NAME`)
)

func NewCmdTopNode(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &TopNodeOptions{}

	cmd := &cobra.Command{
		Use:     "node [NAME | -l label]",
		Short:   "Display Resource (CPU/Memory/Storage) usage of nodes",
		Long:    topNodeLong,
		Example: topNodeExample,
		Run: func(cmd *cobra.Command, args []string) {
			if err := options.Complete(f, cmd, args, out); err != nil {
				cmdutil.CheckErr(err)
		},
	}
	cmd.AddCommand(NewCmdCreateServiceClusterIP(f, cmdOut))
	cmd.AddCommand(NewCmdCreateServiceNodePort(f, cmdOut))
	cmd.AddCommand(NewCmdCreateServiceLoadBalancer(f, cmdOut))

	return cmd
}

var (
	serviceClusterIPLong = templates.LongDesc(`
    Create a clusterIP service with the specified name.`)

	serviceClusterIPExample = templates.Examples(`
    # Create a new clusterIP service named my-cs
    kubectl create service clusterip my-cs --tcp=5678:8080

    # Create a new clusterIP service named my-cs (in headless mode)
    kubectl create service clusterip my-cs --clusterip="None"`)
)

func addPortFlags(cmd *cobra.Command) {
	cmd.Flags().StringSlice("tcp", []string{}, "Port pairs can be specified as '<port>:<targetPort>'.")
}

// NewCmdCreateServiceClusterIP is a command to create a clusterIP service
func NewCmdCreateServiceClusterIP(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run]",
		Short:   "Create a clusterIP service.",
		Long:    serviceClusterIPLong,
		Example: serviceClusterIPExample,
Esempio n. 14
0
		    $ kubectl proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/

		The above lets you 'curl localhost:8001/api/v1/pods'.

		To proxy the entire kubernetes api at a different root, use:

		    $ kubectl proxy --api-prefix=/custom/

		The above lets you 'curl localhost:8001/custom/api/v1/pods'`)

	proxy_example = templates.Examples(`
		# Run a proxy to kubernetes apiserver on port 8011, serving static content from ./local/www/
		kubectl proxy --port=8011 --www=./local/www/

		# Run a proxy to kubernetes apiserver on an arbitrary local port.
		# The chosen port for the server will be output to stdout.
		kubectl proxy --port=0

		# Run a proxy to kubernetes apiserver, changing the api prefix to k8s-api
		# This makes e.g. the pods api available at localhost:8011/k8s-api/v1/pods/
		kubectl proxy --api-prefix=/k8s-api`)
)

func NewCmdProxy(f cmdutil.Factory, out io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix]",
		Short:   "Run a proxy to the Kubernetes API server",
		Long:    proxy_long,
		Example: proxy_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := RunProxy(f, out, cmd)
Esempio n. 15
0
	convert_long = templates.LongDesc(`
		Convert config files between different API versions. Both YAML
		and JSON formats are accepted.

		The command takes filename, directory, or URL as input, and convert it into format
		of version specified by --output-version flag. If target version is not specified or
		not supported, convert to latest version.

		The default output will be printed to stdout in YAML format. One can use -o option
		to change to output destination.`)

	convert_example = templates.Examples(`
		# Convert 'pod.yaml' to latest version and print to stdout.
		kubectl convert -f pod.yaml

		# Convert the live state of the resource specified by 'pod.yaml' to the latest version
		# and print to stdout in json format.
		kubectl convert -f pod.yaml --local -o json

		# Convert all files under current directory to latest version and create them all.
		kubectl convert -f . | kubectl create -f -`)
)

// NewCmdConvert creates a command object for the generic "convert" action, which
// translates the config file into a given version.
func NewCmdConvert(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &ConvertOptions{}

	cmd := &cobra.Command{
		Use:     "convert -f FILENAME",
		Short:   "Convert config files between different API versions",
		Long:    convert_long,
Esempio n. 16
0
	kDaemonsetFatal      = "DaemonSet-managed pods (use --ignore-daemonsets to ignore)"
	kDaemonsetWarning    = "Ignoring DaemonSet-managed pods"
	kLocalStorageFatal   = "pods with local storage (use --delete-local-data to override)"
	kLocalStorageWarning = "Deleting pods with local storage"
	kUnmanagedFatal      = "pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet (use --force to override)"
	kUnmanagedWarning    = "Deleting pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet"
	kMaxNodeUpdateRetry  = 10
)

var (
	cordon_long = templates.LongDesc(`
		Mark node as unschedulable.`)

	cordon_example = templates.Examples(`
		# Mark node "foo" as unschedulable.
		kubectl cordon foo`)
)

func NewCmdCordon(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &DrainOptions{factory: f, out: out}

	cmd := &cobra.Command{
		Use:     "cordon NODE",
		Short:   "Mark node as unschedulable",
		Long:    cordon_long,
		Example: cordon_example,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(options.SetupDrain(cmd, args))
			cmdutil.CheckErr(options.RunCordonOrUncordon(true))
		},
Esempio n. 17
0
		* It is intended to store non-identifying auxiliary data, especially data manipulated by tools and system extensions.
		* If --overwrite is true, then existing annotations can be overwritten, otherwise attempting to overwrite an annotation will result in an error.
		* If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.

		` + valid_resources)

	annotate_example = templates.Examples(`
    # Update pod 'foo' with the annotation 'description' and the value 'my frontend'.
    # If the same annotation is set multiple times, only the last value will be applied
    kubectl annotate pods foo description='my frontend'

    # Update a pod identified by type and name in "pod.json"
    kubectl annotate -f pod.json description='my frontend'

    # Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value.
    kubectl annotate --overwrite pods foo description='my frontend running nginx'

    # Update all pods in the namespace
    kubectl annotate pods --all description='my frontend running nginx'

    # Update pod 'foo' only if the resource is unchanged from version 1.
    kubectl annotate pods foo description='my frontend running nginx' --resource-version=1

    # Update pod 'foo' by removing an annotation named 'description' if it exists.
    # Does not require the --overwrite flag.
    kubectl annotate pods foo description-`)
)

func NewCmdAnnotate(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &AnnotateOptions{}

	// retrieve a list of handled resources from printer as valid args
Esempio n. 18
0
		Perform a rolling update of the given ReplicationController.

		Replaces the specified replication controller with a new replication controller by updating one pod at a time to use the
		new PodTemplate. The new-controller.json must specify the same namespace as the
		existing replication controller and overwrite at least one (common) label in its replicaSelector.

		![Workflow](http://kubernetes.io/images/docs/kubectl_rollingupdate.svg)`)

	rollingUpdate_example = templates.Examples(`
		# Update pods of frontend-v1 using new replication controller data in frontend-v2.json.
		kubectl rolling-update frontend-v1 -f frontend-v2.json

		# Update pods of frontend-v1 using JSON data passed into stdin.
		cat frontend-v2.json | kubectl rolling-update frontend-v1 -f -

		# Update the pods of frontend-v1 to frontend-v2 by just changing the image, and switching the
		# name of the replication controller.
		kubectl rolling-update frontend-v1 frontend-v2 --image=image:v2

		# Update the pods of frontend by just changing the image, and keeping the old name.
		kubectl rolling-update frontend --image=image:v2

		# Abort and reverse an existing rollout in progress (from frontend-v1 to frontend-v2).
		kubectl rolling-update frontend-v1 frontend-v2 --rollback`)
)

var (
	updatePeriod, _ = time.ParseDuration("1m0s")
	timeout, _      = time.ParseDuration("5m0s")
	pollInterval, _ = time.ParseDuration("3s")
)
Esempio n. 19
0
import (
	"errors"
	"fmt"
	"io"

	"github.com/spf13/cobra"

	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
	"k8s.io/kubernetes/pkg/client/unversioned/clientcmd"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

var (
	use_context_example = templates.Examples(`
		# Use the context for the minikube cluster
		kubectl config use-context minikube`)
)

type useContextOptions struct {
	configAccess clientcmd.ConfigAccess
	contextName  string
}

func NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &useContextOptions{configAccess: configAccess}

	cmd := &cobra.Command{
		Use:     "use-context CONTEXT_NAME",
		Short:   "Sets the current-context in a kubeconfig file",
		Long:    `Sets the current-context in a kubeconfig file`,
Esempio n. 20
0
	"github.com/spf13/cobra"
)

var (
	status_long = templates.LongDesc(`
		Show the status of the rollout.

		By default 'rollout status' will watch the status of the latest rollout
		until it's done. If you don't want to wait for the rollout to finish then
		you can use --watch=false. Note that if a new rollout starts in-between, then
		'rollout status' will continue watching the latest revision. If you want to
		pin to a specific revision and abort if it is rolled over by another revision,
		use --revision=N where N is the revision you need to watch for.`)

	status_example = templates.Examples(`
		# Watch the rollout status of a deployment
		kubectl rollout status deployment/nginx`)
)

func NewCmdRolloutStatus(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &resource.FilenameOptions{}

	validArgs := []string{"deployment"}
	argAliases := kubectl.ResourceAliases(validArgs)

	cmd := &cobra.Command{
		Use:     "status (TYPE NAME | TYPE/NAME) [flags]",
		Short:   "Show the status of the rollout",
		Long:    status_long,
		Example: status_example,
		Run: func(cmd *cobra.Command, args []string) {
Esempio n. 21
0
	insecureSkipTLSVerify flag.Tristate
	certificateAuthority  flag.StringFlag
	embedCAData           flag.Tristate
}

var (
	create_cluster_long = templates.LongDesc(`
		Sets a cluster entry in kubeconfig.

		Specifying a name that already exists will merge new fields on top of existing values for those fields.`)

	create_cluster_example = templates.Examples(`
		# Set only the server field on the e2e cluster entry without touching other values.
		kubectl config set-cluster e2e --server=https://1.2.3.4

		# Embed certificate authority data for the e2e cluster entry
		kubectl config set-cluster e2e --certificate-authority=~/.kube/e2e/kubernetes.ca.crt

		# Disable cert checking for the dev cluster entry
		kubectl config set-cluster e2e --insecure-skip-tls-verify=true`)
)

func NewCmdConfigSetCluster(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &createClusterOptions{configAccess: configAccess}

	cmd := &cobra.Command{
		Use:     fmt.Sprintf("set-cluster NAME [--%v=server] [--%v=path/to/certificate/authority] [--%v=true]", clientcmd.FlagAPIServer, clientcmd.FlagCAFile, clientcmd.FlagInsecure),
		Short:   "Sets a cluster entry in kubeconfig",
		Long:    create_cluster_long,
		Example: create_cluster_example,
		Run: func(cmd *cobra.Command, args []string) {
)

var (
	resources_long = templates.LongDesc(`
		Specify compute resource requirements (cpu, memory) for any resource that defines a pod template.  If a pod is successfully scheduled, it is guaranteed the amount of resource requested, but may burst up to its specified limits.

		for each compute resource, if a limit is specified and a request is omitted, the request will default to the limit.
		
		Possible resources include (case insensitive): %s.`)

	resources_example = templates.Examples(`
		# Set a deployments nginx container cpu limits to "200m" and memory to "512Mi"
		kubectl set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi

		# Set the resource request and limits for all containers in nginx
		kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi

		# Remove the resource requests for resources on containers in nginx
		kubectl set resources deployment nginx --limits=cpu=0,memory=0 --requests=cpu=0,memory=0

		# Print the result (in yaml format) of updating nginx container limits from a local, without hitting the server
		kubectl set resources -f path/to/file.yaml --limits=cpu=200m,memory=512Mi --local -o yaml`)
)

// ResourcesOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags
type ResourcesOptions struct {
	resource.FilenameOptions

	f                 cmdutil.Factory
	Mapper            meta.RESTMapper
	Typer             runtime.ObjectTyper
		Create a secret based on a file, directory, or specified literal value.

		A single secret may package one or more key/value pairs.

		When creating a secret based on a file, the key will default to the basename of the file, and the value will
		default to the file content.  If the basename is an invalid key, you may specify an alternate key.

		When creating a secret based on a directory, each file whose basename is a valid key in the directory will be
		packaged into the secret.  Any directory entries except regular files are ignored (e.g. subdirectories,
		symlinks, devices, pipes, etc).`)

	secretExample = templates.Examples(`
	  # Create a new secret named my-secret with keys for each file in folder bar
	  kubectl create secret generic my-secret --from-file=path/to/bar

	  # Create a new secret named my-secret with specified keys instead of names on disk
	  kubectl create secret generic my-secret --from-file=ssh-privatekey=~/.ssh/id_rsa --from-file=ssh-publickey=~/.ssh/id_rsa.pub

	  # Create a new secret named my-secret with key1=supersecret and key2=topsecret
	  kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret`)
)

// NewCmdCreateSecretGeneric is a command to create generic secrets from files, directories, or literal values
func NewCmdCreateSecretGeneric(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]",
		Short:   "Create a secret from a local file, directory or literal value",
		Long:    secretLong,
		Example: secretExample,
		Run: func(cmd *cobra.Command, args []string) {
			err := CreateSecretGeneric(f, cmdOut, cmd, args)
Esempio n. 24
0
	builder *resource.Builder
	mapper  meta.RESTMapper
	encoder runtime.Encoder
}

var (
	selectorLong = templates.LongDesc(`
		Set the selector on a resource. Note that the new selector will overwrite the old selector if the resource had one prior to the invocation
		of 'set selector'.

		A selector must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
		If --resource-version is specified, then updates will use this resource version, otherwise the existing resource-version will be used.
        Note: currently selectors can only be set on Service objects.`)
	selectorExample = templates.Examples(`
        # set the labels and selector before creating a deployment/service pair.
        kubectl create service clusterip my-svc -o yaml --dry-run | kubectl set selector --local -f - 'environment=qa' -o yaml | kubectl create -f -
        kubectl create deployment my-dep -o yaml --dry-run | kubectl label --local -f - environment=qa -o yaml | kubectl create -f -`)
)

// NewCmdSelector is the "set selector" command.
func NewCmdSelector(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &SelectorOptions{
		out: out,
	}

	cmd := &cobra.Command{
		Use:     "selector (-f FILENAME | TYPE NAME) EXPRESSIONS [--resource-version=version]",
		Short:   "Set the selector on a resource",
		Long:    fmt.Sprintf(selectorLong),
		Example: selectorExample,
		Run: func(cmd *cobra.Command, args []string) {
Esempio n. 25
0
var (
	taint_long = templates.LongDesc(`
		Update the taints on one or more nodes.

		* A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect.
		* The key must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
		* The value must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
		* The effect must be NoSchedule or PreferNoSchedule.
		* Currently taint can only apply to node.`)

	taint_example = templates.Examples(`
		# Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'.
		# If a taint with that key and effect already exists, its value is replaced as specified.
		kubectl taint nodes foo dedicated=special-user:NoSchedule

		# Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists.
		kubectl taint nodes foo dedicated:NoSchedule-

		# Remove from node 'foo' all the taints with key 'dedicated'
		kubectl taint nodes foo dedicated-`)
)

func NewCmdTaint(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &TaintOptions{}

	validArgs := []string{"node"}
	argAliases := kubectl.ResourceAliases(validArgs)

	cmd := &cobra.Command{
		Use:     "taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N",
		Short:   "Update the taints on one or more nodes",
Esempio n. 26
0
		Possible resources include (case insensitive):

		` + expose_resources)

	expose_example = templates.Examples(`
		# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
		kubectl expose rc nginx --port=80 --target-port=8000

		# Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml", which serves on port 80 and connects to the containers on port 8000.
		kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000

		# Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
		kubectl expose pod valid-pod --port=444 --name=frontend

		# Create a second service based on the above service, exposing the container port 8443 as port 443 with the name "nginx-https"
		kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https

		# Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
		kubectl expose rc streamer --port=4100 --protocol=udp --name=video-stream

		# Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on port 8000.
		kubectl expose rs nginx --port=80 --target-port=8000

		# Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.
		kubectl expose deployment nginx --port=80 --target-port=8000`)
)

func NewCmdExposeService(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &resource.FilenameOptions{}
Esempio n. 27
0
	Infos       []*resource.Info
	ToRevision  int64
	DryRun      bool

	Out io.Writer
}

var (
	undo_long = templates.LongDesc(`
		Rollback to a previous rollout.`)

	undo_example = templates.Examples(`
		# Rollback to the previous deployment
		kubectl rollout undo deployment/abc

		# Rollback to deployment revision 3
		kubectl rollout undo deployment/abc --to-revision=3

		# Rollback to the previous deployment with dry-run
		kubectl rollout undo --dry-run=true deployment/abc`)
)

func NewCmdRolloutUndo(f cmdutil.Factory, out io.Writer) *cobra.Command {
	options := &UndoOptions{}

	validArgs := []string{"deployment"}
	argAliases := kubectl.ResourceAliases(validArgs)

	cmd := &cobra.Command{
		Use:     "undo (TYPE NAME | TYPE/NAME) [flags]",
		Short:   "Undo a previous rollout",
Esempio n. 28
0
	apply_long = templates.LongDesc(`
		Apply a configuration to a resource by filename or stdin.
		This resource will be created if it doesn't exist yet.
		To use 'apply', always create the resource initially with either 'apply' or 'create --save-config'.

		JSON and YAML formats are accepted.

		Alpha Disclaimer: the --prune functionality is not yet complete. Do not use unless you are aware of what the current state is. See https://issues.k8s.io/34274.`)

	apply_example = templates.Examples(`
		# Apply the configuration in pod.json to a pod.
		kubectl apply -f ./pod.json

		# Apply the JSON passed into stdin to a pod.
		cat pod.json | kubectl apply -f -

		# Note: --prune is still in Alpha
		# Apply the configuration in manifest.yaml that matches label app=nginx and delete all the other resources that are not in the file and match label app=nginx.
		kubectl apply --prune -f manifest.yaml -l app=nginx

		# Apply the configuration in manifest.yaml and delete all the other configmaps that are not in the file.
		kubectl apply --prune -f manifest.yaml --all --prune-whitelist=core/v1/ConfigMap`)
)

func NewCmdApply(f cmdutil.Factory, out io.Writer) *cobra.Command {
	var options ApplyOptions

	cmd := &cobra.Command{
		Use:     "apply -f FILENAME",
		Short:   "Apply a configuration to a resource by filename or stdin",
		Long:    apply_long,
Esempio n. 29
0
	RESTClient    *restclient.RESTClient
	Config        *restclient.Config
	PodClient     coreclient.PodsGetter
	Ports         []string
	PortForwarder portForwarder
	StopChannel   chan struct{}
	ReadyChannel  chan struct{}
}

var (
	portforward_example = templates.Examples(`
		# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
		kubectl port-forward mypod 5000 6000

		# Listen on port 8888 locally, forwarding to 5000 in the pod
		kubectl port-forward mypod 8888:5000

		# Listen on a random port locally, forwarding to 5000 in the pod
		kubectl port-forward mypod :5000

		# Listen on a random port locally, forwarding to 5000 in the pod
		kubectl port-forward  mypod 0:5000`)
)

func NewCmdPortForward(f cmdutil.Factory, cmdOut, cmdErr io.Writer) *cobra.Command {
	opts := &PortForwardOptions{
		PortForwarder: &defaultPortForwarder{
			cmdOut: cmdOut,
			cmdErr: cmdErr,
		},
	}
	cmd := &cobra.Command{
Esempio n. 30
0
	"github.com/spf13/cobra"

	"k8s.io/kubernetes/pkg/kubectl"
	"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

var (
	pdbLong = templates.LongDesc(`
		Create a pod disruption budget with the specified name, selector, and desired minimum available pods`)

	pdbExample = templates.Examples(`
		# Create a pod disruption budget named my-pdb that will select all pods with the app=rails label
		# and require at least one of them being available at any point in time.
		kubectl create poddisruptionbudget my-pdb --selector=app=rails --min-available=1

		# Create a pod disruption budget named my-pdb that will select all pods with the app=nginx label
		# and require at least half of the pods selected to be available at any point in time.
		kubectl create pdb my-pdb --selector=app=nginx --min-available=50%`)
)

// NewCmdCreatePodDisruptionBudget is a macro command to create a new pod disruption budget.
func NewCmdCreatePodDisruptionBudget(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "poddisruptionbudget NAME --selector=SELECTOR --min-available=N [--dry-run]",
		Aliases: []string{"pdb"},
		Short:   "Create a pod disruption budget with the specified name.",
		Long:    pdbLong,
		Example: pdbExample,
		Run: func(cmd *cobra.Command, args []string) {
			err := CreatePodDisruptionBudget(f, cmdOut, cmd, args)