generated from canonical/template-operator
-
Notifications
You must be signed in to change notification settings - Fork 27
/
ingress_per_unit.py
884 lines (711 loc) · 31 KB
/
ingress_per_unit.py
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
# Copyright 2022 Canonical Ltd.
# See LICENSE file for licensing details.
r"""# Interface Library for ingress_per_unit.
This library wraps relation endpoints using the `ingress_per_unit` interface
and provides a Python API for both requesting and providing per-unit
ingress.
## Getting Started
To get started using the library, you just need to fetch the library using `charmcraft`.
```shell
charmcraft fetch-lib charms.traefik_k8s.v1.ingress_per_unit
```
Add the `jsonschema` dependency to the `requirements.txt` of your charm.
```yaml
requires:
ingress:
interface: ingress_per_unit
limit: 1
```
Then, to initialise the library:
```python
from charms.traefik_k8s.v1.ingress_per_unit import (IngressPerUnitRequirer,
IngressPerUnitReadyForUnitEvent, IngressPerUnitRevokedForUnitEvent)
class SomeCharm(CharmBase):
def __init__(self, *args):
# ...
self.ingress_per_unit = IngressPerUnitRequirer(self, port=80)
# The following event is triggered when the ingress URL to be used
# by this unit of `SomeCharm` is ready (or changes).
self.framework.observe(
self.ingress_per_unit.on.ready_for_unit, self._on_ingress_ready
)
self.framework.observe(
self.ingress_per_unit.on.revoked_for_unit, self._on_ingress_revoked
)
def _on_ingress_ready(self, event: IngressPerUnitReadyForUnitEvent):
# event.url is the same as self.ingress_per_unit.url
logger.info("This unit's ingress URL: %s", event.url)
def _on_ingress_revoked(self, event: IngressPerUnitRevokedForUnitEvent):
logger.info("This unit no longer has ingress")
```
If you wish to be notified also (or instead) when another unit's ingress changes
(e.g. if you're the leader and you're doing things with your peers' ingress),
you can pass `listen_to = "all-units" | "both"` to `IngressPerUnitRequirer`
and observe `self.ingress_per_unit.on.ready` and `self.ingress_per_unit.on.revoked`.
"""
import logging
import socket
import typing
from typing import Any, Dict, Optional, Tuple, Union
import yaml
from ops.charm import CharmBase, RelationEvent
from ops.framework import (
EventSource,
Object,
ObjectEvents,
StoredDict,
StoredList,
StoredState,
)
from ops.model import Application, ModelError, Relation, Unit
# The unique Charmhub library identifier, never change it
LIBID = "7ef06111da2945ed84f4f5d4eb5b353a"
# Increment this major API version when introducing breaking changes
LIBAPI = 1
# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 19
log = logging.getLogger(__name__)
try:
import jsonschema
DO_VALIDATION = True
except ModuleNotFoundError:
log.warning(
"The `ingress_per_unit` library needs the `jsonschema` package to be able "
"to do runtime data validation; without it, it will still work but validation "
"will be disabled. \n"
"It is recommended to add `jsonschema` to the 'requirements.txt' of your charm, "
"which will enable this feature."
)
DO_VALIDATION = False
# LIBRARY GLOBS
RELATION_INTERFACE = "ingress_per_unit"
DEFAULT_RELATION_NAME = RELATION_INTERFACE.replace("_", "-")
INGRESS_REQUIRES_UNIT_SCHEMA = {
"type": "object",
"properties": {
"model": {"type": "string"},
"name": {"type": "string"},
"host": {"type": "string"},
"port": {"type": "string"},
"mode": {"type": "string"},
"strip-prefix": {"type": "string"},
"redirect-https": {"type": "string"},
"scheme": {"type": "string"},
},
"required": ["model", "name", "host", "port"],
}
INGRESS_PROVIDES_APP_SCHEMA = {
"type": "object",
"properties": {
"ingress": {
"type": "object",
"patternProperties": {
"": {
"type": "object",
"properties": {
"url": {"type": "string"},
},
"required": ["url"],
}
},
}
},
"required": ["ingress"],
}
# TYPES
try:
from typing import Literal, TypedDict # type: ignore
except ImportError:
from typing_extensions import Literal, TypedDict # py35 compat
# Model of the data a unit implementing the requirer will need to provide.
RequirerData = TypedDict(
"RequirerData",
{
"model": str,
"name": str,
"host": str,
"port": int,
"mode": Optional[Literal["tcp", "http"]],
"strip-prefix": Optional[bool],
"redirect-https": Optional[bool],
"scheme": Optional[Literal["http", "https"]],
},
total=False,
)
RequirerUnitData = Dict[Unit, "RequirerData"]
KeyValueMapping = Dict[str, str]
ProviderApplicationData = Dict[str, KeyValueMapping]
def _type_convert_stored(obj):
"""Convert Stored* to their appropriate types, recursively."""
if isinstance(obj, StoredList):
return list(map(_type_convert_stored, obj))
if isinstance(obj, StoredDict):
rdict: Dict[Any, Any] = {}
for k in obj.keys():
rdict[k] = _type_convert_stored(obj[k])
return rdict
return obj
def _validate_data(data, schema):
"""Checks whether `data` matches `schema`.
Will raise DataValidationError if the data is not valid, else return None.
"""
if not DO_VALIDATION:
return
try:
jsonschema.validate(instance=data, schema=schema) # pyright: ignore[reportUnboundVariable]
except jsonschema.ValidationError as e: # pyright: ignore[reportUnboundVariable]
raise DataValidationError(data, schema) from e
# EXCEPTIONS
class DataValidationError(RuntimeError):
"""Raised when data validation fails on IPU relation data."""
class RelationException(RuntimeError):
"""Base class for relation exceptions from this library.
Attributes:
relation: The Relation which caused the exception.
entity: The Application or Unit which caused the exception.
"""
def __init__(self, relation: Relation, entity: Union[Application, Unit]):
super().__init__(relation)
self.args = (
"There is an error with the relation {}:{} with {}".format(
relation.name, relation.id, entity.name
),
)
self.relation = relation
self.entity = entity
class RelationDataMismatchError(RelationException):
"""Data from different units do not match where they should."""
class RelationPermissionError(RelationException):
"""Ingress is requested to do something for which it lacks permissions."""
def __init__(self, relation: Relation, entity: Union[Application, Unit], message: str):
super(RelationPermissionError, self).__init__(relation, entity)
self.args = (
"Unable to write data to relation '{}:{}' with {}: {}".format(
relation.name, relation.id, entity.name, message
),
)
class _IngressPerUnitBase(Object):
"""Base class for IngressPerUnit interface classes."""
def __init__(self, charm: CharmBase, relation_name: str = DEFAULT_RELATION_NAME):
"""Constructor for _IngressPerUnitBase.
Args:
charm: The charm that is instantiating the instance.
relation_name: The name of the relation name to bind to
(defaults to "ingress-per-unit").
"""
super().__init__(charm, relation_name)
self.charm: CharmBase = charm
self.relation_name = relation_name
self.app = self.charm.app
self.unit = self.charm.unit
observe = self.framework.observe
rel_events = charm.on[relation_name]
observe(rel_events.relation_created, self._handle_relation)
observe(rel_events.relation_joined, self._handle_relation)
observe(rel_events.relation_changed, self._handle_relation)
observe(rel_events.relation_departed, self._handle_relation)
observe(rel_events.relation_broken, self._handle_relation_broken)
observe(charm.on.leader_elected, self._handle_upgrade_or_leader) # type: ignore
observe(charm.on.upgrade_charm, self._handle_upgrade_or_leader) # type: ignore
@property
def relations(self):
"""The list of Relation instances associated with this relation_name."""
return list(self.charm.model.relations[self.relation_name])
def _handle_relation(self, event):
"""Subclasses should implement this method to handle a relation update."""
pass
def _handle_relation_broken(self, event):
"""Subclasses should implement this method to handle a relation breaking."""
pass
def _handle_upgrade_or_leader(self, event):
"""Subclasses should implement this method to handle upgrades or leadership change."""
pass
def is_ready(self, relation: Optional[Relation] = None) -> bool:
"""Checks whether the given relation is ready.
A relation is ready if the remote side has sent valid data.
"""
if relation is None:
return any(map(self.is_ready, self.relations))
if relation.app is None:
# No idea why, but this happened once.
return False
if not relation.app.name: # type: ignore
# Juju doesn't provide JUJU_REMOTE_APP during relation-broken
# hooks. See https://github.com/canonical/operator/issues/693
return False
return True
class IngressDataReadyEvent(RelationEvent):
"""Event triggered when the requirer has provided valid ingress data.
Also emitted when the data has changed.
If you receive this, you should handle it as if the data being
provided was new.
"""
class IngressDataRemovedEvent(RelationEvent):
"""Event triggered when a requirer has wiped its ingress data.
Also emitted when the requirer data has become incomplete or invalid.
If you receive this, you should handle it as if the remote unit no longer
wishes to receive ingress.
"""
class IngressPerUnitProviderEvents(ObjectEvents):
"""Container for events for IngressPerUnit."""
data_provided = EventSource(IngressDataReadyEvent)
data_removed = EventSource(IngressDataRemovedEvent)
class IngressPerUnitProvider(_IngressPerUnitBase):
"""Implementation of the provider of ingress_per_unit."""
on = IngressPerUnitProviderEvents() # type: ignore
def _handle_relation(self, event):
relation = event.relation
try:
self.validate(relation)
except RelationDataMismatchError as e:
self.on.data_removed.emit(relation) # type: ignore
log.warning(
"relation data mismatch: {} " "data_removed ingress for {}.".format(e, relation)
)
return
if self.is_ready(relation):
self.on.data_provided.emit(relation) # type: ignore
else:
self.on.data_removed.emit(relation) # type: ignore
def _handle_relation_broken(self, event):
# relation broken -> we revoke in any case
self.on.data_removed.emit(event.relation) # type: ignore
def is_ready(self, relation: Optional[Relation] = None) -> bool:
"""Checks whether the given relation is ready.
Or any relation if not specified.
A given relation is ready if SOME remote side has sent valid data.
"""
if relation is None:
return any(map(self.is_ready, self.relations))
if not super().is_ready(relation):
return False
try:
requirer_units_data = self._requirer_units_data(relation)
except Exception:
log.exception("Cannot fetch ingress data for the '{}' relation".format(relation))
return False
return any(requirer_units_data.values())
def validate(self, relation: Relation):
"""Checks whether the given relation is failed.
Or any relation if not specified.
"""
# verify that all remote units (requirer's side) publish the same model.
# We do not validate the port because, in case of changes to the configuration
# of the charm or a new version of the charmed workload, e.g. over an upgrade,
# the remote port may be different among units.
expected_model = None # It may be none for units that have not yet written data
remote_units_data = self._requirer_units_data(relation)
for remote_unit, remote_unit_data in remote_units_data.items():
if "model" in remote_unit_data:
remote_model = remote_unit_data["model"]
if not expected_model:
expected_model = remote_model
elif expected_model != remote_model:
raise RelationDataMismatchError(relation, remote_unit)
def is_unit_ready(self, relation: Relation, unit: Unit) -> bool:
"""Report whether the given unit has shared data in its unit data bag."""
# sanity check: this should not occur in production, but it may happen
# during testing: cfr https://github.com/canonical/traefik-k8s-operator/issues/39
assert unit in relation.units, (
"attempting to get ready state " "for unit that does not belong to relation"
)
try:
self._get_requirer_unit_data(relation, unit)
except (KeyError, DataValidationError):
return False
return True
def get_data(self, relation: Relation, unit: Unit) -> "RequirerData":
"""Fetch the data shared by the specified unit on the relation (Requirer side)."""
return self._get_requirer_unit_data(relation, unit)
def publish_url(self, relation: Relation, unit_name: str, url: str):
"""Place the ingress url in the application data bag for the units on the requirer side.
Assumes that this unit is leader.
"""
assert self.unit.is_leader(), "only leaders can do this"
raw_data = relation.data[self.app].get("ingress", None)
data = yaml.safe_load(raw_data) if raw_data else {}
ingress = {"ingress": data}
# we ensure that the application databag has the shape we think it
# should have; to catch any inconsistencies early on.
try:
_validate_data(ingress, INGRESS_PROVIDES_APP_SCHEMA)
except DataValidationError as e:
log.error(
"unable to publish url to {}: corrupted application databag ({})".format(
unit_name, e
)
)
return
# we update the data with a new url
data[unit_name] = {"url": url}
# we validate the data **again**, to ensure that we respected the schema
# and did not accidentally corrupt our own databag.
_validate_data(ingress, INGRESS_PROVIDES_APP_SCHEMA)
relation.data[self.app]["ingress"] = yaml.safe_dump(data)
def wipe_ingress_data(self, relation):
"""Remove all published ingress data.
Assumes that this unit is leader.
"""
assert self.unit.is_leader(), "only leaders can do this"
try:
relation.data
except ModelError as e:
log.warning(
"error {} accessing relation data for {!r}. "
"Probably a ghost of a dead relation is still "
"lingering around.".format(e, relation.name)
)
return
del relation.data[self.app]["ingress"]
def _requirer_units_data(self, relation: Relation) -> RequirerUnitData:
"""Fetch and validate the requirer's units databag."""
if not relation.app or not relation.app.name:
# Handle edge case where remote app name can be missing, e.g.,
# relation_broken events.
# FIXME https://github.com/canonical/traefik-k8s-operator/issues/34
return {}
remote_units = [unit for unit in relation.units if unit.app is not self.app]
requirer_units_data = {}
for remote_unit in remote_units:
try:
remote_data = self._get_requirer_unit_data(relation, remote_unit)
except KeyError:
# this remote unit didn't share data yet
log.warning("Remote unit {} not ready.".format(remote_unit.name))
continue
except DataValidationError as e:
# this remote unit sent invalid data.
log.error("Remote unit {} sent invalid data ({}).".format(remote_unit.name, e))
continue
remote_data["port"] = int(remote_data["port"])
requirer_units_data[remote_unit] = remote_data
return requirer_units_data
def _get_requirer_unit_data(self, relation: Relation, remote_unit: Unit) -> RequirerData: # type: ignore
"""Fetch and validate the requirer unit data for this unit.
For convenience, we convert 'port' to integer.
"""
if not relation.app or not relation.app.name:
# Handle edge case where remote app name can be missing, e.g.,
# relation_broken events.
# FIXME https://github.com/canonical/traefik-k8s-operator/issues/34
return {}
databag = relation.data[remote_unit]
remote_data: Dict[str, Union[int, str]] = {}
for k in (
"port",
"host",
"model",
"name",
"mode",
"strip-prefix",
"redirect-https",
"scheme",
):
v = databag.get(k)
if v is not None:
remote_data[k] = v
_validate_data(remote_data, INGRESS_REQUIRES_UNIT_SCHEMA)
remote_data["port"] = int(remote_data["port"])
remote_data["strip-prefix"] = bool(remote_data.get("strip-prefix", "false") == "true")
remote_data["redirect-https"] = bool(remote_data.get("redirect-https", "false") == "true")
return typing.cast(RequirerData, remote_data)
def _provider_app_data(self, relation: Relation) -> ProviderApplicationData:
"""Fetch and validate the provider's app databag."""
if not relation.app or not relation.app.name:
# Handle edge case where remote app name can be missing, e.g.,
# relation_broken events.
# FIXME https://github.com/canonical/traefik-k8s-operator/issues/34
return {}
# we start by looking at the provider's app databag
if self.unit.is_leader():
# only leaders can read their app's data
data = relation.data[self.app].get("ingress")
if not data:
return {}
deserialized = yaml.safe_load(data)
_validate_data({"ingress": deserialized}, INGRESS_PROVIDES_APP_SCHEMA)
return deserialized
return {}
@property
def proxied_endpoints(self) -> dict:
"""The ingress settings provided to units by this provider.
For example, when this IngressPerUnitProvider has provided the
`http://foo.bar/my-model.my-app-1` and
`http://foo.bar/my-model.my-app-2` URLs to the two units of the
my-app application, the returned dictionary will be:
```
{
"my-app/1": {
"url": "http://foo.bar/my-model.my-app-1"
},
"my-app/2": {
"url": "http://foo.bar/my-model.my-app-2"
}
}
```
"""
results = {}
for ingress_relation in self.relations:
provider_app_data = self._provider_app_data(ingress_relation)
results.update(provider_app_data)
return results
class _IPUEvent(RelationEvent):
__args__: Tuple[str, ...] = ()
__optional_kwargs__: Dict[str, Any] = {}
@classmethod
def __attrs__(cls):
return cls.__args__ + tuple(cls.__optional_kwargs__.keys())
def __init__(self, handle, relation, *args, **kwargs):
super().__init__(handle, relation)
if not len(self.__args__) == len(args):
raise TypeError("expected {} args, got {}".format(len(self.__args__), len(args)))
for attr, obj in zip(self.__args__, args):
setattr(self, attr, obj)
for attr, default in self.__optional_kwargs__.items():
obj = kwargs.get(attr, default)
setattr(self, attr, obj)
def snapshot(self):
dct = super().snapshot()
for attr in self.__attrs__():
obj = getattr(self, attr)
try:
dct[attr] = obj
except ValueError as e:
raise ValueError(
"cannot automagically serialize {}: "
"override this method and do it "
"manually.".format(obj)
) from e
return dct
def restore(self, snapshot) -> None:
super().restore(snapshot)
for attr, obj in snapshot.items():
setattr(self, attr, obj)
class IngressPerUnitReadyEvent(_IPUEvent):
"""Ingress is ready (or has changed) for some unit.
Attrs:
`unit_name`: name of the unit for which ingress has been
provided/has changed.
`url`: the (new) url for that unit.
"""
__args__ = ("unit_name", "url")
if typing.TYPE_CHECKING:
unit_name = ""
url = ""
class IngressPerUnitReadyForUnitEvent(_IPUEvent):
"""Ingress is ready (or has changed) for this unit.
Is only fired on the unit(s) for which ingress has been provided or
has changed.
Attrs:
`url`: the (new) url for this unit.
"""
__args__ = ("url",)
if typing.TYPE_CHECKING:
url = ""
class IngressPerUnitRevokedEvent(_IPUEvent):
"""Ingress is revoked (or has changed) for some unit.
Attrs:
`unit_name`: the name of the unit whose ingress has been revoked.
this could be "THIS" unit, or a peer.
"""
__args__ = ("unit_name",)
if typing.TYPE_CHECKING:
unit_name = ""
class IngressPerUnitRevokedForUnitEvent(RelationEvent):
"""Ingress is revoked (or has changed) for this unit.
Is only fired on the unit(s) for which ingress has changed.
"""
class IngressPerUnitRequirerEvents(ObjectEvents):
"""Container for IUP events."""
ready = EventSource(IngressPerUnitReadyEvent)
revoked = EventSource(IngressPerUnitRevokedEvent)
ready_for_unit = EventSource(IngressPerUnitReadyForUnitEvent)
revoked_for_unit = EventSource(IngressPerUnitRevokedForUnitEvent)
class IngressPerUnitRequirer(_IngressPerUnitBase):
"""Implementation of the requirer of ingress_per_unit."""
on: IngressPerUnitRequirerEvents = IngressPerUnitRequirerEvents()
# used to prevent spurious urls to be sent out if the event we're currently
# handling is a relation-broken one.
_stored = StoredState()
def __init__(
self,
charm: CharmBase,
relation_name: str = DEFAULT_RELATION_NAME,
*,
host: Optional[str] = None,
port: Optional[int] = None,
mode: Literal["tcp", "http"] = "http",
listen_to: Literal["only-this-unit", "all-units", "both"] = "only-this-unit",
strip_prefix: bool = False,
redirect_https: bool = False,
# FIXME: now that `provide_ingress_requirements` takes a scheme, this arg can be changed to
# str type in v2.
scheme: typing.Callable[[], str] = lambda: "http",
):
"""Constructor for IngressPerUnitRequirer.
The request args can be used to specify the ingress properties when the
instance is created. If any are set, at least `port` is required, and
they will be sent to the ingress provider as soon as it is available.
All request args must be given as keyword args.
Args:
charm: the charm that is instantiating the library.
relation_name: the name of the relation name to bind to
(defaults to "ingress-per-unit"; relation must be of interface
type "ingress_per_unit" and have "limit: 1").
host: Hostname to be used by the ingress provider to address the
requirer unit; if unspecified, the FQDN of the unit will be
used instead.
port: port to be used by the ingress provider to address the
requirer unit.
mode: mode to be used between "tcp" and "http".
listen_to: Choose which events should be fired on this unit:
"only-this-unit": this unit will only be notified when ingress
is ready/revoked for this unit.
"all-units": this unit will be notified when ingress is
ready/revoked for any unit of this application, including
itself.
"all": this unit will receive both event types (which means it
will be notified *twice* of changes to this unit's ingress!).
strip_prefix: remove prefixes from the URL path.
redirect_https: redirect incoming requests to HTTPS
scheme: callable returning the scheme to use when constructing the ingress url.
"""
super().__init__(charm, relation_name)
self._stored.set_default(current_urls=None) # type: ignore
# if instantiated with a port, and we are related, then
# we immediately publish our ingress data to speed up the process.
self._host = host
self._port = port
self._mode = mode
self._strip_prefix = strip_prefix
self._redirect_https = redirect_https
self._get_scheme = scheme
self.listen_to = listen_to
self.framework.observe(
self.charm.on[self.relation_name].relation_changed, self._handle_relation
)
self.framework.observe(
self.charm.on[self.relation_name].relation_broken, self._handle_relation
)
def _handle_relation(self, event: RelationEvent):
# we calculate the diff between the urls we were aware of
# before and those we know now
previous_urls = self._stored.current_urls or {} # type: ignore
# since ops 2.10, breaking relations won't show up in self.model.relations, so we're safe
# in assuming all relations that are there are alive and well.
current_urls = self._urls_from_relation_data
self._stored.current_urls = current_urls # type: ignore
removed = previous_urls.keys() - current_urls.keys() # type: ignore
changed = {a for a in current_urls if current_urls[a] != previous_urls.get(a)} # type: ignore
this_unit_name = self.unit.name
# do not use self.relation in this context because if
# the event is relation-broken, self.relation might be None
relation = event.relation
if self.listen_to in {"only-this-unit", "both"}:
if this_unit_name in changed:
self.on.ready_for_unit.emit(relation, current_urls[this_unit_name]) # type: ignore
if this_unit_name in removed:
self.on.revoked_for_unit.emit(relation) # type: ignore
if self.listen_to in {"all-units", "both"}:
for unit_name in changed:
self.on.ready.emit(relation, unit_name, current_urls[unit_name]) # type: ignore
for unit_name in removed:
self.on.revoked.emit(relation, unit_name) # type: ignore
self._publish_auto_data()
def _handle_upgrade_or_leader(self, event):
self._publish_auto_data()
def _publish_auto_data(self):
if self._port:
self.provide_ingress_requirements(host=self._host, port=self._port)
@property
def relation(self) -> Optional[Relation]:
"""The established Relation instance, or None if still unrelated."""
return self.relations[0] if self.relations else None
def is_ready(self) -> bool:
"""Checks whether the given relation is ready.
Or any relation if not specified.
A given relation is ready if the remote side has sent valid data.
"""
if not self.relation:
return False
if super().is_ready(self.relation) is False:
return False
return bool(self.url)
def provide_ingress_requirements(
self, *, scheme: Optional[str] = None, host: Optional[str] = None, port: int
):
"""Publishes the data that Traefik needs to provide ingress.
Args:
scheme: Scheme to be used; if unspecified, use the one used by __init__.
host: Hostname to be used by the ingress provider to address the
requirer unit; if unspecified, FQDN will be used instead
port: the port of the service (required)
"""
# This public method may be used at various points of the charm lifecycle, possibly when
# the ingress relation is not yet there.
# Abort if there is no relation (instead of requiring the caller to guard against it).
if not self.relation:
return
if not host:
host = socket.getfqdn()
if not scheme:
# If scheme was not provided, use the one given to the constructor.
scheme = self._get_scheme()
data = {
"model": self.model.name,
"name": self.unit.name,
"host": host,
"port": str(port),
"mode": self._mode,
"scheme": scheme,
}
if self._strip_prefix:
data["strip-prefix"] = "true"
if self._redirect_https:
data["redirect-https"] = "true"
_validate_data(data, INGRESS_REQUIRES_UNIT_SCHEMA)
self.relation.data[self.unit].update(data)
@property
def _urls_from_relation_data(self) -> Dict[str, str]:
"""The full ingress URLs to reach every unit.
May return an empty dict if the URLs aren't available yet.
"""
relation = self.relation
if not relation:
return {}
if not relation.app or not relation.app.name: # type: ignore
# FIXME Workaround for https://github.com/canonical/operator/issues/693
# We must be in a relation_broken hook
return {}
assert isinstance(relation.app, Application) # type guard
try:
raw = relation.data.get(relation.app, {}).get("ingress")
except ModelError as e:
log.debug(
"Error {} attempting to read remote app data; "
"probably we are in a relation_departed hook".format(e)
)
return {}
if not raw:
# remote side didn't send yet
return {}
data = yaml.safe_load(raw)
_validate_data({"ingress": data}, INGRESS_PROVIDES_APP_SCHEMA)
return {unit_name: unit_data["url"] for unit_name, unit_data in data.items()}
@property
def urls(self) -> Dict[str, str]:
"""The full ingress URLs to reach every unit.
May return an empty dict if the URLs aren't available yet.
"""
current_urls = self._urls_from_relation_data
return current_urls
@property
def url(self) -> Optional[str]:
"""The full ingress URL to reach the current unit.
May return None if the URL isn't available yet.
"""
urls = self.urls
if not urls:
return None
return urls.get(self.charm.unit.name)