forked from juju/juju
/
application.go
2913 lines (2678 loc) · 91.5 KB
/
application.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 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Package application contains api calls for functionality
// related to deploying and managing applications and their
// related charms.
package application
import (
"fmt"
"math"
"net"
"reflect"
"strings"
"time"
"github.com/juju/charm/v9"
csparams "github.com/juju/charmrepo/v7/csclient/params"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/schema"
"github.com/juju/version/v2"
"gopkg.in/juju/environschema.v1"
"gopkg.in/macaroon.v2"
goyaml "gopkg.in/yaml.v2"
"github.com/DavinZhang/juju/apiserver/common"
"github.com/DavinZhang/juju/apiserver/common/storagecommon"
apiservererrors "github.com/DavinZhang/juju/apiserver/errors"
"github.com/DavinZhang/juju/apiserver/facade"
"github.com/DavinZhang/juju/apiserver/facades/controller/caasoperatorprovisioner"
"github.com/DavinZhang/juju/apiserver/params"
"github.com/DavinZhang/juju/caas"
k8s "github.com/DavinZhang/juju/caas/kubernetes/provider"
k8sconstants "github.com/DavinZhang/juju/caas/kubernetes/provider/constants"
"github.com/DavinZhang/juju/charmhub"
"github.com/DavinZhang/juju/controller"
"github.com/DavinZhang/juju/core/application"
corecharm "github.com/DavinZhang/juju/core/charm"
"github.com/DavinZhang/juju/core/constraints"
"github.com/DavinZhang/juju/core/crossmodel"
"github.com/DavinZhang/juju/core/instance"
"github.com/DavinZhang/juju/core/leadership"
"github.com/DavinZhang/juju/core/lxdprofile"
"github.com/DavinZhang/juju/core/model"
"github.com/DavinZhang/juju/core/network"
"github.com/DavinZhang/juju/core/network/firewall"
"github.com/DavinZhang/juju/core/permission"
"github.com/DavinZhang/juju/core/series"
"github.com/DavinZhang/juju/core/status"
"github.com/DavinZhang/juju/environs"
"github.com/DavinZhang/juju/environs/bootstrap"
environsconfig "github.com/DavinZhang/juju/environs/config"
"github.com/DavinZhang/juju/state"
"github.com/DavinZhang/juju/state/stateenvirons"
"github.com/DavinZhang/juju/storage"
"github.com/DavinZhang/juju/storage/poolmanager"
"github.com/DavinZhang/juju/tools"
jujuversion "github.com/DavinZhang/juju/version"
)
var logger = loggo.GetLogger("juju.apiserver.application")
// APIv13 provides the Application API facade for version 13.
type APIv13 struct {
*APIBase
}
// APIBase implements the shared application interface and is the concrete
// implementation of the api end point.
//
// API provides the Application API facade for version 5.
type APIBase struct {
backend Backend
storageAccess storageInterface
authorizer facade.Authorizer
check BlockChecker
updateSeries UpdateSeries
model Model
modelType state.ModelType
resources facade.Resources
leadershipReader leadership.Reader
// TODO(axw) stateCharm only exists because I ran out
// of time unwinding all of the tendrils of state. We
// should pass a charm.Charm and charm.URL back into
// state wherever we pass in a state.Charm currently.
stateCharm func(Charm) *state.Charm
storagePoolManager poolmanager.PoolManager
registry storage.ProviderRegistry
caasBroker caasBrokerInterface
deployApplicationFunc func(ApplicationDeployer, Model, DeployApplicationParams) (Application, error)
}
func NewFacadeV13(ctx facade.Context) (*APIv13, error) {
api, err := newFacadeBase(ctx)
if err != nil {
return nil, errors.Trace(err)
}
return &APIv13{api}, nil
}
type caasBrokerInterface interface {
ValidateStorageClass(config map[string]interface{}) error
Version() (*version.Number, error)
}
func newFacadeBase(ctx facade.Context) (*APIBase, error) {
model, err := ctx.State().Model()
if err != nil {
return nil, errors.Annotate(err, "getting model")
}
storageAccess, err := getStorageState(ctx.State())
if err != nil {
return nil, errors.Annotate(err, "getting state")
}
blockChecker := common.NewBlockChecker(ctx.State())
stateCharm := CharmToStateCharm
var (
storagePoolManager poolmanager.PoolManager
registry storage.ProviderRegistry
caasBroker caas.Broker
)
if model.Type() == state.ModelTypeCAAS {
caasBroker, err = stateenvirons.GetNewCAASBrokerFunc(caas.New)(model)
if err != nil {
return nil, errors.Annotate(err, "getting caas client")
}
registry = stateenvirons.NewStorageProviderRegistry(caasBroker)
storagePoolManager = poolmanager.New(state.NewStateSettings(ctx.State()), registry)
}
resources := ctx.Resources()
leadershipReader, err := ctx.LeadershipReader(ctx.State().ModelUUID())
if err != nil {
return nil, errors.Trace(err)
}
state := &stateShim{ctx.State()}
modelCfg, err := model.Config()
if err != nil {
return nil, errors.Trace(err)
}
options := []charmhub.Option{
// TODO (stickupkid): Get the http transport from the facade context
charmhub.WithHTTPTransport(charmhub.DefaultHTTPTransport),
}
var chCfg charmhub.Config
chURL, ok := modelCfg.CharmHubURL()
if ok {
chCfg, err = charmhub.CharmHubConfigFromURL(chURL, logger, options...)
} else {
chCfg, err = charmhub.CharmHubConfig(logger, options...)
}
if err != nil {
return nil, errors.Trace(err)
}
chClient, err := charmhub.NewClient(chCfg)
if err != nil {
return nil, errors.Trace(err)
}
updateSeries := NewUpdateSeriesAPI(state, makeUpdateSeriesValidator(chClient))
return NewAPIBase(
state,
storageAccess,
ctx.Auth(),
updateSeries,
blockChecker,
&modelShim{Model: model}, // modelShim wraps the AllPorts() API.
leadershipReader,
stateCharm,
DeployApplication,
storagePoolManager,
registry,
resources,
caasBroker,
)
}
// NewAPIBase returns a new application API facade.
func NewAPIBase(
backend Backend,
storageAccess storageInterface,
authorizer facade.Authorizer,
updateSeries UpdateSeries,
blockChecker BlockChecker,
model Model,
leadershipReader leadership.Reader,
stateCharm func(Charm) *state.Charm,
deployApplication func(ApplicationDeployer, Model, DeployApplicationParams) (Application, error),
storagePoolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
resources facade.Resources,
caasBroker caasBrokerInterface,
) (*APIBase, error) {
if !authorizer.AuthClient() {
return nil, apiservererrors.ErrPerm
}
return &APIBase{
backend: backend,
storageAccess: storageAccess,
authorizer: authorizer,
updateSeries: updateSeries,
check: blockChecker,
model: model,
modelType: model.Type(),
leadershipReader: leadershipReader,
stateCharm: stateCharm,
deployApplicationFunc: deployApplication,
storagePoolManager: storagePoolManager,
registry: registry,
resources: resources,
caasBroker: caasBroker,
}, nil
}
func (api *APIBase) checkPermission(tag names.Tag, perm permission.Access) error {
allowed, err := api.authorizer.HasPermission(perm, tag)
if err != nil {
return errors.Trace(err)
}
if !allowed {
return apiservererrors.ErrPerm
}
return nil
}
func (api *APIBase) checkCanRead() error {
return api.checkPermission(api.model.ModelTag(), permission.ReadAccess)
}
func (api *APIBase) checkCanWrite() error {
return api.checkPermission(api.model.ModelTag(), permission.WriteAccess)
}
// SetMetricCredentials sets credentials on the application.
func (api *APIBase) SetMetricCredentials(args params.ApplicationMetricCredentials) (params.ErrorResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Creds)),
}
if len(args.Creds) == 0 {
return result, nil
}
for i, a := range args.Creds {
oneApplication, err := api.backend.Application(a.ApplicationName)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
err = oneApplication.SetMetricCredentials(a.MetricCredentials)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
}
}
return result, nil
}
// Deploy fetches the charms from the charm store and deploys them
// using the specified placement directives.
func (api *APIBase) Deploy(args params.ApplicationsDeploy) (params.ErrorResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
result := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Applications)),
}
if err := api.check.ChangeAllowed(); err != nil {
return result, errors.Trace(err)
}
for i, arg := range args.Applications {
err := deployApplication(
api.backend,
api.model,
api.stateCharm,
arg,
api.deployApplicationFunc,
api.storagePoolManager,
api.registry,
api.caasBroker,
)
result.Results[i].Error = apiservererrors.ServerError(err)
if err != nil && len(arg.Resources) != 0 {
// Remove any pending resources - these would have been
// converted into real resources if the application had
// been created successfully, but will otherwise be
// leaked. lp:1705730
// TODO(babbageclunk): rework the deploy API so the
// resources are created transactionally to avoid needing
// to do this.
resources, err := api.backend.Resources()
if err != nil {
logger.Errorf("couldn't get backend.Resources")
continue
}
err = resources.RemovePendingAppResources(arg.ApplicationName, arg.Resources)
if err != nil {
logger.Errorf("couldn't remove pending resources for %q", arg.ApplicationName)
}
}
}
return result, nil
}
func applicationConfigSchema(modelType state.ModelType) (environschema.Fields, schema.Defaults, error) {
if modelType != state.ModelTypeCAAS {
return trustFields, trustDefaults, nil
}
// TODO(caas) - get the schema from the provider
defaults := caas.ConfigDefaults(k8s.ConfigDefaults())
configSchema, err := caas.ConfigSchema(k8s.ConfigSchema())
if err != nil {
return nil, nil, err
}
return AddTrustSchemaAndDefaults(configSchema, defaults)
}
func splitApplicationAndCharmConfig(modelType state.ModelType, inConfig map[string]string) (
appCfg map[string]interface{},
charmCfg map[string]string,
_ error,
) {
providerSchema, _, err := applicationConfigSchema(modelType)
if err != nil {
return nil, nil, errors.Trace(err)
}
appConfigKeys := application.KnownConfigKeys(providerSchema)
appConfigAttrs := make(map[string]interface{})
charmConfig := make(map[string]string)
for k, v := range inConfig {
if appConfigKeys.Contains(k) {
appConfigAttrs[k] = v
} else {
charmConfig[k] = v
}
}
return appConfigAttrs, charmConfig, nil
}
// splitApplicationAndCharmConfigFromYAML extracts app specific settings from a charm config YAML
// and returns those app settings plus a YAML with just the charm settings left behind.
func splitApplicationAndCharmConfigFromYAML(modelType state.ModelType, inYaml, appName string) (
appCfg map[string]interface{},
outYaml string,
_ error,
) {
var allSettings map[string]interface{}
if err := goyaml.Unmarshal([]byte(inYaml), &allSettings); err != nil {
return nil, "", errors.Annotate(err, "cannot parse settings data")
}
settings, ok := allSettings[appName].(map[interface{}]interface{})
if !ok {
// Application key not present; it might be 'juju get' output.
if _, err := charmConfigFromConfigValues(allSettings); err != nil {
return nil, "", errors.Errorf("no settings found for %q", appName)
}
return nil, inYaml, nil
}
providerSchema, _, err := applicationConfigSchema(modelType)
if err != nil {
return nil, "", errors.Trace(err)
}
appConfigKeys := application.KnownConfigKeys(providerSchema)
appConfigAttrs := make(map[string]interface{})
for k, v := range settings {
if key, ok := k.(string); ok && appConfigKeys.Contains(key) {
appConfigAttrs[key] = v
delete(settings, k)
}
}
if len(settings) == 0 {
return appConfigAttrs, "", nil
}
allSettings[appName] = settings
charmConfig, err := goyaml.Marshal(allSettings)
if err != nil {
return nil, "", errors.Annotate(err, "cannot marshall charm settings")
}
return appConfigAttrs, string(charmConfig), nil
}
func caasPrecheck(
ch Charm,
controllerCfg controller.Config,
model Model,
args params.ApplicationDeploy,
storagePoolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
caasBroker caasBrokerInterface,
) error {
if len(args.AttachStorage) > 0 {
return errors.Errorf(
"AttachStorage may not be specified for container models",
)
}
if len(args.Placement) > 1 {
return errors.Errorf(
"only 1 placement directive is supported for container models, got %d",
len(args.Placement),
)
}
for _, s := range ch.Meta().Storage {
if s.Type == charm.StorageBlock {
return errors.Errorf("block storage %q is not supported for container charms", s.Name)
}
}
serviceType := args.Config[k8s.ServiceTypeConfigKey]
if _, err := k8s.CaasServiceToK8s(caas.ServiceType(serviceType)); err != nil {
return errors.NotValidf("service type %q", serviceType)
}
cfg, err := model.ModelConfig()
if err != nil {
return errors.Trace(err)
}
// For older charms, operator-storage model config is mandatory.
if k8s.RequireOperatorStorage(ch) {
storageClassName, _ := cfg.AllAttrs()[k8sconstants.OperatorStorageKey].(string)
if storageClassName == "" {
return errors.New(
"deploying this Kubernetes application requires a suitable storage class.\n" +
"None have been configured. Set the operator-storage model config to " +
"specify which storage class should be used to allocate operator storage.\n" +
"See https://discourse.jujucharms.com/t/getting-started/152.",
)
}
sp, err := caasoperatorprovisioner.CharmStorageParams("", storageClassName, cfg, "", storagePoolManager, registry)
if err != nil {
return errors.Annotatef(err, "getting operator storage params for %q", args.ApplicationName)
}
if sp.Provider != string(k8sconstants.StorageProviderType) {
poolName := cfg.AllAttrs()[k8sconstants.OperatorStorageKey]
return errors.Errorf(
"the %q storage pool requires a provider type of %q, not %q", poolName, k8sconstants.StorageProviderType, sp.Provider)
}
if err := caasBroker.ValidateStorageClass(sp.Attributes); err != nil {
return errors.Trace(err)
}
}
workloadStorageClass, _ := cfg.AllAttrs()[k8sconstants.WorkloadStorageKey].(string)
for storageName, cons := range args.Storage {
if cons.Pool == "" && workloadStorageClass == "" {
return errors.Errorf("storage pool for %q must be specified since there's no model default storage class", storageName)
}
_, err := caasoperatorprovisioner.CharmStorageParams("", workloadStorageClass, cfg, cons.Pool, storagePoolManager, registry)
if err != nil {
return errors.Annotatef(err, "getting workload storage params for %q", args.ApplicationName)
}
}
caasVersion, err := caasBroker.Version()
if err != nil {
return errors.Trace(err)
}
if err := checkCAASMinVersion(ch, caasVersion); err != nil {
return errors.Trace(err)
}
return nil
}
// deployApplication fetches the charm from the charm store and deploys it.
// The logic has been factored out into a common function which is called by
// both the legacy API on the client facade, as well as the new application facade.
func deployApplication(
backend Backend,
model Model,
stateCharm func(Charm) *state.Charm,
args params.ApplicationDeploy,
deployApplicationFunc func(ApplicationDeployer, Model, DeployApplicationParams) (Application, error),
storagePoolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
caasBroker caasBrokerInterface,
) error {
curl, err := charm.ParseURL(args.CharmURL)
if err != nil {
return errors.Trace(err)
}
if curl.Revision < 0 {
return errors.Errorf("charm url must include revision")
}
// This check is done early so that errors deeper in the call-stack do not
// leave an application deployment in an unrecoverable error state.
if err := checkMachinePlacement(backend, args); err != nil {
return errors.Trace(err)
}
// Try to find the charm URL in state first.
ch, err := backend.Charm(curl)
if err != nil {
return errors.Trace(err)
}
if err := jujuversion.CheckJujuMinVersion(ch.Meta().MinJujuVersion, jujuversion.Current); err != nil {
return errors.Trace(err)
}
modelType := model.Type()
if modelType != state.ModelTypeIAAS {
cfg, err := backend.ControllerConfig()
if err != nil {
return errors.Trace(err)
}
if err := caasPrecheck(ch, cfg, model, args, storagePoolManager, registry, caasBroker); err != nil {
return errors.Trace(err)
}
}
appConfig, _, charmSettings, _, err := parseCharmSettings(modelType, ch, args.ApplicationName, args.Config, args.ConfigYAML, environsconfig.UseDefaults)
if err != nil {
return errors.Trace(err)
}
// Parse storage tags in AttachStorage.
if len(args.AttachStorage) > 0 && args.NumUnits != 1 {
return errors.Errorf("AttachStorage is non-empty, but NumUnits is %d", args.NumUnits)
}
attachStorage := make([]names.StorageTag, len(args.AttachStorage))
for i, tagString := range args.AttachStorage {
tag, err := names.ParseStorageTag(tagString)
if err != nil {
return errors.Trace(err)
}
attachStorage[i] = tag
}
bindings, err := state.NewBindings(backend, args.EndpointBindings)
if err != nil {
return errors.Trace(err)
}
origin, err := convertCharmOrigin(args.CharmOrigin, curl, args.Channel)
if err != nil {
return errors.Trace(err)
}
_, err = deployApplicationFunc(backend, model, DeployApplicationParams{
ApplicationName: args.ApplicationName,
Series: args.Series,
Charm: stateCharm(ch),
CharmOrigin: origin,
Channel: csparams.Channel(args.Channel),
NumUnits: args.NumUnits,
ApplicationConfig: appConfig,
CharmConfig: charmSettings,
Constraints: args.Constraints,
Placement: args.Placement,
Storage: args.Storage,
Devices: args.Devices,
AttachStorage: attachStorage,
EndpointBindings: bindings.Map(),
Resources: args.Resources,
Force: args.Force,
})
return errors.Trace(err)
}
func convertCharmOrigin(origin *params.CharmOrigin, curl *charm.URL, charmStoreChannel string) (corecharm.Origin, error) {
var (
originType string
platform corecharm.Platform
)
if origin != nil {
originType = origin.Type
platform = corecharm.Platform{
Architecture: origin.Architecture,
OS: origin.OS,
Series: origin.Series,
}
}
switch {
case origin == nil || origin.Source == "" || origin.Source == "charm-store":
var rev *int
if curl.Revision != -1 {
rev = &curl.Revision
}
var ch *charm.Channel
if charmStoreChannel != "" {
ch = &charm.Channel{
Risk: charm.Risk(charmStoreChannel),
}
}
return corecharm.Origin{
Type: originType,
Source: corecharm.CharmStore,
Revision: rev,
Channel: ch,
Platform: platform,
}, nil
case origin.Source == "local":
return corecharm.Origin{
Type: originType,
Source: corecharm.Local,
Revision: &curl.Revision,
Platform: platform,
}, nil
}
var track string
if origin.Track != nil {
track = *origin.Track
}
// We do guarantee that there will be a risk value.
// Ignore the error, as only caused by risk as an
// empty string.
var channel *charm.Channel
if ch, err := charm.MakeChannel(track, origin.Risk, ""); err == nil {
channel = &ch
}
return corecharm.Origin{
Type: originType,
Source: corecharm.Source(origin.Source),
ID: origin.ID,
Hash: origin.Hash,
Revision: origin.Revision,
Channel: channel,
Platform: platform,
}, nil
}
// parseCharmSettings parses, verifies and combines the config settings for a
// charm as specified by the provided config map and config yaml payload. Any
// model-specific application settings will be automatically extracted and
// returned back as an *application.Config.
func parseCharmSettings(modelType state.ModelType, ch Charm, appName string, config map[string]string, configYaml string, defaults environsconfig.Defaulting) (*application.Config, environschema.Fields, charm.Settings, schema.Defaults, error) {
// Split out the app config from the charm config for any config
// passed in as a map as opposed to YAML.
var (
applicationConfig map[string]interface{}
charmConfig map[string]string
err error
)
if len(config) > 0 {
if applicationConfig, charmConfig, err = splitApplicationAndCharmConfig(modelType, config); err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
}
// Split out the app config from the charm config for any config
// passed in as YAML.
var (
charmYamlConfig string
appSettings = make(map[string]interface{})
)
if len(configYaml) != 0 {
if appSettings, charmYamlConfig, err = splitApplicationAndCharmConfigFromYAML(modelType, configYaml, appName); err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
}
// Entries from the string-based config map always override any entries
// provided via the YAML payload.
for k, v := range applicationConfig {
appSettings[k] = v
}
appCfgSchema, schemaDefaults, err := applicationConfigSchema(modelType)
if err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
getDefaults := func() schema.Defaults {
// If defaults is UseDefaults, defaults are baked into the app config.
if defaults == environsconfig.UseDefaults {
return schemaDefaults
}
return nil
}
appConfig, err := application.NewConfig(appSettings, appCfgSchema, getDefaults())
if err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
// If there isn't a charm YAML, then we can just return the charmConfig as
// the settings and no need to attempt to parse an empty yaml.
if len(charmYamlConfig) == 0 {
settings, err := ch.Config().ParseSettingsStrings(charmConfig)
if err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
return appConfig, appCfgSchema, settings, schemaDefaults, nil
}
var charmSettings charm.Settings
// Parse the charm YAML and check the yaml against the charm config.
if charmSettings, err = ch.Config().ParseSettingsYAML([]byte(charmYamlConfig), appName); err != nil {
// Check if this is 'juju get' output and parse it as such
jujuGetSettings, pErr := charmConfigFromYamlConfigValues(charmYamlConfig)
if pErr != nil {
// Not 'juju output' either; return original error
return nil, nil, nil, nil, errors.Trace(err)
}
charmSettings = jujuGetSettings
}
// Entries from the string-based config map always override any entries
// provided via the YAML payload.
if len(charmConfig) != 0 {
// Parse config in a compatible way (see function comment).
overrideSettings, err := parseSettingsCompatible(ch.Config(), charmConfig)
if err != nil {
return nil, nil, nil, nil, errors.Trace(err)
}
for k, v := range overrideSettings {
charmSettings[k] = v
}
}
return appConfig, appCfgSchema, charmSettings, schemaDefaults, nil
}
// checkMachinePlacement does a non-exhaustive validation of any supplied
// placement directives.
// If the placement scope is for a machine, ensure that the machine exists.
// If the placement is for a machine or a container on an existing machine,
// check that the machine is not locked for series upgrade.
func checkMachinePlacement(backend Backend, args params.ApplicationDeploy) error {
errTemplate := "cannot deploy %q to machine %s"
app := args.ApplicationName
for _, p := range args.Placement {
dir := p.Directive
toProvisionedMachine := p.Scope == instance.MachineScope
if !toProvisionedMachine && dir == "" {
continue
}
m, err := backend.Machine(dir)
if err != nil {
if errors.IsNotFound(err) && !toProvisionedMachine {
continue
}
return errors.Annotatef(err, errTemplate, app, dir)
}
locked, err := m.IsLockedForSeriesUpgrade()
if locked {
err = errors.New("machine is locked for series upgrade")
}
if err != nil {
return errors.Annotatef(err, errTemplate, app, dir)
}
locked, err = m.IsParentLockedForSeriesUpgrade()
if locked {
err = errors.New("parent machine is locked for series upgrade")
}
if err != nil {
return errors.Annotatef(err, errTemplate, app, dir)
}
}
return nil
}
// parseSettingsCompatible parses setting strings in a way that is
// compatible with the behavior before this CL based on the issue
// http://pad.lv/1194945. Until then setting an option to an empty
// string caused it to reset to the default value. We now allow
// empty strings as actual values, but we want to preserve the API
// behavior.
func parseSettingsCompatible(charmConfig *charm.Config, settings map[string]string) (charm.Settings, error) {
setSettings := map[string]string{}
unsetSettings := charm.Settings{}
// Split settings into those which set and those which unset a value.
for name, value := range settings {
if value == "" {
unsetSettings[name] = nil
continue
}
setSettings[name] = value
}
// Validate the settings.
changes, err := charmConfig.ParseSettingsStrings(setSettings)
if err != nil {
return nil, errors.Trace(err)
}
// Validate the unsettings and merge them into the changes.
unsetSettings, err = charmConfig.ValidateSettings(unsetSettings)
if err != nil {
return nil, errors.Trace(err)
}
for name := range unsetSettings {
changes[name] = nil
}
return changes, nil
}
type setCharmParams struct {
AppName string
Application Application
CharmOrigin *params.CharmOrigin
Channel csparams.Channel
ConfigSettingsStrings map[string]string
ConfigSettingsYAML string
ResourceIDs map[string]string
StorageConstraints map[string]params.StorageConstraints
EndpointBindings map[string]string
Force forceParams
}
type forceParams struct {
ForceSeries, ForceUnits, Force bool
}
func (api *APIBase) setConfig(app Application, generation, settingsYAML string, settingsStrings map[string]string) error {
// We need a guard on the API server-side for direct API callers such as
// python-libjuju, and for older clients.
// Always default to the master branch.
if generation == "" {
generation = model.GenerationMaster
}
// Update settings for charm and/or application.
ch, _, err := app.Charm()
if err != nil {
return errors.Annotate(err, "obtaining charm for this application")
}
// parseCharmSettings is passed false for useDefaults because setConfig
// should not care about defaults.
// If defaults are wanted, one should call unsetApplicationConfig.
appConfig, appConfigSchema, charmSettings, defaults, err := parseCharmSettings(api.modelType, ch, app.Name(), settingsStrings, settingsYAML, environsconfig.NoDefaults)
if err != nil {
return errors.Annotate(err, "parsing settings for application")
}
var configChanged bool
if len(charmSettings) != 0 {
if err = app.UpdateCharmConfig(generation, charmSettings); err != nil {
return errors.Annotate(err, "updating charm config settings")
}
configChanged = true
}
if cfgAttrs := appConfig.Attributes(); len(cfgAttrs) > 0 {
if err = app.UpdateApplicationConfig(cfgAttrs, nil, appConfigSchema, defaults); err != nil {
return errors.Annotate(err, "updating application config settings")
}
configChanged = true
}
// If the config change is generational, add the app to the generation.
if configChanged && generation != model.GenerationMaster {
if err := api.addAppToBranch(generation, app.Name()); err != nil {
return errors.Trace(err)
}
}
return nil
}
// UpdateApplicationSeries updates the application series. Series for
// subordinates updated too.
func (api *APIBase) UpdateApplicationSeries(args params.UpdateSeriesArgs) (params.ErrorResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.ErrorResults{}, err
}
if err := api.check.ChangeAllowed(); err != nil {
return params.ErrorResults{}, errors.Trace(err)
}
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Args)),
}
for i, arg := range args.Args {
err := api.updateOneApplicationSeries(arg)
results.Results[i].Error = apiservererrors.ServerError(err)
}
return results, nil
}
func (api *APIBase) updateOneApplicationSeries(arg params.UpdateSeriesArg) error {
return api.updateSeries.UpdateSeries(arg.Entity.Tag, arg.Series, arg.Force)
}
// SetCharm sets the charm for a given for the application.
func (api *APIBase) SetCharm(args params.ApplicationSetCharm) error {
if err := api.checkCanWrite(); err != nil {
return err
}
// when forced units in error, don't block
if !args.ForceUnits {
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
}
oneApplication, err := api.backend.Application(args.ApplicationName)
if err != nil {
return errors.Trace(err)
}
channel := csparams.Channel(args.Channel)
return api.setCharmWithAgentValidation(
setCharmParams{
AppName: args.ApplicationName,
Application: oneApplication,
CharmOrigin: args.CharmOrigin,
Channel: channel,
ConfigSettingsStrings: args.ConfigSettings,
ConfigSettingsYAML: args.ConfigSettingsYAML,
ResourceIDs: args.ResourceIDs,
StorageConstraints: args.StorageConstraints,
EndpointBindings: args.EndpointBindings,
Force: forceParams{
ForceSeries: args.ForceSeries,
ForceUnits: args.ForceUnits,
Force: args.Force,
},
},
args.CharmURL,
)
}
var (
deploymentInfoUpgradeMessage = `
Juju on containers does not support updating deployment info for services.
The new charm's metadata contains updated deployment info.
You'll need to deploy a new charm rather than upgrading if you need this change.
`[1:]
storageUpgradeMessage = `
Juju on containers does not support updating storage on a statefulset.
The new charm's metadata contains updated storage declarations.
You'll need to deploy a new charm rather than upgrading if you need this change.
`[1:]
devicesUpgradeMessage = `
Juju on containers does not support updating node selectors (configured from charm devices).
The new charm's metadata contains updated device declarations.
You'll need to deploy a new charm rather than upgrading if you need this change.
`[1:]
)
// setCharmWithAgentValidation checks the agent versions of the application
// and unit before continuing on. These checks are important to prevent old
// code running at the same time as the new code. If you encounter the error,
// the correct and only work around is to upgrade the units to match the
// controller.
func (api *APIBase) setCharmWithAgentValidation(
params setCharmParams,
url string,
) error {
curl, err := charm.ParseURL(url)
if err != nil {
return errors.Trace(err)
}
newCharm, err := api.backend.Charm(curl)
if err != nil {
return errors.Trace(err)
}
oneApplication := params.Application
currentCharm, _, err := oneApplication.Charm()
if err != nil {
logger.Debugf("Unable to locate current charm: %v", err)
}
charmOrigin, err := convertCharmOrigin(params.CharmOrigin, curl, string(params.Channel))
if err != nil {
return errors.Trace(err)
}
newOrigin := StateCharmOrigin(charmOrigin)
if api.modelType == state.ModelTypeCAAS {
// We need to disallow updates that k8s does not yet support,
// eg changing the filesystem or device directives, or deployment info.
// TODO(wallyworld) - support resizing of existing storage.
var unsupportedReason string
if !reflect.DeepEqual(currentCharm.Meta().Deployment, newCharm.Meta().Deployment) {
unsupportedReason = deploymentInfoUpgradeMessage
} else if !reflect.DeepEqual(currentCharm.Meta().Storage, newCharm.Meta().Storage) {
unsupportedReason = storageUpgradeMessage
} else if !reflect.DeepEqual(currentCharm.Meta().Devices, newCharm.Meta().Devices) {
unsupportedReason = devicesUpgradeMessage
}
if unsupportedReason != "" {
return errors.NotSupportedf(unsupportedReason)
}
return api.applicationSetCharm(params, newCharm, newOrigin)
}