-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathapplication.py
4515 lines (4034 loc) · 258 KB
/
application.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
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import concurrent.futures
import copy
import json
import logging
import os
import socket
import time
from concurrent.futures import Executor
from datetime import datetime, timedelta
from enum import Enum
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Set, Tuple, Type, Union, cast
from intelliflow.core.application.context.context import Context
from intelliflow.core.application.context.instruction import Instruction
from intelliflow.core.application.context.node.base import AlarmNode, CompositeAlarmNode, DataNode, MetricNode, Node, TimerNode
from intelliflow.core.application.context.node.external.alarm.nodes import ExternalAlarmNode
from intelliflow.core.application.context.node.external.metric.nodes import ExternalMetricNode
from intelliflow.core.application.context.node.external.nodes import ExternalDataNode
from intelliflow.core.application.context.node.filtered_views import FilteredView
from intelliflow.core.application.context.node.internal.alarm.nodes import InternalAlarmNode, InternalCompositeAlarmNode
from intelliflow.core.application.context.node.internal.metric.nodes import InternalMetricNode
from intelliflow.core.application.context.node.internal.nodes import InternalDataNode
from intelliflow.core.application.context.node.marshaling.nodes import MarshalerNode, MarshalingView
from intelliflow.core.deployment import is_on_remote_dev_env
from intelliflow.core.entity import CoreData
from intelliflow.core.platform.compute_targets.descriptor import ComputeDescriptor
from intelliflow.core.platform.constructs import BaseConstruct, ConstructSecurityConf, FeedBackSignalProcessingMode, RoutingTable
from intelliflow.core.platform.definitions.compute import (
ComputeFailedSessionState,
ComputeFailedSessionStateType,
ComputeLogQuery,
ComputeResponseType,
ComputeSessionStateType,
)
from intelliflow.core.platform.development import Configuration, HostPlatform
from intelliflow.core.platform.endpoint import DevEndpoint
from intelliflow.core.serialization import DeserializationError, SerializationError, dumps, loads
from intelliflow.core.signal_processing.definitions.dimension_defs import NameType as OutputDimensionNameType
from intelliflow.core.signal_processing.definitions.metric_alarm_defs import (
AlarmComparisonOperator,
AlarmDefaultActionsMap,
AlarmParams,
AlarmRule,
AlarmTreatMissingData,
AlarmType,
CompositeAlarmParams,
MetricExpression,
MetricSubDimensionMap,
MetricSubDimensionMapType,
)
from intelliflow.core.signal_processing.dimension_constructs import (
DIMENSION_VARIANT_IDENTICAL_MAP_FUNC,
AnyVariant,
Dimension,
DimensionFilter,
DimensionSpec,
DimensionVariant,
DimensionVariantFactory,
DimensionVariantMapFunc,
RawDimensionFilterInput,
RelativeVariant,
)
from intelliflow.core.signal_processing.routing_runtime_constructs import (
Route,
RouteExecutionHook,
RouteID,
RoutePendingNodeHook,
RoutingSession,
RuntimeLinkNode,
)
from intelliflow.core.signal_processing.signal import (
DimensionLinkMatrix,
Signal,
SignalDimensionLink,
SignalDimensionTuple,
SignalDomainSpec,
SignalIntegrityProtocol,
SignalLinkNode,
SignalProvider,
SignalType,
)
from intelliflow.core.signal_processing.signal_source import (
DataFrameFormat,
DatasetSignalSourceAccessSpec,
DatasetSignalSourceFormat,
InternalDatasetSignalSourceAccessSpec,
SignalSourceAccessSpec,
SignalSourceType,
SystemSignalSourceAccessSpec,
)
from intelliflow.core.signal_processing.slot import SlotType
from .core_application import ApplicationID, ApplicationState, CoreApplication
logger = logging.getLogger(__name__)
class _DevPersistedState(CoreData):
def __init__(self, serialized_dev_context: str) -> None:
self.serialized_dev_context = serialized_dev_context
class Application(CoreApplication):
class QueryContext(Enum):
DEV_CONTEXT = 1
ACTIVE_RUNTIME_CONTEXT = 2
ALL = 3
class QueryApplicationScope(Enum):
CURRENT_APP_ONLY = 1
EXTERNAL_APPS_ONLY = 2
ALL = 3
class IncompatibleRuntime(Exception):
pass
def __init__(self, id: ApplicationID, platform: HostPlatform, enforce_runtime_compatibility: bool = True) -> None:
try:
super().__init__(id, platform, enforce_runtime_compatibility)
except (ModuleNotFoundError, AttributeError, SerializationError, DeserializationError) as error:
raise Application.IncompatibleRuntime(
f"Unable to load previously activated application state due to a missing or incompatible module already used at runtime",
error,
)
self._dev_context: Context = Context()
if self._incompatible_runtime or platform.incompatible_runtime:
# add a sanity-check to make sure that active state or platform deserialization would not swallow any incompatibility while compatibility is enforced
assert (
not enforce_runtime_compatibility
), "Application initialization should start with incompatible active state or platform state while runtime compatibility is enforced!"
# reset activated
logger.critical(
f"Terminating incompatible activated runtime [enforce_runtime_compatibility={enforce_runtime_compatibility}]..."
)
# here the goal is to make sure that we let platform (drivers) to reset incompatible data all across the system (e.g RoutingTable data)
self._hard_reset(id, platform)
def _hard_reset(self, id: ApplicationID, platform: HostPlatform):
self._state = ApplicationState.INACTIVE
self._active_context = Context()
# do a flip to reset system. we need to activate first to have an active platform that can terminate itself
self.activate()
self.terminate()
# re-init to resume the construction flow
self._incompatible_runtime = False
platform._incompatible_runtime = False
Application.__init__(self, id, platform, enforce_runtime_compatibility=True)
logger.critical(f"Application got reset! Development and active contexts must be empty now.")
def attach(self):
if self._active_context:
self._dev_context = self._active_context.clone()
def save_dev_state(self) -> None:
dev_state = _DevPersistedState(self._dev_context.serialize(True))
persisted_state: str = dumps(dev_state)
self._platform.storage.save(persisted_state, [Application.__name__], _DevPersistedState.__name__)
def load_dev_state(self) -> None:
if self._platform.storage.check_object([Application.__name__], _DevPersistedState.__name__):
persisted_state: str = self._platform.storage.load([Application.__name__], _DevPersistedState.__name__)
saved_state: _DevPersistedState = loads(persisted_state)
self._dev_context = loads(saved_state.serialized_dev_context)
self._dev_context._deserialized_init(self._platform)
@property
def dev_context(self) -> Context:
return self._dev_context
@property
def uuid(self) -> str:
return self._platform.conf._generate_unique_id_for_context()
def provision_remote_dev_env(self, endpoint_attrs: Dict[str, Any]) -> DevEndpoint:
"""Adds or updates a remote dev-env (e.g notebook) relying on the current
configuration of the platform.
For example; AWSConfiguration -> Sagemaker Notebook Instance
Returns a DevEndpoint object which can be used to analyze, start and stop the remote endpoint.
"""
return cast("HostPlatform", self.platform).provision_remote_dev_env(endpoint_attrs)
def get_remote_dev_env(self) -> DevEndpoint:
return cast("HostPlatform", self.platform).get_remote_dev_env()
def activate(self, allow_concurrent_executions=True) -> None:
"""Interpret dev context and generate platform code in the forms of
- Signals, Routes and Platform (up/downstream) connections
Warning: this API is not synchronized. it is client's (application owner's) responsibility to manage/avoid
possible concurrent calls to this API for the same application, from the same [other threads/processes] or
other endpoints].
:param allow_concurrent_executions: enables a strict orchestration to control concurrent (async) executions
that would use the older version of the application and cause complications.
"""
logger.critical(f"Activating application: {self.id!r}")
self._dev_context.check_referential_integrity()
if self.platform.terminated or self.state == ApplicationState.TERMINATING:
# support re-activating a terminated app instance.
# simply go through the same logic in Application::__init__ on behalf of the client.
# otherwise, clients would need to create a new application instance with the same platform
# for reactivation.
self.platform.context_id = self.id
self.platform.terminated = False
if not allow_concurrent_executions and self._state == ApplicationState.ACTIVE:
logger.critical(f"Concurrent executions are not allowed. Pausing background/remote signal processing...")
self.pause()
logger.critical(f"Signal processing paused!")
while self.has_active_routes():
active_route_records = self.get_active_routes()
logger.critical(f"There are still {len(active_route_records)} active routes/nodes.")
logger.critical(f"Route IDs: {[r.route.route_id for r in active_route_records]!r}")
logger.critical(f"Waiting for 60 seconds...")
time.sleep(60)
self.update_active_routes_status()
logger.critical("All routes idle now! Resuming the activation process...")
if self._active_context:
# get downstream/upstream change set
for remote_app in self._active_context.external_data - self._dev_context.external_data:
self._platform.disconnect_upstream(remote_app.platform)
for downstream_dependency in self._active_context.downstream_dependencies - self._dev_context.downstream_dependencies:
self._platform.disconnect_downstream(downstream_dependency.id, downstream_dependency.conf)
# new platform connections, Signals and Routes will be generated by the following call to _dev_context.
self._dev_context.activate(self._platform)
self._platform.activate()
self._activation_completed()
# current dev context is now the active state
self._active_context = self._dev_context.clone()
try:
self._platform.processor.resume()
except Exception as err:
logger.critical(f"An error {err!r} encountered while resuming the application after the successful activation.")
logger.critical(
f"Application is in a coherent state but still PAUSED. A subsequent call on "
f"Application::resume API might help recover from this state."
)
raise err
self._state = ApplicationState.ACTIVE
# persist the core / active state.
super()._save()
logger.critical(f"Activation complete!")
def _activation_completed(self) -> None:
# first iterate over updated nodes
# we will skip checking upstream 'create_data' calls on this. we have to use the updated node information
# and compute_targets from 'update_data' API (if any)
def _notify(self, instruction: Instruction):
# TODO indexed access will be removed when Instruction will get the API stackframe via inject
compute_descriptors: Sequence[ComputeDescriptor] = instruction.args[5]
if compute_descriptors:
for comp_desc in compute_descriptors:
comp_desc.activation_completed(self.platform)
execution_hook: Optional[RouteExecutionHook] = instruction.args[6]
pending_node_hook: Optional[RoutePendingNodeHook] = instruction.args[7]
for hook in (execution_hook, pending_node_hook):
if hook:
for callback in hook.callbacks():
if isinstance(callback, ComputeDescriptor):
callback.activation_completed(self.platform)
updated_nodes = set()
for instruction in self._dev_context.instruction_chain:
if instruction.user_command == "update_data":
_notify(self, instruction)
updated_nodes.add(instruction.output_node.route_id)
for instruction in self._dev_context.instruction_chain:
if instruction.user_command == "create_data" and instruction.output_node.route_id not in updated_nodes:
_notify(self, instruction)
def terminate(self, wait_for_active_routes=False) -> None:
"""Do a graceful shutdown of the whole application.
Graceful in a way that it is logically the inverse of activation.
It is comprehensive, guaranteed to reverse the activation (if any).
This approach enables us to achieve reuse in low-level termination sequences as well.
It is like going back to a state where it can be assumed that there has been no activations before,
keeping the data from the active state intact. It does not change the current development context but
nullifies the active state. So in order to activate again, same application object can be reused to call
'activate' yielding the same active state from before the termination.
And more importantly, it is ok to make repetitive calls to this API. It is safe to do that
even in scenarios where the workflow fails and another attempt is intended to complete the
termination.
But it is not safe to call this API concurrently (on the same machine or from other endpoints).
:param wait_for_active_routes: graceful shutdown in terms of active executions, application will
pause but also wait for active executions to end in order to achieve a steady-state, only then
will resume the actual termination process.
"""
if self._state not in [ApplicationState.ACTIVE, ApplicationState.PAUSED, ApplicationState.TERMINATING]:
raise RuntimeError(f"Cannot terminate while application state is {self._state!r}!")
logger.critical(f"Terminating application: {self.id!r}")
logger.critical(f"Pausing background/remote signal processing...")
self.pause()
logger.critical(f"Signal processing paused!")
if wait_for_active_routes:
# sleep some time allow event propagation after the pause. if some events that were received before
# the pause are still being processed, then this duration will be enough for them to go through routing
# and possibly trigger executions. Those possible executions will be tracked in the subsequent loop.
time.sleep(5)
logger.critical("Checking active routes/executions...")
while self.has_active_routes():
active_route_records = self.get_active_routes()
logger.critical(f"There are still {len(active_route_records)} active routes/nodes.")
logger.critical(f"Route IDs: {[r.route.route_id for r in active_route_records]!r}")
logger.critical(f"Waiting for 60 seconds...")
time.sleep(60)
self.update_active_routes_status()
logger.critical("All routes idle now! Resuming the termination process...")
self._state = ApplicationState.TERMINATING
super()._save()
# detach from upstream/downstreams
# why is this important? it is to make sure that downstream access (via RemoteApplication, etc) won't be
# possible and cause undefined behaviour from this point on.
# and also for upstream applications to get notified from this termination.
if self._active_context:
for remote_app in self._active_context.external_data:
self._platform.disconnect_upstream(remote_app.platform)
for downstream_dependency in self._active_context.downstream_dependencies:
self._platform.disconnect_downstream(downstream_dependency.id, downstream_dependency.conf)
self._platform.terminate()
self._state = ApplicationState.INACTIVE
self._active_context = Context()
super()._save()
def delete(self) -> None:
"""Delete the remaining resources/data of an inactive (or terminated) app.
Why is this separate from 'terminate' API?
Because, we want to separate the deallocation of runtime resources from internal data which might in some
scenarios intended to outlive an RheocerOS application. A safe-guard against deleting peta-bytes of data
as part of the termination. Independent from the app, data might be used by other purposes. Or more importantly,
same data can be hooked up by the reincarnated version of the same application (as long as the ID and platform
configuration match). So we are providing this flexibility to the user.
And in a more trivial scenario where an application needs to be deleted before even an activation happens,
then this API can be used to clean up the resources (e.g application data in storage). Because, RheocerOS
applications are distributed right from begining (instantiation), even before the activation and might require
resource allocation.
Upon successful execution of this command, using this Application object will not be allowed.
If the same internal data is intended to be reused again, then a new Application object with the same ID and
platform configuration should be created.
"""
if self._state == ApplicationState.INACTIVE:
logger.critical(f"Deleting application: {self.id!r}")
self._platform.delete()
self._state = ApplicationState.DELETED
else:
raise RuntimeError("Only an INACTIVE (terminated) Application can be deleted. You might need to call 'terminate()' first.")
def pause(self) -> None:
if self._state == ApplicationState.ACTIVE:
self._platform.processor.pause()
self._state = ApplicationState.PAUSED
super()._save()
logger.critical("Application paused!")
else:
logger.critical(f"Cannot pause the application while the state is {self._state!r}! " f"It should be ACTIVE.")
def resume(self) -> None:
if self._state == ApplicationState.PAUSED:
self._platform.processor.resume()
self._state = ApplicationState.ACTIVE
super()._save()
logger.critical("Application resumed! Ingesting pending or new signals...")
else:
logger.critical(f"Cannot resume the application while the state is {self._state!r}! " f"It should be PAUSED.")
# overrides
def refresh(self, full_stack: bool = False) -> None:
# important for use-cases such as mount/link support (collaboration) and visualization
if not full_stack:
# HostPlatform does not support refresh, that is against the whole point behind
# forward-looking development effort. Refresh might invalidate platform/conf updates/overwrites.
# So for Application we intend to update the (Core state) active_context only (i.e collaborative editing against same
# app).
CoreApplication._sync(self)
else:
# re-loads platform / drivers for a consistent sync required for development
# e.g Visualization does a sync to retrieve newly activated app state. if we don't use full_stack in that
# case then underlying driver instances might get sync'd with the new app topology. In that case, critical
# in-memory state like RoutingTable::route_index won't be updated (with new node / route data) and this will
# cause issues in execute API (where the old node data [slot compute code for instance] will be used for execution).
Application.__init__(self, self._id, self._platform, self._enforce_runtime_compatibility)
# now refresh the remote applications in the dev-context
# (active context and its remote applications [if any] has already been updated)
for remote_app in self._dev_context.external_data:
remote_app.refresh()
@classmethod
def _build_instruction(
cls, api: str, entity: Union[Node, ApplicationID], inputs: List[Signal], output_node: Node, symbol_tree: Node, *args, **kwargs
) -> Instruction:
return Instruction(entity, inputs, api, args, kwargs, output_node, symbol_tree)
def get_route_metrics(self, route: Union[str, MarshalerNode, MarshalingView]) -> Dict[Type[BaseConstruct], Dict[str, FilteredView]]:
"""Retrieve all of the internal route/node specific metrics that will be emitted by this application once it is
activated. These are comprehensive set of metrics including (but not limited to); orchestration state
transitions around this node (detailed route session state transitions, transient errors / retries, persistence
failures), runtime edge-cases that cannot be captured by hooks (see RouteExecutionHook, RoutePendingNodeHook in
create_data API), etc.
Warning: Input route should belong to this Application (not from imported upstream applications) and its
reference should be from the current development context (which would be activated) not from the already
activated context.
:param route: route/node ID as string; route/node object as a return value from a upstream create_data API call
or retrieved from application dev-context.
:return: Metrics are provided in a dictionary for each platform driver [ProcessingUnit, BatchCompute,
RoutingTable, Storage, Diagnostics, ProcessorQueue]. Routing metric signal alias' used as keys within those
dictionaries and the values can be used as metric inputs into create_alarm calls. For those metric signals,
'Name' dimension (first dimension of any metric) must be specified before inputting to create_alarm call. User
can analyze available 'Name's for the metric signal by calling 'describe()' method on it.
Example:
my_etl_node = app.create_data("my_node", compute_target="output=spark('select * from foo')")
route_metrics_map = app.get_route_metrics(my_etl_node)
routing_table_metrics_map = route_metrics_map[RoutingTable]
batch_compute_map = route_metrics_map[BatchCompute]
# see supported metric signal alias'
# print(routing_table_metrics.keys()) # ['routing_table.receive', 'routing_table.receive.hook',
# 'routingTable.my_node.initial_state']
my_node_triggered_hook_metric = routing_table_metrics_map["routing_table.receive.hook"]
# dump all of the possible metric 'Name' dimension values
# my_node_triggered_hook_metric.describe() # ['IExecutionSucccessHook', 'IExecutionFailureHook', ...]
# use in an alarm by specifying 'Name' dimension as retry hook type 'IComputeRetryHook' which was observed
# by 'describe()' calls above.
# example: have more visibility into transient errors such as "GlueVersion 2.0/3.0 'Resource unavailable'",
# 2 implicit retries within 60 mins.
# this also covers forced orchestration retries based on user provided 'retry_count' param on any compute.
my_node_transient_error_alarm = app.create_alarm(id="my_node_transient_alarm",
target_metric_or_expression=my_node_triggered_hook_metric['IComputeRetryHook'][MetricStatistic.SUM][MetricPeriod.MINUTES(60)],
number_of_evaluation_periods=1,
number_of_datapoint_periods=1,
comparison_operator=AlarmComparisonOperator.GreaterThanOrEqualToThreshold,
threshold=2)
# send email whenever alarm is triggered
alarm_trigger_node = app.create_data("alarm_action", inputs=[my_node_transient_error_alarm],
compute_targets=[EMAIL(sender="...", recipient_list=['...']).action()])
"""
# this 'if' statement's entire purpose is parameter handling to create the <Route> object to be passed to
# HostPlatform::get_route_metrics call. Pretty typical prologue used in other application APIs which minor
# differences (type checks, validations).
if isinstance(route, (str, MarshalerNode, MarshalingView)):
if isinstance(route, str):
# - limit the search to this app (exclude upstream apps) since we can extract internal routing metrics.
# - limit the search to new development context, so as to avoid problematic use of active nodes which
# might not exist in the new topology. If we allow this, metrics (from here) might be used for
# downstream alarming which would never work if the active node is to be deleted in the next activation.
routes = self.get_data(route, Application.QueryApplicationScope.CURRENT_APP_ONLY, Application.QueryContext.DEV_CONTEXT)
if not routes:
raise ValueError(
f"Node/Route with ID {route!r} could not be found within the current development" f" context of this application!"
)
internal_data_node = cast(InternalDataNode, routes[0].bound)
else:
node = route.marshaler_node if isinstance(route, MarshalingView) else route
if not isinstance(node.bound, InternalDataNode):
raise ValueError(f"Node {type(node.bound)} provided as 'route' parameter to 'get_route_metrics' is not internal!")
internal_data_node = cast(InternalDataNode, node.bound)
owner_context_uuid = internal_data_node.signal().resource_access_spec.get_owner_context_uuid()
if owner_context_uuid != self.uuid:
raise ValueError(
f"'route' ({internal_data_node.data_id!r} provided to get_route_metrics is from "
f"another application ({owner_context_uuid!r})! It should be internal to this "
f"application ({self.uuid!r})"
)
# check whether the node exists in the current dev context. if the user pulled in an active node without
# adding it to the dev-context, then extracting metrics and using them in downstream alarms would be
# a false-promise (also an obscure) bug (broken routing) for the user.
dev_version = self.get_data(
internal_data_node.data_id, Application.QueryApplicationScope.CURRENT_APP_ONLY, Application.QueryContext.DEV_CONTEXT
)
if not dev_version:
raise ValueError(
f"Node {internal_data_node.data_id!r} provided as 'route' parameter to "
f"'get_route_metrics' has not been added to new development context! Extracting"
f" metrics from a node that will not get activated along with the new development"
f" context is not allowed."
)
route = internal_data_node.create_route()
else:
raise ValueError(
f"'route' parameter type {type(route)} provided to 'get_route_metric' is not supported! "
f"Please provide route/node ID as string or a node or filtered node object directly to "
f"retrieve routing metrics."
)
metric_signals: Dict[Type["BaseConstruct", List[Signal]]] = self.platform.get_route_metrics(route)
return {const_type: {s.alias: MarshalingView(None, s, None) for s in metrics} for const_type, metrics in metric_signals.items()}
def get_platform_metrics(
self, platform_metric_type: Optional[HostPlatform.MetricType] = HostPlatform.MetricType.ALL
) -> Dict[Type[BaseConstruct], Dict[str, FilteredView]]:
"""Get underlying platform metrics which are:
- auto-generated by system components /resources (e.g AWS resources)
- used by underlying RheocerOS drivers to emit metrics for specific events, state-transitions in this
app (at runtime). An example would be routing related changes or more importantly Processor errors, etc.
- or both
These won't include routing metrics which should be retrieved via 'get_route_metrics' for each node that was
added to the new development context of this application (via an upstream create_data call).
:param platform_metric_type: Changes the result set based on:
- HostPlatform.MetricType.ORCHESTRATION: will include Platform's own orchestration
metrics only
- HostPlatform.MetricType.SYSTEM: will include metrics for underlying system resources only
- HostPlatform.MetricType.ALL: will include both platform internal orchestration and system metrics. This is
the default.
:return: A dict that would have the following format:
{
Construct_Type <[Processor | BatchCompute | RoutingTable | Diagnostics | Storage | ProcessorQueue]>: {
Metric_1_Alias <str>: <MetricSignal>
...
Metric_2_Alias <str>: <MetricSignal>
}
}
Metrics are provided in a dictionary for each platform driver [ProcessingUnit, BatchCompute,
RoutingTable, Storage, Diagnostics, ProcessorQueue]. Routing metric signal alias' used as keys within those
dictionaries and the values can be used as metric inputs into create_alarm calls. For those metric signals,
'Name' dimension (first dimension of any metric) must be specified before inputting to create_alarm call. User
can analyze available 'Name's for the metric signal by calling 'describe()' method on it.
Example:
system_metrics_map = app.get_platform_metrics()
processor_metrics_map = system_metrics_map[ProcessingUnit]
# see supported metric signal alias'
# print(processor_metrics_map.keys())
# Dump system metrics and see their alias' and sub-dimensions!
#for metric in processor_metrics_map.values():
# print(metric.dimensions())
# # dumps metric group ID/alias -> specific MetricNames and other details
# print(metric.describe())
# plese note that "processor.core" is not a concrete metric Name dimension value yet, it is just the
# alias used internally by the Processor driver impl to group different metrics (with same structure,
# sub dimensions) into one metric signal.
processor_core_metric_signal = processor_metrics_map["processor.core"]
# dump all of the possible metric 'Name' dimension values
# processor_core_metric_signal.describe()
# use in an alarm by specifying 'Name' dimension as 'Errors' which was observed by 'describe()' calls above.
processor_alarm = app.create_alarm(id="processor_alarm",
target_metric_or_expression="(m1 > 1 OR m2 > 600000)",
metrics={
"m1": processor_core_metric_signal['Errors'][MetricStatistic.SUM][MetricPeriod.MINUTES(5)],
"m2": ...
...)
"""
if self.state in [ApplicationState.TERMINATING, ApplicationState.DELETED]:
raise RuntimeError(f"Cannot get platform metrics when the application state is {self.state!r}!")
metric_signals: Dict[Type["BaseConstruct", List[Signal]]] = self.platform.get_metrics()
return {const_type: {s.alias: MarshalingView(None, s, None) for s in metrics} for const_type, metrics in metric_signals.items()}
def marshal_external_metric(
self,
external_metric_desc: ExternalMetricNode.Descriptor,
id: str,
dimension_filter: Optional[Union[DimensionFilter, Dict[str, Any]]] = None,
sub_dimensions: Optional[MetricSubDimensionMapType] = MetricSubDimensionMap(),
tags: str = None,
) -> MarshalerNode:
"""Import/add an external metric (e.g AWS CW Metric) resource as a signal into the application.
dimension_filter uses the following spec for specialization/overwrites:
{ MetricDimension.NAME <STRING>: {
MetricDimension.STATISTIC <MetricStatistic | STRING>: {
MetricDimension.PERIOD <MetricPeriod | LONG>: {
MetricDimension.TIME <DATETIME>: {
}
}
}
}
Returned object can be used as an input to create_data API.
"""
if self.get_metric(
metric_id=id,
sub_dimensions=None, # ignore sub_dimensions
app_scope=Application.QueryApplicationScope.CURRENT_APP_ONLY,
context=Application.QueryContext.DEV_CONTEXT,
):
raise ValueError(
f"MetricNode with id {id!r} already exists!"
f"You might want to use 'update_external_metric' API to modify an existing metric node."
)
if dimension_filter is None:
dimension_filter = DimensionFilter.load_raw(
{
"*": { # Any MetricDimension.NAME
"*": {"*": {"*": {}}} # Any MetricDimension.STATISTIC # Any MetricDimension.PERIOD # Any MetricDimension.TIME
}
}
)
dim_filter: DimensionFilter = (
DimensionFilter.load_raw(dimension_filter) if not isinstance(dimension_filter, DimensionFilter) else dimension_filter
)
external_metric_desc.add(SignalSourceAccessSpec.OWNER_CONTEXT_UUID, self.uuid)
metric_node: ExternalMetricNode = external_metric_desc.create_node(id, dim_filter, sub_dimensions, self.platform)
marshaler_node = MarshalerNode(metric_node, tags)
metric_node.add_child(marshaler_node)
# - keep the execution order
# - bookkeeping high-level code
# TODO use "inspect" module or "sys._getFrame" to simplify
# instruction build operation from this api (func) call.
new_inst: Instruction = self._build_instruction(
"marshal_external_metric",
self._id,
None,
marshaler_node,
metric_node,
id,
external_metric_desc,
dimension_filter,
sub_dimensions,
tags,
)
self._dev_context.add_instruction(new_inst)
return marshaler_node
def create_metric(
self,
id: str,
dimension_filter: Optional[Union[DimensionFilter, Dict[str, Any]]] = None,
sub_dimensions: Optional[MetricSubDimensionMapType] = MetricSubDimensionMap(),
**kwargs,
) -> MarshalerNode:
"""Creates an internal metric definition that will depend on the MetricsStore impl of the underlying Platform.
'id' can be used to retrieve the metric def from the MetricsStore at runtime to 'emit' metrics. So it actually
represents the logical/abstract 'Metric Group' for the retrieval of the declaration during development and also
at runtime.
Same 'id' is also used as the default 'alias' (metric id) within create_alarm API for MetricExpressions if alias
is not provided by the user.
Please note that, different metric definitions created with different 'id's here might cannot contribute
to same metric instances at runtime even if the same 'Name' dimension values are used during emission. A Metric
instance is uniquely defined by 'Name' dimension and 'sub-dimensions', and RheocerOS implicitly adds 'id' as a
metric group ID sub-dimension to each internal metric created with this API.
Example:
# declare your internal / custom metrics in application
generic_internal_metric1 = app.create_metric(id="metric_group1")
generic_internal_metric2 = app.create_metric(id="metric_group2")
generic_internal_metric3 = app.create_metric(id="metric_group3", sub_dimensions={"error_type": "foo"})
# then in your inlined or batch compute (e.g Spark) code, do the follow to emit at runtime:
# it won't contribute to the metric declared by "metric_group1"
runtime_platform.diagnostics["metric_group2"]["Error"].emit(1)
# emit from the first metric internal metric decl, this will contribute to a different metric instance
# despite that they are emitted using the same metric name 'Error'
runtime_platform.diagnostics["metric_group1"]["Error"].emit(1)
# same again, will contribute to a different metric even if the same metric Name is used
runtime_platform.diagnostics["metric_group3"]["Error"].emit(1)
runtime_platform.diagnostics["metric_group3"]["Success"].emit([MetricValueCountPairData(5.0), # Count = 1 by default
MetricValueCountPairData(Value=3.0, Count=2)])
Returned 'MarshalerNode' object can be used as an input to create_alarm call or to analyze the metric object.
Example
alarm = app.create_alarm(id="daily_error_tracker",
target_metric_or_expression=generic_internal_metric1["Error"][MetricStatistic.SUM][MetricPeriod.MINUTES(24 * 60)],
number_of_evaluation_periods=1,
number_of_datapoint_periods=1,
comparison_operator=AlarmComparisonOperator.GreaterThanOrEqualToThreshold,
threshold=1)
"""
# check if "ID + subdimensions" is unique
if self.get_metric(id, sub_dimensions, Application.QueryApplicationScope.CURRENT_APP_ONLY, Application.QueryContext.DEV_CONTEXT):
raise ValueError(
f"MetricNode with id {id!r} and sub_dimensions {sub_dimensions!r} already exists!"
f"You might want to use 'update_metric' API to modify an existing metric node."
)
if dimension_filter is None:
dimension_filter = DimensionFilter.load_raw(
{
"*": { # Any MetricDimension.NAME
"*": {"*": {"*": {}}} # Any MetricDimension.STATISTIC # Any MetricDimension.PERIOD # Any MetricDimension.TIME
}
}
)
dim_filter: DimensionFilter = (
DimensionFilter.load_raw(dimension_filter) if not isinstance(dimension_filter, DimensionFilter) else dimension_filter
)
kwargs.update({SignalSourceAccessSpec.OWNER_CONTEXT_UUID: self.uuid})
metric_node = InternalMetricNode(id, dim_filter, sub_dimensions, **kwargs)
marshaler_node = MarshalerNode(metric_node, None)
metric_node.add_child(marshaler_node)
new_inst: Instruction = self._build_instruction(
"create_metric", self._id, None, marshaler_node, metric_node, id, dimension_filter, sub_dimensions, **kwargs
)
self._dev_context.add_instruction(new_inst)
return marshaler_node
def get_metric(
self,
metric_id: str,
sub_dimensions: Optional[MetricSubDimensionMapType] = None,
app_scope: Optional[QueryApplicationScope] = QueryApplicationScope.ALL,
context: Optional[QueryContext] = QueryContext.ACTIVE_RUNTIME_CONTEXT,
) -> List[MarshalerNode]:
"""Returns the metrics (internal or external) that have the id 'metric_id' and contain the given sub dimensions.
@param metric_id: only the metrics whose IDs match this param are returned.
@param sub_dimensions: Optional parameter to narrow down the return value (possible list of metrics) if there
are multiple internal metrics with the same 'metric_id'.
@param app_scope determines from which applications the metrics should be retrieved. By default it searches in
this application and also all applications this applications is connected with
(see Application::import_upstream_application).
@param context within all of the applications (determined by 'app_scope'), this determines from which contexts
the metrics should be retrieved. By default it searches in already activated (remotely active) context/topology.
So a newly added (inactive) metric node cannot be found using this API unless this parameter is set to
DEV_CONTEXT or ALL explicitly.
"""
return [
child_node
for data_node in self.query([MetricNode.QueryVisitor(metric_id, sub_dimensions, exact_match=True)], app_scope, context).values()
for child_node in data_node.child_nodes
if isinstance(child_node, MarshalerNode)
]
def marshal_external_alarm(
self,
external_alarm_desc: ExternalAlarmNode.Descriptor,
id: str,
dimension_filter: Optional[Union[DimensionFilter, Dict[str, Any]]] = None,
alarm_params: Optional[AlarmParams] = None,
tags: str = None,
) -> MarshalerNode:
"""Import/add an external (metric or composite) alarm resource as a new signal into the application."""
if self.get_alarm(
alarm_id=id,
alarm_type=AlarmType.ALL,
app_scope=Application.QueryApplicationScope.CURRENT_APP_ONLY,
context=Application.QueryContext.DEV_CONTEXT,
):
raise ValueError(
f"An AlarmNode or CompositeAlarmNode with id {id!r} already exists!"
f"You might want to use 'update_external_alarm' API to modify an existing alarm node."
)
if dimension_filter is None:
dimension_filter = DimensionFilter.load_raw({"*": {"*": {}}}) # Any AlarmDimension.STATE_TRANSITION # Any AlarmDimension.TIME
dim_filter: DimensionFilter = (
DimensionFilter.load_raw(dimension_filter) if not isinstance(dimension_filter, DimensionFilter) else dimension_filter
)
external_alarm_desc.add(SignalSourceAccessSpec.OWNER_CONTEXT_UUID, self.uuid)
alarm_node: ExternalAlarmNode = external_alarm_desc.create_node(id, dim_filter, alarm_params, self.platform)
marshaler_node = MarshalerNode(alarm_node, tags)
alarm_node.add_child(marshaler_node)
new_inst: Instruction = self._build_instruction(
"marshal_external_alarm",
self._id,
None,
marshaler_node,
alarm_node,
id,
external_alarm_desc,
dimension_filter,
alarm_params,
tags,
)
self._dev_context.add_instruction(new_inst)
return marshaler_node
def create_alarm(
self,
id: str,
target_metric_or_expression: Union[Union[FilteredView, MarshalerNode, Signal], MetricExpression, str],
number_of_evaluation_periods: Optional[int] = 1,
number_of_datapoint_periods: Optional[int] = 1,
comparison_operator: Optional[AlarmComparisonOperator] = AlarmComparisonOperator.GreaterThanOrEqualToThreshold,
threshold: Optional[float] = 1,
metrics: Optional[
Union[List[Union[FilteredView, MarshalerNode, Signal]], Dict[str, Union[FilteredView, MarshalerNode, Signal]]]
] = None,
metric_expressions: Optional[List[MetricExpression]] = None,
default_actions: Optional[AlarmDefaultActionsMap] = None,
description: Optional[str] = None,
treat_missing_data: Optional[AlarmTreatMissingData] = AlarmTreatMissingData.MISSING,
dimension_filter: Optional[Union[DimensionFilter, Dict[str, Any]]] = None,
**kwargs,
) -> MarshalerNode:
"""Creates an internal alarm that depends on the MetricsStore model impl of the underlying Platform object
@param target_metric_or_expression: 'target_metric_or_expression' is a MetricExpression, then 'metrics' input
must be defined, otherwise 'metrics' or metric_expressions definitions will be rejected by the API
(not accepted if it is a metric signal).
@param default_actions: If 'default_actions' is defined, then alarm will have direct connections to those actions even without the
returned object being used in subsequent create_data calls.
@param description: When 'default_actions' is defined, then this parameter becomes more important since it is
the only way to pass extra information to those actions (ex. description for CW Internal actions). In other
cases where alarm is going to be used in create_data, then a more flexible and RheocerOS decorated, rich data
is provided to actions and also within create_data / compute_targets, users can do more to further configure
descriptions and message as part of the action (ticketing, email, etc).
"""
if self.get_alarm(
alarm_id=id,
alarm_type=AlarmType.ALL,
app_scope=Application.QueryApplicationScope.CURRENT_APP_ONLY,
context=Application.QueryContext.DEV_CONTEXT,
):
raise ValueError(
f"An alarm or composite alarm with id {id!r} already exists!"
f"You might want to use 'update_alarm' API to modify an existing alarm node."
)
input_signals: List[Signal] = None
metric_signals: List[Signal] = []
if isinstance(target_metric_or_expression, str):
target_metric_or_expression = MetricExpression(expression=target_metric_or_expression)
if isinstance(target_metric_or_expression, MetricExpression):
if not metrics:
raise ValueError(f"Please provide metric signals for the alarm: {id!r}!")
if isinstance(metrics, Dict):
metric_signals = [self._get_input_signal(filtered_view, alias) for alias, filtered_view in metrics.items()]
else:
metric_signals = [self._get_input_signal(filtered_view) for filtered_view in metrics]
metric_signals = self._check_upstream(metric_signals)
# validate signal type
for s in metric_signals:
if not s.type.is_metric():
raise ValueError(f"Input {s.alias!r} to alarm {id!r} is not a metric!")
# at this point metric signals should be materialized by the client (name, stats, period)
self.platform.diagnostics.check_metric_materialization(s)
input_signals = metric_signals
else:
if metrics or metric_expressions:
raise ValueError(
f"Metrics and metric_expressions should not be defined for the alarm {id!r} that" f"f is linked to a single metric!"
)
# convert to Signal
target_metric_or_expression = self._check_upstream_signal(self._get_input_signal(target_metric_or_expression))
if not target_metric_or_expression.type.is_metric():
raise ValueError(f"Input {target_metric_or_expression.alias!r} provided as a target to alarm {id!r} is " f"not a metric!")
# should be materialized by the client (name, stats, period)
self.platform.diagnostics.check_metric_materialization(target_metric_or_expression)
input_signals = [target_metric_or_expression]
if default_actions is None:
default_actions = AlarmDefaultActionsMap(set())
else:
# TODO add validation for each action
pass
alarm_params = AlarmParams(
target_metric_or_expression,
metric_signals,
metric_expressions if metric_expressions else [],
number_of_evaluation_periods,
number_of_datapoint_periods,
comparison_operator,
threshold,
default_actions,
description,
treat_missing_data,
)
if dimension_filter is None:
dimension_filter = DimensionFilter.load_raw({"*": {"*": {}}}) # Any AlarmDimension.STATE_TRANSITION # Any AlarmDimension.TIME
kwargs.update({SignalSourceAccessSpec.OWNER_CONTEXT_UUID: self.uuid})
alarm_node = InternalAlarmNode(id, dimension_filter, alarm_params, **kwargs)
marshaler_node = MarshalerNode(alarm_node, None)
alarm_node.add_child(marshaler_node)
new_inst: Instruction = self._build_instruction(
"create_alarm", self._id, input_signals, marshaler_node, alarm_node, id, dimension_filter, alarm_params, **kwargs
)
self._dev_context.add_instruction(new_inst)
return marshaler_node
def create_composite_alarm(
self,
id: str,
alarm_rule: Union[AlarmRule, Signal],
default_actions: Optional[AlarmDefaultActionsMap] = None,
description: Optional[str] = None,
dimension_filter: Optional[Union[DimensionFilter, Dict[str, Any]]] = None,
**kwargs,
) -> MarshalerNode:
"""Creates an internal alarm that depends on the MetricsStore model impl of the underlying Platform object.
If 'default_actions' is defined, then alarm will have direct connections to those actions even without the
returned object being used in subsequent create_data calls.
@param alarm_rule: Either signal Alarm signal or an AlarmRule implicitly created from an expression that contains
bitwise AND, OR or INVERTED alarm signals or other nested expressions.
Examples:
~my_alarm['OK']
my_alarm['ALARM']
my_alarm['ALARM'] & (other_alarm['ALARM'] | foo_alarm['ALARM'])
my_alarm & (other_alarm | foo_alarm)
If 'state_transition' dimension ('ALARM', 'OK', 'INSUFFICIENT_DATA' ) is not specified, then 'ALARM' state
is used by default.
Returned object can alternatively be used in subsequent create_data calls as an input signal.
"""
if self.get_alarm(
alarm_id=id,
alarm_type=AlarmType.ALL,
app_scope=Application.QueryApplicationScope.CURRENT_APP_ONLY,
context=Application.QueryContext.DEV_CONTEXT,
):
raise ValueError(
f"An AlarmNode or CompositeAlarmNode with id {id!r} already exists!"
f"You might want to use 'update_alarm' API to modify an existing alarm node."
)
if default_actions is None:
default_actions = AlarmDefaultActionsMap(set())
alarm_params = CompositeAlarmParams(alarm_rule, default_actions, description)
if dimension_filter is None:
dimension_filter = DimensionFilter.load_raw({"*": {"*": {}}}) # Any AlarmDimension.STATE_TRANSITION # Any AlarmDimension.TIME
dim_filter: DimensionFilter = (
DimensionFilter.load_raw(dimension_filter) if not isinstance(dimension_filter, DimensionFilter) else dimension_filter
)
kwargs.update({SignalSourceAccessSpec.OWNER_CONTEXT_UUID: self.uuid})
alarm_node = InternalCompositeAlarmNode(id, dim_filter, alarm_params, **kwargs)
marshaler_node = MarshalerNode(alarm_node, None)
alarm_node.add_child(marshaler_node)
new_inst: Instruction = self._build_instruction(
"create_composite_alarm",
self._id,
alarm_rule.get_alarms(),
marshaler_node,
alarm_node,
id,
dimension_filter,
alarm_params,
**kwargs,
)
self._dev_context.add_instruction(new_inst)
return marshaler_node
def get_alarm(
self,
alarm_id: str,
alarm_type: AlarmType = AlarmType.ALL,
app_scope: Optional[QueryApplicationScope] = QueryApplicationScope.ALL,
context: Optional[QueryContext] = QueryContext.ACTIVE_RUNTIME_CONTEXT,
) -> List[MarshalerNode]: