blob: 6b77236405f4c0d7167f64f5990c3fb87ce703b6 [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
9
10from datetime import datetime
11from collections import defaultdict
12from core.models import *
13from django.db.models import F, Q
Tony Mack387a73f2013-09-18 07:59:14 -040014#from openstack.manager import OpenStackManager
15from openstack.driver import OpenStackDriver
Sapan Bhatia24836f12013-08-27 10:16:05 -040016from util.logger import Logger, logging, logger
17#from timeout import timeout
Sapan Bhatia757e0b62013-09-02 16:55:00 -040018from planetstack.config import Config
Sapan Bhatia04c94ad2013-09-02 18:00:28 -040019from observer.steps import *
Scott Baker45fb7a12013-12-31 00:56:19 -080020from syncstep import SyncStep
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040021from toposort import toposort
Sapan Bhatia24836f12013-08-27 10:16:05 -040022
Sapan Bhatia13c7f112013-09-02 14:19:35 -040023debug_mode = False
Sapan Bhatia24836f12013-08-27 10:16:05 -040024
Andy Bavier04111b72013-10-22 16:47:10 -040025logger = Logger(level=logging.INFO)
Sapan Bhatia24836f12013-08-27 10:16:05 -040026
Sapan Bhatia13c7f112013-09-02 14:19:35 -040027class StepNotReady(Exception):
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040028 pass
Sapan Bhatia24836f12013-08-27 10:16:05 -040029
Scott Baker7771f412014-01-02 16:36:41 -080030class NoOpDriver:
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040031 def __init__(self):
32 self.enabled = True
Scott Baker7771f412014-01-02 16:36:41 -080033
Sapan Bhatia24836f12013-08-27 10:16:05 -040034class PlanetStackObserver:
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040035 #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivileges,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector]
36 sync_steps = []
Sapan Bhatia24836f12013-08-27 10:16:05 -040037
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040038 def __init__(self):
39 # The Condition object that gets signalled by Feefie events
40 self.step_lookup = {}
41 self.load_sync_step_modules()
42 self.load_sync_steps()
43 self.event_cond = threading.Condition()
Scott Baker7771f412014-01-02 16:36:41 -080044
45
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040046 self.driver_kind = getattr(Config(), "observer_driver", "openstack")
47 if self.driver_kind=="openstack":
48 self.driver = OpenStackDriver()
49 else:
50 self.driver = NoOpDriver()
Sapan Bhatia24836f12013-08-27 10:16:05 -040051
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040052 def wait_for_event(self, timeout):
53 self.event_cond.acquire()
54 self.event_cond.wait(timeout)
55 self.event_cond.release()
Scott Baker45fb7a12013-12-31 00:56:19 -080056
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040057 def wake_up(self):
58 logger.info('Wake up routine called. Event cond %r'%self.event_cond)
59 self.event_cond.acquire()
60 self.event_cond.notify()
61 self.event_cond.release()
Sapan Bhatia24836f12013-08-27 10:16:05 -040062
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040063 def load_sync_step_modules(self, step_dir=None):
64 if step_dir is None:
65 if hasattr(Config(), "observer_steps_dir"):
66 step_dir = Config().observer_steps_dir
67 else:
68 step_dir = "/opt/planetstack/observer/steps"
Scott Baker45fb7a12013-12-31 00:56:19 -080069
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040070 for fn in os.listdir(step_dir):
71 pathname = os.path.join(step_dir,fn)
72 if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"):
73 module = imp.load_source(fn[:-3],pathname)
74 for classname in dir(module):
75 c = getattr(module, classname, None)
Scott Baker45fb7a12013-12-31 00:56:19 -080076
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040077 # make sure 'c' is a descendent of SyncStep and has a
78 # provides field (this eliminates the abstract base classes
79 # since they don't have a provides)
Scott Baker45fb7a12013-12-31 00:56:19 -080080
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040081 if inspect.isclass(c) and issubclass(c, SyncStep) and hasattr(c,"provides") and (c not in self.sync_steps):
82 self.sync_steps.append(c)
83 logger.info('loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps]))
84 # print 'loaded sync steps: %s' % ",".join([x.__name__ for x in self.sync_steps])
Scott Baker45fb7a12013-12-31 00:56:19 -080085
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040086 def load_sync_steps(self):
87 dep_path = Config().observer_dependency_graph
88 logger.info('Loading model dependency graph from %s' % dep_path)
89 try:
90 # This contains dependencies between records, not sync steps
91 self.model_dependency_graph = json.loads(open(dep_path).read())
92 except Exception,e:
93 raise e
Sapan Bhatia24836f12013-08-27 10:16:05 -040094
Sapan Bhatia45cbbc32014-03-11 17:48:30 -040095 try:
96 backend_path = Config().observer_pl_dependency_graph
97 logger.info('Loading backend dependency graph from %s' % backend_path)
98 # This contains dependencies between backend records
99 self.backend_dependency_graph = json.loads(open(backend_path).read())
100 except Exception,e:
101 logger.info('Backend dependency graph not loaded')
102 # We can work without a backend graph
103 self.backend_dependency_graph = {}
Sapan Bhatia24836f12013-08-27 10:16:05 -0400104
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400105 provides_dict = {}
106 for s in self.sync_steps:
107 self.step_lookup[s.__name__] = s
108 for m in s.provides:
109 try:
110 provides_dict[m.__name__].append(s.__name__)
111 except KeyError:
112 provides_dict[m.__name__]=[s.__name__]
Sapan Bhatia04c94ad2013-09-02 18:00:28 -0400113
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400114
115 step_graph = {}
116 for k,v in self.model_dependency_graph.iteritems():
117 try:
118 for source in provides_dict[k]:
119 for m in v:
120 try:
121 for dest in provides_dict[m]:
122 # no deps, pass
123 try:
124 if (dest not in step_graph[source]):
125 step_graph[source].append(dest)
126 except:
127 step_graph[source]=[dest]
128 except KeyError:
129 pass
130
131 except KeyError:
132 pass
133 # no dependencies, pass
134
135 #import pdb
136 #pdb.set_trace()
137 if (self.backend_dependency_graph):
138 backend_dict = {}
139 for s in self.sync_steps:
140 for m in s.serves:
141 backend_dict[m]=s.__name__
142
143 for k,v in backend_dependency_graph.iteritems():
144 try:
145 source = backend_dict[k]
146 for m in v:
147 try:
148 dest = backend_dict[m]
149 except KeyError:
150 # no deps, pass
151 pass
152 step_graph[source]=dest
153
154 except KeyError:
155 pass
156 # no dependencies, pass
Sapan Bhatia24836f12013-08-27 10:16:05 -0400157
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400158 dependency_graph = step_graph
Sapan Bhatia24836f12013-08-27 10:16:05 -0400159
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400160 self.ordered_steps = toposort(dependency_graph, map(lambda s:s.__name__,self.sync_steps))
161 print "Order of steps=",self.ordered_steps
162 self.load_run_times()
163
Sapan Bhatia24836f12013-08-27 10:16:05 -0400164
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400165 def check_duration(self, step, duration):
166 try:
167 if (duration > step.deadline):
168 logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration))
169 except AttributeError:
170 # S doesn't have a deadline
171 pass
Sapan Bhatia24836f12013-08-27 10:16:05 -0400172
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400173 def update_run_time(self, step):
174 self.last_run_times[step.__name__]=time.time()
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400175
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400176 def check_schedule(self, step):
177 time_since_last_run = time.time() - self.last_run_times.get(step.__name__, 0)
178 try:
179 if (time_since_last_run < step.requested_interval):
180 raise StepNotReady
181 except AttributeError:
182 logger.info('Step %s does not have requested_interval set'%step.__name__)
183 raise StepNotReady
184
185 def load_run_times(self):
186 try:
187 jrun_times = open('/tmp/observer_run_times').read()
188 self.last_run_times = json.loads(jrun_times)
189 except:
190 self.last_run_times={}
191 for e in self.ordered_steps:
192 self.last_run_times[e]=0
Sapan Bhatia36938ca2013-09-02 14:35:24 -0400193
194
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400195 def save_run_times(self):
196 run_times = json.dumps(self.last_run_times)
197 open('/tmp/observer_run_times','w').write(run_times)
Sapan Bhatia36938ca2013-09-02 14:35:24 -0400198
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400199 def check_class_dependency(self, step, failed_steps):
200 step.dependenices = []
201 for obj in step.provides:
202 step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, []))
203 for failed_step in failed_steps:
204 if (failed_step in step.dependencies):
205 raise StepNotReady
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400206
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400207 def run(self):
208 if not self.driver.enabled:
209 return
210 if (self.driver_kind=="openstack") and (not self.driver.has_openstack):
211 return
Scott Baker7771f412014-01-02 16:36:41 -0800212
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400213 while True:
214 try:
215 logger.info('Waiting for event')
216 tBeforeWait = time.time()
217 self.wait_for_event(timeout=30)
218 logger.info('Observer woke up')
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400219
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400220 # Set of whole steps that failed
221 failed_steps = []
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400222
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400223 # Set of individual objects within steps that failed
224 failed_step_objects = set()
Sapan Bhatia24836f12013-08-27 10:16:05 -0400225
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400226 for S in self.ordered_steps:
227 step = self.step_lookup[S]
228 start_time=time.time()
229
230 sync_step = step(driver=self.driver)
231 sync_step.__name__ = step.__name__
232 sync_step.dependencies = []
233 try:
234 mlist = sync_step.provides
235
236 for m in mlist:
237 sync_step.dependencies.extend(self.model_dependency_graph[m.__name__])
238 except KeyError:
239 pass
240 sync_step.debug_mode = debug_mode
Sapan Bhatia24836f12013-08-27 10:16:05 -0400241
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400242 should_run = False
243 try:
244 # Various checks that decide whether
245 # this step runs or not
246 self.check_class_dependency(sync_step, failed_steps) # dont run Slices if Sites failed
247 self.check_schedule(sync_step) # dont run sync_network_routes if time since last run < 1 hour
248 should_run = True
249 except StepNotReady:
250 logging.info('Step not ready: %s'%sync_step.__name__)
251 failed_steps.append(sync_step)
252 except:
253 failed_steps.append(sync_step)
Sapan Bhatia24836f12013-08-27 10:16:05 -0400254
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400255 if (should_run):
256 try:
257 duration=time.time() - start_time
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400258
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400259 logger.info('Executing step %s' % sync_step.__name__)
Scott Baker45fb7a12013-12-31 00:56:19 -0800260
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400261 # ********* This is the actual sync step
262 #import pdb
263 #pdb.set_trace()
264 failed_objects = sync_step(failed=list(failed_step_objects))
Sapan Bhatia13c7f112013-09-02 14:19:35 -0400265
266
Sapan Bhatia45cbbc32014-03-11 17:48:30 -0400267 self.check_duration(sync_step, duration)
268 if failed_objects:
269 failed_step_objects.update(failed_objects)
270 self.update_run_time(sync_step)
271 except:
272 failed_steps.append(S)
273 self.save_run_times()
274 except:
275 logger.log_exc("Exception in observer run loop")
276 traceback.print_exc()