-
Notifications
You must be signed in to change notification settings - Fork 381
/
retry.go
245 lines (210 loc) · 8.32 KB
/
retry.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
package rollout
import (
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/cli-runtime/pkg/resource"
kexternalclientset "k8s.io/client-go/kubernetes"
kapi "k8s.io/kubernetes/pkg/apis/core"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/scheme"
"k8s.io/kubernetes/pkg/kubectl/util/templates"
appsv1 "github.com/openshift/api/apps/v1"
"github.com/openshift/library-go/pkg/apps/appsutil"
"github.com/openshift/oc/pkg/cli/set"
)
type RetryOptions struct {
PrintFlags *genericclioptions.PrintFlags
Resources []string
Builder func() *resource.Builder
Mapper meta.RESTMapper
Clientset kexternalclientset.Interface
Namespace string
ExplicitNamespace bool
ToPrinter func(string) (printers.ResourcePrinter, error)
resource.FilenameOptions
genericclioptions.IOStreams
}
var (
rolloutRetryLong = templates.LongDesc(`
If a rollout fails, you may opt to retry it (if the error was transient). Some rollouts may
never successfully complete - in which case you can use the rollout latest to force a redeployment.
If a deployment config has completed rolling out successfully at least once in the past, it would be
automatically rolled back in the event of a new failed rollout. Note that you would still need
to update the erroneous deployment config in order to have its template persisted across your
application.
`)
rolloutRetryExample = templates.Examples(`
# Retry the latest failed deployment based on 'frontend'
# The deployer pod and any hook pods are deleted for the latest failed deployment
%[1]s rollout retry dc/frontend
`)
)
func NewRolloutRetryOptions(streams genericclioptions.IOStreams) *RetryOptions {
return &RetryOptions{
PrintFlags: genericclioptions.NewPrintFlags("already retried").WithTypeSetter(scheme.Scheme),
IOStreams: streams,
}
}
func NewCmdRolloutRetry(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
o := NewRolloutRetryOptions(streams)
cmd := &cobra.Command{
Use: "retry (TYPE NAME | TYPE/NAME) [flags]",
Long: rolloutRetryLong,
Example: fmt.Sprintf(rolloutRetryExample, fullName),
Short: "Retry the latest failed rollout",
Run: func(cmd *cobra.Command, args []string) {
kcmdutil.CheckErr(o.Complete(f, cmd, args))
kcmdutil.CheckErr(o.Run())
},
}
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 *RetryOptions) Complete(f kcmdutil.Factory, cmd *cobra.Command, args []string) error {
var err error
if len(args) == 0 && len(o.FilenameOptions.Filenames) == 0 {
return kcmdutil.UsageErrorf(cmd, cmd.Use)
}
o.Resources = args
o.Mapper, err = f.ToRESTMapper()
if err != nil {
return err
}
o.Namespace, o.ExplicitNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
config, err := f.ToRESTConfig()
if err != nil {
return err
}
o.Clientset, err = kexternalclientset.NewForConfig(config)
if err != nil {
return err
}
o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
o.PrintFlags.NamePrintFlags.Operation = operation
return o.PrintFlags.ToPrinter()
}
o.Builder = f.NewBuilder
return err
}
func (o RetryOptions) Run() error {
allErrs := []error{}
mapping, err := o.Mapper.RESTMapping(kapi.Kind("ReplicationController"))
if err != nil {
return err
}
r := o.Builder().
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
NamespaceParam(o.Namespace).DefaultNamespace().
FilenameParam(o.ExplicitNamespace, &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
}
for _, info := range infos {
config, ok := info.Object.(*appsv1.DeploymentConfig)
if !ok {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("expected deployment configuration, got %T", info.Object)))
continue
}
if config.Spec.Paused {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("unable to retry paused deployment config %q", config.Name)))
continue
}
if config.Status.LatestVersion == 0 {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("no rollouts found for %q", config.Name)))
continue
}
latestDeploymentName := appsutil.LatestDeploymentNameForConfig(config)
rc, err := o.Clientset.CoreV1().ReplicationControllers(config.Namespace).Get(latestDeploymentName, metav1.GetOptions{})
if err != nil {
if kerrors.IsNotFound(err) {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("unable to find the latest rollout (#%d).\nYou can start a new rollout with 'oc rollout latest dc/%s'.", config.Status.LatestVersion, config.Name)))
continue
}
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("unable to fetch replication controller %q", config.Name)))
continue
}
if !appsutil.IsFailedDeployment(rc) {
message := fmt.Sprintf("rollout #%d is %s; only failed deployments can be retried.\n", config.Status.LatestVersion,
strings.ToLower(appsutil.AnnotationFor(rc, appsv1.DeploymentStatusAnnotation)))
if appsutil.IsCompleteDeployment(rc) {
message += fmt.Sprintf("You can start a new deployment with 'oc rollout latest dc/%s'.", config.Name)
} else {
message += fmt.Sprintf("Optionally, you can cancel this deployment with 'oc rollout cancel dc/%s'.", config.Name)
}
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, errors.New(message)))
continue
}
// Delete the deployer pod as well as the deployment hooks pods, if any
pods, err := o.Clientset.CoreV1().Pods(config.Namespace).List(metav1.ListOptions{LabelSelector: appsutil.DeployerPodSelector(
latestDeploymentName).String()})
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("failed to list deployer/hook pods for deployment #%d: %v", config.Status.LatestVersion, err)))
continue
}
hasError := false
for _, pod := range pods.Items {
err := o.Clientset.CoreV1().Pods(pod.Namespace).Delete(pod.Name, metav1.NewDeleteOptions(0))
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, fmt.Errorf("failed to delete deployer/hook pod %s for deployment #%d: %v", pod.Name, config.Status.LatestVersion, err)))
hasError = true
}
}
if hasError {
continue
}
patches := set.CalculatePatchesExternal([]*resource.Info{{Object: rc, Mapping: mapping}}, func(info *resource.Info) (bool, error) {
rc.Annotations[appsv1.DeploymentStatusAnnotation] = string(appsv1.DeploymentStatusNew)
delete(rc.Annotations, appsv1.DeploymentStatusReasonAnnotation)
delete(rc.Annotations, appsv1.DeploymentCancelledAnnotation)
return true, nil
})
if len(patches) == 0 {
printer, err := o.ToPrinter("already retried")
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, err))
continue
}
if err := printer.PrintObj(info.Object, o.Out); err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, err))
}
continue
}
if _, err := o.Clientset.CoreV1().ReplicationControllers(rc.Namespace).Patch(rc.Name, types.StrategicMergePatchType, patches[0].Patch); err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, err))
continue
}
printer, err := o.ToPrinter(fmt.Sprintf("retried rollout #%d", config.Status.LatestVersion))
if err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, err))
continue
}
if err := printer.PrintObj(info.Object, o.Out); err != nil {
allErrs = append(allErrs, kcmdutil.AddSourceToErr("retrying", info.Source, err))
continue
}
}
return utilerrors.NewAggregate(allErrs)
}