-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
303 lines (264 loc) · 8.54 KB
/
controller.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
// Copyright 2017 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 crd
import (
"errors"
"fmt"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pilot/pkg/serviceregistry/kube"
"istio.io/istio/pkg/log"
)
// controller is a collection of synchronized resource watchers.
// Caches are thread-safe
type controller struct {
client *Client
queue kube.Queue
kinds map[string]cacheHandler
}
type cacheHandler struct {
informer cache.SharedIndexInformer
handler *kube.ChainHandler
}
var (
// experiment on getting some monitoring on config errors.
k8sEvents = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "pilot_k8s_cfg_events",
Help: "Events from k8s config.",
}, []string{"type", "event"})
k8sErrors = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "pilot_k8s_object_errors",
Help: "Errors converting k8s CRDs",
}, []string{"name"})
// InvalidCRDs contains a sync.Map keyed by the namespace/name of the entry, and has the error as value.
// It can be used by tools like ctrlz to display the errors.
InvalidCRDs atomic.Value
)
func init() {
prometheus.MustRegister(k8sEvents)
prometheus.MustRegister(k8sErrors)
}
// NewController creates a new Kubernetes controller for CRDs
// Use "" for namespace to listen for all namespace changes
func NewController(client *Client, options kube.ControllerOptions) model.ConfigStoreCache {
log.Infof("CRD controller watching namespaces %q", options.WatchedNamespace)
// Queue requires a time duration for a retry delay after a handler error
out := &controller{
client: client,
queue: kube.NewQueue(1 * time.Second),
kinds: make(map[string]cacheHandler),
}
// add stores for CRD kinds
for _, schema := range client.ConfigDescriptor() {
out.addInformer(schema, options.WatchedNamespace, options.ResyncPeriod)
}
return out
}
func (c *controller) addInformer(schema model.ProtoSchema, namespace string, resyncPeriod time.Duration) {
c.kinds[schema.Type] = c.createInformer(knownTypes[schema.Type].object.DeepCopyObject(), schema.Type, resyncPeriod,
func(opts meta_v1.ListOptions) (result runtime.Object, err error) {
result = knownTypes[schema.Type].collection.DeepCopyObject()
rc, ok := c.client.clientset[apiVersion(&schema)]
if !ok {
return nil, fmt.Errorf("client not initialized %s", schema.Type)
}
req := rc.dynamic.Get().
Resource(ResourceName(schema.Plural)).
VersionedParams(&opts, meta_v1.ParameterCodec)
if !schema.ClusterScoped {
req = req.Namespace(namespace)
}
err = req.Do().Into(result)
return
},
func(opts meta_v1.ListOptions) (watch.Interface, error) {
rc, ok := c.client.clientset[apiVersion(&schema)]
if !ok {
return nil, fmt.Errorf("client not initialized %s", schema.Type)
}
opts.Watch = true
req := rc.dynamic.Get().
Resource(ResourceName(schema.Plural)).
VersionedParams(&opts, meta_v1.ParameterCodec)
if !schema.ClusterScoped {
req = req.Namespace(namespace)
}
return req.Watch()
})
}
// notify is the first handler in the handler chain.
// Returning an error causes repeated execution of the entire chain.
func (c *controller) notify(obj interface{}, event model.Event) error {
if !c.HasSynced() {
return errors.New("waiting till full synchronization")
}
_, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
log.Infof("Error retrieving key: %v", err)
}
return nil
}
func (c *controller) createInformer(
o runtime.Object,
otype string,
resyncPeriod time.Duration,
lf cache.ListFunc,
wf cache.WatchFunc) cacheHandler {
handler := &kube.ChainHandler{}
handler.Append(c.notify)
// TODO: finer-grained index (perf)
informer := cache.NewSharedIndexInformer(
&cache.ListWatch{ListFunc: lf, WatchFunc: wf}, o,
resyncPeriod, cache.Indexers{})
informer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
// TODO: filtering functions to skip over un-referenced resources (perf)
AddFunc: func(obj interface{}) {
k8sEvents.With(prometheus.Labels{"type": otype, "event": "add"}).Add(1)
c.queue.Push(kube.NewTask(handler.Apply, obj, model.EventAdd))
},
UpdateFunc: func(old, cur interface{}) {
if !reflect.DeepEqual(old, cur) {
k8sEvents.With(prometheus.Labels{"type": otype, "event": "update"}).Add(1)
c.queue.Push(kube.NewTask(handler.Apply, cur, model.EventUpdate))
} else {
k8sEvents.With(prometheus.Labels{"type": otype, "event": "updateSame"}).Add(1)
}
},
DeleteFunc: func(obj interface{}) {
k8sEvents.With(prometheus.Labels{"type": otype, "event": "delete"}).Add(1)
c.queue.Push(kube.NewTask(handler.Apply, obj, model.EventDelete))
},
})
return cacheHandler{informer: informer, handler: handler}
}
func (c *controller) RegisterEventHandler(typ string, f func(model.Config, model.Event)) {
schema, exists := c.ConfigDescriptor().GetByType(typ)
if !exists {
return
}
c.kinds[typ].handler.Append(func(object interface{}, ev model.Event) error {
item, ok := object.(IstioObject)
if ok {
config, err := ConvertObject(schema, item, c.client.domainSuffix)
if err != nil {
log.Warnf("error translating object for schema %#v : %v\n Object:\n%#v", schema, err, object)
} else {
f(*config, ev)
}
}
return nil
})
}
func (c *controller) HasSynced() bool {
for kind, ctl := range c.kinds {
if !ctl.informer.HasSynced() {
log.Infof("controller %q is syncing...", kind)
return false
}
}
return true
}
func (c *controller) Run(stop <-chan struct{}) {
go c.queue.Run(stop)
for _, ctl := range c.kinds {
go ctl.informer.Run(stop)
}
<-stop
log.Info("controller terminated")
}
func (c *controller) ConfigDescriptor() model.ConfigDescriptor {
return c.client.ConfigDescriptor()
}
func (c *controller) Get(typ, name, namespace string) *model.Config {
schema, exists := c.client.ConfigDescriptor().GetByType(typ)
if !exists {
return nil
}
store := c.kinds[typ].informer.GetStore()
data, exists, err := store.GetByKey(kube.KeyFunc(name, namespace))
if !exists {
return nil
}
if err != nil {
log.Warna(err)
return nil
}
obj, ok := data.(IstioObject)
if !ok {
log.Warn("Cannot convert to config from store")
return nil
}
config, err := ConvertObject(schema, obj, c.client.domainSuffix)
if err != nil {
return nil
}
return config
}
func (c *controller) Create(config model.Config) (string, error) {
return c.client.Create(config)
}
func (c *controller) Update(config model.Config) (string, error) {
return c.client.Update(config)
}
func (c *controller) Delete(typ, name, namespace string) error {
return c.client.Delete(typ, name, namespace)
}
func (c *controller) List(typ, namespace string) ([]model.Config, error) {
schema, ok := c.client.ConfigDescriptor().GetByType(typ)
if !ok {
return nil, fmt.Errorf("missing type %q", typ)
}
var newErrors sync.Map
var errs error
out := make([]model.Config, 0)
oldMap := InvalidCRDs.Load()
if oldMap != nil {
oldMap.(*sync.Map).Range(func(key, value interface{}) bool {
k8sErrors.With(prometheus.Labels{"name": key.(string)}).Set(1)
return true
})
}
for _, data := range c.kinds[typ].informer.GetStore().List() {
item, ok := data.(IstioObject)
if !ok {
continue
}
if namespace != "" && namespace != item.GetObjectMeta().Namespace {
continue
}
config, err := ConvertObject(schema, item, c.client.domainSuffix)
if err != nil {
key := item.GetObjectMeta().Namespace + "/" + item.GetObjectMeta().Name
log.Errorf("Failed to convert %s object, ignoring: %s %v %v", typ, key, err, item.GetSpec())
// DO NOT RETURN ERROR: if a single object is bad, it'll be ignored (with a log message), but
// the rest should still be processed.
// TODO: find a way to reset and represent the error !!
newErrors.Store(key, err)
k8sErrors.With(prometheus.Labels{"name": key}).Set(1)
} else {
out = append(out, *config)
}
}
InvalidCRDs.Store(&newErrors)
return out, errs
}