-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
crdwatcher.go
188 lines (171 loc) · 5.69 KB
/
crdwatcher.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
// Copyright Istio 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 kclient
import (
"fmt"
"sync"
"github.com/Masterminds/semver/v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/gateway-api/pkg/consts"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pkg/config/schema/gvr"
"istio.io/istio/pkg/kube"
"istio.io/istio/pkg/kube/controllers"
"istio.io/istio/pkg/kube/kubetypes"
"istio.io/istio/pkg/log"
)
type crdWatcher struct {
crds Informer[*metav1.PartialObjectMetadata]
queue controllers.Queue
mutex sync.RWMutex
callbacks map[string][]func()
running chan struct{}
stop <-chan struct{}
}
func init() {
// Unfortunate hack needed to avoid circular imports
kube.NewCrdWatcher = newCrdWatcher
}
// newCrdWatcher returns a new CRD watcher controller.
func newCrdWatcher(client kube.Client) kubetypes.CrdWatcher {
c := &crdWatcher{
running: make(chan struct{}),
callbacks: map[string][]func(){},
}
c.queue = controllers.NewQueue("crd watcher",
controllers.WithReconciler(c.Reconcile))
c.crds = NewMetadata(client, gvr.CustomResourceDefinition, Filter{
ObjectFilter: kubetypes.NewStaticObjectFilter(minimumVersionFilter),
})
c.crds.AddEventHandler(controllers.ObjectHandler(c.queue.AddObject))
return c
}
var minimumCRDVersions = map[string]*semver.Version{
"grpcroutes.gateway.networking.k8s.io": semver.New(1, 1, 0, "", ""),
}
// minimumVersionFilter filters CRDs that do not meet a minimum "version".
// Currently, we use this only for Gateway API CRD's, so we hardcode their versioning scheme.
// The problem we are trying to solve is:
// * User installs CRDs with Foo v1alpha1
// * Istio vNext starts watching Foo at v1
// * user upgrades to Istio vNext. It sees Foo exists, and tries to watch v1. This fails.
// The user may have opted into using an experimental CRD, but not to experimental usage *in Istio* so this isn't acceptable.
func minimumVersionFilter(t any) bool {
// Setup a filter
crd := t.(*metav1.PartialObjectMetadata)
mv, f := minimumCRDVersions[crd.Name]
if !f {
return true
}
bv, f := crd.Annotations[consts.BundleVersionAnnotation]
if !f {
log.Errorf("CRD %v expected to have a %v annotation, but none found; ignoring", crd.Name, consts.BundleVersion)
return false
}
fv, err := semver.NewVersion(bv)
if err != nil {
log.Errorf("CRD %v version %v invalid; ignoring: %v", crd.Name, bv, err)
return false
}
// Ignore RC tags, etc. We 'round up' those.
nv, err := fv.SetPrerelease("")
if err != nil {
log.Errorf("CRD %v version %v invalid; ignoring: %v", crd.Name, bv, err)
return false
}
fv = &nv
if fv.LessThan(mv) {
log.Infof("CRD %v version %v is below minimum version %v, ignoring", crd.Name, fv, mv)
return false
}
return true
}
// HasSynced returns whether the underlying cache has synced and the callback has been called at least once.
func (c *crdWatcher) HasSynced() bool {
return c.queue.HasSynced()
}
// Run starts the controller. This must be called.
func (c *crdWatcher) Run(stop <-chan struct{}) {
c.mutex.Lock()
if c.stop != nil {
// Run already called. Because we call this from client.RunAndWait this isn't uncommon
c.mutex.Unlock()
return
}
c.stop = stop
c.mutex.Unlock()
kube.WaitForCacheSync("crd watcher", stop, c.crds.HasSynced)
c.queue.Run(stop)
c.crds.ShutdownHandlers()
}
// WaitForCRD waits until the request CRD exists, and returns true on success. A false return value
// indicates the CRD does not exist but the wait failed or was canceled.
// This is useful to conditionally enable controllers based on CRDs being created.
func (c *crdWatcher) WaitForCRD(s schema.GroupVersionResource, stop <-chan struct{}) bool {
done := make(chan struct{})
if c.KnownOrCallback(s, func(stop <-chan struct{}) {
close(done)
}) {
// Already known
return true
}
select {
case <-stop:
return false
case <-done:
return true
}
}
// KnownOrCallback returns `true` immediately if the resource is known.
// If it is not known, `false` is returned. If the resource is later added, the callback will be triggered.
func (c *crdWatcher) KnownOrCallback(s schema.GroupVersionResource, f func(stop <-chan struct{})) bool {
c.mutex.Lock()
defer c.mutex.Unlock()
// If we are already synced, return immediately if the CRD is present.
if c.crds.HasSynced() && c.known(s) {
// Already known, return early
return true
}
name := fmt.Sprintf("%s.%s", s.Resource, s.Group)
c.callbacks[name] = append(c.callbacks[name], func() {
if features.EnableUnsafeAssertions && c.stop == nil {
log.Fatalf("CRD Watcher callback called without stop set")
}
// Call the callback
f(c.stop)
})
return false
}
func (c *crdWatcher) known(s schema.GroupVersionResource) bool {
// From the spec: "Its name MUST be in the format <.spec.name>.<.spec.group>."
name := fmt.Sprintf("%s.%s", s.Resource, s.Group)
return c.crds.Get(name, "") != nil
}
func (c *crdWatcher) Reconcile(key types.NamespacedName) error {
c.mutex.Lock()
callbacks, f := c.callbacks[key.Name]
if !f {
c.mutex.Unlock()
return nil
}
// Delete them so we do not run again
delete(c.callbacks, key.Name)
c.mutex.Unlock()
for _, cb := range callbacks {
cb()
}
return nil
}