1 from PLC.Faults import *
2 from PLC.Parameter import Parameter
3 from PLC.Filter import Filter
4 from PLC.Table import Row, Table
11 def class_attributes (classname):
12 """ locates various attributes defined in the row class """
13 topmodule = __import__ ('PLC.%ss'%classname)
14 module = topmodule.__dict__['%ss'%classname]
15 # local row-like class, e.g. Node
16 row_class = module.__dict__['%s'%classname]
17 # local tab-like class, e.g. Nodes
18 table_class = module.__dict__['%ss'%classname]
20 return {'row_class':row_class,
21 'table_class':table_class,
22 'class_id': row_class.__dict__['class_id'],
23 'class_key': row_class.__dict__['class_key'],
24 'foreign_fields': row_class.__dict__['foreign_fields'],
25 'foreign_xrefs': row_class.__dict__['foreign_xrefs'],
30 # an attempt to provide genericity in the caching algorithm
32 # the Peer object we are syncing with
33 def __init__ (self, api, peer, peer_server, auth):
38 assert isinstance(peer,PLC.Peers.Peer)
40 self.peer_server = peer_server
45 def __init__ (self, api, classname, alien_objects):
47 attrs = class_attributes (classname)
48 self.class_id = attrs['class_id']
49 self.class_key = attrs['class_key']
51 # cannot use dict, it's acquired by xmlrpc and is untyped
53 for x in alien_objects:
55 self.alien_objects_byid = d
57 local_objects = attrs['table_class'] (api)
58 self.local_objects_byname = local_objects.dict(self.class_key)
59 verbose ('Transcoder init :',classname,
60 self.alien_objects_byid.keys(),
61 self.local_objects_byname.keys())
63 def transcode (self, alien_id):
64 """ transforms an alien id into a local one """
65 # locate alien obj from alien_id
66 verbose ('entering transcode with alien_id',alien_id,)
67 alien_object=self.alien_objects_byid[alien_id]
68 verbose ('located alien_obj',)
69 name = alien_object [self.class_key]
70 verbose ('got name',name,)
71 local_object=self.local_objects_byname[name]
72 verbose ('found local obj')
73 local_id=local_object[self.class_id]
74 verbose ('and local_id',local_id)
80 def __init__ (self, api, tablename, class1, class2):
82 self.tablename = tablename
83 self.lowerclass1 = class1.lower()
84 self.lowerclass2 = class2.lower()
86 def delete_old_items (self, id1, id2_set):
89 sql += "DELETE FROM %s WHERE %s_id=%d"%(self.tablename,self.lowerclass1,id1)
90 sql += " AND %s_id IN ("%self.lowerclass2
91 sql += ",".join([str(i) for i in id2_set])
95 def insert_new_items (self, id1, id2_set):
96 ### xxx needs to be optimized
97 ### tried to figure a way to use a single sql statement
98 ### like: insert into table (x,y) values (1,2),(3,4);
99 ### but apparently this is not supported under postgresql
101 sql = "INSERT INTO %s VALUES (%d,%d)"%(self.tablename,id1,id2)
104 def update_item (self, id1, old_id2s, new_id2s):
105 news = set (new_id2s)
106 olds = set (old_id2s)
107 to_delete = olds-news
108 self.delete_old_items (id1, to_delete)
109 to_create = news-olds
110 self.insert_new_items (id1, to_create)
113 # classname: the type of objects we are talking about; e.g. 'Slice'
114 # peer_object_list list of objects at a given peer - e.g. peer.GetSlices()
115 # alien_xref_objs_dict : a dict {'classname':alien_obj_list} e.g. {'Node':peer.GetNodes()}
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):
124 peer_id = peer['peer_id']
126 attrs = class_attributes (classname)
127 row_class = attrs['row_class']
128 table_class = attrs['table_class']
129 class_id = attrs['class_id']
130 class_key = attrs['class_key']
131 foreign_fields = attrs['foreign_fields']
132 foreign_xrefs = attrs['foreign_xrefs']
135 ### get current local table
136 # get ALL local objects so as to cope with
137 # (*) potential moves between plcs
138 # (*) or naming conflicts
139 local_objects = table_class (self.api)
140 ### index upon class_key for future searches
141 local_objects_index = local_objects.dict(class_key)
142 verbose ('update_table',classname,local_objects_index.keys())
144 ### mark entries for this peer outofdate
146 for local_object in local_objects:
147 if local_object['peer_id'] == peer_id:
148 local_object.uptodate=False
151 local_object.uptodate=True
154 # scan the peer's local objects
155 for alien_object in alien_object_list:
157 ### ignore system-wide slices
158 if lambda_ignore(alien_object):
161 object_name = alien_object[class_key]
162 verbose ('update_table - Considering',object_name)
166 ### We know about this object already
167 local_object = local_objects_index[object_name]
168 if local_object ['peer_id'] is None:
169 print 'We are in trouble here'
170 print 'The %s object named %s is natively defined twice'%(classname,object_name)
171 print 'Once on this PLC and once on peer %d'%peer_id
172 print 'We dont raise an exception so that the remaining updates can still take place'
174 if local_object['peer_id'] != peer_id:
175 ### the object has changed its plc,
176 ### Note, this is not problematic here because both definitions are remote
177 ### we can assume the object just moved
178 ### needs to update peer_id though
179 local_object['peer_id'] = peer_id
180 verbose ('update_table FOUND',object_name)
182 ### create a new entry
183 local_object = row_class(self.api,
184 {class_key :object_name,'peer_id':peer_id})
186 local_objects_index[class_key]=local_object
187 verbose ('update_table CREATED',object_name)
190 for field in foreign_fields:
191 local_object[field]=alien_object[field]
193 # this row is now valid
194 local_object.uptodate=True
199 for related_class,xrefspec in foreign_xrefs.iteritems():
200 field=xrefspec['field']
201 alien_xref_obj_list = alien_xref_objs_dict[related_class]
202 alien_value = alien_object[field]
203 ### yyy optimize objects allocations for transcoders and xreftables
204 if isinstance (alien_value,list):
205 verbose ('update_table list-transcoding ',related_class,' aliens=',alien_value,)
206 transcoder = Cache.Transcoder(self.api,related_class,alien_xref_obj_list)
208 for a in alien_value:
210 local_values.append(transcoder.transcode(a))
212 # could not transcode - might be from another peer that we dont know about..
214 verbose (" trasncoded as ",local_values)
215 xref_table = Cache.XrefTable (self.api,xrefspec['table'],classname,related_class)
216 # newly created objects dont have xrefs yet
218 former_xrefs=local_object[xrefspec['field']]
221 xref_table.update_item (local_object[class_id],
224 elif isinstance (alien_value,int):
225 new_value = transcoder.transcode(alien_value)
226 local_object[field] = new_value
229 ### delete entries that are not uptodate
230 for local_object in local_objects:
231 if not local_object.uptodate:
232 local_object.delete()
236 ### return delta in number of objects
237 return new_count-old_count
239 def refresh_nodes (self, peer_get_nodes):
241 refreshes the foreign_nodes and peer_node tables
242 expected input is the current list of local nodes
243 as returned from the peer by GetNodes {'peer_id':None}
245 returns the number of new nodes (can be negative)
248 return self.update_table ('Node', peer_get_nodes)
250 def refresh_slices (self, peer_get_slices, peer_foreign_nodes):
252 refreshes the foreign_slices and peer_slice tables
253 expected input is the current list of slices as returned by GetSlices
255 returns the number of new slices on this peer (can be negative)
258 # xxx use 'system' flag for slices
259 return self.update_table ('Slice', peer_get_slices,
260 {'Node':peer_foreign_nodes},
261 lambda x: x['creator_person_id']==1)
263 def refresh_peer (self):
265 peer_local_nodes = self.peer_server.GetNodes(self.auth,None,None,'local')
266 peer_foreign_nodes = self.peer_server.GetNodes(self.auth,None,None,'foreign')
267 peer_local_slices = self.peer_server.GetSlices(self.auth,{'peer_id':None})
269 from PLC.Nodes import Nodes
270 verbose ('local nodes before refresh',len(Nodes(self.api)))
271 nb_new_nodes = self.refresh_nodes(peer_local_nodes)
272 verbose ('local nodes after refresh',len(Nodes(self.api)))
274 # rough and temporary
275 nb_new_slices = self.refresh_slices(peer_local_slices,peer_local_nodes+peer_foreign_nodes)
277 return {'plcname':self.api.config.PLC_NAME,
278 'new_nodes':nb_new_nodes,
279 'new_slices':nb_new_slices}