blob: dcfea7db80316457798b540fd0991aef9534f14c [file] [log] [blame]
Sapan Bhatia26d40bc2014-05-12 15:28:02 -04001import os
2import base64
3from datetime import datetime
4from planetstack.config import Config
5from util.logger import Logger, logging
6from observer.steps import *
7
8logger = Logger(level=logging.INFO)
9
10class FailedDependency(Exception):
11 pass
12
13class SyncStep:
14 """ A PlanetStack Sync step.
15
16 Attributes:
17 psmodel Model name the step synchronizes
18 dependencies list of names of models that must be synchronized first if the current model depends on them
19 """
20 slow=False
21 def get_prop(prop):
22 try:
23 sync_config_dir = Config().sync_config_dir
24 except:
25 sync_config_dir = '/etc/planetstack/sync'
26 prop_config_path = '/'.join(sync_config_dir,self.name,prop)
27 return open(prop_config_path).read().rstrip()
28
29 def __init__(self, **args):
30 """Initialize a sync step
31 Keyword arguments:
32 name -- Name of the step
33 provides -- PlanetStack models sync'd by this step
34 """
35 dependencies = []
36 self.driver = args.get('driver')
37 self.error_map = args.get('error_map')
38
39 try:
40 self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
41 except:
42 self.soft_deadline = 5 # 5 seconds
43
44 return
45
46 def fetch_pending(self, deletion=False):
Sapan Bhatia3e328352014-07-23 10:03:50 -040047 # This is the most common implementation of fetch_pending
48 # Steps should override it if they have their own logic
49 # for figuring out what objects are outstanding.
50 main_obj = self.provides[0]
51 if (not deleted):
52 objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None))
53 else:
54 objs = main_obj.deleted_objects.all()
55
56 return objs
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040057 #return Sliver.objects.filter(ip=None)
58
59 def check_dependencies(self, obj, failed):
60 for dep in self.dependencies:
Sapan Bhatia3e328352014-07-23 10:03:50 -040061 peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
62 peer_object = getattr(obj, peer_name)
Sapan Bhatia26d40bc2014-05-12 15:28:02 -040063 if (peer_object.pk==failed.pk):
64 raise FailedDependency
65
66 def call(self, failed=[], deletion=False):
67 pending = self.fetch_pending(deletion)
68 for o in pending:
69 try:
70 for f in failed:
71 self.check_dependencies(o,f) # Raises exception if failed
72 if (deletion):
73 self.delete_record(o)
74 o.delete(purge=True)
75 else:
76 self.sync_record(o)
77 o.enacted = datetime.now() # Is this the same timezone? XXX
78 o.backend_status = "OK"
79 o.save(update_fields=['enacted'])
80 except Exception,e:
81 try:
82 o.backend_status = self.error_map.map(str(e))
83 except:
84 o.backend_status = str(e)
85
86 o.save(update_fields=['backend_status'])
87
88 logger.log_exc("sync step failed!")
89 failed.append(o)
90
91 return failed
92
93 def __call__(self, **args):
94 return self.call(**args)