blob: fb06bddbdd986679a503f6a9b7d4d665397e9310 [file] [log] [blame]
Sapan Bhatia24836f12013-08-27 10:16:05 -04001import os
2import base64
Tony Mack4fa85fb2013-09-25 14:39:57 -04003from datetime import datetime
Scott Baker76a840e2015-02-11 21:38:09 -08004from xos.config import Config
Andy Baviere7abb622013-10-18 15:11:56 -04005from util.logger import Logger, logging
Sapan Bhatiaeba08432014-04-28 23:58:36 -04006from observer.steps import *
Sapan Bhatiad9468eb2014-08-20 03:03:12 -04007from django.db.models import F, Q
Sapan Bhatia709bebd2015-02-08 06:35:36 +00008from core.models import *
Sapan Bhatia47006112015-01-29 20:55:40 +00009import json
10import time
11import pdb
Andy Baviere7abb622013-10-18 15:11:56 -040012
Andy Bavier04111b72013-10-22 16:47:10 -040013logger = Logger(level=logging.INFO)
Sapan Bhatia24836f12013-08-27 10:16:05 -040014
Sapan Bhatia2192fec2015-02-08 06:36:32 +000015def f7(seq):
16 seen = set()
17 seen_add = seen.add
18 return [ x for x in seq if not (x in seen or seen_add(x))]
19
20def elim_dups(backend_str):
21 strs = backend_str.split(' // ')
22 strs2 = f7(strs)
23 return ' // '.join(strs2)
Sapan Bhatiae6376de2015-05-13 15:51:03 +020024
Sapan Bhatia709bebd2015-02-08 06:35:36 +000025def deepgetattr(obj, attr):
26 return reduce(getattr, attr.split('.'), obj)
27
Sapan Bhatiae6376de2015-05-13 15:51:03 +020028
29class InnocuousException(Exception):
30 pass
31
Sapan Bhatia13c7f112013-09-02 14:19:35 -040032class FailedDependency(Exception):
Tony Mackce79de02013-09-24 10:12:33 -040033 pass
Sapan Bhatia13c7f112013-09-02 14:19:35 -040034
Tony Mackb469d242015-01-03 19:37:39 -050035class SyncStep(object):
Sapan Bhatiae6376de2015-05-13 15:51:03 +020036 """ An XOS Sync step.
Sapan Bhatia24836f12013-08-27 10:16:05 -040037
Tony Mackce79de02013-09-24 10:12:33 -040038 Attributes:
Sapan Bhatiae6376de2015-05-13 15:51:03 +020039 psmodel Model name the step synchronizes
Tony Mackce79de02013-09-24 10:12:33 -040040 dependencies list of names of models that must be synchronized first if the current model depends on them
Sapan Bhatiae6376de2015-05-13 15:51:03 +020041 """
Tony Mackce79de02013-09-24 10:12:33 -040042 slow=False
Tony Mackfbdae1b2015-02-24 14:16:43 -050043 def get_prop(self, prop):
Tony Mackce79de02013-09-24 10:12:33 -040044 try:
45 sync_config_dir = Config().sync_config_dir
46 except:
Scott Bakerb8059c92015-02-19 22:25:49 -080047 sync_config_dir = '/etc/xos/sync'
Tony Mackce79de02013-09-24 10:12:33 -040048 prop_config_path = '/'.join(sync_config_dir,self.name,prop)
49 return open(prop_config_path).read().rstrip()
Sapan Bhatia24836f12013-08-27 10:16:05 -040050
Tony Mackce79de02013-09-24 10:12:33 -040051 def __init__(self, **args):
52 """Initialize a sync step
53 Keyword arguments:
54 name -- Name of the step
Scott Baker286a78f2015-02-18 16:13:48 -080055 provides -- XOS models sync'd by this step
Tony Mackce79de02013-09-24 10:12:33 -040056 """
57 dependencies = []
Tony Mack387a73f2013-09-18 07:59:14 -040058 self.driver = args.get('driver')
Sapan Bhatiaeba08432014-04-28 23:58:36 -040059 self.error_map = args.get('error_map')
60
Tony Mackce79de02013-09-24 10:12:33 -040061 try:
62 self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
63 except:
64 self.soft_deadline = 5 # 5 seconds
Sapan Bhatia24836f12013-08-27 10:16:05 -040065
Tony Mackce79de02013-09-24 10:12:33 -040066 return
Sapan Bhatia24836f12013-08-27 10:16:05 -040067
Sapan Bhatiae17bc5b2014-04-30 00:53:06 -040068 def fetch_pending(self, deletion=False):
Sapan Bhatia21765662014-07-23 08:59:30 -040069 # This is the most common implementation of fetch_pending
70 # Steps should override it if they have their own logic
71 # for figuring out what objects are outstanding.
Sapan Bhatia99f49682015-01-29 20:58:25 +000072 main_obj = self.observes
Sapan Bhatiad9468eb2014-08-20 03:03:12 -040073 if (not deletion):
Sapan Bhatiad6e38842015-04-21 17:47:07 -040074 objs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False))
Sapan Bhatia21765662014-07-23 08:59:30 -040075 else:
76 objs = main_obj.deleted_objects.all()
77
78 return objs
Sapan Bhatiaca2e21f2013-10-02 01:10:02 -040079 #return Sliver.objects.filter(ip=None)
Sapan Bhatiae6376de2015-05-13 15:51:03 +020080
Sapan Bhatiaca2e21f2013-10-02 01:10:02 -040081 def check_dependencies(self, obj, failed):
Tony Mackce79de02013-09-24 10:12:33 -040082 for dep in self.dependencies:
Scott Baker105b6b72014-05-12 10:40:25 -070083 peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
Sapan Bhatiae6376de2015-05-13 15:51:03 +020084
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -040085 try:
Sapan Bhatia709bebd2015-02-08 06:35:36 +000086 peer_object = deepgetattr(obj, peer_name)
Sapan Bhatiae6376de2015-05-13 15:51:03 +020087 try:
88 peer_objects = peer_object.all()
Sapan Bhatia709bebd2015-02-08 06:35:36 +000089 except AttributeError:
Sapan Bhatiae6376de2015-05-13 15:51:03 +020090 peer_objects = [peer_object]
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -040091 except:
Sapan Bhatia709bebd2015-02-08 06:35:36 +000092 peer_objects = []
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -040093
Sapan Bhatiae6376de2015-05-13 15:51:03 +020094 if (hasattr(obj,'controller')):
95 try:
96 peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
97 except AttributeError:
98 pass
99
Sapan Bhatia709bebd2015-02-08 06:35:36 +0000100 if (failed in peer_objects):
101 if (obj.backend_status!=failed.backend_status):
102 obj.backend_status = failed.backend_status
Sapan Bhatia7e482de2014-08-22 03:05:13 -0400103 obj.save(update_fields=['backend_status'])
Scott Baker4fd314e2015-03-04 21:31:14 -0800104 raise FailedDependency("Failed dependency for %s:%s peer %s:%s failed %s:%s" % (obj.__class__.__name__, str(getattr(obj,"pk","no_pk")), peer_object.__class__.__name__, str(getattr(peer_object,"pk","no_pk")), failed.__class__.__name__, str(getattr(failed,"pk","no_pk"))))
Sapan Bhatia24836f12013-08-27 10:16:05 -0400105
Sapan Bhatia60823362014-04-30 00:52:32 -0400106 def call(self, failed=[], deletion=False):
107 pending = self.fetch_pending(deletion)
Tony Mackce79de02013-09-24 10:12:33 -0400108 for o in pending:
Sapan Bhatia47006112015-01-29 20:55:40 +0000109 sync_failed = False
Tony Mack68e818d2013-09-25 13:34:17 -0400110 try:
Sapan Bhatia24a2a292015-02-10 17:21:33 -0500111 backoff_disabled = Config().observer_backoff_disabled
Sapan Bhatia9cd17be2015-02-10 17:16:07 -0500112 except:
113 backoff_disabled = 0
114
115 try:
Sapan Bhatia47006112015-01-29 20:55:40 +0000116 scratchpad = json.loads(o.backend_register)
117 if (scratchpad):
118 next_run = scratchpad['next_run']
Sapan Bhatia9cd17be2015-02-10 17:16:07 -0500119 if (not backoff_disabled and next_run>time.time()):
Sapan Bhatia47006112015-01-29 20:55:40 +0000120 sync_failed = True
Sapan Bhatia47006112015-01-29 20:55:40 +0000121 except:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200122 logger.log_exc("Exception while loading scratchpad")
Sapan Bhatia47006112015-01-29 20:55:40 +0000123 pass
124
125 if (not sync_failed):
Sapan Bhatiaeba08432014-04-28 23:58:36 -0400126 try:
Sapan Bhatia47006112015-01-29 20:55:40 +0000127 for f in failed:
128 self.check_dependencies(o,f) # Raises exception if failed
129 if (deletion):
130 self.delete_record(o)
131 o.delete(purge=True)
132 else:
133 self.sync_record(o)
134 o.enacted = datetime.now() # Is this the same timezone? XXX
135 scratchpad = {'next_run':0, 'exponent':0}
136 o.backend_register = json.dumps(scratchpad)
137 o.backend_status = "1 - OK"
138 o.save(update_fields=['enacted','backend_status','backend_register'])
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200139 except (InnocuousException,Exception) as e:
Sapan Bhatia47006112015-01-29 20:55:40 +0000140 logger.log_exc("sync step failed!")
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000141 try:
142 if (o.backend_status.startswith('2 - ')):
143 str_e = '%s // %r'%(o.backend_status[4:],e)
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200144 str_e = elim_dups(str_e)
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000145 else:
146 str_e = '%r'%e
147 except:
148 str_e = '%r'%e
149
Sapan Bhatia9c308fc2014-08-22 03:07:59 -0400150 try:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200151 error = self.error_map.map(str_e)
Sapan Bhatia9c308fc2014-08-22 03:07:59 -0400152 except:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200153 error = '2 - %s'%str_e
154
155 if isinstance(e, InnocuousException) and not force_error:
156 o.backend_status = '1 - %s'%error
157 else:
Sapan Bhatia5e2f87a2015-05-13 15:52:45 +0200158 o.backend_status = '2 - %s'%error
Sapan Bhatiaeba08432014-04-28 23:58:36 -0400159
Sapan Bhatia47006112015-01-29 20:55:40 +0000160 try:
161 scratchpad = json.loads(o.backend_register)
162 scratchpad['exponent']
163 except:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200164 logger.log_exc("Exception while updating scratchpad")
Sapan Bhatia47006112015-01-29 20:55:40 +0000165 scratchpad = {'next_run':0, 'exponent':0}
166
167 # Second failure
168 if (scratchpad['exponent']):
169 delay = scratchpad['exponent'] * 600 # 10 minutes
170 if (delay<1440):
171 delay = 1440
172 scratchpad['next_run'] = time.time() + delay
173
174 scratchpad['exponent']+=1
175
176 o.backend_register = json.dumps(scratchpad)
177
178 # TOFIX:
179 # DatabaseError: value too long for type character varying(140)
180 if (o.pk):
181 try:
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000182 o.backend_status = o.backend_status[:1024]
Sapan Bhatia5e2f87a2015-05-13 15:52:45 +0200183 o.save(update_fields=['backend_status','backend_register','updated'])
Sapan Bhatia47006112015-01-29 20:55:40 +0000184 except:
185 print "Could not update backend status field!"
186 pass
187 sync_failed = True
188
189
190 if (sync_failed):
Tony Mack68e818d2013-09-25 13:34:17 -0400191 failed.append(o)
Sapan Bhatiaca2e21f2013-10-02 01:10:02 -0400192
Tony Mackce79de02013-09-24 10:12:33 -0400193 return failed
Sapan Bhatia24836f12013-08-27 10:16:05 -0400194
Sapan Bhatia9028c9a2015-05-09 18:14:40 +0200195 def sync_record(self, o):
196 return
197
198 def delete_record(self, o):
199 return
200
Tony Mack16f04742013-09-25 08:53:28 -0400201 def __call__(self, **args):
202 return self.call(**args)