/
localpackages.go
598 lines (514 loc) · 25.3 KB
/
localpackages.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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.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 localpackages implements the local storage for packages managed by the ConfigurePackage plugin.
package localpackages
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"time"
"github.com/aws/amazon-ssm-agent/agent/appconfig"
"github.com/aws/amazon-ssm-agent/agent/contracts"
"github.com/aws/amazon-ssm-agent/agent/fileutil"
"github.com/aws/amazon-ssm-agent/agent/fileutil/filelock"
"github.com/aws/amazon-ssm-agent/agent/jsonutil"
"github.com/aws/amazon-ssm-agent/agent/log"
"github.com/aws/amazon-ssm-agent/agent/plugins/configurepackage/envdetect"
"github.com/aws/amazon-ssm-agent/agent/plugins/configurepackage/installer"
"github.com/aws/amazon-ssm-agent/agent/plugins/configurepackage/ssminstaller"
"github.com/aws/amazon-ssm-agent/agent/plugins/configurepackage/trace"
"github.com/aws/amazon-ssm-agent/agent/plugins/inventory/model"
)
// DownloadDelegate is a function that downloads a package to a directory provided by the repository
type DownloadDelegate func(tracer trace.Tracer, targetDirectory string) error
// InstallState is an enum describing the installation state of a package
type InstallState uint
// NOTE: Do not change the order of this enum - the numeric value is serialized as package state and must deserialize to the same value
const (
None InstallState = iota // Package version not present in repository
Unknown InstallState = iota // Present in repository but no state information or corrupt state
Failed InstallState = iota // Installation of the package version was attempted but failed
Uninstalling InstallState = iota // Package version being uninstalled version but not yet uninstalled
Uninstalled InstallState = iota // Successfully uninstalled version of a package (but not yet deleted)
New InstallState = iota // Present in the repository but not yet installed
Upgrading InstallState = iota // Uninstalling previous version
Installing InstallState = iota // Package version being installed but not yet installed
Installed InstallState = iota // Successfully installed / updated version of a package
RollbackUninstall InstallState = iota // Uninstalling as part of rollback
RollbackInstall InstallState = iota // Installing as part of rollback
Updating InstallState = iota // Package version being updated but the update script is not yet executed
)
// String returns the string representation of the InstallState
func (state InstallState) String() string {
stateNames := [...]string{
"None",
"Unknown",
"Failed",
"Uninstalling",
"Uninstalled",
"New",
"Upgrading",
"Installing",
"Installed",
"RollbackUninstall",
"RollbackInstall",
"Updating"}
if state < None || state > Updating {
return "StateNotFound"
}
return stateNames[state]
}
// Repository represents local storage for packages managed by configurePackage
// Different formats for different versions are managed within the Repository abstraction
type Repository interface {
GetInstalledVersion(tracer trace.Tracer, packageArn string) string
ValidatePackage(tracer trace.Tracer, packageArn string, version string) error
RefreshPackage(tracer trace.Tracer, packageArn string, version string, packageServiceName string, downloader DownloadDelegate) error
AddPackage(tracer trace.Tracer, packageArn string, version string, packageServiceName string, downloader DownloadDelegate) error
SetInstallState(tracer trace.Tracer, packageArn string, version string, state InstallState) error
GetInstallState(tracer trace.Tracer, packageArn string) (state InstallState, version string)
RemovePackage(tracer trace.Tracer, packageArn string, version string) error
GetInventoryData(log log.T) []model.ApplicationData
GetInstaller(tracer trace.Tracer, configuration contracts.Configuration, packageArn string, version string, additionalArguments string) installer.Installer
LockPackage(tracer trace.Tracer, packageArn string, action string) error
UnlockPackage(tracer trace.Tracer, packageArn string)
ReadManifest(packageArn string, packageVersion string) ([]byte, error)
WriteManifest(packageArn string, packageVersion string, content []byte) error
DeleteManifest(packageArn string, packageVersion string) error
ReadManifestHash(packageArn string, documentVersion string) ([]byte, error)
WriteManifestHash(packageArn string, documentVersion string, content []byte) error
LoadTraces(tracer trace.Tracer, packageArn string) error
PersistTraces(tracer trace.Tracer, packageArn string) error
}
// NewRepository is the factory method for the package repository with default file system dependencies
func NewRepository() Repository {
return &localRepository{
filesysdep: &fileSysDepImp{},
repoRoot: appconfig.PackageRoot,
lockRoot: appconfig.PackageLockRoot,
manifestCachePath: appconfig.ManifestCacheDirectory,
fileLocker: filelock.NewFileLocker(),
}
}
// PackageInstallState represents the json structure of the current package state
type PackageInstallState struct {
Name string `json:"name"`
Version string `json:"version"`
State InstallState `json:"state"`
Time time.Time `json:"time"`
LastInstalledVersion string `json:"lastinstalledversion"`
RetryCount int `json:"retrycount"`
}
// PackageManifest represents json structure of package's online configuration file.
type PackageManifest struct {
Name string `json:"name"`
Platform string `json:"platform"`
Architecture string `json:"architecture"`
Version string `json:"version"`
AppName string `json:"appname"` // optional inventory attribute
AppPublisher string `json:"apppublisher"` // optional inventory attribute
AppReferenceURL string `json:"appreferenceurl"` // optional inventory attribute
AppType string `json:"apptype"` // optional inventory attribute
}
type localRepository struct {
filesysdep FileSysDep
repoRoot string
lockRoot string
manifestCachePath string
fileLocker filelock.FileLocker
}
func (repo *localRepository) LockPackage(tracer trace.Tracer, packageArn string, action string) error {
err := fileutil.MakeDirs(repo.lockRoot)
if err != nil {
return err
}
lockPath := repo.getLockPath(packageArn)
return lockPackage(repo.fileLocker, lockPath, packageArn, action)
}
func (repo *localRepository) UnlockPackage(tracer trace.Tracer, packageArn string) {
lockPath := repo.getLockPath(packageArn)
unlockPackage(repo.fileLocker, lockPath, packageArn)
}
// GetInstaller returns an Installer appropriate for the package and version
// The configuration should include the appropriate OutputS3KeyPrefix for documents run by the Installer
func (repo *localRepository) GetInstaller(tracer trace.Tracer,
configuration contracts.Configuration,
packageArn string,
version string,
additionalArguments string) installer.Installer {
// Give each version an independent orchestration directory to support install and uninstall for two versions during rollback
configuration.OrchestrationDirectory = filepath.Join(configuration.OrchestrationDirectory, normalizeDirectory(version))
return ssminstaller.New(packageArn,
version,
additionalArguments,
repo.getPackageVersionPath(tracer, packageArn, version),
configuration,
&envdetect.CollectorImp{})
}
// GetInstalledVersion returns the version of the last successfully installed package
func (repo *localRepository) GetInstalledVersion(tracer trace.Tracer, packageArn string) string {
packageState := repo.loadInstallState(repo.filesysdep, tracer, packageArn)
if packageState.State == Installed || (packageState.State == Unknown && packageState.LastInstalledVersion == "") {
return packageState.Version
} else {
return packageState.LastInstalledVersion
}
}
func (repo *localRepository) checkPackageIsSupported(tracer trace.Tracer, packageArn string, version string) error {
validatetrace := tracer.BeginSection("isPackageSupported")
defer validatetrace.End()
path := repo.getPackageVersionPath(tracer, packageArn, version)
if repo.filesysdep.Exists(filepath.Join(path, "install.ps1")) {
return nil
}
if repo.filesysdep.Exists(filepath.Join(path, "install.sh")) {
return nil
}
err := fmt.Errorf("Package is not supported (package is missing install action)")
validatetrace.WithError(err).End()
return err
}
// ValidatePackage returns an error if the given package version artifacts are missing, incomplete, or corrupt
func (repo *localRepository) ValidatePackage(tracer trace.Tracer, packageArn string, version string) error {
// Find and parse manifest
trace := tracer.BeginSection("Validate Package")
if _, err := repo.openPackageManifest(tracer, repo.filesysdep, packageArn, version); err != nil {
trace.WithError(err).End()
return fmt.Errorf("Package manifest is invalid: %v", err)
}
hasContent := false
packageVersionPath := repo.getPackageVersionPath(tracer, packageArn, version)
trace.AppendDebugf("package version path for package %v version %v is %v", packageArn, version, packageVersionPath)
files, errFiles := repo.filesysdep.GetFileNames(packageVersionPath)
if errFiles != nil {
trace.WithError(errFiles)
} else {
trace.AppendDebugf("%v files exist in %v ", len(files), packageVersionPath)
}
dirs, errDirs := repo.filesysdep.GetDirectoryNames(packageVersionPath)
if errDirs != nil {
trace.WithError(errDirs)
} else {
trace.AppendDebugf("%v folders exist in %v", len(dirs), packageVersionPath)
}
// Ensure that at least one other file or folder is present
if errFiles == nil && len(files) > 1 {
hasContent = true
} else if errDirs == nil && len(dirs) > 0 {
hasContent = true
}
if !hasContent {
return fmt.Errorf("Package is incomplete")
}
// This is necessary to make sure pre-birdwatcher packages are deemed unsupported, triggering package refresh to birdwatched version of the package.
if err := repo.checkPackageIsSupported(tracer, packageArn, version); err != nil {
trace.WithError(err).End()
return err
}
trace.End()
return nil
}
// RefreshPackage updates the package binaries. Used if ValidatePackage returns an error, initially same implementation as AddPackage
func (repo *localRepository) RefreshPackage(tracer trace.Tracer, packageArn string, version string, packageServiceName string, downloader DownloadDelegate) error {
return repo.AddPackage(tracer, packageArn, version, packageServiceName, downloader)
}
// AddPackage creates an entry in the repository and downloads artifacts for a package
func (repo *localRepository) AddPackage(tracer trace.Tracer, packageArn string, version string, packageServiceName string, downloader DownloadDelegate) error {
packagePath := repo.getPackageVersionPath(tracer, packageArn, version)
if err := repo.filesysdep.MakeDirExecute(packagePath); err != nil {
return err
}
if err := downloader(tracer, packagePath); err != nil {
// If the downloader delegate execution has any errors, we should clear up the newly made directory.
cleanupTrace := tracer.BeginSection(fmt.Sprintf("cleaning up package version path: %s", packagePath))
if cleanupErr := repo.filesysdep.RemoveAll(packagePath); cleanupErr != nil {
cleanupTrace.WithError(cleanupErr)
}
cleanupTrace.End()
return err
}
// if no previous version, set state to new
repo.SetInstallState(tracer, packageArn, version, New)
return nil
}
// SetInstallState flags the state of a version of a package downloaded to the repository for installation
func (repo *localRepository) SetInstallState(tracer trace.Tracer, packageArn string, version string, state InstallState) error {
var packageState = repo.loadInstallState(repo.filesysdep, tracer, packageArn)
if state == New && packageState.State != None {
return nil
}
packageState.Version = version
packageState.Time = time.Now()
if packageState.State == state {
packageState.RetryCount++
} else {
packageState.RetryCount = 0
}
packageState.State = state
if state == Installed {
packageState.LastInstalledVersion = version
}
if state == Uninstalled {
packageState.LastInstalledVersion = ""
}
var installStateContent string
var err error
if installStateContent, err = jsonutil.Marshal(packageState); err != nil {
return err
}
return repo.filesysdep.WriteFile(repo.getInstallStatePath(packageArn), installStateContent)
}
// GetInstallState returns the current state of a package
func (repo *localRepository) GetInstallState(tracer trace.Tracer, packageArn string) (state InstallState, version string) {
installState := repo.loadInstallState(repo.filesysdep, tracer, packageArn)
return installState.State, installState.Version
}
// RemovePackage deletes an entry in the repository and removes package artifacts
func (repo *localRepository) RemovePackage(tracer trace.Tracer, packageArn string, version string) error {
return repo.filesysdep.RemoveAll(repo.getPackageVersionPath(tracer, packageArn, version))
}
// GetInventoryData returns ApplicationData for every successfully and currently installed package in the repository
// that has inventory fields in its manifest
func (repo *localRepository) GetInventoryData(log log.T) []model.ApplicationData {
result := make([]model.ApplicationData, 0)
// Search package root for packages that are installed and return data from the manifest of the installed version
var dirs []string
var err error
tracer := trace.NewTracer(log) // temporarily wrap log into tracer to pass forward to other method calls
defer tracer.BeginSection("GetInventoryData").EndWithError(&err)
if dirs, err = repo.filesysdep.GetDirectoryNames(repo.repoRoot); err != nil {
return result
}
for _, packageDirectoryName := range dirs {
var packageState *PackageInstallState
if packageState = repo.loadInstallStateByDirectoryName(repo.filesysdep, tracer, packageDirectoryName); packageState == nil || packageState.State != Installed {
continue
}
// NOTE: We could put inventory info in the installstate file. That might be simpler than opening two files in this method.
var manifest *PackageManifest
manifest, err = repo.openPackageManifest(tracer, repo.filesysdep, packageState.Name, packageState.Version)
if hasInventoryData(manifest) {
result = append(result, createApplicationData(manifest, packageState))
}
}
return result
}
// manifest cache
// filePath will return the manifest file path for a package name and package version
func (r *localRepository) filePath(packageArn string, packageVersion string) string {
return filepath.Join(r.manifestCachePath, fmt.Sprintf("%s_%s.json", normalizeDirectory(packageArn), normalizeDirectory(packageVersion)))
}
// ReadManifest will return the manifest data for a given package name and package version from the cache
func (r *localRepository) ReadManifest(packageArn string, packageVersion string) ([]byte, error) {
return r.filesysdep.ReadFile(r.filePath(packageArn, packageVersion))
}
// WriteManifest will put the manifest data for a given package name and package version into the cache
func (r *localRepository) WriteManifest(packageArn string, packageVersion string, content []byte) error {
err := fileutil.MakeDirs(r.manifestCachePath)
if err != nil {
return err
}
return r.filesysdep.WriteFile(r.filePath(packageArn, packageVersion), string(content))
}
// PurgeManifest deletes cached manifest data from the disk for a given package name and package version
func (r *localRepository) DeleteManifest(packageArn string, packageVersion string) error {
manifestFilePath := r.filePath(packageArn, packageVersion)
if !fileutil.Exists(manifestFilePath) {
return nil
}
return fileutil.DeleteFile(manifestFilePath)
}
// manifest cache hash
// textPath will return the manifest file path for a package name and package version
func (r *localRepository) textPath(packageArn string, documentVersion string) string {
return filepath.Join(r.manifestCachePath, fmt.Sprintf("%s_%s.txt", normalizeDirectory(packageArn), documentVersion))
}
// ReadManifestHash will return the manifest data for a given package name and package version from the cache
func (r *localRepository) ReadManifestHash(packageArn string, documentVersion string) ([]byte, error) {
return r.filesysdep.ReadFile(r.textPath(packageArn, documentVersion))
}
// WriteManifestHash will put the manifest data for a given package name and package version into the cache
func (r *localRepository) WriteManifestHash(packageArn string, documentVersion string, content []byte) error {
err := fileutil.MakeDirs(r.manifestCachePath)
if err != nil {
return err
}
return r.filesysdep.WriteFile(r.textPath(packageArn, documentVersion), string(content))
}
// hasInventoryData determines if a package should be reported to inventory by the repository
// if false, it is assumed that the package used an installer type that is already collected by inventory
func hasInventoryData(manifest *PackageManifest) bool {
return manifest != nil && (manifest.Name != "" || manifest.AppName != "" || manifest.AppPublisher != "" || manifest.AppType != "" || manifest.AppReferenceURL != "")
}
// createApplicationData creates an ApplicationData item from a package manifest
func createApplicationData(manifest *PackageManifest, packageState *PackageInstallState) model.ApplicationData {
var compType model.ComponentType
if manifest.AppPublisher == "" || strings.HasPrefix(strings.ToLower(manifest.AppPublisher), "amazon") {
compType = model.AWSComponent
}
appName := manifest.Name
if manifest.AppName != "" {
appName = manifest.AppName
}
return model.ApplicationData{
Name: appName,
Publisher: manifest.AppPublisher,
Version: manifest.Version,
InstalledTime: packageState.Time.Format(time.RFC3339),
ApplicationType: manifest.AppType,
Architecture: model.FormatArchitecture(manifest.Architecture),
URL: manifest.AppReferenceURL,
CompType: compType,
}
}
// getPackageRoot is a helper function that given a package's directory name returns the path to the folder containing all versions of a package
func (repo *localRepository) getPackageRootByDirectoryName(directoryName string) string {
return filepath.Join(repo.repoRoot, directoryName)
}
// getPackageRoot is a helper function that given a packageArn returns the path to the folder containing all versions of a package
func (repo *localRepository) getPackageRoot(packageArn string) string {
return repo.getPackageRootByDirectoryName(normalizeDirectory(packageArn))
}
// getLockPath is a helper function that builds the path to the install state file
func (repo *localRepository) getLockPath(packageArn string) string {
return filepath.Join(repo.lockRoot, normalizeDirectory(packageArn)+".lockfile")
}
// getInstallStatePath is a helper function that given a packagearn builds the path to the install state file
func (repo *localRepository) getInstallStatePath(packageArn string) string {
return filepath.Join(repo.getPackageRoot(packageArn), "installstate")
}
// getInstallStatePath is a helper function that given a package directory name builds the path to the install state file
func (repo *localRepository) getInstallStatePathByDirectoryName(directoryName string) string {
return filepath.Join(repo.getPackageRootByDirectoryName(directoryName), "installstate")
}
// getPackageVersionPath is a helper function that builds a path to the directory containing the given version of a package
func (repo *localRepository) getPackageVersionPath(tracer trace.Tracer, packageArn string, version string) string {
return filepath.Join(repo.getPackageRoot(packageArn), normalizeDirectory(version))
}
// getManifestPath is a helper function that builds the path to the manifest file for a given version of a package
func (repo *localRepository) getManifestPath(tracer trace.Tracer, packageArn string, version string, manifestName string) string {
return filepath.Join(repo.getPackageVersionPath(tracer, packageArn, version), fmt.Sprintf("%v.json", manifestName))
}
func (repo *localRepository) getTracesPath(packageArn string) string {
return filepath.Join(repo.getPackageRoot(packageArn), "traces")
}
// loadInstallState loads the existing installstate file or returns an appropriate default state
func (repo *localRepository) loadInstallState(filesysdep FileSysDep, tracer trace.Tracer, packageArn string) *PackageInstallState {
var filePath = repo.getInstallStatePath(packageArn)
return repo.parseInstallState(tracer, filesysdep, filePath, packageArn)
}
// loadInstallState loads the existing installstate file given a package folder name or returns an appropriate default state
func (repo *localRepository) loadInstallStateByDirectoryName(filesysdep FileSysDep, tracer trace.Tracer, packageDirectoryName string) *PackageInstallState {
var filePath = repo.getInstallStatePathByDirectoryName(packageDirectoryName)
return repo.parseInstallState(tracer, filesysdep, filePath, "")
}
// parseInstallState parses the installState file
func (repo *localRepository) parseInstallState(tracer trace.Tracer, filesysdep FileSysDep, filePath string, packageArn string) *PackageInstallState {
packageState := PackageInstallState{Name: packageArn, State: None}
var fileContent []byte
var err error
if !filesysdep.Exists(filePath) {
if dirs, err := filesysdep.GetDirectoryNames(repo.getPackageRoot(packageArn)); err == nil && len(dirs) > 0 {
// For pre-repository packages, this will be the case, they should be updated and validated
return &PackageInstallState{Name: packageArn, Version: dirs[len(dirs)-1], State: Unknown}
}
return &PackageInstallState{Name: packageArn, State: None}
}
if fileContent, err = filesysdep.ReadFile(filePath); err != nil {
return &PackageInstallState{Name: packageArn, State: Unknown}
}
if err = jsonutil.Unmarshal(string(fileContent[:]), &packageState); err != nil {
tracer.CurrentTrace().AppendErrorf("InstallState file for package %v is invalid: %v", packageArn, err)
return &PackageInstallState{Name: packageArn, State: Unknown}
}
return &packageState
}
// openPackageManifest returns the valid manifest or validation error for a given package version
func (repo *localRepository) openPackageManifest(tracer trace.Tracer, filesysdep FileSysDep, packageArn string, version string) (manifest *PackageManifest, err error) {
trace := tracer.BeginSection("Validate Package")
manifestPath := repo.getManifestPath(tracer, packageArn, version, "manifest")
if filesysdep.Exists(manifestPath) {
return parsePackageManifest(tracer, filesysdep, manifestPath, packageArn, version)
}
trace.End()
return &PackageManifest{}, nil
}
func (repo *localRepository) LoadTraces(tracer trace.Tracer, packageArn string) error {
tracesPath := repo.getTracesPath(packageArn)
if !repo.filesysdep.Exists(tracesPath) {
return nil
}
serialized, err := repo.filesysdep.ReadFile(tracesPath)
_ = repo.filesysdep.RemoveAll(tracesPath) // always remove the file, even if it is corrupted
if err != nil {
return err
}
var traces []*trace.Trace
if err = json.Unmarshal([]byte(serialized), &traces); err != nil {
return err
}
tracer.PrependTraces(traces)
return nil
}
func (repo *localRepository) PersistTraces(tracer trace.Tracer, packageArn string) error {
serialized, err := json.Marshal(tracer.Traces())
if err != nil {
return err
}
return repo.filesysdep.WriteFile(repo.getTracesPath(packageArn), string(serialized))
}
// parsePackageManifest parses the manifest to ensure it is valid.
func parsePackageManifest(tracer trace.Tracer, filesysdep FileSysDep, filePath string, packageArn string, version string) (parsedManifest *PackageManifest, err error) {
// load specified file from file system
trace := tracer.BeginSection("Parse Package Manifest")
var result = []byte{}
if result, err = filesysdep.ReadFile(filePath); err != nil {
trace.WithError(err).End()
return nil, err
}
// parse package's JSON configuration file
if err = json.Unmarshal(result, &parsedManifest); err != nil {
trace.WithError(err).End()
return nil, err
}
// ensure manifest conforms to defined schema
if err = validatePackageManifest(parsedManifest, packageArn, version); err != nil {
trace.WithError(err).End()
return parsedManifest, err
}
trace.End()
return parsedManifest, nil
}
// validatePackageManifest ensures all the fields are provided.
func validatePackageManifest(parsedManifest *PackageManifest, packageArn string, version string) error {
// ensure non-empty and properly formatted required fields
if parsedManifest.Name == "" {
return fmt.Errorf("empty package name")
} else {
manifestName := parsedManifest.Name
if !strings.EqualFold(manifestName, packageArn) && !strings.HasSuffix(packageArn, manifestName) {
return fmt.Errorf("manifest name (%v) does not match expected package name (%v)", manifestName, packageArn)
}
}
if parsedManifest.Version == "" {
return fmt.Errorf("empty package version")
} else {
manifestVersion := parsedManifest.Version
if !strings.EqualFold(manifestVersion, version) {
return fmt.Errorf("manifest version (%v) does not match expected package version (%v)", manifestVersion, version)
}
}
return nil
}