rollout_status.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 rollout
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. "github.com/spf13/cobra"
  19. apierrors "k8s.io/apimachinery/pkg/api/errors"
  20. "k8s.io/apimachinery/pkg/api/meta"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  23. "k8s.io/apimachinery/pkg/fields"
  24. "k8s.io/apimachinery/pkg/runtime"
  25. "k8s.io/apimachinery/pkg/watch"
  26. "k8s.io/cli-runtime/pkg/genericclioptions"
  27. "k8s.io/cli-runtime/pkg/resource"
  28. "k8s.io/client-go/dynamic"
  29. "k8s.io/client-go/tools/cache"
  30. watchtools "k8s.io/client-go/tools/watch"
  31. "k8s.io/kubernetes/pkg/kubectl"
  32. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  33. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  34. "k8s.io/kubernetes/pkg/kubectl/scheme"
  35. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  36. "k8s.io/kubernetes/pkg/kubectl/util/interrupt"
  37. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  38. )
  39. var (
  40. statusLong = templates.LongDesc(`
  41. Show the status of the rollout.
  42. By default 'rollout status' will watch the status of the latest rollout
  43. until it's done. If you don't want to wait for the rollout to finish then
  44. you can use --watch=false. Note that if a new rollout starts in-between, then
  45. 'rollout status' will continue watching the latest revision. If you want to
  46. pin to a specific revision and abort if it is rolled over by another revision,
  47. use --revision=N where N is the revision you need to watch for.`)
  48. statusExample = templates.Examples(`
  49. # Watch the rollout status of a deployment
  50. kubectl rollout status deployment/nginx`)
  51. )
  52. // RolloutStatusOptions holds the command-line options for 'rollout status' sub command
  53. type RolloutStatusOptions struct {
  54. PrintFlags *genericclioptions.PrintFlags
  55. Namespace string
  56. EnforceNamespace bool
  57. BuilderArgs []string
  58. Watch bool
  59. Revision int64
  60. Timeout time.Duration
  61. StatusViewerFn func(*meta.RESTMapping) (kubectl.StatusViewer, error)
  62. Builder func() *resource.Builder
  63. DynamicClient dynamic.Interface
  64. FilenameOptions *resource.FilenameOptions
  65. genericclioptions.IOStreams
  66. }
  67. // NewRolloutStatusOptions returns an initialized RolloutStatusOptions instance
  68. func NewRolloutStatusOptions(streams genericclioptions.IOStreams) *RolloutStatusOptions {
  69. return &RolloutStatusOptions{
  70. PrintFlags: genericclioptions.NewPrintFlags("").WithTypeSetter(scheme.Scheme),
  71. FilenameOptions: &resource.FilenameOptions{},
  72. IOStreams: streams,
  73. Watch: true,
  74. Timeout: 0,
  75. }
  76. }
  77. // NewCmdRolloutStatus returns a Command instance for the 'rollout status' sub command
  78. func NewCmdRolloutStatus(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  79. o := NewRolloutStatusOptions(streams)
  80. validArgs := []string{"deployment", "daemonset", "statefulset"}
  81. cmd := &cobra.Command{
  82. Use: "status (TYPE NAME | TYPE/NAME) [flags]",
  83. DisableFlagsInUseLine: true,
  84. Short: i18n.T("Show the status of the rollout"),
  85. Long: statusLong,
  86. Example: statusExample,
  87. Run: func(cmd *cobra.Command, args []string) {
  88. cmdutil.CheckErr(o.Complete(f, args))
  89. cmdutil.CheckErr(o.Validate())
  90. cmdutil.CheckErr(o.Run())
  91. },
  92. ValidArgs: validArgs,
  93. }
  94. usage := "identifying the resource to get from a server."
  95. cmdutil.AddFilenameOptionFlags(cmd, o.FilenameOptions, usage)
  96. cmd.Flags().BoolVarP(&o.Watch, "watch", "w", o.Watch, "Watch the status of the rollout until it's done.")
  97. cmd.Flags().Int64Var(&o.Revision, "revision", o.Revision, "Pin to a specific revision for showing its status. Defaults to 0 (last revision).")
  98. cmd.Flags().DurationVar(&o.Timeout, "timeout", o.Timeout, "The length of time to wait before ending watch, zero means never. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).")
  99. return cmd
  100. }
  101. // Complete completes all the required options
  102. func (o *RolloutStatusOptions) Complete(f cmdutil.Factory, args []string) error {
  103. o.Builder = f.NewBuilder
  104. var err error
  105. o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
  106. if err != nil {
  107. return err
  108. }
  109. o.BuilderArgs = args
  110. o.StatusViewerFn = polymorphichelpers.StatusViewerFn
  111. clientConfig, err := f.ToRESTConfig()
  112. if err != nil {
  113. return err
  114. }
  115. o.DynamicClient, err = dynamic.NewForConfig(clientConfig)
  116. if err != nil {
  117. return err
  118. }
  119. return nil
  120. }
  121. // Validate makes sure all the provided values for command-line options are valid
  122. func (o *RolloutStatusOptions) Validate() error {
  123. if len(o.BuilderArgs) == 0 && cmdutil.IsFilenameSliceEmpty(o.FilenameOptions.Filenames, o.FilenameOptions.Kustomize) {
  124. return fmt.Errorf("required resource not specified")
  125. }
  126. if o.Revision < 0 {
  127. return fmt.Errorf("revision must be a positive integer: %v", o.Revision)
  128. }
  129. return nil
  130. }
  131. // Run performs the execution of 'rollout status' sub command
  132. func (o *RolloutStatusOptions) Run() error {
  133. r := o.Builder().
  134. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  135. NamespaceParam(o.Namespace).DefaultNamespace().
  136. FilenameParam(o.EnforceNamespace, o.FilenameOptions).
  137. ResourceTypeOrNameArgs(true, o.BuilderArgs...).
  138. SingleResourceType().
  139. Latest().
  140. Do()
  141. err := r.Err()
  142. if err != nil {
  143. return err
  144. }
  145. infos, err := r.Infos()
  146. if err != nil {
  147. return err
  148. }
  149. if len(infos) != 1 {
  150. return fmt.Errorf("rollout status is only supported on individual resources and resource collections - %d resources were found", len(infos))
  151. }
  152. info := infos[0]
  153. mapping := info.ResourceMapping()
  154. statusViewer, err := o.StatusViewerFn(mapping)
  155. if err != nil {
  156. return err
  157. }
  158. fieldSelector := fields.OneTermEqualSelector("metadata.name", info.Name).String()
  159. lw := &cache.ListWatch{
  160. ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
  161. options.FieldSelector = fieldSelector
  162. return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).List(options)
  163. },
  164. WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
  165. options.FieldSelector = fieldSelector
  166. return o.DynamicClient.Resource(info.Mapping.Resource).Namespace(info.Namespace).Watch(options)
  167. },
  168. }
  169. preconditionFunc := func(store cache.Store) (bool, error) {
  170. _, exists, err := store.Get(&metav1.ObjectMeta{Namespace: info.Namespace, Name: info.Name})
  171. if err != nil {
  172. return true, err
  173. }
  174. if !exists {
  175. // We need to make sure we see the object in the cache before we start waiting for events
  176. // or we would be waiting for the timeout if such object didn't exist.
  177. return true, apierrors.NewNotFound(mapping.Resource.GroupResource(), info.Name)
  178. }
  179. return false, nil
  180. }
  181. // if the rollout isn't done yet, keep watching deployment status
  182. ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), o.Timeout)
  183. intr := interrupt.New(nil, cancel)
  184. return intr.Run(func() error {
  185. _, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, preconditionFunc, func(e watch.Event) (bool, error) {
  186. switch t := e.Type; t {
  187. case watch.Added, watch.Modified:
  188. status, done, err := statusViewer.Status(e.Object.(runtime.Unstructured), o.Revision)
  189. if err != nil {
  190. return false, err
  191. }
  192. fmt.Fprintf(o.Out, "%s", status)
  193. // Quit waiting if the rollout is done
  194. if done {
  195. return true, nil
  196. }
  197. shouldWatch := o.Watch
  198. if !shouldWatch {
  199. return true, nil
  200. }
  201. return false, nil
  202. case watch.Deleted:
  203. // We need to abort to avoid cases of recreation and not to silently watch the wrong (new) object
  204. return true, fmt.Errorf("object has been deleted")
  205. default:
  206. return true, fmt.Errorf("internal error: unexpected event %#v", e)
  207. }
  208. })
  209. return err
  210. })
  211. }