blob: 88725dbff214c971f9f336ea50b2b95d6a6ce140 [file] [log] [blame]
Sapan Bhatia26d40bc2014-05-12 15:28:02 -04001import os
2import imp
3import inspect
4import time
5import traceback
6import commands
7import threading
8import json
9
10from datetime import datetime
11from collections import defaultdict
12from core.models import *
13from django.db.models import F, Q
14#from openstack.manager import OpenStackManager
15from openstack.driver import OpenStackDriver
16from util.logger import Logger, logging, logger
17#from timeout import timeout
18from planetstack.config import Config
Sapan Bhatia51f48932014-08-25 04:17:12 -040019from observer.steps import *
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040020from syncstep import SyncStep
21from toposort import toposort
Sapan Bhatia51f48932014-08-25 04:17:12 -040022from observer.error_mapper import *
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040023
24debug_mode = False
25
26logger = Logger(level=logging.INFO)
27
28class StepNotReady(Exception):
Sapan Bhatia51f48932014-08-25 04:17:12 -040029 pass
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040030
31class NoOpDriver:
Sapan Bhatia51f48932014-08-25 04:17:12 -040032 def __init__(self):
33 self.enabled = True
Sapan Bhatia4a1335c2014-09-03 01:06:17 -040034 self.dependency_graph = None
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040035
Sapan Bhatia723b1c32014-09-03 11:28:59 -040036STEP_STATUS_WORKING=1
37STEP_STATUS_OK=2
38STEP_STATUS_KO=3
39
40def invert_graph(g):
41 ig = {}
42 for k,v in g.items():
43 for v0 in v:
44 try:
45 ig[v0].append(k)
46 except:
47 ig=[k]
48 return ig
49
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040050class PlanetStackObserver:
51 #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivileges,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
52 sync_steps = []
53
Sapan Bhatia723b1c32014-09-03 11:28:59 -040054
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040055 def __init__(self):
56 # The Condition object that gets signalled by Feefie events
57 self.step_lookup = {}
58 self.load_sync_step_modules()
59 self.load_sync_steps()
60 self.event_cond = threading.Condition()
61
62 self.driver_kind = getattr(Config(), "observer_driver", "openstack")
63 if self.driver_kind=="openstack":
64 self.driver = OpenStackDriver()
65 else:
66 self.driver = NoOpDriver()
67
Sapan Bhatia723b1c32014-09-03 11:28:59 -040068 def wait_for_event(self, timeout):
69 self.event_cond.acquire()
70 self.event_cond.wait(timeout)
71 self.event_cond.release()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040072
Sapan Bhatia723b1c32014-09-03 11:28:59 -040073 def wake_up(self):
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040074 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
Sapan Bhatia723b1c32014-09-03 11:28:59 -040075 self.event_cond.acquire()
76 self.event_cond.notify()
77 self.event_cond.release()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040078
79 def load_sync_step_modules(self, step_dir=None):
80 if step_dir is None:
81 if hasattr(Config(), "observer_steps_dir"):
82 step_dir = Config().observer_steps_dir
83 else:
84 step_dir = "/opt/planetstack/observer/steps"
85
86 for fn in os.listdir(step_dir):
87 pathname = os.path.join(step_dir,fn)
88 if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
89 module = imp.load_source(fn[:-3],pathname)
90 for classname in dir(module):
91 c = getattr(module, classname, None)
92
93 # make sure 'c' is a descendent of SyncStep and has a
94 # provides field (this eliminates the abstract base classes
95 # since they don't have a provides)
96
97 if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
98 self.sync_steps.append(c)
99 logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
100 # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
101
102 def load_sync_steps(self):
103 dep_path = Config().observer_dependency_graph
104 logger.info('Loading model dependency graph from %s' % dep_path)
105 try:
106 # This contains dependencies between records, not sync steps
107 self.model_dependency_graph = json.loads(open(dep_path).read())
108 except Exception,e:
109 raise e
110
111 try:
112 backend_path = Config().observer_pl_dependency_graph
113 logger.info('Loading backend dependency graph from %s' % backend_path)
114 # This contains dependencies between backend records
115 self.backend_dependency_graph = json.loads(open(backend_path).read())
116 except Exception,e:
Sapan Bhatia51f48932014-08-25 04:17:12 -0400117 logger.info('Backend dependency graph not loaded')
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400118 # We can work without a backend graph
119 self.backend_dependency_graph = {}
120
121 provides_dict = {}
122 for s in self.sync_steps:
123 self.step_lookup[s.__name__] = s
124 for m in s.provides:
125 try:
126 provides_dict[m.__name__].append(s.__name__)
127 except KeyError:
128 provides_dict[m.__name__]=[s.__name__]
129
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400130 step_graph = {}
131 for k,v in self.model_dependency_graph.iteritems():
132 try:
133 for source in provides_dict[k]:
134 for m in v:
135 try:
136 for dest in provides_dict[m]:
137 # no deps, pass
138 try:
139 if (dest not in step_graph[source]):
140 step_graph[source].append(dest)
141 except:
142 step_graph[source]=[dest]
143 except KeyError:
144 pass
145
146 except KeyError:
147 pass
148 # no dependencies, pass
149
150 #import pdb
151 #pdb.set_trace()
152 if (self.backend_dependency_graph):
153 backend_dict = {}
154 for s in self.sync_steps:
155 for m in s.serves:
156 backend_dict[m]=s.__name__
157
158 for k,v in backend_dependency_graph.iteritems():
159 try:
160 source = backend_dict[k]
161 for m in v:
162 try:
163 dest = backend_dict[m]
164 except KeyError:
165 # no deps, pass
166 pass
167 step_graph[source]=dest
168
169 except KeyError:
170 pass
171 # no dependencies, pass
172
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400173 self.dependency_graph = step_graph
Sapan Bhatia723b1c32014-09-03 11:28:59 -0400174 self.deletion_dependency_graph = invert_graph(step_graph)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400175
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400176 self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps))
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400177 print "Order of steps=",self.ordered_steps
178 self.load_run_times()
179
180
181 def check_duration(self, step, duration):
182 try:
183 if (duration > step.deadline):
184 logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
185 except AttributeError:
186 # S doesn't have a deadline
187 pass
188
189 def update_run_time(self, step, deletion):
190 if (not deletion):
191 self.last_run_times[step.__name__]=time.time()
192 else:
193 self.last_deletion_run_times[step.__name__]=time.time()
194
195
196 def check_schedule(self, step, deletion):
197 last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
198
199 time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
200 try:
201 if (time_since_last_run < step.requested_interval):
202 raise StepNotReady
203 except AttributeError:
204 logger.info('Step %s does not have requested_interval set'%step.__name__)
205 raise StepNotReady
206
207 def load_run_times(self):
208 try:
209 jrun_times = open('/tmp/observer_run_times').read()
210 self.last_run_times = json.loads(jrun_times)
211 except:
212 self.last_run_times={}
213 for e in self.ordered_steps:
214 self.last_run_times[e]=0
215 try:
216 jrun_times = open('/tmp/observer_deletion_run_times').read()
217 self.last_deletion_run_times = json.loads(jrun_times)
218 except:
219 self.last_deletion_run_times={}
220 for e in self.ordered_steps:
221 self.last_deletion_run_times[e]=0
222
223
224
225 def save_run_times(self):
226 run_times = json.dumps(self.last_run_times)
227 open('/tmp/observer_run_times','w').write(run_times)
228
229 deletion_run_times = json.dumps(self.last_deletion_run_times)
230 open('/tmp/observer_deletion_run_times','w').write(deletion_run_times)
231
232 def check_class_dependency(self, step, failed_steps):
233 step.dependenices = []
234 for obj in step.provides:
235 step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
236 for failed_step in failed_steps:
237 if (failed_step in step.dependencies):
238 raise StepNotReady
239
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400240 def sync(self, S, deletion):
241 step = self.step_lookup[S]
242 start_time=time.time()
243
244 # Wait for step dependencies to be met
245 deps = self.dependency_graph[S]
246 for d in deps:
247 cond = self.step_conditions[d]
248 acquire(cond)
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400249 if (self.step_status[S] is STEP_STATUS_WORKING):
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400250 cond.wait()
251 cond.release()
Sapan Bhatia51f48932014-08-25 04:17:12 -0400252
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400253 if (self.step_status[S] is not STEP_STATUS_OK):
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400254 self.failed_steps.append(sync_step)
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400255 my_status = STEP_STATUS_KO
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400256 else:
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400257 sync_step = step(driver=self.driver,error_map=error_mapper)
258 sync_step.__name__ = step.__name__
259 sync_step.dependencies = []
260 try:
261 mlist = sync_step.provides
262
263 for m in mlist:
264 sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
265 except KeyError:
266 pass
267 sync_step.debug_mode = debug_mode
268
269 should_run = False
270 try:
271 # Various checks that decide whether
272 # this step runs or not
273 self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
274 self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
275 should_run = True
276 except StepNotReady:
277 logging.info('Step not ready: %s'%sync_step.__name__)
278 self.failed_steps.append(sync_step)
279 my_status = STEP_STATUS_KO
280 except Exception,e:
281 logging.error('%r',e)
282 logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
283 self.failed_steps.append(sync_step)
284 my_status = STEP_STATUS_KO
285
286 if (should_run):
287 try:
288 duration=time.time() - start_time
289
290 logger.info('Executing step %s' % sync_step.__name__)
291
292 failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
293
294 self.check_duration(sync_step, duration)
295
296 if failed_objects:
297 self.failed_step_objects.update(failed_objects)
298
299 my_status = STEP_STATUS_OK
300 self.update_run_time(sync_step,deletion)
301 except Exception,e:
302 logging.error('Model step failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
303 logger.log_exc(e)
304 self.failed_steps.append(S)
305 my_status = STEP_STATUS_KO
306 else:
307 my_status = STEP_STATUS_OK
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400308
309 try:
310 my_cond = self.step_conditions[S]
311 my_cond.acquire()
312 self.step_status[S]=my_status
313 my_cond.notify_all()
314 my_cond.release()
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400315 except KeyError,e:
316 logging.info('Step %r is a leaf')
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400317 pass
Sapan Bhatia51f48932014-08-25 04:17:12 -0400318
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400319 def run(self):
320 if not self.driver.enabled:
321 return
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400322
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400323 if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
324 return
325
326 while True:
327 try:
328 error_map_file = getattr(Config(), "error_map_path", "/opt/planetstack/error_map.txt")
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400329 self.error_mapper = ErrorMapper(error_map_file)
330
331 # Set of whole steps that failed
332 self.failed_steps = []
333
334 # Set of individual objects within steps that failed
335 self.failed_step_objects = set()
336
337 # Set up conditions and step status
338 # This is needed for steps to run in parallel
339 # while obeying dependencies.
340
341 providers = set()
342 for v in self.dependency_graph.values():
343 if (v):
344 providers.update(v)
Sapan Bhatia723b1c32014-09-03 11:28:59 -0400345
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400346 self.step_conditions = {}
347 self.step_status = {}
348 for p in list(providers):
349 self.step_conditions[p] = threading.Condition()
350 self.step_status[p] = STEP_STATUS_IDLE
351
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400352
353 logger.info('Waiting for event')
354 tBeforeWait = time.time()
Sapan Bhatia13d89152014-07-23 10:35:33 -0400355 self.wait_for_event(timeout=30)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400356 logger.info('Observer woke up')
357
358 # Two passes. One for sync, the other for deletion.
Sapan Bhatia0f727b82014-08-18 02:44:20 -0400359 for deletion in [False,True]:
Sapan Bhatia51f48932014-08-25 04:17:12 -0400360 threads = []
Sapan Bhatiabab33762014-07-22 01:21:36 -0400361 logger.info('Deletion=%r...'%deletion)
Sapan Bhatia723b1c32014-09-03 11:28:59 -0400362 schedule = self.ordered_steps if not deletion else reversed(self.ordered_steps)
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400363
364 thread = threading.Thread(target=self.sync, args=(schedule.start_conditions, schedule.ordered_steps,deletion, schedule.signal_sem))
365
Sapan Bhatia51f48932014-08-25 04:17:12 -0400366 logger.info('Deletion=%r...'%deletion)
367 threads.append(thread)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400368
Sapan Bhatia51f48932014-08-25 04:17:12 -0400369 # Start threads
370 for t in threads:
371 t.start()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400372
Sapan Bhatia51f48932014-08-25 04:17:12 -0400373 # Wait for all threads to finish before continuing with the run loop
374 for t in threads:
375 t.join()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400376
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400377 self.save_run_times()
378 except Exception, e:
379 logging.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
380 logger.log_exc("Exception in observer run loop")
381 traceback.print_exc()