forked from barak/tarpoon
Add glide.yaml and vendor deps
This commit is contained in:
parent
db918f12ad
commit
5b3d5e81bd
18880 changed files with 5166045 additions and 1 deletions
54
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/BUILD
generated
vendored
Normal file
54
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/BUILD
generated
vendored
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
licenses(["notice"])
|
||||
|
||||
load(
|
||||
"@io_bazel_rules_go//go:def.bzl",
|
||||
"go_binary",
|
||||
"go_library",
|
||||
"go_test",
|
||||
"cgo_library",
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"helper.go",
|
||||
"set.go",
|
||||
"set_image.go",
|
||||
"set_resources.go",
|
||||
],
|
||||
tags = ["automanaged"],
|
||||
deps = [
|
||||
"//pkg/api:go_default_library",
|
||||
"//pkg/api/errors:go_default_library",
|
||||
"//pkg/api/meta:go_default_library",
|
||||
"//pkg/kubectl:go_default_library",
|
||||
"//pkg/kubectl/cmd/templates:go_default_library",
|
||||
"//pkg/kubectl/cmd/util:go_default_library",
|
||||
"//pkg/kubectl/resource:go_default_library",
|
||||
"//pkg/runtime:go_default_library",
|
||||
"//pkg/util/errors:go_default_library",
|
||||
"//pkg/util/strategicpatch:go_default_library",
|
||||
"//vendor:github.com/spf13/cobra",
|
||||
],
|
||||
)
|
||||
|
||||
go_test(
|
||||
name = "go_default_test",
|
||||
srcs = ["set_image_test.go"],
|
||||
data = [
|
||||
"//examples:config",
|
||||
],
|
||||
library = "go_default_library",
|
||||
tags = ["automanaged"],
|
||||
deps = [
|
||||
"//pkg/api:go_default_library",
|
||||
"//pkg/apimachinery/registered:go_default_library",
|
||||
"//pkg/client/restclient:go_default_library",
|
||||
"//pkg/client/restclient/fake:go_default_library",
|
||||
"//pkg/kubectl/cmd/testing:go_default_library",
|
||||
"//pkg/kubectl/cmd/util:go_default_library",
|
||||
"//pkg/kubectl/resource:go_default_library",
|
||||
],
|
||||
)
|
||||
162
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/helper.go
generated
vendored
Normal file
162
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/helper.go
generated
vendored
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
/*
|
||||
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 set
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/api/errors"
|
||||
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
"k8s.io/kubernetes/pkg/kubectl/resource"
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
"k8s.io/kubernetes/pkg/util/strategicpatch"
|
||||
)
|
||||
|
||||
// selectContainers allows one or more containers to be matched against a string or wildcard
|
||||
func selectContainers(containers []api.Container, spec string) ([]*api.Container, []*api.Container) {
|
||||
out := []*api.Container{}
|
||||
skipped := []*api.Container{}
|
||||
for i, c := range containers {
|
||||
if selectString(c.Name, spec) {
|
||||
out = append(out, &containers[i])
|
||||
} else {
|
||||
skipped = append(skipped, &containers[i])
|
||||
}
|
||||
}
|
||||
return out, skipped
|
||||
}
|
||||
|
||||
// handlePodUpdateError prints a more useful error to the end user when mutating a pod.
|
||||
func handlePodUpdateError(out io.Writer, err error, resource string) {
|
||||
if statusError, ok := err.(*errors.StatusError); ok && errors.IsInvalid(err) {
|
||||
errorDetails := statusError.Status().Details
|
||||
if errorDetails.Kind == "Pod" {
|
||||
all, match := true, false
|
||||
for _, cause := range errorDetails.Causes {
|
||||
if cause.Field == "spec" && strings.Contains(cause.Message, "may not update fields other than") {
|
||||
fmt.Fprintf(out, "error: may not update %s in pod %q directly\n", resource, errorDetails.Name)
|
||||
match = true
|
||||
} else {
|
||||
all = false
|
||||
}
|
||||
}
|
||||
if all && match {
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if ok := kcmdutil.PrintErrorWithCauses(err, out); ok {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "error: %v\n", err)
|
||||
}
|
||||
|
||||
// selectString returns true if the provided string matches spec, where spec is a string with
|
||||
// a non-greedy '*' wildcard operator.
|
||||
// TODO: turn into a regex and handle greedy matches and backtracking.
|
||||
func selectString(s, spec string) bool {
|
||||
if spec == "*" {
|
||||
return true
|
||||
}
|
||||
if !strings.Contains(spec, "*") {
|
||||
return s == spec
|
||||
}
|
||||
|
||||
pos := 0
|
||||
match := true
|
||||
parts := strings.Split(spec, "*")
|
||||
for i, part := range parts {
|
||||
if len(part) == 0 {
|
||||
continue
|
||||
}
|
||||
next := strings.Index(s[pos:], part)
|
||||
switch {
|
||||
// next part not in string
|
||||
case next < pos:
|
||||
fallthrough
|
||||
// first part does not match start of string
|
||||
case i == 0 && pos != 0:
|
||||
fallthrough
|
||||
// last part does not exactly match remaining part of string
|
||||
case i == (len(parts)-1) && len(s) != (len(part)+next):
|
||||
match = false
|
||||
break
|
||||
default:
|
||||
pos = next
|
||||
}
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
// Patch represents the result of a mutation to an object.
|
||||
type Patch struct {
|
||||
Info *resource.Info
|
||||
Err error
|
||||
|
||||
Before []byte
|
||||
After []byte
|
||||
Patch []byte
|
||||
}
|
||||
|
||||
// CalculatePatches calls the mutation function on each provided info object, and generates a strategic merge patch for
|
||||
// the changes in the object. Encoder must be able to encode the info into the appropriate destination type. If mutateFn
|
||||
// returns false, the object is not included in the final list of patches.
|
||||
func CalculatePatches(infos []*resource.Info, encoder runtime.Encoder, mutateFn func(*resource.Info) (bool, error)) []*Patch {
|
||||
var patches []*Patch
|
||||
for _, info := range infos {
|
||||
patch := &Patch{Info: info}
|
||||
patch.Before, patch.Err = runtime.Encode(encoder, info.Object)
|
||||
if patch.Err != nil {
|
||||
patches = append(patches, patch)
|
||||
continue
|
||||
}
|
||||
|
||||
ok, err := mutateFn(info)
|
||||
if err != nil {
|
||||
patch.Err = err
|
||||
patches = append(patches, patch)
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
patches = append(patches, patch)
|
||||
if patch.Err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
patch.After, patch.Err = runtime.Encode(encoder, info.Object)
|
||||
if patch.Err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// TODO: should be via New
|
||||
versioned, err := info.Mapping.ConvertToVersion(info.Object, info.Mapping.GroupVersionKind.GroupVersion())
|
||||
if err != nil {
|
||||
patch.Err = err
|
||||
continue
|
||||
}
|
||||
|
||||
patch.Patch, patch.Err = strategicpatch.CreateTwoWayMergePatch(patch.Before, patch.After, versioned)
|
||||
}
|
||||
return patches
|
||||
}
|
||||
47
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set.go
generated
vendored
Normal file
47
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set.go
generated
vendored
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
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 set
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
)
|
||||
|
||||
var (
|
||||
set_long = templates.LongDesc(`
|
||||
Configure application resources
|
||||
|
||||
These commands help you make changes to existing application resources.`)
|
||||
)
|
||||
|
||||
func NewCmdSet(f cmdutil.Factory, out, err io.Writer) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "set SUBCOMMAND",
|
||||
Short: "Set specific features on objects",
|
||||
Long: set_long,
|
||||
Run: cmdutil.DefaultSubCommandRun(err),
|
||||
}
|
||||
|
||||
// add subcommands
|
||||
cmd.AddCommand(NewCmdImage(f, out, err))
|
||||
cmd.AddCommand(NewCmdResources(f, out, err))
|
||||
|
||||
return cmd
|
||||
}
|
||||
242
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_image.go
generated
vendored
Normal file
242
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_image.go
generated
vendored
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
/*
|
||||
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 set
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/api/meta"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
"k8s.io/kubernetes/pkg/kubectl/resource"
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
utilerrors "k8s.io/kubernetes/pkg/util/errors"
|
||||
)
|
||||
|
||||
// ImageOptions 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 ImageOptions struct {
|
||||
resource.FilenameOptions
|
||||
|
||||
Mapper meta.RESTMapper
|
||||
Typer runtime.ObjectTyper
|
||||
Infos []*resource.Info
|
||||
Encoder runtime.Encoder
|
||||
Selector string
|
||||
Out io.Writer
|
||||
Err io.Writer
|
||||
ShortOutput bool
|
||||
All bool
|
||||
Record bool
|
||||
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 = 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",
|
||||
Short: "Update image of a pod template",
|
||||
Long: image_long,
|
||||
Example: image_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cmdutil.CheckErr(options.Complete(f, cmd, args))
|
||||
cmdutil.CheckErr(options.Validate())
|
||||
cmdutil.CheckErr(options.Run())
|
||||
},
|
||||
}
|
||||
|
||||
cmdutil.AddPrinterFlags(cmd)
|
||||
usage := "identifying the resource to get from a server."
|
||||
cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage)
|
||||
cmd.Flags().BoolVar(&options.All, "all", false, "select all resources in the namespace of the specified resource types")
|
||||
cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on")
|
||||
cmd.Flags().BoolVar(&options.Local, "local", false, "If true, set image will NOT contact api-server but run locally.")
|
||||
cmdutil.AddRecordFlag(cmd)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (o *ImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
|
||||
o.Mapper, o.Typer = f.Object()
|
||||
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
|
||||
o.Encoder = f.JSONEncoder()
|
||||
o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
|
||||
o.Record = cmdutil.GetRecordFlag(cmd)
|
||||
o.ChangeCause = f.Command()
|
||||
o.PrintObject = f.PrintObject
|
||||
o.Cmd = cmd
|
||||
|
||||
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
o.Resources, o.ContainerImages, err = getResourcesAndImages(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
|
||||
ContinueOnError().
|
||||
NamespaceParam(cmdNamespace).DefaultNamespace().
|
||||
FilenameParam(enforceNamespace, &o.FilenameOptions).
|
||||
Flatten()
|
||||
if !o.Local {
|
||||
builder = builder.
|
||||
SelectorParam(o.Selector).
|
||||
ResourceTypeOrNameArgs(o.All, o.Resources...).
|
||||
Latest()
|
||||
}
|
||||
o.Infos, err = builder.Do().Infos()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *ImageOptions) Validate() error {
|
||||
errors := []error{}
|
||||
if len(o.Resources) < 1 && cmdutil.IsFilenameEmpty(o.Filenames) {
|
||||
errors = append(errors, fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>"))
|
||||
}
|
||||
if len(o.ContainerImages) < 1 {
|
||||
errors = append(errors, fmt.Errorf("at least one image update is required"))
|
||||
} else if len(o.ContainerImages) > 1 && hasWildcardKey(o.ContainerImages) {
|
||||
errors = append(errors, fmt.Errorf("all containers are already specified by *, but saw more than one container_name=container_image pairs"))
|
||||
}
|
||||
return utilerrors.NewAggregate(errors)
|
||||
}
|
||||
|
||||
func (o *ImageOptions) Run() error {
|
||||
allErrs := []error{}
|
||||
|
||||
patches := CalculatePatches(o.Infos, o.Encoder, func(info *resource.Info) (bool, error) {
|
||||
transformed := false
|
||||
_, err := o.UpdatePodSpecForObject(info.Object, func(spec *api.PodSpec) error {
|
||||
for name, image := range o.ContainerImages {
|
||||
containerFound := false
|
||||
// Find the container to update, and update its image
|
||||
for i, c := range spec.Containers {
|
||||
if c.Name == name || name == "*" {
|
||||
spec.Containers[i].Image = image
|
||||
containerFound = true
|
||||
// Perform updates
|
||||
transformed = true
|
||||
}
|
||||
}
|
||||
// Add a new container if not found
|
||||
if !containerFound {
|
||||
allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %q", name))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return transformed, err
|
||||
})
|
||||
|
||||
for _, patch := range patches {
|
||||
info := patch.Info
|
||||
if patch.Err != nil {
|
||||
allErrs = append(allErrs, fmt.Errorf("error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err))
|
||||
continue
|
||||
}
|
||||
|
||||
// no changes
|
||||
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if o.Local {
|
||||
return o.PrintObject(o.Cmd, o.Mapper, info.Object, o.Out)
|
||||
}
|
||||
|
||||
// patch the change
|
||||
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch.Patch)
|
||||
if err != nil {
|
||||
allErrs = append(allErrs, fmt.Errorf("failed to patch image update to pod template: %v\n", err))
|
||||
continue
|
||||
}
|
||||
info.Refresh(obj, true)
|
||||
|
||||
// record this change (for rollout history)
|
||||
if o.Record || cmdutil.ContainsChangeCause(info) {
|
||||
if patch, err := cmdutil.ChangeResourcePatch(info, o.ChangeCause); err == nil {
|
||||
if obj, err = resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch); err != nil {
|
||||
fmt.Fprintf(o.Err, "WARNING: changes to %s/%s can't be recorded: %v\n", info.Mapping.Resource, info.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info.Refresh(obj, true)
|
||||
cmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "image updated")
|
||||
}
|
||||
return utilerrors.NewAggregate(allErrs)
|
||||
}
|
||||
|
||||
// getResourcesAndImages retrieves resources and container name:images pair from given args
|
||||
func getResourcesAndImages(args []string) (resources []string, containerImages map[string]string, err error) {
|
||||
pairType := "image"
|
||||
resources, imageArgs, err := cmdutil.GetResourcesAndPairs(args, pairType)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
containerImages, _, err = cmdutil.ParsePairs(imageArgs, pairType, false)
|
||||
return
|
||||
}
|
||||
|
||||
func hasWildcardKey(containerImages map[string]string) bool {
|
||||
_, ok := containerImages["*"]
|
||||
return ok
|
||||
}
|
||||
69
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_image_test.go
generated
vendored
Normal file
69
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_image_test.go
generated
vendored
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
/*
|
||||
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 set
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/apimachinery/registered"
|
||||
"k8s.io/kubernetes/pkg/client/restclient"
|
||||
"k8s.io/kubernetes/pkg/client/restclient/fake"
|
||||
cmdtesting "k8s.io/kubernetes/pkg/kubectl/cmd/testing"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
"k8s.io/kubernetes/pkg/kubectl/resource"
|
||||
)
|
||||
|
||||
func TestImageLocal(t *testing.T) {
|
||||
f, tf, _, ns := cmdtesting.NewAPIFactory()
|
||||
tf.Client = &fake.RESTClient{
|
||||
NegotiatedSerializer: ns,
|
||||
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
|
||||
t.Fatalf("unexpected request: %s %#v\n%#v", req.Method, req.URL, req)
|
||||
return nil, nil
|
||||
}),
|
||||
}
|
||||
tf.Namespace = "test"
|
||||
tf.ClientConfig = &restclient.Config{ContentConfig: restclient.ContentConfig{GroupVersion: ®istered.GroupOrDie(api.GroupName).GroupVersion}}
|
||||
|
||||
buf := bytes.NewBuffer([]byte{})
|
||||
cmd := NewCmdImage(f, buf, buf)
|
||||
cmd.SetOutput(buf)
|
||||
cmd.Flags().Set("output", "name")
|
||||
tf.Printer, _, _ = cmdutil.PrinterForCommand(cmd)
|
||||
|
||||
opts := ImageOptions{FilenameOptions: resource.FilenameOptions{
|
||||
Filenames: []string{"../../../../examples/storage/cassandra/cassandra-controller.yaml"}},
|
||||
Out: buf,
|
||||
Local: true}
|
||||
err := opts.Complete(f, cmd, []string{"cassandra=thingy"})
|
||||
if err == nil {
|
||||
err = opts.Validate()
|
||||
}
|
||||
if err == nil {
|
||||
err = opts.Run()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "replicationcontroller/cassandra") {
|
||||
t.Errorf("did not set image: %s", buf.String())
|
||||
}
|
||||
}
|
||||
242
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_resources.go
generated
vendored
Normal file
242
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/set/set_resources.go
generated
vendored
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
/*
|
||||
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 set
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"k8s.io/kubernetes/pkg/api"
|
||||
"k8s.io/kubernetes/pkg/api/meta"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
"k8s.io/kubernetes/pkg/kubectl/resource"
|
||||
"k8s.io/kubernetes/pkg/runtime"
|
||||
utilerrors "k8s.io/kubernetes/pkg/util/errors"
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
Mapper meta.RESTMapper
|
||||
Typer runtime.ObjectTyper
|
||||
Infos []*resource.Info
|
||||
Encoder runtime.Encoder
|
||||
Out io.Writer
|
||||
Err io.Writer
|
||||
Selector string
|
||||
ContainerSelector string
|
||||
ShortOutput bool
|
||||
All bool
|
||||
Record bool
|
||||
ChangeCause string
|
||||
Local bool
|
||||
Cmd *cobra.Command
|
||||
|
||||
Limits string
|
||||
Requests string
|
||||
ResourceRequirements api.ResourceRequirements
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func NewCmdResources(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
|
||||
options := &ResourcesOptions{
|
||||
Out: out,
|
||||
Err: errOut,
|
||||
}
|
||||
|
||||
resourceTypesWithPodTemplate := []string{}
|
||||
for _, resource := range f.SuggestedPodTemplateResources() {
|
||||
resourceTypesWithPodTemplate = append(resourceTypesWithPodTemplate, resource.Resource)
|
||||
}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "resources (-f FILENAME | TYPE NAME) ([--limits=LIMITS & --requests=REQUESTS]",
|
||||
Short: "update resource requests/limits on objects with pod templates",
|
||||
Long: fmt.Sprintf(resources_long, strings.Join(resourceTypesWithPodTemplate, ", ")),
|
||||
Example: resources_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cmdutil.CheckErr(options.Complete(f, cmd, args))
|
||||
cmdutil.CheckErr(options.Validate())
|
||||
cmdutil.CheckErr(options.Run())
|
||||
},
|
||||
}
|
||||
|
||||
cmdutil.AddPrinterFlags(cmd)
|
||||
//usage := "Filename, directory, or URL to a file identifying the resource to get from the server"
|
||||
//kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
|
||||
usage := "identifying the resource to get from a server."
|
||||
cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage)
|
||||
cmd.Flags().BoolVar(&options.All, "all", false, "select all resources in the namespace of the specified resource types")
|
||||
cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on")
|
||||
cmd.Flags().StringVarP(&options.ContainerSelector, "containers", "c", "*", "The names of containers in the selected pod templates to change, all containers are selected by default - may use wildcards")
|
||||
cmd.Flags().BoolVar(&options.Local, "local", false, "If true, set resources will NOT contact api-server but run locally.")
|
||||
cmdutil.AddDryRunFlag(cmd)
|
||||
cmdutil.AddRecordFlag(cmd)
|
||||
cmd.Flags().StringVar(&options.Limits, "limits", options.Limits, "The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.")
|
||||
cmd.Flags().StringVar(&options.Requests, "requests", options.Requests, "The resource requirement requests for this container. For example, 'cpu=100m,memory=256Mi'. Note that server side components may assign requests depending on the server configuration, such as limit ranges.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func (o *ResourcesOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
|
||||
o.Mapper, o.Typer = f.Object()
|
||||
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
|
||||
o.Encoder = f.JSONEncoder()
|
||||
o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
|
||||
o.Record = cmdutil.GetRecordFlag(cmd)
|
||||
o.ChangeCause = f.Command()
|
||||
o.PrintObject = f.PrintObject
|
||||
o.Cmd = cmd
|
||||
|
||||
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
builder := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
|
||||
ContinueOnError().
|
||||
NamespaceParam(cmdNamespace).DefaultNamespace().
|
||||
//FilenameParam(enforceNamespace, o.Filenames...).
|
||||
FilenameParam(enforceNamespace, &o.FilenameOptions).
|
||||
Flatten()
|
||||
if !o.Local {
|
||||
builder = builder.
|
||||
SelectorParam(o.Selector).
|
||||
ResourceTypeOrNameArgs(o.All, args...).
|
||||
Latest()
|
||||
}
|
||||
|
||||
o.Infos, err = builder.Do().Infos()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *ResourcesOptions) Validate() error {
|
||||
var err error
|
||||
if len(o.Limits) == 0 && len(o.Requests) == 0 {
|
||||
return fmt.Errorf("you must specify an update to requests or limits (in the form of --requests/--limits)")
|
||||
}
|
||||
|
||||
o.ResourceRequirements, err = kubectl.HandleResourceRequirements(map[string]string{"limits": o.Limits, "requests": o.Requests})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *ResourcesOptions) Run() error {
|
||||
allErrs := []error{}
|
||||
patches := CalculatePatches(o.Infos, o.Encoder, func(info *resource.Info) (bool, error) {
|
||||
transformed := false
|
||||
_, err := o.UpdatePodSpecForObject(info.Object, func(spec *api.PodSpec) error {
|
||||
containers, _ := selectContainers(spec.Containers, o.ContainerSelector)
|
||||
if len(containers) != 0 {
|
||||
for i := range containers {
|
||||
if len(o.Limits) != 0 && len(containers[i].Resources.Limits) == 0 {
|
||||
containers[i].Resources.Limits = make(api.ResourceList)
|
||||
}
|
||||
for key, value := range o.ResourceRequirements.Limits {
|
||||
containers[i].Resources.Limits[key] = value
|
||||
}
|
||||
|
||||
if len(o.Requests) != 0 && len(containers[i].Resources.Requests) == 0 {
|
||||
containers[i].Resources.Requests = make(api.ResourceList)
|
||||
}
|
||||
for key, value := range o.ResourceRequirements.Requests {
|
||||
containers[i].Resources.Requests[key] = value
|
||||
}
|
||||
transformed = true
|
||||
}
|
||||
} else {
|
||||
allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %s", o.ContainerSelector))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return transformed, err
|
||||
})
|
||||
|
||||
for _, patch := range patches {
|
||||
info := patch.Info
|
||||
if patch.Err != nil {
|
||||
allErrs = append(allErrs, fmt.Errorf("error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err))
|
||||
continue
|
||||
}
|
||||
|
||||
//no changes
|
||||
if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
|
||||
allErrs = append(allErrs, fmt.Errorf("info: %s %q was not changed\n", info.Mapping.Resource, info.Name))
|
||||
continue
|
||||
}
|
||||
|
||||
if o.Local || cmdutil.GetDryRunFlag(o.Cmd) {
|
||||
return o.PrintObject(o.Cmd, o.Mapper, info.Object, o.Out)
|
||||
}
|
||||
|
||||
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch.Patch)
|
||||
if err != nil {
|
||||
allErrs = append(allErrs, fmt.Errorf("failed to patch limit update to pod template %v\n", err))
|
||||
continue
|
||||
}
|
||||
info.Refresh(obj, true)
|
||||
|
||||
//record this change (for rollout history)
|
||||
if o.Record || cmdutil.ContainsChangeCause(info) {
|
||||
if err := cmdutil.RecordChangeCause(obj, o.ChangeCause); err == nil {
|
||||
if obj, err = resource.NewHelper(info.Client, info.Mapping).Replace(info.Namespace, info.Name, false, obj); err != nil {
|
||||
allErrs = append(allErrs, fmt.Errorf("changes to %s/%s can't be recorded: %v\n", info.Mapping.Resource, info.Name, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
info.Refresh(obj, true)
|
||||
cmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, false, "resource requirements updated")
|
||||
}
|
||||
return utilerrors.NewAggregate(allErrs)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue