blob: cc0611c4c92129baca9804938398c7223767f8fa [file] [log] [blame]
Scott Baker45fb7a12013-12-31 00:56:19 -08001import os
2import imp
3import inspect
Sapan Bhatia24836f12013-08-27 10:16:05 -04004import time
5import traceback
6import commands
7import threading
8import json
Sapan Bhatiaab202a62014-09-03 11:30:21 -04009import pdb
Sapan Bhatia24836f12013-08-27 10:16:05 -040010
11from datetime import datetime
12from collections import defaultdict
13from core.models import *
14from django.db.models import F, Q
Scott Bakerc7ca6552014-09-05 14:48:38 -070015from django.db import connection
Tony Mack387a73f2013-09-18 07:59:14 -040016#from openstack.manager import OpenStackManager
17from openstack.driver import OpenStackDriver
Sapan Bhatia24836f12013-08-27 10:16:05 -040018from util.logger import Logger, logging, logger
19#from timeout import timeout
Sapan Bhatia757e0b62013-09-02 16:55:00 -040020from planetstack.config import Config
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040021from observer.steps import *
Scott Baker45fb7a12013-12-31 00:56:19 -080022from syncstep import SyncStep
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040023from toposort import toposort
Sapan Bhatia13d89152014-07-23 10:35:33 -040024from observer.error_mapper import *
Sapan Bhatiacb6f8d62015-01-17 01:03:52 +000025from openstack_observer.openstacksyncstep import OpenStackSyncStep
26
Sapan Bhatia24836f12013-08-27 10:16:05 -040027
Sapan Bhatia13c7f112013-09-02 14:19:35 -040028debug_mode = False
Sapan Bhatia24836f12013-08-27 10:16:05 -040029
Sapan Bhatiacb6f8d62015-01-17 01:03:52 +000030class bcolors:
31 HEADER = '\033[95m'
32 OKBLUE = '\033[94m'
33 OKGREEN = '\033[92m'
34 WARNING = '\033[93m'
35 FAIL = '\033[91m'
36 ENDC = '\033[0m'
37 BOLD = '\033[1m'
38 UNDERLINE = '\033[4m'
39
Andy Bavier04111b72013-10-22 16:47:10 -040040logger = Logger(level=logging.INFO)
Sapan Bhatia24836f12013-08-27 10:16:05 -040041
Sapan Bhatia13c7f112013-09-02 14:19:35 -040042class StepNotReady(Exception):
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040043 pass
Sapan Bhatia24836f12013-08-27 10:16:05 -040044
Scott Baker7771f412014-01-02 16:36:41 -080045class NoOpDriver:
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040046 def __init__(self):
47 self.enabled = True
Sapan Bhatiaab202a62014-09-03 11:30:21 -040048 self.dependency_graph = None
49
50STEP_STATUS_WORKING=1
51STEP_STATUS_OK=2
52STEP_STATUS_KO=3
53
54def invert_graph(g):
55 ig = {}
56 for k,v in g.items():
57 for v0 in v:
58 try:
59 ig[v0].append(k)
60 except:
61 ig=[k]
62 return ig
Scott Baker7771f412014-01-02 16:36:41 -080063
Sapan Bhatia24836f12013-08-27 10:16:05 -040064class PlanetStackObserver:
Tony Macka7dbd422015-01-05 22:48:11 -050065 #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivilege,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040066 sync_steps = []
Sapan Bhatia24836f12013-08-27 10:16:05 -040067
Sapan Bhatiaab202a62014-09-03 11:30:21 -040068
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040069 def __init__(self):
70 # The Condition object that gets signalled by Feefie events
71 self.step_lookup = {}
72 self.load_sync_step_modules()
73 self.load_sync_steps()
74 self.event_cond = threading.Condition()
Scott Baker7771f412014-01-02 16:36:41 -080075
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040076 self.driver_kind = getattr(Config(), "observer_driver", "openstack")
77 if self.driver_kind=="openstack":
78 self.driver = OpenStackDriver()
79 else:
80 self.driver = NoOpDriver()
Sapan Bhatia24836f12013-08-27 10:16:05 -040081
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040082 def wait_for_event(self, timeout):
83 self.event_cond.acquire()
84 self.event_cond.wait(timeout)
85 self.event_cond.release()
Scott Baker45fb7a12013-12-31 00:56:19 -080086
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040087 def wake_up(self):
88 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
89 self.event_cond.acquire()
90 self.event_cond.notify()
91 self.event_cond.release()
Sapan Bhatia24836f12013-08-27 10:16:05 -040092
Sapan Bhatiaf73664b2014-04-28 13:07:18 -040093 def load_sync_step_modules(self, step_dir=None):
94 if step_dir is None:
95 if hasattr(Config(), "observer_steps_dir"):
96 step_dir = Config().observer_steps_dir
97 else:
98 step_dir = "/opt/planetstack/observer/steps"
Scott Baker45fb7a12013-12-31 00:56:19 -080099
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400100 for fn in os.listdir(step_dir):
101 pathname = os.path.join(step_dir,fn)
102 if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
103 module = imp.load_source(fn[:-3],pathname)
104 for classname in dir(module):
105 c = getattr(module, classname, None)
Scott Baker45fb7a12013-12-31 00:56:19 -0800106
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400107 # make sure 'c' is a descendent of SyncStep and has a
108 # provides field (this eliminates the abstract base classes
109 # since they don't have a provides)
Scott Baker45fb7a12013-12-31 00:56:19 -0800110
Sapan Bhatia43c7f8c2015-01-17 01:04:10 +0000111 if inspect.isclass(c) and (issubclass(c, SyncStep) or issubclass(c,OpenStackSyncStep)) and hasattr(c,"provides") and (c not in self.sync_steps):
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400112 self.sync_steps.append(c)
113 logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
114 # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
Scott Baker45fb7a12013-12-31 00:56:19 -0800115
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400116 def load_sync_steps(self):
117 dep_path = Config().observer_dependency_graph
118 logger.info('Loading model dependency graph from %s' % dep_path)
119 try:
120 # This contains dependencies between records, not sync steps
121 self.model_dependency_graph = json.loads(open(dep_path).read())
122 except Exception,e:
123 raise e
Sapan Bhatia24836f12013-08-27 10:16:05 -0400124
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400125 try:
126 backend_path = Config().observer_pl_dependency_graph
127 logger.info('Loading backend dependency graph from %s' % backend_path)
128 # This contains dependencies between backend records
129 self.backend_dependency_graph = json.loads(open(backend_path).read())
130 except Exception,e:
131 logger.info('Backend dependency graph not loaded')
132 # We can work without a backend graph
133 self.backend_dependency_graph = {}
Sapan Bhatia24836f12013-08-27 10:16:05 -0400134
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400135 provides_dict = {}
136 for s in self.sync_steps:
137 self.step_lookup[s.__name__] = s
138 for m in s.provides:
139 try:
140 provides_dict[m.__name__].append(s.__name__)
141 except KeyError:
142 provides_dict[m.__name__]=[s.__name__]
Sapan Bhatia04c94ad2013-09-02 18:00:28 -0400143
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400144 step_graph = {}
145 for k,v in self.model_dependency_graph.iteritems():
146 try:
147 for source in provides_dict[k]:
148 for m in v:
149 try:
150 for dest in provides_dict[m]:
151 # no deps, pass
152 try:
153 if (dest not in step_graph[source]):
154 step_graph[source].append(dest)
155 except:
156 step_graph[source]=[dest]
157 except KeyError:
158 pass
159
160 except KeyError:
161 pass
162 # no dependencies, pass
163
164 #import pdb
165 #pdb.set_trace()
166 if (self.backend_dependency_graph):
167 backend_dict = {}
168 for s in self.sync_steps:
169 for m in s.serves:
170 backend_dict[m]=s.__name__
171
172 for k,v in backend_dependency_graph.iteritems():
173 try:
174 source = backend_dict[k]
175 for m in v:
176 try:
177 dest = backend_dict[m]
178 except KeyError:
179 # no deps, pass
180 pass
181 step_graph[source]=dest
182
183 except KeyError:
184 pass
185 # no dependencies, pass
Sapan Bhatia24836f12013-08-27 10:16:05 -0400186
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400187 self.dependency_graph = step_graph
188 self.deletion_dependency_graph = invert_graph(step_graph)
Sapan Bhatia24836f12013-08-27 10:16:05 -0400189
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400190 self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps))
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400191 print "Order of steps=",self.ordered_steps
192 self.load_run_times()
193
Sapan Bhatia24836f12013-08-27 10:16:05 -0400194
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400195 def check_duration(self, step, duration):
196 try:
197 if (duration > step.deadline):
198 logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
199 except AttributeError:
200 # S doesn't have a deadline
201 pass
Sapan Bhatia24836f12013-08-27 10:16:05 -0400202
Sapan Bhatia285decb2014-04-30 00:31:44 -0400203 def update_run_time(self, step, deletion):
204 if (not deletion):
205 self.last_run_times[step.__name__]=time.time()
206 else:
207 self.last_deletion_run_times[step.__name__]=time.time()
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400208
Sapan Bhatia285decb2014-04-30 00:31:44 -0400209
210 def check_schedule(self, step, deletion):
211 last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
212
213 time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400214 try:
215 if (time_since_last_run < step.requested_interval):
216 raise StepNotReady
217 except AttributeError:
218 logger.info('Step %s does not have requested_interval set'%step.__name__)
219 raise StepNotReady
220
221 def load_run_times(self):
222 try:
223 jrun_times = open('/tmp/observer_run_times').read()
224 self.last_run_times = json.loads(jrun_times)
225 except:
226 self.last_run_times={}
227 for e in self.ordered_steps:
228 self.last_run_times[e]=0
Sapan Bhatia285decb2014-04-30 00:31:44 -0400229 try:
230 jrun_times = open('/tmp/observer_deletion_run_times').read()
231 self.last_deletion_run_times = json.loads(jrun_times)
232 except:
233 self.last_deletion_run_times={}
234 for e in self.ordered_steps:
235 self.last_deletion_run_times[e]=0
236
Sapan Bhatia36938ca2013-09-02 14:35:24 -0400237
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400238 def save_run_times(self):
239 run_times = json.dumps(self.last_run_times)
240 open('/tmp/observer_run_times','w').write(run_times)
Sapan Bhatia36938ca2013-09-02 14:35:24 -0400241
Sapan Bhatia285decb2014-04-30 00:31:44 -0400242 deletion_run_times = json.dumps(self.last_deletion_run_times)
243 open('/tmp/observer_deletion_run_times','w').write(deletion_run_times)
244
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400245 def check_class_dependency(self, step, failed_steps):
246 step.dependenices = []
247 for obj in step.provides:
248 step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
249 for failed_step in failed_steps:
250 if (failed_step in step.dependencies):
251 raise StepNotReady
252
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400253 def sync(self, S, deletion):
Scott Bakerc7ca6552014-09-05 14:48:38 -0700254 try:
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400255 step = self.step_lookup[S]
256 start_time=time.time()
Scott Bakeradc73172014-09-04 10:36:51 -0700257
258 logger.info("Starting to work on step %s" % step.__name__)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400259
260 dependency_graph = self.dependency_graph if not deletion else self.deletion_dependency_graph
Sapan Bhatia51f48932014-08-25 04:17:12 -0400261
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400262 # Wait for step dependencies to be met
263 try:
264 deps = self.dependency_graph[S]
265 has_deps = True
266 except KeyError:
267 has_deps = False
Sapan Bhatia51f48932014-08-25 04:17:12 -0400268
Sapan Bhatia475c5972014-11-05 10:32:41 -0500269 go = False
270
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400271 if (has_deps):
272 for d in deps:
Scott Bakeradc73172014-09-04 10:36:51 -0700273 if d==step.__name__:
274 logger.info(" step %s self-wait skipped" % step.__name__)
Sapan Bhatia475c5972014-11-05 10:32:41 -0500275 go = True
Scott Bakeradc73172014-09-04 10:36:51 -0700276 continue
277
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400278 cond = self.step_conditions[d]
279 cond.acquire()
280 if (self.step_status[d] is STEP_STATUS_WORKING):
Scott Bakeradc73172014-09-04 10:36:51 -0700281 logger.info(" step %s wait on dep %s" % (step.__name__, d))
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400282 cond.wait()
283 cond.release()
Sapan Bhatia475c5972014-11-05 10:32:41 -0500284 go = go or self.step_status[d] == STEP_STATUS_OK
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400285 else:
286 go = True
287
288 if (not go):
Scott Bakeradc73172014-09-04 10:36:51 -0700289 # SMBAKER: sync_step was not defined here, so I changed
290 # this from 'sync_step' to 'step'. Verify.
291 self.failed_steps.append(step)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400292 my_status = STEP_STATUS_KO
293 else:
294 sync_step = step(driver=self.driver,error_map=self.error_mapper)
Sapan Bhatia51f48932014-08-25 04:17:12 -0400295 sync_step.__name__ = step.__name__
296 sync_step.dependencies = []
297 try:
298 mlist = sync_step.provides
Scott Bakeradc73172014-09-04 10:36:51 -0700299
Sapan Bhatia51f48932014-08-25 04:17:12 -0400300 for m in mlist:
301 sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
302 except KeyError:
303 pass
304 sync_step.debug_mode = debug_mode
305
306 should_run = False
307 try:
308 # Various checks that decide whether
309 # this step runs or not
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400310 self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
Sapan Bhatia51f48932014-08-25 04:17:12 -0400311 self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
312 should_run = True
313 except StepNotReady:
Scott Bakeradc73172014-09-04 10:36:51 -0700314 logger.info('Step not ready: %s'%sync_step.__name__)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400315 self.failed_steps.append(sync_step)
316 my_status = STEP_STATUS_KO
Sapan Bhatia51f48932014-08-25 04:17:12 -0400317 except Exception,e:
Scott Bakeradc73172014-09-04 10:36:51 -0700318 logger.error('%r' % e)
Sapan Bhatia51f48932014-08-25 04:17:12 -0400319 logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400320 self.failed_steps.append(sync_step)
321 my_status = STEP_STATUS_KO
Sapan Bhatia51f48932014-08-25 04:17:12 -0400322
323 if (should_run):
324 try:
325 duration=time.time() - start_time
326
327 logger.info('Executing step %s' % sync_step.__name__)
328
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400329 failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
Sapan Bhatia51f48932014-08-25 04:17:12 -0400330
331 self.check_duration(sync_step, duration)
Sapan Bhatia51f48932014-08-25 04:17:12 -0400332
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400333 if failed_objects:
334 self.failed_step_objects.update(failed_objects)
335
Scott Bakeradc73172014-09-04 10:36:51 -0700336 logger.info("Step %r succeeded" % step)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400337 my_status = STEP_STATUS_OK
Sapan Bhatia51f48932014-08-25 04:17:12 -0400338 self.update_run_time(sync_step,deletion)
339 except Exception,e:
Scott Bakeradc73172014-09-04 10:36:51 -0700340 logger.error('Model step %r failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % (step, e))
Sapan Bhatia51f48932014-08-25 04:17:12 -0400341 logger.log_exc(e)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400342 self.failed_steps.append(S)
343 my_status = STEP_STATUS_KO
344 else:
Scott Bakeradc73172014-09-04 10:36:51 -0700345 logger.info("Step %r succeeded due to non-run" % step)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400346 my_status = STEP_STATUS_OK
Scott Bakeradc73172014-09-04 10:36:51 -0700347
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400348 try:
349 my_cond = self.step_conditions[S]
350 my_cond.acquire()
351 self.step_status[S]=my_status
352 my_cond.notify_all()
353 my_cond.release()
354 except KeyError,e:
Scott Bakeradc73172014-09-04 10:36:51 -0700355 logger.info('Step %r is a leaf' % step)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400356 pass
Scott Bakerc7ca6552014-09-05 14:48:38 -0700357 finally:
358 connection.close()
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400359
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400360 def run(self):
361 if not self.driver.enabled:
362 return
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400363
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400364 if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
365 return
366
367 while True:
368 try:
Sapan Bhatia31ebe5c2014-04-29 00:24:09 -0400369 error_map_file = getattr(Config(), "error_map_path", "/opt/planetstack/error_map.txt")
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400370 self.error_mapper = ErrorMapper(error_map_file)
371
372 # Set of whole steps that failed
373 self.failed_steps = []
374
375 # Set of individual objects within steps that failed
376 self.failed_step_objects = set()
377
378 # Set up conditions and step status
379 # This is needed for steps to run in parallel
380 # while obeying dependencies.
381
382 providers = set()
383 for v in self.dependency_graph.values():
384 if (v):
385 providers.update(v)
386
387 self.step_conditions = {}
388 self.step_status = {}
389 for p in list(providers):
390 self.step_conditions[p] = threading.Condition()
391 self.step_status[p] = STEP_STATUS_WORKING
392
Sapan Bhatia31ebe5c2014-04-29 00:24:09 -0400393
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400394 logger.info('Waiting for event')
395 tBeforeWait = time.time()
Sapan Bhatia13d89152014-07-23 10:35:33 -0400396 self.wait_for_event(timeout=30)
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400397 logger.info('Observer woke up')
398
Sapan Bhatia285decb2014-04-30 00:31:44 -0400399 # Two passes. One for sync, the other for deletion.
Sapan Bhatia0f727b82014-08-18 02:44:20 -0400400 for deletion in [False,True]:
Sapan Bhatia51f48932014-08-25 04:17:12 -0400401 threads = []
Sapan Bhatiae82f5e52014-07-23 10:02:45 -0400402 logger.info('Deletion=%r...'%deletion)
Sapan Bhatiaab202a62014-09-03 11:30:21 -0400403 schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
404
405 for S in schedule:
406 thread = threading.Thread(target=self.sync, args=(S, deletion))
407
408 logger.info('Deletion=%r...'%deletion)
409 threads.append(thread)
Sapan Bhatia285decb2014-04-30 00:31:44 -0400410
Sapan Bhatia51f48932014-08-25 04:17:12 -0400411 # Start threads
412 for t in threads:
413 t.start()
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400414
Sapan Bhatia51f48932014-08-25 04:17:12 -0400415 # Wait for all threads to finish before continuing with the run loop
416 for t in threads:
417 t.join()
Sapan Bhatia285decb2014-04-30 00:31:44 -0400418
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400419 self.save_run_times()
420 except Exception, e:
Scott Bakeradc73172014-09-04 10:36:51 -0700421 logger.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!' % e)
Sapan Bhatiaf73664b2014-04-28 13:07:18 -0400422 logger.log_exc("Exception in observer run loop")
423 traceback.print_exc()