/
gc.go
153 lines (128 loc) · 4.89 KB
/
gc.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
/*
Copyright 2019 The Knative 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 gc
import (
"context"
"fmt"
"sort"
"time"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
"knative.dev/pkg/controller"
"knative.dev/pkg/logging"
"knative.dev/serving/pkg/apis/serving"
"knative.dev/serving/pkg/apis/serving/v1alpha1"
"knative.dev/serving/pkg/apis/serving/v1beta1"
listers "knative.dev/serving/pkg/client/listers/serving/v1alpha1"
pkgreconciler "knative.dev/serving/pkg/reconciler"
configns "knative.dev/serving/pkg/reconciler/gc/config"
)
// reconciler implements controller.Reconciler for Garbage Collection resources.
type reconciler struct {
*pkgreconciler.Base
// listers index properties about resources
configurationLister listers.ConfigurationLister
revisionLister listers.RevisionLister
configStore pkgreconciler.ConfigStore
}
// Check that our reconciler implements controller.Reconciler
var _ controller.Reconciler = (*reconciler)(nil)
// Reconcile compares the actual state with the desired, and attempts to
// converge the two. It then updates the Status block of the Garbage Collection
// resource with the current status of the resource.
func (c *reconciler) Reconcile(ctx context.Context, key string) error {
// Convert the namespace/name string into a distinct namespace and name.
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
c.Logger.Errorf("invalid resource key %q: %v", key, err)
return nil
}
logger := logging.FromContext(ctx)
ctx = c.configStore.ToContext(ctx)
// Get the Configuration resource with this namespace/name.
config, err := c.configurationLister.Configurations(namespace).Get(name)
if errors.IsNotFound(err) {
// The resource no longer exists, in which case we stop processing.
logger.Errorf("Configuration %q in work queue no longer exists", key)
return nil
} else if err != nil {
return err
}
reconcileErr := c.reconcile(ctx, config)
if reconcileErr != nil {
c.Recorder.Event(config, corev1.EventTypeWarning, "InternalError", reconcileErr.Error())
}
return reconcileErr
}
func (c *reconciler) reconcile(ctx context.Context, config *v1alpha1.Configuration) error {
cfg := configns.FromContext(ctx).RevisionGC
logger := logging.FromContext(ctx)
selector := labels.Set{serving.ConfigurationLabelKey: config.Name}.AsSelector()
revs, err := c.revisionLister.Revisions(config.Namespace).List(selector)
if err != nil {
return err
}
gcSkipOffset := cfg.StaleRevisionMinimumGenerations
if gcSkipOffset >= int64(len(revs)) {
return nil
}
// Sort by creation timestamp descending
sort.Slice(revs, func(i, j int) bool {
return revs[j].CreationTimestamp.Before(&revs[i].CreationTimestamp)
})
for _, rev := range revs[gcSkipOffset:] {
if isRevisionStale(ctx, rev, config) {
err := c.ServingClientSet.ServingV1alpha1().Revisions(rev.Namespace).Delete(rev.Name, &metav1.DeleteOptions{})
if err != nil {
logger.Errorw(fmt.Sprintf("Failed to delete stale revision %q", rev.Name), zap.Error(err))
continue
}
}
}
return nil
}
func isRevisionStale(ctx context.Context, rev *v1alpha1.Revision, config *v1alpha1.Configuration) bool {
if config.Status.LatestReadyRevisionName == rev.Name {
return false
}
cfg := configns.FromContext(ctx).RevisionGC
logger := logging.FromContext(ctx)
curTime := time.Now()
if rev.ObjectMeta.CreationTimestamp.Add(cfg.StaleRevisionCreateDelay).After(curTime) {
// Revision was created sooner than staleRevisionCreateDelay. Ignore it.
return false
}
lastPin, err := rev.GetLastPinned()
if err != nil {
if err.(v1alpha1.LastPinnedParseError).Type != v1alpha1.AnnotationParseErrorTypeMissing {
logger.Errorw("Failed to determine revision last pinned", zap.Error(err))
} else {
// Revision was never pinned and its RevisionConditionReady is not true after staleRevisionCreateDelay.
// It usually happens when ksvc was deployed with wrong configuration.
rc := rev.Status.GetCondition(v1beta1.RevisionConditionReady)
if rc == nil || rc.Status != corev1.ConditionTrue {
return true
}
}
return false
}
ret := lastPin.Add(cfg.StaleRevisionTimeout).Before(curTime)
if ret {
logger.Infof("Detected stale revision %v with creation time %v and lastPinned time %v.", rev.ObjectMeta.Name, rev.ObjectMeta.CreationTimestamp, lastPin)
}
return ret
}