forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set_image.go
318 lines (270 loc) · 9.73 KB
/
set_image.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*
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"
"k8s.io/kubernetes/pkg/printers"
"github.com/golang/glog"
"github.com/spf13/cobra"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/resource"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
// 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 SetImageOptions struct {
resource.FilenameOptions
PrintFlags *printers.PrintFlags
RecordFlags *genericclioptions.RecordFlags
Infos []*resource.Info
Selector string
Out io.Writer
Err io.Writer
DryRun bool
All bool
Output string
ChangeCause string
Local bool
Cmd *cobra.Command
ResolveImage func(in string) (string, error)
PrintObj printers.ResourcePrinterFunc
Recorder genericclioptions.Recorder
UpdatePodSpecForObject func(obj runtime.Object, fn func(*v1.PodSpec) error) (bool, error)
Resources []string
ContainerImages map[string]string
}
var (
image_resources = `
pod (po), replicationcontroller (rc), deployment (deploy), daemonset (ds), 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 NewImageOptions(out, errOut io.Writer) *SetImageOptions {
return &SetImageOptions{
PrintFlags: printers.NewPrintFlags("image updated"),
RecordFlags: genericclioptions.NewRecordFlags(),
Recorder: genericclioptions.NoopRecorder{},
Out: out,
Err: errOut,
}
}
func NewCmdImage(f cmdutil.Factory, out, errOut io.Writer) *cobra.Command {
o := NewImageOptions(out, errOut)
cmd := &cobra.Command{
Use: "image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N",
DisableFlagsInUseLine: true,
Short: i18n.T("Update image of a pod template"),
Long: image_long,
Example: image_example,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd, args))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Run())
},
}
o.PrintFlags.AddFlags(cmd)
o.RecordFlags.AddFlags(cmd)
usage := "identifying the resource to get from a server."
cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
cmd.Flags().BoolVar(&o.All, "all", o.All, "Select all resources, including uninitialized ones, in the namespace of the specified resource types")
cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
cmd.Flags().BoolVar(&o.Local, "local", o.Local, "If true, set image will NOT contact api-server but run locally.")
cmdutil.AddDryRunFlag(cmd)
cmdutil.AddIncludeUninitializedFlag(cmd)
return cmd
}
func (o *SetImageOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
var err error
o.RecordFlags.Complete(f.Command(cmd, false))
o.Recorder, err = o.RecordFlags.ToRecorder()
if err != nil {
return err
}
o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
o.ChangeCause = f.Command(cmd, false)
o.DryRun = cmdutil.GetDryRunFlag(cmd)
o.Output = cmdutil.GetFlagString(cmd, "output")
o.ResolveImage = f.ResolveImage
o.Cmd = cmd
if o.DryRun {
o.PrintFlags.Complete("%s (dry run)")
}
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return err
}
o.PrintObj = printer.PrintObj
cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
if err != nil {
return err
}
o.Resources, o.ContainerImages, err = getResourcesAndImages(args)
if err != nil {
return err
}
includeUninitialized := cmdutil.ShouldIncludeUninitialized(cmd, false)
builder := f.NewBuilder().
Internal().
LocalParam(o.Local).
ContinueOnError().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &o.FilenameOptions).
IncludeUninitialized(includeUninitialized).
Flatten()
if !o.Local {
builder.LabelSelectorParam(o.Selector).
ResourceTypeOrNameArgs(o.All, o.Resources...).
Latest()
} else {
// if a --local flag was provided, and a resource was specified in the form
// <resource>/<name>, fail immediately as --local cannot query the api server
// for the specified resource.
if len(o.Resources) > 0 {
return resource.LocalResourceError
}
}
o.Infos, err = builder.Do().Infos()
if err != nil {
return err
}
return nil
}
func (o *SetImageOptions) Validate() error {
errors := []error{}
if o.All && len(o.Selector) > 0 {
errors = append(errors, fmt.Errorf("cannot set --all and --selector at the same time"))
}
if len(o.Resources) < 1 && cmdutil.IsFilenameSliceEmpty(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 *SetImageOptions) Run() error {
allErrs := []error{}
patches := CalculatePatches(o.Infos, cmdutil.InternalVersionJSONEncoder(), func(info *resource.Info) ([]byte, error) {
transformed := false
info.Object = info.AsVersioned()
_, err := o.UpdatePodSpecForObject(info.Object, func(spec *v1.PodSpec) error {
for name, image := range o.ContainerImages {
var (
containerFound bool
err error
resolved string
)
// Find the container to update, and update its image
for i, c := range spec.Containers {
if c.Name == name || name == "*" {
containerFound = true
if len(resolved) == 0 {
if resolved, err = o.ResolveImage(image); err != nil {
allErrs = append(allErrs, fmt.Errorf("error: unable to resolve image %q for container %q: %v", image, name, err))
// Do not loop again if the image resolving failed for wildcard case as we
// will report the same error again for the next container.
if name == "*" {
break
}
continue
}
}
if spec.Containers[i].Image != resolved {
spec.Containers[i].Image = resolved
// 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
})
if err != nil {
return nil, err
}
if !transformed {
return nil, nil
}
// record this change (for rollout history)
if err := o.Recorder.Record(info.Object); err != nil {
glog.V(4).Infof("error recording current command: %v", err)
}
return runtime.Encode(cmdutil.InternalVersionJSONEncoder(), info.Object)
})
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 || o.DryRun {
if err := o.PrintObj(patch.Info.AsVersioned(), o.Out); err != nil {
return err
}
continue
}
// patch the change
obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.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)
if err := o.PrintObj(info.AsVersioned(), o.Out); err != nil {
return err
}
}
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
}