aboutsummaryrefslogtreecommitdiff
path: root/src/mlia/core/workflow.py
blob: 02450874b6078a7f0147daf5dc9b3853f94e4d44 (plain)
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
# SPDX-FileCopyrightText: Copyright 2022, Arm Limited and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
"""Module for executors.

This module contains implementation of the workflow
executors.
"""
import itertools
from abc import ABC
from abc import abstractmethod
from functools import wraps
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple

from mlia.core.advice_generation import Advice
from mlia.core.advice_generation import AdviceEvent
from mlia.core.advice_generation import AdviceProducer
from mlia.core.common import DataItem
from mlia.core.context import Context
from mlia.core.data_analysis import DataAnalyzer
from mlia.core.data_collection import DataCollector
from mlia.core.errors import FunctionalityNotSupportedError
from mlia.core.events import AdviceStageFinishedEvent
from mlia.core.events import AdviceStageStartedEvent
from mlia.core.events import AnalyzedDataEvent
from mlia.core.events import CollectedDataEvent
from mlia.core.events import DataAnalysisStageFinishedEvent
from mlia.core.events import DataAnalysisStageStartedEvent
from mlia.core.events import DataCollectionStageFinishedEvent
from mlia.core.events import DataCollectionStageStartedEvent
from mlia.core.events import DataCollectorSkippedEvent
from mlia.core.events import Event
from mlia.core.events import ExecutionFailedEvent
from mlia.core.events import ExecutionFinishedEvent
from mlia.core.events import ExecutionStartedEvent
from mlia.core.events import stage
from mlia.core.mixins import ContextMixin


class WorkflowExecutor(ABC):
    """Base workflow executor."""

    @abstractmethod
    def run(self) -> None:
        """Run the module."""


STAGE_COLLECTION = (
    DataCollectionStageStartedEvent(),
    DataCollectionStageFinishedEvent(),
)
STAGE_ANALYSIS = (DataAnalysisStageStartedEvent(), DataAnalysisStageFinishedEvent())
STAGE_ADVICE = (AdviceStageStartedEvent(), AdviceStageFinishedEvent())


def on_stage(stage_events: Tuple[Event, Event]) -> Callable:
    """Mark start/finish of the stage with appropriate events."""

    def wrapper(method: Callable) -> Callable:
        """Wrap method."""

        @wraps(method)
        def publish_events(self: Any, *args: Any, **kwargs: Any) -> Any:
            """Publish events before and after execution."""
            with stage(self.context.event_publisher, stage_events):
                return method(self, *args, **kwargs)

        return publish_events

    return wrapper


class DefaultWorkflowExecutor(WorkflowExecutor):
    """Default module executor.

    This is a default implementation of the workflow executor.
    All components are launched sequentually in the same process.
    """

    def __init__(
        self,
        context: Context,
        collectors: Sequence[DataCollector],
        analyzers: Sequence[DataAnalyzer],
        producers: Sequence[AdviceProducer],
        before_start_events: Optional[Sequence[Event]] = None,
    ):
        """Init default workflow executor.

        :param context: Context instance
        :param collectors: List of the data collectors
        :param analyzers: List of the data analyzers
        :param producers: List of the advice producers
        :param before_start_events: Optional list of the custom events that
               should be published before start of the worfkow execution.
        """
        self.context = context
        self.collectors = collectors
        self.analyzers = analyzers
        self.producers = producers
        self.before_start_events = before_start_events

    def run(self) -> None:
        """Run the workflow."""
        self.inject_context()
        self.context.register_event_handlers()

        try:
            self.publish(ExecutionStartedEvent())

            self.before_start()

            collected_data = self.collect_data()
            analyzed_data = self.analyze_data(collected_data)

            self.produce_advice(analyzed_data)
        except Exception as err:  # pylint: disable=broad-except
            self.publish(ExecutionFailedEvent(err))
        else:
            self.publish(ExecutionFinishedEvent())

    def before_start(self) -> None:
        """Run actions before start of the workflow execution."""
        events = self.before_start_events or []
        for event in events:
            self.publish(event)

    @on_stage(STAGE_COLLECTION)
    def collect_data(self) -> List[DataItem]:
        """Collect data.

        Run each of data collector components and return list of
        the collected data items.
        """
        collected_data = []
        for collector in self.collectors:
            try:
                if (data_item := collector.collect_data()) is not None:
                    collected_data.append(data_item)
                    self.publish(CollectedDataEvent(data_item))
            except FunctionalityNotSupportedError as err:
                self.publish(DataCollectorSkippedEvent(collector.name(), str(err)))

        return collected_data

    @on_stage(STAGE_ANALYSIS)
    def analyze_data(self, collected_data: List[DataItem]) -> List[DataItem]:
        """Analyze data.

        Pass each collected data item into each data analyzer and
        return analyzed data.

        :param collected_data: list of collected data items
        """
        analyzed_data = []
        for analyzer in self.analyzers:
            for item in collected_data:
                analyzer.analyze_data(item)

            for data_item in analyzer.get_analyzed_data():
                analyzed_data.append(data_item)

                self.publish(AnalyzedDataEvent(data_item))
        return analyzed_data

    @on_stage(STAGE_ADVICE)
    def produce_advice(self, analyzed_data: List[DataItem]) -> None:
        """Produce advice.

        Pass each analyzed data item into each advice producer and
        publish generated advice.

        :param analyzed_data: list of analyzed data items
        """
        for producer in self.producers:
            for data_item in analyzed_data:
                producer.produce_advice(data_item)

            advice = producer.get_advice()
            if isinstance(advice, Advice):
                advice = [advice]

            for item in advice:
                self.publish(AdviceEvent(item))

    def inject_context(self) -> None:
        """Inject context object into components.

        Inject context object into components that supports context
        injection.
        """
        context_aware_components = (
            comp
            for comp in itertools.chain(
                self.collectors,
                self.analyzers,
                self.producers,
            )
            if isinstance(comp, ContextMixin)
        )

        for component in context_aware_components:
            component.set_context(self.context)

    def publish(self, event: Event) -> None:
        """Publish event.

        Helper method for event publising.

        :param event: event instance
        """
        self.context.event_publisher.publish_event(event)