forked from juju/juju
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provisioner.go
1309 lines (1202 loc) · 39.5 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 caasunitprovisioner
import (
"fmt"
"sort"
"time"
"github.com/juju/clock"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/loggo"
"gopkg.in/juju/names.v3"
"github.com/juju/juju/apiserver/common"
"github.com/juju/juju/apiserver/common/storagecommon"
"github.com/juju/juju/apiserver/facade"
"github.com/juju/juju/apiserver/facades/controller/caasoperatorprovisioner"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/caas"
"github.com/juju/juju/caas/kubernetes/provider"
"github.com/juju/juju/cloudconfig/podcfg"
"github.com/juju/juju/controller"
"github.com/juju/juju/core/status"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/tags"
"github.com/juju/juju/state"
"github.com/juju/juju/state/stateenvirons"
"github.com/juju/juju/state/watcher"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
"github.com/juju/juju/version"
)
var logger = loggo.GetLogger("juju.apiserver.controller.caasunitprovisioner")
type Facade struct {
*common.LifeGetter
resources facade.Resources
state CAASUnitProvisionerState
storage StorageBackend
storagePoolManager poolmanager.PoolManager
registry storage.ProviderRegistry
devices DeviceBackend
clock clock.Clock
}
// NewStateFacade provides the signature required for facade registration.
func NewStateFacade(ctx facade.Context) (*Facade, error) {
authorizer := ctx.Auth()
resources := ctx.Resources()
sb, err := state.NewStorageBackend(ctx.State())
if err != nil {
return nil, errors.Trace(err)
}
db, err := state.NewDeviceBackend(ctx.State())
if err != nil {
return nil, errors.Trace(err)
}
broker, err := stateenvirons.GetNewCAASBrokerFunc(caas.New)(ctx.State())
if err != nil {
return nil, errors.Annotate(err, "getting caas client")
}
registry := stateenvirons.NewStorageProviderRegistry(broker)
pm := poolmanager.New(state.NewStateSettings(ctx.State()), registry)
return NewFacade(
resources,
authorizer,
stateShim{ctx.State()},
sb,
db,
pm,
registry,
clock.WallClock,
)
}
// NewFacade returns a new CAAS unit provisioner Facade facade.
func NewFacade(
resources facade.Resources,
authorizer facade.Authorizer,
st CAASUnitProvisionerState,
sb StorageBackend,
db DeviceBackend,
storagePoolManager poolmanager.PoolManager,
registry storage.ProviderRegistry,
clock clock.Clock,
) (*Facade, error) {
if !authorizer.AuthController() {
return nil, common.ErrPerm
}
return &Facade{
LifeGetter: common.NewLifeGetter(
st, common.AuthAny(
common.AuthFuncForTagKind(names.ApplicationTagKind),
common.AuthFuncForTagKind(names.UnitTagKind),
),
),
resources: resources,
state: st,
storage: sb,
devices: db,
storagePoolManager: storagePoolManager,
registry: registry,
clock: clock,
}, nil
}
// WatchApplications starts a StringsWatcher to watch CAAS applications
// deployed to this model.
func (f *Facade) WatchApplications() (params.StringsWatchResult, error) {
watch := f.state.WatchApplications()
if changes, ok := <-watch.Changes(); ok {
return params.StringsWatchResult{
StringsWatcherId: f.resources.Register(watch),
Changes: changes,
}, nil
}
return params.StringsWatchResult{}, watcher.EnsureErr(watch)
}
// WatchApplicationsScale starts a NotifyWatcher to watch changes
// to the applications' scale.
func (f *Facade) WatchApplicationsScale(args params.Entities) (params.NotifyWatchResults, error) {
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, arg := range args.Entities {
id, err := f.watchApplicationScale(arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].NotifyWatcherId = id
}
return results, nil
}
func (f *Facade) watchApplicationScale(tagString string) (string, error) {
tag, err := names.ParseApplicationTag(tagString)
if err != nil {
return "", errors.Trace(err)
}
app, err := f.state.Application(tag.Id())
if err != nil {
return "", errors.Trace(err)
}
w := app.WatchScale()
if _, ok := <-w.Changes(); ok {
return f.resources.Register(w), nil
}
return "", watcher.EnsureErr(w)
}
// WatchPodSpec starts a NotifyWatcher to watch changes to the
// pod spec for specified units in this model.
func (f *Facade) WatchPodSpec(args params.Entities) (params.NotifyWatchResults, error) {
model, err := f.state.Model()
if err != nil {
return params.NotifyWatchResults{}, errors.Trace(err)
}
results := params.NotifyWatchResults{
Results: make([]params.NotifyWatchResult, len(args.Entities)),
}
for i, arg := range args.Entities {
id, err := f.watchPodSpec(model, arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].NotifyWatcherId = id
}
return results, nil
}
func (f *Facade) watchPodSpec(model Model, tagString string) (string, error) {
tag, err := names.ParseApplicationTag(tagString)
if err != nil {
return "", errors.Trace(err)
}
w, err := model.WatchPodSpec(tag)
if err != nil {
return "", errors.Trace(err)
}
if _, ok := <-w.Changes(); ok {
return f.resources.Register(w), nil
}
return "", watcher.EnsureErr(w)
}
// ApplicationsScale returns the scaling info for specified applications in this model.
func (f *Facade) ApplicationsScale(args params.Entities) (params.IntResults, error) {
results := params.IntResults{
Results: make([]params.IntResult, len(args.Entities)),
}
for i, arg := range args.Entities {
scale, err := f.applicationScale(arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = scale
}
logger.Debugf("provisioning info result: %#v", results)
return results, nil
}
func (f *Facade) applicationScale(tagString string) (int, error) {
appTag, err := names.ParseApplicationTag(tagString)
if err != nil {
return 0, errors.Trace(err)
}
app, err := f.state.Application(appTag.Id())
if err != nil {
return 0, errors.Trace(err)
}
return app.GetScale(), nil
}
// ProvisioningInfo returns the provisioning info for specified applications in this model.
func (f *Facade) ProvisioningInfo(args params.Entities) (params.KubernetesProvisioningInfoResults, error) {
model, err := f.state.Model()
if err != nil {
return params.KubernetesProvisioningInfoResults{}, errors.Trace(err)
}
results := params.KubernetesProvisioningInfoResults{
Results: make([]params.KubernetesProvisioningInfoResult, len(args.Entities)),
}
for i, arg := range args.Entities {
info, err := f.provisioningInfo(model, arg.Tag)
if err != nil {
results.Results[i].Error = common.ServerError(err)
continue
}
results.Results[i].Result = info
}
return results, nil
}
func (f *Facade) provisioningInfo(model Model, tagString string) (*params.KubernetesProvisioningInfo, error) {
appTag, err := names.ParseApplicationTag(tagString)
if err != nil {
return nil, errors.Trace(err)
}
// First the pod spec.
podSpec, err := model.PodSpec(appTag)
if err != nil {
return nil, errors.Trace(err)
}
// Now get any required storage. We need to provision storage
// at the same time as the pod as it can't be attached later.
// All units are currently homogeneous so we just
// need to get info for the first alive unit.
app, err := f.state.Application(appTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
modelConfig, err := model.ModelConfig()
if err != nil {
return nil, errors.Trace(err)
}
controllerCfg, err := f.state.ControllerConfig()
if err != nil {
return nil, errors.Trace(err)
}
vers, ok := modelConfig.AgentVersion()
if !ok {
return nil, errors.NewNotValid(nil,
fmt.Sprintf("agent version is missing in model config %q", modelConfig.Name()),
)
}
operatorImagePath := podcfg.GetJujuOCIImagePath(controllerCfg, vers.ToPatch(), version.OfficialBuild)
filesystemParams, err := f.applicationFilesystemParams(app, controllerCfg, modelConfig)
if err != nil {
return nil, errors.Trace(err)
}
devices, err := f.devicesParams(app)
if err != nil {
return nil, errors.Trace(err)
}
cons, err := app.Constraints()
if err != nil {
return nil, errors.Trace(err)
}
mergedCons, err := f.state.ResolveConstraints(cons)
if err != nil {
return nil, errors.Trace(err)
}
resourceTags := tags.ResourceTags(
names.NewModelTag(modelConfig.UUID()),
names.NewControllerTag(controllerCfg.ControllerUUID()),
modelConfig,
)
ch, _, err := app.Charm()
if err != nil {
return nil, errors.Trace(err)
}
info := ¶ms.KubernetesProvisioningInfo{
PodSpec: podSpec,
Filesystems: filesystemParams,
Devices: devices,
Constraints: mergedCons,
Tags: resourceTags,
OperatorImagePath: operatorImagePath,
}
deployInfo := ch.Meta().Deployment
if deployInfo != nil {
info.DeploymentInfo = ¶ms.KubernetesDeploymentInfo{
DeploymentType: string(deployInfo.DeploymentType),
ServiceType: string(deployInfo.ServiceType),
}
}
return info, 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 params.KubernetesFilesystemParams{}, errors.Annotate(err, "computing storage tags")
}
filesystemTags[tags.JujuStorageOwner] = app.Name()
storageClassName, _ := modelConfig.AllAttrs()[provider.WorkloadStorageKey].(string)
if cons.Pool == "" && storageClassName == "" {
return params.KubernetesFilesystemParams{}, errors.Errorf("storage pool for %q must be specified since there's no model default storage class", storageName)
}
fsParams, err := caasoperatorprovisioner.CharmStorageParams(controllerUUID, storageClassName, modelConfig, cons.Pool, poolManager, registry)
if err != nil {
return params.KubernetesFilesystemParams{}, errors.Maskf(err, "getting filesystem storage parameters")
}
fsParams.Size = cons.Size
fsParams.StorageName = storageName
fsParams.Tags = filesystemTags
return fsParams, nil
}
// applicationFilesystemParams retrieves FilesystemParams for the filesystems
// that should be provisioned with, and attached to, pods of the application.
func (f *Facade) 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,
f.storagePoolManager, f.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, "kubernetes")
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 (f *Facade) 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
}
// ApplicationsConfig returns the config for the specified applications.
func (f *Facade) ApplicationsConfig(args params.Entities) (params.ApplicationGetConfigResults, error) {
results := params.ApplicationGetConfigResults{
Results: make([]params.ConfigResult, len(args.Entities)),
}
for i, arg := range args.Entities {
result, err := f.getApplicationConfig(arg.Tag)
results.Results[i].Config = result
results.Results[i].Error = common.ServerError(err)
}
return results, nil
}
func (f *Facade) getApplicationConfig(tagString string) (map[string]interface{}, error) {
tag, err := names.ParseApplicationTag(tagString)
if err != nil {
return nil, errors.Trace(err)
}
app, err := f.state.Application(tag.Id())
if err != nil {
return nil, errors.Trace(err)
}
return app.ApplicationConfig()
}
// UpdateApplicationsUnits updates the Juju data model to reflect the given
// units of the specified application.
func (a *Facade) 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 = common.ServerError(err)
continue
}
app, err := a.state.Application(appTag.Id())
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
appStatus := appUpdate.Status
if appStatus.Status != "" && appStatus.Status != status.Unknown {
now := a.clock.Now()
err = app.SetStatus(status.StatusInfo{
Status: appStatus.Status,
Message: appStatus.Info,
Data: appStatus.Data,
Since: &now,
})
if err != nil {
result.Results[i].Error = common.ServerError(err)
continue
}
}
appUnitInfo, err := a.updateUnitsFromCloud(app, appUpdate.Scale, appUpdate.Generation, 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 = common.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
}
// updateStatus constructs the agent and cloud container status values.
func (a *Facade) updateStatus(params params.ApplicationUnitParams) (
agentStatus *status.StatusInfo,
cloudContainerStatus *status.StatusInfo,
) {
var containerStatus status.Status
switch status.Status(params.Status) {
case status.Unknown:
// The container runtime can spam us with unimportant
// status updates, so ignore any irrelevant ones.
return nil, nil
case status.Allocating:
// The container runtime has decided to restart the pod.
agentStatus = &status.StatusInfo{
Status: status.Allocating,
Message: params.Info,
}
containerStatus = status.Waiting
case status.Running:
// A pod has finished starting so the workload is now active.
agentStatus = &status.StatusInfo{
Status: status.Idle,
}
containerStatus = status.Running
case status.Error:
agentStatus = &status.StatusInfo{
Status: status.Error,
Message: params.Info,
Data: params.Data,
}
containerStatus = status.Error
case status.Blocked:
containerStatus = status.Blocked
agentStatus = &status.StatusInfo{
Status: status.Idle,
}
}
cloudContainerStatus = &status.StatusInfo{
Status: containerStatus,
Message: params.Info,
Data: params.Data,
}
return agentStatus, cloudContainerStatus
}
// updateUnitsFromCloud takes a slice of unit information provided by an external
// source (typically a cloud update event) and merges that with the existing unit
// data model in state. The passed in units are the complete set for the cloud, so
// any existing units in state with provider ids which aren't in the set will be removed.
func (a *Facade) updateUnitsFromCloud(app Application, scale *int,
generation *int64, unitUpdates []params.ApplicationUnitParams) ([]params.ApplicationUnitInfo, error) {
logger.Debugf("unit updates: %#v", unitUpdates)
if scale != nil {
logger.Debugf("application scale: %v", *scale)
if *scale > 0 && len(unitUpdates) == 0 {
// no ops for empty units because we can not determine if it's stateful or not in this case.
logger.Debugf("ignoring empty k8s event for %q", app.Tag().String())
return nil, nil
}
}
// Set up the initial data structures.
existingStateUnits, err := app.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
stateUnitsById := make(map[string]stateUnit)
cloudPodsById := make(map[string]params.ApplicationUnitParams)
// Record all unit provider ids known to exist in the cloud.
for _, u := range unitUpdates {
cloudPodsById[u.ProviderId] = u
}
stateUnitExistsInCloud := func(providerId string) bool {
if providerId == "" {
return false
}
_, ok := cloudPodsById[providerId]
return ok
}
unitInfo := &updateStateUnitParams{
stateUnitsInCloud: make(map[string]Unit),
deletedRemoved: true,
}
var (
// aliveStateIds holds the provider ids of alive units in state.
aliveStateIds = set.NewStrings()
// extraStateIds holds the provider ids of units in state which
// no longer exist in the cloud.
extraStateIds = set.NewStrings()
)
// Loop over any existing state units and record those which do not yet have
// provider ids, and those which have been removed or updated.
for _, u := range existingStateUnits {
var providerId string
info, err := u.ContainerInfo()
if err != nil && !errors.IsNotFound(err) {
return nil, errors.Trace(err)
}
if err == nil {
providerId = info.ProviderId()
}
unitAlive := u.Life() == state.Alive
if !unitAlive {
continue
}
if providerId == "" {
logger.Debugf("unit %q is not associated with any pod", u.Name())
unitInfo.unassociatedUnits = append(unitInfo.unassociatedUnits, u)
continue
}
stateUnitsById[providerId] = stateUnit{Unit: u}
stateUnitInCloud := stateUnitExistsInCloud(providerId)
aliveStateIds.Add(providerId)
if stateUnitInCloud {
logger.Debugf("unit %q (%v) has changed in the cloud", u.Name(), providerId)
unitInfo.stateUnitsInCloud[u.UnitTag().String()] = u
} else {
logger.Debugf("unit %q (%v) has removed in the cloud", u.Name(), providerId)
extraStateIds.Add(providerId)
}
}
// Do it in sorted order so it's deterministic for tests.
var ids []string
for id := range cloudPodsById {
ids = append(ids, id)
}
sort.Strings(ids)
// Sort extra ids also to guarantee order.
var extraIds []string
for id := range extraStateIds {
extraIds = append(extraIds, id)
}
sort.Strings(extraIds)
unassociatedUnitCount := len(unitInfo.unassociatedUnits)
extraUnitsInStateCount := 0
if scale != nil {
extraUnitsInStateCount = len(stateUnitsById) + unassociatedUnitCount - *scale
}
for _, id := range ids {
u := cloudPodsById[id]
unitInfo.deletedRemoved = !u.Stateful
if aliveStateIds.Contains(id) {
u.UnitTag = stateUnitsById[id].UnitTag().String()
unitInfo.existingCloudPods = append(unitInfo.existingCloudPods, u)
continue
}
// First attempt to add any new cloud pod not yet represented in state
// to a unit which does not yet have a provider id.
if unassociatedUnitCount > 0 {
unassociatedUnitCount--
unitInfo.addedCloudPods = append(unitInfo.addedCloudPods, u)
continue
}
// A new pod was added to the cloud but does not yet have a unit in state.
unitInfo.addedCloudPods = append(unitInfo.addedCloudPods, u)
}
// If there are any extra provider ids left over after allocating all the cloud pods,
// then consider those state units as terminated.
logger.Debugf("alive state ids %v", aliveStateIds.Values())
logger.Debugf("extra state ids %v", extraStateIds.Values())
logger.Debugf("extra units in state: %v", extraUnitsInStateCount)
for _, providerId := range extraIds {
u := stateUnitsById[providerId]
logger.Debugf("unit %q (%v) has been removed from the cloud", u.Name(), providerId)
// If the unit in state is surplus to the application scale, remove it from state also.
// We retain units in state that are not surplus to cloud requirements as they will
// be regenerated by the cloud and we want to keep a stable unit name.
u.delete = unitInfo.deletedRemoved && scale != nil
if !u.delete && extraUnitsInStateCount > 0 {
logger.Debugf("deleting %v because it exceeds the scale of %v", u.Name(), scale)
u.delete = true
extraUnitsInStateCount--
}
unitInfo.removedUnits = append(unitInfo.removedUnits, u)
}
if err := a.updateStateUnits(app, unitInfo); err != nil {
return nil, errors.Trace(err)
}
var providerIds []string
for _, u := range unitUpdates {
providerIds = append(providerIds, u.ProviderId)
}
m, err := a.state.Model()
if err != nil {
return nil, errors.Trace(err)
}
containers, err := m.Containers(providerIds...)
if err != nil {
return nil, errors.Trace(err)
}
var appUnitInfo []params.ApplicationUnitInfo
for _, c := range containers {
appUnitInfo = append(appUnitInfo, params.ApplicationUnitInfo{
ProviderId: c.ProviderId(),
UnitTag: names.NewUnitTag(c.Unit()).String(),
})
}
if scale == nil {
return appUnitInfo, nil
}
// Update the scale last now that the state
// model accurately reflects the cluster pods.
currentScale := app.GetScale()
var gen int64
if generation != nil {
gen = *generation
}
if currentScale != *scale {
return appUnitInfo, app.SetScale(*scale, gen, false)
}
return appUnitInfo, nil
}
type stateUnit struct {
Unit
delete bool
}
type updateStateUnitParams struct {
stateUnitsInCloud map[string]Unit
addedCloudPods []params.ApplicationUnitParams
existingCloudPods []params.ApplicationUnitParams
removedUnits []stateUnit
unassociatedUnits []Unit
deletedRemoved bool
}
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 *Facade) updateStateUnits(app Application, unitInfo *updateStateUnitParams) error {
if app.Life() != state.Alive {
// We ignore any updates for dying applications.
logger.Debugf("ignoring unit updates for dying application: %v", app.Name())
return nil
}
logger.Tracef("added cloud units: %+v", unitInfo.addedCloudPods)
logger.Tracef("existing cloud units: %+v", unitInfo.existingCloudPods)
logger.Tracef("removed units: %+v", unitInfo.removedUnits)
logger.Tracef("unassociated units: %+v", unitInfo.unassociatedUnits)
// Now we have the added, removed, updated units all sorted,
// generate the state update operations.
var unitUpdate state.UpdateUnitsOperation
filesystemUpdates := make(map[string]filesystemInfo)
filesystemStatus := make(map[string]status.StatusInfo)
volumeUpdates := make(map[string]volumeInfo)
volumeStatus := make(map[string]status.StatusInfo)
for _, u := range unitInfo.removedUnits {
// If a unit is removed from the cloud, all filesystems are considered detached.
unitStorage, err := a.storage.UnitStorageAttachments(u.UnitTag())
if err != nil {
return errors.Trace(err)
}
for _, sa := range unitStorage {
fs, err := a.storage.StorageInstanceFilesystem(sa.StorageInstance())
if err != nil {
return errors.Trace(err)
}
filesystemStatus[fs.FilesystemTag().String()] = status.StatusInfo{Status: status.Detached}
}
if u.delete {
unitUpdate.Deletes = append(unitUpdate.Deletes, u.DestroyOperation())
}
// We'll set the status as Terminated. This will either be transient, as will
// occur when a pod is restarted external to Juju, or permanent if the pod has
// been deleted external to Juju. In the latter case, juju remove-unit will be
// need to clean things up on the Juju side.
cloudContainerStatus := &status.StatusInfo{
Status: status.Terminated,
Message: "unit stopped by the cloud",
}
agentStatus := &status.StatusInfo{
Status: status.Idle,
}
updateProps := state.UnitUpdateProperties{
CloudContainerStatus: cloudContainerStatus,
AgentStatus: agentStatus,
}
unitUpdate.Updates = append(unitUpdate.Updates,
u.UpdateOperation(updateProps))
}
processUnitParams := func(unitParams params.ApplicationUnitParams) *state.UnitUpdateProperties {
agentStatus, cloudContainerStatus := a.updateStatus(unitParams)
return &state.UnitUpdateProperties{
ProviderId: &unitParams.ProviderId,
Address: &unitParams.Address,
Ports: &unitParams.Ports,
AgentStatus: agentStatus,
CloudContainerStatus: cloudContainerStatus,
}
}
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
}
var unitParamsWithFilesystemInfo []params.ApplicationUnitParams
for _, unitParams := range unitInfo.existingCloudPods {
u, ok := unitInfo.stateUnitsInCloud[unitParams.UnitTag]
if !ok {
logger.Warningf("unexpected unit parameters %+v not in state", unitParams)
continue
}
updateProps := processUnitParams(unitParams)
if len(unitParams.FilesystemInfo) > 0 {
unitParamsWithFilesystemInfo = append(unitParamsWithFilesystemInfo, unitParams)
}
unitUpdate.Updates = append(unitUpdate.Updates,
u.UpdateOperation(*updateProps))
}
// For newly added units in the cloud, either update state units which
// exist but which do not yet have provider ids (recording the provider
// id as well), or add a brand new unit.
idx := 0
for _, unitParams := range unitInfo.addedCloudPods {
if idx < len(unitInfo.unassociatedUnits) {
u := unitInfo.unassociatedUnits[idx]
updateProps := processUnitParams(unitParams)
unitUpdate.Updates = append(unitUpdate.Updates,
u.UpdateOperation(*updateProps))
idx++
if len(unitParams.FilesystemInfo) > 0 {
unitParamsWithFilesystemInfo = append(unitParamsWithFilesystemInfo, unitParams)
}
continue
}
// Process units added directly in the cloud instead of via Juju.
updateProps := processUnitParams(unitParams)
if len(unitParams.FilesystemInfo) > 0 {
unitParamsWithFilesystemInfo = append(unitParamsWithFilesystemInfo, unitParams)
}
unitUpdate.Adds = append(unitUpdate.Adds,
app.AddOperation(*updateProps))
}
err := app.UpdateUnits(&unitUpdate)
// We ignore any updates for dying applications.
if state.IsNotAlive(err) {
return nil
}
// Now update filesystem info - attachment data and status.
// For units added to the cloud directly, we first need to lookup the
// newly created unit tag from Juju using the cloud provider ids.
var providerIds []string
for _, unitParams := range unitParamsWithFilesystemInfo {
if unitParams.UnitTag == "" {
providerIds = append(providerIds, unitParams.ProviderId)
}
}
m, err := a.state.Model()
if err != nil {
return errors.Trace(err)
}
var providerIdToUnit = make(map[string]names.UnitTag)
containers, err := m.Containers(providerIds...)
if err != nil {
return errors.Trace(err)
}
for _, c := range containers {
providerIdToUnit[c.ProviderId()] = names.NewUnitTag(c.Unit())
}
processedFilesystemIds := set.NewStrings()