forked from juju/juju
/
crossmodel.go
581 lines (532 loc) · 18 KB
/
crossmodel.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
// Copyright 2017 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package crossmodel
import (
"fmt"
"net"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/names/v4"
"github.com/DavinZhang/juju/apiserver/common"
"github.com/DavinZhang/juju/apiserver/params"
"github.com/DavinZhang/juju/core/cache"
"github.com/DavinZhang/juju/core/crossmodel"
"github.com/DavinZhang/juju/core/life"
"github.com/DavinZhang/juju/core/network/firewall"
"github.com/DavinZhang/juju/core/status"
"github.com/DavinZhang/juju/network"
)
var logger = loggo.GetLogger("juju.apiserver.common.crossmodel")
// PublishRelationChange applies the relation change event to the specified backend.
func PublishRelationChange(backend Backend, relationTag names.Tag, change params.RemoteRelationChangeEvent) error {
logger.Debugf("publish into model %v change for %v: %+v", backend.ModelUUID(), relationTag, change)
dyingOrDead := change.Life != "" && change.Life != life.Alive
// Ensure the relation exists.
rel, err := backend.KeyRelation(relationTag.Id())
if errors.IsNotFound(err) {
if dyingOrDead {
return nil
}
}
if err != nil {
return errors.Trace(err)
}
if err := handleSuspendedRelation(change, rel, dyingOrDead); err != nil {
return errors.Trace(err)
}
// Look up the application on the remote side of this relation
// ie from the model which published this change.
applicationTag, err := backend.GetRemoteEntity(change.ApplicationToken)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
logger.Debugf("application tag for token %+v is %v in model %v", change.ApplicationToken, applicationTag, backend.ModelUUID())
// If the remote model has destroyed the relation, do it here also.
forceCleanUp := change.ForceCleanup != nil && *change.ForceCleanup
if dyingOrDead {
logger.Debugf("remote consuming side of %v died", relationTag)
if forceCleanUp && applicationTag != nil {
logger.Debugf("forcing cleanup of units for %v", applicationTag.Id())
remoteUnits, err := rel.AllRemoteUnits(applicationTag.Id())
if err != nil {
return errors.Trace(err)
}
logger.Debugf("got %v relation units to clean", len(remoteUnits))
for _, ru := range remoteUnits {
if err := ru.LeaveScope(); err != nil {
return errors.Trace(err)
}
}
}
if forceCleanUp {
oppErrs, err := rel.DestroyWithForce(true, 0)
if len(oppErrs) > 0 {
logger.Warningf("errors forcing cleanup of %v: %v", rel.Tag().Id(), oppErrs)
}
// If we are forcing cleanup, we can exit early here.
return errors.Trace(err)
}
if err := rel.Destroy(); err != nil {
return errors.Trace(err)
}
}
// TODO(wallyworld) - deal with remote application being removed
if applicationTag == nil {
logger.Infof("no remote application found for %v", relationTag.Id())
return nil
}
logger.Debugf("remote application for changed relation %v is %v in model %v",
relationTag.Id(), applicationTag.Id(), backend.ModelUUID())
// Allow sending an empty non-nil map to clear all the settings.
if change.ApplicationSettings != nil {
logger.Debugf("remote application %v in %v settings changed to %v",
applicationTag.Id(), relationTag.Id(), change.ApplicationSettings)
err := rel.ReplaceApplicationSettings(applicationTag.Id(), change.ApplicationSettings)
if err != nil {
return errors.Trace(err)
}
}
if err := handleDepartedUnits(change, applicationTag, rel); err != nil {
return errors.Trace(err)
}
return errors.Trace(handleChangedUnits(change, applicationTag, rel))
}
func handleSuspendedRelation(change params.RemoteRelationChangeEvent, rel Relation, dyingOrDead bool) error {
// Update the relation suspended status.
currentStatus := rel.Suspended()
if !dyingOrDead && change.Suspended != nil && currentStatus != *change.Suspended {
var (
newStatus status.Status
message string
)
if *change.Suspended {
newStatus = status.Suspending
message = change.SuspendedReason
if message == "" {
message = "suspending after update from remote model"
}
}
if err := rel.SetSuspended(*change.Suspended, message); err != nil {
return errors.Trace(err)
}
if !*change.Suspended {
newStatus = status.Joining
message = ""
}
if err := rel.SetStatus(status.StatusInfo{
Status: newStatus,
Message: message,
}); err != nil && !errors.IsNotValid(err) {
return errors.Trace(err)
}
}
return nil
}
func handleDepartedUnits(change params.RemoteRelationChangeEvent, applicationTag names.Tag, rel Relation) error {
for _, id := range change.DepartedUnits {
unitTag := names.NewUnitTag(fmt.Sprintf("%s/%v", applicationTag.Id(), id))
logger.Debugf("unit %v has departed relation %v", unitTag.Id(), rel.Tag().Id())
ru, err := rel.RemoteUnit(unitTag.Id())
if err != nil {
return errors.Trace(err)
}
logger.Debugf("%s leaving scope", unitTag.Id())
if err := ru.LeaveScope(); err != nil {
return errors.Trace(err)
}
}
return nil
}
func handleChangedUnits(change params.RemoteRelationChangeEvent, applicationTag names.Tag, rel Relation) error {
for _, change := range change.ChangedUnits {
unitTag := names.NewUnitTag(fmt.Sprintf("%s/%v", applicationTag.Id(), change.UnitId))
logger.Debugf("changed unit tag for unit id %v is %v", change.UnitId, unitTag)
ru, err := rel.RemoteUnit(unitTag.Id())
if err != nil {
return errors.Trace(err)
}
inScope, err := ru.InScope()
if err != nil {
return errors.Trace(err)
}
settings := make(map[string]interface{})
for k, v := range change.Settings {
settings[k] = v
}
if !inScope {
logger.Debugf("%s entering scope (%v)", unitTag.Id(), settings)
err = ru.EnterScope(settings)
} else {
logger.Debugf("%s updated settings (%v)", unitTag.Id(), settings)
err = ru.ReplaceSettings(settings)
}
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// GetOfferingRelationTokens returns the tokens for the relation and the offer
// of the passed in relation tag.
func GetOfferingRelationTokens(backend Backend, tag names.RelationTag) (string, string, error) {
offerName, err := backend.OfferNameForRelation(tag.Id())
if err != nil {
return "", "", errors.Annotatef(err, "getting offer for relation %q", tag.Id())
}
relationToken, err := backend.GetToken(tag)
if err != nil {
return "", "", errors.Annotatef(err, "getting token for relation %q", tag.Id())
}
appToken, err := backend.GetToken(names.NewApplicationTag(offerName))
if err != nil {
return "", "", errors.Annotatef(err, "getting token for application %q", offerName)
}
return relationToken, appToken, nil
}
// GetConsumingRelationTokens returns the tokens for the relation and the local
// application of the passed in relation tag.
func GetConsumingRelationTokens(backend Backend, tag names.RelationTag) (string, string, error) {
relation, err := backend.KeyRelation(tag.Id())
if err != nil {
return "", "", errors.Annotatef(err, "getting relation for %q", tag.Id())
}
localAppName, err := getLocalApplicationName(backend, relation)
if err != nil {
return "", "", errors.Annotatef(err, "getting local application for relation %q", tag.Id())
}
relationToken, err := backend.GetToken(tag)
if err != nil {
return "", "", errors.Annotatef(err, "getting consuming token for relation %q", tag.Id())
}
appToken, err := backend.GetToken(names.NewApplicationTag(localAppName))
if err != nil {
return "", "", errors.Annotatef(err, "getting consuming token for application %q", localAppName)
}
return relationToken, appToken, nil
}
func getLocalApplicationName(backend Backend, relation Relation) (string, error) {
for _, ep := range relation.Endpoints() {
_, err := backend.Application(ep.ApplicationName)
if errors.IsNotFound(err) {
// Not found, so it's the remote application. Try the next endpoint.
continue
} else if err != nil {
return "", errors.Trace(err)
}
return ep.ApplicationName, nil
}
return "", errors.NotFoundf("local application for %s", names.ReadableString(relation.Tag()))
}
// WatchRelationUnits returns a watcher for changes to the units on the specified relation.
func WatchRelationUnits(backend Backend, tag names.RelationTag) (common.RelationUnitsWatcher, error) {
relation, err := backend.KeyRelation(tag.Id())
if err != nil {
return nil, errors.Annotatef(err, "getting relation for %q", tag.Id())
}
localAppName, err := getLocalApplicationName(backend, relation)
if err != nil {
return nil, errors.Annotatef(err, "getting local application for relation %q", tag.Id())
}
w, err := relation.WatchUnits(localAppName)
if err != nil {
return nil, errors.Annotatef(err, "watching units for %q", localAppName)
}
wrapped, err := common.RelationUnitsWatcherFromState(w)
if err != nil {
return nil, errors.Annotatef(err, "getting relation units watcher for %q", tag.Id())
}
return wrapped, nil
}
// ExpandChange converts a params.RelationUnitsChange into a
// params.RemoteRelationChangeEvent by filling out the extra
// information from the passed backend. This takes relation and
// application token so that it can still return sensible results if
// the relation has been removed (just departing units).
func ExpandChange(
backend Backend,
relationToken string,
appToken string,
change params.RelationUnitsChange,
) (params.RemoteRelationChangeEvent, error) {
var empty params.RemoteRelationChangeEvent
var departed []int
for _, unitName := range change.Departed {
num, err := names.UnitNumber(unitName)
if err != nil {
return empty, errors.Trace(err)
}
departed = append(departed, num)
}
relationTag, err := backend.GetRemoteEntity(relationToken)
if errors.IsNotFound(err) {
// This can happen when the last unit leaves scope on a dying
// relation and the relation is removed. In that case there
// aren't any application- or unit-level settings to send; we
// just send the departed units so they can leave scope on
// the other side of a cross-model relation.
return params.RemoteRelationChangeEvent{
RelationToken: relationToken,
ApplicationToken: appToken,
DepartedUnits: departed,
}, nil
} else if err != nil {
return empty, errors.Trace(err)
}
relation, err := backend.KeyRelation(relationTag.Id())
if err != nil {
return empty, errors.Trace(err)
}
localAppName, err := getLocalApplicationName(backend, relation)
if err != nil {
return empty, errors.Trace(err)
}
var appSettings map[string]interface{}
if len(change.AppChanged) > 0 {
appSettings, err = relation.ApplicationSettings(localAppName)
if err != nil {
return empty, errors.Trace(err)
}
}
var unitChanges []params.RemoteRelationUnitChange
for unitName := range change.Changed {
relUnit, err := relation.Unit(unitName)
if err != nil {
return empty, errors.Annotatef(err, "getting unit %q in %q", unitName, relationTag.Id())
}
unitSettings, err := relUnit.Settings()
if err != nil {
return empty, errors.Annotatef(err, "getting settings for %q in %q", unitName, relationTag.Id())
}
num, err := names.UnitNumber(unitName)
if err != nil {
return empty, errors.Trace(err)
}
unitChanges = append(unitChanges, params.RemoteRelationUnitChange{
UnitId: num,
Settings: unitSettings,
})
}
uc := relation.UnitCount()
result := params.RemoteRelationChangeEvent{
RelationToken: relationToken,
ApplicationToken: appToken,
ApplicationSettings: appSettings,
ChangedUnits: unitChanges,
DepartedUnits: departed,
UnitCount: &uc,
}
return result, nil
}
// WrappedUnitsWatcher is a relation units watcher that remembers
// details about the relation it came from so changes can be expanded
// for sending outside this model.
type WrappedUnitsWatcher struct {
common.RelationUnitsWatcher
RelationToken string
ApplicationToken string
}
// RelationUnitSettings returns the unit settings for the specified relation unit.
func RelationUnitSettings(backend Backend, ru params.RelationUnit) (params.Settings, error) {
relationTag, err := names.ParseRelationTag(ru.Relation)
if err != nil {
return nil, errors.Trace(err)
}
rel, err := backend.KeyRelation(relationTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
unitTag, err := names.ParseUnitTag(ru.Unit)
if err != nil {
return nil, errors.Trace(err)
}
unit, err := rel.Unit(unitTag.Id())
if err != nil {
return nil, errors.Trace(err)
}
settings, err := unit.Settings()
if err != nil {
return nil, errors.Trace(err)
}
paramsSettings := make(params.Settings)
for k, v := range settings {
vString, ok := v.(string)
if !ok {
return nil, errors.Errorf(
"invalid relation setting %q: expected string, got %T", k, v,
)
}
paramsSettings[k] = vString
}
return paramsSettings, nil
}
// PublishIngressNetworkChange saves the specified ingress networks for a relation.
func PublishIngressNetworkChange(backend Backend, relationTag names.Tag, change params.IngressNetworksChangeEvent) error {
logger.Debugf("publish into model %v network change for %v: %+v", backend.ModelUUID(), relationTag, change)
// Ensure the relation exists.
rel, err := backend.KeyRelation(relationTag.Id())
if errors.IsNotFound(err) {
return nil
}
if err != nil {
return errors.Trace(err)
}
logger.Debugf("relation %v requires ingress networks %v", rel, change.Networks)
if err := validateIngressNetworks(backend, change.Networks); err != nil {
return errors.Trace(err)
}
_, err = backend.SaveIngressNetworks(rel.Tag().Id(), change.Networks)
return err
}
func validateIngressNetworks(backend Backend, networks []string) error {
if len(networks) == 0 {
return nil
}
// Check that the required ingress is allowed.
rule, err := backend.FirewallRule(firewall.JujuApplicationOfferRule)
if err != nil && !errors.IsNotFound(err) {
return errors.Trace(err)
}
if errors.IsNotFound(err) {
return nil
}
var whitelistCIDRs, requestedCIDRs []*net.IPNet
if err := parseCIDRs(&whitelistCIDRs, rule.WhitelistCIDRs()); err != nil {
return errors.Trace(err)
}
if err := parseCIDRs(&requestedCIDRs, networks); err != nil {
return errors.Trace(err)
}
if len(whitelistCIDRs) > 0 {
for _, n := range requestedCIDRs {
if !network.SubnetInAnyRange(whitelistCIDRs, n) {
return ¶ms.Error{
Code: params.CodeForbidden,
Message: fmt.Sprintf("subnet %v not in firewall whitelist", n),
}
}
}
}
return nil
}
func parseCIDRs(cidrs *[]*net.IPNet, values []string) error {
for _, cidrStr := range values {
if _, ipNet, err := net.ParseCIDR(cidrStr); err != nil {
return err
} else {
*cidrs = append(*cidrs, ipNet)
}
}
return nil
}
type relationGetter interface {
// KeyRelation returns the relation identified by the input key.
KeyRelation(string) (Relation, error)
// IsMigrationActive returns true if the current model is
// in the process of being migrated to another controller.
IsMigrationActive() (bool, error)
}
// GetRelationLifeSuspendedStatusChange returns a life/suspended status change
// struct for a specified relation key.
func GetRelationLifeSuspendedStatusChange(
st relationGetter, key string,
) (*params.RelationLifeSuspendedStatusChange, error) {
rel, err := st.KeyRelation(key)
if errors.IsNotFound(err) {
// If the relation is not found we represent it as dead,
// but *only* if we are not currently migrating.
// If we are migrating, we do not want to inform remote watchers that
// the relation is dead before they have had a chance to be redirected
// to the new controller.
if migrating, mErr := st.IsMigrationActive(); mErr == nil && !migrating {
return ¶ms.RelationLifeSuspendedStatusChange{
Key: key,
Life: life.Dead,
}, nil
} else if mErr != nil {
err = mErr
}
}
if err != nil {
return nil, errors.Trace(err)
}
return ¶ms.RelationLifeSuspendedStatusChange{
Key: key,
Life: life.Value(rel.Life().String()),
Suspended: rel.Suspended(),
SuspendedReason: rel.SuspendedReason(),
}, nil
}
type offerGetter interface {
ApplicationOfferForUUID(string) (*crossmodel.ApplicationOffer, error)
Application(string) (Application, error)
}
// CachedModel represents the methods that the StatusAPI needs on a
// model from the model cache.
type CachedModel interface {
Application(string) (CachedApplication, error)
}
// CachedApplication represents the methods that the StatusAPI needs on
// an application from the model cache.
type CachedApplication interface {
Status() status.StatusInfo
}
// GetOfferStatusChange returns a status change
// struct for a specified offer name.
func GetOfferStatusChange(model CachedModel, st offerGetter, offerUUID, offerName string) (*params.OfferStatusChange, error) {
offer, err := st.ApplicationOfferForUUID(offerUUID)
if errors.IsNotFound(err) {
return ¶ms.OfferStatusChange{
OfferName: offerName,
Status: params.EntityStatus{
Status: status.Terminated,
Info: "offer has been removed",
},
}, nil
} else if err != nil {
return nil, errors.Trace(err)
}
// TODO(wallyworld) - for now, offer status is just the application status
app, err := st.Application(offer.ApplicationName)
if errors.IsNotFound(err) {
return ¶ms.OfferStatusChange{
OfferName: offerName,
Status: params.EntityStatus{
Status: status.Terminated,
Info: "application has been removed",
},
}, nil
} else if err != nil {
return nil, errors.Trace(err)
}
// We use the status from the cached application as that is where
// the derived status from the units are handled if this is necessary.
sts := status.StatusInfo{
Status: status.Unknown,
}
cachedApp, err := model.Application(app.Name())
if err == nil {
sts = cachedApp.Status()
}
return ¶ms.OfferStatusChange{
OfferName: offerName,
Status: params.EntityStatus{
Status: sts.Status,
Info: sts.Message,
Data: sts.Data,
Since: sts.Since,
},
}, nil
}
// CacheShim exists to be able to replace the cache with a fake implementation
// for tests.
type CacheShim struct {
Model *cache.Model
}
// Application returns the CachedApplication for the name specified.
func (c CacheShim) Application(name string) (CachedApplication, error) {
app, err := c.Model.Application(name)
if err != nil {
return nil, err
}
return &app, nil
}