blob: 7ab8fe8a245e153ddad1ff89cb3a2e722396d4a7 [file] [log] [blame]
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -05001import socket
2import requests
3import urllib2
4import json
5import msgpack
6import collections
7import time, thread, threading
8
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -05009from flask import request, Request, jsonify
10from flask import Flask
11from flask import make_response
12app = Flask(__name__)
13
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050014projects_map = {}
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050015xos_tenant_info_map = {}
16xos_instances_info_map = {}
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050017
18UDP_IP = "0.0.0.0"
19UDP_PORT = 12346
20
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -050021@app.route('/autoscaledata',methods=['GET'])
22def autoscaledata():
23 response = app.make_response(json.dumps(projects_map))
24 response.mimetype="application/json"
25 return response
26
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050027def acquire_xos_monitoring_channel():
28 url = "http://ctl:9999/xoslib/monitoringchannel/"
29 admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
30 monitoring_channels = requests.get(url, auth=admin_auth).json()
31 ceilometer_url = None
32 if not monitoring_channels:
33 print 'SRIKANTH: No monitoring channels for this user...'
34 return None
35 else:
36 monitoring_channel = monitoring_channels[0]
37 while not monitoring_channel['ceilometer_url']:
38 print 'SRIKANTH: Waiting for monitoring channel create'
39 sleep(0.5)
40 monitoring_channel = requests.get(url, auth=admin_auth).json()[0]
41 #TODO: Wait until URL is completely UP
42 while True:
43 print 'SRIKANTH: Waiting for ceilometer proxy URL %s is available' % monitoring_channel['ceilometer_url']
44 try:
45 response = urllib2.urlopen(monitoring_channel['ceilometer_url'],timeout=1)
46 break
47 except urllib2.HTTPError, e:
48 print 'SRIKANTH: HTTP error %s' % e.reason
49 break
50 except urllib2.URLError, e:
51 print 'SRIKANTH: URL error %(reason)s' % e.reason
52 pass
53 return monitoring_channel
54
55def print_samples():
56 print ""
57 print ""
58 for project in projects_map.keys():
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050059 print "service=%s slice=%s, alarm_state=%s" % (projects_map[project]['xos_tenant_info']['service'] if projects_map[project]['xos_tenant_info'] else None, projects_map[project]['xos_tenant_info']['slice'] if projects_map[project]['xos_tenant_info'] else project, projects_map[project]['alarm'])
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050060 for resource in projects_map[project]['resources'].keys():
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050061 print "resource=%s" % (projects_map[project]['resources'][resource]['xos_instance_info']['instance_name'] if projects_map[project]['resources'][resource]['xos_instance_info'] else resource)
62 for i in projects_map[project]['resources'][resource]['queue']:
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050063 print " time=%s val=%s" % ( i['timestamp'],i['counter_volume'])
64
65def periodic_print():
66 print_samples()
67 #Print every 1minute
68 threading.Timer(60, periodic_print).start()
69
70
71CPU_UPPER_THRESHOLD = 80 #80%
72CPU_LOWER_THRESHOLD = 30 #30%
73CPU_THRESHOLD_REPEAT = 3
74INITIAL_STATE = 'normal_config'
75SCALE_UP_EVALUATION = 'scale_up_eval'
76SCALE_DOWN_EVALUATION = 'scale_down_eval'
77SCALE_UP_ALARM = 'scale_up'
78SCALE_DOWN_ALARM = 'scale_down'
79
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050080def loadAllXosTenantInfo():
81 print "SRIKANTH: Loading all XOS tenant info"
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050082 url = "http://ctl:9999/xos/controllerslices/"
83 admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
84 controller_slices = requests.get(url, auth=admin_auth).json()
85 for cslice in controller_slices:
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050086 slice = requests.get(cslice['slice'], auth=admin_auth).json()
87 slice_name = slice['humanReadableName']
88 if slice['service']:
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -050089 service = requests.get(slice['service'], auth=admin_auth).json()
90 service_name = service['humanReadableName']
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -050091 else:
92 service_name = None
93 xos_tenant_info_map[cslice['tenant_id']] = {'service':service_name, 'slice':slice_name}
94 print "SRIKANTH: Project: %s Service:%s Slice:%s" % (cslice['tenant_id'],service_name,slice_name)
95
96def loadAllXosInstanceInfo():
97 print "SRIKANTH: Loading all XOS instance info"
98 url = "http://130.127.133.87:9999/xos/instances/"
99 admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
100 xos_instances = requests.get(url, auth=admin_auth).json()
101 for instance in xos_instances:
102 xos_instances_info_map[instance['instance_uuid']] = {'instance_name':instance['instance_name']}
103
104def getXosTenantInfo(project):
105 xos_tenant_info = xos_tenant_info_map.get(project, None)
106 if xos_tenant_info:
107 return xos_tenant_info
108 else:
109 loadAllXosTenantInfo()
110 xos_tenant_info = xos_tenant_info_map.get(project, None)
111 if not xos_tenant_info:
112 print "SRIKANTH: Project %s has no associated XOS slice" % project
113 return xos_tenant_info
114
115def getXosInstanceInfo(resource):
116 xos_instance_info = xos_instances_info_map.get(resource, None)
117 if xos_instance_info:
118 return xos_instance_info
119 else:
120 loadAllXosInstanceInfo()
121 xos_instance_info = xos_instances_info_map.get(resource, None)
122 if not xos_instance_info:
123 print "SRIKANTH: Resource %s has no associated XOS instance" % project
124 return xos_instance_info
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500125
126def handle_adjust_scale(project, adjust):
127 if (adjust != 'up') and (adjust != 'down'):
128 print "SRIKANTH: Invalid adjust value %s " % adjust
129 return
130 current_instances = len(projects_map[project]['resources'].keys())
131 if (current_instances <=1 and adjust == 'down'):
132 print "SRIKANTH: %s is running with already minimum instances and can not scale down further " % project
133 return
134 if (current_instances >=2 and adjust == 'up'):
135 print "SRIKANTH: %s is running with already maximum instances and can not scale up further " % project
136 return
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -0500137 #xos_tenant = getXosTenantInfo(project)
138 xos_tenant = projects_map[project]['xos_tenant_info']
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500139 if not xos_tenant:
140 print "SRIKANTH: Can not handle adjust_scale for Project %s because not associated with any slice" % project
141 return
142 xos_service = xos_tenant['service']
143 xos_slice = xos_tenant['slice']
144 if not xos_service or not xos_slice:
145 print "SRIKANTH: Can not handle adjust_scale for Project %s because not associated with any service or slice" % project
146 return
147 print "SRIKANTH: SCALE %s for Project %s, Slice=%s, Service=%s from current=%d to new=%d" % (adjust, project, xos_slice, xos_service, current_instances, current_instances+1 if (adjust=='up') else current_instances-1)
148 query_params = {'service':xos_service, 'slice_hint':xos_slice, 'scale':current_instances+1 if (adjust=='up') else current_instances-1}
149 url = "http://ctl:9999/xoslib/serviceadjustscale/"
150 admin_auth=("padmin@vicci.org", "letmein") # use your XOS username and password
151 response = requests.get(url, params=query_params, auth=admin_auth).json()
152 print "SRIKANTH: XOS adjust_scale response: %s" % response
153
154def periodic_cpu_threshold_evaluator():
155 for project in projects_map.keys():
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -0500156 aggregate_cpu_util = sum([resource['queue'][-1]['counter_volume'] \
157 for resource in projects_map[project]['resources'].values()]) \
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500158 /len(projects_map[project]['resources'].keys())
159
160 if (projects_map[project]['alarm'] == INITIAL_STATE or
161 projects_map[project]['alarm'] == SCALE_UP_ALARM or
162 projects_map[project]['alarm'] == SCALE_DOWN_ALARM):
163 if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
164 projects_map[project]['uthreadshold_count'] = 1
165 projects_map[project]['alarm'] = SCALE_UP_EVALUATION
166 if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
167 projects_map[project]['alarm'] = SCALE_UP_ALARM
168 handle_adjust_scale(project, 'up')
169 elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
170 projects_map[project]['lthreadshold_count'] = 1
171 projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
172 if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
173 projects_map[project]['alarm'] = SCALE_DOWN_ALARM
174 handle_adjust_scale(project, 'down')
175 else:
176 projects_map[project]['uthreadshold_count'] = 0
177 projects_map[project]['lthreadshold_count'] = 0
178 projects_map[project]['alarm'] = INITIAL_STATE
179 elif projects_map[project]['alarm'] == SCALE_UP_EVALUATION:
180 if aggregate_cpu_util > CPU_UPPER_THRESHOLD:
181 projects_map[project]['uthreadshold_count'] += 1
182 if projects_map[project]['uthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
183 projects_map[project]['alarm'] = SCALE_UP_ALARM
184 handle_adjust_scale(project, 'up')
185 elif aggregate_cpu_util < CPU_LOWER_THRESHOLD:
186 projects_map[project]['lthreadshold_count'] += 1
187 projects_map[project]['alarm'] = SCALE_DOWN_EVALUATION
188 else:
189 projects_map[project]['uthreadshold_count'] = 0
190 projects_map[project]['alarm'] = INITIAL_STATE
191 elif projects_map[project]['alarm'] == SCALE_DOWN_EVALUATION:
192 if aggregate_cpu_util < CPU_LOWER_THRESHOLD:
193 projects_map[project]['lthreadshold_count'] += 1
194 if projects_map[project]['lthreadshold_count'] >= CPU_THRESHOLD_REPEAT:
195 projects_map[project]['alarm'] = SCALE_DOWN_ALARM
196 handle_adjust_scale(project, 'down')
197 elif aggregate_cpu_util > CPU_UPPER_THRESHOLD:
198 projects_map[project]['uthreadshold_count'] += 1
199 projects_map[project]['alarm'] = SCALE_UP_EVALUATION
200 else:
201 projects_map[project]['lthreadshold_count'] = 0
202 projects_map[project]['alarm'] = INITIAL_STATE
203 threading.Timer(60, periodic_cpu_threshold_evaluator).start()
204
205def read_notification_from_ceilometer(host,port):
206 udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
207 udp.bind((host, port))
208
209 while True:
210 data, source = udp.recvfrom(64000)
211 try:
212 sample = msgpack.loads(data, encoding='utf-8')
213 if sample['counter_name'] != 'cpu_util':
214 continue
215 if sample['project_id'] not in projects_map.keys():
216 projects_map[sample['project_id']] = {}
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -0500217 projects_map[sample['project_id']]['xos_tenant_info'] = getXosTenantInfo(sample['project_id'])
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500218 projects_map[sample['project_id']]['resources'] = {}
219 projects_map[sample['project_id']]['uthreadshold_count'] = 0
220 projects_map[sample['project_id']]['lthreadshold_count'] = 0
221 projects_map[sample['project_id']]['alarm'] = INITIAL_STATE
222 resource_map = projects_map[sample['project_id']]['resources']
223 if sample['resource_id'] not in resource_map.keys():
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -0500224 resource_map[sample['resource_id']] = {}
225 resource_map[sample['resource_id']]['xos_instance_info'] = getXosInstanceInfo(sample['resource_id'])
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -0500226 resource_map[sample['resource_id']]['queue'] = []
227 samples_queue = resource_map[sample['resource_id']]['queue']
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500228 sample = {'counter_name':sample['counter_name'],
229 'project_id':sample['project_id'],
230 'resource_id':sample['resource_id'],
231 'timestamp':sample['timestamp'],
232 'counter_unit':sample['counter_unit'],
233 'counter_volume':sample['counter_volume']}
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -0500234 deque = collections.deque(samples_queue, maxlen=10)
235 deque.append(sample)
236 resource_map[sample['resource_id']]['queue'] = list(deque)
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500237 except Exception as e:
238 print e
239
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -0500240def setup_webserver():
241 try:
242 #config = ConfigParser.ConfigParser()
243 #config.read('pub_sub.conf')
244 #webserver_host = config.get('WEB_SERVER','webserver_host')
245 #webserver_port = int (config.get('WEB_SERVER','webserver_port'))
246 #client_host = config.get('CLIENT','client_host')
247 #client_port = int (config.get('CLIENT','client_port'))
248
249 #log_level = config.get('LOGGING','level')
250 #log_file = config.get('LOGGING','filename')
251
252 #level = LEVELS.get(log_level, logging.NOTSET)
253 #logging.basicConfig(filename=log_file,format='%(asctime)s %(levelname)s %(message)s',\
254 # datefmt=_DEFAULT_LOG_DATE_FORMAT,level=level)
255 webserver_host = '0.0.0.0'
256 webserver_port = 9991
257
258 except Exception as e:
259 print("* Error in config file:",e.__str__())
260 logging.error("* Error in confing file:%s",e.__str__())
261 else:
262 app.run(host=webserver_host,port=webserver_port,debug=True, use_reloader=False)
263
264
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500265def main():
266 monitoring_channel = acquire_xos_monitoring_channel()
267 if not monitoring_channel:
268 print 'SRIKANTH: XOS monitoring_channel is not created... Create it before using this app'
269 return
Srikanth Vavilapalli73afe292015-12-14 17:35:04 -0500270 loadAllXosTenantInfo()
271 loadAllXosInstanceInfo()
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500272 thread.start_new(read_notification_from_ceilometer,(UDP_IP,UDP_PORT,))
273 ceilometer_url = monitoring_channel['ceilometer_url']
274 subscribe_data = {"sub_info":"cpu_util","app_id":"xos_auto_scale","target":"udp://10.11.10.1:12346"}
275 subscribe_url = ceilometer_url + 'v2/subscribe'
276 response = requests.post(subscribe_url, data=json.dumps(subscribe_data))
277 print 'SRIKANTH: Ceilometer Subscription status:%s' % response.text
278 #TODO: Fix the typo in 'sucess'
279 if (not 'sucess' in response.text) and (not 'already exists' in response.text):
280 print 'SRIKANTH: Ceilometer Subscription unsuccessful...Exiting'
281 return
282 periodic_cpu_threshold_evaluator()
283 periodic_print()
Srikanth Vavilapallia6de6a32015-12-16 14:55:30 -0500284 setup_webserver()
Srikanth Vavilapalli1ea11fc2015-12-14 00:52:57 -0500285
286if __name__ == "__main__":
287 main()