/
provisioner.go
1413 lines (1289 loc) · 42.2 KB
/
provisioner.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 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package caasapplicationprovisioner
import (
"encoding/json"
"fmt"
"io"
"sort"
"time"
charmresource "github.com/juju/charm/v12/resource"
"github.com/juju/clock"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v5"
"gopkg.in/yaml.v2"
"github.com/juju/juju/apiserver/common"
charmscommon "github.com/juju/juju/apiserver/common/charms"
"github.com/juju/juju/apiserver/common/storagecommon"
apiservererrors "github.com/juju/juju/apiserver/errors"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/facades/client/application"
"github.com/juju/juju/caas"
k8sconstants "github.com/juju/juju/caas/kubernetes/provider/constants"
"github.com/juju/juju/cloudconfig/podcfg"
"github.com/juju/juju/controller"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/resources"
"github.com/juju/juju/core/status"
"github.com/juju/juju/docker"
"github.com/juju/juju/environs/bootstrap"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/resource"
"github.com/juju/juju/rpc/params"
"github.com/juju/juju/state"
stateerrors "github.com/juju/juju/state/errors"
"github.com/juju/juju/state/stateenvirons"
"github.com/juju/juju/state/watcher"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
)
var logger = loggo.GetLogger("juju.apiserver.caasapplicationprovisioner")
type APIGroup struct {
*common.PasswordChanger
*common.LifeGetter
*common.AgentEntityWatcher
*common.Remover
charmInfoAPI *charmscommon.CharmInfoAPI
appCharmInfoAPI *charmscommon.ApplicationCharmInfoAPI
*API
}
type NewResourceOpenerFunc func(appName string) (resources.Opener, error)
type API struct {
auth facade.Authorizer
resources facade.Resources
ctrlSt CAASApplicationControllerState
state CAASApplicationProvisionerState
newResourceOpener NewResourceOpenerFunc
storage StorageBackend
storagePoolManager poolmanager.PoolManager
registry storage.ProviderRegistry
clock clock.Clock
}
// NewStateCAASApplicationProvisionerAPI provides the signature required for facade registration.
func NewStateCAASApplicationProvisionerAPI(ctx facade.Context) (*APIGroup, error) {
authorizer := ctx.Auth()
st := ctx.State()
sb, err := state.NewStorageBackend(ctx.State())
if err != nil {
return nil, errors.Trace(err)
}
model, err := st.Model()
if err != nil {
return nil, errors.Trace(err)
}
broker, err := stateenvirons.GetNewCAASBrokerFunc(caas.New)(model)
if err != nil {
return nil, errors.Annotate(err, "getting caas client")
}
registry := stateenvirons.NewStorageProviderRegistry(broker)
pm := poolmanager.New(state.NewStateSettings(st), registry)
commonState := &charmscommon.StateShim{st}
commonCharmsAPI, err := charmscommon.NewCharmInfoAPI(commonState, authorizer)
if err != nil {
return nil, errors.Trace(err)
}
appCharmInfoAPI, err := charmscommon.NewApplicationCharmInfoAPI(commonState, authorizer)
if err != nil {
return nil, errors.Trace(err)
}
newResourceOpener := func(appName string) (resources.Opener, error) {
return resource.NewResourceOpenerForApplication(st, appName)
}
systemState, err := ctx.StatePool().SystemState()
if err != nil {
return nil, errors.Trace(err)
}
api, err := NewCAASApplicationProvisionerAPI(
stateShim{systemState},
stateShim{st},
ctx.Resources(),
newResourceOpener,
authorizer,
sb,
pm,
registry,
clock.WallClock,
)
if err != nil {
return nil, errors.Trace(err)
}
leadershipRevoker, err := ctx.LeadershipRevoker(ctx.State().ModelUUID())
if err != nil {
return nil, errors.Annotate(err, "getting leadership client")
}
lifeCanRead := common.AuthAny(
common.AuthFuncForTagKind(names.ApplicationTagKind),
common.AuthFuncForTagKind(names.UnitTagKind),
)
apiGroup := &APIGroup{
PasswordChanger: common.NewPasswordChanger(st, common.AuthFuncForTagKind(names.ApplicationTagKind)),
LifeGetter: common.NewLifeGetter(st, lifeCanRead),
AgentEntityWatcher: common.NewAgentEntityWatcher(st, ctx.Resources(), common.AuthFuncForTagKind(names.ApplicationTagKind)),
Remover: common.NewRemover(st, common.RevokeLeadershipFunc(leadershipRevoker), true, common.AuthFuncForTagKind(names.UnitTagKind)),
charmInfoAPI: commonCharmsAPI,
appCharmInfoAPI: appCharmInfoAPI,
API: api,
}
return apiGroup, nil
}
// CharmInfo returns information about the requested charm.
func (a *APIGroup) CharmInfo(args params.CharmURL) (params.Charm, error) {
return a.charmInfoAPI.CharmInfo(args)
}
// ApplicationCharmInfo returns information about an application's charm.
func (a *APIGroup) ApplicationCharmInfo(args params.Entity) (params.Charm, error) {
return a.appCharmInfoAPI.ApplicationCharmInfo(args)
}
// NewCAASApplicationProvisionerAPI returns a new CAAS operator provisioner API facade.
func NewCAASApplicationProvisionerAPI(
ctrlSt CAASApplicationControllerState,
st CAASApplicationProvisionerState,
resources facade.Resources,
newResourceOpener NewResourceOpenerFunc,
authorizer facade.Authorizer,
sb StorageBackend,
storagePoolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
clock clock.Clock,
) (*API, error) {
if !authorizer.AuthController() {
return nil, apiservererrors.ErrPerm
}
return &API{
auth: authorizer,
resources: resources,
newResourceOpener: newResourceOpener,
ctrlSt: ctrlSt,
state: st,
storage: sb,
storagePoolManager: storagePoolManager,
registry: registry,
clock: clock,
}, nil
}
// WatchApplications starts a StringsWatcher to watch applications
// deployed to this model.
func (a *API) WatchApplications() (params.StringsWatchResult, error) {
watch := a.state.WatchApplications()
// Consume the initial event and forward it to the result.
if changes, ok := <-watch.Changes(); ok {
return params.StringsWatchResult{
StringsWatcherId: a.resources.Register(watch),
Changes: changes,
}, nil
}
return params.StringsWatchResult{}, watcher.EnsureErr(watch)
}
// WatchProvisioningInfo provides a watcher for changes that affect the
// information returned by ProvisioningInfo. This is useful for ensuring the
// latest application stated is ensured.
func (a *API) WatchProvisioningInfo(args params.Entities) (params.NotifyWatchResults, error) {
var result params.NotifyWatchResults
result.Results = make([]params.NotifyWatchResult, len(args.Entities))
for i, entity := range args.Entities {
appName, err := names.ParseApplicationTag(entity.Tag)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
res, err := a.watchProvisioningInfo(appName)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
result.Results[i].NotifyWatcherId = res.NotifyWatcherId
}
return result, nil
}
func (a *API) watchProvisioningInfo(appName names.ApplicationTag) (params.NotifyWatchResult, error) {
result := params.NotifyWatchResult{}
app, err := a.state.Application(appName.Id())
if err != nil {
return result, errors.Trace(err)
}
model, err := a.state.Model()
if err != nil {
return result, errors.Trace(err)
}
appWatcher := app.Watch()
controllerConfigWatcher := a.ctrlSt.WatchControllerConfig()
controllerAPIHostPortsWatcher := a.ctrlSt.WatchAPIHostPortsForAgents()
modelConfigWatcher := model.WatchForModelConfigChanges()
multiWatcher := common.NewMultiNotifyWatcher(appWatcher, controllerConfigWatcher, controllerAPIHostPortsWatcher, modelConfigWatcher)
if _, ok := <-multiWatcher.Changes(); ok {
result.NotifyWatcherId = a.resources.Register(multiWatcher)
} else {
return result, watcher.EnsureErr(multiWatcher)
}
return result, nil
}
// ProvisioningInfo returns the info needed to provision a caas application.
func (a *API) ProvisioningInfo(args params.Entities) (params.CAASApplicationProvisioningInfoResults, error) {
var result params.CAASApplicationProvisioningInfoResults
result.Results = make([]params.CAASApplicationProvisioningInfo, len(args.Entities))
for i, entity := range args.Entities {
appName, err := names.ParseApplicationTag(entity.Tag)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
info, err := a.provisioningInfo(appName)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
result.Results[i] = *info
}
return result, nil
}
func (a *API) provisioningInfo(appName names.ApplicationTag) (*params.CAASApplicationProvisioningInfo, error) {
app, err := a.state.Application(appName.Id())
if err != nil {
return nil, errors.Trace(err)
}
charmURL, _ := app.CharmURL()
if charmURL == nil {
return nil, errors.NotValidf("application charm url nil")
}
if app.CharmPendingToBeDownloaded() {
return nil, errors.NotProvisionedf("charm %q pending", *charmURL)
}
cfg, err := a.ctrlSt.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
model, err := a.state.Model()
if err != nil {
return nil, errors.Trace(err)
}
modelConfig, err := model.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
filesystemParams, err := a.applicationFilesystemParams(app, cfg, modelConfig)
if err != nil {
return nil, errors.Trace(err)
}
devices, err := a.devicesParams(app)
if err != nil {
return nil, errors.Trace(err)
}
cons, err := app.Constraints()
if err != nil {
return nil, errors.Trace(err)
}
mergedCons, err := a.state.ResolveConstraints(cons)
if err != nil {
return nil, errors.Trace(err)
}
resourceTags := tags.ResourceTags(
names.NewModelTag(modelConfig.UUID()),
names.NewControllerTag(cfg.ControllerUUID()),
modelConfig,
)
vers, ok := modelConfig.AgentVersion()
if !ok {
return nil, errors.NewNotValid(nil,
fmt.Sprintf("agent version is missing in model config %q", modelConfig.Name()),
)
}
imagePath, err := podcfg.GetJujuOCIImagePath(cfg, vers)
if err != nil {
return nil, errors.Annotatef(err, "getting juju oci image path")
}
apiHostPorts, err := a.ctrlSt.APIHostPortsForAgents()
if err != nil {
return nil, errors.Annotatef(err, "getting api addresses")
}
addrs := []string(nil)
for _, hostPorts := range apiHostPorts {
ordered := hostPorts.HostPorts().PrioritizedForScope(network.ScopeMatchCloudLocal)
for _, addr := range ordered {
if addr != "" {
addrs = append(addrs, addr)
}
}
}
caCert, _ := cfg.CACert()
appConfig, err := app.ApplicationConfig()
if err != nil {
return nil, errors.Annotatef(err, "getting application config")
}
base := app.Base()
imageRepoDetails, err := docker.NewImageRepoDetails(cfg.CAASImageRepo())
if err != nil {
return nil, errors.Annotatef(err, "parsing %s", controller.CAASImageRepo)
}
return ¶ms.CAASApplicationProvisioningInfo{
Version: vers,
APIAddresses: addrs,
CACert: caCert,
Tags: resourceTags,
Filesystems: filesystemParams,
Devices: devices,
Constraints: mergedCons,
Base: params.Base{Name: base.OS, Channel: base.Channel},
ImageRepo: params.NewDockerImageInfo(imageRepoDetails, imagePath),
CharmModifiedVersion: app.CharmModifiedVersion(),
CharmURL: *charmURL,
Trust: appConfig.GetBool(application.TrustConfigOptionName, false),
Scale: app.GetScale(),
}, nil
}
// SetOperatorStatus sets the status of each given entity.
func (a *API) SetOperatorStatus(args params.SetStatus) (params.ErrorResults, error) {
results := params.ErrorResults{
Results: make([]params.ErrorResult, len(args.Entities)),
}
for i, arg := range args.Entities {
tag, err := names.ParseApplicationTag(arg.Tag)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
info := status.StatusInfo{
Status: status.Status(arg.Status),
Message: arg.Info,
Data: arg.Data,
}
results.Results[i].Error = apiservererrors.ServerError(a.setStatus(tag, info))
}
return results, nil
}
func (a *API) setStatus(tag names.ApplicationTag, info status.StatusInfo) error {
app, err := a.state.Application(tag.Id())
if err != nil {
return errors.Trace(err)
}
return app.SetOperatorStatus(info)
}
// Units returns all the units for each application specified.
func (a *API) Units(args params.Entities) (params.CAASUnitsResults, error) {
results := params.CAASUnitsResults{
Results: make([]params.CAASUnitsResult, len(args.Entities)),
}
for i, entity := range args.Entities {
appName, err := names.ParseApplicationTag(entity.Tag)
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
app, err := a.state.Application(appName.Id())
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
units, err := app.AllUnits()
if err != nil {
results.Results[i].Error = apiservererrors.ServerError(err)
continue
}
result := params.CAASUnitsResult{
Units: make([]params.CAASUnitInfo, len(units)),
}
for uIdx, unit := range units {
unitStatus, err := unit.Status()
if err != nil {
result.Error = apiservererrors.ServerError(err)
break
}
result.Units[uIdx] = params.CAASUnitInfo{
Tag: unit.Tag().String(),
UnitStatus: ¶ms.UnitStatus{
AgentStatus: statusInfoToDetailedStatus(unitStatus),
WorkloadStatus: statusInfoToDetailedStatus(unitStatus),
},
}
}
results.Results[i] = result
}
return results, nil
}
func statusInfoToDetailedStatus(in status.StatusInfo) params.DetailedStatus {
return params.DetailedStatus{
Status: in.Status.String(),
Info: in.Message,
Since: in.Since,
Data: in.Data,
}
}
// CharmStorageParams returns filesystem parameters needed
// to provision storage used for a charm operator or workload.
func CharmStorageParams(
controllerUUID string,
storageClassName string,
modelCfg *config.Config,
poolName string,
poolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
) (*params.KubernetesFilesystemParams, error) {
// The defaults here are for operator storage.
// Workload storage will override these elsewhere.
const size uint64 = 1024
tags := tags.ResourceTags(
names.NewModelTag(modelCfg.UUID()),
names.NewControllerTag(controllerUUID),
modelCfg,
)
result := ¶ms.KubernetesFilesystemParams{
StorageName: "charm",
Size: size,
Provider: string(k8sconstants.StorageProviderType),
Tags: tags,
Attributes: make(map[string]interface{}),
}
// The storage key value from the model config might correspond
// to a storage pool, unless there's been a specific storage pool
// requested.
// First, blank out the fallback pool name used in previous
// versions of Juju.
if poolName == string(k8sconstants.StorageProviderType) {
poolName = ""
}
maybePoolName := poolName
if maybePoolName == "" {
maybePoolName = storageClassName
}
providerType, attrs, err := poolStorageProvider(poolManager, registry, maybePoolName)
if err != nil && (!errors.IsNotFound(err) || poolName != "") {
return nil, errors.Trace(err)
}
if err == nil {
result.Provider = string(providerType)
if len(attrs) > 0 {
result.Attributes = attrs
}
}
if _, ok := result.Attributes[k8sconstants.StorageClass]; !ok && result.Provider == string(k8sconstants.StorageProviderType) {
result.Attributes[k8sconstants.StorageClass] = storageClassName
}
return result, nil
}
func poolStorageProvider(poolManager poolmanager.PoolManager, registry storage.ProviderRegistry, poolName string) (storage.ProviderType, map[string]interface{}, error) {
pool, err := poolManager.Get(poolName)
if errors.IsNotFound(err) {
// If there's no pool called poolName, maybe a provider type
// has been specified directly.
providerType := storage.ProviderType(poolName)
provider, err1 := registry.StorageProvider(providerType)
if err1 != nil {
// The name can't be resolved as a storage provider type,
// so return the original "pool not found" error.
return "", nil, errors.Trace(err)
}
if !provider.Supports(storage.StorageKindFilesystem) {
return "", nil, errors.NotValidf("storage provider %q", providerType)
}
return providerType, nil, nil
} else if err != nil {
return "", nil, errors.Trace(err)
}
providerType := pool.Provider()
return providerType, pool.Attrs(), nil
}
func (a *API) applicationFilesystemParams(
app Application,
controllerConfig controller.Config,
modelConfig *config.Config,
) ([]params.KubernetesFilesystemParams, error) {
storageConstraints, err := app.StorageConstraints()
if err != nil {
return nil, errors.Trace(err)
}
ch, _, err := app.Charm()
if err != nil {
return nil, errors.Trace(err)
}
var allFilesystemParams []params.KubernetesFilesystemParams
// To always guarantee the same order, sort by names.
var sNames []string
for name := range storageConstraints {
sNames = append(sNames, name)
}
sort.Strings(sNames)
for _, name := range sNames {
cons := storageConstraints[name]
fsParams, err := filesystemParams(
app, cons, name,
controllerConfig.ControllerUUID(),
modelConfig,
a.storagePoolManager, a.registry,
)
if err != nil {
return nil, errors.Annotatef(err, "getting filesystem %q parameters", name)
}
for i := 0; i < int(cons.Count); i++ {
charmStorage := ch.Meta().Storage[name]
id := fmt.Sprintf("%s/%v", name, i)
tag := names.NewStorageTag(id)
location, err := state.FilesystemMountPoint(charmStorage, tag, "ubuntu")
if err != nil {
return nil, errors.Trace(err)
}
filesystemAttachmentParams := params.KubernetesFilesystemAttachmentParams{
Provider: fsParams.Provider,
MountPoint: location,
ReadOnly: charmStorage.ReadOnly,
}
fsParams.Attachment = &filesystemAttachmentParams
allFilesystemParams = append(allFilesystemParams, *fsParams)
}
}
return allFilesystemParams, nil
}
func filesystemParams(
app Application,
cons state.StorageConstraints,
storageName string,
controllerUUID string,
modelConfig *config.Config,
poolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
) (*params.KubernetesFilesystemParams, error) {
filesystemTags, err := storagecommon.StorageTags(nil, modelConfig.UUID(), controllerUUID, modelConfig)
if err != nil {
return nil, errors.Annotate(err, "computing storage tags")
}
filesystemTags[tags.JujuStorageOwner] = app.Name()
storageClassName, _ := modelConfig.AllAttrs()[k8sconstants.WorkloadStorageKey].(string)
if cons.Pool == "" && storageClassName == "" {
return nil, errors.Errorf("storage pool for %q must be specified since there's no model default storage class", storageName)
}
fsParams, err := CharmStorageParams(controllerUUID, storageClassName, modelConfig, cons.Pool, poolManager, registry)
if err != nil {
return nil, errors.Maskf(err, "getting filesystem storage parameters")
}
fsParams.Size = cons.Size
fsParams.StorageName = storageName
fsParams.Tags = filesystemTags
return fsParams, nil
}
func (a *API) devicesParams(app Application) ([]params.KubernetesDeviceParams, error) {
devices, err := app.DeviceConstraints()
if err != nil {
return nil, errors.Trace(err)
}
logger.Debugf("getting device constraints from state: %#v", devices)
var devicesParams []params.KubernetesDeviceParams
for _, d := range devices {
devicesParams = append(devicesParams, params.KubernetesDeviceParams{
Type: params.DeviceType(d.Type),
Count: d.Count,
Attributes: d.Attributes,
})
}
return devicesParams, nil
}
// ApplicationOCIResources returns the OCI image resources for an application.
func (a *API) ApplicationOCIResources(args params.Entities) (params.CAASApplicationOCIResourceResults, error) {
res := params.CAASApplicationOCIResourceResults{
Results: make([]params.CAASApplicationOCIResourceResult, len(args.Entities)),
}
for i, entity := range args.Entities {
appTag, err := names.ParseApplicationTag(entity.Tag)
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
continue
}
app, err := a.state.Application(appTag.Id())
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
continue
}
ch, _, err := app.Charm()
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
continue
}
resources, err := a.newResourceOpener(app.Name())
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
continue
}
imageResources := params.CAASApplicationOCIResources{
Images: make(map[string]params.DockerImageInfo),
}
for _, v := range ch.Meta().Resources {
if v.Type != charmresource.TypeContainerImage {
continue
}
reader, err := resources.OpenResource(v.Name)
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
break
}
rsc, err := readDockerImageResource(reader)
_ = reader.Close()
if err != nil {
res.Results[i].Error = apiservererrors.ServerError(err)
break
}
imageResources.Images[v.Name] = rsc
}
if res.Results[i].Error != nil {
continue
}
res.Results[i].Result = &imageResources
}
return res, nil
}
func readDockerImageResource(reader io.Reader) (params.DockerImageInfo, error) {
var details resources.DockerImageDetails
contents, err := io.ReadAll(reader)
if err != nil {
return params.DockerImageInfo{}, errors.Trace(err)
}
if err := json.Unmarshal(contents, &details); err != nil {
if err := yaml.Unmarshal(contents, &details); err != nil {
return params.DockerImageInfo{}, errors.Annotate(err, "file neither valid json or yaml")
}
}
if err := resources.ValidateDockerRegistryPath(details.RegistryPath); err != nil {
return params.DockerImageInfo{}, err
}
return params.DockerImageInfo{
RegistryPath: details.RegistryPath,
Username: details.Username,
Password: details.Password,
}, nil
}
// UpdateApplicationsUnits updates the Juju data model to reflect the given
// units of the specified application.
func (a *API) UpdateApplicationsUnits(args params.UpdateApplicationUnitArgs) (params.UpdateApplicationUnitResults, error) {
result := params.UpdateApplicationUnitResults{
Results: make([]params.UpdateApplicationUnitResult, len(args.Args)),
}
if len(args.Args) == 0 {
return result, nil
}
for i, appUpdate := range args.Args {
appTag, err := names.ParseApplicationTag(appUpdate.ApplicationTag)
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
app, err := a.state.Application(appTag.Id())
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
if app.Life() != state.Alive {
// We ignore any updates for dying applications.
logger.Debugf("ignoring unit updates for dying application: %v", app.Name())
continue
}
appStatus := appUpdate.Status
if appStatus.Status != "" && appStatus.Status != status.Unknown {
now := a.clock.Now()
err = app.SetOperatorStatus(status.StatusInfo{
Status: appStatus.Status,
Message: appStatus.Info,
Data: appStatus.Data,
Since: &now,
})
if err != nil {
result.Results[i].Error = apiservererrors.ServerError(err)
continue
}
}
appUnitInfo, err := a.updateUnitsFromCloud(app, appUpdate.Units)
if err != nil {
// Mask any not found errors as the worker (caller) treats them specially
// and they are not relevant here.
result.Results[i].Error = apiservererrors.ServerError(errors.Mask(err))
}
// Errors from SetScale will also include unit info.
if appUnitInfo != nil {
result.Results[i].Info = ¶ms.UpdateApplicationUnitsInfo{
Units: appUnitInfo,
}
}
}
return result, nil
}
type filesystemInfo struct {
unitTag names.UnitTag
providerId string
mountPoint string
readOnly bool
size uint64
filesystemId string
}
type volumeInfo struct {
unitTag names.UnitTag
providerId string
readOnly bool
persistent bool
size uint64
volumeId string
}
func (a *API) updateUnitsFromCloud(app Application, unitUpdates []params.ApplicationUnitParams) ([]params.ApplicationUnitInfo, error) {
logger.Debugf("unit updates: %#v", unitUpdates)
m, err := a.state.Model()
if err != nil {
return nil, errors.Trace(err)
}
var providerIds []string
for _, u := range unitUpdates {
providerIds = append(providerIds, u.ProviderId)
}
containers, err := m.Containers(providerIds...)
if err != nil {
return nil, errors.Trace(err)
}
units, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
unitByTag := make(map[string]Unit)
for _, v := range units {
unitByTag[v.Tag().String()] = v
}
unitByProviderID := make(map[string]Unit)
for _, v := range containers {
tag := names.NewUnitTag(v.Unit())
unit, ok := unitByTag[tag.String()]
if !ok {
return nil, errors.NotFoundf("unit %q with provider id %q", tag, v.ProviderId())
}
unitByProviderID[v.ProviderId()] = unit
}
filesystemUpdates := make(map[string]filesystemInfo)
filesystemStatus := make(map[string]status.StatusInfo)
volumeUpdates := make(map[string]volumeInfo)
volumeStatus := make(map[string]status.StatusInfo)
processFilesystemParams := func(processedFilesystemIds set.Strings, unitTag names.UnitTag, unitParams params.ApplicationUnitParams) error {
// Once a unit is available in the cluster, we consider
// its filesystem(s) to be attached since the unit is
// not considered ready until this happens.
filesystemInfoByName := make(map[string][]params.KubernetesFilesystemInfo)
for _, fsInfo := range unitParams.FilesystemInfo {
infos := filesystemInfoByName[fsInfo.StorageName]
infos = append(infos, fsInfo)
filesystemInfoByName[fsInfo.StorageName] = infos
}
for storageName, infos := range filesystemInfoByName {
logger.Debugf("updating storage %v for %v", storageName, unitTag)
if len(infos) == 0 {
continue
}
unitStorage, err := a.storage.UnitStorageAttachments(unitTag)
if err != nil {
return errors.Trace(err)
}
// Loop over all the storage for the unit and skip storage not
// relevant for storageName.
// TODO(caas) - Add storage bankend API to get all unit storage instances for a named storage.
for _, sa := range unitStorage {
si, err := a.storage.StorageInstance(sa.StorageInstance())
if errors.IsNotFound(err) {
logger.Warningf("ignoring non-existent storage instance %v for unit %v", sa.StorageInstance(), unitTag.Id())
continue
}
if err != nil {
return errors.Trace(err)
}
if si.StorageName() != storageName {
continue
}
fs, err := a.storage.StorageInstanceFilesystem(sa.StorageInstance())
if err != nil {
return errors.Trace(err)
}
fsInfo := infos[0]
processedFilesystemIds.Add(fsInfo.FilesystemId)
// k8s reports provisioned info even when the volume is not ready.
// Only update state when volume is created so Juju doesn't think
// the volume is active when it's not.
if fsInfo.Status != status.Pending.String() {
filesystemUpdates[fs.FilesystemTag().String()] = filesystemInfo{
unitTag: unitTag,
providerId: unitParams.ProviderId,
mountPoint: fsInfo.MountPoint,
readOnly: fsInfo.ReadOnly,
size: fsInfo.Size,
filesystemId: fsInfo.FilesystemId,
}
}
filesystemStatus[fs.FilesystemTag().String()] = status.StatusInfo{
Status: status.Status(fsInfo.Status),
Message: fsInfo.Info,
Data: fsInfo.Data,
}
// If the filesystem has a backing volume, get that info also.
if _, err := fs.Volume(); err == nil {
vol, err := a.storage.StorageInstanceVolume(sa.StorageInstance())
if err != nil {
return errors.Trace(err)
}
if fsInfo.Volume.Status != status.Pending.String() {
volumeUpdates[vol.VolumeTag().String()] = volumeInfo{
unitTag: unitTag,
providerId: unitParams.ProviderId,
size: fsInfo.Volume.Size,
volumeId: fsInfo.Volume.VolumeId,
persistent: fsInfo.Volume.Persistent,
readOnly: fsInfo.ReadOnly,
}
}
volumeStatus[vol.VolumeTag().String()] = status.StatusInfo{
Status: status.Status(fsInfo.Volume.Status),
Message: fsInfo.Volume.Info,
Data: fsInfo.Volume.Data,
}
}
infos = infos[1:]
if len(infos) == 0 {
break
}
}
}
return nil
}
unitUpdate := state.UpdateUnitsOperation{}
processedFilesystemIds := set.NewStrings()
for _, unitParams := range unitUpdates {
unit, ok := unitByProviderID[unitParams.ProviderId]
if !ok {
logger.Warningf("ignoring non-existent unit with provider id %q", unitParams.ProviderId)
continue
}
updateProps := processUnitParams(unitParams)
unitUpdate.Updates = append(unitUpdate.Updates, unit.UpdateOperation(*updateProps))
if len(unitParams.FilesystemInfo) > 0 {
err := processFilesystemParams(processedFilesystemIds, unit.Tag().(names.UnitTag), unitParams)
if err != nil {
return nil, errors.Annotatef(err, "processing filesystems for unit %q", unit.Tag())
}
}
}
err = app.UpdateUnits(&unitUpdate)
// We ignore any updates for dying applications.
if stateerrors.IsNotAlive(err) {
return nil, nil
} else if err != nil {
return nil, errors.Trace(err)
}
// If pods are recreated on the Kubernetes side, new units are created on the Juju
// side and so any previously attached filesystems become orphaned and need to
// be cleaned up.
appName := app.Name()
if err := a.cleanupOrphanedFilesystems(processedFilesystemIds); err != nil {
return nil, errors.Annotatef(err, "deleting orphaned filesystems for %v", appName)
}
// First do the volume updates as volumes need to be attached before the filesystem updates.
if err := a.updateVolumeInfo(volumeUpdates, volumeStatus); err != nil {
return nil, errors.Annotatef(err, "updating volume information for %v", appName)
}
if err := a.updateFilesystemInfo(filesystemUpdates, filesystemStatus); err != nil {
return nil, errors.Annotatef(err, "updating filesystem information for %v", appName)
}
var appUnitInfo []params.ApplicationUnitInfo
for _, c := range containers {
appUnitInfo = append(appUnitInfo, params.ApplicationUnitInfo{
ProviderId: c.ProviderId(),
UnitTag: names.NewUnitTag(c.Unit()).String(),
})
}
return appUnitInfo, nil
}
func (a *API) cleanupOrphanedFilesystems(processedFilesystemIds set.Strings) error {
// TODO(caas) - record unit id on the filesystem so we can query by unit
allFilesystems, err := a.storage.AllFilesystems()
if err != nil {
return errors.Trace(err)
}
for _, fs := range allFilesystems {
fsInfo, err := fs.Info()
if errors.IsNotProvisioned(err) {
continue
}
if err != nil {
return errors.Trace(err)
}
if !processedFilesystemIds.Contains(fsInfo.FilesystemId) {
continue
}
storageTag, err := fs.Storage()
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if err != nil {
continue
}