Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 1 | import os |
| 2 | import imp |
| 3 | import inspect |
| 4 | import time |
| 5 | import traceback |
| 6 | import commands |
| 7 | import threading |
| 8 | import json |
| 9 | |
| 10 | from datetime import datetime |
| 11 | from collections import defaultdict |
| 12 | from core.models import * |
| 13 | from django.db.models import F, Q |
| 14 | #from openstack.manager import OpenStackManager |
| 15 | from openstack.driver import OpenStackDriver |
| 16 | from util.logger import Logger, logging, logger |
| 17 | #from timeout import timeout |
| 18 | from planetstack.config import Config |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 19 | from observer.steps import * |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 20 | from syncstep import SyncStep |
| 21 | from toposort import toposort |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 22 | from observer.error_mapper import * |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 23 | |
| 24 | debug_mode = False |
| 25 | |
| 26 | logger = Logger(level=logging.INFO) |
| 27 | |
| 28 | class StepNotReady(Exception): |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 29 | pass |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 30 | |
| 31 | class NoOpDriver: |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 32 | def __init__(self): |
| 33 | self.enabled = True |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 34 | |
| 35 | class PlanetStackObserver: |
| 36 | #sync_steps = [SyncNetworks,SyncNetworkSlivers,SyncSites,SyncSitePrivileges,SyncSlices,SyncSliceMemberships,SyncSlivers,SyncSliverIps,SyncExternalRoutes,SyncUsers,SyncRoles,SyncNodes,SyncImages,GarbageCollector] |
| 37 | sync_steps = [] |
| 38 | |
| 39 | def __init__(self): |
| 40 | # The Condition object that gets signalled by Feefie events |
| 41 | self.step_lookup = {} |
| 42 | self.load_sync_step_modules() |
| 43 | self.load_sync_steps() |
| 44 | self.event_cond = threading.Condition() |
| 45 | |
| 46 | self.driver_kind = getattr(Config(), "observer_driver", "openstack") |
| 47 | if self.driver_kind=="openstack": |
| 48 | self.driver = OpenStackDriver() |
| 49 | else: |
| 50 | self.driver = NoOpDriver() |
| 51 | |
Sapan Bhatia | 97e18bd | 2014-09-03 00:38:26 -0400 | [diff] [blame^] | 52 | def wait_for_event(self, timeout, cond=self.event_cond): |
| 53 | cond.acquire() |
| 54 | cond.wait(timeout) |
| 55 | cond.release() |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 56 | |
Sapan Bhatia | 97e18bd | 2014-09-03 00:38:26 -0400 | [diff] [blame^] | 57 | def wake_up(self, cond=self.event_cond): |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 58 | logger.info('Wake up routine called. Event cond %r'%self.event_cond) |
Sapan Bhatia | 97e18bd | 2014-09-03 00:38:26 -0400 | [diff] [blame^] | 59 | cond.acquire() |
| 60 | cond.notify() |
| 61 | cond.release() |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 62 | |
| 63 | 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" |
| 69 | |
| 70 | 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) |
| 76 | |
| 77 | # 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) |
| 80 | |
| 81 | 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]) |
| 85 | |
| 86 | 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 |
| 94 | |
| 95 | 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: |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 101 | logger.info('Backend dependency graph not loaded') |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 102 | # We can work without a backend graph |
| 103 | self.backend_dependency_graph = {} |
| 104 | |
| 105 | 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__] |
| 113 | |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 114 | step_graph = {} |
| 115 | for k,v in self.model_dependency_graph.iteritems(): |
| 116 | try: |
| 117 | for source in provides_dict[k]: |
| 118 | for m in v: |
| 119 | try: |
| 120 | for dest in provides_dict[m]: |
| 121 | # no deps, pass |
| 122 | try: |
| 123 | if (dest not in step_graph[source]): |
| 124 | step_graph[source].append(dest) |
| 125 | except: |
| 126 | step_graph[source]=[dest] |
| 127 | except KeyError: |
| 128 | pass |
| 129 | |
| 130 | except KeyError: |
| 131 | pass |
| 132 | # no dependencies, pass |
| 133 | |
| 134 | #import pdb |
| 135 | #pdb.set_trace() |
| 136 | if (self.backend_dependency_graph): |
| 137 | backend_dict = {} |
| 138 | for s in self.sync_steps: |
| 139 | for m in s.serves: |
| 140 | backend_dict[m]=s.__name__ |
| 141 | |
| 142 | for k,v in backend_dependency_graph.iteritems(): |
| 143 | try: |
| 144 | source = backend_dict[k] |
| 145 | for m in v: |
| 146 | try: |
| 147 | dest = backend_dict[m] |
| 148 | except KeyError: |
| 149 | # no deps, pass |
| 150 | pass |
| 151 | step_graph[source]=dest |
| 152 | |
| 153 | except KeyError: |
| 154 | pass |
| 155 | # no dependencies, pass |
| 156 | |
| 157 | dependency_graph = step_graph |
| 158 | |
| 159 | self.ordered_steps = toposort(dependency_graph, map(lambda s:s.__name__,self.sync_steps)) |
| 160 | print "Order of steps=",self.ordered_steps |
| 161 | self.load_run_times() |
| 162 | |
| 163 | |
| 164 | def check_duration(self, step, duration): |
| 165 | try: |
| 166 | if (duration > step.deadline): |
| 167 | logger.info('Sync step %s missed deadline, took %.2f seconds'%(step.name,duration)) |
| 168 | except AttributeError: |
| 169 | # S doesn't have a deadline |
| 170 | pass |
| 171 | |
| 172 | def update_run_time(self, step, deletion): |
| 173 | if (not deletion): |
| 174 | self.last_run_times[step.__name__]=time.time() |
| 175 | else: |
| 176 | self.last_deletion_run_times[step.__name__]=time.time() |
| 177 | |
| 178 | |
| 179 | def check_schedule(self, step, deletion): |
| 180 | last_run_times = self.last_run_times if not deletion else self.last_deletion_run_times |
| 181 | |
| 182 | time_since_last_run = time.time() - last_run_times.get(step.__name__, 0) |
| 183 | try: |
| 184 | if (time_since_last_run < step.requested_interval): |
| 185 | raise StepNotReady |
| 186 | except AttributeError: |
| 187 | logger.info('Step %s does not have requested_interval set'%step.__name__) |
| 188 | raise StepNotReady |
| 189 | |
| 190 | def load_run_times(self): |
| 191 | try: |
| 192 | jrun_times = open('/tmp/observer_run_times').read() |
| 193 | self.last_run_times = json.loads(jrun_times) |
| 194 | except: |
| 195 | self.last_run_times={} |
| 196 | for e in self.ordered_steps: |
| 197 | self.last_run_times[e]=0 |
| 198 | try: |
| 199 | jrun_times = open('/tmp/observer_deletion_run_times').read() |
| 200 | self.last_deletion_run_times = json.loads(jrun_times) |
| 201 | except: |
| 202 | self.last_deletion_run_times={} |
| 203 | for e in self.ordered_steps: |
| 204 | self.last_deletion_run_times[e]=0 |
| 205 | |
| 206 | |
| 207 | |
| 208 | def save_run_times(self): |
| 209 | run_times = json.dumps(self.last_run_times) |
| 210 | open('/tmp/observer_run_times','w').write(run_times) |
| 211 | |
| 212 | deletion_run_times = json.dumps(self.last_deletion_run_times) |
| 213 | open('/tmp/observer_deletion_run_times','w').write(deletion_run_times) |
| 214 | |
| 215 | def check_class_dependency(self, step, failed_steps): |
| 216 | step.dependenices = [] |
| 217 | for obj in step.provides: |
| 218 | step.dependenices.extend(self.model_dependency_graph.get(obj.__name__, [])) |
| 219 | for failed_step in failed_steps: |
| 220 | if (failed_step in step.dependencies): |
| 221 | raise StepNotReady |
| 222 | |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 223 | def sync(self, ordered_steps, error_mapper, deletion): |
| 224 | # Set of whole steps that failed |
| 225 | failed_steps = [] |
| 226 | |
| 227 | # Set of individual objects within steps that failed |
| 228 | failed_step_objects = set() |
| 229 | |
| 230 | for S in ordered_steps: |
| 231 | step = self.step_lookup[S] |
| 232 | start_time=time.time() |
| 233 | |
| 234 | sync_step = step(driver=self.driver,error_map=error_mapper) |
| 235 | sync_step.__name__ = step.__name__ |
| 236 | sync_step.dependencies = [] |
| 237 | try: |
| 238 | mlist = sync_step.provides |
| 239 | |
| 240 | for m in mlist: |
| 241 | sync_step.dependencies.extend(self.model_dependency_graph[m.__name__]) |
| 242 | except KeyError: |
| 243 | pass |
| 244 | sync_step.debug_mode = debug_mode |
| 245 | |
| 246 | should_run = False |
| 247 | try: |
| 248 | # Various checks that decide whether |
| 249 | # this step runs or not |
| 250 | self.check_class_dependency(sync_step, failed_steps) # dont run Slices if Sites failed |
| 251 | self.check_schedule(sync_step, deletion) # dont run sync_network_routes if time since last run < 1 hour |
| 252 | should_run = True |
| 253 | except StepNotReady: |
| 254 | logging.info('Step not ready: %s'%sync_step.__name__) |
| 255 | failed_steps.append(sync_step) |
| 256 | except Exception,e: |
| 257 | logging.error('%r',e) |
| 258 | logger.log_exc("sync step failed: %r. Deletion: %r"%(sync_step,deletion)) |
| 259 | failed_steps.append(sync_step) |
| 260 | |
| 261 | if (should_run): |
| 262 | try: |
| 263 | duration=time.time() - start_time |
| 264 | |
| 265 | logger.info('Executing step %s' % sync_step.__name__) |
| 266 | |
| 267 | # ********* This is the actual sync step |
| 268 | #import pdb |
| 269 | #pdb.set_trace() |
| 270 | failed_objects = sync_step(failed=list(failed_step_objects), deletion=deletion) |
| 271 | |
| 272 | |
| 273 | self.check_duration(sync_step, duration) |
| 274 | if failed_objects: |
| 275 | failed_step_objects.update(failed_objects) |
| 276 | |
| 277 | self.update_run_time(sync_step,deletion) |
| 278 | except Exception,e: |
| 279 | logging.error('Model step failed. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e) |
| 280 | logger.log_exc(e) |
| 281 | failed_steps.append(S) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 282 | def run(self): |
| 283 | if not self.driver.enabled: |
| 284 | return |
| 285 | if (self.driver_kind=="openstack") and (not self.driver.has_openstack): |
| 286 | return |
| 287 | |
| 288 | while True: |
| 289 | try: |
| 290 | error_map_file = getattr(Config(), "error_map_path", "/opt/planetstack/error_map.txt") |
| 291 | error_mapper = ErrorMapper(error_map_file) |
| 292 | |
| 293 | logger.info('Waiting for event') |
| 294 | tBeforeWait = time.time() |
Sapan Bhatia | 13d8915 | 2014-07-23 10:35:33 -0400 | [diff] [blame] | 295 | self.wait_for_event(timeout=30) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 296 | logger.info('Observer woke up') |
| 297 | |
| 298 | # Two passes. One for sync, the other for deletion. |
Sapan Bhatia | 0f727b8 | 2014-08-18 02:44:20 -0400 | [diff] [blame] | 299 | for deletion in [False,True]: |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 300 | threads = [] |
Sapan Bhatia | bab3376 | 2014-07-22 01:21:36 -0400 | [diff] [blame] | 301 | logger.info('Deletion=%r...'%deletion) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 302 | ordered_steps = self.ordered_steps if not deletion else reversed(self.ordered_steps) |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 303 | thread = threading.Thread(target=self.sync, args=(ordered_steps,error_mapper,deletion)) |
| 304 | logger.info('Deletion=%r...'%deletion) |
| 305 | threads.append(thread) |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 306 | |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 307 | # Start threads |
| 308 | for t in threads: |
| 309 | t.start() |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 310 | |
Sapan Bhatia | 51f4893 | 2014-08-25 04:17:12 -0400 | [diff] [blame] | 311 | # Wait for all threads to finish before continuing with the run loop |
| 312 | for t in threads: |
| 313 | t.join() |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 314 | |
Sapan Bhatia | 26d40bc | 2014-05-12 15:28:02 -0400 | [diff] [blame] | 315 | self.save_run_times() |
| 316 | except Exception, e: |
| 317 | logging.error('Core error. This seems like a misconfiguration or bug: %r. This error will not be relayed to the user!',e) |
| 318 | logger.log_exc("Exception in observer run loop") |
| 319 | traceback.print_exc() |