From 60907fe5ac4011c938484960318ef7cc1889f643 Mon Sep 17 00:00:00 2001 From: Fotis Paraskevopoulos Date: Mon, 10 May 2021 16:34:10 +0300 Subject: [PATCH 1/2] Upgrading Python Library --- amq-message-python-library/Event.py | 420 ++++++++++++++++++ .../MorphemicConnection.py | 6 +- .../MorphemicListener.py | 29 ++ amq-message-python-library/Payloads.py | 10 + amq-message-python-library/__init__.py | 5 +- 5 files changed, 464 insertions(+), 6 deletions(-) create mode 100644 amq-message-python-library/Event.py create mode 100644 amq-message-python-library/MorphemicListener.py create mode 100644 amq-message-python-library/Payloads.py diff --git a/amq-message-python-library/Event.py b/amq-message-python-library/Event.py new file mode 100644 index 00000000..52dbc842 --- /dev/null +++ b/amq-message-python-library/Event.py @@ -0,0 +1,420 @@ + + +class Metric(enumerate): + """ + [0] (current/detected) Metrics & SLOs Events Format: + + + This event is aggregated by EMS and it is persisted in InfluxDB. Moreover, + Prediction Orchestrator will subscribe and receive the current metrics in order to + evaluate the forecasting methods, according to the defined KPIs (e.g., MAPE) + + * Topic: [metric_name] + > (e.g. MaxCPULoad) + + + { + "metricValue": 12.34, + + "level": 1, + + "timestamp": 143532341251, + + "refersTo": "MySQL_12345", + + "cloud": "AWS-Dublin", + + "provider": "AWS" + + } + + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + """ + TIMESTAMP = "timestamp" + METRIC_VALUE = "metricValue" + REFERS_TO = "refersTo" + CLOUD = "cloud" + PROVIDER = "provider" + + + +class PredictionMetric(enumerate): + + """ + [1] Predicted Metrics & SLOs Events Format + + + This event is produced by the Prediction Orchestrator and reflects the final predicted value for a metric. + + - Topic: prediction.[metric_name] + > (e.g. prediction.MaxCPULoad) + + + { + "metricValue": 12.34, + + "level": 1, + + "timestamp": 143532341251, + + "probability": 0.98, + + "confidence_interval " : [8,15] + + "predictionTime": 143532342, + + "refersTo": "MySQL_12345", + + "cloud": "AWS-Dublin", + + "provider": "AWS" + + } + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + """ + + _match = "prediction." + + METRICVALUE= "metricValue" + '''Predicted metric value''' + LEVEL= "level" + '''Level of VM where prediction occurred or refers''' + TIMESTAMP= "timestamp" + '''Prediction creation date/time from epoch''' + PROBABILITY= "probability" + '''Probability of the predicted metric value (range 0..1)''' + CONFIDENCE_INTERVAL= "confidence_interval" + '''the probability-confidence interval for the prediction''' + PREDICTION_TIME= "predictionTime" + '''This refers to time point in the imminent future (that is relative to the time + that is needed for reconfiguration) for which the predicted value is considered + valid/accurate (in UNIX Epoch)''' + REFERSTO= "refersTo" + '''The id of the application or component or (VM) host for which the prediction refers to''' + CLOUD= "cloud" + '''Cloud provider of the VM (with location)''' + PROVIDER= "provider" + '''Cloud provider name''' + + + +class MetricsToPredict(enumerate): + + """ + [2] Translator – to – Forecasting Methods/Prediction Orchestrator Events Format + + + This event is produced by the translator, to: + + imform Dataset Maker which metrics should subscribe to in order to aggregate the appropriate tanning dataset in the time-series DB. + instruct each of the Forecasting methods to predict the values of one or more monitoring metrics + inform the Prediction Orchestrator for the metrics which will be forecasted + + * Topic: metrics_to_predict + + + *Note:* This event could be communicated through Mule + + + [ + { + + "metric": "MaxCPULoad", + + "level": 3, + + "publish_rate": 60000, + + }, + + { + + "metric": "MinCPULoad", + + "level": 3, + + "publish_rate": 50000, + + } + + ] + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + """ + + _match = "metrics_to_predict" + + METRIC = "metric" + '''name of the metric to predict''' + LEVEL = "level" + '''Level of monitoring topology where this metric may be produced/found''' + PUBLISH_RATE = "publish_rate" + '''expected rate for datapoints regarding the specific metric (according to CAMEL)''' + + +class TraningModels(enumerate): + """ + + [3] Forecasting Methods – to – Prediction Orchestrator Events Format + + + This event is produced by each of the Forecasting methods, to inform the + Prediction Orchestrator that the method has (re-)trained its model for one or more metrics. + + * Topic: training_models + + + { + + "metrics": ["MaxCPULoad","MinCPULoad"]", + + "forecasting_method": "ESHybrid", + + "timestamp": 143532341251, + + } + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + """ + _match = "training_models" + + METRICS = "metrics" + '''metrics for which a certain forecasting method has successfully trained or re-trained its model''' + FORECASTING_METHOD = "forecasting_method" + '''the method that is currently re-training its models''' + TIMESTAMP = "timestamp" + '''date/time of model(s) (re-)training''' + + +class IntermediatePrediction(enumerate): + """ + + [4] Forecasting Methods – to – Prediction Orchestrator Events Format + + + This event is produced by each of the Forecasting methods, and is used by the Prediction Orchestrator to determine the final prediction value for the particular metric. + + + * Topic: intermediate_prediction.[forecasting_method].[metric_name] + * (e.g. intermediate_prediction.ESHybrid.MaxCPULoad) + * We note that any component will be able to subscribe to topics like: + * intermediate_prediction.*.MaxCPULoad → gets MaxCPULoad predictions produced by all forecasting methods or + * intermediate_prediction.ESHybrid.* → gets all metrics predictions from ESHybrid method + * We consider that each forecasting method publishes a static (but configurable) number m of predicted values (under the same timestamp) for time points into the future. These time points into the future are relevant to the reconfiguration time that it is needed (and can also be updated). + * For example if we configure m=5 predictions into the future and the reconfiguration time needed is TR=10 minutes, then at t0 a forecasting method publishes 5 events with the same timestamp and prediction times t0+10, t0+20, t0+30, t0+40, t0+50. + + + + { + "metricValue": 12.34, + + "level": 3, + + "timestamp": 143532341251, + + "probability": 0.98, + + "confidence_interval " : [8,15] + + "predictionTime": 143532342, + + "refersTo": "MySQL_12345", + + "cloud": "AWS-Dublin", + + "provider": "AWS" + + } + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + """ + + _match="intermediate_prediction." + + METRICVALUE = "metricValue" + '''Predicted metric value (more than one such events will be produced for different time points into the future – this can be valuable to the Prediction Orchestrator in certain situations e.g., forecasting method is unreachable for a time period)''' + + LEVEL = "level" + '''Level of VM where prediction occurred or refers''' + + TIMESTAMP = "timestamp" + '''Prediction creation date/time from epoch''' + + PROBABILITY = "probability" + '''Probability of the predicted metric value (range 0..1)''' + + CONFIDENCE_INTERVAL = "confidence_interval" + '''the probability-confidence interval for the prediction''' + + PREDICTION_TIME = "predictionTime" + '''This refers to time point in the imminent future (that is relative to the time that is needed for reconfiguration) for which the predicted value is considered valid/accurate (in UNIX Epoch)''' + + REFERS_TO = "refersTo" + '''The id of the application or component or (VM) host for which the prediction refers to''' + + CLOUD = "cloud" + '''Cloud provider of the VM (with location)''' + + PROVIDER = "provider" + '''Cloud provider name''' + + + +class Prediction(enumerate): + """ + + [5] Prediction Orchestrator – to – Severity-based SLO Violation Detector Events Format + + + This event is used by the Prediction Orchestrator to inform the SLO Violation Detector about the current values of a metric, which can possibly lead to an SLO Violation detection. + + * Topic: prediction.[metric_name] + * (e.g. prediction.MaxCPULoad) + + + { + "metricValue": 12.34, + + "level": 1, + + "timestamp": 143532341251, + + "probability": 0.98, + + "confidence_interval " : [8,15] + + "predictionTime": 143532342, + + "refersTo": "MySQL_12345", + + "cloud": "AWS-Dublin", + + "provider": "AWS" + + } + + + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + + """ + + _match = "prediction." + + METRICVALUE = "metricValue" + '''Predicted metric value''' + + LEVEL = "level" + '''Level of VM where prediction occurred or refers''' + + TIMESTAMP = "timestamp" + '''Prediction creation date/time from epoch''' + + PROBABILITY = "probability" + '''Probability of the predicted metric value (range 0..1)''' + + CONFIDENCE_INTERVAL = "confidence_interval" + '''the probability-confidence interval for the prediction''' + + PREDICTIONTIME = "predictionTime" + '''This refers to time point in the imminent future (that is relative to the time that is needed for reconfiguration) for which the predicted value is considered valid/accurate (in UNIX Epoch)''' + + REFERSTO = "refersTo" + '''The id of the application or component or (VM) host for which the prediction refers to''' + + CLOUD = "cloud" + '''Cloud provider of the VM (with location)''' + + PROVIDER = "provider" + '''Cloud provider name''' + + +class StopForecasting(enumerate): + """ + [6] Prediction Orchestrator – to – Forecasting Methods Events Format + + + This event is used by the Prediction Orchestrator to instruct a forecasting method to stop producing predicted values for a selection of metrics. + + + * Topic: stop_forecasting.[forecasting_method] + * Each component that implements a specific forecasting method it should subscribe to its relevant topic (e.g. the ES-Hybrid component should subscribe to stop_forecasting.eshybrid topic) + + + { + "metrics": ["MaxCPULoad","MinCPULoad"], + "timestamp": 143532341251, + } + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + + """ + + _match="stop_forecasting." + + METRICS = "metrics" + '''metrics for which a certain method should stop producing predictions (because of poor results)''' + TIMESTAMP = "timestamp" + '''date/time of the command of the orchestrator''' + + +class StartForecasting(enumerate): + """ + + [7] Prediction Orchestrator – to – Forecasting Methods Events Format + + This event is used by the Prediction Orchestrator to instruct a forecasting method to start producing predicted values for a selection of metrics. + + + * Topic: start_forecasting.[forecasting_method] + * Each component that implements a specific forecasting method it should subscribe to its relevant topic (e.g. the ES-Hybrid component should subscribe to start_forecasting.eshybrid topic) + * We consider that each forecasting method should publish a static (but configurable) number m of predicted values (under the same timestamp) for time points into the future. These time points into the future are relevant to the reconfiguration time that it is needed (and can also be updated). + * For example if we configure m=5 predictions into the future and the reconfiguration time needed is TR=10 minutes, then at t0 a forecasting method publishes 5 events with the same timestamp and prediction times t0+10, t0+20, t0+30, t0+40, t0+50. + + + + + { + "metrics": ["MaxCPULoad","MinCPULoad"], + + "timestamp": 143532341251, + + "epoch_start": 143532341252, + + "number_of_forward_predictions": 5, + + "prediction_horizon": 600 + + } + + https://confluence.7bulls.eu/display/MOR/Forecasting+Mechanism+Sub-components+Communication + + + """ + + _match="start_forecasting." + + METRICS = "metrics" + '''metrics for which a certain method should start producing predictions''' + TIMESTAMP = "timestamp" + '''date/time of the command of the orchestrator''' + EPOCH_START = "epoch_start" + '''this time refers to the start time after which all predictions will be considered (i.e. t0)''' + NUMBER_OF_FORWARD_PREDICTIONS = "number_of_forward_predictions" + ''' this is a number that indicates how many time points into the future do we need predictions for.''' + PREDICTION_HORIZON = "prediction_horizon" + '''This time equals to the time (in seconds) that is needed for the platform to implement an application reconfiguration (i.e. TR).''' \ No newline at end of file diff --git a/amq-message-python-library/MorphemicConnection.py b/amq-message-python-library/MorphemicConnection.py index d67a179f..59f8dd0f 100644 --- a/amq-message-python-library/MorphemicConnection.py +++ b/amq-message-python-library/MorphemicConnection.py @@ -29,7 +29,7 @@ class Connection: def subscribe(self,destination, id, ack='auto'): - ref = next((item for item in self.subscriptions if item['id'] == id), None) + ref = next((item for item in self.subscriptions if item['destination'] == destination and item['id'] == id), None) if not ref: self.subscriptions.append( @@ -46,8 +46,6 @@ class Connection: def queue(self,destination, id, ack='auto'): self.subscribe("/queue/%s" % destination,id,ack) - def is_topic(self,headers, topic): - return headers.get('destination') == '/topic/metrics_to_predict' def unsubscribe(self, id): if not self.conn: @@ -65,9 +63,7 @@ class Connection: return self.conn.connect(self.username, self.password, wait=wait) - for s in self.subscriptions: - self.conn.subscribe(s['destination'], s['id'], s['ack']) diff --git a/amq-message-python-library/MorphemicListener.py b/amq-message-python-library/MorphemicListener.py new file mode 100644 index 00000000..1317bf76 --- /dev/null +++ b/amq-message-python-library/MorphemicListener.py @@ -0,0 +1,29 @@ + +from stomp.listener import ConnectionListener +import logging +import json + +class MorphemicListener(ConnectionListener): + + def is_topic(self,headers, event): + if not hasattr(event,"_match"): + return False + match = getattr(event,'_match') + return headers.get('destination').startswith(match) + + def _unknown_message(self,body): + logging.debug("Unknown message %s ",body) + pass + + + def on_message(self, headers, body): + + logging.debug("Headers %s",headers) + logging.debug(" %s",body) + + func_name='on_%s' % headers.get('destination').replace('/topic/','') + if hasattr(self,func_name): + func = getattr(self, func_name) + func(json.loads(body)) + else: + self._unknown_message(body) diff --git a/amq-message-python-library/Payloads.py b/amq-message-python-library/Payloads.py new file mode 100644 index 00000000..5de1adc8 --- /dev/null +++ b/amq-message-python-library/Payloads.py @@ -0,0 +1,10 @@ + +class MetricsToPredict: + + + def load(self,body): + self.metrics = body["metrics"] + self.timestamp = body["timestamp"] + self.epoch_start = body["epoch_start"] + self.number_of_forward_predictions = body["number_of_forward_predictions"] + self.prediction_horizon = body["prediction_horizon"] diff --git a/amq-message-python-library/__init__.py b/amq-message-python-library/__init__.py index 21f52880..45fe25b1 100644 --- a/amq-message-python-library/__init__.py +++ b/amq-message-python-library/__init__.py @@ -1,2 +1,5 @@ -from . import MorphemicConnection as morphemic \ No newline at end of file +from . import MorphemicConnection as morphemic +from . import MorphemicListener as listener +from . import Event as events +from . import Payloads as payloads \ No newline at end of file -- GitLab From 4eae629771144aea911517edc5dd44a39d0146f6 Mon Sep 17 00:00:00 2001 From: Fotis Paraskevopoulos Date: Wed, 26 May 2021 10:57:55 +0300 Subject: [PATCH 2/2] Adding handler --- .../MorphemicConnection.py | 39 ++++++------------- .../MorphemicListener.py | 21 +++++++--- amq-message-python-library/requirements.txt | 1 + 3 files changed, 27 insertions(+), 34 deletions(-) diff --git a/amq-message-python-library/MorphemicConnection.py b/amq-message-python-library/MorphemicConnection.py index 59f8dd0f..0160419c 100644 --- a/amq-message-python-library/MorphemicConnection.py +++ b/amq-message-python-library/MorphemicConnection.py @@ -13,48 +13,38 @@ class Connection: host='localhost', port=61613, debug=True): - self.hosts = [(host, port)] self.username = username self.password = password self.conn = stomp.Connection(host_and_ports=self.hosts) if debug: - print("Enabling debug") + logging.debug("Enabling debug") self.conn.set_listener('print', PrintingListener()) + def _build_id(self,topic,id): + return "id.%s-%s" % (topic,id) + def set_listener(self, id, listener): if self.conn: self.conn.set_listener(id,listener) def subscribe(self,destination, id, ack='auto'): + if not self.conn: + raise RuntimeError('You need to connect first') - ref = next((item for item in self.subscriptions if item['destination'] == destination and item['id'] == id), None) - - if not ref: - self.subscriptions.append( - { - 'id': id, - 'destination': destination, - 'ack': ack, - } - ) + self.conn.subscribe(destination, id, ack) def topic(self,destination, id, ack='auto'): - self.subscribe("/topic/%s" % destination ,id,ack) + self.subscribe("/topic/%s" % destination ,self._build_id(destination,id),ack) def queue(self,destination, id, ack='auto'): - self.subscribe("/queue/%s" % destination,id,ack) - + self.subscribe("/queue/%s" % destination ,self._build_id(destination,id),ack) - def unsubscribe(self, id): + def unsubscribe(self, topic,id): if not self.conn: return - - if not self.conn.running: - return - - self.conn.unsubscribe(id) + self.conn.unsubscribe(self._build_id(topic,id)) def connect(self, wait=True): @@ -63,15 +53,8 @@ class Connection: return self.conn.connect(self.username, self.password, wait=wait) - for s in self.subscriptions: - self.conn.subscribe(s['destination'], s['id'], s['ack']) - def disconnect(self): - - for s in self.subscriptions: - self.unsubscribe(s['id']) - self.conn.disconnect() diff --git a/amq-message-python-library/MorphemicListener.py b/amq-message-python-library/MorphemicListener.py index 1317bf76..638c153c 100644 --- a/amq-message-python-library/MorphemicListener.py +++ b/amq-message-python-library/MorphemicListener.py @@ -2,6 +2,7 @@ from stomp.listener import ConnectionListener import logging import json +from slugify import slugify class MorphemicListener(ConnectionListener): @@ -11,8 +12,16 @@ class MorphemicListener(ConnectionListener): match = getattr(event,'_match') return headers.get('destination').startswith(match) - def _unknown_message(self,body): - logging.debug("Unknown message %s ",body) + + def has_topic_name(self,headers, string): + return headers.get('destination').startswith(string) + + def get_topic_name(self,headers): + return headers.get('destination').replace('/topic/','') + + + def on(self,headers, res): + logging.debug("Unknown message %s ",res) pass @@ -20,10 +29,10 @@ class MorphemicListener(ConnectionListener): logging.debug("Headers %s",headers) logging.debug(" %s",body) - - func_name='on_%s' % headers.get('destination').replace('/topic/','') + res = json.loads(body) + func_name='on_%s' % slugify(headers.get('destination').replace('/topic/',''), separator='_',) if hasattr(self,func_name): func = getattr(self, func_name) - func(json.loads(body)) + func(res) else: - self._unknown_message(body) + self.on(headers,res) diff --git a/amq-message-python-library/requirements.txt b/amq-message-python-library/requirements.txt index 12393625..2ed8eb95 100644 --- a/amq-message-python-library/requirements.txt +++ b/amq-message-python-library/requirements.txt @@ -1 +1,2 @@ stomp.py +python-slugify -- GitLab