6 # read the planetlab database and update the local registry database accordingly
7 # (in other words, with this testbed, the SFA registry is *not* authoritative)
8 # so we update the following collections
9 # . authorities (from pl sites)
10 # . node (from pl nodes)
11 # . users+keys (from pl persons and attached keys)
12 # known limitation : *one* of the ssh keys is chosen at random here
13 # xxx todo/check xxx at the very least, when a key is known to the registry
14 # and is still current in plc
15 # then we should definitely make sure to keep that one in sfa...
16 # . slice+researchers (from pl slices and attached users)
21 from sfa.util.config import Config
22 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn
24 from sfa.trust.gid import create_uuid
25 from sfa.trust.certificate import convert_public_key, Keypair
27 from sfa.storage.alchemy import dbsession
28 from sfa.storage.model import RegRecord, RegAuthority, RegSlice, RegNode, RegUser, RegKey
30 from sfa.planetlab.plshell import PlShell
31 from sfa.planetlab.plxrn import hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
33 def _get_site_hrn(interface_hrn, site):
34 # Hardcode 'internet2' into the hrn for sites hosting
35 # internet2 nodes. This is a special operation for some vini
37 hrn = ".".join([interface_hrn, site['login_base']])
38 if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
39 if site['login_base'].startswith("i2") or site['login_base'].startswith("nlr"):
40 hrn = ".".join([interface_hrn, "internet2", site['login_base']])
46 def __init__ (self, auth_hierarchy, logger):
47 self.auth_hierarchy = auth_hierarchy
50 def add_options (self, parser):
51 # we don't have any options for now
54 # hrn hash is initialized from current db
55 # remember just-created records as we go
56 # xxx might make sense to add a UNIQUE constraint in the db itself
57 def remember_record_by_hrn (self, record):
58 tuple = (record.type, record.hrn)
59 if tuple in self.records_by_type_hrn:
60 self.logger.warning ("PlImporter.remember_record_by_hrn: duplicate (%s,%s)"%tuple)
62 self.records_by_type_hrn [ tuple ] = record
64 # ditto for pointer hash
65 def remember_record_by_pointer (self, record):
66 if record.pointer == -1:
67 self.logger.warning ("PlImporter.remember_record_by_pointer: pointer is void")
69 tuple = (record.type, record.pointer)
70 if tuple in self.records_by_type_pointer:
71 self.logger.warning ("PlImporter.remember_record_by_pointer: duplicate (%s,%s)"%tuple)
73 self.records_by_type_pointer [ ( record.type, record.pointer,) ] = record
75 def remember_record (self, record):
76 self.remember_record_by_hrn (record)
77 self.remember_record_by_pointer (record)
79 def locate_by_type_hrn (self, type, hrn):
80 return self.records_by_type_hrn.get ( (type, hrn), None)
82 def locate_by_type_pointer (self, type, pointer):
83 return self.records_by_type_pointer.get ( (type, pointer), None)
85 # a convenience/helper function to see if a record is already known
86 # a former, broken, attempt (in 2.1-9) had been made
87 # to try and use 'pointer' as a first, most significant attempt
88 # the idea being to preserve stuff as much as possible, and thus
89 # to avoid creating a new gid in the case of a simple hrn rename
90 # however this of course doesn't work as the gid depends on the hrn...
91 #def locate (self, type, hrn=None, pointer=-1):
93 # attempt = self.locate_by_type_pointer (type, pointer)
94 # if attempt : return attempt
96 # attempt = self.locate_by_type_hrn (type, hrn,)
97 # if attempt : return attempt
100 # this makes the run method a bit abtruse - out of the way
101 def create_special_vini_record (self, interface_hrn):
102 # special case for vini
103 if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
104 # create a fake internet2 site first
105 i2site = {'name': 'Internet2', 'login_base': 'internet2', 'site_id': -1}
106 site_hrn = _get_site_hrn(interface_hrn, i2site)
107 # import if hrn is not in list of existing hrns or if the hrn exists
108 # but its not a site record
109 if ( 'authority', site_hrn, ) not in self.records_by_type_hrn:
110 urn = hrn_to_urn(site_hrn, 'authority')
111 if not self.auth_hierarchy.auth_exists(urn):
112 self.auth_hierarchy.create_auth(urn)
113 auth_info = self.auth_hierarchy.get_auth_info(urn)
114 auth_record = RegAuthority(hrn=site_hrn, gid=auth_info.get_gid_object(),
115 pointer=site['site_id'],
116 authority=get_authority(site_hrn))
117 auth_record.just_created()
118 dbsession.add(auth_record)
120 self.logger.info("PlImporter: Imported authority (vini site) %s"%auth_record)
121 self.remember_record ( site_record )
123 def run (self, options):
125 interface_hrn = config.SFA_INTERFACE_HRN
126 root_auth = config.SFA_REGISTRY_ROOT_AUTH
127 shell = PlShell (config)
129 ######## retrieve all existing SFA objects
130 all_records = dbsession.query(RegRecord).all()
132 # create hash by (type,hrn)
133 # we essentially use this to know if a given record is already known to SFA
134 self.records_by_type_hrn = \
135 dict ( [ ( (record.type, record.hrn) , record ) for record in all_records ] )
136 # create hash by (type,pointer)
137 self.records_by_type_pointer = \
138 dict ( [ ( (record.type, record.pointer) , record ) for record in all_records
139 if record.pointer != -1] )
141 # initialize record.stale to True by default, then mark stale=False on the ones that are in use
142 for record in all_records: record.stale=True
144 ######## retrieve PLC data
146 # retrieve only required stuf
147 sites = shell.GetSites({'peer_id': None, 'enabled' : True},
148 ['site_id','login_base','node_ids','slice_ids','person_ids',])
149 # create a hash of sites by login_base
150 # sites_by_login_base = dict ( [ ( site['login_base'], site ) for site in sites ] )
152 persons = shell.GetPersons({'peer_id': None, 'enabled': True},
153 ['person_id', 'email', 'key_ids', 'site_ids', 'role_ids'])
154 # create a hash of persons by person_id
155 persons_by_id = dict ( [ ( person['person_id'], person) for person in persons ] )
156 # also gather non-enabled user accounts so as to issue relevant warnings
157 disabled_persons = shell.GetPersons({'peer_id': None, 'enabled': False}, ['person_id'])
158 disabled_person_ids = [ person['person_id'] for person in disabled_persons ]
159 # Get all plc public keys
160 # accumulate key ids for keys retrieval
162 for person in persons:
163 key_ids.extend(person['key_ids'])
164 keys = shell.GetKeys( {'peer_id': None, 'key_id': key_ids,
166 # create a hash of keys by key_id
167 keys_by_id = dict ( [ ( key['key_id'], key ) for key in keys ] )
168 # create a dict person_id -> [ (plc)keys ]
169 keys_by_person_id = {}
170 for person in persons:
172 for key_id in person['key_ids']:
173 # by construction all the keys we fetched are ssh keys
174 # so gpg keys won't be in there
176 key = keys_by_id[key_id]
179 self.logger.warning("Could not spot key %d - probably non-ssh"%key_id)
180 keys_by_person_id[person['person_id']] = pubkeys
182 nodes = shell.GetNodes( {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
183 # create hash by node_id
184 nodes_by_id = dict ( [ ( node['node_id'], node, ) for node in nodes ] )
186 slices = shell.GetSlices( {'peer_id': None}, ['slice_id', 'name', 'person_ids'])
187 # create hash by slice_id
188 slices_by_id = dict ( [ (slice['slice_id'], slice ) for slice in slices ] )
190 # isolate special vini case in separate method
191 self.create_special_vini_record (interface_hrn)
195 site_hrn = _get_site_hrn(interface_hrn, site)
196 # import if hrn is not in list of existing hrns or if the hrn exists
197 # but its not a site record
198 site_record=self.locate_by_type_hrn ('authority', site_hrn)
201 urn = hrn_to_urn(site_hrn, 'authority')
202 if not self.auth_hierarchy.auth_exists(urn):
203 self.auth_hierarchy.create_auth(urn)
204 auth_info = self.auth_hierarchy.get_auth_info(urn)
205 site_record = RegAuthority(hrn=site_hrn, gid=auth_info.get_gid_object(),
206 pointer=site['site_id'],
207 authority=get_authority(site_hrn))
208 site_record.just_created()
209 dbsession.add(site_record)
211 self.logger.info("PlImporter: imported authority (site) : %s" % site_record)
212 self.remember_record (site_record)
214 # if the site import fails then there is no point in trying to import the
215 # site's child records (node, slices, persons), so skip them.
216 self.logger.log_exc("PlImporter: failed to import site %s. Skipping child records"%site_hrn)
219 # xxx update the record ...
221 site_record.stale=False
223 # import node records
224 for node_id in site['node_ids']:
226 node = nodes_by_id[node_id]
228 self.logger.warning ("PlImporter: cannot find node_id %s - ignored"%node_id)
230 site_auth = get_authority(site_hrn)
231 site_name = site['login_base']
232 node_hrn = hostname_to_hrn(site_auth, site_name, node['hostname'])
233 # xxx this sounds suspicious
234 if len(node_hrn) > 64: node_hrn = node_hrn[:64]
235 node_record = self.locate_by_type_hrn ( 'node', node_hrn )
238 pkey = Keypair(create=True)
239 urn = hrn_to_urn(node_hrn, 'node')
240 node_gid = self.auth_hierarchy.create_gid(urn, create_uuid(), pkey)
241 node_record = RegNode (hrn=node_hrn, gid=node_gid,
242 pointer =node['node_id'],
243 authority=get_authority(node_hrn))
244 node_record.just_created()
245 dbsession.add(node_record)
247 self.logger.info("PlImporter: imported node: %s" % node_record)
248 self.remember_record (node_record)
250 self.logger.log_exc("PlImporter: failed to import node %s"%node_hrn)
253 # xxx update the record ...
255 node_record.stale=False
259 for person_id in site['person_ids']:
261 if person_id in persons_by_id:
262 person=persons_by_id[person_id]
264 elif person_id in disabled_person_ids:
267 self.logger.warning ("PlImporter: cannot locate person_id %s in site %s - ignored"%(person_id,site_hrn))
268 # make sure to NOT run this if anything is wrong
269 if not proceed: continue
271 person_hrn = email_to_hrn(site_hrn, person['email'])
272 # xxx suspicious again
273 if len(person_hrn) > 64: person_hrn = person_hrn[:64]
274 person_urn = hrn_to_urn(person_hrn, 'user')
276 user_record = self.locate_by_type_hrn ( 'user', person_hrn)
278 # return a tuple pubkey (a plc key object) and pkey (a Keypair object)
279 def init_person_key (person, plc_keys):
281 if person['key_ids']:
282 # randomly pick first key in set
285 pkey = convert_public_key(pubkey['key'])
287 self.logger.warn('PlImporter: unable to convert public key for %s' % person_hrn)
288 pkey = Keypair(create=True)
290 # the user has no keys. Creating a random keypair for the user's gid
291 self.logger.warn("PlImporter: person %s does not have a PL public key"%person_hrn)
292 pkey = Keypair(create=True)
293 return (pubkey, pkey)
297 plc_keys = keys_by_person_id.get(person['person_id'],[])
299 (pubkey,pkey) = init_person_key (person, plc_keys )
300 person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey)
301 person_gid.set_email(person['email'])
302 user_record = RegUser (hrn=person_hrn, gid=person_gid,
303 pointer=person['person_id'],
304 authority=get_authority(person_hrn),
305 email=person['email'])
307 user_record.reg_keys=[RegKey (pubkey['key'], pubkey['key_id'])]
309 self.logger.warning("No key found for user %s"%user_record)
310 user_record.just_created()
311 dbsession.add (user_record)
313 self.logger.info("PlImporter: imported person: %s" % user_record)
314 self.remember_record ( user_record )
316 # update the record ?
317 # if user's primary key has changed then we need to update the
318 # users gid by forcing an update here
319 sfa_keys = user_record.reg_keys
320 def key_in_list (key,sfa_keys):
321 for reg_key in sfa_keys:
322 if reg_key.key==key['key']: return True
324 # is there a new key in myplc ?
327 if not key_in_list (key,sfa_keys):
330 (pubkey,pkey) = init_person_key (person, plc_keys)
331 person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey)
333 user_record.reg_keys=[]
335 user_record.reg_keys=[ RegKey (pubkey['key'], pubkey['key_id'])]
336 self.logger.info("PlImporter: updated person: %s" % user_record)
337 user_record.email = person['email']
339 user_record.stale=False
340 # accumulate PIs - PLCAPI has a limitation that when someone has PI role
341 # this is valid for all sites she is in..
342 # PI is coded with role_id==20
343 if 20 in person['role_ids']:
344 site_pis.append (user_record)
346 self.logger.log_exc("PlImporter: failed to import person %d %s"%(person['person_id'],person['email']))
348 # maintain the list of PIs for a given site
349 # for the record, Jordan had proposed the following addition as a welcome hotfix to a previous version:
350 # site_pis = list(set(site_pis))
351 # this was likely due to a bug in the above logic,
352 # that had to do with enabled persons, and where the whole loop on persons
353 # could be performed twice with the same person...
354 # so hopefully we do not need to eliminate duplicates explicitly here anymore
355 site_record.reg_pis = site_pis
359 for slice_id in site['slice_ids']:
361 slice = slices_by_id[slice_id]
363 self.logger.warning ("PlImporter: cannot locate slice_id %s - ignored"%slice_id)
364 slice_hrn = slicename_to_hrn(interface_hrn, slice['name'])
365 slice_record = self.locate_by_type_hrn ('slice', slice_hrn)
368 pkey = Keypair(create=True)
369 urn = hrn_to_urn(slice_hrn, 'slice')
370 slice_gid = self.auth_hierarchy.create_gid(urn, create_uuid(), pkey)
371 slice_record = RegSlice (hrn=slice_hrn, gid=slice_gid,
372 pointer=slice['slice_id'],
373 authority=get_authority(slice_hrn))
374 slice_record.just_created()
375 dbsession.add(slice_record)
377 self.logger.info("PlImporter: imported slice: %s" % slice_record)
378 self.remember_record ( slice_record )
380 self.logger.log_exc("PlImporter: failed to import slice %s (%s)"%(slice_hrn,slice['name']))
382 # xxx update the record ...
383 # given that we record the current set of users anyways, there does not seem to be much left to do here
384 # self.logger.warning ("Slice update not yet implemented on slice %s (%s)"%(slice_hrn,slice['name']))
386 # record current users affiliated with the slice
387 slice_record.reg_researchers = \
388 [ self.locate_by_type_pointer ('user',user_id) for user_id in slice['person_ids'] ]
390 slice_record.stale=False
392 ### remove stale records
393 # special records must be preserved
394 system_hrns = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
395 for record in all_records:
396 if record.hrn in system_hrns:
398 if record.peer_authority:
400 if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
401 record.hrn.endswith("internet2"):
404 for record in all_records:
405 try: stale=record.stale
408 self.logger.warning("stale not found with %s"%record)
410 self.logger.info("PlImporter: deleting stale record: %s" % record)
411 dbsession.delete(record)