-
Notifications
You must be signed in to change notification settings - Fork 67
/
packages.go
584 lines (493 loc) · 15.1 KB
/
packages.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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
// or more contributor license agreements. Licensed under the Elastic License;
// you may not use this file except in compliance with the Elastic License.
package packages
import (
"archive/zip"
"context"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/prometheus/client_golang/prometheus"
"go.elastic.co/apm/v2"
"go.uber.org/zap"
"github.com/elastic/package-registry/metrics"
)
// ValidationDisabled is a flag which can disable package content validation (package, data streams, assets, etc.).
var ValidationDisabled bool
// Packages is a list of packages.
type Packages []*Package
func (p Packages) Len() int { return len(p) }
func (p Packages) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p Packages) Less(i, j int) bool {
if p[i].Title != nil && p[j].Title != nil && *p[i].Title != *p[j].Title {
return *p[i].Title < *p[j].Title
}
return p[i].Version < p[j].Version
}
// Join returns a set of packages that combines both sets. If there is already
// a package in `p1` with the same name and version that a package in `p2`, the
// latter is not added.
func (p1 Packages) Join(p2 Packages) Packages {
for _, p := range p2 {
if p1.contains(p) {
continue
}
p1 = append(p1, p)
}
return p1
}
// contains returns true if `ps` contains a package with the same name and version as `p`.
func (ps Packages) contains(p *Package) bool {
return ps.index(p) >= 0
}
// index finds if `ps` contains a package with the same name and version as `p` and
// returns its index. If it is not found, it returns -1.
func (ps Packages) index(p *Package) int {
for i, candidate := range ps {
if candidate.Name != p.Name {
continue
}
if cv, pv := candidate.versionSemVer, p.versionSemVer; cv != nil && pv != nil {
if !cv.Equal(pv) {
continue
}
}
if candidate.Version != p.Version {
continue
}
return i
}
return -1
}
// GetOptions can be used to pass options to Get.
type GetOptions struct {
// Filter to apply when querying for packages. If the filter is nil,
// all packages are returned. This is different to a zero-object filter,
// where experimental packages are filtered by default.
Filter *Filter
}
// FileSystemIndexer indexes packages from the filesystem.
type FileSystemIndexer struct {
paths []string
packageList Packages
// Label used for APM instrumentation.
label string
// Walker function used to look for files, it returns true for paths that should be indexed.
walkerFn func(basePath, path string, info os.DirEntry) (shouldIndex bool, err error)
// Builder to access the files of a package in this indexer.
fsBuilder FileSystemBuilder
logger *zap.Logger
}
// NewFileSystemIndexer creates a new FileSystemIndexer for the given paths.
func NewFileSystemIndexer(logger *zap.Logger, paths ...string) *FileSystemIndexer {
walkerFn := func(basePath, path string, info os.DirEntry) (bool, error) {
relativePath, err := filepath.Rel(basePath, path)
if err != nil {
return false, err
}
dirs := strings.Split(relativePath, string(filepath.Separator))
if len(dirs) < 2 {
return false, nil // need to go to the package version level
}
if info.IsDir() {
versionDir := dirs[1]
_, err := semver.StrictNewVersion(versionDir)
if err != nil {
logger.Warn("ignoring unexpected directory",
zap.String("file.path", path))
return false, filepath.SkipDir
}
return true, nil
}
// Unexpected file, return nil in order to continue processing sibling directories
// Fixes an annoying problem when the .DS_Store file is left behind and the package
// is not loading without any error information
logger.Warn("ignoring unexpected file", zap.String("file.path", path))
return false, nil
}
return &FileSystemIndexer{
paths: paths,
label: "FileSystemIndexer",
walkerFn: walkerFn,
fsBuilder: ExtractedFileSystemBuilder,
logger: logger,
}
}
var ExtractedFileSystemBuilder = func(p *Package) (PackageFileSystem, error) {
return NewExtractedPackageFileSystem(p)
}
// NewZipFileSystemIndexer creates a new ZipFileSystemIndexer for the given paths.
func NewZipFileSystemIndexer(logger *zap.Logger, paths ...string) *FileSystemIndexer {
walkerFn := func(basePath, path string, info os.DirEntry) (bool, error) {
if info.IsDir() {
return false, nil
}
if !strings.HasSuffix(path, ".zip") {
return false, nil
}
// Check if the file is actually a zip file.
r, err := zip.OpenReader(path)
if err != nil {
logger.Warn("ignoring invalid zip file",
zap.String("file.path", path), zap.Error(err))
return false, nil
}
defer r.Close()
return true, nil
}
return &FileSystemIndexer{
paths: paths,
label: "ZipFileSystemIndexer",
walkerFn: walkerFn,
fsBuilder: ZipFileSystemBuilder,
logger: logger,
}
}
var ZipFileSystemBuilder = func(p *Package) (PackageFileSystem, error) {
return NewZipPackageFileSystem(p)
}
// Init initializes the indexer.
func (i *FileSystemIndexer) Init(ctx context.Context) (err error) {
i.packageList, err = i.getPackagesFromFileSystem(ctx)
if err != nil {
return fmt.Errorf("reading packages from filesystem failed: %w", err)
}
return nil
}
// Get returns a slice with packages.
// Options can be used to filter the returned list of packages. When no options are passed
// or they don't contain any filter, no filtering is done.
// The list is stored in memory and on the second request directly served from memory.
// This assumes changes to packages only happen on restart (unless development mode is enabled).
// Caching the packages request many file reads every time this method is called.
func (i *FileSystemIndexer) Get(ctx context.Context, opts *GetOptions) (Packages, error) {
start := time.Now()
defer metrics.IndexerGetDurationSeconds.With(prometheus.Labels{"indexer": i.label}).Observe(time.Since(start).Seconds())
if opts == nil {
return i.packageList, nil
}
if opts.Filter != nil {
return opts.Filter.Apply(ctx, i.packageList)
}
return i.packageList, nil
}
func (i *FileSystemIndexer) getPackagesFromFileSystem(ctx context.Context) (Packages, error) {
span, _ := apm.StartSpan(ctx, "GetFromFileSystem", "app")
span.Context.SetLabel("indexer", i.label)
defer span.End()
type packageKey struct {
name string
version string
}
packagesFound := make(map[packageKey]struct{})
var pList Packages
for _, basePath := range i.paths {
packagePaths, err := i.getPackagePaths(basePath)
if err != nil {
return nil, err
}
i.logger.Info("Searching packages in " + basePath)
for _, path := range packagePaths {
p, err := NewPackage(path, i.fsBuilder)
if err != nil {
return nil, fmt.Errorf("loading package failed (path: %s): %w", path, err)
}
key := packageKey{name: p.Name, version: p.Version}
if _, found := packagesFound[key]; found {
i.logger.Debug("duplicated package",
zap.String("package.name", p.Name),
zap.String("package.version", p.Version),
zap.String("package.path", p.BasePath))
continue
}
packagesFound[key] = struct{}{}
pList = append(pList, p)
i.logger.Debug("found package",
zap.String("package.name", p.Name),
zap.String("package.version", p.Version),
zap.String("package.path", p.BasePath))
}
}
return pList, nil
}
// getPackagePaths returns list of available packages, one for each version.
func (i *FileSystemIndexer) getPackagePaths(packagesPath string) ([]string, error) {
var foundPaths []string
err := filepath.WalkDir(packagesPath, func(path string, info os.DirEntry, err error) error {
if os.IsNotExist(err) {
return filepath.SkipDir
}
if err != nil {
return err
}
shouldIndex, err := i.walkerFn(packagesPath, path, info)
if err != nil {
return err
}
if !shouldIndex {
return nil
}
foundPaths = append(foundPaths, path)
if info.IsDir() {
// If a directory is being added, consider all its contents part of
// the package and continue.
return filepath.SkipDir
}
return nil
})
if err != nil {
return nil, fmt.Errorf("listing packages failed (path: %s): %w", packagesPath, err)
}
return foundPaths, nil
}
// Filter can be used to filter a list of packages.
type Filter struct {
AllVersions bool
Category string
Prerelease bool
KibanaVersion *semver.Version
PackageName string
PackageVersion string
PackageType string
Capabilities []string
SpecMin *semver.Version
SpecMax *semver.Version
Discovery *discoveryFilter
// Deprecated, release tags to be removed.
Experimental bool
}
type discoveryFilter struct {
Fields discoveryFilterFields
}
func NewDiscoveryFilter(filter string) (*discoveryFilter, error) {
filterType, args, found := strings.Cut(filter, ":")
if !found {
return nil, fmt.Errorf("could not parse filter %q", filter)
}
var result discoveryFilter
switch filterType {
case "fields":
for _, name := range strings.Split(args, ",") {
result.Fields = append(result.Fields, DiscoveryField{
Name: name,
})
}
default:
return nil, fmt.Errorf("unknown discovery filter %q", filterType)
}
return &result, nil
}
func (f *discoveryFilter) Matches(p *Package) bool {
if f == nil {
return true
}
return f.Fields.Matches(p)
}
type discoveryFilterFields []DiscoveryField
// Matches implements matching for a collection of fields used as discovery filter.
// It matches if all fields in the package are included in the list of fields in the query.
func (fields discoveryFilterFields) Matches(p *Package) bool {
// If the package doesn't define this filter, it doesn't match.
if p.Discovery == nil || len(p.Discovery.Fields) == 0 {
return false
}
for _, packageField := range p.Discovery.Fields {
if !slices.Contains([]DiscoveryField(fields), packageField) {
return false
}
}
return true
}
// Apply applies the filter to the list of packages, if the filter is nil, no filtering is done.
func (f *Filter) Apply(ctx context.Context, packages Packages) (Packages, error) {
if f == nil {
return packages, nil
}
span, ctx := apm.StartSpan(ctx, "FilterPackages", "app")
defer span.End()
if f.Experimental {
return f.legacyApply(ctx, packages), nil
}
// Checks that only the most recent version of an integration is added to the list
var packagesList Packages
for _, p := range packages {
// Skip experimental packages if flag is not specified.
if p.Release == ReleaseExperimental && !f.Prerelease {
continue
}
// Skip prerelease packages by default.
if p.IsPrerelease() && !f.Prerelease {
continue
}
if f.KibanaVersion != nil {
if valid := p.HasKibanaVersion(f.KibanaVersion); !valid {
continue
}
}
if f.PackageName != "" && f.PackageName != p.Name {
continue
}
if f.PackageVersion != "" && f.PackageVersion != p.Version {
continue
}
if f.PackageType != "" && f.PackageType != p.Type {
continue
}
if f.Capabilities != nil {
if valid := p.WorksWithCapabilities(f.Capabilities); !valid {
continue
}
}
if f.Discovery != nil && !f.Discovery.Matches(p) {
continue
}
if f.SpecMin != nil || f.SpecMax != nil {
valid, err := p.HasCompatibleSpec(f.SpecMin, f.SpecMax, f.KibanaVersion)
if err != nil {
return nil, fmt.Errorf("can't compare spec version for %s (%s-%s): %w", p.Name, f.SpecMin, f.SpecMax, err)
}
if !valid {
continue
}
}
addPackage := true
if !f.AllVersions {
// Check if the version exists and if it should be added or not.
for i, current := range packagesList {
if current.Name != p.Name {
continue
}
addPackage = false
// If the package in the list is newer or equal, do nothing.
if current.IsNewerOrEqual(p) {
continue
}
// Otherwise replace it.
packagesList[i] = p
}
}
if addPackage {
packagesList = append(packagesList, p)
}
}
// Filter by category after selecting the newer packages.
packagesList = filterCategories(packagesList, f.Category)
return packagesList, nil
}
// legacyApply applies the filter to the list of packages for legacy clients using `experimental=true`.
func (f *Filter) legacyApply(ctx context.Context, packages Packages) Packages {
if f == nil {
return packages
}
// Checks that only the most recent version of an integration is added to the list
var packagesList Packages
for _, p := range packages {
// Skip experimental packages if flag is not specified.
if p.Release == ReleaseExperimental && !f.Experimental {
continue
}
if f.KibanaVersion != nil {
if valid := p.HasKibanaVersion(f.KibanaVersion); !valid {
continue
}
}
if f.PackageName != "" && f.PackageName != p.Name {
continue
}
if f.PackageVersion != "" && f.PackageVersion != p.Version {
continue
}
if f.PackageType != "" && f.PackageType != p.Type {
continue
}
addPackage := true
if !f.AllVersions {
// Check if the version exists and if it should be added or not.
for i, current := range packagesList {
if current.Name != p.Name {
continue
}
addPackage = false
// If the package in the list is newer or equal, do nothing, unless it is a prerelease.
if current.IsPrerelease() == p.IsPrerelease() && current.IsNewerOrEqual(p) {
continue
}
// If the package in the list is not a prerelease, and current is, do nothing.
if !current.IsPrerelease() && p.IsPrerelease() {
continue
}
// Otherwise replace it.
packagesList[i] = p
}
}
if addPackage {
packagesList = append(packagesList, p)
}
}
if f.AllVersions {
packageHasNonPrerelease := make(map[string]bool)
for _, p := range packagesList {
if !p.IsPrerelease() {
packageHasNonPrerelease[p.Name] = true
}
}
i := 0
for _, p := range packagesList {
if packageHasNonPrerelease[p.Name] && p.IsPrerelease() {
continue
}
packagesList[i] = p
i++
}
packagesList = packagesList[:i]
}
// Filter by category after selecting the newer packages.
packagesList = filterCategories(packagesList, f.Category)
return packagesList
}
func filterCategories(packages Packages, category string) Packages {
if category == "" {
return packages
}
var result Packages
for _, p := range packages {
if !p.HasCategory(category) && !p.HasPolicyTemplateWithCategory(category) {
continue
}
if !p.HasCategory(category) {
p = filterPolicyTemplates(*p, category)
}
result = append(result, p)
}
return result
}
func filterPolicyTemplates(p Package, category string) *Package {
var updatedPolicyTemplates []PolicyTemplate
var updatedBasePolicyTemplates []BasePolicyTemplate
for i, pt := range p.PolicyTemplates {
if slices.Contains(pt.Categories, category) {
updatedPolicyTemplates = append(updatedPolicyTemplates, pt)
updatedBasePolicyTemplates = append(updatedBasePolicyTemplates, p.BasePackage.BasePolicyTemplates[i])
}
}
p.PolicyTemplates = updatedPolicyTemplates
p.BasePackage.BasePolicyTemplates = updatedBasePolicyTemplates
return &p
}
// NameVersionFilter is a helper to initialize a Filter with the usual
// options to look per name and version along all packages indexed.
func NameVersionFilter(name, version string) GetOptions {
return GetOptions{
Filter: &Filter{
Experimental: true,
Prerelease: true,
PackageName: name,
PackageVersion: version,
},
}
}