-
Notifications
You must be signed in to change notification settings - Fork 494
/
deploy_test.go
3198 lines (2820 loc) · 110 KB
/
deploy_test.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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package application
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"time"
"github.com/golang/mock/gomock"
"github.com/juju/charm/v9"
charmresource "github.com/juju/charm/v9/resource"
"github.com/juju/charmrepo/v7"
csparams "github.com/juju/charmrepo/v7/csclient/params"
"github.com/juju/cmd/v3"
"github.com/juju/cmd/v3/cmdtesting"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/loggo"
"github.com/juju/names/v4"
jujutesting "github.com/juju/testing"
jc "github.com/juju/testing/checkers"
"github.com/juju/utils/v3"
"github.com/juju/utils/v3/fs"
gc "gopkg.in/check.v1"
"gopkg.in/macaroon.v2"
"github.com/juju/juju/api"
unitassignerapi "github.com/juju/juju/api/agent/unitassigner"
"github.com/juju/juju/api/base"
"github.com/juju/juju/api/client/annotations"
"github.com/juju/juju/api/client/application"
apicharms "github.com/juju/juju/api/client/charms"
apiclient "github.com/juju/juju/api/client/client"
"github.com/juju/juju/api/client/modelconfig"
"github.com/juju/juju/api/client/resources"
commoncharm "github.com/juju/juju/api/common/charm"
apicommoncharms "github.com/juju/juju/api/common/charms"
apitesting "github.com/juju/juju/api/testing"
"github.com/juju/juju/cmd/juju/application/deployer"
"github.com/juju/juju/cmd/juju/application/mocks"
"github.com/juju/juju/cmd/juju/application/store"
apputils "github.com/juju/juju/cmd/juju/application/utils"
"github.com/juju/juju/cmd/juju/common"
"github.com/juju/juju/cmd/modelcmd"
"github.com/juju/juju/core/arch"
corecharm "github.com/juju/juju/core/charm"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/core/devices"
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/model"
jujuseries "github.com/juju/juju/core/series"
jjtesting "github.com/juju/juju/juju/testing"
"github.com/juju/juju/jujuclient"
"github.com/juju/juju/jujuclient/jujuclienttesting"
"github.com/juju/juju/rpc/params"
"github.com/juju/juju/state"
"github.com/juju/juju/storage"
"github.com/juju/juju/testcharms"
coretesting "github.com/juju/juju/testing"
"github.com/juju/juju/version"
)
var defaultLocalOrigin = commoncharm.Origin{
Source: commoncharm.OriginLocal,
Architecture: arch.DefaultArchitecture,
OS: "ubuntu",
Series: "jammy",
}
type DeploySuiteBase struct {
jjtesting.RepoSuite
coretesting.CmdBlockHelper
DeployResources deployer.DeployResourcesFunc
fakeAPI *fakeDeployAPI
}
// deployCommand returns a deploy command that stubs out the
// charm store and the controller deploy API.
func (s *DeploySuiteBase) deployCommand() *DeployCommand {
deploy := s.deployCommandForState()
deploy.NewDeployAPI = func() (deployer.DeployerAPI, error) {
return s.fakeAPI, nil
}
deploy.NewModelConfigAPI = func(api base.APICallCloser) ModelConfigGetter {
return s.fakeAPI
}
deploy.NewCharmsAPI = func(api base.APICallCloser) CharmsAPI {
return apicharms.NewClient(s.fakeAPI)
}
return deploy
}
// deployCommandForState returns a deploy command that stubs out the
// charm store but writes data to the juju database.
func (s *DeploySuiteBase) deployCommandForState() *DeployCommand {
deploy := newDeployCommand()
deploy.Steps = nil
deploy.DeployResources = s.DeployResources
deploy.NewCharmRepo = func() (*store.CharmStoreAdaptor, error) {
return s.fakeAPI.CharmStoreAdaptor, nil
}
deploy.NewResolver = func(charmsAPI store.CharmsAPI, charmRepoFn store.CharmStoreRepoFunc, downloadFn store.DownloadBundleClientFunc) deployer.Resolver {
return s.fakeAPI
}
deploy.NewConsumeDetailsAPI = func(url *charm.OfferURL) (deployer.ConsumeDetails, error) {
return s.fakeAPI, nil
}
return deploy
}
func (s *DeploySuiteBase) runDeploy(c *gc.C, args ...string) error {
_, _, err := s.runDeployWithOutput(c, args...)
return err
}
func (s *DeploySuiteBase) runDeployForState(c *gc.C, args ...string) error {
deploy := newDeployCommand()
deploy.Steps = nil
deploy.DeployResources = s.DeployResources
deploy.NewCharmRepo = func() (*store.CharmStoreAdaptor, error) {
return s.fakeAPI.CharmStoreAdaptor, nil
}
deploy.NewResolver = func(charmsAPI store.CharmsAPI, charmRepoFn store.CharmStoreRepoFunc, downloadFn store.DownloadBundleClientFunc) deployer.Resolver {
return s.fakeAPI
}
deploy.NewConsumeDetailsAPI = func(url *charm.OfferURL) (deployer.ConsumeDetails, error) {
return s.fakeAPI, nil
}
_, err := cmdtesting.RunCommand(c, modelcmd.Wrap(deploy), args...)
return err
}
func (s *DeploySuiteBase) runDeployWithOutput(c *gc.C, args ...string) (string, string, error) {
deployCmd := newWrappedDeployCommandForTest(s.fakeAPI)
ctx, err := cmdtesting.RunCommand(c, deployCmd, args...)
return strings.Trim(cmdtesting.Stdout(ctx), "\n"),
strings.Trim(cmdtesting.Stderr(ctx), "\n"),
err
}
func (s *DeploySuiteBase) SetUpTest(c *gc.C) {
if runtime.GOOS == "darwin" {
c.Skip("Mongo failures on macOS")
}
s.RepoSuite.SetUpTest(c)
// TODO: remove this patch once we removed all the old series from tests in current package.
s.PatchValue(&deployer.SupportedJujuSeries,
func(time.Time, string, string) (set.Strings, error) {
return set.NewStrings(
"centos7", "centos8", "centos9", "genericlinux", "kubernetes", "opensuseleap",
"jammy", "focal", "bionic", "xenial",
), nil
},
)
s.CmdBlockHelper = coretesting.NewCmdBlockHelper(s.APIState)
c.Assert(s.CmdBlockHelper, gc.NotNil)
s.AddCleanup(func(*gc.C) { s.CmdBlockHelper.Close() })
s.DeployResources = func(applicationID string,
chID resources.CharmID,
csMac *macaroon.Macaroon,
filesAndRevisions map[string]string,
resources map[string]charmresource.Meta,
conn base.APICallCloser,
filesystem modelcmd.Filesystem,
) (ids map[string]string, err error) {
return deployResources(s.State, applicationID, resources)
}
cfgAttrs := map[string]interface{}{
"name": "name",
"uuid": coretesting.ModelTag.Id(),
"type": "foo",
}
s.fakeAPI = vanillaFakeModelAPI(cfgAttrs)
s.fakeAPI.CharmStoreAdaptor = &store.CharmStoreAdaptor{
CharmrepoForDeploy: &fakeCharmStoreAPI{
fakeDeployAPI: s.fakeAPI,
},
MacaroonGetter: &noopMacaroonGetter{},
}
s.fakeAPI.deployerFactoryFunc = deployer.NewDeployerFactory
}
// deployResources does what would be expected when a charm with
// resources is deployed (ie write the pending and actual resources
// to state), but it does not upload or otherwise use the charmstore
// (fake data from the store is used).
func deployResources(
st *state.State,
applicationID string,
resources map[string]charmresource.Meta,
) (ids map[string]string, err error) {
if len(resources) == 0 {
return nil, nil
}
stRes := st.Resources()
ids = make(map[string]string)
for _, res := range resources {
content := res.Name + " content"
origin := charmresource.OriginStore
user := ""
if res.Name == "upload-resource" {
content = "some-data"
origin = charmresource.OriginUpload
user = "admin"
}
chRes := charmresource.Resource{
Meta: res,
Origin: origin,
Fingerprint: resourceHash(content),
Size: int64(len(content)),
}
pendingID, err := stRes.AddPendingResource(applicationID, user, chRes)
if err != nil {
return nil, err
}
ids[res.Name] = pendingID
if origin == charmresource.OriginUpload {
_, err := stRes.UpdatePendingResource(applicationID, pendingID, user, chRes, strings.NewReader(content))
if err != nil {
// We don't bother aggregating errors since a partial
// completion is disruptive and a retry of this endpoint
// is not expensive.
return nil, err
}
}
}
return ids, nil
}
type DeploySuite struct {
DeploySuiteBase
}
var _ = gc.Suite(&DeploySuite{})
// runDeploy executes the deploy command in order to deploy the given
// charm or bundle. The deployment stderr output and error are returned.
func runDeployWithOutput(c *gc.C, cmd cmd.Command, args ...string) (string, string, error) {
ctx, err := cmdtesting.RunCommand(c, cmd, args...)
return strings.Trim(cmdtesting.Stdout(ctx), "\n"),
strings.Trim(cmdtesting.Stderr(ctx), "\n"),
err
}
// runDeploy executes the deploy command in order to deploy the given
// charm or bundle. The deployment stderr output and error are returned.
func runDeploy(c *gc.C, args ...string) error {
_, _, err := runDeployWithOutput(c, NewDeployCommand(), args...)
return err
}
var initErrorTests = []struct {
args []string
err string
}{
{
args: nil,
err: `no charm or bundle specified`,
}, {
args: []string{"charm-name", "application-name", "hotdog"},
err: `unrecognized args: \["hotdog"\]`,
}, {
args: []string{"craziness", "burble-1"},
err: `invalid application name "burble-1", unexpected number\(s\) found after last hyphen`,
}, {
args: []string{"craziness", "Burble-1"},
err: `invalid application name "Burble-1", unexpected uppercase character`,
}, {
args: []string{"craziness", "bu£rble"},
err: `invalid application name "bu£rble", unexpected character £`,
}, {
args: []string{"craziness", "burble1", "-n", "0"},
err: `--num-units must be a positive integer`,
}, {
args: []string{"craziness", "burble1", "--to", "#:foo"},
err: `invalid --to parameter "#:foo"`,
}, {
args: []string{"charm", "--attach-storage", "foo/0", "-n", "2"},
err: `--attach-storage cannot be used with -n`,
}, {
args: []string{"bundle", "--map-machines", "foo"},
err: `error in --map-machines: expected "existing" or "<bundle-id>=<machine-id>", got "foo"`,
},
}
func (s *DeploySuite) TestInitErrors(c *gc.C) {
for i, t := range initErrorTests {
c.Logf("test %d", i)
deployCmd := newWrappedDeployCommandForTest(s.fakeAPI)
err := cmdtesting.InitCommand(deployCmd, t.args)
c.Check(err, gc.ErrorMatches, t.err)
}
}
func (s *DeploySuite) TestNoCharmOrBundle(c *gc.C) {
err := s.runDeploy(c, c.MkDir())
c.Check(err, jc.Satisfies, errors.IsNotFound)
c.Assert(err, gc.ErrorMatches, `charm or bundle at .*`)
}
func (s *DeploySuite) TestBlockDeploy(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, curl, "some-application-name", "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
// Block operation
s.BlockAllChanges(c, "TestBlockDeploy")
err := s.runDeployForState(c, charmDir.Path, "some-application-name", "--series", "jammy")
s.AssertBlocked(c, err, ".*TestBlockDeploy.*")
}
func (s *DeploySuite) TestInvalidPath(c *gc.C) {
err := s.runDeploy(c, "/home/nowhere")
c.Assert(err, gc.ErrorMatches, `cannot resolve charm or bundle "nowhere": charm or bundle not found`)
}
func (s *DeploySuite) TestInvalidFileFormat(c *gc.C) {
path := filepath.Join(c.MkDir(), "bundle.yaml")
err := ioutil.WriteFile(path, []byte(":"), 0600)
c.Assert(err, jc.ErrorIsNil)
err = s.runDeploy(c, path)
c.Assert(err, gc.ErrorMatches, `cannot deploy bundle: cannot unmarshal bundle contents:.* yaml:.*`)
}
func (s *DeploySuite) TestPathWithNoCharmOrBundle(c *gc.C) {
err := s.runDeploy(c, c.MkDir())
c.Check(err, jc.Satisfies, errors.IsNotFound)
c.Assert(err, gc.ErrorMatches, `charm or bundle at .*`)
}
func (s *DeploySuite) TestCharmDir(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, curl, "some-application-name", "bionic", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "multi-series", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPathRelativeDir(c *gc.C) {
dir := c.MkDir()
testcharms.RepoWithSeries("bionic").ClonedDirPath(dir, "multi-series")
wd, err := os.Getwd()
c.Assert(err, jc.ErrorIsNil)
defer func() { _ = os.Chdir(wd) }()
err = os.Chdir(dir)
c.Assert(err, jc.ErrorIsNil)
err = s.runDeploy(c, "multi-series")
c.Assert(err, gc.ErrorMatches, ""+
"The charm or bundle \"multi-series\" is ambiguous.\n"+
"To deploy a local charm or bundle, run `juju deploy ./multi-series`.\n"+
"To deploy a charm or bundle from CharmHub, run `juju deploy ch:multi-series`.")
}
func (s *DeploySuite) TestDeployFromPathOldCharm(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "dummy")
curl := charm.MustParseURL("local:focal/dummy-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "bionic", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--series", "focal", "--force")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "dummy", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPathOldCharmMissingSeries(c *gc.C) {
// Update the model default series to be unset.
updateAttrs := map[string]interface{}{"default-series": ""}
err := s.Model.UpdateModelConfig(updateAttrs, nil)
c.Assert(err, jc.ErrorIsNil)
path := testcharms.RepoWithSeries("bionic").ClonedDirPath(c.MkDir(), "dummy")
err = s.runDeploy(c, path)
c.Assert(err, gc.ErrorMatches, "series not specified and charm does not define any")
}
func (s *DeploySuite) TestDeployFromPathOldCharmMissingSeriesUseDefaultSeries(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "dummy")
curl := charm.MustParseURL(fmt.Sprintf("local:%s/dummy-1", version.DefaultSupportedLTS()))
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "focal", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path)
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "dummy", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPathDefaultSeries(c *gc.C) {
// multi-series/metadata.yaml provides "focal" as its default series
// and yet, here, the model defaults to the series "jammy". This test
// asserts that the model's default takes precedence.
updateAttrs := map[string]interface{}{"default-series": "jammy"}
err := s.Model.UpdateModelConfig(updateAttrs, nil)
c.Assert(err, jc.ErrorIsNil)
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "bionic", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err = s.runDeployForState(c, charmDir.Path)
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "multi-series", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPath(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "focal", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "multi-series", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPathUnsupportedSeriesHaveOverlap(c *gc.C) {
// Donot remove this because we want to test: series supported by the charm and series supported by Juju have overlap.
s.PatchValue(&deployer.SupportedJujuSeries,
func(time.Time, string, string) (set.Strings, error) {
return set.NewStrings(
"jammy", "focal",
), nil
},
)
path := testcharms.RepoWithSeries("bionic").ClonedDirPath(c.MkDir(), "multi-series")
err := s.runDeploy(c, path, "--series", "quantal")
c.Assert(err, gc.ErrorMatches, `series "quantal" is not supported, supported series are: focal,jammy`)
}
func (s *DeploySuite) TestDeployFromPathUnsupportedSeriesHaveNoOverlap(c *gc.C) {
// Donot remove this because we want to test: series supported by the charm and series supported by Juju have NO overlap.
s.PatchValue(&deployer.SupportedJujuSeries,
func(time.Time, string, string) (set.Strings, error) {
return set.NewStrings("kinetic"), nil
},
)
path := testcharms.RepoWithSeries("bionic").ClonedDirPath(c.MkDir(), "multi-series")
err := s.runDeploy(c, path, "--series", "quantal")
c.Assert(err, gc.ErrorMatches, `multi-series is not available on the following series: quantal`)
}
func (s *DeploySuite) TestDeployFromPathUnsupportedSeriesForce(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:quantal/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "focal", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
// TODO: remove this patch once we removed all the old series from tests in current package.
s.PatchValue(&deployer.SupportedJujuSeries,
func(time.Time, string, string) (set.Strings, error) {
return set.NewStrings(
"jammy", "focal", "bionic", "xenial", "quantal",
), nil
},
)
err := s.runDeployForState(c, charmDir.Path, "--series", "quantal", "--force")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "multi-series", curl, 1, 0)
}
func (s *DeploySuite) TestDeployFromPathUnsupportedLXDProfileForce(c *gc.C) {
charmDir := testcharms.RepoWithSeries("quantal").ClonedDir(c.MkDir(), "lxd-profile-fail")
curl := charm.MustParseURL("local:quantal/lxd-profile-fail-0")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "focal", charmDir.Meta(), charmDir.Metrics(), false, true, 1, nil, nil)
// TODO: remove this patch once we removed all the old series from tests in current package.
s.PatchValue(&deployer.SupportedJujuSeries,
func(time.Time, string, string) (set.Strings, error) {
return set.NewStrings(
"jammy", "focal", "bionic", "xenial", "quantal",
), nil
},
)
err := s.runDeployForState(c, charmDir.Path, "--series", "quantal", "--force")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "lxd-profile-fail", curl, 1, 0)
}
func (s *DeploySuite) TestUpgradeCharmDir(c *gc.C) {
// Add the charm, so the url will exist and a new revision will be
// picked in application Deploy.
dummyCharm := s.AddTestingCharmForSeries(c, "dummy", "bionic")
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "dummy")
deployURL := charm.MustParseURL("local:bionic/dummy-1")
withLocalCharmDeployable(s.fakeAPI, deployURL, charmDir, false)
withCharmDeployable(s.fakeAPI, deployURL, "bionic", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--series", "bionic")
c.Assert(err, jc.ErrorIsNil)
upgradedRev := dummyCharm.Revision() + 1
curl := dummyCharm.URL().WithRevision(upgradedRev)
s.AssertApplication(c, "dummy", curl, 1, 0)
// Check the charm dir was left untouched.
ch, err := charm.ReadCharmDir(charmDir.Path)
c.Assert(err, jc.ErrorIsNil)
c.Assert(ch.Revision(), gc.Equals, 1)
}
func (s *DeploySuite) TestCharmBundle(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
charmURL := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, charmURL, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, charmURL, "some-application-name", "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "some-application-name", "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
curl := charm.MustParseURL("local:jammy/multi-series-1")
s.AssertApplication(c, "some-application-name", curl, 1, 0)
}
func (s *DeploySuite) TestSubordinateCharm(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "logging")
curl := charm.MustParseURL("local:jammy/logging-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "logging", curl, 0, 0)
}
func (s *DeploySuite) combinedSettings(ch charm.Charm, inSettings charm.Settings) charm.Settings {
result := ch.Config().DefaultSettings()
for name, value := range inSettings {
result[name] = value
}
return result
}
func (s *DeploySuite) TestSingleConfigFile(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, curl, "dummy-application", "focal", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
path := setupConfigFile(c, c.MkDir())
err := s.runDeployForState(c, charmDir.Path, "dummy-application", "--config", path, "--series", "focal")
c.Assert(err, jc.ErrorIsNil)
app, err := s.State.Application("dummy-application")
c.Assert(err, jc.ErrorIsNil)
settings, err := app.CharmConfig(model.GenerationMaster)
c.Assert(err, jc.ErrorIsNil)
appCh, _, err := app.Charm()
c.Assert(err, jc.ErrorIsNil)
c.Assert(settings, gc.DeepEquals, s.combinedSettings(appCh, charm.Settings{
"skill-level": int64(9000),
"username": "admin001",
}))
}
func (s *DeploySuite) TestRelativeConfigPath(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "focal", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
// Putting a config file in home is okay as $HOME is set to a tempdir
setupConfigFile(c, utils.Home())
err := s.runDeployForState(c, charmDir.Path, "dummy-application", "--config", "~/testconfig.yaml")
c.Assert(err, jc.ErrorIsNil)
}
func (s *DeploySuite) TestConfigValues(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, curl, "dummy-name", "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
confPath := filepath.Join(c.MkDir(), "include.txt")
c.Assert(ioutil.WriteFile(confPath, []byte("lorem\nipsum"), os.ModePerm), jc.ErrorIsNil)
err := s.runDeployForState(c, charmDir.Path, "dummy-application", "--config", "skill-level=9000", "--config", "outlook=good", "--config", "title=@"+confPath, "--series", "bionic")
c.Assert(err, jc.ErrorIsNil)
app, err := s.State.Application("dummy-application")
c.Assert(err, jc.ErrorIsNil)
settings, err := app.CharmConfig(model.GenerationMaster)
c.Assert(err, jc.ErrorIsNil)
appCh, _, err := app.Charm()
c.Assert(err, jc.ErrorIsNil)
c.Assert(settings, gc.DeepEquals, s.combinedSettings(appCh, charm.Settings{
"outlook": "good",
"skill-level": int64(9000),
"username": "admin001",
"title": "lorem\nipsum",
}))
}
func (s *DeploySuite) TestConfigValuesWithFile(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
path := setupConfigFile(c, c.MkDir())
err := s.runDeployForState(c, charmDir.Path, "dummy-application", "--config", path, "--config", "outlook=good", "--config", "skill-level=8000", "--series", "bionic")
c.Assert(err, jc.ErrorIsNil)
app, err := s.State.Application("dummy-application")
c.Assert(err, jc.ErrorIsNil)
settings, err := app.CharmConfig(model.GenerationMaster)
c.Assert(err, jc.ErrorIsNil)
appCh, _, err := app.Charm()
c.Assert(err, jc.ErrorIsNil)
c.Assert(settings, gc.DeepEquals, s.combinedSettings(appCh, charm.Settings{
"outlook": "good",
"skill-level": int64(8000),
"username": "admin001",
}))
}
func (s *DeploySuite) TestSingleConfigMoreThanOneFile(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
curl := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "bionic", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "dummy-application", "--config", "one", "--config", "another", "--series", "jammy")
c.Assert(err, gc.ErrorMatches, "only a single config YAML file can be specified, got 2")
}
func (s *DeploySuite) TestConfigError(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
charmURL := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, charmURL, charmDir, false)
withAliasedCharmDeployable(s.fakeAPI, charmURL, "some-application-name", "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
path := setupConfigFile(c, c.MkDir())
err := s.runDeployForState(c, charmDir.Path, "other-application", "--config", path)
c.Assert(err, gc.ErrorMatches, `no settings found for "other-application"`)
_, err = s.State.Application("other-application")
c.Assert(err, jc.Satisfies, errors.IsNotFound)
}
func (s *DeploySuite) TestConstraints(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "multi-series")
charmURL := charm.MustParseURL("local:jammy/multi-series-1")
withLocalCharmDeployable(s.fakeAPI, charmURL, charmDir, false)
withCharmDeployable(s.fakeAPI, charmURL, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path, "--constraints", "mem=2G cores=2", "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
curl := charm.MustParseURL("local:jammy/multi-series-1")
app, _ := s.AssertApplication(c, "multi-series", curl, 1, 0)
cons, err := app.Constraints()
c.Assert(err, jc.ErrorIsNil)
c.Assert(cons, jc.DeepEquals, constraints.MustParse("mem=2G cores=2 arch=amd64"))
}
func (s *DeploySuite) TestResources(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "dummy")
curl := charm.MustParseURL("local:jammy/dummy-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
foopath := "/test/path/foo"
barpath := "/test/path/var"
res1 := fmt.Sprintf("foo=%s", foopath)
res2 := fmt.Sprintf("bar=%s", barpath)
d := DeployCommand{}
args := []string{charmDir.Path, "--resource", res1, "--resource", res2, "--series", "jammy"}
err := cmdtesting.InitCommand(modelcmd.Wrap(&d), args)
c.Assert(err, jc.ErrorIsNil)
c.Assert(d.Resources, gc.DeepEquals, map[string]string{
"foo": foopath,
"bar": barpath,
})
}
func (s *DeploySuite) TestLXDProfileLocalCharm(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "lxd-profile")
curl := charm.MustParseURL("local:jammy/lxd-profile-0")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path)
c.Assert(err, jc.ErrorIsNil)
s.AssertApplication(c, "lxd-profile", curl, 1, 0)
}
func (s *DeploySuite) TestLXDProfileLocalCharmFails(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "lxd-profile-fail")
curl := charm.MustParseURL("local:jammy/lxd-profile-fail-0")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployable(s.fakeAPI, curl, "jammy", charmDir.Meta(), charmDir.Metrics(), false, false, 1, nil, nil)
err := s.runDeployForState(c, charmDir.Path)
c.Assert(errors.Cause(err), gc.ErrorMatches, `invalid lxd-profile.yaml: contains device type "unix-disk"`)
}
func (s *DeploySuite) TestStorage(c *gc.C) {
charmDir := testcharms.RepoWithSeries("bionic").ClonedDir(c.MkDir(), "storage-block")
curl := charm.MustParseURL("local:jammy/storage-block-1")
withLocalCharmDeployable(s.fakeAPI, curl, charmDir, false)
withCharmDeployableWithStorage(
s.fakeAPI, curl, "storage-block", "jammy",
charmDir.Meta(),
charmDir.Metrics(),
false, false, 1, nil, nil,
map[string]storage.Constraints{
"data": {
Pool: "machinescoped",
Size: 1024,
Count: 1,
},
},
)
err := s.runDeployForState(c, charmDir.Path, "--storage", "data=machinescoped,1G", "--series", "jammy")
c.Assert(err, jc.ErrorIsNil)
app, _ := s.AssertApplication(c, "storage-block", curl, 1, 0)
cons, err := app.StorageConstraints()
c.Assert(err, jc.ErrorIsNil)
c.Assert(cons, jc.DeepEquals, map[string]state.StorageConstraints{
"data": {
Pool: "machinescoped",
Count: 1,
Size: 1024,
},
"allecto": {
Pool: "loop",
Count: 0,
Size: 1024,
},
})
}
func (s *DeploySuite) TestErrorDeployingBundlesRequiringTrust(c *gc.C) {
specs := []struct {
descr string
bundle string
expAppList []string
}{
{
descr: "bundle with a single app with the trust field set to true",
bundle: "aws-integrator-trust-single",
expAppList: []string{"aws-integrator"},
},
{
descr: "bundle with a multiple apps with the trust field set to true",
bundle: "aws-integrator-trust-multi",
expAppList: []string{"aws-integrator", "gcp-integrator"},
},
{
descr: "bundle with a single app with a 'trust: true' config option",
bundle: "aws-integrator-trust-conf-param",
expAppList: []string{"aws-integrator"},
},
}
for specIndex, spec := range specs {
c.Logf("[spec %d] %s", specIndex, spec.descr)
expErr := fmt.Sprintf(`Bundle cannot be deployed without trusting applications with your cloud credentials.
Please repeat the deploy command with the --trust argument if you consent to trust the following application(s):
- %s`, strings.Join(spec.expAppList, "\n - "))
bundlePath := testcharms.RepoWithSeries("bionic").ClonedBundleDirPath(c.MkDir(), spec.bundle)
err := s.runDeploy(c, bundlePath)
c.Assert(err, gc.Not(gc.IsNil))
c.Assert(err.Error(), gc.Equals, expErr)
}
}
func (s *DeploySuite) TestDeployBundleWithChannel(c *gc.C) {
withAllWatcher(s.fakeAPI)
// The second charm from the bundle does not require trust so no
// additional configuration should be injected
ubURL := charm.MustParseURL("cs:~jameinel/ubuntu-lite-7")
withCharmRepoResolvable(s.fakeAPI, ubURL, "jammy")
withCharmRepoResolvable(s.fakeAPI, ubURL, "")
withCharmDeployable(
s.fakeAPI, ubURL, "jammy",
&charm.Meta{Name: "ubuntu-lite", Series: []string{"jammy"}},
nil, false, false, 0, nil, nil,
)
s.fakeAPI.Call("AddUnits", application.AddUnitsParams{
ApplicationName: "ubuntu-lite",
NumUnits: 1,
}).Returns([]string{"ubuntu-lite/0"}, error(nil))
s.fakeAPI.Call("ListSpaces").Returns([]params.Space{{Name: "alpha", Id: "0"}}, error(nil))
deploy := s.deployCommand()
bundlePath := testcharms.RepoWithSeries("bionic").ClonedBundleDirPath(c.MkDir(), "basic")
_, err := cmdtesting.RunCommand(c, modelcmd.Wrap(deploy), bundlePath, "--channel", "edge")
c.Assert(err, jc.ErrorIsNil)
}
func (s *DeploySuite) TestDeployBundlesRequiringTrust(c *gc.C) {
withAllWatcher(s.fakeAPI)
inURL := charm.MustParseURL("cs:~containers/aws-integrator")
withCharmRepoResolvable(s.fakeAPI, inURL, "jammy")
withCharmRepoResolvable(s.fakeAPI, inURL, "")
// The aws-integrator charm requires trust and since the operator passes
// --trust we expect to see a "trust: true" config value in the yaml
// config passed to deploy.
//
// As withCharmDeployable does not support passing a "ConfigYAML"
// it's easier to just invoke it to set up all other calls and then
// explicitly Deploy here.
withCharmDeployable(
s.fakeAPI, inURL, "jammy",
&charm.Meta{Name: "aws-integrator", Series: []string{"jammy"}},
nil, false, false, 0, nil, nil,
)
origin := commoncharm.Origin{
Source: commoncharm.OriginCharmStore,
Architecture: arch.DefaultArchitecture,
Series: "jammy",
}
deployURL := *inURL
deployURL.Revision = 1
deployURL.Series = "jammy"
s.fakeAPI.Call("Deploy", application.DeployArgs{
CharmID: application.CharmID{
URL: &deployURL,
Origin: origin,
},
CharmOrigin: origin,
ApplicationName: inURL.Name,
Series: "jammy",
ConfigYAML: "aws-integrator:\n trust: \"true\"\n",
}).Returns(error(nil))
s.fakeAPI.Call("Deploy", application.DeployArgs{
CharmID: application.CharmID{
URL: &deployURL,
Origin: origin,
},
CharmOrigin: origin,
ApplicationName: inURL.Name,
Series: "jammy",
}).Returns(errors.New("expected Deploy for aws-integrator to be called with 'trust: true'"))
s.fakeAPI.Call("AddUnits", application.AddUnitsParams{
ApplicationName: "aws-integrator",
NumUnits: 1,
}).Returns([]string{"aws-integrator/0"}, error(nil))
s.fakeAPI.Call("ListSpaces").Returns([]params.Space{{Name: "alpha", Id: "0"}}, error(nil))
// The second charm from the bundle does not require trust so no
// additional configuration should be injected
ubURL := charm.MustParseURL("cs:~jameinel/ubuntu-lite-7")
withCharmRepoResolvable(s.fakeAPI, ubURL, "jammy")
withCharmRepoResolvable(s.fakeAPI, ubURL, "")
withCharmDeployable(
s.fakeAPI, ubURL, "jammy",
&charm.Meta{Name: "ubuntu-lite", Series: []string{"jammy"}},
nil, false, false, 0, nil, nil,
)
s.fakeAPI.Call("AddUnits", application.AddUnitsParams{
ApplicationName: "ubuntu-lite",
NumUnits: 1,
}).Returns([]string{"ubuntu-lite/0"}, error(nil))
deploy := s.deployCommand()
bundlePath := testcharms.RepoWithSeries("bionic").ClonedBundleDirPath(c.MkDir(), "aws-integrator-trust-single")
_, err := cmdtesting.RunCommand(c, modelcmd.Wrap(deploy), bundlePath, "--trust")
c.Assert(err, jc.ErrorIsNil)
}
func (s *DeploySuite) TestDeployBundleWithOffers(c *gc.C) {
withAllWatcher(s.fakeAPI)
inURL := charm.MustParseURL("cs:apache2-26")
withCharmRepoResolvable(s.fakeAPI, inURL, "jammy")
withCharmRepoResolvable(s.fakeAPI, inURL, "")
withCharmDeployable(
s.fakeAPI, inURL, "jammy",
&charm.Meta{Name: "apache2", Series: []string{"jammy"}},
nil, false, false, 0, nil, nil,
)
s.fakeAPI.Call("AddUnits", application.AddUnitsParams{
ApplicationName: "apache2",
NumUnits: 1,
}).Returns([]string{"apache2/0"}, error(nil))
s.fakeAPI.Call("Offer",
"deadbeef-0bad-400d-8000-4b1d0d06f00d",
"apache2",
[]string{"apache-website", "website-cache"},
"admin",
"my-offer",
"",
).Returns([]params.ErrorResult{}, nil)
s.fakeAPI.Call("Offer",
"deadbeef-0bad-400d-8000-4b1d0d06f00d",
"apache2",
[]string{"apache-website"},
"admin",
"my-other-offer",
"",
).Returns([]params.ErrorResult{}, nil)
s.fakeAPI.Call("GrantOffer",
"admin",
"admin",
[]string{"controller.my-offer"},
).Returns(errors.New(`cannot grant admin access to user admin on offer admin/controller.my-offer: user already has "admin" access or greater`))
s.fakeAPI.Call("GrantOffer",
"bar",
"consume",
[]string{"controller.my-offer"},
).Returns(nil)
s.fakeAPI.Call("ListSpaces").Returns([]params.Space{{Name: "alpha", Id: "0"}}, error(nil))
deploy := s.deployCommand()
bundlePath := testcharms.RepoWithSeries("bionic").ClonedBundleDirPath(c.MkDir(), "apache2-with-offers-legacy")
_, err := cmdtesting.RunCommand(c, modelcmd.Wrap(deploy), bundlePath)
c.Assert(err, jc.ErrorIsNil)
var offerCallCount int
var grantOfferCallCount int
for _, call := range s.fakeAPI.Calls() {
switch call.FuncName {
case "Offer":
offerCallCount++
case "GrantOffer":
grantOfferCallCount++
}
}
c.Assert(offerCallCount, gc.Equals, 2)
c.Assert(grantOfferCallCount, gc.Equals, 2)
}
func (s *DeploySuite) TestDeployBundleWithSAAS(c *gc.C) {
withAllWatcher(s.fakeAPI)
inURL := charm.MustParseURL("cs:wordpress")
withCharmRepoResolvable(s.fakeAPI, inURL, "jammy")
withCharmRepoResolvable(s.fakeAPI, inURL, "")
withCharmDeployable(
s.fakeAPI, inURL, "jammy",
&charm.Meta{Name: "wordpress", Series: []string{"jammy"}},
nil, false, false, 0, nil, nil,
)
mac, err := apitesting.NewMacaroon("id")
c.Assert(err, jc.ErrorIsNil)
s.fakeAPI.Call("AddUnits", application.AddUnitsParams{
ApplicationName: "wordpress",
NumUnits: 1,
}).Returns([]string{"wordpress/0"}, error(nil))
s.fakeAPI.Call("GetConsumeDetails",
"admin/default.mysql",
).Returns(params.ConsumeOfferDetails{
Offer: ¶ms.ApplicationOfferDetails{
OfferName: "mysql",
OfferURL: "admin/default.mysql",
},
Macaroon: mac,
ControllerInfo: ¶ms.ExternalControllerInfo{
ControllerTag: coretesting.ControllerTag.String(),
Addrs: []string{"192.168.1.0"},
Alias: "controller-alias",
CACert: coretesting.CACert,
},