/
deployer.go
750 lines (674 loc) · 25.1 KB
/
deployer.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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
// Copyright 2020 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package deployer
import (
"archive/zip"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/juju/charm/v12"
charmresource "github.com/juju/charm/v12/resource"
jujuclock "github.com/juju/clock"
"github.com/juju/cmd/v3"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/loggo"
"github.com/juju/juju/api/client/application"
commoncharm "github.com/juju/juju/api/common/charm"
"github.com/juju/juju/cmd/juju/application/store"
"github.com/juju/juju/cmd/juju/application/utils"
"github.com/juju/juju/cmd/juju/common"
"github.com/juju/juju/cmd/modelcmd"
corebase "github.com/juju/juju/core/base"
corecharm "github.com/juju/juju/core/charm"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/devices"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/model"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/storage"
)
var logger = loggo.GetLogger("juju.cmd.juju.application.deployer")
// DeployerKind is an interface that provides CreateDeployer function to
// attempt creation of the related deployer.
type DeployerKind interface {
CreateDeployer(d factory) (Deployer, error)
}
// localBundleDeployerKind represents a local bundle deployment
type localBundleDeployerKind struct {
DataSource charm.BundleDataSource
}
// localPreDeployerKind represents a local pre-deployed charm deployment
type localPreDeployerKind struct {
userCharmURL *charm.URL
}
// localCharmDeployerKind represents a local charm deployment
type localCharmDeployerKind struct {
base corebase.Base
imageStream string
ch charm.Charm
curl *charm.URL
}
// repositoryBundleDeployerKind represents a repository bundle deployment
type repositoryBundleDeployerKind struct {
bundleURL *charm.URL
bundleOrigin commoncharm.Origin
resolver Resolver
}
// repositoryCharmDeployerKind struct represents a repository charm deployment
type repositoryCharmDeployerKind struct {
deployCharm deployCharm
charmURL *charm.URL
}
// NewDeployerFactory returns a factory setup with the API and
// function dependencies required by every deployer.
func NewDeployerFactory(dep DeployerDependencies) DeployerFactory {
d := &factory{
clock: jujuclock.WallClock,
model: dep.Model,
fileSystem: dep.FileSystem,
charmReader: dep.CharmReader,
newConsumeDetailsAPI: dep.NewConsumeDetailsAPI,
}
if dep.DeployResources == nil {
d.deployResources = DeployResources
}
return d
}
// GetDeployer returns the correct deployer to use based on the cfg provided.
// A ModelConfigGetter needed to find the deployer.
func (d *factory) GetDeployer(cfg DeployerConfig, getter ModelConfigGetter, resolver Resolver) (Deployer, error) {
// Determine the type of deploy we have
var dk DeployerKind
// Set the factory config
d.setConfig(cfg)
// Check the path and try to catch problems (e.g. ambiguity) and fail early
if fileStatErr := d.checkPath(); fileStatErr != nil {
return nil, errors.Trace(fileStatErr)
}
if charm.IsValidLocalCharmOrBundlePath(d.charmOrBundle) || isLocalSchema(d.charmOrBundle) {
// Local charm or bundle or a pre-deployed local charm
// Go for local bundle
var localBundleErr error
if dk, localBundleErr = d.localBundleDeployer(); localBundleErr != nil {
return nil, errors.Trace(localBundleErr)
}
// Go for local charm (if it's not set by the localBundleDeployer above)
if dk == nil {
var localCharmErr error
if dk, localCharmErr = d.localCharmDeployer(getter); localCharmErr != nil {
return nil, errors.Trace(localCharmErr)
}
}
// Go for local pre-deployed charm (if it's not set by the localCharmDeployer above)
if dk == nil {
var localPreDeployedCharmErr error
if dk, localPreDeployedCharmErr = d.localPreDeployedCharmDeployer(); localPreDeployedCharmErr != nil {
return nil, errors.Trace(localPreDeployedCharmErr)
}
}
} else {
// Repository charm or bundle
userCharmURL, resolveCharmErr := resolveCharmURL(d.charmOrBundle, d.defaultCharmSchema)
if resolveCharmErr != nil {
return nil, errors.Trace(resolveCharmErr)
}
charmHubSchemaCheck := charm.CharmHub.Matches(userCharmURL.Schema)
// Check revision
revision, revErr := d.checkHandleRevision(userCharmURL, charmHubSchemaCheck)
if revErr != nil {
return nil, errors.Trace(revErr)
}
// Make the origin
platform := utils.MakePlatform(d.constraints, d.base, d.modelConstraints)
origin, err := utils.MakeOrigin(charm.CharmHub, revision, d.channel, platform)
if err != nil {
return nil, errors.Trace(err)
}
// Go for repository bundle
var bundleErr error
if dk, bundleErr = d.repoBundleDeployer(userCharmURL, origin, resolver, charmHubSchemaCheck); bundleErr != nil && !errors.Is(bundleErr, errors.NotValid) {
// If the error is NotValid, then the URL is resolved alright, but not to a bundle, so no need to raise
return nil, errors.Trace(bundleErr)
}
// Go for repository charm (if it's not set by the repoBundleDeployer above)
if dk == nil {
var charmErr error
dk, charmErr = d.repoCharmDeployer(userCharmURL, origin, charmHubSchemaCheck)
if charmErr != nil {
return nil, charmErr
}
}
}
return dk.CreateDeployer(*d)
}
func (d *factory) repoCharmDeployer(userCharmURL *charm.URL, origin commoncharm.Origin, charmHubSchemaCheck bool) (DeployerKind, error) {
// Check for when revision is set without a channel for future upgrades
if d.revision != -1 && charmHubSchemaCheck && d.channel.Empty() {
return nil, errors.Errorf("specifying a revision requires a channel for future upgrades. Please use --channel")
}
deployCharm := d.newDeployCharm()
deployCharm.id = application.CharmID{
Origin: origin,
}
return &repositoryCharmDeployerKind{deployCharm, userCharmURL}, nil
}
func (d *factory) repoBundleDeployer(userCharmURL *charm.URL, origin commoncharm.Origin, resolver Resolver, charmHubSchemaCheck bool) (DeployerKind, error) {
// TODO (cderici): check the validity of the comment below
// Resolve the bundle URL using the channel supplied via the channel
// supplied. All charms within this bundle unless pinned via a channel are
// NOT expected to be in the same channel as the bundle channel.
// The pinning of a bundle does not flow down to charms as well. Each charm
// has it's own channel supplied via a bundle, if no is supplied then the
// channel is worked out via the resolving what is available.
// See: LP:1677404 and LP:1832873
bundleURL, bundleOrigin, bundleResolveErr := resolver.ResolveBundleURL(userCharmURL, origin)
if charm.IsUnsupportedSeriesError(errors.Cause(bundleResolveErr)) {
return nil, errors.Errorf("%v. Use --force to deploy the charm anyway.", bundleResolveErr)
}
if bundleResolveErr != nil {
return nil, errors.Trace(bundleResolveErr)
} else {
if d.revision != -1 && charmHubSchemaCheck {
if !d.channel.Empty() {
return nil, errors.Errorf("revision and channel are mutually exclusive when deploying a bundle. Please choose one.")
}
}
if err := d.validateBundleFlags(); err != nil {
return nil, errors.Trace(err)
}
// Set the deployer kind to repositoryBundleDeployerKind
return &repositoryBundleDeployerKind{bundleURL, bundleOrigin, resolver}, nil
}
}
func (d *factory) localBundleDeployer() (DeployerKind, error) {
if ds, localBundleDataErr := charm.LocalBundleDataSource(d.charmOrBundle); localBundleDataErr == nil {
// Set the deployer kind to localBundleDeployerKind
return &localBundleDeployerKind{DataSource: ds}, nil
} else if !errors.Is(localBundleDataErr, errors.NotFound) {
// Only raise if it's not a NotFound.
// Otherwise, no need to raise, it's not a bundle,
// continue with trying for local charm.
return nil, errors.Annotatef(localBundleDataErr, "cannot deploy bundle")
} else {
return nil, nil
}
}
func (d *factory) localCharmDeployer(getter ModelConfigGetter) (DeployerKind, error) {
// Determine base
charmOrBundle := d.charmOrBundle
if isLocalSchema(charmOrBundle) {
charmOrBundle = charmOrBundle[6:]
}
base, imageStream, baseErr := d.determineBaseForLocalCharm(charmOrBundle, getter)
if baseErr != nil {
return nil, errors.Trace(baseErr)
}
// Charm may have been supplied via a path reference.
ch, curl, err := corecharm.NewCharmAtPathForceBase(charmOrBundle, base, d.force)
// We check for several types of known error which indicate
// that the supplied reference was indeed a path but there was
// an issue reading the charm located there.
if errors.Is(err, corecharm.MissingBaseError) {
return nil, err
} else if corecharm.IsUnsupportedBaseError(err) {
return nil, errors.Trace(err)
} else if errors.Cause(err) == zip.ErrFormat {
return nil, errors.Errorf("invalid charm or bundle provided at %q", charmOrBundle)
} else if errors.Is(err, errors.NotFound) {
return nil, errors.Wrap(err, errors.NotFoundf("charm or bundle at %q", charmOrBundle))
} else if errors.Is(err, os.ErrNotExist) {
logger.Debugf("cannot interpret as local charm: %v", err)
return nil, nil
} else if err != nil {
// If we get a "not exists" error then we attempt to interpret
// the supplied charm reference as a URL elsewhere, otherwise
// we return the error.
return nil, errors.Annotatef(err, "attempting to deploy %q", charmOrBundle)
}
return &localCharmDeployerKind{base, imageStream, ch, curl}, nil
}
func (d *factory) localPreDeployedCharmDeployer() (DeployerKind, error) {
// If the charm's schema is local, we should definitively attempt
// to deploy a charm that's already deployed in the
// environment.
userCharmURL, resolveCharmErr := resolveCharmURL(d.charmOrBundle, d.defaultCharmSchema)
if resolveCharmErr != nil {
return nil, errors.Trace(resolveCharmErr)
}
if !charm.Local.Matches(userCharmURL.Schema) {
return nil, errors.Errorf("cannot interpret as a redeployment of a local charm from the controller")
}
return &localPreDeployerKind{userCharmURL: userCharmURL}, nil
}
func (d *factory) determineBaseForLocalCharm(charmOrBundle string, getter ModelConfigGetter) (corebase.Base, string, error) {
// NOTE: Reading the charm here is only meant to aid in inferring the
// correct base. If this fails, we simply return with default values
// and trust the caller to handle this failure properly (the charm is
// read again later).
// TODO: A proper refactoring is required for a proper fix
var (
imageStream string
selectedBase corebase.Base
)
ch, err := d.charmReader.ReadCharm(charmOrBundle)
if err != nil {
return corebase.Base{}, "", nil
}
modelCfg, err := getModelConfig(getter)
if err != nil {
return corebase.Base{}, "", errors.Trace(err)
}
imageStream = modelCfg.ImageStream()
workloadBases, err := SupportedJujuBases(d.clock.Now(), d.base, imageStream)
if err != nil {
return corebase.Base{}, "", errors.Trace(err)
}
supportedBases, err := corecharm.ComputedBases(ch)
if err != nil {
return corebase.Base{}, "", errors.Trace(err)
}
baseSelector, err := corecharm.ConfigureBaseSelector(corecharm.SelectorConfig{
Config: modelCfg,
Force: d.force,
Logger: logger,
RequestedBase: d.base,
SupportedCharmBases: supportedBases,
WorkloadBases: workloadBases,
UsingImageID: d.constraints.HasImageID() || d.modelConstraints.HasImageID(),
})
if err != nil {
return corebase.Base{}, "", errors.Trace(err)
}
selectedBase, err = baseSelector.CharmBase()
if err = charmValidationError(ch.Meta().Name, errors.Trace(err)); err != nil {
return corebase.Base{}, "", errors.Trace(err)
}
return selectedBase, imageStream, nil
}
func (d *factory) checkHandleRevision(userCharmURL *charm.URL, charmHubSchemaCheck bool) (int, error) {
// To deploy by revision, the revision number must be in the origin for a charmhub bundle
if userCharmURL.Revision != -1 && charmHubSchemaCheck {
return -1, errors.Errorf("cannot specify revision in a charm or bundle name. Please use --revision.")
}
if d.revision != -1 {
return d.revision, nil
}
return userCharmURL.Revision, nil
}
func (d *factory) checkPath() error {
_, fileStatErr := d.fileSystem.Stat(d.charmOrBundle)
// Check for path ambiguity where we don't have a valid local path,
// but such a path does exist
if fileStatErr == nil && !charm.IsValidLocalCharmOrBundlePath(d.charmOrBundle) {
return errors.Errorf(""+
"The charm or bundle %q is ambiguous.\n"+
"To deploy a local charm or bundle, run `juju deploy ./%[1]s`.\n"+
"To deploy a charm or bundle from CharmHub, run `juju deploy ch:%[1]s`.",
d.charmOrBundle,
)
}
// Check in case we do have a valid path, but it doesn't exist
if fileStatErr != nil && charm.IsValidLocalCharmOrBundlePath(d.charmOrBundle) && os.IsNotExist(errors.Cause(fileStatErr)) {
return errors.Errorf("no charm was found at %q", d.charmOrBundle)
}
return nil
}
func (d *factory) setConfig(cfg DeployerConfig) {
d.placementSpec = cfg.PlacementSpec
d.placement = cfg.Placement
d.numUnits = cfg.NumUnits
d.attachStorage = cfg.AttachStorage
d.charmOrBundle = cfg.CharmOrBundle
d.defaultCharmSchema = cfg.DefaultCharmSchema
d.bundleOverlayFile = cfg.BundleOverlayFile
d.channel = cfg.Channel
d.base = cfg.Base
d.force = cfg.Force
d.dryRun = cfg.DryRun
d.applicationName = cfg.ApplicationName
d.configOptions = cfg.ConfigOptions
d.constraints = cfg.Constraints
d.modelConstraints = cfg.ModelConstraints
d.storage = cfg.Storage
d.bundleStorage = cfg.BundleStorage
d.devices = cfg.Devices
d.bundleDevices = cfg.BundleDevices
d.resources = cfg.Resources
d.revision = cfg.Revision
d.bindings = cfg.Bindings
d.useExisting = cfg.UseExisting
d.bundleMachines = cfg.BundleMachines
d.trust = cfg.Trust
d.flagSet = cfg.FlagSet
}
// DeployerDependencies are required for any deployer to be run.
type DeployerDependencies struct {
DeployResources DeployResourcesFunc
Model ModelCommand
FileSystem modelcmd.Filesystem
CharmReader CharmReader
NewConsumeDetailsAPI func(url *charm.OfferURL) (ConsumeDetails, error)
DeployKind DeployerFactory
}
// DeployerConfig is the data required to choose a deployer and then run
// PrepareAndDeploy.
// TODO (hml) 2020-08-14
// Is there a better structure for this config?
type DeployerConfig struct {
Model ModelCommand
ApplicationName string
AttachStorage []string
Bindings map[string]string
BindToSpaces string
BundleDevices map[string]map[string]devices.Constraints
BundleMachines map[string]string
BundleOverlayFile []string
BundleStorage map[string]map[string]storage.Constraints
Channel charm.Channel
CharmOrBundle string
DefaultCharmSchema charm.Schema
ConfigOptions common.ConfigFlag
ConstraintsStr string
Constraints constraints.Value
ModelConstraints constraints.Value
Devices map[string]devices.Constraints
DeployResources DeployResourcesFunc
DryRun bool
FlagSet *gnuflag.FlagSet
Force bool
NewConsumeDetailsAPI func(url *charm.OfferURL) (ConsumeDetails, error)
NumUnits int
PlacementSpec string
Placement []*instance.Placement
Resources map[string]string
Revision int
Base corebase.Base
Storage map[string]storage.Constraints
Trust bool
UseExisting bool
}
type factory struct {
// DeployerDependencies
model ModelCommand
deployResources DeployResourcesFunc
newConsumeDetailsAPI func(url *charm.OfferURL) (ConsumeDetails, error)
fileSystem modelcmd.Filesystem
charmReader CharmReader
// DeployerConfig
defaultCharmSchema charm.Schema
placementSpec string
placement []*instance.Placement
numUnits int
attachStorage []string
charmOrBundle string
bundleOverlayFile []string
channel charm.Channel
revision int
base corebase.Base
force bool
dryRun bool
applicationName string
configOptions common.ConfigFlag
constraints constraints.Value
modelConstraints constraints.Value
storage map[string]storage.Constraints
bundleStorage map[string]map[string]storage.Constraints
devices map[string]devices.Constraints
bundleDevices map[string]map[string]devices.Constraints
resources map[string]string
bindings map[string]string
useExisting bool
bundleMachines map[string]string
trust bool
flagSet *gnuflag.FlagSet
// Private
clock jujuclock.Clock
}
// newDeployCharm returns the config needed to eventually call
// deployCharm.deploy. This is used by all types of charms to
// be deployed
func (d *factory) newDeployCharm() deployCharm {
return deployCharm{
applicationName: d.applicationName,
attachStorage: d.attachStorage,
bindings: d.bindings,
configOptions: &d.configOptions,
constraints: d.constraints,
dryRun: d.dryRun,
modelConstraints: d.modelConstraints,
devices: d.devices,
deployResources: d.deployResources,
flagSet: d.flagSet,
force: d.force,
model: d.model,
numUnits: d.numUnits,
placement: d.placement,
placementSpec: d.placementSpec,
resources: d.resources,
baseFlag: d.base,
storage: d.storage,
trust: d.trust,
validateCharmBaseWithName: d.validateCharmBaseWithName,
validateResourcesNeededForLocalDeploy: d.validateResourcesNeededForLocalDeploy,
}
}
func (dt *localBundleDeployerKind) CreateDeployer(d factory) (Deployer, error) {
if err := d.validateBundleFlags(); err != nil {
return nil, errors.Trace(err)
}
platform := utils.MakePlatform(d.constraints, d.base, d.modelConstraints)
db := d.newDeployBundle(d.defaultCharmSchema, dt.DataSource)
var base corebase.Base
var err error
if platform.Channel != "" {
base, err = corebase.ParseBase(platform.OS, platform.Channel)
if err != nil {
return nil, errors.Trace(err)
}
}
db.origin = commoncharm.Origin{
Source: commoncharm.OriginLocal,
Architecture: platform.Architecture,
Base: base,
}
return &localBundle{deployBundle: db}, nil
}
// newDeployBundle returns the config needed to eventually call
// deployBundle.deploy. This is used by all types of bundles to
// be deployed
func (d *factory) newDeployBundle(_ charm.Schema, ds charm.BundleDataSource) deployBundle {
return deployBundle{
model: d.model,
dryRun: d.dryRun,
force: d.force,
trust: d.trust,
bundleDataSource: ds,
newConsumeDetailsAPI: d.newConsumeDetailsAPI,
deployResources: d.deployResources,
useExistingMachines: d.useExisting,
bundleMachines: d.bundleMachines,
bundleStorage: d.bundleStorage,
bundleDevices: d.bundleDevices,
bundleOverlayFile: d.bundleOverlayFile,
bundleDir: d.charmOrBundle,
modelConstraints: d.modelConstraints,
charmReader: d.charmReader,
defaultCharmSchema: d.defaultCharmSchema,
}
}
func (dk *localPreDeployerKind) CreateDeployer(d factory) (Deployer, error) {
return &predeployedLocalCharm{
deployCharm: d.newDeployCharm(),
userCharmURL: dk.userCharmURL,
}, nil
}
func (dk *localCharmDeployerKind) CreateDeployer(d factory) (Deployer, error) {
// Avoid deploying charm if the charm base is not correct for the
// available image streams.
var err error
if err = d.validateCharmBaseWithName(dk.base, dk.curl.Name, dk.imageStream); err != nil {
return nil, errors.Trace(err)
}
if err := d.validateResourcesNeededForLocalDeploy(dk.ch.Meta()); err != nil {
return nil, errors.Trace(err)
}
return &localCharm{
deployCharm: d.newDeployCharm(),
curl: dk.curl,
base: dk.base,
ch: dk.ch,
}, err
}
func (dk *repositoryCharmDeployerKind) CreateDeployer(d factory) (Deployer, error) {
return &repositoryCharm{
deployCharm: dk.deployCharm,
userRequestedURL: dk.charmURL,
clock: d.clock,
uploadExistingPendingResources: UploadExistingPendingResources,
}, nil
}
func (dk *repositoryBundleDeployerKind) CreateDeployer(d factory) (Deployer, error) {
// Validated, prepare to Deploy
// TODO(bundles) - Ideally, we would like to expose a GetBundleDataSource method for the charmstore.
// As a short-term solution and given that we don't
// want to support (for now at least) multi-doc bundles
// from the charmstore we simply use the existing
// charmrepo.v4 API to read the base bundle and
// wrap it in a BundleDataSource for use by deployBundle.
dir, err := os.MkdirTemp("", dk.bundleURL.Name)
if err != nil {
return nil, errors.Trace(err)
}
bundle, err := dk.resolver.GetBundle(dk.bundleURL, dk.bundleOrigin, filepath.Join(dir, dk.bundleURL.Name))
if err != nil {
return nil, errors.Trace(err)
}
db := d.newDeployBundle(d.defaultCharmSchema, store.NewResolvedBundle(bundle))
db.bundleURL = dk.bundleURL
db.bundleOverlayFile = d.bundleOverlayFile
db.origin = dk.bundleOrigin
return &repositoryBundle{deployBundle: db}, nil
}
func resolveCharmURL(path string, defaultSchema charm.Schema) (*charm.URL, error) {
var err error
path, err = charm.EnsureSchema(path, defaultSchema)
if err != nil {
return nil, errors.Trace(err)
}
return charm.ParseURL(path)
}
func isLocalSchema(u string) bool {
raw, err := url.Parse(u)
if err != nil {
return false
}
switch charm.Schema(raw.Scheme) {
case charm.Local:
return true
}
return false
}
func appsRequiringTrust(appSpecList map[string]*charm.ApplicationSpec) []string {
var tl []string
for a, appSpec := range appSpecList {
if applicationRequiresTrust(appSpec) {
tl = append(tl, a)
}
}
// Since map iterations are random we should sort the list to ensure
// consistent output in any errors containing the returned list contents.
sort.Strings(tl)
return tl
}
var getModelConfig = func(api ModelConfigGetter) (*config.Config, error) {
// Separated into a variable for easy overrides
attrs, err := api.ModelGet()
if err != nil {
return nil, errors.Wrap(err, errors.New("cannot fetch model settings"))
}
return config.New(config.NoDefaults, attrs)
}
func (d *factory) validateCharmBase(base corebase.Base, imageStream string) error {
// TODO(sidecar): handle systems
if d.force {
return nil
}
// attempt to locate the charm base from the list of known juju bases
// that we currently support.
workloadBases, err := SupportedJujuBases(d.clock.Now(), base, imageStream)
if err != nil {
return errors.Trace(err)
}
for _, workloadBase := range workloadBases {
if workloadBase == base {
return nil
}
}
return errors.NotSupportedf("base: %s", base)
}
// validateCharmBaseWithName calls the validateCharmBase, but handles the
// error return value to check for NotSupported error and returns a custom error
// message if that's found.
func (d *factory) validateCharmBaseWithName(base corebase.Base, name string, imageStream string) error {
err := d.validateCharmBase(base, imageStream)
return charmValidationError(name, errors.Trace(err))
}
// charmValidationError consumes an error along with a charmSeries and name
// to help provide better feedback to the user when somethings gone wrong around
// validating a charm validation
func charmValidationError(name string, err error) error {
if errors.Is(err, errors.NotSupported) {
return errors.Errorf("%v is not available on the following %v", name, err)
}
return errors.Trace(err)
}
func (d *factory) validateResourcesNeededForLocalDeploy(charmMeta *charm.Meta) error {
modelType, err := d.model.ModelType()
if err != nil {
return errors.Trace(err)
}
// If the target model is IAAS, then we don't need to validate the resources
// for a given deploy.
if modelType == model.IAAS {
return nil
}
var missingImages []string
for resName, resMeta := range charmMeta.Resources {
if resMeta.Type == charmresource.TypeContainerImage {
if _, ok := d.resources[resName]; !ok {
missingImages = append(missingImages, resName)
}
}
}
if len(missingImages) > 0 {
return errors.Errorf("local charm missing OCI images for: %v", strings.Join(missingImages, ", "))
}
return nil
}
func (d *factory) validateBundleFlags() error {
if flags := utils.GetFlags(d.flagSet, CharmOnlyFlags()); len(flags) > 0 {
return errors.Errorf("options provided but not supported when deploying a bundle: %s", strings.Join(flags, ", "))
}
return nil
}
// CharmOnlyFlags and BundleOnlyFlags are used to validate flags based on
// whether we are deploying a charm or a bundle.
func CharmOnlyFlags() []string {
charmOnlyFlags := []string{
"bind", "config", "constraints", "n", "num-units",
"series", "base", "to", "resource", "attach-storage",
}
return charmOnlyFlags
}
// checkPodspec checks if the given charm is a podspec charm, and if so, prints
// a deprecation warning.
func checkPodspec(cm charm.CharmMeta, ctx *cmd.Context) bool {
isPodspec := corecharm.IsKubernetes(cm) && charm.MetaFormat(cm) == charm.FormatV1
if isPodspec {
ctx.Warningf("deploying podspec charm %q: podspec charms are deprecated. Support for them will be removed soon.", cm.Meta().Name)
}
return isPodspec
}