forked from juju/juju
/
modelmanager.go
1801 lines (1612 loc) · 55.1 KB
/
modelmanager.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 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// Package modelmanager defines an API end point for functions dealing with
// models. Creating, listing and sharing models. This facade is available at
// the root of the controller API, and as such, there is no implicit Model
// associated.
package modelmanager
import (
stdcontext "context"
"fmt"
"sort"
"time"
"github.com/juju/description/v3"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/juju/txn/v2"
"github.com/juju/utils/v2"
"github.com/juju/version/v2"
"gopkg.in/yaml.v2"
"github.com/DavinZhang/juju/apiserver/common"
apiservererrors "github.com/DavinZhang/juju/apiserver/errors"
"github.com/DavinZhang/juju/apiserver/facade"
"github.com/DavinZhang/juju/apiserver/params"
"github.com/DavinZhang/juju/caas"
jujucloud "github.com/DavinZhang/juju/cloud"
"github.com/DavinZhang/juju/controller/modelmanager"
"github.com/DavinZhang/juju/core/life"
"github.com/DavinZhang/juju/core/permission"
"github.com/DavinZhang/juju/environs"
environscloudspec "github.com/DavinZhang/juju/environs/cloudspec"
"github.com/DavinZhang/juju/environs/config"
"github.com/DavinZhang/juju/environs/context"
"github.com/DavinZhang/juju/environs/space"
"github.com/DavinZhang/juju/feature"
"github.com/DavinZhang/juju/state"
"github.com/DavinZhang/juju/state/stateenvirons"
"github.com/DavinZhang/juju/tools"
)
var (
logger = loggo.GetLogger("juju.apiserver.modelmanager")
// Overridden by tests.
supportedFeaturesGetter = stateenvirons.SupportedFeatures
)
// ModelManagerV9 defines the methods on the version 9 facade for the
// modelmanager API endpoint.
type ModelManagerV9 interface {
ModelManagerV8
ValidateModelUpgrades(args params.ValidateModelUpgradeParams) (params.ErrorResults, error)
}
// ModelManagerV8 defines the methods on the version 8 facade for the
// modelmanager API endpoint.
type ModelManagerV8 interface {
ModelManagerV7
// ModelInfo gains credential validity in return.
}
// ModelManagerV7 defines the methods on the version 7 facade for the
// modelmanager API endpoint.
type ModelManagerV7 interface {
ModelManagerV6
// DestroyModels now has 'force' and 'max-wait' parameters.
}
// ModelManagerV6 defines the methods on the version 6 facade for the
// modelmanager API endpoint.
type ModelManagerV6 interface {
ModelManagerV5
ModelDefaultsForClouds(args params.Entities) (params.ModelDefaultsResults, error)
}
// ModelManagerV5 defines the methods on the version 5 facade for the
// modelmanager API endpoint.
type ModelManagerV5 interface {
CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error)
DumpModels(args params.DumpModelRequest) params.StringResults
DumpModelsDB(args params.Entities) params.MapResults
ListModelSummaries(request params.ModelSummariesRequest) (params.ModelSummaryResults, error)
ListModels(user params.Entity) (params.UserModelList, error)
DestroyModels(args params.DestroyModelsParams) (params.ErrorResults, error)
ModelInfo(args params.Entities) (params.ModelInfoResults, error)
ModelStatus(req params.Entities) (params.ModelStatusResults, error)
ChangeModelCredential(args params.ChangeModelCredentialsParams) (params.ErrorResults, error)
}
// ModelManagerV4 defines the methods on the version 4 facade for the
// modelmanager API endpoint.
type ModelManagerV4 interface {
CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error)
DumpModels(args params.DumpModelRequest) params.StringResults
DumpModelsDB(args params.Entities) params.MapResults
ListModelSummaries(request params.ModelSummariesRequest) (params.ModelSummaryResults, error)
ListModels(user params.Entity) (params.UserModelList, error)
DestroyModels(args params.DestroyModelsParams) (params.ErrorResults, error)
ModelInfo(args params.Entities) (params.ModelInfoResults, error)
ModelStatus(req params.Entities) (params.ModelStatusResults, error)
}
// ModelManagerV3 defines the methods on the version 3 facade for the
// modelmanager API endpoint.
type ModelManagerV3 interface {
CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error)
DumpModels(args params.DumpModelRequest) params.StringResults
DumpModelsDB(args params.Entities) params.MapResults
ListModels(user params.Entity) (params.UserModelList, error)
DestroyModels(args params.Entities) (params.ErrorResults, error)
ModelInfo(args params.Entities) (params.ModelInfoResults, error)
ModelStatus(req params.Entities) (params.ModelStatusResults, error)
}
// ModelManagerV2 defines the methods on the version 2 facade for the
// modelmanager API endpoint.
type ModelManagerV2 interface {
CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error)
DumpModels(args params.Entities) params.MapResults
DumpModelsDB(args params.Entities) params.MapResults
ListModels(user params.Entity) (params.UserModelList, error)
DestroyModels(args params.Entities) (params.ErrorResults, error)
ModelStatus(req params.Entities) (params.ModelStatusResults, error)
}
type newCaasBrokerFunc func(_ stdcontext.Context, args environs.OpenParams) (caas.Broker, error)
// StatePool represents a point of use interface for getting the state from the
// pool.
type StatePool interface {
Get(string) (State, error)
}
// State represents a point of use interface for modelling a current model.
type State interface {
Model() (Model, error)
HasUpgradeSeriesLocks() (bool, error)
Release() bool
}
// Model defines a point of use interface for the model from state.
type Model interface {
IsControllerModel() bool
}
// ModelManagerAPI implements the model manager interface and is
// the concrete implementation of the api end point.
type ModelManagerAPI struct {
*common.ModelStatusAPI
state common.ModelManagerBackend
statePool StatePool
ctlrState common.ModelManagerBackend
check *common.BlockChecker
authorizer facade.Authorizer
toolsFinder common.ToolsFinder
apiUser names.UserTag
isAdmin bool
model common.Model
getBroker newCaasBrokerFunc
callContext context.ProviderCallContext
}
// ModelManagerAPIV8 provides a way to wrap the different calls between
// version 8 and version 8 of the model manager API
type ModelManagerAPIV8 struct {
*ModelManagerAPI
}
// ModelManagerAPIV7 provides a way to wrap the different calls between
// version 8 and version 7 of the model manager API
type ModelManagerAPIV7 struct {
*ModelManagerAPIV8
}
// ModelManagerAPIV6 provides a way to wrap the different calls between
// version 7 and version 6 of the model manager API
type ModelManagerAPIV6 struct {
*ModelManagerAPIV7
}
// ModelManagerAPIV5 provides a way to wrap the different calls between
// version 5 and version 6 of the model manager API
type ModelManagerAPIV5 struct {
*ModelManagerAPIV6
}
// ModelManagerAPIV4 provides a way to wrap the different calls between
// version 4 and version 5 of the model manager API
type ModelManagerAPIV4 struct {
*ModelManagerAPIV5
}
// ModelManagerAPIV3 provides a way to wrap the different calls between
// version 3 and version 4 of the model manager API
type ModelManagerAPIV3 struct {
*ModelManagerAPIV4
}
// ModelManagerAPIV2 provides a way to wrap the different calls between
// version 2 and version 3 of the model manager API
type ModelManagerAPIV2 struct {
*ModelManagerAPIV3
}
var (
_ ModelManagerV9 = (*ModelManagerAPI)(nil)
_ ModelManagerV8 = (*ModelManagerAPIV8)(nil)
_ ModelManagerV7 = (*ModelManagerAPIV7)(nil)
_ ModelManagerV6 = (*ModelManagerAPIV6)(nil)
_ ModelManagerV5 = (*ModelManagerAPIV5)(nil)
_ ModelManagerV4 = (*ModelManagerAPIV4)(nil)
_ ModelManagerV3 = (*ModelManagerAPIV3)(nil)
_ ModelManagerV2 = (*ModelManagerAPIV2)(nil)
)
// NewFacadeV9 is used for API registration.
func NewFacadeV9(ctx facade.Context) (*ModelManagerAPI, error) {
st := ctx.State()
pool := ctx.StatePool()
ctlrSt := pool.SystemState()
auth := ctx.Auth()
var err error
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
configGetter := stateenvirons.EnvironConfigGetter{Model: model}
ctrlModel, err := ctlrSt.Model()
if err != nil {
return nil, err
}
// Since we know this is a user tag (because AuthClient is true),
// we just do the type assertion to the UserTag.
if !auth.AuthClient() {
return nil, apiservererrors.ErrPerm
}
apiUser, _ := auth.GetAuthTag().(names.UserTag)
return NewModelManagerAPI(
common.NewUserAwareModelManagerBackend(model, pool, apiUser),
common.NewModelManagerBackend(ctrlModel, pool),
statePoolShim{
StatePool: pool,
},
configGetter,
caas.New,
auth,
model,
context.CallContext(st),
)
}
// NewFacadeV8 is used for API registration.
func NewFacadeV8(ctx facade.Context) (*ModelManagerAPIV8, error) {
v9, err := NewFacadeV9(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV8{v9}, nil
}
// NewFacadeV7 is used for API registration.
func NewFacadeV7(ctx facade.Context) (*ModelManagerAPIV7, error) {
v8, err := NewFacadeV8(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV7{v8}, nil
}
// NewFacadeV6 is used for API registration.
func NewFacadeV6(ctx facade.Context) (*ModelManagerAPIV6, error) {
v7, err := NewFacadeV7(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV6{v7}, nil
}
// NewFacadeV5 is used for API registration.
func NewFacadeV5(ctx facade.Context) (*ModelManagerAPIV5, error) {
v6, err := NewFacadeV6(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV5{v6}, nil
}
// NewFacadeV4 is used for API registration.
func NewFacadeV4(ctx facade.Context) (*ModelManagerAPIV4, error) {
v5, err := NewFacadeV5(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV4{v5}, nil
}
// NewFacadeV3 is used for API registration.
func NewFacadeV3(ctx facade.Context) (*ModelManagerAPIV3, error) {
v4, err := NewFacadeV4(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV3{v4}, nil
}
// NewFacadeV2 is used for API registration.
func NewFacadeV2(ctx facade.Context) (*ModelManagerAPIV2, error) {
v3, err := NewFacadeV3(ctx)
if err != nil {
return nil, err
}
return &ModelManagerAPIV2{v3}, nil
}
// NewModelManagerAPI creates a new api server endpoint for managing
// models.
func NewModelManagerAPI(
st common.ModelManagerBackend,
ctlrSt common.ModelManagerBackend,
stPool StatePool,
configGetter environs.EnvironConfigGetter,
getBroker newCaasBrokerFunc,
authorizer facade.Authorizer,
m common.Model,
callCtx context.ProviderCallContext,
) (*ModelManagerAPI, error) {
if !authorizer.AuthClient() {
return nil, apiservererrors.ErrPerm
}
// Since we know this is a user tag (because AuthClient is true),
// we just do the type assertion to the UserTag.
apiUser, _ := authorizer.GetAuthTag().(names.UserTag)
// Pretty much all of the user manager methods have special casing for admin
// users, so look once when we start and remember if the user is an admin.
isAdmin, err := authorizer.HasPermission(permission.SuperuserAccess, st.ControllerTag())
if err != nil {
return nil, errors.Trace(err)
}
urlGetter := common.NewToolsURLGetter(st.ModelUUID(), ctlrSt)
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
newEnviron := common.EnvironFuncForModel(model, configGetter)
return &ModelManagerAPI{
ModelStatusAPI: common.NewModelStatusAPI(st, authorizer, apiUser),
state: st,
ctlrState: ctlrSt,
statePool: stPool,
getBroker: getBroker,
check: common.NewBlockChecker(st),
authorizer: authorizer,
toolsFinder: common.NewToolsFinder(configGetter, st, urlGetter, newEnviron),
apiUser: apiUser,
isAdmin: isAdmin,
model: m,
callContext: callCtx,
}, nil
}
// authCheck checks if the user is acting on their own behalf, or if they
// are an administrator acting on behalf of another user.
func (m *ModelManagerAPI) authCheck(user names.UserTag) error {
if m.isAdmin {
logger.Tracef("%q is a controller admin", m.apiUser.Id())
return nil
}
// We can't just compare the UserTags themselves as the provider part
// may be unset, and gets replaced with 'local'. We must compare against
// the Canonical value of the user tag.
if m.apiUser == user {
return nil
}
return apiservererrors.ErrPerm
}
func (m *ModelManagerAPI) hasWriteAccess(modelTag names.ModelTag) (bool, error) {
canWrite, err := m.authorizer.HasPermission(permission.WriteAccess, modelTag)
if errors.IsNotFound(err) {
return false, nil
}
return canWrite, err
}
// ConfigSource describes a type that is able to provide config.
// Abstracted primarily for testing.
type ConfigSource interface {
Config() (*config.Config, error)
}
func (m *ModelManagerAPI) newModelConfig(
cloudSpec environscloudspec.CloudSpec,
args params.ModelCreateArgs,
source ConfigSource,
) (*config.Config, error) {
// For now, we just smash to the two maps together as we store
// the account values and the model config together in the
// *config.Config instance.
joint := make(map[string]interface{})
for key, value := range args.Config {
joint[key] = value
}
if _, ok := joint[config.UUIDKey]; ok {
return nil, errors.New("uuid is generated, you cannot specify one")
}
if args.Name == "" {
return nil, errors.NewNotValid(nil, "Name must be specified")
}
if _, ok := joint[config.NameKey]; ok {
return nil, errors.New("name must not be specified in config")
}
joint[config.NameKey] = args.Name
baseConfig, err := source.Config()
if err != nil {
return nil, errors.Trace(err)
}
regionSpec := &environscloudspec.CloudRegionSpec{Cloud: cloudSpec.Name, Region: cloudSpec.Region}
if joint, err = m.state.ComposeNewModelConfig(joint, regionSpec); err != nil {
return nil, errors.Trace(err)
}
creator := modelmanager.ModelConfigCreator{
Provider: environs.Provider,
FindTools: func(n version.Number) (tools.List, error) {
if jujucloud.CloudTypeIsCAAS(cloudSpec.Type) {
return tools.List{&tools.Tools{Version: version.Binary{Number: n}}}, nil
}
result, err := m.toolsFinder.FindTools(params.FindToolsParams{
Number: n,
})
if err != nil {
return nil, errors.Trace(err)
}
return result.List, nil
},
}
return creator.NewModelConfig(cloudSpec, baseConfig, joint)
}
func (m *ModelManagerAPI) checkAddModelPermission(cloud string, userTag names.UserTag) (bool, error) {
perm, err := m.ctlrState.GetCloudAccess(cloud, userTag)
if err != nil && !errors.IsNotFound(err) {
return false, errors.Trace(err)
}
if !perm.EqualOrGreaterCloudAccessThan(permission.AddModelAccess) {
return false, nil
}
return true, nil
}
// CreateModel creates a new model using the account and
// model config specified in the args.
func (m *ModelManagerAPI) CreateModel(args params.ModelCreateArgs) (params.ModelInfo, error) {
result := params.ModelInfo{}
// Get the controller model first. We need it both for the state
// server owner and the ability to get the config.
controllerModel, err := m.ctlrState.Model()
if err != nil {
return result, errors.Trace(err)
}
var cloudTag names.CloudTag
cloudRegionName := args.CloudRegion
if args.CloudTag != "" {
var err error
cloudTag, err = names.ParseCloudTag(args.CloudTag)
if err != nil {
return result, errors.Trace(err)
}
} else {
cloudTag = names.NewCloudTag(controllerModel.CloudName())
}
if cloudRegionName == "" && cloudTag.Id() == controllerModel.CloudName() {
cloudRegionName = controllerModel.CloudRegion()
}
isAdmin, err := m.authorizer.HasPermission(permission.SuperuserAccess, m.state.ControllerTag())
if err != nil {
return result, errors.Trace(err)
}
if !isAdmin {
canAddModel, err := m.checkAddModelPermission(cloudTag.Id(), m.apiUser)
if err != nil {
return result, errors.Trace(err)
}
if !canAddModel {
return result, apiservererrors.ErrPerm
}
}
ownerTag, err := names.ParseUserTag(args.OwnerTag)
if err != nil {
return result, errors.Trace(err)
}
// a special case of ErrPerm will happen if the user has add-model permission but is trying to
// create a model for another person, which is not yet supported.
if !m.isAdmin && ownerTag != m.apiUser {
return result, errors.Annotatef(apiservererrors.ErrPerm, "%q permission does not permit creation of models for different owners", permission.AddModelAccess)
}
cloud, err := m.state.Cloud(cloudTag.Id())
if err != nil {
if errors.IsNotFound(err) && args.CloudTag != "" {
// A cloud was specified, and it was not found.
// Annotate the error with the supported clouds.
clouds, err := m.state.Clouds()
if err != nil {
return result, errors.Trace(err)
}
cloudNames := make([]string, 0, len(clouds))
for tag := range clouds {
cloudNames = append(cloudNames, tag.Id())
}
sort.Strings(cloudNames)
return result, errors.NewNotFound(err, fmt.Sprintf(
"cloud %q not found, expected one of %q",
cloudTag.Id(), cloudNames,
))
}
return result, errors.Annotate(err, "getting cloud definition")
}
var cloudCredentialTag names.CloudCredentialTag
if args.CloudCredentialTag != "" {
var err error
cloudCredentialTag, err = names.ParseCloudCredentialTag(args.CloudCredentialTag)
if err != nil {
return result, errors.Trace(err)
}
} else {
if ownerTag == controllerModel.Owner() {
cloudCredentialTag, _ = controllerModel.CloudCredentialTag()
} else {
// TODO(axw) check if the user has one and only one
// cloud credential, and if so, use it? For now, we
// require the user to specify a credential unless
// the cloud does not require one.
var hasEmpty bool
for _, authType := range cloud.AuthTypes {
if authType != jujucloud.EmptyAuthType {
continue
}
hasEmpty = true
break
}
if !hasEmpty {
return result, errors.NewNotValid(nil, "no credential specified")
}
}
}
var credential *jujucloud.Credential
if cloudCredentialTag != (names.CloudCredentialTag{}) {
credentialValue, err := m.state.CloudCredential(cloudCredentialTag)
if err != nil {
return result, errors.Annotate(err, "getting credential")
}
cloudCredential := jujucloud.NewNamedCredential(
credentialValue.Name,
jujucloud.AuthType(credentialValue.AuthType),
credentialValue.Attributes,
credentialValue.Revoked,
)
credential = &cloudCredential
}
cloudSpec, err := environscloudspec.MakeCloudSpec(cloud, cloudRegionName, credential)
if err != nil {
return result, errors.Trace(err)
}
var model common.Model
if jujucloud.CloudIsCAAS(cloud) {
model, err = m.newCAASModel(
cloudSpec,
args,
controllerModel,
cloudTag,
cloudRegionName,
cloudCredentialTag,
ownerTag)
} else {
model, err = m.newModel(
cloudSpec,
args,
controllerModel,
cloudTag,
cloudRegionName,
cloudCredentialTag,
ownerTag)
}
if err != nil {
return result, errors.Trace(err)
}
return m.getModelInfo(model.ModelTag())
}
func (m *ModelManagerAPI) newCAASModel(
cloudSpec environscloudspec.CloudSpec,
createArgs params.ModelCreateArgs,
controllerModel common.Model,
cloudTag names.CloudTag,
cloudRegionName string,
cloudCredentialTag names.CloudCredentialTag,
ownerTag names.UserTag,
) (_ common.Model, err error) {
newConfig, err := m.newModelConfig(cloudSpec, createArgs, controllerModel)
if err != nil {
return nil, errors.Annotate(err, "failed to create config")
}
controllerConfig, err := m.state.ControllerConfig()
if err != nil {
return nil, errors.Annotate(err, "getting controller config")
}
defer func() {
// Retain the error stack but with a better message.
if errors.IsAlreadyExists(err) {
err = errors.Wrap(err, errors.NewAlreadyExists(nil,
`
the model cannot be created because a namespace with the proposed
model name already exists in the k8s cluster.
Please choose a different model name.
`[1:],
))
}
}()
broker, err := m.getBroker(stdcontext.TODO(), environs.OpenParams{
ControllerUUID: controllerConfig.ControllerUUID(),
Cloud: cloudSpec,
Config: newConfig,
})
if err != nil {
return nil, errors.Annotate(err, "failed to open kubernetes client")
}
if err = broker.Create(
m.callContext,
environs.CreateParams{ControllerUUID: controllerConfig.ControllerUUID()},
); err != nil {
return nil, errors.Annotatef(err, "creating namespace %q", createArgs.Name)
}
storageProviderRegistry := stateenvirons.NewStorageProviderRegistry(broker)
model, st, err := m.state.NewModel(state.ModelArgs{
Type: state.ModelTypeCAAS,
CloudName: cloudTag.Id(),
CloudRegion: cloudRegionName,
CloudCredential: cloudCredentialTag,
Config: newConfig,
Owner: ownerTag,
StorageProviderRegistry: storageProviderRegistry,
})
if err != nil {
return nil, errors.Annotate(err, "failed to create new model")
}
defer st.Close()
return model, nil
}
func (m *ModelManagerAPI) newModel(
cloudSpec environscloudspec.CloudSpec,
createArgs params.ModelCreateArgs,
controllerModel common.Model,
cloudTag names.CloudTag,
cloudRegionName string,
cloudCredentialTag names.CloudCredentialTag,
ownerTag names.UserTag,
) (common.Model, error) {
newConfig, err := m.newModelConfig(cloudSpec, createArgs, controllerModel)
if err != nil {
return nil, errors.Annotate(err, "failed to create config")
}
controllerCfg, err := m.state.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
// Create the Environ.
env, err := environs.New(stdcontext.TODO(), environs.OpenParams{
ControllerUUID: controllerCfg.ControllerUUID(),
Cloud: cloudSpec,
Config: newConfig,
})
if err != nil {
return nil, errors.Annotate(err, "failed to open environ")
}
err = env.Create(
m.callContext,
environs.CreateParams{
ControllerUUID: controllerCfg.ControllerUUID(),
},
)
if err != nil {
return nil, errors.Annotate(err, "failed to create environ")
}
storageProviderRegistry := stateenvirons.NewStorageProviderRegistry(env)
// NOTE: check the agent-version of the config, and if it is > the current
// version, it is not supported, also check existing tools, and if we don't
// have tools for that version, also die.
model, st, err := m.state.NewModel(state.ModelArgs{
Type: state.ModelTypeIAAS,
CloudName: cloudTag.Id(),
CloudRegion: cloudRegionName,
CloudCredential: cloudCredentialTag,
Config: newConfig,
Owner: ownerTag,
StorageProviderRegistry: storageProviderRegistry,
EnvironVersion: env.Provider().Version(),
})
if err != nil {
// Clean up the environ.
if e := env.Destroy(m.callContext); e != nil {
logger.Warningf("failed to destroy environ, error %v", e)
}
return nil, errors.Annotate(err, "failed to create new model")
}
defer st.Close()
if err = model.AutoConfigureContainerNetworking(env); err != nil {
if errors.IsNotSupported(err) {
logger.Debugf("Not performing container networking autoconfiguration on a non-networking environment")
} else {
return nil, errors.Annotate(err, "Failed to perform container networking autoconfiguration")
}
}
if err = space.ReloadSpaces(m.callContext, spaceStateShim{
ModelManagerBackend: st,
}, env); err != nil {
if errors.IsNotSupported(err) {
logger.Debugf("Not performing spaces load on a non-networking environment")
} else {
return nil, errors.Annotate(err, "Failed to perform spaces discovery")
}
}
return model, nil
}
func (m *ModelManagerAPI) dumpModel(args params.Entity, simplified bool) ([]byte, error) {
modelTag, err := names.ParseModelTag(args.Tag)
if err != nil {
return nil, errors.Trace(err)
}
isModelAdmin, err := m.authorizer.HasPermission(permission.AdminAccess, modelTag)
if err != nil {
return nil, errors.Trace(err)
}
if !isModelAdmin && !m.isAdmin {
return nil, apiservererrors.ErrPerm
}
st, release, err := m.state.GetBackend(modelTag.Id())
if err != nil {
if errors.IsNotFound(err) {
return nil, errors.Trace(apiservererrors.ErrBadId)
}
return nil, errors.Trace(err)
}
defer release()
exportConfig := state.ExportConfig{IgnoreIncompleteModel: true}
if simplified {
exportConfig.SkipActions = true
exportConfig.SkipAnnotations = true
exportConfig.SkipCloudImageMetadata = true
exportConfig.SkipCredentials = true
exportConfig.SkipIPAddresses = true
exportConfig.SkipSettings = true
exportConfig.SkipSSHHostKeys = true
exportConfig.SkipStatusHistory = true
exportConfig.SkipLinkLayerDevices = true
}
model, err := st.ExportPartial(exportConfig)
if err != nil {
return nil, errors.Trace(err)
}
bytes, err := description.Serialize(model)
if err != nil {
return nil, errors.Trace(err)
}
return bytes, nil
}
func (m *ModelManagerAPIV2) dumpModel(args params.Entity) (map[string]interface{}, error) {
bytes, err := m.ModelManagerAPI.dumpModel(args, false)
if err != nil {
return nil, errors.Trace(err)
}
// Now read it back into a map.
var asMap map[string]interface{}
err = yaml.Unmarshal(bytes, &asMap)
if err != nil {
return nil, errors.Trace(err)
}
// In order to serialize the map through JSON, we need to make sure
// that all the embedded maps are map[string]interface{}, not
// map[interface{}]interface{} which is what YAML gives by default.
out, err := utils.ConformYAML(asMap)
if err != nil {
return nil, errors.Trace(err)
}
return out.(map[string]interface{}), nil
}
func (m *ModelManagerAPI) dumpModelDB(args params.Entity) (map[string]interface{}, error) {
modelTag, err := names.ParseModelTag(args.Tag)
if err != nil {
return nil, errors.Trace(err)
}
isModelAdmin, err := m.authorizer.HasPermission(permission.AdminAccess, modelTag)
if err != nil {
return nil, errors.Trace(err)
}
if !isModelAdmin && !m.isAdmin {
return nil, apiservererrors.ErrPerm
}
st := m.state
if st.ModelTag() != modelTag {
newSt, release, err := m.state.GetBackend(modelTag.Id())
if errors.IsNotFound(err) {
return nil, errors.Trace(apiservererrors.ErrBadId)
} else if err != nil {
return nil, errors.Trace(err)
}
defer release()
st = newSt
}
return st.DumpAll()
}
// DumpModels will export the models into the database agnostic
// representation. The user needs to either be a controller admin, or have
// admin privileges on the model itself.
func (m *ModelManagerAPI) DumpModels(args params.DumpModelRequest) params.StringResults {
results := params.StringResults{
Results: make([]params.StringResult, len(args.Entities)),
}
for i, entity := range args.Entities {
bytes, err := m.dumpModel(entity, args.Simplified)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
// We know here that the bytes are valid YAML.
results.Results[i].Result = string(bytes)
}
return results
}
// DumpModels will export the models into the database agnostic
// representation. The user needs to either be a controller admin, or have
// admin privileges on the model itself.
func (m *ModelManagerAPIV2) DumpModels(args params.Entities) params.MapResults {
results := params.MapResults{
Results: make([]params.MapResult, len(args.Entities)),
}
for i, entity := range args.Entities {
dumped, err := m.dumpModel(entity)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
results.Results[i].Result = dumped
}
return results
}
// DumpModelsDB will gather all documents from all model collections
// for the specified model. The map result contains a map of collection
// names to lists of documents represented as maps.
func (m *ModelManagerAPI) DumpModelsDB(args params.Entities) params.MapResults {
results := params.MapResults{
Results: make([]params.MapResult, len(args.Entities)),
}
for i, entity := range args.Entities {
dumped, err := m.dumpModelDB(entity)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
results.Results[i].Result = dumped
}
return results
}
// ListModelSummaries returns models that the specified user
// has access to in the current server. Controller admins (superuser)
// can list models for any user. Other users
// can only ask about their own models.
func (m *ModelManagerAPI) ListModelSummaries(req params.ModelSummariesRequest) (params.ModelSummaryResults, error) {
result := params.ModelSummaryResults{}
userTag, err := names.ParseUserTag(req.UserTag)
if err != nil {
return result, errors.Trace(err)
}
err = m.authCheck(userTag)
if err != nil {
return result, errors.Trace(err)
}
modelInfos, err := m.state.ModelSummariesForUser(userTag, req.All)
if err != nil {
return result, errors.Trace(err)
}
for _, mi := range modelInfos {
summary := ¶ms.ModelSummary{
Name: mi.Name,
UUID: mi.UUID,
Type: string(mi.Type),
OwnerTag: names.NewUserTag(mi.Owner).String(),
ControllerUUID: mi.ControllerUUID,
IsController: mi.IsController,
Life: life.Value(mi.Life.String()),
CloudTag: mi.CloudTag,
CloudRegion: mi.CloudRegion,
CloudCredentialTag: mi.CloudCredentialTag,
SLA: ¶ms.ModelSLAInfo{
Level: mi.SLALevel,
Owner: mi.Owner,
},
DefaultSeries: mi.DefaultSeries,
ProviderType: mi.ProviderType,
AgentVersion: mi.AgentVersion,
Status: common.EntityStatusFromState(mi.Status),
Counts: []params.ModelEntityCount{},
UserLastConnection: mi.UserLastConnection,
}
if mi.MachineCount > 0 {
summary.Counts = append(summary.Counts, params.ModelEntityCount{params.Machines, mi.MachineCount})
}
if mi.CoreCount > 0 {
summary.Counts = append(summary.Counts, params.ModelEntityCount{params.Cores, mi.CoreCount})
}
if mi.UnitCount > 0 {
summary.Counts = append(summary.Counts, params.ModelEntityCount{params.Units, mi.UnitCount})
}
access, err := common.StateToParamsUserAccessPermission(mi.Access)
if err == nil {
summary.UserAccess = access
}
if mi.Migration != nil {
migration := mi.Migration
startTime := migration.StartTime()
endTime := new(time.Time)
*endTime = migration.EndTime()
var zero time.Time
if *endTime == zero {
endTime = nil
}
summary.Migration = ¶ms.ModelMigrationStatus{
Status: migration.StatusMessage(),
Start: &startTime,
End: endTime,
}
}
result.Results = append(result.Results, params.ModelSummaryResult{Result: summary})
}
return result, nil