-
Notifications
You must be signed in to change notification settings - Fork 311
/
namespace.go
363 lines (314 loc) · 10.1 KB
/
namespace.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright 2023 The Okteto 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 namespaces
import (
"context"
"fmt"
"strings"
"sync"
"github.com/okteto/okteto/pkg/k8s/statefulsets"
"github.com/okteto/okteto/pkg/k8s/volumes"
oktetoLog "github.com/okteto/okteto/pkg/log"
"github.com/okteto/okteto/pkg/model"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/pager"
)
const (
parallelism int64 = 10
volumeKind = "PersistentVolumeClaim"
volumeSnapshotKind = "VolumeSnapshot"
jobKind = "Job"
resourcePolicyAnnotation = "dev.okteto.com/policy"
keepPolicy = "keep"
)
type Traveler interface {
See(obj runtime.Object) error
}
type TravelerFunc func(obj runtime.Object) error
func (t TravelerFunc) See(obj runtime.Object) error {
return t(obj)
}
// DeleteAllOptions options for delete all operation
type DeleteAllOptions struct {
// LabelSelector selector for resources to be deleted
LabelSelector string
// IncludeVolumes flag to indicate if volumes have to be deleted or not
IncludeVolumes bool
}
// Namespaces struct to interact with namespaces in k8s
type Namespaces struct {
dynClient dynamic.Interface
discClient discovery.DiscoveryInterface
restConfig *rest.Config
k8sClient kubernetes.Interface
}
type Options struct {
List metav1.ListOptions
Namespace string
Parallelism int64
}
type Trip struct {
k8s kubernetes.Interface
dynamic dynamic.Interface
restConfig *rest.Config
sem *semaphore.Weighted
list metav1.ListOptions
namespace string
writeLock sync.Mutex
}
// noneRateLimiter noop rate limiter to avoid rate limiting errors on k8s client.
// We created this to avoid to depend on github.com/rancher/rancher dependency as this is the only place where it was used.
type noneRateLimiter struct{}
func (*noneRateLimiter) TryAccept() bool { return true }
func (*noneRateLimiter) Stop() {}
func (*noneRateLimiter) Accept() {}
func (*noneRateLimiter) QPS() float32 { return 1 }
func (*noneRateLimiter) Wait(_ context.Context) error { return nil }
// NewNamespace allows to create a new Namespace object
func NewNamespace(dynClient dynamic.Interface, discClient discovery.DiscoveryInterface, restConfig *rest.Config, k8s kubernetes.Interface) *Namespaces {
return &Namespaces{
dynClient: dynClient,
discClient: discClient,
restConfig: restConfig,
k8sClient: k8s,
}
}
// DestroyWithLabel deletes all resources within a namespace
func (n *Namespaces) DestroyWithLabel(ctx context.Context, ns string, opts DeleteAllOptions) error {
listOptions := metav1.ListOptions{
LabelSelector: opts.LabelSelector,
}
trip, err := newTrip(n.restConfig, &Options{
Namespace: ns,
Parallelism: parallelism,
List: listOptions,
})
if err != nil {
return err
}
groupResources, err := restmapper.GetAPIGroupResources(n.discClient)
if err != nil {
return err
}
rm := restmapper.NewDiscoveryRESTMapper(groupResources)
// This is done because the wander function will try to list all k8s resources and most of them cannot be listed by
// Okteto user's service accounts, so it prints tons of warnings in the standard output. Setting the logrus level to err avoid those warnings
prevLevel := logrus.GetLevel()
logrus.SetLevel(logrus.ErrorLevel)
defer func() {
logrus.SetLevel(prevLevel)
}()
return trip.wander(ctx, TravelerFunc(func(obj runtime.Object) error {
m, err := meta.Accessor(obj)
if err != nil {
return err
}
gvk := obj.GetObjectKind().GroupVersionKind()
if isStorage(gvk.Kind) && !opts.IncludeVolumes {
oktetoLog.Debugf("skipping deletion of '%s' '%s' because of volume flag", gvk.Kind, m.GetName())
return nil
}
if m.GetAnnotations()[resourcePolicyAnnotation] == keepPolicy {
oktetoLog.Debugf("skipping deletion of %s '%s' because of policy annotation", gvk.Kind, m.GetName())
return nil
}
mapping, err := rm.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
if err != nil {
return err
}
deleteOpts := metav1.DeleteOptions{}
// It seems that by default, client-go doesn't delete pods scheduled by jobs, so we need to set the propagation policy
if gvk.Kind == jobKind {
deletePropagation := metav1.DeletePropagationBackground
deleteOpts.PropagationPolicy = &deletePropagation
}
err = n.dynClient.
Resource(mapping.Resource).
Namespace(ns).
Delete(ctx, m.GetName(), deleteOpts)
if err != nil {
oktetoLog.Debugf("error deleting '%s' '%s': %s", gvk.Kind, m.GetName(), err)
return err
}
oktetoLog.Debugf("successfully deleted '%s' '%s'", gvk.Kind, m.GetName())
return nil
}))
}
// DestroySFSVolumes This function deletes volumes for any statefulset that matches with opts.LabelSelector but it doesn't have any
// dev.okteto.com/deployed-by label. This is to avoid to left PVCs behind when everything deployed with okteto deploy
// command is deleted
func (n *Namespaces) DestroySFSVolumes(ctx context.Context, ns string, opts DeleteAllOptions) error {
if !opts.IncludeVolumes {
return nil
}
var pvcNames []string
ssList, err := statefulsets.List(ctx, ns, opts.LabelSelector, n.k8sClient)
if err != nil {
return fmt.Errorf("error getting statefulsets: %w", err)
}
for _, ss := range ssList {
for _, pvcTemplate := range ss.Spec.VolumeClaimTemplates {
pvcNames = append(pvcNames, fmt.Sprintf("%s-%s-", pvcTemplate.Name, ss.Name))
}
}
if len(pvcNames) == 0 {
return nil
}
// We only need to delete all the volumes without deployed-by label. The ones with the label will be deleted by
// DestroyWithLabel function
deployedByNotExist, err := labels.NewRequirement(
model.DeployedByLabel,
selection.DoesNotExist,
nil,
)
if err != nil {
return err
}
deployedByNotExistSelector := labels.NewSelector().Add(*deployedByNotExist).String()
vList, err := volumes.List(ctx, ns, deployedByNotExistSelector, n.k8sClient)
if err != nil {
return fmt.Errorf("error getting volumes: %w", err)
}
for _, v := range vList {
if v.Annotations[resourcePolicyAnnotation] == keepPolicy {
oktetoLog.Debugf("skipping deletion of pvc '%s' because of policy annotation", v.GetName())
continue
}
for _, pvcName := range pvcNames {
if strings.HasPrefix(v.Name, pvcName) {
if err := volumes.DestroyWithoutTimeout(ctx, v.Name, ns, n.k8sClient); err != nil {
return err
}
break
}
}
}
return nil
}
// Below functions were added to remove "github.com/ibuildthecloud/finalizers" as a dependency
func newTrip(restConfig *rest.Config, opts *Options) (*Trip, error) {
if opts == nil {
opts = &Options{}
}
if restConfig.RateLimiter == nil {
restConfig.RateLimiter = &noneRateLimiter{}
}
k8s, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, err
}
dynamic, err := dynamic.NewForConfig(restConfig)
if err != nil {
return nil, err
}
defaultMaxWeight := int64(10)
var sem *semaphore.Weighted
if opts.Parallelism > 0 {
sem = semaphore.NewWeighted(opts.Parallelism)
} else {
sem = semaphore.NewWeighted(defaultMaxWeight)
}
return &Trip{
namespace: opts.Namespace,
list: opts.List,
restConfig: restConfig,
k8s: k8s,
dynamic: dynamic,
sem: sem,
}, nil
}
func (t *Trip) wander(ctx context.Context, traveler Traveler) error {
_, apis, err := t.k8s.Discovery().ServerGroupsAndResources()
if err != nil {
return err
}
eg, _ := errgroup.WithContext(ctx)
for _, api := range apis {
for _, api2 := range api.APIResources {
listable := false
for _, verb := range api2.Verbs {
if verb == "list" {
listable = true
break
}
}
if !listable {
continue
}
if t.namespace != "" && !api2.Namespaced {
continue
}
gvr := schema.FromAPIVersionAndKind(api.GroupVersion, api2.Kind).
GroupVersion().
WithResource(api2.Name)
var client dynamic.ResourceInterface
if t.namespace == "" {
client = t.dynamic.Resource(gvr)
} else {
client = t.dynamic.Resource(gvr).Namespace(t.namespace)
}
// capture values for goroutine
api := api
api2 := api2
eg.Go(func() error {
if err := t.listAll(ctx, traveler, client, api, api2); err != nil {
logrus.Warn("Failed to list", api.GroupVersion, api2.Kind, err)
}
return nil
})
}
}
return eg.Wait()
}
func (t *Trip) listAll(ctx context.Context, traveler Traveler, client dynamic.ResourceInterface, api *metav1.APIResourceList, api2 metav1.APIResource) error {
if err := t.sem.Acquire(ctx, 1); err != nil {
return err
}
defer t.sem.Release(1)
pager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) {
objs, err := client.List(ctx, t.list)
return objs, err
}))
return pager.EachListItem(ctx, t.list, func(obj runtime.Object) error {
t.writeLock.Lock()
defer t.writeLock.Unlock()
if err := traveler.See(obj); err != nil {
m, err2 := meta.Accessor(obj)
if err2 == nil {
logrus.Warn("Failed to process", api.GroupVersion, api2.Kind, m.GetNamespace(), m.GetName(), err)
}
}
return nil
})
}
// isStorage returns if the kind is some of storage kind
func isStorage(kind string) bool {
switch kind {
case volumeKind, volumeSnapshotKind:
return true
}
return false
}