-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.go
3274 lines (3001 loc) · 103 KB
/
application.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package state
import (
stderrors "errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/juju/charm/v7"
csparams "github.com/juju/charmrepo/v5/csclient/params"
"github.com/juju/collections/set"
"github.com/juju/errors"
"github.com/juju/names/v4"
"github.com/juju/os/series"
"github.com/juju/schema"
jujutxn "github.com/juju/txn"
"github.com/juju/utils"
"github.com/juju/version"
"gopkg.in/juju/environschema.v1"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"gopkg.in/mgo.v2/txn"
"github.com/juju/juju/core/application"
"github.com/juju/juju/core/constraints"
"github.com/juju/juju/core/leadership"
"github.com/juju/juju/core/model"
"github.com/juju/juju/core/network"
"github.com/juju/juju/core/status"
mgoutils "github.com/juju/juju/mongo/utils"
"github.com/juju/juju/tools"
)
// Application represents the state of an application.
type Application struct {
st *State
doc applicationDoc
}
// applicationDoc represents the internal state of an application in MongoDB.
// Note the correspondence with ApplicationInfo in apiserver.
type applicationDoc struct {
DocID string `bson:"_id"`
Name string `bson:"name"`
ModelUUID string `bson:"model-uuid"`
Series string `bson:"series"`
Subordinate bool `bson:"subordinate"`
CharmURL *charm.URL `bson:"charmurl"`
Channel string `bson:"cs-channel"`
CharmModifiedVersion int `bson:"charmmodifiedversion"`
ForceCharm bool `bson:"forcecharm"`
Life Life `bson:"life"`
UnitCount int `bson:"unitcount"`
RelationCount int `bson:"relationcount"`
Exposed bool `bson:"exposed"`
MinUnits int `bson:"minunits"`
Tools *tools.Tools `bson:",omitempty"`
TxnRevno int64 `bson:"txn-revno"`
MetricCredentials []byte `bson:"metric-credentials"`
// CAAS related attributes.
DesiredScale int `bson:"scale"`
PasswordHash string `bson:"passwordhash"`
// Placement is the placement directive that should be used allocating units/pods.
Placement string `bson:"placement,omitempty"`
// HasResources is set to false after an application has been removed
// and any k8s cluster resources have been fully cleaned up.
// Until then, the application must not be removed from the Juju model.
HasResources bool `bson:"has-resources,omitempty"`
}
func newApplication(st *State, doc *applicationDoc) *Application {
app := &Application{
st: st,
doc: *doc,
}
return app
}
// IsRemote returns false for a local application.
func (a *Application) IsRemote() bool {
return false
}
// Name returns the application name.
func (a *Application) Name() string {
return a.doc.Name
}
// Tag returns a name identifying the application.
// The returned name will be different from other Tag values returned by any
// other entities from the same state.
func (a *Application) Tag() names.Tag {
return a.ApplicationTag()
}
// ApplicationTag returns the more specific ApplicationTag rather than the generic
// Tag.
func (a *Application) ApplicationTag() names.ApplicationTag {
return names.NewApplicationTag(a.Name())
}
// applicationGlobalKey returns the global database key for the application
// with the given name.
func applicationGlobalKey(appName string) string {
return "a#" + appName
}
// globalKey returns the global database key for the application.
func (a *Application) globalKey() string {
return applicationGlobalKey(a.doc.Name)
}
func applicationGlobalOperatorKey(appName string) string {
return applicationGlobalKey(appName) + "#operator"
}
func applicationCharmConfigKey(appName string, curl *charm.URL) string {
return fmt.Sprintf("a#%s#%s", appName, curl)
}
// charmConfigKey returns the charm-version-specific settings collection
// key for the application.
func (a *Application) charmConfigKey() string {
return applicationCharmConfigKey(a.doc.Name, a.doc.CharmURL)
}
func applicationConfigKey(appName string) string {
return fmt.Sprintf("a#%s#application", appName)
}
// applicationConfigKey returns the charm-version-specific settings collection
// key for the application.
func (a *Application) applicationConfigKey() string {
return applicationConfigKey(a.doc.Name)
}
func applicationStorageConstraintsKey(appName string, curl *charm.URL) string {
return fmt.Sprintf("asc#%s#%s", appName, curl)
}
// storageConstraintsKey returns the charm-version-specific storage
// constraints collection key for the application.
func (a *Application) storageConstraintsKey() string {
return applicationStorageConstraintsKey(a.doc.Name, a.doc.CharmURL)
}
func applicationDeviceConstraintsKey(appName string, curl *charm.URL) string {
return fmt.Sprintf("adc#%s#%s", appName, curl)
}
// deviceConstraintsKey returns the charm-version-specific device
// constraints collection key for the application.
func (a *Application) deviceConstraintsKey() string {
return applicationDeviceConstraintsKey(a.doc.Name, a.doc.CharmURL)
}
// Series returns the specified series for this charm.
func (a *Application) Series() string {
return a.doc.Series
}
// Life returns whether the application is Alive, Dying or Dead.
func (a *Application) Life() Life {
return a.doc.Life
}
// AgentTools returns the tools that the operator is currently running.
// It an error that satisfies errors.IsNotFound if the tools have not
// yet been set.
func (a *Application) AgentTools() (*tools.Tools, error) {
if a.doc.Tools == nil {
return nil, errors.NotFoundf("operator image metadata for application %q", a)
}
result := *a.doc.Tools
return &result, nil
}
// SetAgentVersion sets the Tools value in applicationDoc.
func (a *Application) SetAgentVersion(v version.Binary) (err error) {
defer errors.DeferredAnnotatef(&err, "cannot set agent version for application %q", a)
if err = checkVersionValidity(v); err != nil {
return errors.Trace(err)
}
versionedTool := &tools.Tools{Version: v}
ops := []txn.Op{{
C: applicationsC,
Id: a.doc.DocID,
Assert: notDeadDoc,
Update: bson.D{{"$set", bson.D{{"tools", versionedTool}}}},
}}
if err := a.st.db().RunTransaction(ops); err != nil {
return onAbort(err, ErrDead)
}
a.doc.Tools = versionedTool
return nil
}
var errRefresh = stderrors.New("state seems inconsistent, refresh and try again")
// Destroy ensures that the application and all its relations will be removed at
// some point; if the application has no units, and no relation involving the
// application has any units in scope, they are all removed immediately.
func (a *Application) Destroy() (err error) {
op := a.DestroyOperation()
defer func() {
logger.Tracef("Application(%s).Destroy() => %v", a.doc.Name, err)
if err == nil {
// After running the destroy ops, app life is either Dying,
// or it may be set to Dead. If removed, life will also be marked as Dead.
a.doc.Life = op.PostDestoryAppLife
}
}()
err = a.st.ApplyOperation(op)
if len(op.Errors) != 0 {
logger.Warningf("operational errors destroying application %v: %v", a.Name(), op.Errors)
}
return err
}
// DestroyOperation returns a model operation that will destroy the application.
func (a *Application) DestroyOperation() *DestroyApplicationOperation {
return &DestroyApplicationOperation{
app: &Application{st: a.st, doc: a.doc},
}
}
// DestroyApplicationOperation is a model operation for destroying an
// application.
type DestroyApplicationOperation struct {
// app holds the application to destroy.
app *Application
// DestroyStorage controls whether or not storage attached
// to units of the application are destroyed. If this is false,
// then detachable storage will be detached and left in the model.
DestroyStorage bool
// RemoveOffers controls whether or not application offers
// are removed. If this is false, then the operation will
// fail if there are any offers remaining.
RemoveOffers bool
// CleanupIgnoringResources is true if this operation has been
// scheduled by a forced cleanup task.
CleanupIgnoringResources bool
// PostDestoryAppLife is the life of the app if destroy completes without error.
PostDestoryAppLife Life
// ForcedOperation stores needed information to force this operation.
ForcedOperation
}
// Build is part of the ModelOperation interface.
func (op *DestroyApplicationOperation) Build(attempt int) ([]txn.Op, error) {
if attempt > 0 {
if err := op.app.Refresh(); errors.IsNotFound(err) {
return nil, jujutxn.ErrNoOperations
} else if err != nil {
return nil, err
}
}
// This call returns needed operations to destroy an application.
// All operational errors are added to 'op' struct
// and may be of interest to the user. Without 'force', these errors are considered fatal.
// If 'force' is specified, they are treated as non-fatal - they will not prevent further
// processing: we'll still try to remove application.
ops, err := op.destroyOps()
switch errors.Cause(err) {
case errRefresh:
return nil, jujutxn.ErrTransientFailure
case errAlreadyDying:
return nil, jujutxn.ErrNoOperations
case nil:
if len(op.Errors) == 0 {
return ops, nil
}
if op.Force {
logger.Debugf("forcing application removal")
return ops, nil
}
// Should be impossible to reach as--by convention--we return an error and
// an empty ops slice when a force-able error occurs and we're running !op.Force
err = errors.Errorf("errors encountered: %q", op.Errors)
}
return nil, err
}
// Done is part of the ModelOperation interface.
func (op *DestroyApplicationOperation) Done(err error) error {
if err == nil {
return err
}
connected, err2 := applicationHasConnectedOffers(op.app.st, op.app.Name())
if err2 != nil {
err = errors.Trace(err2)
} else if connected {
rels, err2 := op.app.st.AllRelations()
if err2 != nil {
err = errors.Trace(err2)
} else {
n := 0
for _, r := range rels {
if _, isCrossModel, err := r.RemoteApplication(); err == nil && isCrossModel {
n++
}
}
err = errors.Errorf("application is used by %d consumer%s", n, plural(n))
}
} else {
err = errors.NewNotSupported(err, "change to the application detected")
}
return errors.Annotatef(err, "cannot destroy application %q", op.app)
}
// destroyOps returns the operations required to destroy the application. If it
// returns errRefresh, the application should be refreshed and the destruction
// operations recalculated.
//
// When this operation has 'force' set, all operational errors are considered non-fatal
// and are accumulated on the operation.
// This method will return all operations we can construct despite errors.
//
// When the 'force' is not set, any operational errors will be considered fatal. All operations
// constructed up until the error will be discarded and the error will be returned.
func (op *DestroyApplicationOperation) destroyOps() ([]txn.Op, error) {
rels, err := op.app.Relations()
if op.FatalError(err) {
return nil, err
}
if len(rels) != op.app.doc.RelationCount {
// This is just an early bail out. The relations obtained may still
// be wrong, but that situation will be caught by a combination of
// asserts on relationcount and on each known relation, below.
logger.Tracef("DestroyApplicationOperation(%s).destroyOps mismatched relation count %d != %d",
op.app.doc.Name, len(rels), op.app.doc.RelationCount)
return nil, errRefresh
}
ops := []txn.Op{minUnitsRemoveOp(op.app.st, op.app.doc.Name)}
removeCount := 0
failedRels := false
for _, rel := range rels {
// When forced, this call will return both operations to remove this
// relation as well as all operational errors encountered.
// If the 'force' is not set and the call came across some errors,
// these errors will be fatal and no operations will be returned.
relOps, isRemove, err := rel.destroyOps(op.app.doc.Name, &op.ForcedOperation)
if errors.Cause(err) == errAlreadyDying {
relOps = []txn.Op{{
C: relationsC,
Id: rel.doc.DocID,
Assert: bson.D{{"life", Dying}},
}}
} else if err != nil {
op.AddError(err)
failedRels = true
continue
}
if isRemove {
removeCount++
}
ops = append(ops, relOps...)
}
op.PostDestoryAppLife = Dying
if !op.Force && failedRels {
return nil, op.LastError()
}
resOps, err := removeResourcesOps(op.app.st, op.app.doc.Name)
if op.FatalError(err) {
return nil, errors.Trace(err)
}
ops = append(ops, resOps...)
// We can't delete an application if it is being offered,
// unless those offers have no relations.
if !op.RemoveOffers {
countOp, n, err := countApplicationOffersRefOp(op.app.st, op.app.Name())
if err != nil {
return nil, errors.Trace(err)
}
if n == 0 {
ops = append(ops, countOp)
} else {
connected, err := applicationHasConnectedOffers(op.app.st, op.app.Name())
if err != nil {
return nil, errors.Trace(err)
}
if connected {
return nil, errors.Errorf("application is used by %d offer%s", n, plural(n))
}
// None of our offers are connected,
// it's safe to remove them.
removeOfferOps, err := removeApplicationOffersOps(op.app.st, op.app.Name())
if err != nil {
return nil, errors.Trace(err)
}
ops = append(ops, removeOfferOps...)
ops = append(ops, txn.Op{
C: applicationsC,
Id: op.app.doc.DocID,
Assert: bson.D{
// We're using the txn-revno here because relationcount is too
// coarse-grained for what we need. Using the revno will
// create false positives during concurrent updates of the
// model, but eliminates the possibility of it entering
// an inconsistent state.
{"txn-revno", op.app.doc.TxnRevno},
},
})
}
}
branchOps, err := op.unassignBranchOps()
if err != nil {
if !op.Force {
return nil, errors.Trace(err)
}
op.AddError(err)
}
ops = append(ops, branchOps...)
// If the application has no units, and all its known relations will be
// removed, the application can also be removed, so long as there are
// no other cluster resources, as can be the case for k8s charms.
if op.app.doc.UnitCount == 0 && op.app.doc.RelationCount == removeCount {
logger.Tracef("DestroyApplicationOperation(%s).destroyOps removing application", op.app.doc.Name)
// If we're forcing destruction the assertion shouldn't be that
// life is alive, but that it's what we think it is now.
assertion := bson.D{
{"life", op.app.doc.Life},
{"unitcount", 0},
{"relationcount", removeCount},
}
// There are resources pending so don't remove app yet.
if op.app.doc.HasResources && !op.CleanupIgnoringResources {
if op.Force {
// We need to wait longer than normal for any k8s resources to be fully removed
// since it can take a while for the cluster to terminate rnning pods etc.
logger.Debugf("scheduling forced application %q cleanup", op.app.doc.Name)
deadline := op.app.st.stateClock.Now().Add(2 * op.MaxWait)
cleanupOp := newCleanupAtOp(deadline, cleanupForceApplication, op.app.doc.Name, op.MaxWait)
ops = append(ops, cleanupOp)
}
logger.Debugf("advancing application %q to dead, waiting for cluster resources", op.app.doc.Name)
update := bson.D{{"$set", bson.D{{"life", Dead}}}}
if removeCount != 0 {
decref := bson.D{{"$inc", bson.D{{"relationcount", -removeCount}}}}
update = append(update, decref...)
}
advanceLifecycleOp := txn.Op{
C: applicationsC,
Id: op.app.doc.DocID,
Assert: assertion,
Update: update,
}
op.PostDestoryAppLife = Dead
return append(ops, advanceLifecycleOp), nil
}
// When forced, this call will return operations to remove this
// application and accumulate all operational errors encountered in the operation.
// If the 'force' is not set and the call came across some errors,
// these errors will be fatal and no operations will be returned.
removeOps, err := op.app.removeOps(assertion, &op.ForcedOperation)
if err != nil {
if !op.Force || errors.Cause(err) == errRefresh {
return nil, errors.Trace(err)
}
op.AddError(err)
return ops, nil
}
return append(ops, removeOps...), nil
}
// In all other cases, application removal will be handled as a consequence
// of the removal of the last unit or relation referencing it. If any
// relations have been removed, they'll be caught by the operations
// collected above; but if any has been added, we need to abort and add
// a destroy op for that relation too. In combination, it's enough to
// check for count equality: an add/remove will not touch the count, but
// will be caught by virtue of being a remove.
notLastRefs := bson.D{
{"life", op.app.doc.Life},
{"relationcount", op.app.doc.RelationCount},
}
// With respect to unit count, a changing value doesn't matter, so long
// as the count's equality with zero does not change, because all we care
// about is that *some* unit is, or is not, keeping the application from
// being removed: the difference between 1 unit and 1000 is irrelevant.
if op.app.doc.UnitCount > 0 {
logger.Tracef("DestroyApplicationOperation(%s).destroyOps UnitCount == %d, queuing up unitCleanup",
op.app.doc.Name, op.app.doc.UnitCount)
cleanupOp := newCleanupOp(
cleanupUnitsForDyingApplication,
op.app.doc.Name,
op.DestroyStorage,
op.Force,
op.MaxWait,
)
ops = append(ops, cleanupOp)
notLastRefs = append(notLastRefs, bson.D{{"unitcount", bson.D{{"$gt", 0}}}}...)
} else {
notLastRefs = append(notLastRefs, bson.D{{"unitcount", 0}}...)
}
update := bson.D{{"$set", bson.D{{"life", Dying}}}}
if removeCount != 0 {
decref := bson.D{{"$inc", bson.D{{"relationcount", -removeCount}}}}
update = append(update, decref...)
}
ops = append(ops, txn.Op{
C: applicationsC,
Id: op.app.doc.DocID,
Assert: notLastRefs,
Update: update,
})
return ops, nil
}
func (op *DestroyApplicationOperation) unassignBranchOps() ([]txn.Op, error) {
m, err := op.app.st.Model()
if err != nil {
return nil, errors.Trace(err)
}
appName := op.app.doc.Name
branches, err := m.applicationBranches(appName)
if err != nil {
return nil, errors.Trace(err)
}
if len(branches) == 0 {
return nil, nil
}
ops := []txn.Op{}
for _, b := range branches {
// assumption: branches from applicationBranches will
// ALWAYS have the appName in assigned-units, but not
// always in config.
ops = append(ops, b.unassignAppOps(appName)...)
}
return ops, nil
}
func removeResourcesOps(st *State, applicationID string) ([]txn.Op, error) {
persist, err := st.ResourcesPersistence()
if errors.IsNotSupported(err) {
// Nothing to see here, move along.
return nil, nil
}
if err != nil {
return nil, errors.Trace(err)
}
ops, err := persist.NewRemoveResourcesOps(applicationID)
if err != nil {
return nil, errors.Trace(err)
}
return ops, nil
}
// removeOps returns the operations required to remove the application. Supplied
// asserts will be included in the operation on the application document.
// When force is set, the operation will proceed regardless of the errors,
// and if any errors are encountered, all possible accumulated operations
// as well as all encountered errors will be returned.
// When 'force' is set, this call will return operations to remove this
// application and will accumulate all operational errors encountered in the operation.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
func (a *Application) removeOps(asserts bson.D, op *ForcedOperation) ([]txn.Op, error) {
ops := []txn.Op{{
C: applicationsC,
Id: a.doc.DocID,
Assert: asserts,
Remove: true,
}}
// Remove application offers.
removeOfferOps, err := removeApplicationOffersOps(a.st, a.doc.Name)
if op.FatalError(err) {
return nil, errors.Trace(err)
}
ops = append(ops, removeOfferOps...)
// Note that appCharmDecRefOps might not catch the final decref
// when run in a transaction that decrefs more than once. So we
// avoid attempting to do the final cleanup in the ref dec ops and
// do it explicitly below.
name := a.doc.Name
curl := a.doc.CharmURL
// When 'force' is set, this call will return operations to delete application references
// to this charm as well as accumulate all operational errors encountered in the operation.
// If the 'force' is not set, any error will be fatal and no operations will be returned.
charmOps, err := appCharmDecRefOps(a.st, name, curl, false, op)
if err != nil {
if errors.Cause(err) == errRefcountAlreadyZero {
// We have already removed the reference to the charm, this indicates
// the application is already removed, reload yourself and try again
return nil, errRefresh
}
if op.FatalError(err) {
return nil, errors.Trace(err)
}
}
ops = append(ops, charmOps...)
// By the time we get to here, all units and charm refs have been removed,
// so it's safe to do this additional cleanup.
ops = append(ops, finalAppCharmRemoveOps(name, curl)...)
ops = append(ops, a.removeCloudServiceOps()...)
globalKey := a.globalKey()
ops = append(ops,
removeEndpointBindingsOp(globalKey),
removeConstraintsOp(globalKey),
annotationRemoveOp(a.st, globalKey),
removeLeadershipSettingsOp(name),
removeStatusOp(a.st, globalKey),
removeStatusOp(a.st, applicationGlobalOperatorKey(name)),
removeSettingsOp(settingsC, a.applicationConfigKey()),
removeModelApplicationRefOp(a.st, name),
removePodSpecOp(a.ApplicationTag()),
)
return ops, nil
}
// IsExposed returns whether this application is exposed. The explicitly open
// ports (with open-port) for exposed applications may be accessed from machines
// outside of the local deployment network. See SetExposed and ClearExposed.
func (a *Application) IsExposed() bool {
return a.doc.Exposed
}
// SetExposed marks the application as exposed.
// See ClearExposed and IsExposed.
func (a *Application) SetExposed() error {
return a.setExposed(true)
}
// ClearExposed removes the exposed flag from the application.
// See SetExposed and IsExposed.
func (a *Application) ClearExposed() error {
return a.setExposed(false)
}
func (a *Application) setExposed(exposed bool) (err error) {
ops := []txn.Op{{
C: applicationsC,
Id: a.doc.DocID,
Assert: isAliveDoc,
Update: bson.D{{"$set", bson.D{{"exposed", exposed}}}},
}}
if err := a.st.db().RunTransaction(ops); err != nil {
return errors.Errorf("cannot set exposed flag for application %q to %v: %v", a, exposed, onAbort(err, applicationNotAliveErr))
}
a.doc.Exposed = exposed
return nil
}
// Charm returns the application's charm and whether units should upgrade to that
// charm even if they are in an error state.
func (a *Application) Charm() (ch *Charm, force bool, err error) {
// We don't worry about the channel since we aren't interacting
// with the charm store here.
ch, err = a.st.Charm(a.doc.CharmURL)
if err != nil {
return nil, false, err
}
return ch, a.doc.ForceCharm, nil
}
// IsPrincipal returns whether units of the application can
// have subordinate units.
func (a *Application) IsPrincipal() bool {
return !a.doc.Subordinate
}
// CharmModifiedVersion increases whenever the application's charm is changed in any
// way.
func (a *Application) CharmModifiedVersion() int {
return a.doc.CharmModifiedVersion
}
// CharmURL returns the application's charm URL, and whether units should upgrade
// to the charm with that URL even if they are in an error state.
func (a *Application) CharmURL() (curl *charm.URL, force bool) {
return a.doc.CharmURL, a.doc.ForceCharm
}
// Channel identifies the charm store channel from which the application's
// charm was deployed. It is only needed when interacting with the charm
// store.
func (a *Application) Channel() csparams.Channel {
return csparams.Channel(a.doc.Channel)
}
// Endpoints returns the application's currently available relation endpoints.
func (a *Application) Endpoints() (eps []Endpoint, err error) {
ch, _, err := a.Charm()
if err != nil {
return nil, err
}
collect := func(role charm.RelationRole, rels map[string]charm.Relation) {
for _, rel := range rels {
eps = append(eps, Endpoint{
ApplicationName: a.doc.Name,
Relation: rel,
})
}
}
meta := ch.Meta()
collect(charm.RolePeer, meta.Peers)
collect(charm.RoleProvider, meta.Provides)
collect(charm.RoleRequirer, meta.Requires)
collect(charm.RoleProvider, map[string]charm.Relation{
"juju-info": {
Name: "juju-info",
Role: charm.RoleProvider,
Interface: "juju-info",
Scope: charm.ScopeGlobal,
},
})
sort.Sort(epSlice(eps))
return eps, nil
}
// Endpoint returns the relation endpoint with the supplied name, if it exists.
func (a *Application) Endpoint(relationName string) (Endpoint, error) {
eps, err := a.Endpoints()
if err != nil {
return Endpoint{}, err
}
for _, ep := range eps {
if ep.Name == relationName {
return ep, nil
}
}
return Endpoint{}, errors.Errorf("application %q has no %q relation", a, relationName)
}
// extraPeerRelations returns only the peer relations in newMeta not
// present in the application's current charm meta data.
func (a *Application) extraPeerRelations(newMeta *charm.Meta) map[string]charm.Relation {
if newMeta == nil {
// This should never happen, since we're checking the charm in SetCharm already.
panic("newMeta is nil")
}
ch, _, err := a.Charm()
if err != nil {
return nil
}
newPeers := newMeta.Peers
oldPeers := ch.Meta().Peers
extraPeers := make(map[string]charm.Relation)
for relName, rel := range newPeers {
if _, ok := oldPeers[relName]; !ok {
extraPeers[relName] = rel
}
}
return extraPeers
}
func (a *Application) checkRelationsOps(ch *Charm, relations []*Relation) ([]txn.Op, error) {
asserts := make([]txn.Op, 0, len(relations))
isPeerToItself := func(ep Endpoint) bool {
// We do not want to prevent charm upgrade when endpoint relation is
// peer-scoped and there is only one unit of this application.
// Essentially, this is the corner case when a unit relates to itself.
// For example, in this case, we want to allow charm upgrade, for e.g.
// interface name change does not affect anything.
units, err := a.AllUnits()
if err != nil {
// Whether we could get application units does not matter.
// We are only interested in thinking further if we can get units.
return false
}
return len(units) == 1 && isPeer(ep)
}
// All relations must still exist and their endpoints are implemented by the charm.
for _, rel := range relations {
if ep, err := rel.Endpoint(a.doc.Name); err != nil {
return nil, err
} else if !ep.ImplementedBy(ch) {
if !isPeerToItself(ep) {
return nil, errors.Errorf("would break relation %q", rel)
}
}
asserts = append(asserts, txn.Op{
C: relationsC,
Id: rel.doc.DocID,
Assert: txn.DocExists,
})
}
return asserts, nil
}
func (a *Application) checkStorageUpgrade(newMeta, oldMeta *charm.Meta, units []*Unit) (_ []txn.Op, err error) {
// Make sure no storage instances are added or removed.
sb, err := NewStorageBackend(a.st)
if err != nil {
return nil, errors.Trace(err)
}
var ops []txn.Op
for name, oldStorageMeta := range oldMeta.Storage {
if _, ok := newMeta.Storage[name]; ok {
continue
}
if oldStorageMeta.CountMin > 0 {
return nil, errors.Errorf("required storage %q removed", name)
}
// Optional storage has been removed. So long as there
// are no instances of the store, it can safely be
// removed.
if oldStorageMeta.Shared {
op, n, err := sb.countEntityStorageInstances(a.Tag(), name)
if err != nil {
return nil, errors.Trace(err)
}
if n > 0 {
return nil, errors.Errorf("in-use storage %q removed", name)
}
ops = append(ops, op)
} else {
for _, u := range units {
op, n, err := sb.countEntityStorageInstances(u.Tag(), name)
if err != nil {
return nil, errors.Trace(err)
}
if n > 0 {
return nil, errors.Errorf("in-use storage %q removed", name)
}
ops = append(ops, op)
}
}
}
less := func(a, b int) bool {
return a != -1 && (b == -1 || a < b)
}
for name, newStorageMeta := range newMeta.Storage {
oldStorageMeta, ok := oldMeta.Storage[name]
if !ok {
continue
}
if newStorageMeta.Type != oldStorageMeta.Type {
return nil, errors.Errorf(
"existing storage %q type changed from %q to %q",
name, oldStorageMeta.Type, newStorageMeta.Type,
)
}
if newStorageMeta.Shared != oldStorageMeta.Shared {
return nil, errors.Errorf(
"existing storage %q shared changed from %v to %v",
name, oldStorageMeta.Shared, newStorageMeta.Shared,
)
}
if newStorageMeta.ReadOnly != oldStorageMeta.ReadOnly {
return nil, errors.Errorf(
"existing storage %q read-only changed from %v to %v",
name, oldStorageMeta.ReadOnly, newStorageMeta.ReadOnly,
)
}
if newStorageMeta.Location != oldStorageMeta.Location {
return nil, errors.Errorf(
"existing storage %q location changed from %q to %q",
name, oldStorageMeta.Location, newStorageMeta.Location,
)
}
if less(newStorageMeta.CountMax, oldStorageMeta.CountMax) {
var oldCountMax interface{} = oldStorageMeta.CountMax
if oldStorageMeta.CountMax == -1 {
oldCountMax = "<unbounded>"
}
return nil, errors.Errorf(
"existing storage %q range contracted: max decreased from %v to %d",
name, oldCountMax, newStorageMeta.CountMax,
)
}
if oldStorageMeta.Location != "" && oldStorageMeta.CountMax == 1 && newStorageMeta.CountMax != 1 {
// If a location is specified, the store may not go
// from being a singleton to multiple, since then the
// location has a different meaning.
return nil, errors.Errorf(
"existing storage %q with location changed from single to multiple",
name,
)
}
}
return ops, nil
}
// changeCharmOps returns the operations necessary to set a application's
// charm URL to a new value.
func (a *Application) changeCharmOps(
ch *Charm,
channel string,
updatedSettings charm.Settings,
forceUnits bool,
resourceIDs map[string]string,
updatedStorageConstraints map[string]StorageConstraints,
) ([]txn.Op, error) {
// Build the new application config from what can be used of the old one.
var newSettings charm.Settings
oldKey, err := readSettings(a.st.db(), settingsC, a.charmConfigKey())
if err == nil {
// Filter the old settings through to get the new settings.
newSettings = ch.Config().FilterSettings(oldKey.Map())
for k, v := range updatedSettings {
newSettings[k] = v
}
} else if errors.IsNotFound(err) {
// No old settings, start with the updated settings.
newSettings = updatedSettings
} else {
return nil, errors.Annotatef(err, "application %q", a.doc.Name)
}
// Create or replace application settings.
var settingsOp txn.Op
newSettingsKey := applicationCharmConfigKey(a.doc.Name, ch.URL())
if _, err := readSettings(a.st.db(), settingsC, newSettingsKey); errors.IsNotFound(err) {
// No settings for this key yet, create it.
settingsOp = createSettingsOp(settingsC, newSettingsKey, newSettings)
} else if err != nil {
return nil, errors.Annotatef(err, "application %q", a.doc.Name)
} else {
// Settings exist, just replace them with the new ones.
settingsOp, _, err = replaceSettingsOp(a.st.db(), settingsC, newSettingsKey, newSettings)
if err != nil {
return nil, errors.Annotatef(err, "application %q", a.doc.Name)
}
}
// Make sure no units are added or removed while the upgrade
// transaction is being executed. This allows us to make
// changes to units during the upgrade, e.g. add storage
// to existing units, or remove optional storage so long as
// it is unreferenced.
units, err := a.AllUnits()
if err != nil {
return nil, errors.Trace(err)
}
unitOps := make([]txn.Op, len(units))
for i, u := range units {
unitOps[i] = txn.Op{
C: unitsC,
Id: u.doc.DocID,
Assert: txn.DocExists,
}
}
unitOps = append(unitOps, txn.Op{
C: applicationsC,
Id: a.doc.DocID,
Assert: bson.D{{"unitcount", len(units)}},
})
checkStorageOps, upgradeStorageOps, storageConstraintsOps, err := a.newCharmStorageOps(ch, units, updatedStorageConstraints)
if err != nil {
return nil, errors.Trace(err)
}
// Add or create a reference to the new charm, settings,
// and storage constraints docs.
incOps, err := appCharmIncRefOps(a.st, a.doc.Name, ch.URL(), true)
if err != nil {
return nil, errors.Trace(err)
}
var decOps []txn.Op
// Drop the references to the old settings, storage constraints,
// and charm docs (if the refs actually exist yet).
if oldKey != nil {
// Since we can force this now, let's.. There is no point hanging on
// to the old key.
op := &ForcedOperation{Force: true}
decOps, err = appCharmDecRefOps(a.st, a.doc.Name, a.doc.CharmURL, true, op) // current charm
if err != nil {
return nil, errors.Annotatef(err, "could not remove old charm references for %v", oldKey)
}
if len(op.Errors) != 0 {
logger.Errorf("could not remove old charm references for %v:%v", oldKey, op.Errors)
}
}
// Build the transaction.
var ops []txn.Op
if oldKey != nil {
// Old settings shouldn't change (when they exist).
ops = append(ops, oldKey.assertUnchangedOp())
}
ops = append(ops, unitOps...)
ops = append(ops, incOps...)
ops = append(ops, []txn.Op{
// Create or replace new settings.
settingsOp,