/
source.go
468 lines (423 loc) · 11.5 KB
/
source.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// Copyright 2018 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 fs
import (
"bytes"
"crypto/sha1"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
"github.com/ghodss/yaml"
"github.com/howeyc/fsnotify"
kubeMeta "istio.io/istio/galley/pkg/metadata/kube"
"istio.io/istio/galley/pkg/runtime"
"istio.io/istio/galley/pkg/runtime/resource"
"istio.io/istio/galley/pkg/source/kube/builtin"
"istio.io/istio/galley/pkg/source/kube/dynamic"
"istio.io/istio/galley/pkg/source/kube/dynamic/converter"
"istio.io/istio/galley/pkg/source/kube/log"
"istio.io/istio/galley/pkg/source/kube/schema"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
kubeJson "k8s.io/apimachinery/pkg/runtime/serializer/json"
)
const (
yamlSeparator = "\n---\n"
)
var (
supportedExtensions = map[string]bool{
".yaml": true,
".yml": true,
}
)
// source is source implementation for filesystem.
type source struct {
// configuration for the converters.
config *converter.Config
// Config File Path
root string
donec chan struct{}
mu sync.RWMutex
// map to store namespace/name : shas
shas map[fileResourceKey][sha1.Size]byte
handler resource.EventHandler
// map to store kind : bool to indicate whether we need to deal with the resource or not
kinds map[string]bool
// map to store filename: []{namespace/name,kind} to indicate whether the resources has been deleted from one file
fileResourceKeys map[string][]*fileResourceKey
// fsresource version
version int64
watcher *fsnotify.Watcher
}
func (s *source) readFiles(root string) map[fileResourceKey]*fileResource {
results := map[fileResourceKey]*fileResource{}
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
result := s.readFile(path, info, true)
if result != nil && len(result) != 0 {
for _, r := range result {
results[r.newKey()] = r
}
}
//add watcher for sub folders
if info.Mode().IsDir() {
_ = s.watcher.Watch(path)
}
return nil
})
if err != nil {
log.Scope.Errorf("failure during filepath.Walk: %v", err)
}
return results
}
func (s *source) readFile(path string, info os.FileInfo, initial bool) []*fileResource {
result := []*fileResource{}
if mode := info.Mode() & os.ModeType; !supportedExtensions[filepath.Ext(path)] || (mode != 0 && mode != os.ModeSymlink) {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil {
log.Scope.Warnf("Failed to read %s: %v", path, err)
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
resourceKeyList := make([]*fileResourceKey, 0, 10)
for _, r := range s.parseFile(path, data) {
if !s.kinds[r.spec.Kind] {
continue
}
result = append(result, r)
key := r.newKey()
resourceKeyList = append(resourceKeyList, &key)
}
if initial {
s.fileResourceKeys[path] = resourceKeyList
}
return result
}
//process delete part of the resources in a file
func (s *source) processPartialDelete(fileName string, newData []*fileResource) {
s.mu.Lock()
defer s.mu.Unlock()
if resourceKeys, ok := s.fileResourceKeys[fileName]; ok {
for i := len(resourceKeys) - 1; i >= 0; i-- {
if resourceKeys[i] != nil {
found := false
for _, r := range newData {
if r.newKey() == *resourceKeys[i] {
found = true
break
}
}
if !found {
delete(s.shas, *resourceKeys[i])
s.process(resource.Deleted, *resourceKeys[i], nil)
resourceKeys = append(resourceKeys[:i], resourceKeys[i+1:]...)
}
}
}
if len(resourceKeys) > 0 {
s.fileResourceKeys[fileName] = resourceKeys
} else {
delete(s.fileResourceKeys, fileName)
}
}
}
func (s *source) processAddOrUpdate(fileName string, newData []*fileResource) {
s.mu.Lock()
defer s.mu.Unlock()
// need versionUpdated as sometimes when fswatcher fires events, there is actually no change on the file content
versionUpdated := false
for _, r := range newData {
k := r.newKey()
if _, ok := s.shas[k]; ok {
if s.shas[k] != r.sha {
versionUpdated = true
break
}
} else {
versionUpdated = true
break
}
}
if versionUpdated {
s.version++
}
for _, r := range newData {
k := r.newKey()
if _, ok := s.shas[k]; ok {
if s.shas[k] != r.sha {
s.fileResourceKeys[fileName] = append(s.fileResourceKeys[fileName], &k)
s.process(resource.Updated, k, r)
}
s.shas[k] = r.sha
continue
}
if s.fileResourceKeys != nil {
s.fileResourceKeys[fileName] = append(s.fileResourceKeys[fileName], &k)
}
s.process(resource.Added, k, r)
s.shas[k] = r.sha
}
}
//process delete all resources in a file
func (s *source) processDelete(fileName string) {
s.mu.Lock()
defer s.mu.Unlock()
if fileResourceKeys, ok := s.fileResourceKeys[fileName]; ok {
for _, fileResourceKey := range fileResourceKeys {
if fileResourceKey != nil {
delete(s.shas, *fileResourceKey)
s.process(resource.Deleted, *fileResourceKey, nil)
}
}
delete(s.fileResourceKeys, fileName)
}
}
func (s *source) initialCheck() {
newData := s.readFiles(s.root)
s.mu.Lock()
defer s.mu.Unlock()
for k, r := range newData {
s.process(resource.Added, k, r)
s.shas[k] = r.sha
}
s.handler(resource.FullSyncEvent)
}
// Stop implements runtime.Source
func (s *source) Stop() {
close(s.donec)
_ = s.watcher.Close()
}
func (s *source) process(eventKind resource.EventKind, key fileResourceKey, r *fileResource) {
version := resource.Version(fmt.Sprintf("v%d", s.version))
var event resource.Event
switch eventKind {
case resource.Added, resource.Updated:
event = resource.Event{
Kind: eventKind,
Entry: resource.Entry{
ID: resource.VersionedKey{
Key: resource.Key{
Collection: r.spec.Target.Collection,
FullName: key.fullName,
},
Version: version,
},
Item: r.entry.Resource,
Metadata: r.entry.Metadata,
},
}
case resource.Deleted:
spec := kubeMeta.Types.Get(key.kind)
event = resource.Event{
Kind: eventKind,
Entry: resource.Entry{
ID: resource.VersionedKey{
Key: resource.Key{
Collection: spec.Target.Collection,
FullName: key.fullName,
},
Version: version,
},
},
}
}
log.Scope.Debugf("Dispatching source event: %v", event)
s.handler(event)
}
// Start implements runtime.Source
func (s *source) Start(handler resource.EventHandler) error {
s.handler = handler
watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
s.watcher = watcher
_ = s.watcher.Watch(s.root)
s.initialCheck()
go func() {
for {
select {
// watch for events
case ev, more := <-s.watcher.Event:
if !more {
break
}
if ev.IsDelete() {
s.processDelete(ev.Name)
} else if ev.IsCreate() {
fi, err := os.Stat(ev.Name)
if err != nil {
log.Scope.Warnf("error occurs for watching %s", ev.Name)
} else {
if fi.Mode().IsDir() {
log.Scope.Debugf("add watcher for new folder %s", ev.Name)
_ = s.watcher.Watch(ev.Name)
} else {
newData := s.readFile(ev.Name, fi, true)
if newData != nil && len(newData) != 0 {
s.processAddOrUpdate(ev.Name, newData)
}
}
}
} else if ev.IsModify() {
fi, err := os.Stat(ev.Name)
if err != nil {
log.Scope.Warnf("error occurs for watching %s", ev.Name)
} else {
if fi.Mode().IsDir() {
_ = s.watcher.RemoveWatch(ev.Name)
} else {
newData := s.readFile(ev.Name, fi, false)
if newData != nil && len(newData) != 0 {
s.processPartialDelete(ev.Name, newData)
s.processAddOrUpdate(ev.Name, newData)
} else {
s.processDelete(ev.Name)
}
}
}
}
case <-s.donec:
return
}
}
}()
return nil
}
// New returns a File System implementation of runtime.Source.
func New(root string, schema *schema.Instance, config *converter.Config) (runtime.Source, error) {
fs := &source{
config: config,
root: root,
kinds: map[string]bool{},
fileResourceKeys: map[string][]*fileResourceKey{},
donec: make(chan struct{}),
shas: map[fileResourceKey][sha1.Size]byte{},
version: 0,
}
for _, spec := range schema.All() {
fs.kinds[spec.Kind] = true
}
return fs, nil
}
type fileResource struct {
entry converter.Entry
spec *schema.ResourceSpec
sha [sha1.Size]byte
}
func (r *fileResource) newKey() fileResourceKey {
return fileResourceKey{
kind: r.spec.Kind,
fullName: r.entry.Key,
}
}
type fileResourceKey struct {
fullName resource.FullName
kind string
}
func (s *source) parseFile(path string, data []byte) []*fileResource {
chunks := bytes.Split(data, []byte(yamlSeparator))
resources := make([]*fileResource, 0, len(chunks))
for i, chunk := range chunks {
chunk = bytes.TrimSpace(chunk)
if len(chunk) == 0 {
continue
}
r, err := s.parseChunk(chunk)
if err != nil {
log.Scope.Errorf("Error processing %s[%d]: %v", path, i, err)
continue
}
if r == nil {
continue
}
resources = append(resources, r)
}
return resources
}
func (s *source) parseChunk(yamlChunk []byte) (*fileResource, error) {
// Convert to JSON
jsonChunk, err := yaml.YAMLToJSON(yamlChunk)
if err != nil {
return nil, fmt.Errorf("failed converting YAML to JSON")
}
// Peek at the beginning of the JSON to
groupVersionKind, err := kubeJson.DefaultMetaFactory.Interpret(jsonChunk)
if err != nil {
return nil, err
}
spec := kubeMeta.Types.Get(groupVersionKind.Kind)
if spec == nil {
return nil, fmt.Errorf("failed finding spec for kind: %s", groupVersionKind.Kind)
}
builtinType := builtin.GetType(groupVersionKind.Kind)
if builtinType != nil {
obj, err := builtinType.ParseJSON(jsonChunk)
if err != nil {
return nil, err
}
objMeta := builtinType.ExtractObject(obj)
key := resource.FullNameFromNamespaceAndName(objMeta.GetNamespace(), objMeta.GetName())
return &fileResource{
spec: spec,
sha: sha1.Sum(yamlChunk),
entry: converter.Entry{
Metadata: resource.Metadata{
CreateTime: objMeta.GetCreationTimestamp().Time,
Labels: objMeta.GetLabels(),
Annotations: objMeta.GetAnnotations(),
},
Key: key,
Resource: builtinType.ExtractResource(obj),
},
}, nil
}
// No built-in processor for this type. Use dynamic processing via unstructured...
u := &unstructured.Unstructured{}
if err := json.Unmarshal(jsonChunk, u); err != nil {
return nil, err
}
if empty(u) {
return nil, nil
}
key := resource.FullNameFromNamespaceAndName(u.GetNamespace(), u.GetName())
entries, err := dynamic.ConvertAndLog(s.config, *spec, key, u.GetResourceVersion(), u)
if err != nil {
return nil, err
}
if len(entries) == 0 {
return nil, fmt.Errorf("did not receive any entries from converter: kind=%v, fullName=%v, rv=%s",
u.GetKind(), key, u.GetResourceVersion())
}
// TODO(nmittler): Will there ever be > 1 entries?
return &fileResource{
spec: spec,
sha: sha1.Sum(yamlChunk),
entry: entries[0],
}, nil
}
// Check if the parsed resource is empty
func empty(r *unstructured.Unstructured) bool {
if r.Object == nil || len(r.Object) == 0 {
return true
}
return false
}