labfreed 0.0.4__py3-none-any.whl → 0.2.0b0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- labfreed/PAC_CAT/__init__.py +16 -0
- labfreed/PAC_CAT/category_base.py +51 -0
- labfreed/PAC_CAT/pac_cat.py +159 -0
- labfreed/PAC_CAT/predefined_categories.py +190 -0
- labfreed/PAC_ID/__init__.py +19 -0
- labfreed/PAC_ID/extension.py +48 -0
- labfreed/PAC_ID/id_segment.py +90 -0
- labfreed/PAC_ID/pac_id.py +140 -0
- labfreed/PAC_ID/url_parser.py +154 -0
- labfreed/PAC_ID/url_serializer.py +80 -0
- labfreed/PAC_ID_Resolver/__init__.py +2 -0
- labfreed/PAC_ID_Resolver/cit_v1.py +149 -0
- labfreed/PAC_ID_Resolver/cit_v2.py +303 -0
- labfreed/PAC_ID_Resolver/resolver.py +81 -0
- labfreed/PAC_ID_Resolver/services.py +80 -0
- labfreed/__init__.py +4 -1
- labfreed/labfreed_infrastructure.py +276 -0
- labfreed/qr/__init__.py +1 -0
- labfreed/qr/generate_qr.py +422 -0
- labfreed/trex/__init__.py +16 -0
- labfreed/trex/python_convenience/__init__.py +3 -0
- labfreed/trex/python_convenience/data_table.py +45 -0
- labfreed/trex/python_convenience/pyTREX.py +242 -0
- labfreed/trex/python_convenience/quantity.py +46 -0
- labfreed/trex/table_segment.py +227 -0
- labfreed/trex/trex.py +69 -0
- labfreed/trex/trex_base_models.py +336 -0
- labfreed/trex/value_segments.py +111 -0
- labfreed/{DisplayNameExtension → utilities}/base36.py +29 -13
- labfreed/well_known_extensions/__init__.py +5 -0
- labfreed/well_known_extensions/default_extension_interpreters.py +7 -0
- labfreed/well_known_extensions/display_name_extension.py +40 -0
- labfreed/well_known_extensions/trex_extension.py +31 -0
- labfreed/well_known_keys/gs1/__init__.py +6 -0
- labfreed/well_known_keys/gs1/gs1.py +4 -0
- labfreed/well_known_keys/gs1/gs1_ai_enum_sorted.py +57 -0
- labfreed/well_known_keys/labfreed/well_known_keys.py +16 -0
- labfreed/well_known_keys/unece/UneceUnits.json +33730 -0
- labfreed/well_known_keys/unece/__init__.py +4 -0
- labfreed/well_known_keys/unece/unece_units.py +68 -0
- labfreed-0.2.0b0.dist-info/METADATA +329 -0
- labfreed-0.2.0b0.dist-info/RECORD +44 -0
- {labfreed-0.0.4.dist-info → labfreed-0.2.0b0.dist-info}/WHEEL +1 -1
- labfreed/DisplayNameExtension/DisplayNameExtension.py +0 -34
- labfreed/PAC_CAT/data_model.py +0 -109
- labfreed/PAC_ID/data_model.py +0 -114
- labfreed/PAC_ID/parse.py +0 -133
- labfreed/PAC_ID/serialize.py +0 -57
- labfreed/TREXExtension/data_model.py +0 -239
- labfreed/TREXExtension/parse.py +0 -46
- labfreed/TREXExtension/uncertainty.py +0 -32
- labfreed/TREXExtension/unit_utilities.py +0 -134
- labfreed-0.0.4.dist-info/METADATA +0 -15
- labfreed-0.0.4.dist-info/RECORD +0 -17
- {labfreed-0.0.4.dist-info → labfreed-0.2.0b0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
import json
|
|
3
|
+
import re
|
|
4
|
+
from typing import Self
|
|
5
|
+
from pydantic import Field, field_validator, model_validator
|
|
6
|
+
import yaml
|
|
7
|
+
import jsonpath_ng.ext as jsonpath
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
from labfreed.pac_id_resolver.services import Service, ServiceGroup
|
|
11
|
+
from labfreed.labfreed_infrastructure import LabFREED_BaseModel, ValidationMsgLevel, _quote_texts
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"CIT_v2",
|
|
15
|
+
"CITBlock_v2",
|
|
16
|
+
"CITEntry_v2"
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
class ServiceType(Enum):
|
|
20
|
+
USER_HANDOVER_GENERIC = 'userhandover-generic'
|
|
21
|
+
ATTRIBUTE_SERVICE_GENERIC = 'attributes-generic'
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CITEntry_v2(LabFREED_BaseModel):
|
|
25
|
+
service_name: str
|
|
26
|
+
application_intents:list[str]
|
|
27
|
+
service_type:ServiceType |str
|
|
28
|
+
template_url:str
|
|
29
|
+
|
|
30
|
+
@model_validator(mode='after')
|
|
31
|
+
def _validate_service_name(self):
|
|
32
|
+
# service_name
|
|
33
|
+
if not_allowed_chars := set(re.sub(r'[A-Za-z0-9\-\x20]', '', self.service_name)):
|
|
34
|
+
self._add_validation_message(
|
|
35
|
+
level=ValidationMsgLevel.ERROR,
|
|
36
|
+
source=f'Service {self.service_name}',
|
|
37
|
+
msg=f'Service name ontains invalid characters {_quote_texts(not_allowed_chars)}',
|
|
38
|
+
highlight_sub=not_allowed_chars
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
if len(self.service_name) == 0 or len(self.service_name) > 255:
|
|
42
|
+
self._add_validation_message(
|
|
43
|
+
level=ValidationMsgLevel.ERROR,
|
|
44
|
+
source=f'Service {self.service_name}',
|
|
45
|
+
msg='Service name must be at least one and maximum 255 characters long'
|
|
46
|
+
)
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@model_validator(mode='after')
|
|
51
|
+
def _validate_application_intent(self):
|
|
52
|
+
for intent in self.application_intents:
|
|
53
|
+
if re.fullmatch('.*-generic$', intent):
|
|
54
|
+
self._add_validation_message(
|
|
55
|
+
level=ValidationMsgLevel.ERROR,
|
|
56
|
+
source=f'Application intent {intent}',
|
|
57
|
+
msg="Ends with '-generic'. This is not permitted, since it is reserved for future uses'",
|
|
58
|
+
highlight_sub=[intent]
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
if not_allowed_chars := set(re.sub(r'[A-Za-z0-9\-]', '', intent)):
|
|
62
|
+
self._add_validation_message(
|
|
63
|
+
level=ValidationMsgLevel.ERROR,
|
|
64
|
+
source=f'Application intent {self.service_name}',
|
|
65
|
+
msg=f'Contains invalid characters {_quote_texts(not_allowed_chars)}',
|
|
66
|
+
highlight_sub=not_allowed_chars
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
if len(intent) == 0 or len(intent) > 255:
|
|
70
|
+
self._add_validation_message(
|
|
71
|
+
level=ValidationMsgLevel.ERROR,
|
|
72
|
+
source=f'Application intent {intent}',
|
|
73
|
+
msg='Must be at least one and maximum 255 characters long'
|
|
74
|
+
)
|
|
75
|
+
return self
|
|
76
|
+
|
|
77
|
+
@model_validator(mode='after')
|
|
78
|
+
def _validate_service_type(self):
|
|
79
|
+
allowed_types = [ServiceType.ATTRIBUTE_SERVICE_GENERIC.value, ServiceType.USER_HANDOVER_GENERIC.value]
|
|
80
|
+
if self.service_type not in allowed_types:
|
|
81
|
+
if isinstance(self.service_type, ServiceType):
|
|
82
|
+
s= self.service_type.value
|
|
83
|
+
else:
|
|
84
|
+
s= self.service_type
|
|
85
|
+
for at in allowed_types:
|
|
86
|
+
s = s.replace(at,'')
|
|
87
|
+
self._add_validation_message(
|
|
88
|
+
level=ValidationMsgLevel.ERROR,
|
|
89
|
+
source=f'Service Type {self.service_type}',
|
|
90
|
+
msg=f'Invalid service type. Must be {_quote_texts(allowed_types)} must be at least one and maximum 255 characters long',
|
|
91
|
+
highlight_sub=s
|
|
92
|
+
)
|
|
93
|
+
return self
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class CITBlock_v2(LabFREED_BaseModel):
|
|
98
|
+
applicable_if: str = Field(default='True', alias='if')
|
|
99
|
+
entries: list[CITEntry_v2]
|
|
100
|
+
|
|
101
|
+
@field_validator('applicable_if', mode='before')
|
|
102
|
+
@classmethod
|
|
103
|
+
def _convert_if(cls, v):
|
|
104
|
+
return v if v is not None else 'True'
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class CIT_v2(LabFREED_BaseModel):
|
|
110
|
+
'''Coupling Information Table (CIT)'''
|
|
111
|
+
origin: str = ''
|
|
112
|
+
model_config = {
|
|
113
|
+
"extra": "allow"
|
|
114
|
+
}
|
|
115
|
+
'''@private'''
|
|
116
|
+
cit: list[CITBlock_v2] = Field(default_factory=list)
|
|
117
|
+
|
|
118
|
+
@model_validator(mode='after')
|
|
119
|
+
def _validate_origin(self):
|
|
120
|
+
if len(self.origin) == 0:
|
|
121
|
+
self._add_validation_message(level=ValidationMsgLevel.WARNING,
|
|
122
|
+
source='CIT origin',
|
|
123
|
+
msg='Origin should not be empty'
|
|
124
|
+
)
|
|
125
|
+
return self
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def from_yaml(cls, yml:str) -> Self:
|
|
130
|
+
return cls.model_validate(yml)
|
|
131
|
+
|
|
132
|
+
def __str__(self):
|
|
133
|
+
yml = yaml.dump(self.model_dump() )
|
|
134
|
+
return yml
|
|
135
|
+
|
|
136
|
+
def evaluate_pac_id(self, pac):
|
|
137
|
+
pac_id_json = pac.to_dict()
|
|
138
|
+
cit_evaluated = ServiceGroup(origin=self.origin)
|
|
139
|
+
for block in self.cit:
|
|
140
|
+
_, is_applicable = self._evaluate_applicable_if(pac_id_json, block.applicable_if)
|
|
141
|
+
if not is_applicable:
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
for e in block.entries:
|
|
145
|
+
url = self._eval_url_template(pac_id_json, e.template_url)
|
|
146
|
+
cit_evaluated.services.append(Service(
|
|
147
|
+
service_name=e.service_name,
|
|
148
|
+
application_intents=e.application_intents,
|
|
149
|
+
service_type=e.service_type,
|
|
150
|
+
url = url
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
return cit_evaluated
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _evaluate_applicable_if(self, pac_id_json:str, expression) -> tuple[str, bool]:
|
|
157
|
+
expression = self._apply_convenience_substitutions(expression)
|
|
158
|
+
|
|
159
|
+
tokens = self._tokenize_jsonpath_expression(expression)
|
|
160
|
+
expression_for_eval = self._expression_from_tokens(pac_id_json, tokens)
|
|
161
|
+
applicable = eval(expression_for_eval, {}, {})
|
|
162
|
+
|
|
163
|
+
return expression_for_eval, applicable
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _apply_convenience_substitutions(self, query):
|
|
167
|
+
''' applies a few substitutions, which enable abbreviated syntax.'''
|
|
168
|
+
|
|
169
|
+
# allow access to array elements by key
|
|
170
|
+
q_mod = re.sub(r'\[(".+?")\]', r'[?(@.key == \1)]', query )
|
|
171
|
+
|
|
172
|
+
# allow shorter path
|
|
173
|
+
# substitutions = [
|
|
174
|
+
# (r'(?<=^)id', 'pac.id'),
|
|
175
|
+
# (r'(?<=^)cat', 'pac.id.cat'),
|
|
176
|
+
# (r'(?<=\.)id(?=\.)', 'identifier'),
|
|
177
|
+
# (r'(?<=\.)cat$', 'categories'),
|
|
178
|
+
# (r'(?<=\.)cat(?=\[)', 'categories'),
|
|
179
|
+
# (r'(?<=\.)seg$', 'segments'),
|
|
180
|
+
# (r'(?<=\.)seg(?=\[)', 'segments'),
|
|
181
|
+
# (r'(?<=^)isu', 'pac.isu'),
|
|
182
|
+
# (r'(?<=\.)isu', 'issuer'),
|
|
183
|
+
# (r'(?<=^)ext', 'pac.ext'),
|
|
184
|
+
# (r'(?<=\.)ext(?=$)', 'extensions'),
|
|
185
|
+
# (r'(?<=\.)ext(?=\[)', 'extensions'),
|
|
186
|
+
# ]
|
|
187
|
+
# for sub in substitutions:
|
|
188
|
+
# q_mod = re.sub(sub[0], sub[1], q_mod)
|
|
189
|
+
|
|
190
|
+
return q_mod
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _tokenize_jsonpath_expression(self, expr: str):
|
|
194
|
+
token_pattern = re.compile(
|
|
195
|
+
r"""
|
|
196
|
+
(?P<LPAREN>\() |
|
|
197
|
+
(?P<RPAREN>\)) |
|
|
198
|
+
(?P<LOGIC>\bAND\b|\bOR\b|\bNOT\b) |
|
|
199
|
+
(?P<OPERATOR>==|!=|<=|>=|<|>) |
|
|
200
|
+
(?P<JSONPATH>
|
|
201
|
+
\$ # starts with $
|
|
202
|
+
(?:
|
|
203
|
+
[^\s\[\]()]+ # path segments, dots, etc.
|
|
204
|
+
|
|
|
205
|
+
\[ # open bracket
|
|
206
|
+
(?: # non-capturing group
|
|
207
|
+
[^\[\]]+ # anything but brackets
|
|
208
|
+
|
|
|
209
|
+
\[[^\[\]]*\] # nested brackets (1 level)
|
|
210
|
+
)*
|
|
211
|
+
\]
|
|
212
|
+
)+ # one or more bracket/segment blocks
|
|
213
|
+
) |
|
|
214
|
+
(?P<LITERAL>
|
|
215
|
+
-?[\w\.\-]+ # domain-like literals
|
|
216
|
+
)
|
|
217
|
+
""",
|
|
218
|
+
re.VERBOSE
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
tokens = []
|
|
222
|
+
pos = 0
|
|
223
|
+
while pos < len(expr):
|
|
224
|
+
match = token_pattern.match(expr, pos)
|
|
225
|
+
if match:
|
|
226
|
+
group_type = match.lastgroup
|
|
227
|
+
value = match.group().strip()
|
|
228
|
+
tokens.append((value, group_type))
|
|
229
|
+
pos = match.end()
|
|
230
|
+
elif expr[pos].isspace():
|
|
231
|
+
pos += 1 # skip whitespace
|
|
232
|
+
else:
|
|
233
|
+
raise SyntaxError(f"Unexpected character at position {pos}: {expr[pos]}")
|
|
234
|
+
|
|
235
|
+
return tokens
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _expression_from_tokens(self, pac_id_json:str, tokens: tuple[str, str]):
|
|
239
|
+
out = []
|
|
240
|
+
for i in range(len(tokens)):
|
|
241
|
+
prev_token = tokens[i-1] if i > 0 else (None, None)
|
|
242
|
+
curr_token = tokens[i]
|
|
243
|
+
next_token = tokens[i+1] if i < len(tokens)-1 else (None, None)
|
|
244
|
+
if curr_token[1] == 'JSONPATH':
|
|
245
|
+
res = self._evaluate_jsonpath(pac_id_json, curr_token[0])
|
|
246
|
+
|
|
247
|
+
if prev_token[1] == 'OPERATOR' or next_token[1] == 'OPERATOR':
|
|
248
|
+
# if token is part of comparison return the value of the node
|
|
249
|
+
if len(res) == 0:
|
|
250
|
+
out.append('""')
|
|
251
|
+
else:
|
|
252
|
+
out.append(f'"{res[0].upper()}"')
|
|
253
|
+
else:
|
|
254
|
+
# if token is not part of comparison evaluate to boolean
|
|
255
|
+
if len(res) == 0:
|
|
256
|
+
out.append(False)
|
|
257
|
+
else:
|
|
258
|
+
out.append(True)
|
|
259
|
+
|
|
260
|
+
elif curr_token[1] == 'LOGIC':
|
|
261
|
+
out.append(curr_token[0].lower())
|
|
262
|
+
|
|
263
|
+
elif curr_token[1] == 'LITERAL':
|
|
264
|
+
t = curr_token[0]
|
|
265
|
+
if t[0] != '"':
|
|
266
|
+
t = '"' + t
|
|
267
|
+
if t[-1] != '"':
|
|
268
|
+
t = t + '"'
|
|
269
|
+
out.append(t.upper())
|
|
270
|
+
else:
|
|
271
|
+
out.append(curr_token[0])
|
|
272
|
+
|
|
273
|
+
s = ' '.join([str(e) for e in out])
|
|
274
|
+
return s
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _eval_url_template(self, pac_id_json, url_template):
|
|
280
|
+
url = url_template
|
|
281
|
+
placeholders = re.findall(r'\{(.+?)\}', url_template)
|
|
282
|
+
for placeholder in placeholders:
|
|
283
|
+
expanded_placeholder = self._apply_convenience_substitutions(placeholder)
|
|
284
|
+
res = self._evaluate_jsonpath(pac_id_json, expanded_placeholder) or ['']
|
|
285
|
+
url = url.replace(f'{{{placeholder}}}', str(res[0]))
|
|
286
|
+
# res = self.substitute_jsonpath_expressions(expanded_placeholder, Patterns.jsonpath.value, as_bool=False)
|
|
287
|
+
# url = url.replace(f'{{{placeholder}}}', res)
|
|
288
|
+
return url
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _evaluate_jsonpath(self, pac_id_json, jp_query):
|
|
293
|
+
if isinstance(pac_id_json, str):
|
|
294
|
+
pac_id_json = json.loads(pac_id_json)
|
|
295
|
+
jsonpath_expr = jsonpath.parse(jp_query)
|
|
296
|
+
matches = [match.value for match in jsonpath_expr.find(pac_id_json)]
|
|
297
|
+
return matches
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Self
|
|
3
|
+
import yaml
|
|
4
|
+
from requests import get
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
from labfreed.pac_cat.pac_cat import PAC_CAT
|
|
9
|
+
from labfreed.pac_id.pac_id import PAC_ID
|
|
10
|
+
from labfreed.pac_id_resolver.services import ServiceGroup
|
|
11
|
+
from labfreed.pac_id_resolver.cit_v1 import CIT_v1
|
|
12
|
+
from labfreed.pac_id_resolver.cit_v2 import CIT_v2
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
''' Configure pdoc'''
|
|
17
|
+
__all__ = ["PAC_ID_Resolver"]
|
|
18
|
+
|
|
19
|
+
def load_cit(path):
|
|
20
|
+
with open(path, 'r') as f:
|
|
21
|
+
s = f.read()
|
|
22
|
+
return _cit_from_str(s)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _cit_from_str(s:str, issuer:str='') -> CIT_v1|CIT_v2:
|
|
26
|
+
try:
|
|
27
|
+
cit_yml= yaml.safe_load(s)
|
|
28
|
+
cit2 = CIT_v2.from_yaml(cit_yml)
|
|
29
|
+
except Exception:
|
|
30
|
+
cit2 = None
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
cit1 = CIT_v1.from_csv(s, issuer)
|
|
34
|
+
except Exception:
|
|
35
|
+
cit1 = None
|
|
36
|
+
|
|
37
|
+
cit = cit2 or cit1 or None
|
|
38
|
+
return cit
|
|
39
|
+
|
|
40
|
+
def _get_issuer_cit(issuer:str):
|
|
41
|
+
'''Gets the issuer's cit.'''
|
|
42
|
+
url = 'HTTPS://PAC.' + issuer + '/coupling-information-table'
|
|
43
|
+
try:
|
|
44
|
+
r = get(url, timeout=2)
|
|
45
|
+
if r.status_code < 400:
|
|
46
|
+
cit_str = r.text
|
|
47
|
+
else:
|
|
48
|
+
logging.error(f"Could not get CIT form {issuer}")
|
|
49
|
+
cit_str = None
|
|
50
|
+
except Exception:
|
|
51
|
+
logging.error(f"Could not get CIT form {issuer}")
|
|
52
|
+
cit_str = None
|
|
53
|
+
cit = _cit_from_str(cit_str, issuer=issuer)
|
|
54
|
+
return cit
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class PAC_ID_Resolver():
|
|
59
|
+
def __init__(self, cits:list[CIT_v2|CIT_v1]=None) -> Self:
|
|
60
|
+
'''Initialize the resolver with coupling information tables'''
|
|
61
|
+
if not cits:
|
|
62
|
+
cits = []
|
|
63
|
+
self._cits = cits
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def resolve(self, pac_id:PAC_ID|str) -> list[ServiceGroup]:
|
|
67
|
+
'''Resolve a PAC-ID'''
|
|
68
|
+
if isinstance(pac_id, str):
|
|
69
|
+
pac_id = PAC_CAT.from_url(pac_id)
|
|
70
|
+
|
|
71
|
+
if issuer_cit := _get_issuer_cit(pac_id.issuer):
|
|
72
|
+
self._cits.append(issuer_cit)
|
|
73
|
+
|
|
74
|
+
matches = [cit.evaluate_pac_id(pac_id) for cit in self._cits]
|
|
75
|
+
return matches
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == '__main__':
|
|
80
|
+
r = PAC_ID_Resolver()
|
|
81
|
+
r.resolve()
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
|
|
2
|
+
from enum import auto, Enum
|
|
3
|
+
|
|
4
|
+
from pydantic import Field
|
|
5
|
+
from requests import RequestException, get, head
|
|
6
|
+
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
8
|
+
|
|
9
|
+
from rich import print
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
|
|
12
|
+
from labfreed.labfreed_infrastructure import LabFREED_BaseModel
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ServiceStatus(Enum):
|
|
16
|
+
ACTIVE = auto()
|
|
17
|
+
INACTIVE = auto()
|
|
18
|
+
UNKNOWN = auto()
|
|
19
|
+
|
|
20
|
+
class Service(LabFREED_BaseModel):
|
|
21
|
+
service_name: str
|
|
22
|
+
application_intents:list[str]
|
|
23
|
+
service_type:str
|
|
24
|
+
url:str
|
|
25
|
+
status:ServiceStatus =ServiceStatus.UNKNOWN
|
|
26
|
+
|
|
27
|
+
def check_service_status(self):
|
|
28
|
+
'''Checks the availability of the service.'''
|
|
29
|
+
try:
|
|
30
|
+
r = head(self.url, timeout=2)
|
|
31
|
+
if r.status_code < 400:
|
|
32
|
+
self.status = ServiceStatus.ACTIVE
|
|
33
|
+
else:
|
|
34
|
+
self.status = ServiceStatus.INACTIVE
|
|
35
|
+
except RequestException as e:
|
|
36
|
+
print(f"Request failed: {e}")
|
|
37
|
+
self.status = ServiceStatus.INACTIVE
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ServiceGroup(LabFREED_BaseModel):
|
|
41
|
+
""" Services with common origin. The result of resolving a PAC-ID against a CIT"""
|
|
42
|
+
origin: str = ""
|
|
43
|
+
services: list[Service] = Field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
def update_states(self):
|
|
46
|
+
'''Triggers each service to check if the url can be reached'''
|
|
47
|
+
if not _has_internet_connection():
|
|
48
|
+
raise ConnectionError("No Internet Connection")
|
|
49
|
+
with ThreadPoolExecutor(max_workers=10) as executor:
|
|
50
|
+
futures = [executor.submit(s.check_service_status) for s in self.services]
|
|
51
|
+
for _ in as_completed(futures):
|
|
52
|
+
pass # just wait for all to finish
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def __str__(self):
|
|
57
|
+
out = [f'CIT (origin {self.origin})']
|
|
58
|
+
for s in self.services:
|
|
59
|
+
out.append(f'{s.service_name}\t\t\t{s.url}')
|
|
60
|
+
return '\n'.join(out)
|
|
61
|
+
|
|
62
|
+
def print(self):
|
|
63
|
+
table = Table(title=f"Services from origin '{self.origin}")
|
|
64
|
+
|
|
65
|
+
table.add_column("Service Name")
|
|
66
|
+
table.add_column("URL")
|
|
67
|
+
table.add_column('Reachable')
|
|
68
|
+
|
|
69
|
+
for s in self.services:
|
|
70
|
+
table.add_row(s.service_name, s.url, s.status.name)
|
|
71
|
+
|
|
72
|
+
print(table)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _has_internet_connection():
|
|
76
|
+
try:
|
|
77
|
+
get("https://1.1.1.1", timeout=3)
|
|
78
|
+
return True
|
|
79
|
+
except RequestException:
|
|
80
|
+
return False
|
labfreed/__init__.py
CHANGED