Merge "Fixes bugs for integration with policy module"
[osm/MON.git] / osm_mon / core / message_bus / common_consumer.py
1 # Copyright 2017 Intel Research and Development Ireland Limited
2 # *************************************************************
3 # This file is part of OSM Monitoring module
4 # All Rights Reserved to Intel Corporation
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you
7 # may not use this file except in compliance with the License. You may
8 # obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # implied. See the License for the specific language governing
16 # permissions and limitations under the License.
17 #
18 # For those usages not covered by the Apache License, Version 2.0 please
19 # contact: helena.mcgough@intel.com or adrian.hoban@intel.com
20 """A common KafkaConsumer for all MON plugins."""
21
22 import json
23 import logging
24 import os
25 import sys
26
27 logging.basicConfig(stream=sys.stdout,
28 format='%(asctime)s %(message)s',
29 datefmt='%m/%d/%Y %I:%M:%S %p',
30 level=logging.INFO)
31 log = logging.getLogger(__name__)
32
33 sys.path.append(os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..')))
34
35 from kafka import KafkaConsumer
36
37 from osm_mon.plugins.OpenStack.Aodh import alarming
38 from osm_mon.plugins.OpenStack.Gnocchi import metrics
39
40 from osm_mon.plugins.CloudWatch.plugin_alarm import plugin_alarms
41 from osm_mon.plugins.CloudWatch.plugin_metric import plugin_metrics
42 from osm_mon.plugins.CloudWatch.connection import Connection
43 from osm_mon.plugins.CloudWatch.access_credentials import AccessCredentials
44
45 from osm_mon.plugins.vRealiseOps import plugin_receiver
46
47 from osm_mon.core.auth import AuthManager
48 from osm_mon.core.database import DatabaseManager
49
50 # Initialize servers
51 if "BROKER_URI" in os.environ:
52 server = {'server': os.getenv("BROKER_URI")}
53 else:
54 server = {'server': 'localhost:9092'}
55
56 # Initialize consumers for alarms and metrics
57 common_consumer = KafkaConsumer(bootstrap_servers=server['server'],
58 key_deserializer=bytes.decode,
59 value_deserializer=bytes.decode,
60 group_id="mon-consumer")
61
62 auth_manager = AuthManager()
63 database_manager = DatabaseManager()
64 database_manager.create_tables()
65
66 # Create OpenStack alarming and metric instances
67 openstack_metrics = metrics.Metrics()
68 openstack_alarms = alarming.Alarming()
69
70 # Create CloudWatch alarm and metric instances
71 cloudwatch_alarms = plugin_alarms()
72 cloudwatch_metrics = plugin_metrics()
73 aws_connection = Connection()
74 aws_access_credentials = AccessCredentials()
75
76 # Create vROps plugin_receiver class instance
77 vrops_rcvr = plugin_receiver.PluginReceiver()
78
79
80 def get_vim_type(msg):
81 """Get the vim type that is required by the message."""
82 try:
83 vim_uuid = json.loads(msg.value)["vim_uuid"].lower()
84 credentials = database_manager.get_credentials(vim_uuid)
85 return credentials.type
86 except Exception as exc:
87 log.warn("vim_type is not configured correctly; %s", exc)
88 return None
89
90
91 # Define subscribe the consumer for the plugins
92 topics = ['metric_request', 'alarm_request', 'access_credentials', 'vim_account']
93 # TODO: Remove access_credentials
94 common_consumer.subscribe(topics)
95
96 log.info("Listening for alarm_request and metric_request messages")
97 for message in common_consumer:
98 log.info("Message arrived: %s", message)
99 try:
100 values = json.loads(message.value)
101 # Check the message topic
102 if message.topic == "metric_request":
103 # Check the vim desired by the message
104 vim_type = get_vim_type(message)
105
106 if vim_type == "openstack":
107 log.info("This message is for the OpenStack plugin.")
108 openstack_metrics.metric_calls(message)
109 elif vim_type == "aws":
110 log.info("This message is for the CloudWatch plugin.")
111 aws_conn = aws_connection.setEnvironment()
112 cloudwatch_metrics.metric_calls(message, aws_conn)
113
114 elif vim_type == "vmware":
115 log.info("This metric_request message is for the vROPs plugin.")
116 vrops_rcvr.consume(message)
117
118 else:
119 log.debug("vim_type is misconfigured or unsupported; %s",
120 vim_type)
121
122 elif message.topic == "alarm_request":
123 # Check the vim desired by the message
124 vim_type = get_vim_type(message)
125 if vim_type == "openstack":
126 log.info("This message is for the OpenStack plugin.")
127 openstack_alarms.alarming(message)
128
129 elif vim_type == "aws":
130 log.info("This message is for the CloudWatch plugin.")
131 aws_conn = aws_connection.setEnvironment()
132 cloudwatch_alarms.alarm_calls(message, aws_conn)
133
134 elif vim_type == "vmware":
135 log.info("This alarm_request message is for the vROPs plugin.")
136 vrops_rcvr.consume(message)
137
138 else:
139 log.debug("vim_type is misconfigured or unsupported; %s",
140 vim_type)
141
142 elif message.topic == "vim_account":
143 if message.key == "create" or message.key == "edit":
144 auth_manager.store_auth_credentials(values)
145 if message.key == "delete":
146 auth_manager.delete_auth_credentials(values)
147
148 # TODO: Remove in the near future when all plugins support vim_uuid. Modify tests accordingly.
149 elif message.topic == "access_credentials":
150 # Check the vim desired by the message
151 vim_type = get_vim_type(message)
152
153 if vim_type == "aws":
154 log.info("This message is for the CloudWatch plugin.")
155 aws_access_credentials.access_credential_calls(message)
156
157 elif vim_type == "vmware":
158 log.info("This access_credentials message is for the vROPs plugin.")
159 vrops_rcvr.consume(message)
160
161 else:
162 log.debug("vim_type is misconfigured or unsupported; %s",
163 vim_type)
164
165 else:
166 log.info("This topic is not relevant to any of the MON plugins.")
167
168
169 except Exception as exc:
170 log.exception("Exception: %s")