-
Notifications
You must be signed in to change notification settings - Fork 246
/
load.go
328 lines (289 loc) · 8.72 KB
/
load.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
package declcfg
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"runtime"
"sync"
"github.com/joelanford/ignore"
"golang.org/x/sync/errgroup"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"github.com/operator-framework/api/pkg/operators"
"github.com/operator-framework/operator-registry/alpha/property"
)
const (
indexIgnoreFilename = ".indexignore"
)
type WalkMetasFSFunc func(path string, meta *Meta, err error) error
// WalkMetasFS walks the filesystem rooted at root and calls walkFn for each individual meta object found in the root.
// By default, WalkMetasFS is not thread-safe because it invokes walkFn concurrently. In order to make it thread-safe,
// use the WithConcurrency(1) to avoid concurrent invocations of walkFn.
func WalkMetasFS(ctx context.Context, root fs.FS, walkFn WalkMetasFSFunc, opts ...LoadOption) error {
if root == nil {
return fmt.Errorf("no declarative config filesystem provided")
}
options := LoadOptions{
concurrency: runtime.NumCPU(),
}
for _, opt := range opts {
opt(&options)
}
pathChan := make(chan string, options.concurrency)
// Create an errgroup to manage goroutines. The context is closed when any
// goroutine returns an error. Goroutines should check the context
// to see if they should return early (in the case of another goroutine
// returning an error).
eg, ctx := errgroup.WithContext(ctx)
// Walk the FS and send paths to a channel for parsing.
eg.Go(func() error {
return sendPaths(ctx, root, pathChan)
})
// Parse paths concurrently. The waitgroup ensures that all paths are parsed
// before the cfgChan is closed.
for i := 0; i < options.concurrency; i++ {
eg.Go(func() error {
return parseMetaPaths(ctx, root, pathChan, walkFn, options)
})
}
return eg.Wait()
}
type WalkMetasReaderFunc func(meta *Meta, err error) error
func WalkMetasReader(r io.Reader, walkFn WalkMetasReaderFunc) error {
dec := yaml.NewYAMLOrJSONDecoder(r, 4096)
for {
var in Meta
if err := dec.Decode(&in); err != nil {
if errors.Is(err, io.EOF) {
break
}
return walkFn(nil, err)
}
if err := walkFn(&in, nil); err != nil {
return err
}
}
return nil
}
type WalkFunc func(path string, cfg *DeclarativeConfig, err error) error
// WalkFS walks root using a gitignore-style filename matcher to skip files
// that match patterns found in .indexignore files found throughout the filesystem.
// It calls walkFn for each declarative config file it finds. If WalkFS encounters
// an error loading or parsing any file, the error will be immediately returned.
func WalkFS(root fs.FS, walkFn WalkFunc) error {
return walkFiles(root, func(root fs.FS, path string, err error) error {
if err != nil {
return walkFn(path, nil, err)
}
cfg, err := LoadFile(root, path)
if err != nil {
return walkFn(path, cfg, err)
}
return walkFn(path, cfg, nil)
})
}
func walkFiles(root fs.FS, fn func(root fs.FS, path string, err error) error) error {
if root == nil {
return fmt.Errorf("no declarative config filesystem provided")
}
matcher, err := ignore.NewMatcher(root, indexIgnoreFilename)
if err != nil {
return err
}
return fs.WalkDir(root, ".", func(path string, info fs.DirEntry, err error) error {
if err != nil {
return fn(root, path, err)
}
// avoid validating a directory, an .indexignore file, or any file that matches
// an ignore pattern outlined in a .indexignore file.
if info.IsDir() || info.Name() == indexIgnoreFilename || matcher.Match(path, false) {
return nil
}
return fn(root, path, nil)
})
}
type LoadOptions struct {
concurrency int
}
type LoadOption func(*LoadOptions)
func WithConcurrency(concurrency int) LoadOption {
return func(opts *LoadOptions) {
opts.concurrency = concurrency
}
}
// LoadFS loads a declarative config from the provided root FS. LoadFS walks the
// filesystem from root and uses a gitignore-style filename matcher to skip files
// that match patterns found in .indexignore files found throughout the filesystem.
// If LoadFS encounters an error loading or parsing any file, the error will be
// immediately returned.
func LoadFS(ctx context.Context, root fs.FS, opts ...LoadOption) (*DeclarativeConfig, error) {
builder := fbcBuilder{}
if err := WalkMetasFS(ctx, root, func(path string, meta *Meta, err error) error {
if err != nil {
return err
}
return builder.addMeta(meta)
}, opts...); err != nil {
return nil, err
}
return &builder.cfg, nil
}
func sendPaths(ctx context.Context, root fs.FS, pathChan chan<- string) error {
defer close(pathChan)
return walkFiles(root, func(_ fs.FS, path string, err error) error {
if err != nil {
return err
}
select {
case pathChan <- path:
case <-ctx.Done(): // don't block on sending to pathChan
return ctx.Err()
}
return nil
})
}
func parseMetaPaths(ctx context.Context, root fs.FS, pathChan <-chan string, walkFn WalkMetasFSFunc, options LoadOptions) error {
for {
select {
case <-ctx.Done(): // don't block on receiving from pathChan
return ctx.Err()
case path, ok := <-pathChan:
if !ok {
return nil
}
file, err := root.Open(path)
if err != nil {
return err
}
if err := WalkMetasReader(file, func(meta *Meta, err error) error {
return walkFn(path, meta, err)
}); err != nil {
return err
}
}
}
}
func readBundleObjects(b *Bundle) error {
var obj property.BundleObject
for i, props := range b.Properties {
if props.Type != property.TypeBundleObject {
continue
}
if err := json.Unmarshal(props.Value, &obj); err != nil {
return fmt.Errorf("package %q, bundle %q: parse property at index %d as bundle object: %v", b.Package, b.Name, i, err)
}
objJson, err := yaml.ToJSON(obj.Data)
if err != nil {
return fmt.Errorf("package %q, bundle %q: convert bundle object property at index %d to JSON: %v", b.Package, b.Name, i, err)
}
b.Objects = append(b.Objects, string(objJson))
}
b.CsvJSON = extractCSV(b.Objects)
return nil
}
func extractCSV(objs []string) string {
for _, obj := range objs {
u := unstructured.Unstructured{}
if err := yaml.Unmarshal([]byte(obj), &u); err != nil {
continue
}
if u.GetKind() == operators.ClusterServiceVersionKind {
return obj
}
}
return ""
}
// LoadReader reads yaml or json from the passed in io.Reader and unmarshals it into a DeclarativeConfig struct.
func LoadReader(r io.Reader) (*DeclarativeConfig, error) {
builder := fbcBuilder{}
if err := WalkMetasReader(r, func(meta *Meta, err error) error {
if err != nil {
return err
}
return builder.addMeta(meta)
}); err != nil {
return nil, err
}
return &builder.cfg, nil
}
// LoadFile will unmarshall declarative config components from a single filename provided in 'path'
// located at a filesystem hierarchy 'root'
func LoadFile(root fs.FS, path string) (*DeclarativeConfig, error) {
file, err := root.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
cfg, err := LoadReader(file)
if err != nil {
return nil, err
}
return cfg, nil
}
// LoadSlice will compose declarative config components from a slice of Meta objects
func LoadSlice(metas []*Meta) (*DeclarativeConfig, error) {
builder := fbcBuilder{}
for _, meta := range metas {
if err := builder.addMeta(meta); err != nil {
return nil, err
}
}
return &builder.cfg, nil
}
type fbcBuilder struct {
cfg DeclarativeConfig
packagesMu sync.Mutex
channelsMu sync.Mutex
bundlesMu sync.Mutex
deprecationsMu sync.Mutex
othersMu sync.Mutex
}
func (c *fbcBuilder) addMeta(in *Meta) error {
switch in.Schema {
case SchemaPackage:
var p Package
if err := json.Unmarshal(in.Blob, &p); err != nil {
return fmt.Errorf("parse package: %v", err)
}
c.packagesMu.Lock()
c.cfg.Packages = append(c.cfg.Packages, p)
c.packagesMu.Unlock()
case SchemaChannel:
var ch Channel
if err := json.Unmarshal(in.Blob, &ch); err != nil {
return fmt.Errorf("parse channel: %v", err)
}
c.channelsMu.Lock()
c.cfg.Channels = append(c.cfg.Channels, ch)
c.channelsMu.Unlock()
case SchemaBundle:
var b Bundle
if err := json.Unmarshal(in.Blob, &b); err != nil {
return fmt.Errorf("parse bundle: %v", err)
}
if err := readBundleObjects(&b); err != nil {
return fmt.Errorf("read bundle objects: %v", err)
}
c.bundlesMu.Lock()
c.cfg.Bundles = append(c.cfg.Bundles, b)
c.bundlesMu.Unlock()
case SchemaDeprecation:
var d Deprecation
if err := json.Unmarshal(in.Blob, &d); err != nil {
return fmt.Errorf("parse deprecation: %w", err)
}
c.deprecationsMu.Lock()
c.cfg.Deprecations = append(c.cfg.Deprecations, d)
c.deprecationsMu.Unlock()
case "":
return fmt.Errorf("object '%s' is missing root schema field", string(in.Blob))
default:
c.othersMu.Lock()
c.cfg.Others = append(c.cfg.Others, *in)
c.othersMu.Unlock()
}
return nil
}