blob: f6b92ea1ba95561ca14f293022f4158fb9716ba8 [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
36class PlanetStackObserver:
37 #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivileges,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
38 sync_steps = []
39
Sapan Bhatia4a1335c2014-09-03 01:06:17 -040040 STEP_STATUS_WORKING=1
41 STEP_STATUS_OK=2
42 STEP_STATUS_KO=3
43
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040044 def __init__(self):
45 # The Condition object that gets signalled by Feefie events
46 self.step_lookup = {}
47 self.load_sync_step_modules()
48 self.load_sync_steps()
49 self.event_cond = threading.Condition()
50
51 self.driver_kind = getattr(Config(), "observer_driver", "openstack")
52 if self.driver_kind=="openstack":
53 self.driver = OpenStackDriver()
54 else:
55 self.driver = NoOpDriver()
56
Sapan Bhatia97e18bd2014-09-03 00:38:26 -040057 def wait_for_event(self, timeout, cond=self.event_cond):
58 cond.acquire()
59 cond.wait(timeout)
60 cond.release()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040061
Sapan Bhatia97e18bd2014-09-03 00:38:26 -040062 def wake_up(self, cond=self.event_cond):
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040063 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
Sapan Bhatia97e18bd2014-09-03 00:38:26 -040064 cond.acquire()
65 cond.notify()
66 cond.release()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040067
68 def load_sync_step_modules(self, step_dir=None):
69 if step_dir is None:
70 if hasattr(Config(), "observer_steps_dir"):
71 step_dir = Config().observer_steps_dir
72 else:
73 step_dir = "/opt/planetstack/observer/steps"
74
75 for fn in os.listdir(step_dir):
76 pathname = os.path.join(step_dir,fn)
77 if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
78 module = imp.load_source(fn[:-3],pathname)
79 for classname in dir(module):
80 c = getattr(module, classname, None)
81
82 # make sure 'c' is a descendent of SyncStep and has a
83 # provides field (this eliminates the abstract base classes
84 # since they don't have a provides)
85
86 if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
87 self.sync_steps.append(c)
88 logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
89 # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
90
91 def load_sync_steps(self):
92 dep_path = Config().observer_dependency_graph
93 logger.info('Loading model dependency graph from %s' % dep_path)
94 try:
95 # This contains dependencies between records, not sync steps
96 self.model_dependency_graph = json.loads(open(dep_path).read())
97 except Exception,e:
98 raise e
99
100 try:
101 backend_path = Config().observer_pl_dependency_graph
102 logger.info('Loading backend dependency graph from %s' % backend_path)
103 # This contains dependencies between backend records
104 self.backend_dependency_graph = json.loads(open(backend_path).read())
105 except Exception,e:
Sapan Bhatia51f48932014-08-25 04:17:12 -0400106 logger.info('Backend dependency graph not loaded')
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400107 # We can work without a backend graph
108 self.backend_dependency_graph = {}
109
110 provides_dict = {}
111 for s in self.sync_steps:
112 self.step_lookup[s.__name__] = s
113 for m in s.provides:
114 try:
115 provides_dict[m.__name__].append(s.__name__)
116 except KeyError:
117 provides_dict[m.__name__]=[s.__name__]
118
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400119 step_graph = {}
120 for k,v in self.model_dependency_graph.iteritems():
121 try:
122 for source in provides_dict[k]:
123 for m in v:
124 try:
125 for dest in provides_dict[m]:
126 # no deps, pass
127 try:
128 if (dest not in step_graph[source]):
129 step_graph[source].append(dest)
130 except:
131 step_graph[source]=[dest]
132 except KeyError:
133 pass
134
135 except KeyError:
136 pass
137 # no dependencies, pass
138
139 #import pdb
140 #pdb.set_trace()
141 if (self.backend_dependency_graph):
142 backend_dict = {}
143 for s in self.sync_steps:
144 for m in s.serves:
145 backend_dict[m]=s.__name__
146
147 for k,v in backend_dependency_graph.iteritems():
148 try:
149 source = backend_dict[k]
150 for m in v:
151 try:
152 dest = backend_dict[m]
153 except KeyError:
154 # no deps, pass
155 pass
156 step_graph[source]=dest
157
158 except KeyError:
159 pass
160 # no dependencies, pass
161
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400162 self.dependency_graph = step_graph
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400163
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400164 self.ordered_steps = toposort(self.dependency_graph, map(lambda s:s.__name__,self.sync_steps))
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400165 print "Order of steps=",self.ordered_steps
166 self.load_run_times()
167
168
169 def check_duration(self, step, duration):
170 try:
171 if (duration > step.deadline):
172 logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
173 except AttributeError:
174 # S doesn't have a deadline
175 pass
176
177 def update_run_time(self, step, deletion):
178 if (not deletion):
179 self.last_run_times[step.__name__]=time.time()
180 else:
181 self.last_deletion_run_times[step.__name__]=time.time()
182
183
184 def check_schedule(self, step, deletion):
185 last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times
186
187 time_since_last_run = time.time() - last_run_times.get(step.__name__, 0)
188 try:
189 if (time_since_last_run < step.requested_interval):
190 raise StepNotReady
191 except AttributeError:
192 logger.info('Step %s does not have requested_interval set'%step.__name__)
193 raise StepNotReady
194
195 def load_run_times(self):
196 try:
197 jrun_times = open('/tmp/observer_run_times').read()
198 self.last_run_times = json.loads(jrun_times)
199 except:
200 self.last_run_times={}
201 for e in self.ordered_steps:
202 self.last_run_times[e]=0
203 try:
204 jrun_times = open('/tmp/observer_deletion_run_times').read()
205 self.last_deletion_run_times = json.loads(jrun_times)
206 except:
207 self.last_deletion_run_times={}
208 for e in self.ordered_steps:
209 self.last_deletion_run_times[e]=0
210
211
212
213 def save_run_times(self):
214 run_times = json.dumps(self.last_run_times)
215 open('/tmp/observer_run_times','w').write(run_times)
216
217 deletion_run_times = json.dumps(self.last_deletion_run_times)
218 open('/tmp/observer_deletion_run_times','w').write(deletion_run_times)
219
220 def check_class_dependency(self, step, failed_steps):
221 step.dependenices = []
222 for obj in step.provides:
223 step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
224 for failed_step in failed_steps:
225 if (failed_step in step.dependencies):
226 raise StepNotReady
227
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400228 def sync(self, S, deletion):
229 step = self.step_lookup[S]
230 start_time=time.time()
231
232 # Wait for step dependencies to be met
233 deps = self.dependency_graph[S]
234 for d in deps:
235 cond = self.step_conditions[d]
236 acquire(cond)
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400237 if (self.step_status[S] is STEP_STATUS_WORKING):
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400238 cond.wait()
239 cond.release()
Sapan Bhatia51f48932014-08-25 04:17:12 -0400240
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400241 if (self.step_status[S] is not STEP_STATUS_OK):
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400242 self.failed_steps.append(sync_step)
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400243 my_status = STEP_STATUS_KO
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400244 else:
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400245 sync_step = step(driver=self.driver,error_map=error_mapper)
246 sync_step.__name__ = step.__name__
247 sync_step.dependencies = []
248 try:
249 mlist = sync_step.provides
250
251 for m in mlist:
252 sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
253 except KeyError:
254 pass
255 sync_step.debug_mode = debug_mode
256
257 should_run = False
258 try:
259 # Various checks that decide whether
260 # this step runs or not
261 self.check_class_dependency(sync_step, self.failed_steps) # dont run Slices if Sites failed
262 self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour
263 should_run = True
264 except StepNotReady:
265 logging.info('Step not ready: %s'%sync_step.__name__)
266 self.failed_steps.append(sync_step)
267 my_status = STEP_STATUS_KO
268 except Exception,e:
269 logging.error('%r',e)
270 logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion))
271 self.failed_steps.append(sync_step)
272 my_status = STEP_STATUS_KO
273
274 if (should_run):
275 try:
276 duration=time.time() - start_time
277
278 logger.info('Executing step %s' % sync_step.__name__)
279
280 failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion)
281
282 self.check_duration(sync_step, duration)
283
284 if failed_objects:
285 self.failed_step_objects.update(failed_objects)
286
287 my_status = STEP_STATUS_OK
288 self.update_run_time(sync_step,deletion)
289 except Exception,e:
290 logging.error('Model step failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
291 logger.log_exc(e)
292 self.failed_steps.append(S)
293 my_status = STEP_STATUS_KO
294 else:
295 my_status = STEP_STATUS_OK
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400296
297 try:
298 my_cond = self.step_conditions[S]
299 my_cond.acquire()
300 self.step_status[S]=my_status
301 my_cond.notify_all()
302 my_cond.release()
Sapan Bhatia6ff37c42014-09-03 05:28:42 -0400303 except KeyError,e:
304 logging.info('Step %r is a leaf')
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400305 pass
Sapan Bhatia51f48932014-08-25 04:17:12 -0400306
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400307 def run(self):
308 if not self.driver.enabled:
309 return
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400310
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400311 if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
312 return
313
314 while True:
315 try:
316 error_map_file = getattr(Config(), "error_map_path", "/opt/planetstack/error_map.txt")
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400317 self.error_mapper = ErrorMapper(error_map_file)
318
319 # Set of whole steps that failed
320 self.failed_steps = []
321
322 # Set of individual objects within steps that failed
323 self.failed_step_objects = set()
324
325 # Set up conditions and step status
326 # This is needed for steps to run in parallel
327 # while obeying dependencies.
328
329 providers = set()
330 for v in self.dependency_graph.values():
331 if (v):
332 providers.update(v)
333 self.step_conditions = {}
334 self.step_status = {}
335 for p in list(providers):
336 self.step_conditions[p] = threading.Condition()
337 self.step_status[p] = STEP_STATUS_IDLE
338
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400339
340 logger.info('Waiting for event')
341 tBeforeWait = time.time()
Sapan Bhatia13d89152014-07-23 10:35:33 -0400342 self.wait_for_event(timeout=30)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400343 logger.info('Observer woke up')
344
345 # Two passes. One for sync, the other for deletion.
Sapan Bhatia0f727b82014-08-18 02:44:20 -0400346 for deletion in [False,True]:
Sapan Bhatia51f48932014-08-25 04:17:12 -0400347 threads = []
Sapan Bhatiabab33762014-07-22 01:21:36 -0400348 logger.info('Deletion=%r...'%deletion)
Sapan Bhatia4a1335c2014-09-03 01:06:17 -0400349 schedule = self.sync_schedule if not deletion else self.delete_schedule
350
351 thread = threading.Thread(target=self.sync, args=(schedule.start_conditions, schedule.ordered_steps,deletion, schedule.signal_sem))
352
Sapan Bhatia51f48932014-08-25 04:17:12 -0400353 logger.info('Deletion=%r...'%deletion)
354 threads.append(thread)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400355
Sapan Bhatia51f48932014-08-25 04:17:12 -0400356 # Start threads
357 for t in threads:
358 t.start()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400359
Sapan Bhatia51f48932014-08-25 04:17:12 -0400360 # Wait for all threads to finish before continuing with the run loop
361 for t in threads:
362 t.join()
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400363
Sapan Bhatia26d40bc2014-05-12 15:28:02 -0400364 self.save_run_times()
365 except Exception, e:
366 logging.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e)
367 logger.log_exc("Exception in observer run loop")
368 traceback.print_exc()