Skip to content

Commit

Permalink
Add --scopes to kubectl-create-quota and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sttts committed Jul 26, 2016
1 parent 5b95524 commit 199f991
Show file tree
Hide file tree
Showing 9 changed files with 248 additions and 67 deletions.
2 changes: 2 additions & 0 deletions .generated_docs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ docs/man/man1/kubectl-convert.1
docs/man/man1/kubectl-cordon.1
docs/man/man1/kubectl-create-configmap.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
Expand Down Expand Up @@ -89,6 +90,7 @@ 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_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
Expand Down
3 changes: 3 additions & 0 deletions docs/man/man1/kubectl-create-quota.1
Original file line number Diff line number Diff line change
@@ -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.
36 changes: 36 additions & 0 deletions docs/user-guide/kubectl/kubectl_create_quota.md
Original file line number Diff line number Diff line change
@@ -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_quota.md?pixel)]()
<!-- END MUNGE: GENERATED_ANALYTICS -->
1 change: 1 addition & 0 deletions hack/verify-flags/known-flags.txt
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ save-config
scheduler-config
scheduler-name
schema-cache-dir
scopes
seccomp-profile-root
secure-port
serialize-image-pulls
Expand Down
27 changes: 13 additions & 14 deletions pkg/kubectl/cmd/create_quota.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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.
Expand Down Expand Up @@ -28,16 +28,19 @@ import (

const (
quotaLong = `
Create a resourcequota with the specified name and hard limits`
Create a resourcequota with the specified name, hard limits and optional scopes`

quotaExample = ` // Create a new resourcequota named my-quota
$ kubectl create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10`
$ kubectl create quota my-quota --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10
// Create a new resourcequota named best-effort
$ kubectl create quota best-effort --hard=pods=100 --scopes=BestEffort`
)

// NewCmdCreateQuota is a macro command to create a new quota
func NewCmdCreateQuota(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "quota NAME [--hard=key1=value1,key2=value2] [--dry-run=bool]",
Use: "quota NAME [--hard=key1=value1,key2=value2] [--scopes=Scope1,Scope2] [--dry-run=bool]",
Aliases: []string{"q"},
Short: "Create a quota with the specified name.",
Long: quotaLong,
Expand All @@ -50,9 +53,10 @@ func NewCmdCreateQuota(f *cmdutil.Factory, cmdOut io.Writer) *cobra.Command {

cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddPrinterFlags(cmd)
cmdutil.AddGeneratorFlags(cmd, cmdutil.ResourceQuotaV1GeneratorName)
cmd.Flags().String("hard", "", "Specify multiple key/value pair to insert in resourcequota (i.e. --hard=cpu=1,memory=1G,pods=2,services=3,replicationcontrollers=2,resourcequotas=1,secrets=5,persistentvolumeclaims=10)")
cmd.MarkFlagRequired("hard")
cmd.Flags().String("hard", "", "A comma-delimited set of resource=quantity pairs that define a hard limit.")
cmd.Flags().String("scopes", "", "A comma-delimited set of quota scopes that must all match each object tracked by the quota.")
return cmd
}

Expand All @@ -62,18 +66,13 @@ func CreateQuota(f *cmdutil.Factory, cmdOut io.Writer, cmd *cobra.Command, args
if err != nil {
return err
}
requiredFlags := []string{"hard"}
for _, requiredFlag := range requiredFlags {
if value := cmdutil.GetFlagString(cmd, requiredFlag); len(value) == 0 {
return cmdutil.UsageError(cmd, "flag %s is required", requiredFlag)
}
}
var generator kubectl.StructuredGenerator
switch generatorName := cmdutil.GetFlagString(cmd, "generator"); generatorName {
case cmdutil.ResourceQuotaV1GeneratorName:
generator = &kubectl.ResourceQuotaGeneratorV1{
Name: name,
Hard: cmdutil.GetFlagString(cmd, "hard"),
Name: name,
Hard: cmdutil.GetFlagString(cmd, "hard"),
Scopes: cmdutil.GetFlagString(cmd, "scopes"),
}
default:
return cmdutil.UsageError(cmd, fmt.Sprintf("Generator: %s not supported.", generatorName))
Expand Down
48 changes: 36 additions & 12 deletions pkg/kubectl/cmd/create_quota_test.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
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.
Expand Down Expand Up @@ -28,28 +28,52 @@ import (
func TestCreateQuota(t *testing.T) {
resourceQuotaObject := &api.ResourceQuota{}
resourceQuotaObject.Name = "my-quota"
f, tf, codec := NewAPIFactory()
f, tf, codec, ns := NewAPIFactory()
tf.Printer = &testPrinter{}
tf.Client = &fake.RESTClient{
Codec: codec,
NegotiatedSerializer: ns,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
switch p, m := req.URL.Path, req.Method; {
case p == "/namespaces/test/resourcequotas" && m == "POST":
return &http.Response{StatusCode: 201, Body: objBody(codec, resourceQuotaObject)}, nil
return &http.Response{StatusCode: 201, Header: defaultHeader(), Body: objBody(codec, resourceQuotaObject)}, nil
default:
t.Fatalf("unexpected request: %#v\n%#v", req.URL, req)
return nil, nil
}
}),
}
tf.Namespace = "test"
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateQuota(f, buf)
cmd.Flags().Set("hard", "cpu=1")
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{resourceQuotaObject.Name})
expectedOutput := "resourcequota/" + resourceQuotaObject.Name + "\n"
if buf.String() != expectedOutput {
t.Errorf("expected output: %s, but got: %s", expectedOutput, buf.String())

tests := map[string]struct {
flags map[string]string
expectedOutput string
}{
"single resource": {
flags: map[string]string{"hard": "cpu=1", "output": "name"},
expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
},
"single resource with a scope": {
flags: map[string]string{"hard": "cpu=1", "output": "name", "scopes": "BestEffort"},
expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
},
"multiple resources": {
flags: map[string]string{"hard": "cpu=1,pods=42", "output": "name", "scopes": "BestEffort"},
expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
},
"single resource with multiple scopes": {
flags: map[string]string{"hard": "cpu=1", "output": "name", "scopes": "BestEffort,NotTerminating"},
expectedOutput: "resourcequota/" + resourceQuotaObject.Name + "\n",
},
}
for name, test := range tests {
buf := bytes.NewBuffer([]byte{})
cmd := NewCmdCreateQuota(f, buf)
cmd.Flags().Set("hard", "cpu=1")
cmd.Flags().Set("output", "name")
cmd.Run(cmd, []string{resourceQuotaObject.Name})

if buf.String() != test.expectedOutput {
t.Errorf("%s: expected output: %s, but got: %s", name, test.expectedOutput, buf.String())
}
}
}
66 changes: 39 additions & 27 deletions pkg/kubectl/quota.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2015 The Kubernetes Authors All rights reserved.
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.
Expand All @@ -18,24 +18,30 @@ package kubectl

import (
"fmt"
"strings"

"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/runtime"
"strings"
)

// ResourceQuotaGeneratorV1 supports stable generation of a namespace
// ResourceQuotaGeneratorV1 supports stable generation of a resource quota
type ResourceQuotaGeneratorV1 struct {
// The name of a quota object.
Name string

// The hard resource limit string before parsing.
Hard string

// The scopes of a quota object before parsing.
Scopes string
}

// ParamNames returns the set of supported input parameters when using the parameter injection generator pattern
func (g ResourceQuotaGeneratorV1) ParamNames() []GeneratorParam {
return []GeneratorParam{
{"name", true},
{"hard", true},
{"scopes", false},
}
}

Expand Down Expand Up @@ -63,6 +69,7 @@ func (g ResourceQuotaGeneratorV1) Generate(genericParams map[string]interface{})
delegate := &ResourceQuotaGeneratorV1{}
delegate.Name = params["name"]
delegate.Hard = params["hard"]
delegate.Scopes = params["scopes"]
return delegate.StructuredGenerate()
}

Expand All @@ -72,42 +79,47 @@ func (g *ResourceQuotaGeneratorV1) StructuredGenerate() (runtime.Object, error)
return nil, err
}

resourceQuotaSpec, err := generateResourceQuotaSpecList(g.Hard)
resourceList, err := populateResourceList(g.Hard)
if err != nil {
return nil, err
}

scopes, err := parseScopes(g.Scopes)
if err != nil {
return nil, err
}

resourceQuota := &api.ResourceQuota{}
resourceQuota.Name = g.Name
resourceQuota.Spec.Hard = resourceQuotaSpec
resourceQuota.Spec.Hard = resourceList
resourceQuota.Spec.Scopes = scopes
return resourceQuota, nil
}

func generateResourceQuotaSpecList(hard string) (resourceList api.ResourceList, err error) {

defer func() {
if p := recover(); p != nil {
resourceList = nil
err = fmt.Errorf("Invalid input %v", p)
}
}()

resourceList = make(api.ResourceList)
for _, keyValue := range strings.Split(hard, ",") {
items := strings.Split(keyValue, "=")
if len(items) != 2 {
return nil, fmt.Errorf("invalid input %v, expected key=value", keyValue)
}

resourceList[api.ResourceName(items[0])] = resource.MustParse(items[1])
}
return
}

// validate validates required fields are set to support structured generation
func (r *ResourceQuotaGeneratorV1) validate() error {
if len(r.Name) == 0 {
return fmt.Errorf("name must be specified")
}
return nil
}

func parseScopes(spec string) ([]api.ResourceQuotaScope, error) {
// empty input gets a nil response to preserve generator test expected behaviors
if spec == "" {
return nil, nil
}

scopes := strings.Split(spec, ",")
result := make([]api.ResourceQuotaScope, 0, len(scopes))
for _, scope := range scopes {
// intentionally do not verify the scope against the valid scope list. This is done by the apiserver anyway.

if scope == "" {
return nil, fmt.Errorf("invalid resource quota scope \"\"")
}

result = append(result, api.ResourceQuotaScope(scope))
}
return result, nil
}
Loading

0 comments on commit 199f991

Please sign in to comment.