blob: 7accbfad3e9d3af27984bf8460d0109a120a0d1d [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
Scott Baker8bbc77c2015-06-22 10:56:16 -07008from core.models import *
9from django.db import reset_queries
Sapan Bhatia7fdccee2015-09-16 16:42:38 +020010from observer.ansible import *
11
Sapan Bhatia47006112015-01-29 20:55:40 +000012import json
13import time
14import pdb
Andy Baviere7abb622013-10-18 15:11:56 -040015
Andy Bavier04111b72013-10-22 16:47:10 -040016logger = Logger(level=logging.INFO)
Sapan Bhatia24836f12013-08-27 10:16:05 -040017
Sapan Bhatia2192fec2015-02-08 06:36:32 +000018def f7(seq):
19 seen = set()
20 seen_add = seen.add
21 return [ x for x in seq if not (x in seen or seen_add(x))]
22
23def elim_dups(backend_str):
24 strs = backend_str.split(' // ')
25 strs2 = f7(strs)
26 return ' // '.join(strs2)
Sapan Bhatiae6376de2015-05-13 15:51:03 +020027
Sapan Bhatia709bebd2015-02-08 06:35:36 +000028def deepgetattr(obj, attr):
29 return reduce(getattr, attr.split('.'), obj)
30
Sapan Bhatiae6376de2015-05-13 15:51:03 +020031
32class InnocuousException(Exception):
33 pass
34
Scott Baker7ed0b762015-08-25 16:23:37 -070035class DeferredException(Exception):
36 pass
37
Sapan Bhatia13c7f112013-09-02 14:19:35 -040038class FailedDependency(Exception):
Tony Mackce79de02013-09-24 10:12:33 -040039 pass
Sapan Bhatia13c7f112013-09-02 14:19:35 -040040
Tony Mackb469d242015-01-03 19:37:39 -050041class SyncStep(object):
Sapan Bhatiae6376de2015-05-13 15:51:03 +020042 """ An XOS Sync step.
Sapan Bhatia24836f12013-08-27 10:16:05 -040043
Tony Mackce79de02013-09-24 10:12:33 -040044 Attributes:
Sapan Bhatiae6376de2015-05-13 15:51:03 +020045 psmodel Model name the step synchronizes
Tony Mackce79de02013-09-24 10:12:33 -040046 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 +020047 """
Scott Baker1a36d662015-10-12 18:28:00 -070048
49 # map_sync_outputs can return this value to cause a step to be marked
50 # successful without running ansible. Used for sync_network_controllers
51 # on nat networks.
52 SYNC_WITHOUT_RUNNING = "sync_without_running"
53
Tony Mackce79de02013-09-24 10:12:33 -040054 slow=False
Tony Mackfbdae1b2015-02-24 14:16:43 -050055 def get_prop(self, prop):
Tony Mackce79de02013-09-24 10:12:33 -040056 try:
57 sync_config_dir = Config().sync_config_dir
58 except:
Scott Bakerb8059c92015-02-19 22:25:49 -080059 sync_config_dir = '/etc/xos/sync'
Tony Mackce79de02013-09-24 10:12:33 -040060 prop_config_path = '/'.join(sync_config_dir,self.name,prop)
61 return open(prop_config_path).read().rstrip()
Sapan Bhatia24836f12013-08-27 10:16:05 -040062
Tony Mackce79de02013-09-24 10:12:33 -040063 def __init__(self, **args):
64 """Initialize a sync step
65 Keyword arguments:
66 name -- Name of the step
Scott Baker286a78f2015-02-18 16:13:48 -080067 provides -- XOS models sync'd by this step
Tony Mackce79de02013-09-24 10:12:33 -040068 """
69 dependencies = []
Tony Mack387a73f2013-09-18 07:59:14 -040070 self.driver = args.get('driver')
Sapan Bhatiaeba08432014-04-28 23:58:36 -040071 self.error_map = args.get('error_map')
72
Tony Mackce79de02013-09-24 10:12:33 -040073 try:
74 self.soft_deadline = int(self.get_prop('soft_deadline_seconds'))
75 except:
76 self.soft_deadline = 5 # 5 seconds
Sapan Bhatia24836f12013-08-27 10:16:05 -040077
Tony Mackce79de02013-09-24 10:12:33 -040078 return
Sapan Bhatia24836f12013-08-27 10:16:05 -040079
Sapan Bhatiae17bc5b2014-04-30 00:53:06 -040080 def fetch_pending(self, deletion=False):
Sapan Bhatia21765662014-07-23 08:59:30 -040081 # This is the most common implementation of fetch_pending
82 # Steps should override it if they have their own logic
83 # for figuring out what objects are outstanding.
Sapan Bhatiaab18ee42015-08-19 12:20:30 -040084
85 main_objs = self.observes
86 if (type(main_objs) is not list):
Sapan Bhatia83e7a642015-09-10 11:08:35 -040087 main_objs=[main_objs]
Sapan Bhatiaab18ee42015-08-19 12:20:30 -040088
89 objs = []
90 for main_obj in main_objs:
91 if (not deletion):
Sapan Bhatiad063f5f2015-09-16 17:42:07 +020092 lobjs = main_obj.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None),Q(lazy_blocked=False),Q(no_sync=False))
Sapan Bhatiaab18ee42015-08-19 12:20:30 -040093 else:
94 lobjs = main_obj.deleted_objects.all()
95 objs.extend(lobjs)
Sapan Bhatia21765662014-07-23 08:59:30 -040096
97 return objs
Tony Mack3de59e32015-08-19 11:58:18 -040098 #return Instance.objects.filter(ip=None)
Sapan Bhatiae6376de2015-05-13 15:51:03 +020099
Sapan Bhatiaca2e21f2013-10-02 01:10:02 -0400100 def check_dependencies(self, obj, failed):
Tony Mackce79de02013-09-24 10:12:33 -0400101 for dep in self.dependencies:
Scott Baker105b6b72014-05-12 10:40:25 -0700102 peer_name = dep[0].lower() + dep[1:] # django names are camelCased with the first letter lower
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200103
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -0400104 try:
Sapan Bhatia709bebd2015-02-08 06:35:36 +0000105 peer_object = deepgetattr(obj, peer_name)
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200106 try:
107 peer_objects = peer_object.all()
Sapan Bhatia709bebd2015-02-08 06:35:36 +0000108 except AttributeError:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200109 peer_objects = [peer_object]
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -0400110 except:
Sapan Bhatia709bebd2015-02-08 06:35:36 +0000111 peer_objects = []
Sapan Bhatiacfef6ef2014-08-20 03:04:03 -0400112
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200113 if (hasattr(obj,'controller')):
114 try:
115 peer_objects = filter(lambda o:o.controller==obj.controller, peer_objects)
116 except AttributeError:
117 pass
118
Sapan Bhatia709bebd2015-02-08 06:35:36 +0000119 if (failed in peer_objects):
120 if (obj.backend_status!=failed.backend_status):
121 obj.backend_status = failed.backend_status
Sapan Bhatia7e482de2014-08-22 03:05:13 -0400122 obj.save(update_fields=['backend_status'])
Scott Baker4fd314e2015-03-04 21:31:14 -0800123 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 -0400124
Sapan Bhatia7fdccee2015-09-16 16:42:38 +0200125
126 def sync_record(self, o):
127 try:
128 controller = o.get_controller()
129 controller_register = json.loads(o.node.site_deployment.controller.backend_register)
130
131 if (controller_register.get('disabled',False)):
132 raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
133 except AttributeError:
134 pass
135
136 tenant_fields = self.map_sync_inputs(o)
Scott Baker1a36d662015-10-12 18:28:00 -0700137 if tenant_fields == SyncStep.SYNC_WITHOUT_RUNNING:
138 return
Sapan Bhatia7fdccee2015-09-16 16:42:38 +0200139 main_objs=self.observes
140 if (type(main_objs) is list):
141 main_objs=main_objs[0]
142
143 path = ''.join(main_objs.__name__).lower()
144 res = run_template(self.playbook,tenant_fields,path=path)
145
146 try:
147 self.map_sync_outputs(o,res)
148 except AttributeError:
149 pass
150
151 def delete_record(self, o):
152 try:
153 controller = o.get_controller()
154 controller_register = json.loads(o.node.site_deployment.controller.backend_register)
155
156 if (controller_register.get('disabled',False)):
157 raise InnocuousException('Controller %s is disabled'%sliver.node.site_deployment.controller.name)
158 except AttributeError:
159 pass
160
Scott Bakerf7cb9132015-09-17 22:04:57 -0700161 tenant_fields = self.map_delete_inputs(o)
Sapan Bhatia7fdccee2015-09-16 16:42:38 +0200162
163 main_objs=self.observes
164 if (type(main_objs) is list):
165 main_objs=main_objs[0]
166
167 path = ''.join(main_objs.__name__).lower()
168
169 tenant_fields['delete']=True
170 res = run_template(self.playbook,tenant_fields,path=path)
171 try:
172 self.map_delete_outputs(o,res)
173 except AttributeError:
174 pass
175
Sapan Bhatia60823362014-04-30 00:52:32 -0400176 def call(self, failed=[], deletion=False):
177 pending = self.fetch_pending(deletion)
Sapan Bhatia7fdccee2015-09-16 16:42:38 +0200178
Tony Mackce79de02013-09-24 10:12:33 -0400179 for o in pending:
Scott Baker8bbc77c2015-06-22 10:56:16 -0700180 # another spot to clean up debug state
181 try:
182 reset_queries()
183 except:
184 # this shouldn't happen, but in case it does, catch it...
185 logger.log_exc("exception in reset_queries")
186
Sapan Bhatia47006112015-01-29 20:55:40 +0000187 sync_failed = False
Tony Mack68e818d2013-09-25 13:34:17 -0400188 try:
Sapan Bhatia24a2a292015-02-10 17:21:33 -0500189 backoff_disabled = Config().observer_backoff_disabled
Sapan Bhatia9cd17be2015-02-10 17:16:07 -0500190 except:
191 backoff_disabled = 0
192
193 try:
Sapan Bhatia47006112015-01-29 20:55:40 +0000194 scratchpad = json.loads(o.backend_register)
195 if (scratchpad):
196 next_run = scratchpad['next_run']
Sapan Bhatia9cd17be2015-02-10 17:16:07 -0500197 if (not backoff_disabled and next_run>time.time()):
Sapan Bhatia47006112015-01-29 20:55:40 +0000198 sync_failed = True
Sapan Bhatia47006112015-01-29 20:55:40 +0000199 except:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200200 logger.log_exc("Exception while loading scratchpad")
Sapan Bhatia47006112015-01-29 20:55:40 +0000201 pass
202
203 if (not sync_failed):
Sapan Bhatiaeba08432014-04-28 23:58:36 -0400204 try:
Sapan Bhatia47006112015-01-29 20:55:40 +0000205 for f in failed:
206 self.check_dependencies(o,f) # Raises exception if failed
207 if (deletion):
208 self.delete_record(o)
209 o.delete(purge=True)
210 else:
211 self.sync_record(o)
212 o.enacted = datetime.now() # Is this the same timezone? XXX
213 scratchpad = {'next_run':0, 'exponent':0}
214 o.backend_register = json.dumps(scratchpad)
215 o.backend_status = "1 - OK"
216 o.save(update_fields=['enacted','backend_status','backend_register'])
Scott Baker7ed0b762015-08-25 16:23:37 -0700217 except (InnocuousException,Exception,DeferredException) as e:
Sapan Bhatia47006112015-01-29 20:55:40 +0000218 logger.log_exc("sync step failed!")
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000219 try:
220 if (o.backend_status.startswith('2 - ')):
221 str_e = '%s // %r'%(o.backend_status[4:],e)
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200222 str_e = elim_dups(str_e)
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000223 else:
224 str_e = '%r'%e
225 except:
226 str_e = '%r'%e
227
Sapan Bhatia9c308fc2014-08-22 03:07:59 -0400228 try:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200229 error = self.error_map.map(str_e)
Sapan Bhatia9c308fc2014-08-22 03:07:59 -0400230 except:
Sapan Bhatiac368d4a2015-06-09 14:14:12 -0400231 error = '%s'%str_e
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200232
233 if isinstance(e, InnocuousException) and not force_error:
234 o.backend_status = '1 - %s'%error
235 else:
Sapan Bhatia5e2f87a2015-05-13 15:52:45 +0200236 o.backend_status = '2 - %s'%error
Sapan Bhatiaeba08432014-04-28 23:58:36 -0400237
Sapan Bhatia47006112015-01-29 20:55:40 +0000238 try:
239 scratchpad = json.loads(o.backend_register)
240 scratchpad['exponent']
241 except:
Sapan Bhatiae6376de2015-05-13 15:51:03 +0200242 logger.log_exc("Exception while updating scratchpad")
Sapan Bhatia47006112015-01-29 20:55:40 +0000243 scratchpad = {'next_run':0, 'exponent':0}
244
245 # Second failure
246 if (scratchpad['exponent']):
Scott Baker7ed0b762015-08-25 16:23:37 -0700247 if isinstance(e,DeferredException):
248 delay = scratchpad['exponent'] * 60 # 1 minute
249 else:
250 delay = scratchpad['exponent'] * 600 # 10 minutes
251 # cap delays at 8 hours
252 if (delay>8*60*60):
253 delay=8*60*60
Sapan Bhatia47006112015-01-29 20:55:40 +0000254 scratchpad['next_run'] = time.time() + delay
255
256 scratchpad['exponent']+=1
257
258 o.backend_register = json.dumps(scratchpad)
259
260 # TOFIX:
261 # DatabaseError: value too long for type character varying(140)
262 if (o.pk):
263 try:
Sapan Bhatia2175c1d2015-02-08 06:31:42 +0000264 o.backend_status = o.backend_status[:1024]
Sapan Bhatia5e2f87a2015-05-13 15:52:45 +0200265 o.save(update_fields=['backend_status','backend_register','updated'])
Sapan Bhatia47006112015-01-29 20:55:40 +0000266 except:
267 print "Could not update backend status field!"
268 pass
269 sync_failed = True
270
271
272 if (sync_failed):
Tony Mack68e818d2013-09-25 13:34:17 -0400273 failed.append(o)
Sapan Bhatiaca2e21f2013-10-02 01:10:02 -0400274
Tony Mackce79de02013-09-24 10:12:33 -0400275 return failed
Sapan Bhatia24836f12013-08-27 10:16:05 -0400276
Tony Mack16f04742013-09-25 08:53:28 -0400277 def __call__(self, **args):
278 return self.call(**args)