예제 #1
0
func NewKubeadmCommand(f cmdutil.Factory, in io.Reader, out, err io.Writer) *cobra.Command {
	cmds := &cobra.Command{
		Use:   "kubeadm",
		Short: "kubeadm: easily bootstrap a secure Kubernetes cluster",
		Long: dedent.Dedent(`
			kubeadm: easily bootstrap a secure Kubernetes cluster.

			    ┌──────────────────────────────────────────────────────────┐
			    │ KUBEADM IS ALPHA, DO NOT USE IT FOR PRODUCTION CLUSTERS! │
			    │                                                          │
			    │ But, please try it out! Give us feedback at:             │
			    │ https://github.com/kubernetes/kubernetes/issues          │
			    │ and at-mention @kubernetes/sig-cluster-lifecycle         │
			    └──────────────────────────────────────────────────────────┘

			Example usage:

			    Create a two-machine cluster with one master (which controls the cluster),
			    and one node (where workloads, like pods and replica sets run).

			    ┌──────────────────────────────────────────────────────────┐
			    │  On the first machine                                    │
			    ├──────────────────────────────────────────────────────────┤
			    │ master# kubeadm init                                     │
			    └──────────────────────────────────────────────────────────┘

			    ┌──────────────────────────────────────────────────────────┐
			    │ On the second machine                                    │
			    ├──────────────────────────────────────────────────────────┤
			    │ node# kubeadm join --token=<token> <ip-of-master>        │
			    └──────────────────────────────────────────────────────────┘

			    You can then repeat the second step on as many other machines as you like.

		`),
	}
	// TODO(phase2+) figure out how to avoid running as root
	//
	// TODO(phase2) detect interactive vs non-interactive use and adjust output accordingly
	// i.e. make it automation friendly
	//
	// TODO(phase2) create an abstraction that defines files and the content that needs to
	// be written to disc and write it all in one go at the end as we have a lot of
	// crapy little files written from different parts of this code; this could also
	// be useful for testing
	// by having this model we can allow users to create some files before `kubeadm init` runs, e.g. PKI assets, we
	// would then be able to look at files users has given an diff or validate if those are sane, we could also warn
	// if any of the files had been deprecated

	cmds.ResetFlags()
	cmds.SetGlobalNormalizationFunc(flag.WarnWordSepNormalizeFunc)

	cmds.AddCommand(NewCmdInit(out))
	cmds.AddCommand(NewCmdJoin(out))
	cmds.AddCommand(NewCmdReset(out))
	cmds.AddCommand(NewCmdToken(out))
	cmds.AddCommand(NewCmdVersion(out))

	return cmds
}
예제 #2
0
func TestLoadFromBytesWithInvalidName(t *testing.T) {
	conf := dedent.Dedent(`
		image=image:latest:
		  image: imagename
		  dockerfile: what
	`)

	_, err := LoadFromBytes([]byte(conf))
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "invalid character \":\"")
}
예제 #3
0
func TestLoadFromBytes(t *testing.T) {
	conf := dedent.Dedent(`
		meta:
		  default: alias-def

		image=image-def:
		  image: imagename
		  dockerfile: what
		  args:
		    VERSION: "3.3.3"
		    DEBUG: 'true'

		mount=vol-def:
		  bind: dist/
		  path: /target

		job=cmd-def:
		  use: image-dev
		  mounts: [vol-def]

		alias=alias-def:
		  tasks: [vol-def, cmd-def]

		compose=compose-def:
		  files: ['foo.yml']
	`)

	config, err := LoadFromBytes([]byte(conf))
	assert.Nil(t, err)
	assert.Equal(t, 5, len(config.Resources))
	assert.IsType(t, &ImageConfig{}, config.Resources["image-def"])
	assert.IsType(t, &MountConfig{}, config.Resources["vol-def"])
	assert.IsType(t, &JobConfig{}, config.Resources["cmd-def"])
	assert.IsType(t, &AliasConfig{}, config.Resources["alias-def"])

	// Test default value and override
	imageConf := config.Resources["image-def"].(*ImageConfig)
	assert.Equal(t, "what", imageConf.Dockerfile)
	assert.Equal(t, map[string]string{
		"VERSION": "3.3.3",
		"DEBUG":   "true",
	}, imageConf.Args)

	mountConf := config.Resources["vol-def"].(*MountConfig)
	assert.Equal(t, "dist/", mountConf.Bind)
	assert.Equal(t, "/target", mountConf.Path)
	assert.Equal(t, false, mountConf.ReadOnly)

	aliasConf := config.Resources["alias-def"].(*AliasConfig)
	assert.Equal(t, []string{"vol-def", "cmd-def"}, aliasConf.Tasks)

	assert.Equal(t, &MetaConfig{Default: "alias-def"}, config.Meta)
}
예제 #4
0
func TestLoadFromBytesWithReservedName(t *testing.T) {
	conf := dedent.Dedent(`
		image=image-def:
		  image: imagename
		  dockerfile: what

		mount=autoclean:
		  path: dist/
		  mount: /target
	`)

	_, err := LoadFromBytes([]byte(conf))
	assert.Error(t, err)
	assert.Contains(t, err.Error(), "\"autoclean\" is reserved")
}
예제 #5
0
func NewCmdTokenGenerate(out io.Writer) *cobra.Command {
	return &cobra.Command{
		Use:   "generate",
		Short: "Generate and print a bootstrap token, but do not create it on the server.",
		Long: dedent.Dedent(`
			This command will print out a randomly-generated bootstrap token that can be used with
			the "init" and "join" commands.

			You don't have to use this command in order to generate a token, you can do so
			yourself as long as it's in the format "<6 characters>:<16 characters>". This
			command is provided for convenience to generate tokens in that format.

			You can also use "kubeadm init" without specifying a token, and it will
			generate and print one for you.
		`),
		Run: func(cmd *cobra.Command, args []string) {
			err := RunGenerateToken(out)
			kubeadmutil.CheckErr(err)
		},
	}
}
예제 #6
0
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: dedent.Dedent(`
			To proxy all of the kubernetes api and nothing else, use:

			kubectl proxy --api-prefix=/

			To proxy only part of the kubernetes api and also some static files:

			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'
			`),
		Example: proxy_example,
		Run: func(cmd *cobra.Command, args []string) {
			err := RunProxy(f, out, cmd)
			cmdutil.CheckErr(err)
		},
	}
	cmd.Flags().StringP("www", "w", "", "Also serve static files from the given directory under the specified prefix.")
	cmd.Flags().StringP("www-prefix", "P", "/static/", "Prefix to serve static files under, if static file directory is specified.")
	cmd.Flags().StringP("api-prefix", "", "/", "Prefix to serve the proxied API under.")
	cmd.Flags().String("accept-paths", kubectl.DefaultPathAcceptRE, "Regular expression for paths that the proxy should accept.")
	cmd.Flags().String("reject-paths", kubectl.DefaultPathRejectRE, "Regular expression for paths that the proxy should reject.")
	cmd.Flags().String("accept-hosts", kubectl.DefaultHostAcceptRE, "Regular expression for hosts that the proxy should accept.")
	cmd.Flags().String("reject-methods", kubectl.DefaultMethodRejectRE, "Regular expression for HTTP methods that the proxy should reject.")
	cmd.Flags().IntP("port", "p", default_port, "The port on which to run the proxy. Set to 0 to pick a random port.")
	cmd.Flags().StringP("address", "", "127.0.0.1", "The IP address on which to serve on.")
	cmd.Flags().Bool("disable-filter", false, "If true, disable request filtering in the proxy. This is dangerous, and can leave you vulnerable to XSRF attacks, when used with an accessible port.")
	cmd.Flags().StringP("unix-socket", "u", "", "Unix socket on which to run the proxy.")
	return cmd
}
예제 #7
0
func NewCmdCreateService(f *cmdutil.Factory, cmdOut, errOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "service",
		Short: "Create a service using specified subcommand.",
		Long:  "Create a service using specified subcommand.",
		Run:   cmdutil.DefaultSubCommandRun(errOut),
	}
	cmd.AddCommand(NewCmdCreateServiceClusterIP(f, cmdOut))
	cmd.AddCommand(NewCmdCreateServiceNodePort(f, cmdOut))
	cmd.AddCommand(NewCmdCreateServiceLoadBalancer(f, cmdOut))

	return cmd
}

var (
	serviceClusterIPLong = dedent.Dedent(`
                Create a clusterIP service with the specified name.`)

	serviceClusterIPExample = dedent.Dedent(`
                # 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 generic secrets from files, directories, or literal values
func NewCmdCreateServiceClusterIP(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
예제 #8
0
var patchTypes = map[string]api.PatchType{"json": api.JSONPatchType, "merge": api.MergePatchType, "strategic": api.StrategicMergePatchType}

// PatchOptions 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 PatchOptions struct {
	resource.FilenameOptions

	Local bool

	OutputFormat string
}

var (
	patch_long = dedent.Dedent(`
		Update field(s) of a resource using strategic merge patch

		JSON and YAML formats are accepted.

		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.`)
	patch_example = dedent.Dedent(`

		# Partially update a node using strategic merge patch
		kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'

		# Partially update a node identified by the type and name specified in "node.json" using strategic merge patch
		kubectl patch -f node.json -p '{"spec":{"unschedulable":true}}'

		# Update a container's image; spec.containers[*].name is required because it's a merge key
		kubectl patch pod valid-pod -p '{"spec":{"containers":[{"name":"kubernetes-serve-hostname","image":"new image"}]}}'

		# Update a container's image using a json patch with positional arrays
		kubectl patch pod valid-pod --type='json' -p='[{"op": "replace", "path": "/spec/containers/0/image", "value":"new image"}]'`)
예제 #9
0
	"k8s.io/kubernetes/cmd/kubeadm/app/discovery"
	kubemaster "k8s.io/kubernetes/cmd/kubeadm/app/master"
	"k8s.io/kubernetes/cmd/kubeadm/app/preflight"
	kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/runtime"
	netutil "k8s.io/kubernetes/pkg/util/net"
)

var (
	initDoneMsgf = dedent.Dedent(`
		Your Kubernetes master has initialized successfully!

		You should now deploy a pod network to the cluster.
		Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
		    http://kubernetes.io/docs/admin/addons/

		You can now join any number of machines by running the following on each node:

		kubeadm join --discovery %s
		`)
)

// NewCmdInit returns "kubeadm init" command.
func NewCmdInit(out io.Writer) *cobra.Command {
	versioned := &kubeadmapiext.MasterConfiguration{}
	api.Scheme.Default(versioned)
	cfg := kubeadmapi.MasterConfiguration{}
	api.Scheme.Convert(versioned, &cfg, nil)

	var cfgPath string
예제 #10
0
	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"

	kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
	kubenode "k8s.io/kubernetes/cmd/kubeadm/app/node"
	"k8s.io/kubernetes/cmd/kubeadm/app/preflight"
	kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/runtime"
)

var (
	joinDoneMsgf = dedent.Dedent(`
		Node join complete:
		* Certificate signing request sent to master and response
		  received.
		* Kubelet informed of new secure connection details.

		Run 'kubectl get nodes' on the master to see this machine join.
		`)
)

// NewCmdJoin returns "kubeadm join" command.
func NewCmdJoin(out io.Writer) *cobra.Command {
	cfg := &kubeadmapi.NodeConfiguration{}
	var skipPreFlight bool
	var cfgPath string
	cmd := &cobra.Command{
		Use:   "join",
		Short: "Run this on any machine you wish to join an existing cluster.",
		Run: func(cmd *cobra.Command, args []string) {
			j, err := NewJoin(cfgPath, args, cfg, skipPreFlight)
예제 #11
0
type fatal struct {
	string
}

const (
	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, or DaemonSet (use --force to override)"
	kUnmanagedWarning    = "Deleting pods not managed by ReplicationController, ReplicaSet, Job, or DaemonSet"
)

var (
	cordon_long = dedent.Dedent(`
		Mark node as unschedulable.
		`)
	cordon_example = dedent.Dedent(`
		# 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,
예제 #12
0
	"k8s.io/kubernetes/pkg/util/strategicpatch"
)

const (
	// maxPatchRetry is the maximum number of conflicts retry for during a patch operation before returning failure
	maxPatchRetry = 5
	// backOffPeriod is the period to back off when apply patch resutls in error.
	backOffPeriod = 1 * time.Second
	// how many times we can retry before back off
	triesBeforeBackOff = 1
)

var (
	apply_long = dedent.Dedent(`
		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.`)

	apply_example = dedent.Dedent(`
		# 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 -`)
)

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

	cmd := &cobra.Command{
예제 #13
0
파일: edit.go 프로젝트: ncdc/kubernetes
	"github.com/golang/glog"
	"github.com/spf13/cobra"
)

var (
	editLong = dedent.Dedent(`
		Edit a resource from the default editor.

		The edit command allows you to directly edit any API resource you can retrieve via the
		command line tools. It will open the editor defined by your KUBE_EDITOR, or EDITOR
		environment variables, or fall back to 'vi' for Linux or 'notepad' for Windows.
		You can edit multiple objects, although changes are applied one at a time. The command
		accepts filenames as well as command line arguments, although the files you point to must
		be previously saved versions of resources.

		The files to edit will be output in the default API version, or a version specified
		by --output-version. The default format is YAML - if you would like to edit in JSON
		pass -o json. The flag --windows-line-endings can be used to force Windows line endings,
		otherwise the default for your operating system will be used.

		In the event an error occurs while updating, a temporary file will be created on disk
		that contains your unapplied changes. The most common error when updating a resource
		is another editor changing the resource on the server. When this occurs, you will have
		to apply your changes to the newer version of the resource, or update your temporary
		saved copy to include the latest resource version.`)

	editExample = dedent.Dedent(`
		  # Edit the service named 'docker-registry':
		  kubectl edit svc/docker-registry

		  # Use an alternative editor
예제 #14
0
package cmd

import (
	"bytes"
	"io"

	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"

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

var (
	completion_long = dedent.Dedent(`
		Output shell completion code for the given shell (bash or zsh).

		This command prints shell code which must be evaluation to provide interactive
		completion of kubectl commands.
    `)

	completion_example = dedent.Dedent(`
		$ source <(kubectl completion bash)

		will load the kubectl completion code for bash. Note that this depends on the
		bash-completion framework. It must be sourced before sourcing the kubectl
		completion, e.g. on the Mac:

		$ brew install bash-completion
		$ source $(brew --prefix)/etc/bash_completion
		$ source <(kubectl completion bash)

		If you use zsh*, the following will load kubectl zsh completion:
package cmd

import (
	"fmt"
	"io"

	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"

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

var (
	namespaceLong = dedent.Dedent(`
		Create a namespace with the specified name.`)

	namespaceExample = dedent.Dedent(`
		  # Create a new namespace named my-namespace
		  kubectl create namespace my-namespace`)
)

// NewCmdCreateNamespace is a macro command to create a new namespace
func NewCmdCreateNamespace(f cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "namespace NAME [--dry-run]",
		Aliases: []string{"ns"},
		Short:   "Create a namespace with the specified name",
		Long:    namespaceLong,
		Example: namespaceExample,
		Run: func(cmd *cobra.Command, args []string) {
예제 #16
0
	taintsToAdd    []api.Taint
	taintsToRemove []api.Taint
	builder        *resource.Builder
	selector       string
	overwrite      bool
	all            bool
	f              cmdutil.Factory
	out            io.Writer
	cmd            *cobra.Command
}

var (
	taint_long = dedent.Dedent(`
		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 = dedent.Dedent(`
		# 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-`)
)
예제 #17
0
	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/client/restclient"
	"k8s.io/kubernetes/pkg/client/unversioned/portforward"
	"k8s.io/kubernetes/pkg/client/unversioned/remotecommand"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)

var (
	portforward_example = dedent.Dedent(`
		# 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 {
	cmd := &cobra.Command{
		Use:     "port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]",
		Short:   "Forward one or more local ports to a pod.",
		Long:    "Forward one or more local ports to a pod.",
		Example: portforward_example,
		Run: func(cmd *cobra.Command, args []string) {
			pf := &defaultPortForwarder{
예제 #18
0
// referencing the cmd.Flags()
type ResumeConfig struct {
	resource.FilenameOptions

	ResumeObject func(object runtime.Object) (bool, error)
	Mapper       meta.RESTMapper
	Typer        runtime.ObjectTyper
	Infos        []*resource.Info

	Out io.Writer
}

var (
	resume_long = dedent.Dedent(`
		Resume a paused resource

		Paused resources will not be reconciled by a controller. By resuming a
		resource, we allow it to be reconciled again.
		Currently only deployments support being resumed.`)

	resume_example = dedent.Dedent(`
		# Resume an already paused deployment
		kubectl rollout resume deployment/nginx`)
)

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

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

	cmd := &cobra.Command{
예제 #19
0
	"github.com/spf13/cobra"
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/labels"
)

// TopNodeOptions contains all the options for running the top-node cli command.
type TopNodeOptions struct {
	ResourceName string
	Selector     string
	Client       *metricsutil.HeapsterMetricsClient
	Printer      *metricsutil.TopCmdPrinter
}

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

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

	topNodeExample = dedent.Dedent(`
		  # 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]",
예제 #20
0
파일: delete.go 프로젝트: ncdc/kubernetes
	"github.com/spf13/cobra"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/meta"
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
)

var (
	delete_long = dedent.Dedent(`
		Delete resources by filenames, stdin, resources and names, or by resources and label selector.

		JSON and YAML formats are accepted.

		Only one type of the arguments may be specified: filenames, resources and names, or resources and label selector

		Note that the delete command does NOT do resource version checks, so if someone
		submits an update to a resource right when you submit a delete, their update
		will be lost along with the rest of the resource.`)
	delete_example = dedent.Dedent(`
		# Delete a pod using the type and name specified in pod.json.
		kubectl delete -f ./pod.json

		# Delete a pod based on the type and name in the JSON passed into stdin.
		cat pod.json | kubectl delete -f -

		# Delete pods and services with same names "baz" and "foo"
		kubectl delete pod,service baz foo

		# Delete pods and services with label name=myLabel.
예제 #21
0
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
)

// StopOptions 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 StopOptions struct {
	Filenames []string
	Recursive bool
}

var (
	stop_long = dedent.Dedent(`
		Deprecated: Gracefully shut down a resource by name or filename.

		The stop command is deprecated, all its functionalities are covered by delete command.
		See 'kubectl delete --help' for more details.

		Attempts to shut down and delete a resource that supports graceful termination.
		If the resource is scalable it will be scaled to 0 before deletion.`)
	stop_example = dedent.Dedent(`
		# Shut down foo.
		kubectl stop replicationcontroller foo

		# Stop pods and services with label name=myLabel.
		kubectl stop pods,services -l name=myLabel

		# Shut down the service defined in service.json
		kubectl stop -f service.json

		# Shut down all resources in the path/to/resources directory
		kubectl stop -f path/to/resources`)
예제 #22
0
	cmdutil "github.com/ttysteale/kubernetes-api/kubectl/cmd/util"
	"github.com/ttysteale/kubernetes-api/kubectl/resource"
)

// ScaleOptions 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 ScaleOptions struct {
	Filenames []string
	Recursive bool
}

var (
	scale_long = dedent.Dedent(`
		Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.

		Scale also allows users to specify one or more preconditions for the scale action.
		If --current-replicas or --resource-version is specified, it is validated before the
		scale is attempted, and it is guaranteed that the precondition holds true when the
		scale is sent to the server.`)
	scale_example = dedent.Dedent(`
		# Scale a replicaset named 'foo' to 3.
		kubectl scale --replicas=3 rs/foo

		# Scale a resource identified by type and name specified in "foo.yaml" to 3.
		kubectl scale --replicas=3 -f foo.yaml

		# If the deployment named mysql's current size is 2, scale mysql to 3.
		kubectl scale --current-replicas=2 --replicas=3 deployment/mysql

		# Scale multiple replication controllers.
		kubectl scale --replicas=5 rc/foo rc/bar rc/baz
예제 #23
0
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"

	"github.com/spf13/cobra"
)

// HistoryOptions 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 HistoryOptions struct {
	Filenames []string
	Recursive bool
}

var (
	history_long = dedent.Dedent(`
		View previous rollout revisions and configurations.`)
	history_example = dedent.Dedent(`
		# View the rollout history of a deployment
		kubectl rollout history deployment/abc

		# View the details of deployment revision 3
		kubectl rollout history deployment/abc --revision=3`)
)

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

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

	cmd := &cobra.Command{
예제 #24
0
파일: view.go 프로젝트: XbinZh/kubernetes
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/util/flag"
)

type ViewOptions struct {
	ConfigAccess clientcmd.ConfigAccess
	Merge        flag.Tristate
	Flatten      bool
	Minify       bool
	RawByteData  bool
}

var (
	view_long = dedent.Dedent(`
		Displays merged kubeconfig settings or a specified kubeconfig file.

		You can use --output jsonpath={...} to extract specific values using a jsonpath expression.`)
	view_example = dedent.Dedent(`
		# Show Merged kubeconfig settings.
		kubectl config view

		# Get the password for the e2e user
		kubectl config view -o jsonpath='{.users[?(@.name == "e2e")].user.password}'`)
)

func NewCmdConfigView(out io.Writer, ConfigAccess clientcmd.ConfigAccess) *cobra.Command {
	options := &ViewOptions{ConfigAccess: ConfigAccess}
	// Default to yaml
	defaultOutputFormat := "yaml"

	cmd := &cobra.Command{
예제 #25
0
	ChangeCause string
	Local       bool
	Cmd         *cobra.Command

	PrintObject            func(cmd *cobra.Command, mapper meta.RESTMapper, obj runtime.Object, out io.Writer) error
	UpdatePodSpecForObject func(obj runtime.Object, fn func(*api.PodSpec) error) (bool, error)
	Resources              []string
	ContainerImages        map[string]string
}

var (
	image_resources = `
  pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), job, replicaset (rs)`

	image_long = dedent.Dedent(`
		Update existing container image(s) of resources.

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

	image_example = dedent.Dedent(`
		# 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`)
)
package cmd

import (
	"fmt"
	"io"

	"github.com/renstrom/dedent"
	"github.com/spf13/cobra"

	"github.com/ttysteale/kubernetes-api/kubectl"
	cmdutil "github.com/ttysteale/kubernetes-api/kubectl/cmd/util"
)

var (
	serviceAccountLong = dedent.Dedent(`
		Create a service account with the specified name.`)

	serviceAccountExample = dedent.Dedent(`
		  # Create a new service account named my-service-account
		  $ kubectl create serviceaccount my-service-account`)
)

// NewCmdCreateServiceAccount is a macro command to create a new service account
func NewCmdCreateServiceAccount(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
	cmd := &cobra.Command{
		Use:     "serviceaccount NAME [--dry-run]",
		Aliases: []string{"sa"},
		Short:   "Create a service account with the specified name.",
		Long:    serviceAccountLong,
		Example: serviceAccountExample,
		Run: func(cmd *cobra.Command, args []string) {
예제 #27
0
파일: replace.go 프로젝트: ncdc/kubernetes
	"github.com/spf13/cobra"

	"github.com/golang/glog"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/wait"
)

var (
	replace_long = dedent.Dedent(`
		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 = dedent.Dedent(`
		# 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`)
예제 #28
0
파일: convert.go 프로젝트: nak3/origin
	"k8s.io/kubernetes/pkg/apimachinery/registered"
	"k8s.io/kubernetes/pkg/kubectl"
	cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/runtime"

	"github.com/spf13/cobra"
)

var (
	convert_long = dedent.Dedent(`
		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 = dedent.Dedent(`
		# 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.
예제 #29
0
)

// DescribeOptions 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 DescribeOptions struct {
	Filenames []string
	Recursive bool
}

var (
	describe_long = dedent.Dedent(`
		Show details of a specific resource or group of resources.
		This command joins many API calls together to form a detailed description of a
		given resource or group of resources.

		$ kubectl describe TYPE NAME_PREFIX

		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 = dedent.Dedent(`
		# Describe a node
		kubectl describe nodes kubernetes-minion-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
예제 #30
0
// UndoOptions 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 UndoOptions struct {
	Rollbackers []kubectl.Rollbacker
	Mapper      meta.RESTMapper
	Typer       runtime.ObjectTyper
	Infos       []*resource.Info
	ToRevision  int64

	Out       io.Writer
	Filenames []string
	Recursive bool
}

var (
	undo_long = dedent.Dedent(`
		Rollback to a previous rollout.`)
	undo_example = dedent.Dedent(`
		# Rollback to the previous deployment
		kubectl rollout undo deployment/abc

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

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

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

	cmd := &cobra.Command{