set_image.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package set
  14. import (
  15. "fmt"
  16. "io"
  17. "github.com/renstrom/dedent"
  18. "github.com/spf13/cobra"
  19. "k8s.io/kubernetes/pkg/api"
  20. "k8s.io/kubernetes/pkg/api/meta"
  21. "k8s.io/kubernetes/pkg/kubectl"
  22. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  23. "k8s.io/kubernetes/pkg/kubectl/resource"
  24. "k8s.io/kubernetes/pkg/runtime"
  25. utilerrors "k8s.io/kubernetes/pkg/util/errors"
  26. )
  27. // ImageOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  28. // referencing the cmd.Flags()
  29. type ImageOptions struct {
  30. Mapper meta.RESTMapper
  31. Typer runtime.ObjectTyper
  32. Infos []*resource.Info
  33. Encoder runtime.Encoder
  34. Selector string
  35. Out io.Writer
  36. Err io.Writer
  37. Filenames []string
  38. Recursive bool
  39. ShortOutput bool
  40. All bool
  41. Record bool
  42. ChangeCause string
  43. Local bool
  44. Cmd *cobra.Command
  45. PrintObject func(cmd *cobra.Command, mapper meta.RESTMapper, obj runtime.Object, out io.Writer) error
  46. UpdatePodSpecForObject func(obj runtime.Object, fn func(*api.PodSpec) error) (bool, error)
  47. Resources []string
  48. ContainerImages map[string]string
  49. }
  50. var (
  51. image_resources = `
  52. pod (po), replicationcontroller (rc), deployment, daemonset (ds), job, replicaset (rs)`
  53. image_long = dedent.Dedent(`
  54. Update existing container image(s) of resources.
  55. Possible resources include (case insensitive):`) + image_resources
  56. image_example = dedent.Dedent(`
  57. # Set a deployment's nginx container image to 'nginx:1.9.1', and its busybox container image to 'busybox'.
  58. kubectl set image deployment/nginx busybox=busybox nginx=nginx:1.9.1
  59. # Update all deployments' and rc's nginx container's image to 'nginx:1.9.1'
  60. kubectl set image deployments,rc nginx=nginx:1.9.1 --all
  61. # Update image of all containers of daemonset abc to 'nginx:1.9.1'
  62. kubectl set image daemonset abc *=nginx:1.9.1
  63. # Print result (in yaml format) of updating nginx container image from local file, without hitting the server
  64. kubectl set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml`)
  65. )
  66. func NewCmdImage(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  67. options := &ImageOptions{
  68. Out: out,
  69. }
  70. cmd := &cobra.Command{
  71. Use: "image (-f FILENAME | TYPE NAME) CONTAINER_NAME_1=CONTAINER_IMAGE_1 ... CONTAINER_NAME_N=CONTAINER_IMAGE_N",
  72. Short: "Update image of a pod template",
  73. Long: image_long,
  74. Example: image_example,
  75. Run: func(cmd *cobra.Command, args []string) {
  76. cmdutil.CheckErr(options.Complete(f, cmd, args))
  77. cmdutil.CheckErr(options.Validate())
  78. cmdutil.CheckErr(options.Run())
  79. },
  80. }
  81. cmdutil.AddPrinterFlags(cmd)
  82. usage := "Filename, directory, or URL to a file identifying the resource to get from a server."
  83. kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
  84. cmd.Flags().BoolVar(&options.All, "all", false, "select all resources in the namespace of the specified resource types")
  85. cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on")
  86. cmd.Flags().BoolVar(&options.Local, "local", false, "If true, set image will NOT contact api-server but run locally.")
  87. cmdutil.AddRecordFlag(cmd)
  88. cmdutil.AddRecursiveFlag(cmd, &options.Recursive)
  89. return cmd
  90. }
  91. func (o *ImageOptions) Complete(f *cmdutil.Factory, cmd *cobra.Command, args []string) error {
  92. o.Mapper, o.Typer = f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
  93. o.UpdatePodSpecForObject = f.UpdatePodSpecForObject
  94. o.Encoder = f.JSONEncoder()
  95. o.ShortOutput = cmdutil.GetFlagString(cmd, "output") == "name"
  96. o.Record = cmdutil.GetRecordFlag(cmd)
  97. o.ChangeCause = f.Command()
  98. o.PrintObject = f.PrintObject
  99. o.Cmd = cmd
  100. cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
  101. if err != nil {
  102. return err
  103. }
  104. o.Resources, o.ContainerImages, err = getResourcesAndImages(args)
  105. if err != nil {
  106. return err
  107. }
  108. builder := resource.NewBuilder(o.Mapper, o.Typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
  109. ContinueOnError().
  110. NamespaceParam(cmdNamespace).DefaultNamespace().
  111. FilenameParam(enforceNamespace, o.Recursive, o.Filenames...).
  112. Flatten()
  113. if !o.Local {
  114. builder = builder.
  115. SelectorParam(o.Selector).
  116. ResourceTypeOrNameArgs(o.All, o.Resources...).
  117. Latest()
  118. }
  119. o.Infos, err = builder.Do().Infos()
  120. if err != nil {
  121. return err
  122. }
  123. return nil
  124. }
  125. func (o *ImageOptions) Validate() error {
  126. if len(o.Resources) < 1 && len(o.Filenames) == 0 {
  127. return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>")
  128. }
  129. if len(o.ContainerImages) < 1 {
  130. return fmt.Errorf("at least one image update is required")
  131. } else if len(o.ContainerImages) > 1 && hasWildcardKey(o.ContainerImages) {
  132. return fmt.Errorf("all containers are already specified by *, but saw more than one container_name=container_image pairs")
  133. }
  134. return nil
  135. }
  136. func (o *ImageOptions) Run() error {
  137. allErrs := []error{}
  138. patches := CalculatePatches(o.Infos, o.Encoder, func(info *resource.Info) (bool, error) {
  139. transformed := false
  140. _, err := o.UpdatePodSpecForObject(info.Object, func(spec *api.PodSpec) error {
  141. for name, image := range o.ContainerImages {
  142. containerFound := false
  143. // Find the container to update, and update its image
  144. for i, c := range spec.Containers {
  145. if c.Name == name || name == "*" {
  146. spec.Containers[i].Image = image
  147. containerFound = true
  148. // Perform updates
  149. transformed = true
  150. }
  151. }
  152. // Add a new container if not found
  153. if !containerFound {
  154. allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %q", name))
  155. }
  156. }
  157. return nil
  158. })
  159. return transformed, err
  160. })
  161. for _, patch := range patches {
  162. info := patch.Info
  163. if patch.Err != nil {
  164. allErrs = append(allErrs, fmt.Errorf("error: %s/%s %v\n", info.Mapping.Resource, info.Name, patch.Err))
  165. continue
  166. }
  167. // no changes
  168. if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
  169. continue
  170. }
  171. if o.Local {
  172. fmt.Fprintln(o.Out, "running in local mode...")
  173. return o.PrintObject(o.Cmd, o.Mapper, info.Object, o.Out)
  174. }
  175. // patch the change
  176. obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch.Patch)
  177. if err != nil {
  178. allErrs = append(allErrs, fmt.Errorf("failed to patch image update to pod template: %v\n", err))
  179. continue
  180. }
  181. info.Refresh(obj, true)
  182. // record this change (for rollout history)
  183. if o.Record || cmdutil.ContainsChangeCause(info) {
  184. if patch, err := cmdutil.ChangeResourcePatch(info, o.ChangeCause); err == nil {
  185. if obj, err = resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch); err != nil {
  186. fmt.Fprintf(o.Err, "WARNING: changes to %s/%s can't be recorded: %v\n", info.Mapping.Resource, info.Name, err)
  187. }
  188. }
  189. }
  190. info.Refresh(obj, true)
  191. cmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, "image updated")
  192. }
  193. return utilerrors.NewAggregate(allErrs)
  194. }
  195. // getResourcesAndImages retrieves resources and container name:images pair from given args
  196. func getResourcesAndImages(args []string) (resources []string, containerImages map[string]string, err error) {
  197. pairType := "image"
  198. resources, imageArgs, err := cmdutil.GetResourcesAndPairs(args, pairType)
  199. if err != nil {
  200. return
  201. }
  202. containerImages, _, err = cmdutil.ParsePairs(imageArgs, pairType, false)
  203. return
  204. }
  205. func hasWildcardKey(containerImages map[string]string) bool {
  206. _, ok := containerImages["*"]
  207. return ok
  208. }