/
entity_address_utils.py
392 lines (341 loc) · 14.2 KB
/
entity_address_utils.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
import logging
from typing import Optional, Union
from urllib.parse import urlparse
import re
from tldextract import extract as tld_extract
from tldextract.tldextract import ExtractResult as TldExtractResult
from flask import request, current_app, has_request_context
from flexmeasures.utils.time_utils import get_first_day_of_next_month
"""
Functionality to support parsing and building Entity Addresses as defined by USEF [1].
See our documentation for more details.
[1] https://www.usef.energy/app/uploads/2020/01/USEF-Flex-Trading-Protocol-Specifications-1.01.pdf
"""
ADDR_SCHEME = "ea1"
FM1_ADDR_SCHEME = "fm1"
FM0_ADDR_SCHEME = "fm0"
class EntityAddressException(Exception):
pass
def get_host() -> str:
"""Get host from the context of the request.
Strips off www. but keeps subdomains.
Can be localhost, too.
"""
if has_request_context():
host = urlparse(request.url).netloc.lstrip("www.")
if host[:9] != "127.0.0.1":
return host
# Assume localhost (for CLI/tests/simulations)
return "localhost"
def build_entity_address(
entity_info: dict,
entity_type: str,
host: Optional[str] = None,
fm_scheme: str = FM1_ADDR_SCHEME,
) -> str:
"""
Build an entity address.
fm1 type entity address should use entity_info["sensor_id"]
todo: implement entity addresses for actuators with entity_info["actuator_id"] (first ensuring globally unique ids across sensors and actuators)
If the host is not given, it is attempted to be taken from the request.
entity_info is expected to contain the required fields for the custom string.
Returns the address as string.
"""
if host is None:
host = get_host()
def build_field(field: str, required: bool = True):
if required and field not in entity_info:
raise EntityAddressException(
f"Cannot find required field '{field}' to build entity address."
)
if field not in entity_info:
return ""
return f"{entity_info[field]}:"
if fm_scheme == FM1_ADDR_SCHEME: # and entity_type == "sensor":
locally_unique_str = f"{build_field('sensor_id')}"
# elif fm_scheme == FM1_ADDR_SCHEME and entity_type == "actuator":
# locally_unique_str = f"{build_field('actuator_id')}"
elif fm_scheme != FM0_ADDR_SCHEME:
raise EntityAddressException(
f"Unrecognized FlexMeasures scheme for entity addresses: {fm_scheme}"
)
elif entity_type == "connection":
locally_unique_str = (
f"{build_field('owner_id', required=False)}{build_field('asset_id')}"
)
elif entity_type == "weather_sensor":
locally_unique_str = f"{build_field('weather_sensor_type_name')}{build_field('latitude')}{build_field('longitude')}"
elif entity_type == "market":
locally_unique_str = f"{build_field('market_name')}"
elif entity_type == "event":
locally_unique_str = f"{build_field('owner_id', required=False)}{build_field('asset_id')}{build_field('event_id')}{build_field('event_type')}"
else:
raise EntityAddressException(f"Unrecognized entity type: {entity_type}")
return (
build_ea_scheme_and_naming_authority(host)
+ ":"
+ fm_scheme
+ "."
+ locally_unique_str.rstrip(":")
)
def parse_entity_address( # noqa: C901
entity_address: str,
entity_type: str,
fm_scheme: str = FM1_ADDR_SCHEME,
) -> dict:
"""
Parses a generic asset name into an info dict.
Returns a dictionary with scheme, naming_authority and various other fields,
depending on the entity type and FlexMeasures scheme (see examples above).
Returns None if entity type is unknown or entity_address is not parse-able.
We recommend to `return invalid_domain()` in that case.
Examples for the fm1 scheme:
sensor = ea1.2021-01.io.flexmeasures:fm1.42
sensor = ea1.2021-01.io.flexmeasures:fm1.<sensor_id>
connection = ea1.2021-01.io.flexmeasures:fm1.<sensor_id>
market = ea1.2021-01.io.flexmeasures:fm1.<sensor_id>
weather_station = ea1.2021-01.io.flexmeasures:fm1.<sensor_id>
todo: UDI events are not yet modelled in the fm1 scheme, but will probably be ea1.2021-01.io.flexmeasures:fm1.<actuator_id>
Examples for the fm0 scheme:
connection = ea1.2021-01.localhost:fm0.40:30
connection = ea1.2021-01.io.flexmeasures:fm0.<owner_id>:<asset_id>
weather_sensor = ea1.2021-01.io.flexmeasures:fm0.temperature:52:73.0
weather_sensor = ea1.2021-01.io.flexmeasures:fm0.<sensor_type>:<latitude>:<longitude>
market = ea1.2021-01.io.flexmeasures:fm0.epex_da
market = ea1.2021-01.io.flexmeasures:fm0.<market_name>
event = ea1.2021-01.io.flexmeasures:fm0.40:30:302:soc
event = ea1.2021-01.io.flexmeasures:fm0.<owner_id>:<asset_id>:<event_id>:<event_type>
For the fm0 scheme, the 'fm0.' part is optional, for backwards compatibility.
"""
# Check the scheme and naming authority date
if not entity_address.startswith(ADDR_SCHEME):
raise EntityAddressException(
f"A valid type 1 USEF entity address starts with '{ADDR_SCHEME}', please review {entity_address}"
)
date_regex = r"([0-9]{4})-(0[1-9]|1[012])"
if not re.search(fr"^{date_regex}$", entity_address[4:11]):
raise EntityAddressException(
f"After '{ADDR_SCHEME}.', a date specification of the format {date_regex} is expected."
)
# Check the entity type
if entity_type not in ("sensor", "connection", "weather_sensor", "market", "event"):
raise EntityAddressException(f"Unrecognized entity type: {entity_type}")
def validate_ea_for_fm_scheme(ea: dict, fm_scheme: str):
if "fm_scheme" not in ea:
# Backwards compatibility: assume fm0 if fm_scheme is not specified
ea["fm_scheme"] = FM0_ADDR_SCHEME
scheme = ea["scheme"]
naming_authority = ea["naming_authority"]
if ea["fm_scheme"] != fm_scheme:
raise EntityAddressException(
f"A valid type {fm_scheme[2:]} FlexMeasures entity address starts with '{scheme}.{naming_authority}:{fm_scheme}', please review {entity_address}"
)
if fm_scheme == FM1_ADDR_SCHEME:
# Check the FlexMeasures scheme
if entity_address.split(":")[1][: len(fm_scheme) + 1] != FM1_ADDR_SCHEME + ".":
raise EntityAddressException(
f"A valid type {fm_scheme[2:]} FlexMeasures entity address starts with '{build_ea_scheme_and_naming_authority(get_host())}:{fm_scheme}.', please review {entity_address}"
)
match = re.search(
r"^"
r"(?P<scheme>.+)\."
fr"(?P<naming_authority>{date_regex}\.[^:]+)" # everything until the colon (no port)
r":"
r"((?P<fm_scheme>.+)\.)"
r"(?P<sensor_id>\d+)"
r"$",
entity_address,
)
if match is None:
raise EntityAddressException(
f"Could not parse {entity_type} {entity_address}."
)
value_types = {
"scheme": str,
"naming_authority": str,
"fm_scheme": str,
"sensor_id": int,
}
elif fm_scheme != FM0_ADDR_SCHEME:
raise EntityAddressException(
f"Unrecognized FlexMeasures scheme for entity addresses: {fm_scheme}"
)
elif entity_type == "connection":
match = re.search(
r"^"
r"(?P<scheme>.+)\."
fr"(?P<naming_authority>{date_regex}\.[^:]+)" # everything until the colon (no port)
r":"
r"((?P<fm_scheme>.+)\.)*" # for backwards compatibility, missing fm_scheme is interpreted as fm0
r"((?P<owner_id>\d+):)*" # owner id is optional
r"(?P<asset_id>\d+)"
r"$",
entity_address,
)
if match is None:
raise EntityAddressException(
f"Could not parse {entity_type} {entity_address}."
)
value_types = {
"scheme": str,
"naming_authority": str,
"owner_id": int,
"asset_id": int,
}
elif entity_type == "weather_sensor":
match = re.search(
r"^"
r"(?P<scheme>.+)"
r"\."
fr"(?P<naming_authority>{date_regex}\.[^:]+)"
r":"
r"((?P<fm_scheme>.+)\.)*" # for backwards compatibility, missing fm_scheme is interpreted as fm0
r"(?=[a-zA-Z])(?P<weather_sensor_type_name>[\w]+)" # should start with at least one letter
r":"
r"(?P<latitude>\-?\d+(\.\d+)?)"
r":"
r"(?P<longitude>\-?\d+(\.\d+)?)"
r"$",
entity_address,
)
if match is None:
raise EntityAddressException(
f"Could not parse {entity_type} {entity_address}."
)
value_types = {
"scheme": str,
"naming_authority": str,
"weather_sensor_type_name": str,
"latitude": float,
"longitude": float,
}
elif entity_type == "market":
match = re.search(
r"^"
r"(?P<scheme>.+)"
r"\."
fr"(?P<naming_authority>{date_regex}\.[^:]+)"
r":"
r"((?P<fm_scheme>.+)\.)*" # for backwards compatibility, missing fm_scheme is interpreted as fm0
r"(?=[a-zA-Z])(?P<market_name>[\w]+)" # should start with at least one letter
r"$",
entity_address,
)
if match is None:
raise EntityAddressException(
f"Could not parse {entity_type} {entity_address}."
)
value_types = {"scheme": str, "naming_authority": str, "market_name": str}
elif entity_type == "event":
match = re.search(
r"^"
r"(?P<scheme>.+)"
r"\."
fr"(?P<naming_authority>{date_regex}\.[^:]+)"
r":"
r"((?P<fm_scheme>.+)\.)*" # for backwards compatibility, missing fm_scheme is interpreted as fm0
r"((?P<owner_id>\d+):)*" # owner id is optional
r"(?P<asset_id>\d+)"
r":"
r"(?P<event_id>\d+)"
r":"
r"(?P<event_type>.+)"
r"$",
entity_address,
)
if match is None:
raise EntityAddressException(
f"Could not parse {entity_type} {entity_address}."
)
value_types = {
"scheme": str,
"naming_authority": str,
"owner_id": int,
"asset_id": int,
"event_id": int,
"event_type": str,
}
else:
# Finally, we simply raise without precise information what went wrong
raise EntityAddressException(f"Could not parse {entity_address}.")
ea = _typed_regex_results(match, value_types)
validate_ea_for_fm_scheme(ea, fm_scheme)
return ea
def build_ea_scheme_and_naming_authority(
host: str, host_auth_start_month: Optional[str] = None
) -> str:
"""
This function creates the host identification part of
USEF's EA1 addressing scheme, so everything but the locally unique string.
If not given nor configured, host_auth_start_month is the start of the next month for
localhost.
"""
domain_parts: TldExtractResult = get_domain_parts(host)
if host_auth_start_month is None:
config_var_domain_key = ".".join(
filter(
lambda x: x,
[domain_parts.subdomain, domain_parts.domain, domain_parts.suffix],
)
)
if domain_parts.domain in ("localhost", "127.0.0.1"):
host_auth_start_month = get_first_day_of_next_month().strftime("%Y-%m")
elif config_var_domain_key in current_app.config.get(
"FLEXMEASURES_HOSTS_AND_AUTH_START", {}
):
host_auth_start_month = current_app.config.get(
"FLEXMEASURES_HOSTS_AND_AUTH_START", {}
)[config_var_domain_key]
else:
raise Exception(
f"Could not find out when authority for {config_var_domain_key} started. Is FLEXMEASURES_HOSTS_AND_AUTH_START configured for it?"
)
regex = r"^\d{4}-\d{2}$"
if not re.search(regex, host_auth_start_month):
raise ValueError(
f"{host_auth_start_month} should adhere to the format {regex}."
)
if not int(host_auth_start_month[-2:]) in range(1, 13):
raise ValueError(
f"Month in {host_auth_start_month} should be in the range of 1 to 12."
)
reversed_domain_name = reverse_domain_name(domain_parts)
if reversed_domain_name == "":
raise Exception(f"Could not make domain name from {host}!")
return f"{ADDR_SCHEME}.{host_auth_start_month}.{reversed_domain_name}"
def reverse_domain_name(domain: Union[str, TldExtractResult]) -> str:
"""
Returns the reverse notation of the domain.
You can pass in a string domain or an extraction result from tldextract
"""
if isinstance(domain, str):
domain_parts: TldExtractResult = get_domain_parts(domain)
else:
domain_parts = domain
suffix = domain_parts.suffix
if suffix != "":
if "." in suffix:
suffix = ".".join(suffix.split(".")[::-1])
suffix = f"{suffix}."
domain = domain_parts.domain
reversed_subdomain = ""
if domain_parts.subdomain != "":
sd_list = ".".join(domain_parts.subdomain.split(".")[::-1])
reversed_subdomain = f".{sd_list}"
return f"{suffix}{domain}{reversed_subdomain}"
def get_domain_parts(domain: str) -> TldExtractResult:
"""wrapper for calling tldextract as it logs things about file locks we don't care about."""
logger = logging.getLogger()
level = logger.getEffectiveLevel()
logger.setLevel(logging.ERROR)
domain_parts: TldExtractResult = tld_extract(domain)
logging.getLogger().setLevel(level)
return domain_parts
def _typed_regex_results(match, value_types) -> dict:
return {
k: v_type(v) if v is not None else v
for k, v, v_type in _zip_dic(match.groupdict(), value_types)
}
def _zip_dic(*dicts):
for i in set(dicts[0]).intersection(*dicts[1:]):
yield (i,) + tuple(d[i] for d in dicts)