3 from PLC.Faults import *
4 from PLC.Parameter import Parameter
5 from PLC.Filter import Filter
6 from PLC.Table import Row, Table
14 def class_attributes (classname):
15 """ locates various attributes defined in the row class """
16 topmodule = __import__ ('PLC.%ss'%classname)
17 module = topmodule.__dict__['%ss'%classname]
18 # local row-like class, e.g. Node
19 row_class = module.__dict__['%s'%classname]
20 # local tab-like class, e.g. Nodes
21 table_class = module.__dict__['%ss'%classname]
23 return {'row_class':row_class,
24 'table_class':table_class,
25 'primary_key': row_class.__dict__['primary_key'],
26 'class_key': row_class.__dict__['class_key'],
27 'foreign_fields': row_class.__dict__['foreign_fields'],
28 'foreign_xrefs': row_class.__dict__['foreign_xrefs'],
33 # an attempt to provide genericity in the caching algorithm
35 def __init__ (self, api, peer_id, peer_server, auth):
38 self.peer_id = peer_id
39 self.peer_server = peer_server
44 def __init__ (self, api, classname, alien_objects):
46 attrs = class_attributes (classname)
47 self.primary_key = attrs['primary_key']
48 self.class_key = attrs['class_key']
50 # cannot use dict, it's acquired by xmlrpc and is untyped
51 self.alien_objects_byid = dict( [ (x[self.primary_key],x) for x in alien_objects ] )
53 # retrieve local objects
54 local_objects = attrs['table_class'] (api)
55 self.local_objects_byname = local_objects.dict(self.class_key)
57 verbose ('Transcoder init :',classname,
58 self.alien_objects_byid.keys(),
59 self.local_objects_byname.keys())
61 def transcode (self, alien_id):
62 """ transforms an alien id into a local one """
63 # locate alien obj from alien_id
64 #verbose ('.entering transcode with alien_id',alien_id,)
65 alien_object=self.alien_objects_byid[alien_id]
66 #verbose ('..located alien_obj',)
67 name = alien_object [self.class_key]
68 #verbose ('...got name',name,)
69 local_object=self.local_objects_byname[name]
70 #verbose ('....found local obj')
71 local_id=local_object[self.primary_key]
72 #verbose ('.....and local_id',local_id)
76 # for handling simple n-to-n relation tables, like e.g. slice_node
79 def __init__ (self, api, tablename, class1, class2):
81 self.tablename = tablename
82 self.lowerclass1 = class1.lower()
83 self.lowerclass2 = class2.lower()
85 def delete_old_items (self, id1, id2_set):
88 sql += "DELETE FROM %s WHERE %s_id=%d"%(self.tablename,self.lowerclass1,id1)
89 sql += " AND %s_id IN ("%self.lowerclass2
90 sql += ",".join([str(i) for i in id2_set])
94 def insert_new_items (self, id1, id2_set):
96 sql = "INSERT INTO %s select %d, %d " % \
97 self.tablename, id1, id2[0]
98 for id2 in id2_set[1:]:
99 sql += " UNION ALL SELECT %d, %d " % \
103 def update_item (self, id1, old_id2s, new_id2s):
104 news = set (new_id2s)
105 olds = set (old_id2s)
106 to_delete = olds-news
107 self.delete_old_items (id1, to_delete)
108 to_create = news-olds
109 self.insert_new_items (id1, to_create)
112 # classname: the type of objects we are talking about; e.g. 'Slice'
113 # peer_object_list list of objects at a given peer - e.g. peer.GetSlices()
114 # alien_xref_objs_dict : a dict {'classname':alien_obj_list} e.g. {'Node':peer.GetNodes()}
115 # we need an entry for each class mentioned in the class's foreign_xrefs
116 # lambda_ignore : the alien objects are ignored if this returns true
117 def update_table (self,
120 alien_xref_objs_dict = {},
121 lambda_ignore=lambda x:False,
122 report_name_conflicts = True):
124 verbose ("============================== entering update_table on",classname)
127 attrs = class_attributes (classname)
128 row_class = attrs['row_class']
129 table_class = attrs['table_class']
130 primary_key = attrs['primary_key']
131 class_key = attrs['class_key']
132 foreign_fields = attrs['foreign_fields']
133 foreign_xrefs = attrs['foreign_xrefs']
135 ## allocate transcoders and xreftables once, for each item in foreign_xrefs
136 # create a dict 'classname' -> {'transcoder' : ..., 'xref_table' : ...}
137 xref_accessories = dict(
139 {'transcoder' : Cache.Transcoder (self.api,xref['class'],alien_xref_objs_dict[xref['class']]),
140 'xref_table' : Cache.XrefTable (self.api,xref['table'],classname,xref['class'])})
141 for xref in foreign_xrefs ])
143 # the fields that are direct references, like e.g. site_id in Node
144 # determined lazily, we need an alien_object to do that, and we may have none here
145 direct_ref_fields = None
147 ### get current local table
148 # get ALL local objects so as to cope with
149 # (*) potential moves between plcs
150 # (*) or naming conflicts
151 local_objects = table_class (self.api)
152 ### index upon class_key for future searches
153 local_objects_index = local_objects.dict(class_key)
155 #verbose ('update_table',classname,local_objects_index.keys())
157 ### mark entries for this peer outofdate
160 for local_object in local_objects:
161 if local_object['peer_id'] == peer_id:
162 local_object.uptodate=False
165 local_object.uptodate=True
167 # scan the peer's local objects
168 for alien_object in alien_object_list:
170 object_name = alien_object[class_key]
172 ### ignore, e.g. system-wide slices
173 if lambda_ignore(alien_object):
174 verbose('Ignoring',object_name)
177 verbose ('update_table (%s) - Considering'%classname,object_name)
181 ### We know about this object already
182 local_object = local_objects_index[object_name]
183 if local_object ['peer_id'] is None:
184 if report_name_conflicts:
186 print '!!!!!!!!!! We are in trouble here'
187 print 'The %s object named %s is natively defined twice, '%(classname,object_name),
188 print 'once on this PLC and once on peer %d'%peer_id
189 print 'We dont raise an exception so that the remaining updates can still take place'
192 if local_object['peer_id'] != peer_id:
193 ### the object has changed its plc,
194 ### Note, this is not problematic here because both definitions are remote
195 ### we can assume the object just moved
196 ### needs to update peer_id though
197 local_object['peer_id'] = peer_id
198 # update all fields as per foreign_fields
199 for field in foreign_fields:
200 local_object[field]=alien_object[field]
201 verbose ('update_table FOUND',object_name)
203 ### create a new entry
204 local_object = row_class(self.api,
205 {class_key :object_name,'peer_id':peer_id})
207 local_objects_index[class_key]=local_object
208 verbose ('update_table CREATED',object_name)
209 # update all fields as per foreign_fields
210 for field in foreign_fields:
211 local_object[field]=alien_object[field]
212 # this is tricky; at this point we may have primary_key unspecified,
213 # but we need it for handling xrefs below, so we'd like to sync to get one
214 # on the other hand some required fields may be still missing so
215 # the DB would refuse to sync in this case (e.g. site_id in Node)
216 # so let's fill them with 1 so we can sync, this will be overridden below
217 # lazily determine this set of fields now
218 if direct_ref_fields is None:
220 for xref in foreign_xrefs:
222 verbose('checking field %s for direct_ref'%field)
223 if isinstance(alien_object[field],int):
224 direct_ref_fields.append(field)
225 verbose("FOUND DIRECT REFS",direct_ref_fields)
226 for field in direct_ref_fields:
227 local_object[field]=1
228 verbose('Early sync on',local_object)
231 # this row is now valid
232 local_object.uptodate=True
236 for xref in foreign_xrefs:
238 alien_xref_obj_list = alien_xref_objs_dict[xref['class']]
239 alien_value = alien_object[field]
240 transcoder = xref_accessories[xref['field']]['transcoder']
241 if isinstance (alien_value,list):
242 #verbose ('update_table list-transcoding ',xref['class'],' aliens=',alien_value,)
244 for a in alien_value:
246 local_values.append(transcoder.transcode(a))
248 # could not transcode - might be from another peer that we dont know about..
250 #verbose (" transcoded as ",local_values)
251 xref_table = xref_accessories[xref['field']]['xref_table']
252 # newly created objects dont have xref fields set yet
254 former_xrefs=local_object[xref['field']]
257 xref_table.update_item (local_object[primary_key],
260 elif isinstance (alien_value,int):
261 #verbose ('update_table atom-transcoding ',xref['class'],' aliens=',alien_value,)
262 new_value = transcoder.transcode(alien_value)
263 local_object[field] = new_value
265 ### this object is completely updated, let's save it
266 verbose('FINAL sync on %s:'%object_name,local_object)
270 ### delete entries that are not uptodate
271 for local_object in local_objects:
272 if not local_object.uptodate:
273 local_object.delete()
277 ### return delta in number of objects
278 return new_count-old_count
280 # slice attributes exhibit a special behaviour
281 # because there is no name we can use to retrieve/check for equality
282 # this object is like a 3-part xref, linking slice_attribute_type, slice,
283 # and potentially node, together with a value that can change over time.
284 # extending the generic model to support a lambda rather than class_key
285 # would clearly become overkill
286 def update_slice_attributes (self,
287 alien_slice_attributes,
291 from PLC.SliceAttributeTypes import SliceAttributeTypes
292 from PLC.SliceAttributes import SliceAttribute, SliceAttributes
295 peer_id = self.peer_id
298 node_xcoder = Cache.Transcoder (self.api, 'Node', alien_nodes)
299 slice_xcoder= Cache.Transcoder (self.api, 'Slice', alien_slices)
300 # no need to transcode SliceAttributeTypes, we have a name in the result
301 local_sat_dict = SliceAttributeTypes(self.api).dict('name')
304 local_objects = SliceAttributes (self.api,{'peer_id':peer_id})
306 ### mark entries for this peer outofdate
308 old_count=len(local_objects)
309 for local_object in local_objects:
310 local_object.uptodate=False
312 for alien_object in alien_slice_attributes:
314 verbose('----- update_slice_attributes: considering ...')
315 verbose(' ',alien_object)
319 slice_id = slice_xcoder.transcode(alien_object['slice_id'])
321 verbose('update_slice_attributes: unable to locate slice',
322 alien_object['slice_id'])
324 # locate slice_attribute_type
326 sat_id = local_sat_dict[alien_object['name']]['attribute_type_id']
328 verbose('update_slice_attributes: unable to locate slice attribute type',
329 alien_object['name'])
331 # locate local node if specified
333 alien_node_id = alien_object['node_id']
334 if alien_node_id is not None:
335 node_id = node_xcoder.transcode(alien_node_id)
339 verbose('update_slice_attributes: unable to locate node',
340 alien_object['node_id'])
343 # locate the local SliceAttribute if any
345 verbose ('searching name=', alien_object['name'],
346 'slice_id',slice_id, 'node_id',node_id)
347 local_object = SliceAttributes (self.api,
348 {'name':alien_object['name'],
350 'node_id':node_id})[0]
352 if local_object['peer_id'] != peer_id:
353 verbose ('FOUND local sa - skipped')
355 verbose('FOUND already cached sa - setting value')
356 local_object['value'] = alien_object['value']
357 # create it if missing
359 local_object = SliceAttribute(self.api,
363 'attribute_type_id':sat_id,
364 'value':alien_object['value']})
365 verbose('CREATED new sa')
366 local_object.uptodate=True
370 for local_object in local_objects:
371 if not local_object.uptodate:
372 local_object.delete()
375 ### return delta in number of objects
376 return new_count-old_count
378 def refresh_peer (self):
380 # so as to minimize the numer of requests
381 # we get all objects in a single call and sort afterwards
382 # xxx ideally get objects either local or the ones attached here
383 # requires to know remote peer's peer_id for ourselves, mmhh..
384 # does not make any difference in a 2-peer deployment though
386 ### uses GetPeerData to gather all info in a single xmlrpc request
389 # xxx see also GetPeerData - peer_id arg unused yet
390 all_data = self.peer_server.GetPeerData (self.auth,0)
392 t_acquired = time.time()
394 plocal_sites = all_data['Sites-local']
395 all_sites = plocal_sites + all_data['Sites-peer']
396 nb_new_sites = self.update_table('Site', plocal_sites)
399 plocal_keys = all_data['Keys-local']
400 all_keys = plocal_keys + all_data['Keys-peer']
401 nb_new_keys = self.update_table('Key', plocal_keys)
404 plocal_nodes = all_data['Nodes-local']
405 all_nodes = plocal_nodes + all_data['Nodes-peer']
406 nb_new_nodes = self.update_table('Node', plocal_nodes,
407 { 'Site' : all_sites } )
410 plocal_persons = all_data['Persons-local']
411 all_persons = plocal_persons + all_data['Persons-peer']
412 nb_new_persons = self.update_table ('Person', plocal_persons,
413 { 'Key': all_keys, 'Site' : all_sites } )
415 # refresh slice attribute types
416 plocal_slice_attribute_types = all_data ['SliceAttibuteTypes-local']
417 nb_new_slice_attribute_types = self.update_table ('SliceAttributeType',
418 plocal_slice_attribute_types,
419 report_name_conflicts = False)
422 plocal_slices = all_data['Slices-local']
423 all_slices = plocal_slices + all_data['Slices-peer']
425 def is_system_slice (slice):
426 return slice['creator_person_id'] == 1
428 nb_new_slices = self.update_table ('Slice', plocal_slices,
430 'Person': all_persons,
434 # refresh slice attributes
435 plocal_slice_attributes = all_data ['SliceAttributes-local']
436 nb_new_slice_attributes = self.update_slice_attributes (plocal_slice_attributes,
441 ### returned as-is by RefreshPeer
442 return {'plcname':self.api.config.PLC_NAME,
443 'new_sites':nb_new_sites,
444 'new_keys':nb_new_keys,
445 'new_nodes':nb_new_nodes,
446 'new_persons':nb_new_persons,
447 'new_slice_attribute_types':nb_new_slice_attribute_types,
448 'new_slices':nb_new_slices,
449 'new_slice_attributes':nb_new_slice_attributes,
450 'time_gather': all_data['ellapsed'],
451 'time_transmit':t_acquired-t_start-all_data['ellapsed'],
452 'time_process':t_end-t_acquired,
453 'time_all':t_end-t_start,