forked from juju/juju
/
application.go
1289 lines (1203 loc) · 39.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"
"regexp"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/utils/featureflag"
"github.com/juju/utils/set"
"gopkg.in/juju/charm.v6-unstable"
csparams "gopkg.in/juju/charmrepo.v2-unstable/csclient/params"
"gopkg.in/juju/names.v2"
goyaml "gopkg.in/yaml.v2"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/params"
jujucrossmodel "github.com/juju/juju/core/crossmodel"
"github.com/juju/juju/feature"
"github.com/juju/juju/instance"
jjj "github.com/juju/juju/juju"
"github.com/juju/juju/permission"
"github.com/juju/juju/state"
)
var logger = loggo.GetLogger("juju.apiserver.application")
func init() {
// TODO - version 1 is required for the legacy deployer,
// remove when deploy is updated.
common.RegisterStandardFacade("Application", 1, newAPI)
common.RegisterStandardFacade("Application", 2, newAPI)
// Version 3 adds support for cross model relations.
common.RegisterStandardFacade("Application", 3, newAPI)
// Version 4 adds the DestroyUnit and DestroyApplication
// methods, superseding the existing DestroyUnits and
// Destroy methods respectively.
common.RegisterStandardFacade("Application", 4, newAPI)
}
// API implements the application interface and is the concrete
// implementation of the api end point.
type API struct {
backend Backend
authorizer facade.Authorizer
check BlockChecker
dataDir string
statePool *state.StatePool
// 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
deployApplicationFunc func(backend Backend, args jjj.DeployApplicationParams) error
}
// DeployApplication is a wrapper around juju.DeployApplication, to
// match the function signature expected by NewAPI.
func DeployApplication(backend Backend, args jjj.DeployApplicationParams) error {
_, err := jjj.DeployApplication(backend, args)
return err
}
func newAPI(ctx facade.Context) (*API, error) {
backend := NewStateBackend(ctx.State())
blockChecker := common.NewBlockChecker(ctx.State())
stateCharm := CharmToStateCharm
return NewAPI(
backend,
ctx.Auth(),
ctx.Resources(),
ctx.StatePool(),
blockChecker,
stateCharm,
DeployApplication,
)
}
// NewAPI returns a new application API facade.
func NewAPI(
backend Backend,
authorizer facade.Authorizer,
resources facade.Resources,
statePool *state.StatePool,
blockChecker BlockChecker,
stateCharm func(Charm) *state.Charm,
deployApplication func(Backend, jjj.DeployApplicationParams) error,
) (*API, error) {
if !authorizer.AuthClient() {
return nil, common.ErrPerm
}
dataDir := resources.Get("dataDir").(common.StringResource)
return &API{
backend: backend,
authorizer: authorizer,
check: blockChecker,
stateCharm: stateCharm,
statePool: statePool,
dataDir: dataDir.String(),
deployApplicationFunc: deployApplication,
}, nil
}
func (api *API) checkCanRead() error {
canRead, err := api.authorizer.HasPermission(permission.ReadAccess, api.backend.ModelTag())
if err != nil {
return errors.Trace(err)
}
if !canRead {
return common.ErrPerm
}
return nil
}
func (api *API) checkCanWrite() error {
canWrite, err := api.authorizer.HasPermission(permission.WriteAccess, api.backend.ModelTag())
if err != nil {
return errors.Trace(err)
}
if !canWrite {
return common.ErrPerm
}
return nil
}
// SetMetricCredentials sets credentials on the application.
func (api *API) 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 {
application, err := api.backend.Application(a.ApplicationName)
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
err = application.SetMetricCredentials(a.MetricCredentials)
if err != nil {
result.Results[i].Error = common.ServerError(err)
}
}
return result, nil
}
// Deploy fetches the charms from the charm store and deploys them
// using the specified placement directives.
func (api *API) 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.stateCharm, arg, api.deployApplicationFunc)
result.Results[i].Error = common.ServerError(err)
}
return result, 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,
stateCharm func(Charm) *state.Charm,
args params.ApplicationDeploy,
deployApplicationFunc func(Backend, jjj.DeployApplicationParams) error,
) 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")
}
// Do a quick but not complete validation check before going any further.
for _, p := range args.Placement {
if p.Scope != instance.MachineScope {
continue
}
_, err = backend.Machine(p.Directive)
if err != nil {
return errors.Annotatef(err, `cannot deploy "%v" to machine %v`, args.ApplicationName, p.Directive)
}
}
// Try to find the charm URL in state first.
ch, err := backend.Charm(curl)
if err != nil {
return errors.Trace(err)
}
if err := checkMinVersion(ch); err != nil {
return errors.Trace(err)
}
var settings charm.Settings
if len(args.ConfigYAML) > 0 {
settings, err = ch.Config().ParseSettingsYAML([]byte(args.ConfigYAML), args.ApplicationName)
} else if len(args.Config) > 0 {
// Parse config in a compatible way (see function comment).
settings, err = parseSettingsCompatible(ch.Config(), args.Config)
}
if err != nil {
return errors.Trace(err)
}
return errors.Trace(deployApplicationFunc(backend, jjj.DeployApplicationParams{
ApplicationName: args.ApplicationName,
Series: args.Series,
Charm: stateCharm(ch),
Channel: csparams.Channel(args.Channel),
NumUnits: args.NumUnits,
ConfigSettings: settings,
Constraints: args.Constraints,
Placement: args.Placement,
Storage: args.Storage,
EndpointBindings: args.EndpointBindings,
Resources: args.Resources,
}))
}
// ApplicationSetSettingsStrings updates the settings for the given application,
// taking the configuration from a map of strings.
func ApplicationSetSettingsStrings(application Application, settings map[string]string) error {
ch, _, err := application.Charm()
if err != nil {
return errors.Trace(err)
}
// Parse config in a compatible way (see function comment).
changes, err := parseSettingsCompatible(ch.Config(), settings)
if err != nil {
return errors.Trace(err)
}
return application.UpdateConfigSettings(changes)
}
// 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
}
// Update updates the application attributes, including charm URL,
// minimum number of units, settings and constraints.
// All parameters in params.ApplicationUpdate except the application name are optional.
func (api *API) Update(args params.ApplicationUpdate) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if !args.ForceCharmURL {
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
}
app, err := api.backend.Application(args.ApplicationName)
if err != nil {
return errors.Trace(err)
}
// Set the charm for the given application.
if args.CharmURL != "" {
// For now we do not support changing the channel through Update().
// TODO(ericsnow) Support it?
channel := app.Channel()
if err = api.applicationSetCharm(
args.ApplicationName,
app,
args.CharmURL,
channel,
nil, // charm settings (strings map)
"", // charm settings (YAML)
args.ForceSeries,
args.ForceCharmURL,
nil, // resource IDs
nil, // storage constraints
); err != nil {
return errors.Trace(err)
}
}
// Set the minimum number of units for the given application.
if args.MinUnits != nil {
if err = app.SetMinUnits(*args.MinUnits); err != nil {
return errors.Trace(err)
}
}
// Set up application's settings.
if args.SettingsYAML != "" {
if err = applicationSetSettingsYAML(args.ApplicationName, app, args.SettingsYAML); err != nil {
return errors.Annotate(err, "setting configuration from YAML")
}
} else if len(args.SettingsStrings) > 0 {
if err = ApplicationSetSettingsStrings(app, args.SettingsStrings); err != nil {
return errors.Trace(err)
}
}
// Update application's constraints.
if args.Constraints != nil {
return app.SetConstraints(*args.Constraints)
}
return nil
}
// SetCharm sets the charm for a given for the application.
func (api *API) 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)
}
}
application, err := api.backend.Application(args.ApplicationName)
if err != nil {
return errors.Trace(err)
}
channel := csparams.Channel(args.Channel)
return api.applicationSetCharm(
args.ApplicationName,
application,
args.CharmURL,
channel,
args.ConfigSettings,
args.ConfigSettingsYAML,
args.ForceSeries,
args.ForceUnits,
args.ResourceIDs,
args.StorageConstraints,
)
}
// applicationSetCharm sets the charm for the given for the application.
func (api *API) applicationSetCharm(
appName string,
application Application,
url string,
channel csparams.Channel,
configSettingsStrings map[string]string,
configSettingsYAML string,
forceSeries,
forceUnits bool,
resourceIDs map[string]string,
storageConstraints map[string]params.StorageConstraints,
) error {
curl, err := charm.ParseURL(url)
if err != nil {
return errors.Trace(err)
}
sch, err := api.backend.Charm(curl)
if err != nil {
return errors.Trace(err)
}
var settings charm.Settings
if configSettingsYAML != "" {
settings, err = sch.Config().ParseSettingsYAML([]byte(configSettingsYAML), appName)
} else if len(configSettingsStrings) > 0 {
settings, err = parseSettingsCompatible(sch.Config(), configSettingsStrings)
}
if err != nil {
return errors.Annotate(err, "parsing config settings")
}
var stateStorageConstraints map[string]state.StorageConstraints
if len(storageConstraints) > 0 {
stateStorageConstraints = make(map[string]state.StorageConstraints)
for name, cons := range storageConstraints {
stateCons := state.StorageConstraints{Pool: cons.Pool}
if cons.Size != nil {
stateCons.Size = *cons.Size
}
if cons.Count != nil {
stateCons.Count = *cons.Count
}
stateStorageConstraints[name] = stateCons
}
}
cfg := state.SetCharmConfig{
Charm: api.stateCharm(sch),
Channel: channel,
ConfigSettings: settings,
ForceSeries: forceSeries,
ForceUnits: forceUnits,
ResourceIDs: resourceIDs,
StorageConstraints: stateStorageConstraints,
}
return application.SetCharm(cfg)
}
// settingsYamlFromGetYaml will parse a yaml produced by juju get and generate
// charm.Settings from it that can then be sent to the application.
func settingsFromGetYaml(yamlContents map[string]interface{}) (charm.Settings, error) {
onlySettings := charm.Settings{}
settingsMap, ok := yamlContents["settings"].(map[interface{}]interface{})
if !ok {
return nil, errors.New("unknown format for settings")
}
for setting := range settingsMap {
s, ok := settingsMap[setting].(map[interface{}]interface{})
if !ok {
return nil, errors.Errorf("unknown format for settings section %v", setting)
}
// some keys might not have a value, we don't care about those.
v, ok := s["value"]
if !ok {
continue
}
stringSetting, ok := setting.(string)
if !ok {
return nil, errors.Errorf("unexpected setting key, expected string got %T", setting)
}
onlySettings[stringSetting] = v
}
return onlySettings, nil
}
// applicationSetSettingsYAML updates the settings for the given application,
// taking the configuration from a YAML string.
func applicationSetSettingsYAML(appName string, application Application, settings string) error {
b := []byte(settings)
var all map[string]interface{}
if err := goyaml.Unmarshal(b, &all); err != nil {
return errors.Annotate(err, "parsing settings data")
}
// The file is already in the right format.
if _, ok := all[appName]; !ok {
changes, err := settingsFromGetYaml(all)
if err != nil {
return errors.Annotate(err, "processing YAML generated by get")
}
return errors.Annotate(application.UpdateConfigSettings(changes), "updating settings with application YAML")
}
ch, _, err := application.Charm()
if err != nil {
return errors.Annotate(err, "obtaining charm for this application")
}
changes, err := ch.Config().ParseSettingsYAML(b, appName)
if err != nil {
return errors.Annotate(err, "creating config from YAML")
}
return errors.Annotate(application.UpdateConfigSettings(changes), "updating settings")
}
// GetCharmURL returns the charm URL the given application is
// running at present.
func (api *API) GetCharmURL(args params.ApplicationGet) (params.StringResult, error) {
if err := api.checkCanWrite(); err != nil {
return params.StringResult{}, errors.Trace(err)
}
application, err := api.backend.Application(args.ApplicationName)
if err != nil {
return params.StringResult{}, errors.Trace(err)
}
charmURL, _ := application.CharmURL()
return params.StringResult{Result: charmURL.String()}, nil
}
// Set implements the server side of Application.Set.
// It does not unset values that are set to an empty string.
// Unset should be used for that.
func (api *API) Set(p params.ApplicationSet) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
app, err := api.backend.Application(p.ApplicationName)
if err != nil {
return err
}
ch, _, err := app.Charm()
if err != nil {
return err
}
// Validate the settings.
changes, err := ch.Config().ParseSettingsStrings(p.Options)
if err != nil {
return err
}
return app.UpdateConfigSettings(changes)
}
// Unset implements the server side of Client.Unset.
func (api *API) Unset(p params.ApplicationUnset) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
app, err := api.backend.Application(p.ApplicationName)
if err != nil {
return err
}
settings := make(charm.Settings)
for _, option := range p.Options {
settings[option] = nil
}
return app.UpdateConfigSettings(settings)
}
// CharmRelations implements the server side of Application.CharmRelations.
func (api *API) CharmRelations(p params.ApplicationCharmRelations) (params.ApplicationCharmRelationsResults, error) {
var results params.ApplicationCharmRelationsResults
if err := api.checkCanRead(); err != nil {
return results, errors.Trace(err)
}
application, err := api.backend.Application(p.ApplicationName)
if err != nil {
return results, errors.Trace(err)
}
endpoints, err := application.Endpoints()
if err != nil {
return results, errors.Trace(err)
}
results.CharmRelations = make([]string, len(endpoints))
for i, endpoint := range endpoints {
results.CharmRelations[i] = endpoint.Relation.Name
}
return results, nil
}
// Expose changes the juju-managed firewall to expose any ports that
// were also explicitly marked by units as open.
func (api *API) Expose(args params.ApplicationExpose) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
app, err := api.backend.Application(args.ApplicationName)
if err != nil {
return err
}
return app.SetExposed()
}
// Unexpose changes the juju-managed firewall to unexpose any ports that
// were also explicitly marked by units as open.
func (api *API) Unexpose(args params.ApplicationUnexpose) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
app, err := api.backend.Application(args.ApplicationName)
if err != nil {
return err
}
return app.ClearExposed()
}
// addApplicationUnits adds a given number of units to an application.
func addApplicationUnits(backend Backend, args params.AddApplicationUnits) ([]*state.Unit, error) {
application, err := backend.Application(args.ApplicationName)
if err != nil {
return nil, errors.Trace(err)
}
if args.NumUnits < 1 {
return nil, errors.New("must add at least one unit")
}
return jjj.AddUnits(backend, application, args.ApplicationName, args.NumUnits, args.Placement)
}
// AddUnits adds a given number of units to an application.
func (api *API) AddUnits(args params.AddApplicationUnits) (params.AddApplicationUnitsResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.AddApplicationUnitsResults{}, errors.Trace(err)
}
if err := api.check.ChangeAllowed(); err != nil {
return params.AddApplicationUnitsResults{}, errors.Trace(err)
}
units, err := addApplicationUnits(api.backend, args)
if err != nil {
return params.AddApplicationUnitsResults{}, errors.Trace(err)
}
unitNames := make([]string, len(units))
for i, unit := range units {
unitNames[i] = unit.String()
}
return params.AddApplicationUnitsResults{Units: unitNames}, nil
}
// DestroyUnits removes a given set of application units.
//
// NOTE(axw) this exists only for backwards compatibility,
// for API facade versions 1-3; clients should prefer its
// successor, DestroyUnit, below.
//
// TODO(axw) 2017-03-16 #1673323
// Drop this in Juju 3.0.
func (api *API) DestroyUnits(args params.DestroyApplicationUnits) error {
var errs []error
entities := params.Entities{
Entities: make([]params.Entity, 0, len(args.UnitNames)),
}
for _, unitName := range args.UnitNames {
if !names.IsValidUnit(unitName) {
errs = append(errs, errors.NotValidf("unit name %q", unitName))
continue
}
entities.Entities = append(entities.Entities, params.Entity{
Tag: names.NewUnitTag(unitName).String(),
})
}
results, err := api.DestroyUnit(entities)
if err != nil {
return errors.Trace(err)
}
for _, result := range results.Results {
if result.Error != nil {
errs = append(errs, result.Error)
}
}
return common.DestroyErr("units", args.UnitNames, errs)
}
// DestroyUnit removes a given set of application units.
func (api *API) DestroyUnit(args params.Entities) (params.DestroyUnitResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.DestroyUnitResults{}, err
}
if err := api.check.RemoveAllowed(); err != nil {
return params.DestroyUnitResults{}, errors.Trace(err)
}
destroyUnit := func(entity params.Entity) (*params.DestroyUnitInfo, error) {
unitTag, err := names.ParseUnitTag(entity.Tag)
if err != nil {
return nil, err
}
name := unitTag.Id()
unit, err := api.backend.Unit(name)
if errors.IsNotFound(err) {
return nil, errors.Errorf("unit %q does not exist", name)
} else if err != nil {
return nil, errors.Trace(err)
}
if !unit.IsPrincipal() {
return nil, errors.Errorf("unit %q is a subordinate", name)
}
var info params.DestroyUnitInfo
storage, err := common.UnitStorage(api.backend, unit.UnitTag())
if err != nil {
return nil, err
}
info.DestroyedStorage, info.DetachedStorage = common.ClassifyDetachedStorage(storage)
if err := unit.Destroy(); err != nil {
return nil, err
}
return &info, nil
}
results := make([]params.DestroyUnitResult, len(args.Entities))
for i, entity := range args.Entities {
info, err := destroyUnit(entity)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Info = info
}
return params.DestroyUnitResults{results}, nil
}
// Destroy destroys a given application, local or remote.
//
// NOTE(axw) this exists only for backwards compatibility,
// for API facade versions 1-3; clients should prefer its
// successor, DestroyApplication, below.
//
// TODO(axw) 2017-03-16 #1673323
// Drop this in Juju 3.0.
func (api *API) Destroy(args params.ApplicationDestroy) error {
if !names.IsValidApplication(args.ApplicationName) {
return errors.NotValidf("application name %q", args.ApplicationName)
}
entities := params.Entities{
Entities: []params.Entity{{
Tag: names.NewApplicationTag(args.ApplicationName).String(),
}},
}
results, err := api.DestroyApplication(entities)
if err != nil {
return errors.Trace(err)
}
if err := results.Results[0].Error; err != nil {
return common.ServerError(err)
}
return nil
}
// DestroyApplication removes a given set of applications.
func (api *API) DestroyApplication(args params.Entities) (params.DestroyApplicationResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.DestroyApplicationResults{}, err
}
if err := api.check.RemoveAllowed(); err != nil {
return params.DestroyApplicationResults{}, errors.Trace(err)
}
destroyRemoteApp := func(name string) error {
app, err := api.backend.RemoteApplication(name)
if err != nil {
return err
}
return app.Destroy()
}
destroyApp := func(entity params.Entity) (*params.DestroyApplicationInfo, error) {
tag, err := names.ParseApplicationTag(entity.Tag)
if err != nil {
return nil, err
}
var info params.DestroyApplicationInfo
if err := destroyRemoteApp(tag.Id()); !errors.IsNotFound(err) {
return &info, err
}
app, err := api.backend.Application(tag.Id())
if err != nil {
return nil, err
}
units, err := app.AllUnits()
if err != nil {
return nil, err
}
storageSeen := make(set.Tags)
for _, unit := range units {
info.DestroyedUnits = append(
info.DestroyedUnits,
params.Entity{unit.UnitTag().String()},
)
storage, err := common.UnitStorage(api.backend, unit.UnitTag())
if err != nil {
return nil, err
}
// Filter out storage we've already seen. Shared
// storage may be attached to multiple units.
var unseen []state.StorageInstance
for _, storage := range storage {
storageTag := storage.StorageTag()
if storageSeen.Contains(storageTag) {
continue
}
storageSeen.Add(storageTag)
unseen = append(unseen, storage)
}
storage = unseen
destroyed, detached := common.ClassifyDetachedStorage(storage)
info.DestroyedStorage = append(info.DestroyedStorage, destroyed...)
info.DetachedStorage = append(info.DetachedStorage, detached...)
}
if err := app.Destroy(); err != nil {
return nil, err
}
return &info, nil
}
results := make([]params.DestroyApplicationResult, len(args.Entities))
for i, entity := range args.Entities {
info, err := destroyApp(entity)
if err != nil {
results[i].Error = common.ServerError(err)
continue
}
results[i].Info = info
}
return params.DestroyApplicationResults{results}, nil
}
// GetConstraints returns the constraints for a given application.
func (api *API) GetConstraints(args params.GetApplicationConstraints) (params.GetConstraintsResults, error) {
if err := api.checkCanRead(); err != nil {
return params.GetConstraintsResults{}, errors.Trace(err)
}
app, err := api.backend.Application(args.ApplicationName)
if err != nil {
return params.GetConstraintsResults{}, errors.Trace(err)
}
cons, err := app.Constraints()
return params.GetConstraintsResults{cons}, errors.Trace(err)
}
// SetConstraints sets the constraints for a given application.
func (api *API) SetConstraints(args params.SetConstraints) error {
if err := api.checkCanWrite(); err != nil {
return err
}
if err := api.check.ChangeAllowed(); err != nil {
return errors.Trace(err)
}
app, err := api.backend.Application(args.ApplicationName)
if err != nil {
return err
}
return app.SetConstraints(args.Constraints)
}
// applicationUrlEndpointParse is used to split an application url and optional
// relation name into url and relation name.
var applicationUrlEndpointParse = regexp.MustCompile("(?P<url>.*[/.][^:]*)(:(?P<relname>.*)$)?")
// AddRelation adds a relation between the specified endpoints and returns the relation info.
func (api *API) AddRelation(args params.AddRelation) (params.AddRelationResults, error) {
if err := api.checkCanWrite(); err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
if err := api.check.ChangeAllowed(); err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
endpoints := make([]string, len(args.Endpoints))
// We may have a remote application passed in as the endpoint spec.
// We'll iterate the endpoints to check.
for i, ep := range args.Endpoints {
endpoints[i] = ep
// If cross model relations not enabled, ignore remote endpoints.
if !featureflag.Enabled(feature.CrossModelRelations) {
continue
}
// If the endpoint is not remote, skip it.
// We first need to strip off any relation name
// which may have been appended to the URL, then
// we try parsing the URL.
possibleURL := applicationUrlEndpointParse.ReplaceAllString(ep, "$url")
relName := applicationUrlEndpointParse.ReplaceAllString(ep, "$relname")
// If the URL parses, we need to look up the remote application
// details and save to state.
url, err := jujucrossmodel.ParseApplicationURL(possibleURL)
if err != nil {
// Not a URL.
continue
}
// Save the remote application details into state.
// TODO(wallyworld) - allow app name to be aliased
alias := url.ApplicationName
remoteApp, err := api.processRemoteApplication(url, alias)
if err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
// The endpoint is named after the remote application name,
// not the application name from the URL.
endpoints[i] = remoteApp.Name()
if relName != "" {
endpoints[i] = remoteApp.Name() + ":" + relName
}
}
inEps, err := api.backend.InferEndpoints(endpoints...)
if err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
rel, err := api.backend.AddRelation(inEps...)
if err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
outEps := make(map[string]params.CharmRelation)
for _, inEp := range inEps {
outEp, err := rel.Endpoint(inEp.ApplicationName)
if err != nil {
return params.AddRelationResults{}, errors.Trace(err)
}
outEps[inEp.ApplicationName] = params.CharmRelation{
Name: outEp.Relation.Name,
Role: string(outEp.Relation.Role),
Interface: outEp.Relation.Interface,
Optional: outEp.Relation.Optional,
Limit: outEp.Relation.Limit,
Scope: string(outEp.Relation.Scope),
}
}
return params.AddRelationResults{Endpoints: outEps}, nil
}
func (api *API) sameControllerSourceModel(userName, modelName string) (names.ModelTag, error) {
// Look up the model by qualified name, ie user/model.
var sourceModelTag names.ModelTag
allModels, err := api.backend.AllModels()
if err != nil {
return sourceModelTag, errors.Trace(err)
}
for _, m := range allModels {
if m.Name() != modelName {
continue
}
if m.Owner().Name() != userName {
continue
}
sourceModelTag = m.Tag().(names.ModelTag)
}
if sourceModelTag.Id() == "" {
return sourceModelTag, errors.NotFoundf(`model "%s/%s"`, userName, modelName)
}
return sourceModelTag, nil
}
// processRemoteApplication takes a remote application URL and retrieves or confirms the the details
// of the application and endpoint. These details are saved to the state model so relations to
// the remote application can be created.
func (api *API) processRemoteApplication(url *jujucrossmodel.ApplicationURL, alias string) (*state.RemoteApplication, error) {
// TODO(wallyworld) - add permission to offer. For now user requires write access to model.
app, releaser, sourceModelTag, err := api.sameControllerOfferedApplication(url, permission.WriteAccess)
if err != nil {
return nil, errors.Trace(err)
}
defer releaser()
eps, err := app.Endpoints()
if err != nil {
return nil, errors.Trace(err)
}
endpoints := make([]params.RemoteEndpoint, len(eps))
for i, ep := range eps {
endpoints[i] = params.RemoteEndpoint{
Name: ep.Name,
Scope: ep.Scope,
Interface: ep.Interface,
Role: ep.Role,
Limit: ep.Limit,
}
}
appName := alias
if appName == "" {
appName = url.ApplicationName
}
remoteApp, err := api.saveRemoteApplication(sourceModelTag, appName, url.ApplicationName, url.String(), endpoints)
return remoteApp, err
}
// sameControllerOfferedApplication looks in the specified model on the same controller
// and returns the specified application and a reference to its state.State.
func (api *API) sameControllerOfferedApplication(url *jujucrossmodel.ApplicationURL, perm permission.Access) (
_ *state.Application,
releaser func(),
sourceModelTag names.ModelTag,
err error,
) {
defer func() {
if err != nil && releaser != nil {
releaser()
}
}()