forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcancel.go
259 lines (221 loc) · 7.76 KB
/
cancel.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
package rollout
import (
"fmt"
"sort"
"strings"
"time"
"github.com/docker/go-units"
"github.com/spf13/cobra"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/client-go/kubernetes"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/printers"
"k8s.io/kubernetes/pkg/kubectl/genericclioptions/resource"
"k8s.io/kubernetes/pkg/kubectl/scheme"
appsv1 "github.com/openshift/api/apps/v1"
appsutil "github.com/openshift/origin/pkg/apps/util"
"github.com/openshift/origin/pkg/oc/cli/set"
)
type CancelOptions struct {
PrintFlags *genericclioptions.PrintFlags
Builder func() *resource.Builder
Namespace string
NamespaceExplicit bool
Mapper meta.RESTMapper
Encoder runtime.Encoder
Resources []string
KubeClient kubernetes.Interface
Printer func(string) (printers.ResourcePrinter, error)
resource.FilenameOptions
genericclioptions.IOStreams
}
var (
rolloutCancelLong = templates.LongDesc(`
Cancel the in-progress deployment
Running this command will cause the current in-progress deployment to be
cancelled, but keep in mind that this is a best-effort operation and may take
some time to complete. It’s possible the deployment will partially or totally
complete before the cancellation is effective. In such a case an appropriate
event will be emitted.`)
rolloutCancelExample = templates.Examples(`
# Cancel the in-progress deployment based on 'nginx'
%[1]s rollout cancel dc/nginx`)
)
func NewRolloutCancelOptions(streams genericclioptions.IOStreams) *CancelOptions {
return &CancelOptions{
IOStreams: streams,
PrintFlags: genericclioptions.NewPrintFlags("already cancelled"),
}
}
func NewCmdRolloutCancel(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewRolloutCancelOptions(streams)
cmd := &cobra.Command{
Use: "cancel (TYPE NAME | TYPE/NAME) [flags]",
Long: rolloutCancelLong,
Example: fmt.Sprintf(rolloutCancelExample, fullName),
Short: "cancel the in-progress deployment",
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, cmd, args))
kcmdutil.CheckErr(o.Run())
},
ValidArgs: []string{"deploymentconfig"},
}
o.PrintFlags.AddFlags(cmd)
usage := "Filename, directory, or URL to a file identifying the resource to get from a server."
kcmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
return cmd
}
func (o *CancelOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
if len(args) == 0 && len(o.FilenameOptions.Filenames) == 0 {
return kcmdutil.UsageErrorf(cmd, "a resource or filename must be specified")
}
var err error
o.Mapper, err = f.ToRESTMapper()
if err != nil {
return err
}
o.Encoder = kcmdutil.InternalVersionJSONEncoder()
o.Namespace, o.NamespaceExplicit, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
config, err := f.ToRESTConfig()
if err != nil {
return err
}
o.KubeClient, err = kubernetes.NewForConfig(config)
if err != nil {
return err
}
o.Printer = func(successMsg string) (printers.ResourcePrinter, error) {
o.PrintFlags.Complete(successMsg)
return o.PrintFlags.ToPrinter()
}
o.Builder = f.NewBuilder
o.Resources = args
return nil
}
func (o CancelOptions) Run() error {
r := o.Builder().
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
NamespaceParam(o.Namespace).DefaultNamespace().
FilenameParam(o.NamespaceExplicit, &o.FilenameOptions).
ResourceTypeOrNameArgs(true, o.Resources...).
ContinueOnError().
Latest().
Flatten().
Do()
if err := r.Err(); err != nil {
return err
}
infos, err := r.Infos()
if err != nil {
return err
}
allErrs := []error{}
for _, info := range infos {
config, ok := info.Object.(*appsv1.DeploymentConfig)
if !ok {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, fmt.Errorf("expected deployment configuration, got %s", info.Mapping.Resource.Resource)))
continue
}
if config.Spec.Paused {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, fmt.Errorf("unable to cancel paused deployment %s/%s", config.Namespace, config.Name)))
}
mapping, err := o.Mapper.RESTMapping(kapi.Kind("ReplicationController"))
if err != nil {
return err
}
mutateFn := func(rc *corev1.ReplicationController) bool {
printer, err := o.Printer("already cancelled")
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, err))
return false
}
if appsutil.IsDeploymentCancelled(rc) {
printer.PrintObj(info.Object, o.Out)
return false
}
patches := set.CalculatePatchesExternal([]*resource.Info{{Object: rc, Mapping: mapping}}, func(info *resource.Info) (bool, error) {
appsutil.SetCancelledByUserReason(rc)
return true, nil
})
allPatchesEmpty := true
for _, patch := range patches {
if len(patch.Patch) > 0 {
allPatchesEmpty = false
break
}
}
if allPatchesEmpty {
printer.PrintObj(info.Object, o.Out)
return false
}
if _, err := o.KubeClient.CoreV1().ReplicationControllers(rc.Namespace).Patch(rc.Name, types.StrategicMergePatchType,
patches[0].Patch); err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, err))
return false
}
printer, err = o.Printer("cancelling")
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, err))
return false
}
printer.PrintObj(info.Object, o.Out)
return true
}
deployments, cancelled, err := o.forEachControllerInConfig(config.Namespace, config.Name, mutateFn)
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("cancelling", info.Source, err))
continue
}
if !cancelled {
latest := deployments[0]
maybeCancelling := ""
if appsutil.IsDeploymentCancelled(latest) && !appsutil.IsTerminatedDeployment(latest) {
maybeCancelling = " (cancelling)"
}
timeAt := strings.ToLower(units.HumanDuration(time.Now().Sub(latest.CreationTimestamp.Time)))
fmt.Fprintf(o.Out, "No rollout is in progress (latest rollout #%d %s%s %s ago)\n",
appsutil.DeploymentVersionFor(latest),
strings.ToLower(string(appsutil.DeploymentStatusFor(latest))),
maybeCancelling,
timeAt)
}
}
return utilerrors.NewAggregate(allErrs)
}
func (o CancelOptions) forEachControllerInConfig(namespace, name string, mutateFunc func(*corev1.ReplicationController) bool) ([]*corev1.ReplicationController, bool, error) {
deploymentList, err := o.KubeClient.CoreV1().ReplicationControllers(namespace).List(metav1.ListOptions{LabelSelector: appsutil.ConfigSelector(name).String()})
if err != nil {
return nil, false, err
}
if len(deploymentList.Items) == 0 {
return nil, false, fmt.Errorf("there have been no replication controllers for %s/%s\n", namespace, name)
}
deployments := make([]*corev1.ReplicationController, 0, len(deploymentList.Items))
for i := range deploymentList.Items {
deployments = append(deployments, &deploymentList.Items[i])
}
sort.Sort(appsutil.ByLatestVersionDesc(deployments))
allErrs := []error{}
cancelled := false
for _, deployment := range deployments {
status := appsutil.DeploymentStatusFor(deployment)
switch status {
case appsv1.DeploymentStatusNew,
appsv1.DeploymentStatusPending,
appsv1.DeploymentStatusRunning:
cancelled = mutateFunc(deployment)
}
}
return deployments, cancelled, utilerrors.NewAggregate(allErrs)
}