Merge pull request #27109 from asalkeld/more-create-commands

Automatic merge from submit-queue

Add service and deployment create sub-commands to kubectl

```release-note
Added new commands kubectl create service & kubectl create deployment
```
Partial #25382
This commit is contained in:
Kubernetes Submit Queue 2016-08-08 16:53:18 -07:00 committed by GitHub
commit d52204a1aa
22 changed files with 1209 additions and 1 deletions

View File

@ -27,12 +27,17 @@ docs/man/man1/kubectl-config.1
docs/man/man1/kubectl-convert.1
docs/man/man1/kubectl-cordon.1
docs/man/man1/kubectl-create-configmap.1
docs/man/man1/kubectl-create-deployment.1
docs/man/man1/kubectl-create-namespace.1
docs/man/man1/kubectl-create-quota.1
docs/man/man1/kubectl-create-secret-docker-registry.1
docs/man/man1/kubectl-create-secret-generic.1
docs/man/man1/kubectl-create-secret-tls.1
docs/man/man1/kubectl-create-secret.1
docs/man/man1/kubectl-create-service-clusterip.1
docs/man/man1/kubectl-create-service-loadbalancer.1
docs/man/man1/kubectl-create-service-nodeport.1
docs/man/man1/kubectl-create-service.1
docs/man/man1/kubectl-create-serviceaccount.1
docs/man/man1/kubectl-create.1
docs/man/man1/kubectl-delete.1
@ -89,12 +94,17 @@ docs/user-guide/kubectl/kubectl_convert.md
docs/user-guide/kubectl/kubectl_cordon.md
docs/user-guide/kubectl/kubectl_create.md
docs/user-guide/kubectl/kubectl_create_configmap.md
docs/user-guide/kubectl/kubectl_create_deployment.md
docs/user-guide/kubectl/kubectl_create_namespace.md
docs/user-guide/kubectl/kubectl_create_quota.md
docs/user-guide/kubectl/kubectl_create_secret.md
docs/user-guide/kubectl/kubectl_create_secret_docker-registry.md
docs/user-guide/kubectl/kubectl_create_secret_generic.md
docs/user-guide/kubectl/kubectl_create_secret_tls.md
docs/user-guide/kubectl/kubectl_create_service.md
docs/user-guide/kubectl/kubectl_create_service_clusterip.md
docs/user-guide/kubectl/kubectl_create_service_loadbalancer.md
docs/user-guide/kubectl/kubectl_create_service_nodeport.md
docs/user-guide/kubectl/kubectl_create_serviceaccount.md
docs/user-guide/kubectl/kubectl_delete.md
docs/user-guide/kubectl/kubectl_describe.md

View File

@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.

View File

@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.

View File

@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.

View File

@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.

View File

@ -0,0 +1,3 @@
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.

View File

@ -0,0 +1,36 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_deployment.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -0,0 +1,36 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_service.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -0,0 +1,36 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_service_clusterip.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -0,0 +1,36 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_service_loadbalancer.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -0,0 +1,36 @@
<!-- BEGIN MUNGE: UNVERSIONED_WARNING -->
<!-- BEGIN STRIP_FOR_RELEASE -->
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<img src="http://kubernetes.io/kubernetes/img/warning.png" alt="WARNING"
width="25" height="25">
<h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2>
If you are using a released version of Kubernetes, you should
refer to the docs that go with that version.
Documentation for other releases can be found at
[releases.k8s.io](http://releases.k8s.io).
</strong>
--
<!-- END STRIP_FOR_RELEASE -->
<!-- END MUNGE: UNVERSIONED_WARNING -->
This file is autogenerated, but we've stopped checking such files into the
repository to reduce the need for rebases. Please run hack/generate-docs.sh to
populate this file.
<!-- BEGIN MUNGE: GENERATED_ANALYTICS -->
[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/kubectl/kubectl_create_service_nodeport.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->

View File

@ -84,6 +84,8 @@ func NewCmdCreate(f *cmdutil.Factory, out io.Writer) *cobra.Command {
cmd.AddCommand(NewCmdCreateSecret(f, out))
cmd.AddCommand(NewCmdCreateConfigMap(f, out))
cmd.AddCommand(NewCmdCreateServiceAccount(f, out))
cmd.AddCommand(NewCmdCreateService(f, out))
cmd.AddCommand(NewCmdCreateDeployment(f, out))
return cmd
}

View File

@ -0,0 +1,80 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
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 (
deploymentLong = dedent.Dedent(`
Create a deployment with the specified name.`)
deploymentExample = dedent.Dedent(`
# Create a new deployment named my-dep that runs the busybox image.
kubectl create deployment my-dep --image=busybox`)
)
// NewCmdCreateDeployment is a macro command to create a new deployment
func NewCmdCreateDeployment(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "deployment NAME --image=image [--dry-run]",
Aliases: []string{"dep"},
Short: "Create a deployment with the specified name.",
Long: deploymentLong,
Example: deploymentExample,
Run: func(cmd *cobra.Command, args []string) {
err := CreateDeployment(f, cmdOut, cmd, args)
cmdutil.CheckErr(err)
},
}
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddPrinterFlags(cmd)
cmdutil.AddGeneratorFlags(cmd, cmdutil.DeploymentBasicV1Beta1GeneratorName)
cmd.Flags().StringSlice("image", []string{}, "Image name to run.")
cmd.MarkFlagRequired("image")
return cmd
}
// CreateDeployment implements the behavior to run the create deployment command
func CreateDeployment(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.DeploymentBasicV1Beta1GeneratorName:
generator = &kubectl.DeploymentBasicGeneratorV1{Name: name, Images: cmdutil.GetFlagStringSlice(cmd, "image")}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}

View File

@ -0,0 +1,54 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bytes"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCreateDeployment(t *testing.T) {
depName := "jonny-dep"
f, tf, _, _ := NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateDeployment(f, buf)
cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "name")
cmd.Flags().Set("image", "hollywood/jonny.depp:v2")
cmd.Run(cmd, []string{depName})
expectedOutput := "deployment/" + depName + "\n"
if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
}
}
func TestCreateDeploymentNoImage(t *testing.T) {
depName := "jonny-dep"
f, tf, _, _ := NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateDeployment(f, buf)
cmd.Flags().Set("dry-run", "true")
cmd.Flags().Set("output", "name")
err := CreateDeployment(f, buf, cmd, []string{depName})
assert.Error(t, err, "at least one image must be specified")
}

View File

@ -0,0 +1,219 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"fmt"
"io"
"github.com/renstrom/dedent"
"github.com/spf13/cobra"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/kubectl"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
// NewCmdCreateService is a macro command to create a new namespace
func NewCmdCreateService(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "service",
Short: "Create a service using specified subcommand.",
Long: "Create a service using specified subcommand.",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
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 {
cmd := &cobra.Command{
Use: "clusterip NAME [--tcp=<port>:<targetPort>] [--dry-run]",
Short: "Create a clusterIP service.",
Long: serviceClusterIPLong,
Example: serviceClusterIPExample,
Run: func(cmd *cobra.Command, args []string) {
err := CreateServiceClusterIP(f, cmdOut, cmd, args)
cmdutil.CheckErr(err)
},
}
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddPrinterFlags(cmd)
cmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceClusterIPGeneratorV1Name)
addPortFlags(cmd)
cmd.Flags().String("clusterip", "", "Assign your own ClusterIP or set to 'None' for a 'headless' service (no loadbalancing).")
return cmd
}
// CreateServiceClusterIP implements the behavior to run the create namespace command
func CreateServiceClusterIP(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ServiceClusterIPGeneratorV1Name:
generator = &kubectl.ServiceCommonGeneratorV1{
Name: name,
TCP: cmdutil.GetFlagStringSlice(cmd, "tcp"),
Type: api.ServiceTypeClusterIP,
ClusterIP: cmdutil.GetFlagString(cmd, "clusterip"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
var (
serviceNodePortLong = dedent.Dedent(`
Create a nodeport service with the specified name.`)
serviceNodePortExample = dedent.Dedent(`
# Create a new nodeport service named my-ns
kubectl create service nodeport my-ns --tcp=5678:8080`)
)
// NewCmdCreateServiceNodePort is a macro command for creating secrets to work with Docker registries
func NewCmdCreateServiceNodePort(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "nodeport NAME [--tcp=port:targetPort] [--dry-run]",
Short: "Create a NodePort service.",
Long: serviceNodePortLong,
Example: serviceNodePortExample,
Run: func(cmd *cobra.Command, args []string) {
err := CreateServiceNodePort(f, cmdOut, cmd, args)
cmdutil.CheckErr(err)
},
}
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddPrinterFlags(cmd)
cmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceNodePortGeneratorV1Name)
addPortFlags(cmd)
return cmd
}
// CreateServiceNodePort is the implementation of the create secret docker-registry command
func CreateServiceNodePort(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ServiceNodePortGeneratorV1Name:
generator = &kubectl.ServiceCommonGeneratorV1{
Name: name,
TCP: cmdutil.GetFlagStringSlice(cmd, "tcp"),
Type: api.ServiceTypeNodePort,
ClusterIP: "",
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetDryRunFlag(cmd),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}
var (
serviceLoadBalancerLong = dedent.Dedent(`
Create a LoadBalancer service with the specified name.`)
serviceLoadBalancerExample = dedent.Dedent(`
# Create a new nodeport service named my-lbs
kubectl create service loadbalancer my-lbs --tcp=5678:8080`)
)
// NewCmdCreateServiceLoadBalancer is a macro command for creating secrets to work with Docker registries
func NewCmdCreateServiceLoadBalancer(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "loadbalancer NAME [--tcp=port:targetPort] [--dry-run]",
Short: "Create a LoadBalancer service.",
Long: serviceLoadBalancerLong,
Example: serviceLoadBalancerExample,
Run: func(cmd *cobra.Command, args []string) {
err := CreateServiceLoadBalancer(f, cmdOut, cmd, args)
cmdutil.CheckErr(err)
},
}
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddPrinterFlags(cmd)
cmdutil.AddGeneratorFlags(cmd, cmdutil.ServiceLoadBalancerGeneratorV1Name)
addPortFlags(cmd)
return cmd
}
// CreateServiceLoadBalancer is the implementation of the create secret tls command
func CreateServiceLoadBalancer(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ServiceLoadBalancerGeneratorV1Name:
generator = &kubectl.ServiceCommonGeneratorV1{
Name: name,
TCP: cmdutil.GetFlagStringSlice(cmd, "tcp"),
Type: api.ServiceTypeLoadBalancer,
ClusterIP: "",
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
}
return RunCreateSubcommand(f, cmd, cmdOut, &CreateSubcommandOptions{
Name: name,
StructuredGenerator: generator,
DryRun: cmdutil.GetFlagBool(cmd, "dry-run"),
OutputFormat: cmdutil.GetFlagString(cmd, "output"),
})
}

View File

@ -0,0 +1,55 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bytes"
"net/http"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/unversioned/fake"
)
func TestCreateService(t *testing.T) {
service := &api.Service{}
service.Name = "my-service"
f, tf, codec, negSer := NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{
NegotiatedSerializer: negSer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/services" && m == "POST":
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: objBody(codec, service)}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateServiceClusterIP(f, buf)
cmd.Flags().Set("output", "name")
cmd.Flags().Set("tcp", "8080:8000")
cmd.Run(cmd, []string{service.Name})
expectedOutput := "service/" + service.Name + "\n"
if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())
}
}

View File

@ -158,10 +158,14 @@ const (
RunPodV1GeneratorName = "run-pod/v1"
ServiceV1GeneratorName = "service/v1"
ServiceV2GeneratorName = "service/v2"
ServiceNodePortGeneratorV1Name = "service-nodeport/v1"
ServiceClusterIPGeneratorV1Name = "service-clusterip/v1"
ServiceLoadBalancerGeneratorV1Name = "service-loadbalancer/v1"
ServiceAccountV1GeneratorName = "serviceaccount/v1"
HorizontalPodAutoscalerV1Beta1GeneratorName = "horizontalpodautoscaler/v1beta1"
HorizontalPodAutoscalerV1GeneratorName = "horizontalpodautoscaler/v1"
DeploymentV1Beta1GeneratorName = "deployment/v1beta1"
DeploymentBasicV1Beta1GeneratorName = "deployment-basic/v1beta1"
JobV1Beta1GeneratorName = "job/v1beta1"
JobV1GeneratorName = "job/v1"
ScheduledJobV2Alpha1GeneratorName = "scheduledjob/v2alpha1"
@ -180,6 +184,18 @@ func DefaultGenerators(cmdName string) map[string]kubectl.Generator {
ServiceV1GeneratorName: kubectl.ServiceGeneratorV1{},
ServiceV2GeneratorName: kubectl.ServiceGeneratorV2{},
}
generators["service-clusterip"] = map[string]kubectl.Generator{
ServiceClusterIPGeneratorV1Name: kubectl.ServiceClusterIPGeneratorV1{},
}
generators["service-nodeport"] = map[string]kubectl.Generator{
ServiceNodePortGeneratorV1Name: kubectl.ServiceNodePortGeneratorV1{},
}
generators["service-loadbalancer"] = map[string]kubectl.Generator{
ServiceLoadBalancerGeneratorV1Name: kubectl.ServiceLoadBalancerGeneratorV1{},
}
generators["deployment"] = map[string]kubectl.Generator{
DeploymentBasicV1Beta1GeneratorName: kubectl.DeploymentBasicGeneratorV1{},
}
generators["run"] = map[string]kubectl.Generator{
RunV1GeneratorName: kubectl.BasicReplicationController{},
RunPodV1GeneratorName: kubectl.BasicPod{},

107
pkg/kubectl/deployment.go Normal file
View File

@ -0,0 +1,107 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubectl
import (
"fmt"
"strings"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/runtime"
)
// DeploymentGeneratorV1 supports stable generation of a deployment
type DeploymentBasicGeneratorV1 struct {
Name string
Images []string
}
// Ensure it supports the generator pattern that uses parameters specified during construction
var _ StructuredGenerator = &DeploymentBasicGeneratorV1{}
func (DeploymentBasicGeneratorV1) ParamNames() []GeneratorParam {
return []GeneratorParam{
{"name", true},
{"image", true},
}
}
func (s DeploymentBasicGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {
err := ValidateParams(s.ParamNames(), params)
if err != nil {
return nil, err
}
name, isString := params["name"].(string)
if !isString {
return nil, fmt.Errorf("expected string, saw %v for 'name'", name)
}
imageStrings, isArray := params["image"].([]string)
if !isArray {
return nil, fmt.Errorf("expected []string, found :%v", imageStrings)
}
delegate := &DeploymentBasicGeneratorV1{Name: name, Images: imageStrings}
return delegate.StructuredGenerate()
}
// StructuredGenerate outputs a deployment object using the configured fields
func (s *DeploymentBasicGeneratorV1) StructuredGenerate() (runtime.Object, error) {
if err := s.validate(); err != nil {
return nil, err
}
podSpec := api.PodSpec{Containers: []api.Container{}}
for _, imageString := range s.Images {
imageSplit := strings.Split(imageString, "/")
name := imageSplit[len(imageSplit)-1]
podSpec.Containers = append(podSpec.Containers, api.Container{Name: name, Image: imageString})
}
// setup default label and selector
labels := map[string]string{}
labels["app"] = s.Name
selector := unversioned.LabelSelector{MatchLabels: labels}
deployment := extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: s.Name,
Labels: labels,
},
Spec: extensions.DeploymentSpec{
Replicas: 1,
Selector: &selector,
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: labels,
},
Spec: podSpec,
},
},
}
return &deployment, nil
}
// validate validates required fields are set to support structured generation
func (s *DeploymentBasicGeneratorV1) validate() error {
if len(s.Name) == 0 {
return fmt.Errorf("name must be specified")
}
if len(s.Images) == 0 {
return fmt.Errorf("at least one image must be specified")
}
return nil
}

View File

@ -0,0 +1,134 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubectl
import (
"reflect"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/extensions"
)
func TestDeploymentGenerate(t *testing.T) {
tests := []struct {
params map[string]interface{}
expected *extensions.Deployment
expectErr bool
}{
{
params: map[string]interface{}{
"name": "foo",
"image": []string{"abc/app:v4"},
},
expected: &extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: "foo",
Labels: map[string]string{"app": "foo"},
},
Spec: extensions.DeploymentSpec{
Replicas: 1,
Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"app": "foo"}},
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"app": "foo"},
},
Spec: api.PodSpec{
Containers: []api.Container{{Name: "app:v4", Image: "abc/app:v4"}},
},
},
},
},
expectErr: false,
},
{
params: map[string]interface{}{
"name": "foo",
"image": []string{"abc/app:v4", "zyx/ape"},
},
expected: &extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: "foo",
Labels: map[string]string{"app": "foo"},
},
Spec: extensions.DeploymentSpec{
Replicas: 1,
Selector: &unversioned.LabelSelector{MatchLabels: map[string]string{"app": "foo"}},
Template: api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"app": "foo"},
},
Spec: api.PodSpec{
Containers: []api.Container{{Name: "app:v4", Image: "abc/app:v4"},
{Name: "ape", Image: "zyx/ape"}},
},
},
},
},
expectErr: false,
},
{
params: map[string]interface{}{},
expectErr: true,
},
{
params: map[string]interface{}{
"name": 1,
},
expectErr: true,
},
{
params: map[string]interface{}{
"name": nil,
},
expectErr: true,
},
{
params: map[string]interface{}{
"name": "foo",
"image": []string{},
},
expectErr: true,
},
{
params: map[string]interface{}{
"NAME": "some_value",
},
expectErr: true,
},
}
generator := DeploymentBasicGeneratorV1{}
for index, test := range tests {
obj, err := generator.Generate(test.params)
switch {
case test.expectErr && err != nil:
continue // loop, since there's no output to check
case test.expectErr && err == nil:
t.Errorf("%v: expected error and didn't get one", index)
continue // loop, no expected output object
case !test.expectErr && err != nil:
t.Errorf("%v: unexpected error %v", index, err)
continue // loop, no output object
case !test.expectErr && err == nil:
// do nothing and drop through
}
if !reflect.DeepEqual(obj.(*extensions.Deployment), test.expected) {
t.Errorf("%v\nexpected:\n%#v\nsaw:\n%#v", index, test.expected, obj.(*extensions.Deployment))
}
}
}

View File

@ -80,7 +80,7 @@ func TestNamespaceGenerate(t *testing.T) {
t.Errorf("%v: expected error and didn't get one", index)
continue // loop, no expected output object
case !test.expectErr && err != nil:
t.Errorf("%v: expected error and didn't get one", index)
t.Errorf("%v: unexpected error %v", index, err)
continue // loop, no output object
case !test.expectErr && err == nil:
// do nothing and drop through

View File

@ -0,0 +1,207 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubectl
import (
"fmt"
"strconv"
"strings"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/runtime"
"k8s.io/kubernetes/pkg/util/intstr"
)
type ServiceCommonGeneratorV1 struct {
Name string
TCP []string
Type api.ServiceType
ClusterIP string
}
type ServiceClusterIPGeneratorV1 struct {
ServiceCommonGeneratorV1
}
type ServiceNodePortGeneratorV1 struct {
ServiceCommonGeneratorV1
}
type ServiceLoadBalancerGeneratorV1 struct {
ServiceCommonGeneratorV1
}
func (ServiceClusterIPGeneratorV1) ParamNames() []GeneratorParam {
return []GeneratorParam{
{"name", true},
{"tcp", true},
{"clusterip", false},
}
}
func (ServiceNodePortGeneratorV1) ParamNames() []GeneratorParam {
return []GeneratorParam{
{"name", true},
{"tcp", true},
}
}
func (ServiceLoadBalancerGeneratorV1) ParamNames() []GeneratorParam {
return []GeneratorParam{
{"name", true},
{"tcp", true},
}
}
func parsePorts(portString string) (int32, intstr.IntOrString, error) {
portStringSlice := strings.Split(portString, ":")
port, err := strconv.Atoi(portStringSlice[0])
if err != nil {
return 0, intstr.FromInt(0), err
}
if len(portStringSlice) == 1 {
return int32(port), intstr.FromInt(int(port)), nil
}
var targetPort intstr.IntOrString
if portNum, err := strconv.Atoi(portStringSlice[1]); err != nil {
targetPort = intstr.FromString(portStringSlice[1])
} else {
targetPort = intstr.FromInt(portNum)
}
return int32(port), targetPort, nil
}
func (s ServiceCommonGeneratorV1) GenerateCommon(params map[string]interface{}) error {
name, isString := params["name"].(string)
if !isString {
return fmt.Errorf("expected string, saw %v for 'name'", name)
}
tcpStrings, isArray := params["tcp"].([]string)
if !isArray {
return fmt.Errorf("expected []string, found :%v", tcpStrings)
}
clusterip, isString := params["clusterip"].(string)
if !isString {
return fmt.Errorf("expected string, saw %v for 'clusterip'", clusterip)
}
s.Name = name
s.TCP = tcpStrings
s.ClusterIP = clusterip
return nil
}
func (s ServiceLoadBalancerGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {
err := ValidateParams(s.ParamNames(), params)
if err != nil {
return nil, err
}
delegate := &ServiceCommonGeneratorV1{Type: api.ServiceTypeLoadBalancer, ClusterIP: ""}
err = delegate.GenerateCommon(params)
if err != nil {
return nil, err
}
return delegate.StructuredGenerate()
}
func (s ServiceNodePortGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {
err := ValidateParams(s.ParamNames(), params)
if err != nil {
return nil, err
}
delegate := &ServiceCommonGeneratorV1{Type: api.ServiceTypeNodePort, ClusterIP: ""}
err = delegate.GenerateCommon(params)
if err != nil {
return nil, err
}
return delegate.StructuredGenerate()
}
func (s ServiceClusterIPGeneratorV1) Generate(params map[string]interface{}) (runtime.Object, error) {
err := ValidateParams(s.ParamNames(), params)
if err != nil {
return nil, err
}
delegate := &ServiceCommonGeneratorV1{Type: api.ServiceTypeClusterIP, ClusterIP: ""}
err = delegate.GenerateCommon(params)
if err != nil {
return nil, err
}
return delegate.StructuredGenerate()
}
// validate validates required fields are set to support structured generation
func (s ServiceCommonGeneratorV1) validate() error {
if len(s.Name) == 0 {
return fmt.Errorf("name must be specified")
}
if len(s.Type) == 0 {
return fmt.Errorf("type must be specified")
}
if s.ClusterIP == api.ClusterIPNone && s.Type != api.ServiceTypeClusterIP {
return fmt.Errorf("ClusterIP=None can only be used with ClusterIP service type")
}
if s.ClusterIP == api.ClusterIPNone && len(s.TCP) > 0 {
return fmt.Errorf("can not map ports with clusterip=None")
}
if s.ClusterIP != api.ClusterIPNone && len(s.TCP) == 0 {
return fmt.Errorf("at least one tcp port specifier must be provided")
}
return nil
}
func (s ServiceCommonGeneratorV1) StructuredGenerate() (runtime.Object, error) {
err := s.validate()
if err != nil {
return nil, err
}
ports := []api.ServicePort{}
for _, tcpString := range s.TCP {
port, targetPort, err := parsePorts(tcpString)
if err != nil {
return nil, err
}
portName := strings.Replace(tcpString, ":", "-", -1)
ports = append(ports, api.ServicePort{
Name: portName,
Port: port,
TargetPort: targetPort,
Protocol: api.Protocol("TCP"),
})
}
// setup default label and selector
labels := map[string]string{}
labels["app"] = s.Name
selector := map[string]string{}
selector["app"] = s.Name
service := api.Service{
ObjectMeta: api.ObjectMeta{
Name: s.Name,
Labels: labels,
},
Spec: api.ServiceSpec{
Type: api.ServiceType(s.Type),
Selector: selector,
Ports: ports,
},
}
if len(s.ClusterIP) > 0 {
service.Spec.ClusterIP = s.ClusterIP
}
return &service, nil
}

View File

@ -0,0 +1,129 @@
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package kubectl
import (
"reflect"
"testing"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/util/intstr"
)
func TestServiceBasicGenerate(t *testing.T) {
tests := []struct {
name string
serviceType api.ServiceType
tcp []string
clusterip string
expected *api.Service
expectErr bool
}{
{
name: "clusterip-ok",
tcp: []string{"456", "321:908"},
clusterip: "",
serviceType: api.ServiceTypeClusterIP,
expected: &api.Service{
ObjectMeta: api.ObjectMeta{
Name: "clusterip-ok",
Labels: map[string]string{"app": "clusterip-ok"},
},
Spec: api.ServiceSpec{Type: "ClusterIP",
Ports: []api.ServicePort{{Name: "456", Protocol: "TCP", Port: 456, TargetPort: intstr.IntOrString{Type: 0, IntVal: 456, StrVal: ""}, NodePort: 0},
{Name: "321-908", Protocol: "TCP", Port: 321, TargetPort: intstr.IntOrString{Type: 0, IntVal: 908, StrVal: ""}, NodePort: 0}},
Selector: map[string]string{"app": "clusterip-ok"},
ClusterIP: "", ExternalIPs: []string(nil), LoadBalancerIP: ""},
},
expectErr: false,
},
{
name: "clusterip-missing",
serviceType: api.ServiceTypeClusterIP,
expectErr: true,
},
{
name: "clusterip-none and port mapping",
tcp: []string{"456:9898"},
clusterip: "None",
serviceType: api.ServiceTypeClusterIP,
expectErr: true,
},
{
name: "clusterip-none-wrong-type",
tcp: []string{},
clusterip: "None",
serviceType: api.ServiceTypeNodePort,
expectErr: true,
},
{
name: "clusterip-none-ok",
tcp: []string{},
clusterip: "None",
serviceType: api.ServiceTypeClusterIP,
expected: &api.Service{
ObjectMeta: api.ObjectMeta{
Name: "clusterip-none-ok",
Labels: map[string]string{"app": "clusterip-none-ok"},
},
Spec: api.ServiceSpec{Type: "ClusterIP",
Ports: []api.ServicePort{},
Selector: map[string]string{"app": "clusterip-none-ok"},
ClusterIP: "None", ExternalIPs: []string(nil), LoadBalancerIP: ""},
},
expectErr: false,
},
{
name: "loadbalancer-ok",
tcp: []string{"456:9898"},
clusterip: "",
serviceType: api.ServiceTypeLoadBalancer,
expected: &api.Service{
ObjectMeta: api.ObjectMeta{
Name: "loadbalancer-ok",
Labels: map[string]string{"app": "loadbalancer-ok"},
},
Spec: api.ServiceSpec{Type: "LoadBalancer",
Ports: []api.ServicePort{{Name: "456-9898", Protocol: "TCP", Port: 456, TargetPort: intstr.IntOrString{Type: 0, IntVal: 9898, StrVal: ""}, NodePort: 0}},
Selector: map[string]string{"app": "loadbalancer-ok"},
ClusterIP: "", ExternalIPs: []string(nil), LoadBalancerIP: ""},
},
expectErr: false,
},
{
expectErr: true,
},
}
for _, test := range tests {
generator := ServiceCommonGeneratorV1{
Name: test.name,
TCP: test.tcp,
Type: test.serviceType,
ClusterIP: test.clusterip,
}
obj, err := generator.StructuredGenerate()
if !test.expectErr && err != nil {
t.Errorf("unexpected error: %v", err)
}
if test.expectErr && err != nil {
continue
}
if !reflect.DeepEqual(obj.(*api.Service), test.expected) {
t.Errorf("test: %v\nexpected:\n%#v\nsaw:\n%#v", test.name, test.expected, obj.(*api.Service))
}
}
}