7 from datetime import datetime
8 from collections import defaultdict
9 from core.models import *
10 from django.db.models import F, Q
11 from openstack.manager import OpenStackManager
12 from util.logger import Logger, logging, logger
13 #from timeout import timeout
14 from planetstack.config import Config
15 from observer.steps import *
19 logger = Logger(logfile='observer.log', level=logging.INFO)
21 class StepNotReady(Exception):
24 def toposort(g, steps):
36 if not reverse.has_key(k):
40 for k,v in reverse.iteritems():
59 class PlanetStackObserver:
60 sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivileges,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps]
63 # The Condition object that gets signalled by Feefie events
64 self.load_sync_steps()
65 self.event_cond = threading.Condition()
67 def wait_for_event(self, timeout):
68 self.event_cond.acquire()
69 self.event_cond.wait(timeout)
70 self.event_cond.release()
73 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
74 self.event_cond.acquire()
75 self.event_cond.notify()
76 self.event_cond.release()
78 def load_sync_steps(self):
79 dep_path = Config().observer_dependency_path
81 # This contains dependencies between records, not sync steps
82 self.model_dependency_graph = json.loads(open(dep_path).read())
86 backend_path = Config().observer_backend_dependency_path
88 # This contains dependencies between backend records
89 self.backend_dependency_graph = json.loads(open(backend_path).read())
91 # We can work without a backend graph
92 self.backend_dependency_graph = {}
95 for s in self.sync_steps:
98 provides_dict[m.__name__].append(s.__name__)
100 provides_dict[m.__name__]=[s.__name__]
104 for k,v in self.model_dependency_graph.iteritems():
106 for source in provides_dict[k]:
109 for dest in provides_dict[m]:
112 step_graph[source].append(dest)
114 step_graph[source]=[dest]
120 # no dependencies, pass
124 if (self.backend_dependency_graph):
128 backend_dict[m]=s.__name__
130 for k,v in backend_dependency_graph.iteritems():
132 source = backend_dict[k]
135 dest = backend_dict[m]
139 step_graph[source]=dest
143 # no dependencies, pass
145 dependency_graph = step_graph
147 self.ordered_steps = toposort(dependency_graph, self.sync_steps)
148 print "Order of steps=",self.ordered_steps
149 self.load_run_times()
152 def check_duration(self):
154 if (duration > S.deadline):
155 logger.info('Sync step %s missed deadline, took %.2f seconds'%(S.name,duration))
156 except AttributeError:
157 # S doesn't have a deadline
160 def update_run_time(self, step):
161 self.last_run_times[step.name]=time.time()
163 def check_schedule(self, step):
164 time_since_last_run = time.time() - self.last_run_times[step.name]
166 if (time_since_last_run < step.requested_interval):
168 except AttributeError:
169 logger.info('Step %s does not have requested_interval set'%step.name)
172 def load_run_times(self):
174 jrun_times = open('/tmp/observer_run_times').read()
175 self.last_run_times = json.loads(jrun_times)
177 self.last_run_times={}
178 for e in self.ordered_steps:
179 self.last_run_times[e.name]=0
183 def save_run_times(self):
184 run_times = json.dumps(self.last_run_times)
185 open('/tmp/observer_run_times','w').write(run_times)
187 def check_class_dependency(self, step, failed_steps):
188 for failed_step in failed_steps:
189 if (failed_step in self.dependency_graph[step.name]):
193 if not self.manager.enabled or not self.manager.has_openstack:
198 logger.info('Waiting for event')
199 tBeforeWait = time.time()
200 self.wait_for_event(timeout=300)
201 logger.info('Observer woke up')
203 # Set of whole steps that failed
206 # Set of individual objects within steps that failed
207 failed_step_objects = []
209 for S in self.ordered_steps:
210 start_time=time.time()
213 sync_step.dependencies = self.dependencies[sync_step.name]
214 sync_step.debug_mode = debug_mode
218 # Various checks that decide whether
219 # this step runs or not
220 self.check_class_dependency(sync_step, failed_steps) # dont run Slices if Sites failed
221 self.check_schedule(sync_step) # dont run sync_network_routes if time since last run < 1 hour
224 logging.info('Step not ready: %s'%sync_step.name)
225 failed_steps.add(sync_step)
227 failed_steps.add(sync_step)
231 duration=time.time() - start_time
233 # ********* This is the actual sync step
234 failed_objects = sync_step(failed=failed_step_objects)
237 check_deadline(sync_step, duration)
238 failed_step_objects.extend(failed_objects)
239 self.update_run_time(sync_step)
242 self.save_run_times()
244 logger.log_exc("Exception in observer run loop")
245 traceback.print_exc()