-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathmrack.py
1450 lines (1116 loc) · 46 KB
/
mrack.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
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
import asyncio
import dataclasses
import datetime
import importlib.metadata
import logging
import os
import re
from collections.abc import Mapping
from contextlib import suppress
from functools import wraps
from typing import Any, Callable, Optional, TypedDict, Union, cast
import packaging.version
import tmt
import tmt.hardware
import tmt.log
import tmt.options
import tmt.steps
import tmt.steps.provision
import tmt.utils
from tmt.container import container, field, simple_field
from tmt.utils import (
Command,
Path,
ProvisionError,
ShellScript,
UpdatableMessage,
)
MRACK_VERSION: Optional[str] = None
mrack: Any
providers: Any
ProvisioningError: Any
NotAuthenticatedError: Any
BEAKER: Any
BeakerProvider: Any
BeakerTransformer: Any
TmtBeakerTransformer: Any
_MRACK_IMPORTED: bool = False
DEFAULT_USER = 'root'
DEFAULT_ARCH = 'x86_64'
DEFAULT_IMAGE = 'fedora'
DEFAULT_PROVISION_TIMEOUT = 3600 # 1 hour timeout at least
DEFAULT_PROVISION_TICK = 60 # poll job each minute
#: How often Beaker session should be refreshed to pick up up-to-date
#: Kerberos ticket.
DEFAULT_API_SESSION_REFRESH = 3600
def mrack_constructs_ks_pre() -> bool:
"""
Kickstart construction has been improved in 1.21.0
"""
assert MRACK_VERSION is not None
return packaging.version.Version(MRACK_VERSION) >= packaging.version.Version('1.21.0')
# Type annotation for "data" package describing a guest instance. Passed
# between load() and save() calls
class GuestInspectType(TypedDict):
status: str
system: str
address: Optional[str]
# Mapping of HW requirement operators to their Beaker representation.
OPERATOR_SIGN_TO_OPERATOR = {
tmt.hardware.Operator.EQ: '==',
tmt.hardware.Operator.NEQ: '!=',
tmt.hardware.Operator.GT: '>',
tmt.hardware.Operator.GTE: '>=',
tmt.hardware.Operator.LT: '<',
tmt.hardware.Operator.LTE: '<=',
}
def operator_to_beaker_op(operator: tmt.hardware.Operator, value: str) -> tuple[str, str, bool]:
"""
Convert constraint operator to Beaker "op".
:param operator: operator to convert.
:param value: value operator works with. It shall be a string representation
of the the constraint value, as converted for the Beaker job XML.
:returns: tuple of three items: Beaker operator, fit for ``op`` attribute
of XML filters, a value to go with it instead of the input one, and
a boolean signalizing whether the filter, constructed by the caller,
should be negated.
"""
if operator in OPERATOR_SIGN_TO_OPERATOR:
return OPERATOR_SIGN_TO_OPERATOR[operator], value, False
# MATCH has special handling - convert the pattern to a wildcard form -
# and that may be weird :/
if operator == tmt.hardware.Operator.MATCH:
return 'like', value.replace('.*', '%').replace('.+', '%'), False
if operator == tmt.hardware.Operator.NOTMATCH:
return 'like', value.replace('.*', '%').replace('.+', '%'), True
raise ProvisionError(f"Hardware requirement operator '{operator}' is not supported.")
# Transcription of our HW constraints into Mrack's own representation. It's based
# on dictionaries, and it's slightly weird. There is no distinction between elements
# that do not have attributes, like <and/>, and elements that must have them, like
# <memory/> and other binary operations. Also, there is no distinction between
# element attribute and child element, both are specified as dictionary key, just
# the former would be a string, the latter another, nested, dictionary.
#
# This makes it harder for us to enforce correct structure of the transcribed tree.
# Therefore adding a thin layer of containers that describe what Mrack is willing
# to accept, but with strict type annotations; the layer is aware of how to convert
# its components into dictionaries.
@container
class MrackBaseHWElement:
"""
Base for Mrack hardware requirement elements
"""
# Only a name is defined, as it's the only property shared across all element
# types.
name: str
def to_mrack(self) -> dict[str, Any]:
"""
Convert the element to Mrack-compatible dictionary tree
"""
raise NotImplementedError
@container
class MrackHWElement(MrackBaseHWElement):
"""
An element with name and attributes.
This type of element is not allowed to have any child elements.
"""
attributes: dict[str, str] = simple_field(default_factory=dict)
def to_mrack(self) -> dict[str, Any]:
return {self.name: self.attributes}
@container(init=False)
class MrackHWBinOp(MrackHWElement):
"""
An element describing a binary operation, a "check"
"""
def __init__(self, name: str, operator: str, value: str) -> None:
super().__init__(name)
self.attributes = {'_op': operator, '_value': value}
@container(init=False)
class MrackHWKeyValue(MrackHWElement):
"""
A key-value element
"""
def __init__(self, name: str, operator: str, value: str) -> None:
super().__init__('key_value')
self.attributes = {'_key': name, '_op': operator, '_value': value}
@container
class MrackHWGroup(MrackBaseHWElement):
"""
An element with child elements.
This type of element is not allowed to have any attributes.
"""
children: list[MrackBaseHWElement] = simple_field(default_factory=list)
def to_mrack(self) -> dict[str, Any]:
# Another unexpected behavior of mrack dictionary tree: if there is just
# a single child, it is "packed" into its parent as a key/dict item.
if len(self.children) == 1 and self.name not in ('and', 'or'):
return {self.name: self.children[0].to_mrack()}
return {self.name: [child.to_mrack() for child in self.children]}
@container
class MrackHWAndGroup(MrackHWGroup):
"""
Represents ``<and/>`` element
"""
name: str = 'and'
@container
class MrackHWOrGroup(MrackHWGroup):
"""
Represents ``<or/>`` element
"""
name: str = 'or'
@container
class MrackHWNotGroup(MrackHWGroup):
"""
Represents ``<not/>`` element
"""
name: str = 'not'
def _transform_unsupported(
constraint: tmt.hardware.Constraint[Any], logger: tmt.log.Logger
) -> MrackBaseHWElement:
# Unsupported constraint has been already logged via report_support(). Make
# sure user is aware it would have no effect, and since we have to return
# something, return an empty `or` group - no harm done, composable with other
# elements.
logger.warning(f"Hardware requirement '{constraint.printable_name}' will have no effect.")
return MrackHWOrGroup()
def _transform_beaker_pool(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(constraint.operator, constraint.value)
return MrackHWBinOp('pool', beaker_operator, actual_value)
def _transform_cpu_family(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('family', beaker_operator, actual_value)])
def _transform_cpu_flag(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator = (
OPERATOR_SIGN_TO_OPERATOR[tmt.hardware.Operator.EQ]
if constraint.operator is tmt.hardware.Operator.CONTAINS
else OPERATOR_SIGN_TO_OPERATOR[tmt.hardware.Operator.NEQ]
)
actual_value = str(constraint.value)
return MrackHWGroup('cpu', children=[MrackHWBinOp('flag', beaker_operator, actual_value)])
def _transform_cpu_model(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('model', beaker_operator, actual_value)])
def _transform_cpu_processors(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup(
'cpu', children=[MrackHWBinOp('processors', beaker_operator, actual_value)]
)
def _transform_cpu_cores(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('cores', beaker_operator, actual_value)])
def _transform_cpu_model_name(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'cpu', children=[MrackHWBinOp('model_name', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup(
'cpu', children=[MrackHWBinOp('model_name', beaker_operator, actual_value)]
)
def _transform_cpu_frequency(
constraint: tmt.hardware.NumberConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(float(constraint.value.to('MHz').magnitude))
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('speed', beaker_operator, actual_value)])
def _transform_cpu_stepping(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('stepping', beaker_operator, actual_value)])
def _transform_cpu_vendor_name(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'cpu', children=[MrackHWBinOp('vendor', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('vendor', beaker_operator, actual_value)])
def _transform_cpu_hyper_threading(
constraint: tmt.hardware.FlagConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup('cpu', children=[MrackHWBinOp('hyper', beaker_operator, actual_value)])
def _transform_disk_driver(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[MrackHWKeyValue('BOOTDISK', beaker_operator, actual_value)]
)
return MrackHWKeyValue('BOOTDISK', beaker_operator, actual_value)
def _transform_disk_size(
constraint: tmt.hardware.SizeConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(int(constraint.value.to('B').magnitude))
)
return MrackHWGroup('disk', children=[MrackHWBinOp('size', beaker_operator, actual_value)])
def _transform_disk_model_name(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'disk', children=[MrackHWBinOp('model', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup('disk', children=[MrackHWBinOp('model', beaker_operator, actual_value)])
def _transform_disk_physical_sector_size(
constraint: tmt.hardware.SizeConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup(
'disk', children=[MrackHWBinOp('phys_sector_size', beaker_operator, actual_value)]
)
def _transform_disk_logical_sector_size(
constraint: tmt.hardware.SizeConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup(
'disk', children=[MrackHWBinOp('sector_size', beaker_operator, actual_value)]
)
def _transform_hostname(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(children=[MrackHWBinOp('hostname', beaker_operator, actual_value)])
return MrackHWBinOp('hostname', beaker_operator, actual_value)
def _transform_memory(
constraint: tmt.hardware.SizeConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(int(constraint.value.to('MiB').magnitude))
)
return MrackHWGroup('system', children=[MrackHWBinOp('memory', beaker_operator, actual_value)])
def _transform_tpm_version(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(constraint.operator, constraint.value)
return MrackHWKeyValue('TPM', beaker_operator, actual_value)
def _transform_virtualization_is_virtualized(
constraint: tmt.hardware.FlagConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
test = (constraint.operator, constraint.value)
if test in [(tmt.hardware.Operator.EQ, True), (tmt.hardware.Operator.NEQ, False)]:
return MrackHWGroup('system', children=[MrackHWBinOp('hypervisor', '!=', '')])
if test in [(tmt.hardware.Operator.EQ, False), (tmt.hardware.Operator.NEQ, True)]:
return MrackHWGroup('system', children=[MrackHWBinOp('hypervisor', '==', '')])
return _transform_unsupported(constraint, logger)
def _transform_virtualization_hypervisor(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'system', children=[MrackHWBinOp('hypervisor', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup(
'system', children=[MrackHWBinOp('hypervisor', beaker_operator, actual_value)]
)
def _transform_zcrypt_adapter(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'system',
children=[MrackHWKeyValue('ZCRYPT_MODEL', beaker_operator, actual_value)],
)
]
)
return MrackHWGroup(
'system', children=[MrackHWKeyValue('ZCRYPT_MODEL', beaker_operator, actual_value)]
)
def _transform_zcrypt_mode(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'system',
children=[MrackHWKeyValue('ZCRYPT_MODE', beaker_operator, actual_value)],
)
]
)
return MrackHWGroup(
'system', children=[MrackHWKeyValue('ZCRYPT_MODE', beaker_operator, actual_value)]
)
def _transform_iommu_is_supported(
constraint: tmt.hardware.FlagConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
test = (constraint.operator, constraint.value)
if test in [(tmt.hardware.Operator.EQ, True), (tmt.hardware.Operator.NEQ, False)]:
return MrackHWKeyValue('VIRT_IOMMU', '==', '1')
if test in [(tmt.hardware.Operator.EQ, False), (tmt.hardware.Operator.NEQ, True)]:
return MrackHWKeyValue('VIRT_IOMMU', '==', '0')
return _transform_unsupported(constraint, logger)
def _transform_location_lab_controller(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
if constraint.operator not in [tmt.hardware.Operator.EQ, tmt.hardware.Operator.NEQ]:
raise ProvisionError(
f"Cannot apply hardware requirement '{constraint}', operator not supported."
)
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, constraint.value
)
if negate:
return MrackHWNotGroup(
children=[MrackHWBinOp('labcontroller', beaker_operator, actual_value)]
)
return MrackHWBinOp('labcontroller', beaker_operator, actual_value)
def _transform_system_numa_nodes(
constraint: tmt.hardware.IntegerConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, _ = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
return MrackHWGroup(
'system', children=[MrackHWBinOp('numanodes', beaker_operator, actual_value)]
)
def _transform_system_model_name(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'system', children=[MrackHWBinOp('model', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup('system', children=[MrackHWBinOp('model', beaker_operator, actual_value)])
def _transform_system_vendor_name(
constraint: tmt.hardware.TextConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
beaker_operator, actual_value, negate = operator_to_beaker_op(
constraint.operator, str(constraint.value)
)
if negate:
return MrackHWNotGroup(
children=[
MrackHWGroup(
'system', children=[MrackHWBinOp('vendor', beaker_operator, actual_value)]
)
]
)
return MrackHWGroup('system', children=[MrackHWBinOp('vendor', beaker_operator, actual_value)])
ConstraintTransformer = Callable[
[tmt.hardware.Constraint[Any], tmt.log.Logger], MrackBaseHWElement
]
_CONSTRAINT_TRANSFORMERS: Mapping[str, ConstraintTransformer] = {
'beaker.pool': _transform_beaker_pool, # type: ignore[dict-item]
'cpu.cores': _transform_cpu_cores, # type: ignore[dict-item]
'cpu.family': _transform_cpu_family, # type: ignore[dict-item]
'cpu.flag': _transform_cpu_flag, # type: ignore[dict-item]
'cpu.frequency': _transform_cpu_frequency, # type: ignore[dict-item]
'cpu.hyper_threading': _transform_cpu_hyper_threading, # type: ignore[dict-item]
'cpu.model': _transform_cpu_model, # type: ignore[dict-item]
'cpu.model_name': _transform_cpu_model_name, # type: ignore[dict-item]
'cpu.processors': _transform_cpu_processors, # type: ignore[dict-item]
'cpu.stepping': _transform_cpu_stepping, # type: ignore[dict-item]
'cpu.vendor_name': _transform_cpu_vendor_name, # type: ignore[dict-item]
'disk.driver': _transform_disk_driver, # type: ignore[dict-item]
'disk.model_name': _transform_disk_model_name, # type: ignore[dict-item]
'disk.size': _transform_disk_size, # type: ignore[dict-item]
'disk.physical_sector_size': _transform_disk_physical_sector_size, # type: ignore[dict-item]
'disk.logical_sector_size': _transform_disk_logical_sector_size, # type: ignore[dict-item]
'hostname': _transform_hostname, # type: ignore[dict-item]
'location.lab_controller': _transform_location_lab_controller, # type: ignore[dict-item]
'memory': _transform_memory, # type: ignore[dict-item]
'tpm.version': _transform_tpm_version, # type: ignore[dict-item]
'virtualization.is_virtualized': _transform_virtualization_is_virtualized, # type: ignore[dict-item]
'virtualization.hypervisor': _transform_virtualization_hypervisor, # type: ignore[dict-item]
'zcrypt.adapter': _transform_zcrypt_adapter, # type: ignore[dict-item]
'zcrypt.mode': _transform_zcrypt_mode, # type: ignore[dict-item]
'system.numa_nodes': _transform_system_numa_nodes, # type: ignore[dict-item]
'system.model_name': _transform_system_model_name, # type: ignore[dict-item]
'system.vendor_name': _transform_system_vendor_name, # type: ignore[dict-item]
'iommu.is_supported': _transform_iommu_is_supported, # type: ignore[dict-item]
}
def constraint_to_beaker_filter(
constraint: tmt.hardware.BaseConstraint, logger: tmt.log.Logger
) -> MrackBaseHWElement:
"""
Convert a hardware constraint into a Mrack-compatible filter
"""
if isinstance(constraint, tmt.hardware.And):
return MrackHWAndGroup(
children=[
constraint_to_beaker_filter(child_constraint, logger)
for child_constraint in constraint.constraints
]
)
if isinstance(constraint, tmt.hardware.Or):
return MrackHWOrGroup(
children=[
constraint_to_beaker_filter(child_constraint, logger)
for child_constraint in constraint.constraints
]
)
assert isinstance(constraint, tmt.hardware.Constraint)
name, _, child_name = constraint.expand_name()
if child_name:
transformer = _CONSTRAINT_TRANSFORMERS.get(f'{name}.{child_name}')
else:
transformer = _CONSTRAINT_TRANSFORMERS.get(name)
if transformer:
return transformer(constraint, logger)
return _transform_unsupported(constraint, logger)
def import_and_load_mrack_deps(workdir: Any, name: str, logger: tmt.log.Logger) -> None:
"""
Import mrack module only when needed
"""
global _MRACK_IMPORTED
if _MRACK_IMPORTED:
return
global MRACK_VERSION
global mrack
global providers
global ProvisioningError
global NotAuthenticatedError
global BEAKER
global BeakerProvider
global BeakerTransformer
global TmtBeakerTransformer
try:
import mrack
from mrack.errors import NotAuthenticatedError, ProvisioningError
from mrack.providers import providers
from mrack.providers.beaker import PROVISIONER_KEY as BEAKER
from mrack.providers.beaker import BeakerProvider
from mrack.transformers.beaker import BeakerTransformer
MRACK_VERSION = importlib.metadata.version('mrack')
# hack: remove mrack stdout and move the logfile to /tmp
mrack.logger.removeHandler(mrack.console_handler)
mrack.logger.removeHandler(mrack.file_handler)
with suppress(OSError):
os.remove("mrack.log")
logging.FileHandler(str(f"{workdir}/{name}-mrack.log"))
providers.register(BEAKER, BeakerProvider)
except ImportError:
raise ProvisionError("Install 'tmt+provision-beaker' to provision using this method.")
# ignore the misc because mrack sources are not typed and result into
# error: Class cannot subclass "BeakerTransformer" (has type "Any")
# as mypy does not have type information for the BeakerTransformer class
class TmtBeakerTransformer(BeakerTransformer): # type: ignore[misc]
def _translate_tmt_hw(self, hw: tmt.hardware.Hardware) -> dict[str, Any]:
"""
Return hw requirements from given hw dictionary
"""
assert hw.constraint
# Beaker, unlike instance-type-based infrastructures like AWS, does
# have the actual filtering, and can express `or` and `and`
# groups. And our `constraint_to_beaker_filter()` does that,
# even for groups nested deeper in the tree.
transformed = constraint_to_beaker_filter(hw.constraint, logger)
logger.debug('Transformed hardware', tmt.utils.dict_to_yaml(transformed.to_mrack()))
# Mrack does not handle well situation when the filter
# consists of just a single filtering element, e.g. just
# `hostname`. In that case, the element is converted into
# XML element incorrectly. Therefore wrapping our filter
# with `<and/>` group, even if it has just a single child,
# it works around the problem.
# See https://github.com/teemtee/tmt/issues/3442
return {'hostRequires': MrackHWAndGroup(children=[transformed]).to_mrack()}
def create_host_requirement(self, host: CreateJobParameters) -> dict[str, Any]:
"""
Create single input for Beaker provisioner
"""
req: dict[str, Any] = super().create_host_requirement(host.to_mrack())
if host.hardware and host.hardware.constraint:
req.update(self._translate_tmt_hw(host.hardware))
if host.beaker_job_owner:
req['job_owner'] = host.beaker_job_owner
if host.kickstart:
if 'kernel-options' in host.kickstart:
req['kernel_options'] = host.kickstart['kernel-options']
if 'kernel-options-post' in host.kickstart:
req['kernel_options_post'] = host.kickstart['kernel-options-post']
if not mrack_constructs_ks_pre():
ks_components: list[str] = []
for ks_section in ('pre-install', 'script', 'post-install'):
if ks_section in host.kickstart:
ks_components.append(host.kickstart[ks_section])
if ks_components:
req['ks_append'] = ['\n'.join(ks_components)]
# Whiteboard must be added *after* request preparation, to overwrite the default one.
req['whiteboard'] = host.whiteboard
logger.debug('mrack request', req, level=4)
logger.info('whiteboard', host.whiteboard, 'green')
return req
_MRACK_IMPORTED = True
def async_run(func: Any) -> Any:
"""
Decorate click actions to run as async
"""
@wraps(func)
def update_wrapper(*args: Any, **kwargs: Any) -> Any:
return asyncio.run(func(*args, **kwargs))
return update_wrapper
@container
class BeakerGuestData(tmt.steps.provision.GuestSshData):
# Override parent class with our defaults
user: str = field(
default=DEFAULT_USER,
option=('-u', '--user'),
metavar='USERNAME',
help='Username to use for all guest operations.',
)
# Guest request properties
whiteboard: Optional[str] = field(
default=None,
option=('-w', '--whiteboard'),
metavar='WHITEBOARD',
help='Text description of the beaker job which is displayed in the list of jobs.',
)
arch: str = field(
default=DEFAULT_ARCH,
option='--arch',
metavar='ARCH',
help='Architecture to provision.',
)
image: Optional[str] = field(
default=DEFAULT_IMAGE,
option=('-i', '--image'),
metavar='COMPOSE',
help='Image (distro or "compose" in Beaker terminology) to provision.',
)
# Provided in Beaker job
job_id: Optional[str] = field(
default=None,
internal=True,
)
# Timeouts and deadlines
provision_timeout: int = field(
default=DEFAULT_PROVISION_TIMEOUT,
option='--provision-timeout',
metavar='SECONDS',
help=f"""
How long to wait for provisioning to complete,
{DEFAULT_PROVISION_TIMEOUT} seconds by default.
""",
normalize=tmt.utils.normalize_int,
)
provision_tick: int = field(
default=DEFAULT_PROVISION_TICK,
option='--provision-tick',
metavar='SECONDS',
help=f"""
How often check Beaker for provisioning status,
{DEFAULT_PROVISION_TICK} seconds by default.
""",
normalize=tmt.utils.normalize_int,
)
api_session_refresh_tick: int = field(
default=DEFAULT_API_SESSION_REFRESH,
option='--api-session-refresh-tick',
metavar='SECONDS',
help=f"""
How often should Beaker session be refreshed to pick up-to-date Kerberos ticket,
{DEFAULT_API_SESSION_REFRESH} seconds by default.
""",
normalize=tmt.utils.normalize_int,
)
kickstart: dict[str, str] = field(
default_factory=dict,
option='--kickstart',
metavar='KEY=VALUE',
help='Optional Beaker kickstart to use when provisioning the guest.',
multiple=True,
normalize=tmt.utils.normalize_string_dict,
)
beaker_job_owner: Optional[str] = field(
default=None,
option='--beaker-job-owner',
metavar='USERNAME',
help="""
If set, Beaker jobs will be submitted on behalf of ``USERNAME``.
Submitting user must be a submission delegate for the ``USERNAME``.
""",
)
public_key: list[str] = field(
default_factory=list,
option='--public-key',
metavar='PUBKEY',
help="""
Public keys to add among authorized SSH keys.
""",
multiple=True,
normalize=tmt.utils.normalize_string_list,
)
beaker_job_group: Optional[str] = field(
default=None,
option='--beaker-job-group',
metavar='GROUPNAME',
help="""
If set, Beaker jobs will be submitted on behalf of ``GROUPNAME``.
""",
)
@container
class ProvisionBeakerData(BeakerGuestData, tmt.steps.provision.ProvisionStepData):
pass
GUEST_STATE_COLOR_DEFAULT = 'green'
GUEST_STATE_COLORS = {
"New": "blue",
"Scheduled": "blue",
"Queued": "cyan",
"Processed": "cyan",
"Waiting": "magenta",
"Installing": "magenta",
"Running": "magenta",
"Cancelled": "yellow",
"Aborted": "yellow",
"Reserved": "green",
"Completed": "green",
}
@container
class CreateJobParameters:
"""
Collect all parameters for a future Beaker job
"""
tmt_name: str
name: str
os: str
arch: str
hardware: Optional[tmt.hardware.Hardware]
kickstart: dict[str, str]
whiteboard: Optional[str]
beaker_job_owner: Optional[str]
public_key: list[str]
group: Optional[str]
def to_mrack(self) -> dict[str, Any]:
data = dataclasses.asdict(self)
data['beaker'] = {}
if self.kickstart:
kickstart = self.kickstart.copy()
if 'metadata' in kickstart:
data['beaker']['ks_meta'] = kickstart.pop('metadata')
# Mrack does not handle metadata-only kickstart nicely, ends
# up with just an empty string. Don't tempt it, don't let it
# see kickstart if it was just metadata.
if kickstart:
data['beaker']['ks_append'] = kickstart
if self.public_key:
data['beaker']['pubkeys'] = self.public_key
return data
class BeakerAPI: