-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_crr.go
301 lines (263 loc) · 10.2 KB
/
create_crr.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
/*
Copyright 2022 The Kruise 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 create
import (
"context"
"fmt"
internalapi "github.com/dong4325/kruise-tools-test/pkg/api"
kruiseappsv1alpha1 "github.com/openkruise/kruise-api/apps/v1alpha1"
kruiseclientsets "github.com/openkruise/kruise-api/client/clientset/versioned"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/util/i18n"
"k8s.io/kubectl/pkg/util/templates"
utilpointer "k8s.io/utils/pointer"
)
var (
crrLong = templates.LongDesc(i18n.T(`
Create a crr with the specified name.`))
crrExample = templates.Examples(i18n.T(`
NOTE: The default value of CRR is:
strategy:
failurePolicy: Fail
orderedRecreate: false
unreadyGracePeriodSeconds: 3
activeDeadlineSeconds: 300
ttlSecondsAfterFinished: 1800
# Create a crr with default value to restart all containers in pod-1
kubectl kruise create ContainerRecreateRequest my-crr --namespace=ns --pod=pod-1
# Create a crr with default value to restart container-1 in pod-1
kubectl kruise create ContainerRecreateRequest my-crr --namespace=ns --pod=pod-1 --containers=container-1
# Create a crr with unreadyGracePeriodSeconds 5 and terminationGracePeriodSeconds 30 to restart container-1 in pod-1
kubectl kruise create ContainerRecreateRequest my-crr --namespace=ns --pod=pod-1 --containers=container-1 --unreadyGracePeriodSeconds=5 --terminationGracePeriodSeconds=30`))
defaultCRRStrategy = kruiseappsv1alpha1.ContainerRecreateRequestStrategy{
FailurePolicy: kruiseappsv1alpha1.ContainerRecreateRequestFailurePolicyFail,
OrderedRecreate: false,
UnreadyGracePeriodSeconds: utilpointer.Int64Ptr(3),
MinStartedSeconds: 3,
}
defaultActiveDeadlineSeconds int64 = 300
defaultTtlSecondsAfterFinished int32 = 1800
)
// CreateCRROptions is the command line options for 'create crr'
type CreateCRROptions struct {
PrintFlags *genericclioptions.PrintFlags
PrintObj func(obj runtime.Object) error
PodName string
UnreadyGracePeriodSeconds int64
MinStartedSeconds int32
Containers []string
ContainerRecreateRequestContainer []kruiseappsv1alpha1.ContainerRecreateRequestContainer
Namespace string
Name string
From string
kruisev1alpha1Client kruiseclientsets.Interface
ClientSet kubernetes.Interface
EnforceNamespace bool
DryRunStrategy cmdutil.DryRunStrategy
DryRunVerifier *resource.DryRunVerifier
Builder *resource.Builder
FieldManager string
CreateAnnotation bool
genericclioptions.IOStreams
}
// NewCreateCRROptions initializes and returns new CreateCRROptions instance
func NewCreateCRROptions(ioStreams genericclioptions.IOStreams) *CreateCRROptions {
return &CreateCRROptions{
PrintFlags: genericclioptions.NewPrintFlags("created").WithTypeSetter(internalapi.GetScheme()),
IOStreams: ioStreams,
}
}
// NewCmdCreateCRR is a command to ease creating ContainerRecreateRequest.
func NewCmdCreateCRR(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
o := NewCreateCRROptions(ioStreams)
cmd := &cobra.Command{
Use: "ContainerRecreateRequest NAME --pod=podName [--containers=container]",
DisableFlagsInUseLine: true,
Short: crrLong,
Long: crrLong,
Example: crrExample,
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)
cmdutil.AddApplyAnnotationFlags(cmd)
cmdutil.AddValidateFlags(cmd)
cmdutil.AddDryRunFlag(cmd)
cmd.Flags().StringVarP(&o.PodName, "pod", "p", o.PodName, "The name of the pod).")
cmd.Flags().StringSlice("containers", o.Containers, "The containers those need to restarted.")
cmd.Flags().Int64VarP(&o.UnreadyGracePeriodSeconds, "unreadyGracePeriodSeconds", "u", o.UnreadyGracePeriodSeconds, "UnreadyGracePeriodSeconds is the optional duration in seconds to mark Pod as not ready over this duration before executing preStop hook and stopping the container")
cmd.Flags().Int32VarP(&o.MinStartedSeconds, "minStartedSeconds", "m", o.MinStartedSeconds, "Minimum number of seconds for which a newly created container should be started and ready without any of its container crashing, for it to be considered Succeeded.Defaults to 0 (container will be considered Succeeded as soon as it is started and ready)")
cmdutil.AddFieldManagerFlagVar(cmd, &o.FieldManager, "kubectl kruise-create")
return cmd
}
// Complete completes all the required options
func (o *CreateCRROptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
name, err := NameFromCommandArgs(cmd, args)
if err != nil {
return err
}
o.Name = name
clientConfig, err := f.ToRESTConfig()
if err != nil {
return err
}
o.ClientSet, err = kubernetes.NewForConfig(clientConfig)
if err != nil {
return err
}
o.kruisev1alpha1Client, err = kruiseclientsets.NewForConfig(clientConfig)
if err != nil {
return err
}
o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
if len(o.Namespace) == 0 {
o.Namespace = "default"
}
o.CreateAnnotation = cmdutil.GetFlagBool(cmd, cmdutil.ApplyAnnotationsFlag)
o.Builder = f.NewBuilder()
if len(o.Containers) == 0 {
// restart all containers in pod
o.ContainerRecreateRequestContainer, err = o.getAllCRRContainersInPod()
if err != nil {
return err
}
}
o.DryRunStrategy, err = cmdutil.GetDryRunStrategy(cmd)
if err != nil {
return err
}
dynamicClient, err := f.DynamicClient()
if err != nil {
return err
}
o.DryRunVerifier = resource.NewDryRunVerifier(dynamicClient, f.OpenAPIGetter())
cmdutil.PrintFlagsWithDryRunStrategy(o.PrintFlags, o.DryRunStrategy)
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return err
}
o.PrintObj = func(obj runtime.Object) error {
return printer.PrintObj(obj, o.Out)
}
return nil
}
// Validate makes sure provided values and valid crr options
func (o *CreateCRROptions) Validate() error {
// validate whether containers in pod
if !o.isPodExist() {
return fmt.Errorf("pod %s in namespace %s not exist", o.Name, o.Namespace)
}
var containers []string
crrContainers, err := o.getAllCRRContainersInPod()
if err != nil {
return fmt.Errorf("found containers failed")
}
for i := range crrContainers {
containers = append(containers, crrContainers[i].Name)
}
allContainerSet := sets.NewString(containers...)
if !allContainerSet.HasAll(o.Containers...) {
return fmt.Errorf("has container not exist")
}
return nil
}
// Run performs the execution of 'create crr' sub command
func (o *CreateCRROptions) Run() error {
crr := o.createCRR()
if o.DryRunStrategy != cmdutil.DryRunClient {
createOptions := metav1.CreateOptions{}
if o.FieldManager != "" {
createOptions.FieldManager = o.FieldManager
}
if o.DryRunStrategy == cmdutil.DryRunServer {
if err := o.DryRunVerifier.HasSupport(crr.GroupVersionKind()); err != nil {
return err
}
createOptions.DryRun = []string{metav1.DryRunAll}
}
var err error
crr, err = o.kruisev1alpha1Client.AppsV1alpha1().ContainerRecreateRequests(o.Namespace).Create(context.TODO(), crr, createOptions)
if err != nil {
return fmt.Errorf("failed to create crr: %v", err)
}
}
return o.PrintObj(crr)
}
func (o *CreateCRROptions) getAllCRRContainersInPod() ([]kruiseappsv1alpha1.ContainerRecreateRequestContainer, error) {
var crrContainers []kruiseappsv1alpha1.ContainerRecreateRequestContainer
var selectedCrrContainers []kruiseappsv1alpha1.ContainerRecreateRequestContainer
selectedContainers := sets.NewString(o.Containers...)
pod, err := o.ClientSet.CoreV1().Pods(o.Namespace).Get(context.TODO(), o.PodName, metav1.GetOptions{})
if err != nil {
return crrContainers, err
}
for _, container := range pod.Spec.Containers {
crrContainer := kruiseappsv1alpha1.ContainerRecreateRequestContainer{}
if container.Lifecycle != nil {
crrContainer.PreStop = container.Lifecycle.PreStop
}
crrContainer.Name = container.Name
crrContainer.Ports = container.Ports
crrContainers = append(crrContainers, crrContainer)
}
if len(o.Containers) == 0 {
return crrContainers, nil
} else {
for _, container := range crrContainers {
if selectedContainers.Has(container.Name) {
selectedCrrContainers = append(selectedCrrContainers, container)
}
}
return selectedCrrContainers, nil
}
}
func (o *CreateCRROptions) isPodExist() bool {
_, err := o.ClientSet.CoreV1().Pods(o.Namespace).Get(context.TODO(), o.PodName, metav1.GetOptions{})
if err != nil {
return false
}
return true
}
func (o *CreateCRROptions) createCRR() *kruiseappsv1alpha1.ContainerRecreateRequest {
crr := &kruiseappsv1alpha1.ContainerRecreateRequest{
TypeMeta: metav1.TypeMeta{APIVersion: kruiseappsv1alpha1.SchemeGroupVersion.String(), Kind: "ContainerRecreateRequest"},
ObjectMeta: metav1.ObjectMeta{
Name: o.Name,
Namespace: o.Namespace,
},
Spec: kruiseappsv1alpha1.ContainerRecreateRequestSpec{
PodName: o.PodName,
Containers: o.ContainerRecreateRequestContainer,
Strategy: &defaultCRRStrategy,
ActiveDeadlineSeconds: utilpointer.Int64Ptr(defaultActiveDeadlineSeconds),
TTLSecondsAfterFinished: utilpointer.Int32Ptr(defaultTtlSecondsAfterFinished),
},
}
if o.EnforceNamespace {
crr.Namespace = o.Namespace
}
return crr
}