xstack 2.0.2__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.
xstack/stack.py ADDED
@@ -0,0 +1,1078 @@
1
+ import os
2
+ import copy
3
+ import time
4
+ import json
5
+ import typing
6
+ import logging
7
+ import functools
8
+ import traceback
9
+ import factories
10
+ import signalling
11
+
12
+ from . import constants
13
+ from . import compat
14
+ from . import address
15
+ from .constants import Status
16
+ from .component import Component
17
+ from .component import MissingComponent
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ # -- The deprecated component names already reported as resolved, so each is
22
+ # -- only logged once per session
23
+ _LOGGED_DEPRECATED_NAMES = set()
24
+
25
+
26
+ # --------------------------------------------------------------------------------------
27
+ class Stack:
28
+ """
29
+ This class is the main class of stackx and represents the actual stack object.
30
+
31
+ This is typically the class you will interact with and utilise to add components
32
+ to the stack.
33
+
34
+ Args:
35
+ label: This is a human-readable identifier for the stack that has no bearing
36
+ component_paths: A list of paths that should be added to the component library
37
+ when the stack is instanced
38
+ component_base_class: This allows for any subclassing of the Stack object to
39
+ specify their own base class for components. Note, that if you do pass a
40
+ custom base class, your base class must still inherit from Component class.
41
+
42
+ This class exposes a series of signals to help intergrate it into UI elements or
43
+ other frameworks. These are:
44
+
45
+ component_added(component_instance): Emitted after a component has been added to
46
+ the stack
47
+
48
+ component_removed(component_instance): Emitted after a component has been
49
+ removed from the stack. Note, that this component will not show any more
50
+ in Stack.components()
51
+
52
+ hierarchy_changed(): Emitted when an item is moved in the hierarchy or build order.
53
+
54
+ changed(): Emitted whenever a component is added or removed or the build order
55
+ is changed in any way.
56
+
57
+ build_started(): Emitted when a build (or validation) starts.
58
+
59
+ build_progressed(percentage): Emitted as each component is built.
60
+
61
+ build_completed(): Emitted when a build completes successfully. It is not
62
+ emitted when a build fails.
63
+
64
+ build_finished(successful): Emitted whenever a build (or validation) that
65
+ emitted build_started ends, whether it succeeded or not.
66
+
67
+ build_failed(component, details): Emitted before build_finished when a build
68
+ fails, with the first component that failed or was invalid (or None if
69
+ the failure was not down to one component), and the reason as text -
70
+ the traceback if the component raised an exception.
71
+
72
+ Builds started from within a component's run (nested builds) emit none of
73
+ the build signals: the outer build reports the overall result.
74
+
75
+ component_reporting(component, stage): Emitted just before the build report
76
+ lines for a component are printed, where stage is "validate" or
77
+ "build". Unlike the build signals it is emitted in nested builds too,
78
+ so a listener (such as the app's log) can find each component's part
79
+ of the report.
80
+ """
81
+ status = constants.Status
82
+
83
+ # -- The class used to stand in for components whose type is not
84
+ # -- available when loading serialised data
85
+ missing_component_class = MissingComponent
86
+
87
+ # ----------------------------------------------------------------------------------
88
+ def __init__(
89
+ self,
90
+ label: str = "",
91
+ component_paths: typing.Optional[typing.List] = None,
92
+ component_base_class=Component
93
+ ):
94
+ super().__init__()
95
+
96
+ # -- The label of a stack has no functional bearing, but can be useful
97
+ # -- from a usability perspective.
98
+ self.label: str = label
99
+
100
+ # -- We do not hard code the base class. We do expect all base classes to
101
+ # -- ultimately inherit from xstack.Component, but by allowing you to specify
102
+ # -- your own base class that inherits from the xstack.Component means you
103
+ # -- can provide a more tailored expoerience.
104
+ self.component_base_class = component_base_class
105
+
106
+ # -- This is where our components should be sourced from
107
+ self.component_paths: typing.List = component_paths or list()
108
+
109
+ # -- The build hierarchy is held as a list of root components;
110
+ # -- each component owns its own children, so the full tree is
111
+ # -- reachable by walking from each root.
112
+ self.root_components = list()
113
+
114
+ # -- Declare our signals. These are useful for other classes
115
+ # -- to bind into
116
+ self.component_added = signalling.Signal()
117
+ self.component_removed = signalling.Signal()
118
+ self.hierarchy_changed = signalling.Signal()
119
+ self.changed = signalling.Signal()
120
+
121
+ self.build_started = signalling.Signal()
122
+ self.build_progressed = signalling.Signal()
123
+ self.build_completed = signalling.Signal()
124
+ self.build_finished = signalling.Signal()
125
+ self.build_failed = signalling.Signal()
126
+ self.component_reporting = signalling.Signal()
127
+
128
+ # -- The build_below components of the builds currently running, outermost
129
+ # -- first. Anything in this list means we are inside a build.
130
+ self._active_builds: typing.List = list()
131
+
132
+ # -- The first failure reported by a nested build, so the outer build
133
+ # -- can report the component that actually failed
134
+ self._nested_failure = None
135
+
136
+ @functools.cached_property
137
+ def component_library(self) -> factories.Factory:
138
+ """
139
+ This will return a factory class giving access to all the available components.
140
+
141
+ Note that it is a cached property, as we do not want to re-instance the factory
142
+ each time it is called.
143
+ """
144
+
145
+ # -- Get a copy of our component path list
146
+ paths = self.component_paths[:]
147
+
148
+ # -- Add in any paths given to us by our environment
149
+ paths.extend(
150
+ os.environ.get(constants.COMPONENT_PATHS_ENVVAR, "").split(",")
151
+ )
152
+
153
+ # -- Remove any null entries
154
+ paths = [
155
+ p
156
+ for p in paths
157
+ if p
158
+ ]
159
+
160
+ # -- Instance the factory
161
+ lib = factories.Factory(
162
+ abstract=self.component_base_class,
163
+ paths=paths,
164
+ plugin_identifier="identifier",
165
+ )
166
+
167
+ return lib
168
+
169
+ def resolve_component_type(self, component_type: str) -> str:
170
+ """
171
+ Returns the current identifier for the given component type. This is
172
+ the component type itself if a component has that identifier, otherwise
173
+ the identifier of the component which lists it in its deprecated_names.
174
+
175
+ If nothing matches, the component type is returned unchanged, so callers
176
+ report it as missing just as they would without this.
177
+ """
178
+ library = self.component_library
179
+
180
+ # -- A current identifier always wins, and is by far the most common
181
+ # -- case, so renamed components cost nothing until an old name is used
182
+ if not component_type or component_type in library.identifiers(include_disabled=True):
183
+ return component_type
184
+
185
+ for plugin in library.plugins(include_disabled=True):
186
+ deprecated_names = getattr(plugin, "deprecated_names", None)
187
+
188
+ # -- A bare string would otherwise be searched character by character
189
+ if not isinstance(deprecated_names, (list, tuple)):
190
+ continue
191
+
192
+ if component_type in deprecated_names:
193
+ if component_type not in _LOGGED_DEPRECATED_NAMES:
194
+ _LOGGED_DEPRECATED_NAMES.add(component_type)
195
+ log.info(
196
+ f"'{component_type}' is a deprecated name for '{plugin.identifier}', "
197
+ f"and will be saved as '{plugin.identifier}'"
198
+ )
199
+ return plugin.identifier
200
+
201
+ return component_type
202
+
203
+ def add_component(
204
+ self,
205
+ component_type: str,
206
+ label: str,
207
+ inputs: typing.Dict = None,
208
+ options: typing.Dict = None,
209
+ parent: Component = None,
210
+ child_index=None,
211
+ force_uuid: str = None,
212
+ suppress_events: bool = False,
213
+ ) -> typing.Optional[Component]:
214
+ """
215
+ This will add a component of the given component type to the stack with the given
216
+ label.
217
+
218
+ Any inputs or options passed will have those values set at the time the
219
+ component is added. Any that the component does not declare are skipped
220
+ with a warning.
221
+
222
+ If a parent uuid is given it will be assigned as a child of that component in
223
+ the build order. If one is not given then it will be added to the end of the
224
+ builder order list.
225
+
226
+ if a forced uuid is given then the component will be assigned that uuid at time
227
+ of initialisation rather than one being generated. This is typically only used
228
+ when loading from pre-defined data.
229
+
230
+ None is returned if the component type is not available or fails to
231
+ initialise.
232
+
233
+ The component type may be one of a component's deprecated_names, in
234
+ which case that component is added (with its current identifier).
235
+ """
236
+ component_type = self.resolve_component_type(component_type)
237
+
238
+ # -- Check we can access this component type
239
+ if component_type not in self.component_library.identifiers():
240
+ log.warning(f"{component_type} is not recognised")
241
+ return None
242
+
243
+ # -- We're instancing a class which comes from third party code. Because of
244
+ # -- this, we wrap it in a broad exception test
245
+ # noinspection PyBroadException
246
+ try:
247
+ component_instance: Component = self.component_library.request(
248
+ component_type,
249
+ )(
250
+ label=label,
251
+ stack=self,
252
+ uuid_=force_uuid,
253
+ )
254
+
255
+ except Exception:
256
+ log.exception(f"Failed to initialise component: {component_type}")
257
+ return None
258
+
259
+ return self._add_component_instance(
260
+ component_instance,
261
+ inputs=inputs,
262
+ options=options,
263
+ parent=parent,
264
+ child_index=child_index,
265
+ suppress_events=suppress_events,
266
+ )
267
+
268
+ def _add_component_instance(
269
+ self,
270
+ component_instance: Component,
271
+ inputs: typing.Dict = None,
272
+ options: typing.Dict = None,
273
+ parent: Component = None,
274
+ child_index=None,
275
+ suppress_events: bool = False,
276
+ ) -> Component:
277
+ """
278
+ Applies the given inputs and options to an instanced component and adds it
279
+ into the hierarchy of the stack.
280
+ """
281
+ component_type = component_instance.identifier
282
+
283
+ # -- If we're given a parent, inherit any attributes that are flagged
284
+ # -- as expecting inheritance.
285
+ if parent:
286
+ for option in component_instance.options():
287
+ if not option.should_inherit():
288
+ continue
289
+ parent_option = parent.option(option.name())
290
+ if parent_option:
291
+ option.set(parent_option.get())
292
+
293
+ for input_ in component_instance.inputs():
294
+ if not input_.should_inherit():
295
+ continue
296
+ parent_input = parent.input(input_.name())
297
+ if parent_input:
298
+ input_.set(parent_input.get())
299
+
300
+ # -- Set any option values we were given
301
+ for option_name, value in (options or dict()).items():
302
+ option = component_instance.option(option_name)
303
+
304
+ if not option:
305
+ log.warning(
306
+ f"{component_instance.label()} ({component_type}) has no option "
307
+ f"called '{option_name}', so its value has been dropped"
308
+ )
309
+ continue
310
+
311
+ option.set(value)
312
+
313
+ # -- Set any input values we were given
314
+ for input_name, value in (inputs or dict()).items():
315
+ input_ = component_instance.input(input_name)
316
+
317
+ if not input_:
318
+ log.warning(
319
+ f"{component_instance.label()} ({component_type}) has no input "
320
+ f"called '{input_name}', so its value has been dropped"
321
+ )
322
+ continue
323
+
324
+ input_.set(value)
325
+
326
+ # -- Whenever we have value changes, ensure we save the result
327
+ component_instance.changed.connect(self.changed.emit)
328
+ component_instance.set_parent(parent, child_index=child_index)
329
+
330
+ # -- Call the enter stack feature
331
+ if not suppress_events:
332
+ component_instance.on_enter_stack()
333
+
334
+ # -- Emit the fact that we have added the component and the
335
+ # -- state has changed
336
+ self.component_added.emit(component_instance)
337
+ self.changed.emit()
338
+
339
+ return component_instance
340
+
341
+ def remove_component(self, component: Component) -> bool:
342
+ """
343
+ This will remove the given component, and recursively all of its
344
+ descendants, from the stack. Each removed component receives an
345
+ ``on_removed_from_stack`` callback and the stack emits a
346
+ ``component_removed`` signal per component.
347
+ """
348
+ # -- Snapshot the children list before recursing — remove_component
349
+ # -- mutates parent.children, which would shift indices mid-iteration.
350
+ for child in list(component.children):
351
+ self.remove_component(child)
352
+
353
+ component.set_parent(None)
354
+ self.root_components.remove(component)
355
+
356
+ # noinspection PyBroadException
357
+ try:
358
+ component.on_removed_from_stack()
359
+ except Exception:
360
+ log.exception(f"on_removed_from_stack failed for {component.label()}")
361
+
362
+ self.component_removed.emit()
363
+ self.changed.emit()
364
+
365
+ return True
366
+
367
+ def serialise(self) -> typing.Dict:
368
+ """
369
+ This will serialise the stack down to a json format from which it can later
370
+ be deserialised.
371
+
372
+ :return: dict
373
+ """
374
+ return dict(
375
+ label=self.label,
376
+ tree=[
377
+ root.serialise()
378
+ for root in self.root_components
379
+ ],
380
+ format="galaxy"
381
+ )
382
+
383
+ def deserialize(self, data: typing.Dict, clear: bool = True):
384
+ """
385
+ This will take in a dictionary (of the format provided by the serialise
386
+ method. The class will then be populated by all the data in that dictionary.
387
+
388
+ Args:
389
+ data: The dictionary of data to read the component list from
390
+ clear: If True (default), any existing components are removed
391
+ before deserialising. Pass False to append the loaded tree
392
+ to the existing components.
393
+
394
+ Note:
395
+ This method uses the American spelling for historical
396
+ reasons; the equivalent British-spelling alias
397
+ :meth:`deserialise` is available and fully equivalent.
398
+ Subclasses that need to extend the behaviour should
399
+ override ``deserialize`` (the canonical implementation);
400
+ both names will route through to the override.
401
+
402
+ :return:
403
+ """
404
+ if clear:
405
+ self.clear()
406
+
407
+ # -- Ensure any legacy data format is converted
408
+ # -- to the latest data format
409
+ data = compat.to_latest(data)
410
+ self.label = data.get("label", "stack")
411
+
412
+ self._add_child_components(parent=None, child_list=data.get("tree", []))
413
+
414
+ def deserialise(self, data: typing.Dict, clear: bool = True):
415
+ """
416
+ British-spelling alias for :meth:`deserialize`. Both methods
417
+ are fully equivalent — pick whichever matches your codebase's
418
+ convention. This alias routes through to ``deserialize`` so
419
+ subclass overrides on the canonical name continue to work.
420
+ """
421
+ return self.deserialize(data, clear=clear)
422
+
423
+ def _add_child_components(self, parent, child_list, regenerate_uuids=False):
424
+ for child_data in child_list:
425
+ self._add_component_from_data(
426
+ child_data,
427
+ parent=parent,
428
+ regenerate_uuids=regenerate_uuids,
429
+ )
430
+
431
+ def _add_component_from_data(self, data: typing.Dict, parent, regenerate_uuids=False) -> Component:
432
+ """
433
+ Adds a component, and all its children, from serialised data.
434
+
435
+ Data saved by an older version of the component is migrated first. If the
436
+ component type is not available (or fails to initialise) a placeholder of
437
+ missing_component_class is added instead, which keeps the data so that
438
+ nothing is lost when the stack is next serialised.
439
+
440
+ Data saved under one of a component's deprecated_names is given that
441
+ component's current identifier before anything else (including
442
+ migrate) sees it.
443
+ """
444
+ component_type = self.resolve_component_type(data["component_type"])
445
+ if component_type != data["component_type"]:
446
+ data = dict(data, component_type=component_type)
447
+
448
+ force_uuid = None if regenerate_uuids else data.get("uuid")
449
+
450
+ component_class = None
451
+ if component_type in self.component_library.identifiers():
452
+ component_class = self.component_library.request(component_type)
453
+
454
+ # -- Data saved before components were versioned counts as version 1
455
+ stored_version = data.get("version", 1)
456
+
457
+ if component_class and stored_version < component_class.version:
458
+
459
+ # noinspection PyBroadException
460
+ try:
461
+ data = component_class.migrate(copy.deepcopy(data), stored_version)
462
+
463
+ except Exception:
464
+ log.exception(
465
+ f"Failed to migrate {data['label']} ({component_type}) from version "
466
+ f"{stored_version} to {component_class.version}"
467
+ )
468
+ component_class = None
469
+
470
+ component = None
471
+
472
+ if component_class:
473
+ component = self.add_component(
474
+ component_type,
475
+ data["label"],
476
+ inputs=data.get("inputs"),
477
+ options=data.get("options"),
478
+ force_uuid=force_uuid,
479
+ suppress_events=True,
480
+ parent=parent,
481
+ )
482
+
483
+ if not component:
484
+ log.warning(
485
+ f"The component type '{component_type}' could not be loaded, so "
486
+ f"{data['label']} has been loaded as a placeholder. It keeps its data "
487
+ f"but cannot be built."
488
+ )
489
+ component = self._add_component_instance(
490
+ self.missing_component_class(
491
+ label=data["label"],
492
+ stack=self,
493
+ uuid_=force_uuid,
494
+ missing_identifier=component_type,
495
+ data=data,
496
+ ),
497
+ parent=parent,
498
+ suppress_events=True,
499
+ )
500
+
501
+ # -- If the component was marked as disabled, then we disable it
502
+ # -- now
503
+ if not data.get("enabled", True):
504
+ component.set_enabled(False)
505
+
506
+ # -- Let the component restore any additional data before its
507
+ # -- children are added, as they may rely on it
508
+ component.deserialise_additional_data(data.get("additional_data"))
509
+
510
+ # -- Create any children
511
+ self._add_child_components(
512
+ component,
513
+ data.get("children", []),
514
+ regenerate_uuids=regenerate_uuids,
515
+ )
516
+
517
+ return component
518
+
519
+ def import_subtree_under(self, parent: "Component|None", filepath: str) -> None:
520
+ """
521
+ Load a serialised subtree from a JSON file and add the root
522
+ components in that file as children of the given parent.
523
+
524
+ Accepts files produced by both ``Component.save_settings()``
525
+ (single-component shape) and ``Stack.save()`` (full-stack shape
526
+ with a ``tree`` key). In the latter case, every root component
527
+ in the file becomes a child of ``parent``.
528
+
529
+ All component UUIDs are regenerated to avoid collisions with
530
+ existing components in this stack. Labels are preserved, so any
531
+ internal cross-references (which are label-based) continue to
532
+ work after import. If a loaded component has a label that
533
+ already exists in this stack, a warning is logged — address
534
+ resolution will pick the first matching label, which may not be
535
+ the intended one.
536
+
537
+ :param parent: The Component to attach the loaded subtree to,
538
+ or None to add the loaded components as root components.
539
+ :param filepath: Absolute path to the JSON file.
540
+ """
541
+ if not filepath or not os.path.exists(filepath):
542
+ log.warning(f"{filepath} does not exist")
543
+ return
544
+
545
+ with open(filepath, "r") as f:
546
+ data = json.load(f)
547
+
548
+ # -- Files saved via Component.save_settings() are a single
549
+ # -- component dict; files saved via Stack.save() are a stack
550
+ # -- dict with a "tree" key (or legacy "build_order"). Only run
551
+ # -- the compat upgrader on stack-format data — single-component
552
+ # -- dicts have no versioned format to raise.
553
+ if "tree" in data or "build_order" in data:
554
+ data = compat.to_latest(data)
555
+
556
+ if "tree" in data:
557
+ roots = data["tree"]
558
+ else:
559
+ roots = [data]
560
+
561
+ # -- Warn about any label collisions before adding the new
562
+ # -- components, since address resolution is label-based.
563
+ existing_labels = {
564
+ component.label()
565
+ for component in self.components()
566
+ }
567
+ incoming_labels = self._collect_labels(roots)
568
+ collisions = existing_labels & incoming_labels
569
+ if collisions:
570
+ log.warning(
571
+ f"xstack.import_subtree_under: label collision(s) with existing "
572
+ f"components: {sorted(collisions)}. Address resolution may be "
573
+ f"ambiguous; consider renaming."
574
+ )
575
+
576
+ self._add_child_components(
577
+ parent=parent,
578
+ child_list=roots,
579
+ regenerate_uuids=True,
580
+ )
581
+
582
+ self.hierarchy_changed.emit()
583
+
584
+ @classmethod
585
+ def _collect_labels(cls, child_list: typing.List) -> set:
586
+ """
587
+ Walks a serialised child list and returns the set of every
588
+ label present in the tree.
589
+ """
590
+ labels = set()
591
+ for child_data in child_list:
592
+ labels.add(child_data["label"])
593
+ labels.update(cls._collect_labels(child_data.get("children", [])))
594
+ return labels
595
+
596
+ def save(self, filepath, additional_data=None):
597
+ """
598
+ Saves the serialised data to a filepath, including any additional
599
+ data.
600
+ """
601
+ if not filepath:
602
+ log.warning("No filepath given to save to")
603
+ return
604
+
605
+ # -- Ensure we're fully serialised
606
+ data = self.serialise()
607
+ data["additional_data"] = additional_data
608
+
609
+ with open(filepath, 'w') as f:
610
+ json.dump(
611
+ data,
612
+ f,
613
+ sort_keys=False,
614
+ indent=4,
615
+ )
616
+
617
+ def clear(self):
618
+ """
619
+ Removes every component from the stack, firing
620
+ ``component_removed`` and the component's
621
+ ``on_removed_from_stack`` callback for each one — symmetric
622
+ with :meth:`remove_component` so listeners and plugins see a
623
+ consistent teardown.
624
+ """
625
+ # -- Snapshot the component list in build order before we
626
+ # -- start mutating anything. We need descendants too, not
627
+ # -- just root_components.
628
+ components = self.components()
629
+
630
+ for component in components:
631
+ # noinspection PyBroadException
632
+ try:
633
+ component.on_removed_from_stack()
634
+ except Exception:
635
+ log.exception(f"on_removed_from_stack failed for {component.label()}")
636
+ self.component_removed.emit()
637
+
638
+ self.root_components = []
639
+ self.changed.emit()
640
+
641
+ @classmethod
642
+ def open(
643
+ cls,
644
+ data: typing.Union[str, typing.Dict],
645
+ component_paths: typing.Optional[typing.List] = None,
646
+ ) -> "Stack":
647
+ """
648
+ Loads a Stack from either a JSON file path or an in-memory
649
+ dict produced by :meth:`serialise`.
650
+
651
+ :param data: Either a filepath to a JSON file, or the parsed
652
+ dict directly.
653
+ :param component_paths: Optional list of paths to add to the
654
+ new stack's component library on construction.
655
+ :raises FileNotFoundError: If ``data`` is a string but is
656
+ empty or refers to a missing file.
657
+ """
658
+ if isinstance(data, str):
659
+ if not data:
660
+ raise FileNotFoundError(
661
+ "Stack.open requires a non-empty filepath or a dict."
662
+ )
663
+
664
+ if not os.path.exists(data):
665
+ raise FileNotFoundError(f"Stack file not found: {data}")
666
+
667
+ with open(data, "r") as f:
668
+ data = json.load(f)
669
+
670
+ stack = cls(
671
+ label=data["label"],
672
+ component_paths=component_paths or list(),
673
+ )
674
+
675
+ # -- Deserialise into the freshly-constructed stack. ``deserialize``
676
+ # -- clears by default, but the stack has nothing to clear here.
677
+ stack.deserialize(data)
678
+
679
+ return stack
680
+
681
+ def components(self, from_component=None, of_type=None):
682
+ """
683
+ Returns a list of all components used in the active stack. This is always
684
+ returned in build order.
685
+ """
686
+ # -- Declare our list of components
687
+ all_components = []
688
+
689
+ # -- This function will cycle children (in order) and add those too
690
+ def process_children(sub_component):
691
+ for child in sub_component.children:
692
+ all_components.append(child)
693
+ process_children(child)
694
+
695
+ start_points = [from_component] if from_component else self.root_components
696
+ for component in start_points:
697
+ all_components.append(component)
698
+ process_children(component)
699
+
700
+ if of_type:
701
+ of_type = self.resolve_component_type(of_type)
702
+ all_components = [
703
+ component
704
+ for component in all_components
705
+ if component.identifier == of_type
706
+ ]
707
+
708
+ return all_components
709
+
710
+ def get_component_by_uuid(self, uuid_: str) -> typing.Optional[Component]:
711
+ """
712
+ This will cycle the hierarchy and search it for a component
713
+ with the given uuid.
714
+ """
715
+ for component in self.components():
716
+ if component.uuid() == uuid_:
717
+ return component
718
+
719
+ return None
720
+
721
+ def get_component_by_label(self, label, of_type=None) -> typing.Optional[Component]:
722
+ """
723
+ This will cycle the hierarchy and search it for a component
724
+ with the given uuid.
725
+ """
726
+ of_type = self.resolve_component_type(of_type)
727
+
728
+ for component in self.components():
729
+
730
+ # -- If we're specifically looking for a particular
731
+ # -- type then ignore anything which is not of that
732
+ # -- type.
733
+ if of_type and not component.identifier == of_type:
734
+ continue
735
+
736
+ if component.label() == label:
737
+ return component
738
+
739
+ return None
740
+
741
+ def get_component_by_type(self, of_type) -> typing.Optional[Component]:
742
+ """
743
+ This will cycle the hierarchy and search it for a component
744
+ with the given uuid.
745
+ """
746
+ of_type = self.resolve_component_type(of_type)
747
+
748
+ for component in self.components():
749
+
750
+ # -- If we're specifically looking for a particular
751
+ # -- type then ignore anything which is not of that
752
+ # -- type.
753
+ if of_type == component.identifier:
754
+ return component
755
+ return None
756
+
757
+ def _get_components_to_build(
758
+ self,
759
+ build_up_to: Component = None,
760
+ build_only: Component = None,
761
+ build_below: Component = None,
762
+ ):
763
+ # -- Pick the candidate set: the subtree below a given
764
+ # -- component (build_below), or the whole stack otherwise.
765
+ # -- The filter loop below runs the same way for both so
766
+ # -- ``is_enabled`` / ``build_up_to`` / ``build_only`` are
767
+ # -- honoured consistently regardless of entry point.
768
+ if build_below:
769
+ candidates = self.components(from_component=build_below)
770
+ else:
771
+ candidates = self.components()
772
+
773
+ components = []
774
+ for component in candidates:
775
+
776
+ # -- A disabled component also disables all of its children
777
+ if not self._is_enabled_in_hierarchy(component):
778
+ continue
779
+
780
+ if build_only and component != build_only:
781
+ continue
782
+
783
+ # -- This is where we need to perform the build.
784
+ components.append(component)
785
+
786
+ # -- End of the build
787
+ if build_up_to and component == build_up_to:
788
+ break
789
+ return components
790
+
791
+ @staticmethod
792
+ def _is_enabled_in_hierarchy(component: Component) -> bool:
793
+ """
794
+ Returns True if the component and all of its ancestors are enabled
795
+ """
796
+ while component:
797
+ if not component.is_enabled():
798
+ return False
799
+ component = component.parent
800
+ return True
801
+
802
+ def is_building(self) -> bool:
803
+ """
804
+ Returns True whilst a build (or validation) of this stack is running
805
+ """
806
+ return bool(self._active_builds)
807
+
808
+ def build(
809
+ self,
810
+ build_up_to: Component = None,
811
+ build_only: Component = None,
812
+ build_below: Component = None,
813
+ validate_only: bool = False
814
+ ) -> bool:
815
+ """
816
+ This is the main function for building/executing the stack. You can choose to build
817
+ up to a certain point in the build hierarchy or choose to build only a
818
+ specific component.
819
+
820
+ If neither are specified then all components will be built within the defined
821
+ build order.
822
+
823
+ A build started from within a component's run is a nested build. It only
824
+ resets the status of the components it builds, emits no build signals, and
825
+ is refused if it would build something that is already being built (such
826
+ as two execution blocks which run each other).
827
+ """
828
+ nested = self.is_building()
829
+
830
+ if nested and build_below in self._active_builds:
831
+ target = build_below.label() if build_below else "The stack"
832
+ log.error(
833
+ f"{target} is already being built, so it cannot be built again "
834
+ f"from within its own build. Check for components which run each "
835
+ f"other's builds."
836
+ )
837
+ self._nested_failure = None
838
+ return False
839
+
840
+ self._active_builds.append(build_below)
841
+
842
+ try:
843
+ return self._build(
844
+ build_up_to=build_up_to,
845
+ build_only=build_only,
846
+ build_below=build_below,
847
+ validate_only=validate_only,
848
+ nested=nested,
849
+ )
850
+
851
+ finally:
852
+ self._active_builds.pop()
853
+
854
+ def _build(self, build_up_to, build_only, build_below, validate_only, nested) -> bool:
855
+ """
856
+ Performs the build for the build method, which manages nesting
857
+ """
858
+ if not nested:
859
+ self._nested_failure = None
860
+ self.build_started.emit()
861
+
862
+ components_to_build = self._get_components_to_build(
863
+ build_up_to=build_up_to,
864
+ build_only=build_only,
865
+ build_below=build_below,
866
+ )
867
+
868
+ # -- Before doing any thing, ensure we have set every component
869
+ # -- to not executed. A nested build leaves the status of the outer
870
+ # -- build's components alone.
871
+ for component in components_to_build if nested else self.components():
872
+ component.set_status(
873
+ Status.NotExecuted,
874
+ )
875
+
876
+ overall_build_start = time.time()
877
+
878
+ # -- The first component to fail, and why
879
+ failure = None
880
+
881
+ # -- Cycle the build order. Note that we are not building at this point,
882
+ # -- we are doing a full pass over all the components and checking they
883
+ # -- are valid. If there are invalid components, we still continue, but
884
+ # -- we log the fact and set the status.
885
+ for component in components_to_build:
886
+
887
+ # -- We're executing third party code at this point, so we cannot
888
+ # -- gaurantee the quality of execution. Therefore we wrap it in
889
+ # -- a try, to ensure a failure in the third party code does not
890
+ # -- cause a failure at the stackx level
891
+ # -- The validate and build lines below are the build report rather
892
+ # -- than diagnostics, so they are printed as they are. A log record
893
+ # -- only prefixes its first line, which breaks the report's columns.
894
+ # noinspection PyBroadException
895
+ try:
896
+ self.component_reporting.emit(component, "validate")
897
+ print(f"About to Validate : {component.label()}")
898
+
899
+ if not component.is_valid():
900
+ component.set_status(
901
+ Status.Invalid,
902
+ )
903
+
904
+ reason = f"{component.label()} FAILED its is_valid test"
905
+ log.warning(reason)
906
+ failure = failure or (component, reason)
907
+
908
+ for input_ in component.inputs():
909
+ if input_.requires_validation() and not input_.validate():
910
+ reason = f"{input_.name()} for {component.label()} is not set"
911
+ log.warning(reason)
912
+ failure = failure or (component, reason)
913
+
914
+ component.set_status(Status.Invalid)
915
+
916
+ except Exception:
917
+ log.exception(f"{component.label()} failed during validation check")
918
+ component.set_status(
919
+ Status.Failed,
920
+ )
921
+ failure = failure or (component, traceback.format_exc())
922
+
923
+ if failure:
924
+ log.warning("Validation failed - please see output for details")
925
+ return self._finish_build(False, nested, failure=failure)
926
+
927
+ # -- If we only wanted to perform validation, we can exit at this point
928
+ if validate_only:
929
+ return self._finish_build(True, nested, validate_only=True)
930
+
931
+ # -- Run the pre-build events
932
+ self.run_events(components_to_build, "on_build_started")
933
+
934
+ # -- We now re-cycle over the build order but this time we will trigger the build
935
+ for idx, component in enumerate(components_to_build):
936
+
937
+ # -- Emit a progression signal
938
+ if not nested:
939
+ percentage = (float(idx) / len(components_to_build)) * 100
940
+ self.build_progressed.emit(percentage)
941
+
942
+ start_time = time.time()
943
+
944
+ # -- Any nested build this component runs will record its failure here
945
+ self._nested_failure = None
946
+
947
+ # -- Just as during the validation, we're executing third party code, so
948
+ # -- we wrap this process in a broad exception
949
+ # noinspection PyBroadException
950
+ try:
951
+ self.component_reporting.emit(component, "build")
952
+ print(f"About to Build : {component.label()}")
953
+ component.describe()
954
+ result = component.wrapped_run()
955
+ component.describe_outputs()
956
+ print(
957
+ f"Component Build Status : {component.status()} "
958
+ f"({time.time() - start_time:.3f}s)"
959
+ )
960
+
961
+ except Exception:
962
+ log.exception("Build failed")
963
+ component.set_status(Status.Failed)
964
+ failure = (component, traceback.format_exc())
965
+ result = False
966
+
967
+ if not result:
968
+
969
+ # -- Where the component failed because a build it ran failed,
970
+ # -- report the component which actually failed
971
+ failure = failure or self._nested_failure or (component, component.last_error())
972
+
973
+ self.run_events(components_to_build, "on_build_finished", False)
974
+ return self._finish_build(False, nested, failure=failure)
975
+
976
+ # -- Emit our completion
977
+ self.run_events(components_to_build, "on_build_finished", True)
978
+ print(f"Build Succeeded. ({time.time() - overall_build_start:.3f}s)")
979
+
980
+ return self._finish_build(True, nested)
981
+
982
+ def _finish_build(self, successful: bool, nested: bool, failure=None, validate_only=False) -> bool:
983
+ """
984
+ Emits the signals for the end of a build and returns whether it was
985
+ successful. A nested build emits nothing, but records its failure so
986
+ the outer build can report it.
987
+ """
988
+ if nested:
989
+ if not successful:
990
+ self._nested_failure = failure
991
+ return successful
992
+
993
+ if successful and not validate_only:
994
+ self.build_progressed.emit(100)
995
+ self.build_completed.emit()
996
+
997
+ if not successful:
998
+ component, details = failure or (None, "")
999
+ self.build_failed.emit(component, details)
1000
+
1001
+ self.build_finished.emit(successful)
1002
+ return successful
1003
+
1004
+ def run_events(self, components, event_name, *args, **kwargs):
1005
+ for component in components:
1006
+ # noinspection PyBroadException
1007
+ try:
1008
+ func_ = getattr(component, event_name)
1009
+ func_(*args, **kwargs)
1010
+
1011
+ except Exception:
1012
+ log.exception(f"{component.label()} failed during {event_name}")
1013
+
1014
+ # ----------------------------------------------------------------------------------
1015
+ def resolve_attribute(self, attribute_address):
1016
+ return address.get_attribute(
1017
+ attribute_address,
1018
+ stack=self,
1019
+ )
1020
+
1021
+ def replace_component(self, component: "xstack.Component", new_component_type: str):
1022
+ """
1023
+ This will replace the given component with a new component of the given
1024
+ component type.
1025
+
1026
+ Where options or inputs match the data will be carried over. All children
1027
+ will also be carried over. This includes the stored data of a
1028
+ MissingComponent, so switching one to an available type keeps its values.
1029
+ """
1030
+ component_parent = component.parent
1031
+ component_child_index = component.child_index()
1032
+
1033
+ new_component = self.add_component(
1034
+ component_type=new_component_type,
1035
+ label=component.label(),
1036
+ parent=None,
1037
+ )
1038
+ new_component.set_parent(component_parent, component_child_index)
1039
+
1040
+ if isinstance(component, MissingComponent):
1041
+ stored_data = component.serialise()
1042
+ option_values = stored_data.get("options") or dict()
1043
+ input_values = stored_data.get("inputs") or dict()
1044
+
1045
+ else:
1046
+ option_values = {
1047
+ option.name(): option.get(resolved=False)
1048
+ for option in component.options()
1049
+ }
1050
+ input_values = {
1051
+ input_.name(): input_.get(resolved=False)
1052
+ for input_ in component.inputs()
1053
+ }
1054
+
1055
+ # -- Propogate any matching option data
1056
+ for name, value in option_values.items():
1057
+ if new_component.option(name):
1058
+ new_component.option(name).set(value)
1059
+
1060
+ # -- Propogate any matching inputs
1061
+ for name, value in input_values.items():
1062
+ if new_component.input(name):
1063
+ new_component.input(name).set(value)
1064
+
1065
+ # -- Make all the children of the component become
1066
+ # -- children of the new component instead
1067
+ indices = dict()
1068
+ for child in component.children[:]:
1069
+ indices[child] = child.child_index()
1070
+
1071
+ for child, child_index in indices.items():
1072
+ child.set_parent(new_component, child_index=child_index)
1073
+
1074
+ # -- Now we can remove the component
1075
+ self.remove_component(component)
1076
+ self.hierarchy_changed.emit()
1077
+
1078
+ return new_component