c31aa9206b990eb7c0c6c2424f47034e3ecb9e42
[sfa.git] / sfa / importer / plimporter.py
1 #
2 # PlanetLab importer
3
4 # requirements
5
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)
17
18
19 import os
20
21 from sfa.util.config import Config
22 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn
23
24 from sfa.trust.gid import create_uuid    
25 from sfa.trust.certificate import convert_public_key, Keypair
26
27 # using global alchemy.session() here is fine 
28 # as importer is on standalone one-shot process
29 from sfa.storage.alchemy import global_dbsession
30 from sfa.storage.model import RegRecord, RegAuthority, RegSlice, RegNode, RegUser, RegKey
31
32 from sfa.planetlab.plshell import PlShell    
33 from sfa.planetlab.plxrn import hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
34
35 def _get_site_hrn(interface_hrn, site):
36     # Hardcode 'internet2' into the hrn for sites hosting
37     # internet2 nodes. This is a special operation for some vini
38     # sites only
39     hrn = ".".join([interface_hrn, site['login_base']]) 
40     if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
41         if site['login_base'].startswith("i2") or site['login_base'].startswith("nlr"):
42             hrn = ".".join([interface_hrn, "internet2", site['login_base']])
43     return hrn
44
45
46 class PlImporter:
47
48     def __init__ (self, auth_hierarchy, logger):
49         self.auth_hierarchy = auth_hierarchy
50         self.logger=logger
51
52     def add_options (self, parser):
53         # we don't have any options for now
54         pass
55
56     # hrn hash is initialized from current db
57     # remember just-created records as we go
58     # xxx might make sense to add a UNIQUE constraint in the db itself
59     def remember_record_by_hrn (self, record):
60         tuple = (record.type, record.hrn)
61         if tuple in self.records_by_type_hrn:
62             self.logger.warning ("PlImporter.remember_record_by_hrn: duplicate (%s,%s)"%tuple)
63             return
64         self.records_by_type_hrn [ tuple ] = record
65
66     # ditto for pointer hash
67     def remember_record_by_pointer (self, record):
68         if record.pointer == -1:
69             self.logger.warning ("PlImporter.remember_record_by_pointer: pointer is void")
70             return
71         tuple = (record.type, record.pointer)
72         if tuple in self.records_by_type_pointer:
73             self.logger.warning ("PlImporter.remember_record_by_pointer: duplicate (%s,%s)"%tuple)
74             return
75         self.records_by_type_pointer [ ( record.type, record.pointer,) ] = record
76
77     def remember_record (self, record):
78         self.remember_record_by_hrn (record)
79         self.remember_record_by_pointer (record)
80
81     def locate_by_type_hrn (self, type, hrn):
82         return self.records_by_type_hrn.get ( (type, hrn), None)
83
84     def locate_by_type_pointer (self, type, pointer):
85         return self.records_by_type_pointer.get ( (type, pointer), None)
86
87     # a convenience/helper function to see if a record is already known
88     # a former, broken, attempt (in 2.1-9) had been made 
89     # to try and use 'pointer' as a first, most significant attempt
90     # the idea being to preserve stuff as much as possible, and thus 
91     # to avoid creating a new gid in the case of a simple hrn rename
92     # however this of course doesn't work as the gid depends on the hrn...
93     #def locate (self, type, hrn=None, pointer=-1):
94     #    if pointer!=-1:
95     #        attempt = self.locate_by_type_pointer (type, pointer)
96     #        if attempt : return attempt
97     #    if hrn is not None:
98     #        attempt = self.locate_by_type_hrn (type, hrn,)
99     #        if attempt : return attempt
100     #    return None
101
102     # this makes the run method a bit abtruse - out of the way
103     def create_special_vini_record (self, interface_hrn):
104         # special case for vini
105         if ".vini" in interface_hrn and interface_hrn.endswith('vini'):
106             # create a fake internet2 site first
107             i2site = {'name': 'Internet2', 'login_base': 'internet2', 'site_id': -1}
108             site_hrn = _get_site_hrn(interface_hrn, i2site)
109             # import if hrn is not in list of existing hrns or if the hrn exists
110             # but its not a site record
111             if ( 'authority', site_hrn, ) not in self.records_by_type_hrn:
112                 urn = hrn_to_urn(site_hrn, 'authority')
113                 if not self.auth_hierarchy.auth_exists(urn):
114                     self.auth_hierarchy.create_auth(urn)
115                 auth_info = self.auth_hierarchy.get_auth_info(urn)
116                 auth_record = RegAuthority(hrn=site_hrn, gid=auth_info.get_gid_object(),
117                                            pointer=site['site_id'],
118                                            authority=get_authority(site_hrn))
119                 auth_record.just_created()
120                 global_dbsession.add(auth_record)
121                 global_dbsession.commit()
122                 self.logger.info("PlImporter: Imported authority (vini site) %s"%auth_record)
123                 self.remember_record ( site_record )
124
125     def run (self, options):
126         config = Config ()
127         interface_hrn = config.SFA_INTERFACE_HRN
128         root_auth = config.SFA_REGISTRY_ROOT_AUTH
129         shell = PlShell (config)
130
131         ######## retrieve all existing SFA objects
132         all_records = global_dbsession.query(RegRecord).all()
133
134         # create hash by (type,hrn) 
135         # we essentially use this to know if a given record is already known to SFA 
136         self.records_by_type_hrn = \
137             dict ( [ ( (record.type, record.hrn) , record ) for record in all_records ] )
138         # create hash by (type,pointer) 
139         self.records_by_type_pointer = \
140             dict ( [ ( (record.type, record.pointer) , record ) for record in all_records 
141                      if record.pointer != -1] )
142
143         # initialize record.stale to True by default, then mark stale=False on the ones that are in use
144         for record in all_records: record.stale=True
145
146         ######## retrieve PLC data
147         # Get all plc sites
148         # retrieve only required stuf
149         sites = shell.GetSites({'peer_id': None, 'enabled' : True},
150                                ['site_id','login_base','node_ids','slice_ids','person_ids', 'name', 'hrn'])
151         # create a hash of sites by login_base
152 #        sites_by_login_base = dict ( [ ( site['login_base'], site ) for site in sites ] )
153         # Get all plc users
154         persons = shell.GetPersons({'peer_id': None, 'enabled': True}, 
155                                    ['person_id', 'email', 'key_ids', 'site_ids', 'role_ids', 'hrn'])
156         # create a hash of persons by person_id
157         persons_by_id = dict ( [ ( person['person_id'], person) for person in persons ] )
158         # also gather non-enabled user accounts so as to issue relevant warnings
159         disabled_persons = shell.GetPersons({'peer_id': None, 'enabled': False}, ['person_id'])
160         disabled_person_ids = [ person['person_id'] for person in disabled_persons ] 
161         # Get all plc public keys
162         # accumulate key ids for keys retrieval
163         key_ids = []
164         for person in persons:
165             key_ids.extend(person['key_ids'])
166         keys = shell.GetKeys( {'peer_id': None, 'key_id': key_ids,
167                                'key_type': 'ssh'} )
168         # create a hash of keys by key_id
169         keys_by_id = dict ( [ ( key['key_id'], key ) for key in keys ] ) 
170         # create a dict person_id -> [ (plc)keys ]
171         keys_by_person_id = {} 
172         for person in persons:
173             pubkeys = []
174             for key_id in person['key_ids']:
175                 # by construction all the keys we fetched are ssh keys
176                 # so gpg keys won't be in there
177                 try:
178                     key = keys_by_id[key_id]
179                     pubkeys.append(key)
180                 except:
181                     self.logger.warning("Could not spot key %d - probably non-ssh"%key_id)
182             keys_by_person_id[person['person_id']] = pubkeys
183         # Get all plc nodes  
184         nodes = shell.GetNodes( {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
185         # create hash by node_id
186         nodes_by_id = dict ( [ ( node['node_id'], node, ) for node in nodes ] )
187         # Get all plc slices
188         slices = shell.GetSlices( {'peer_id': None}, ['slice_id', 'name', 'person_ids', 'hrn'])
189         # create hash by slice_id
190         slices_by_id = dict ( [ (slice['slice_id'], slice ) for slice in slices ] )
191
192         # isolate special vini case in separate method
193         self.create_special_vini_record (interface_hrn)
194
195         # Get top authority record
196         top_auth_record = self.locate_by_type_hrn ('authority', root_auth)
197         admins = []
198
199         # start importing 
200         for site in sites:
201             try:
202                site_sfa_created = shell.GetSiteSfaCreated(site['site_id'])
203             except: 
204                site_sfa_created = None
205             if site['name'].startswith('sfa:') or site_sfa_created == 'True':
206                 continue
207
208             #site_hrn = _get_site_hrn(interface_hrn, site)
209             site_hrn = site['hrn']
210             # import if hrn is not in list of existing hrns or if the hrn exists
211             # but its not a site record
212             site_record = self.locate_by_type_hrn ('authority', site_hrn)
213             if not site_record:
214                 try:
215                     urn = hrn_to_urn(site_hrn, 'authority')
216                     if not self.auth_hierarchy.auth_exists(urn):
217                         self.auth_hierarchy.create_auth(urn)
218                     auth_info = self.auth_hierarchy.get_auth_info(urn)
219                     site_record = RegAuthority(hrn=site_hrn, gid=auth_info.get_gid_object(),
220                                                pointer=site['site_id'],
221                                                authority=get_authority(site_hrn),
222                                                name=site['name'])
223                     site_record.just_created()
224                     global_dbsession.add(site_record)
225                     global_dbsession.commit()
226                     self.logger.info("PlImporter: imported authority (site) : %s" % site_record) 
227                     self.remember_record (site_record)
228                 except:
229                     # if the site import fails then there is no point in trying to import the
230                     # site's child records (node, slices, persons), so skip them.
231                     self.logger.log_exc("PlImporter: failed to import site %s. Skipping child records"%site_hrn) 
232                     continue 
233             else:
234                 # xxx update the record ...
235                 pass
236             site_record.stale=False
237              
238             # import node records
239             for node_id in site['node_ids']:
240                 try:
241                     node = nodes_by_id[node_id]
242                 except:
243                     self.logger.warning ("PlImporter: cannot find node_id %s - ignored"%node_id)
244                     continue 
245                 site_auth = get_authority(site_hrn)
246                 site_name = site['login_base']
247                 node_hrn =  hostname_to_hrn(site_auth, site_name, node['hostname'])
248                 # xxx this sounds suspicious
249                 if len(node_hrn) > 64: node_hrn = node_hrn[:64]
250                 node_record = self.locate_by_type_hrn ( 'node', node_hrn )
251                 if not node_record:
252                     try:
253                         pkey = Keypair(create=True)
254                         urn = hrn_to_urn(node_hrn, 'node')
255                         node_gid = self.auth_hierarchy.create_gid(urn, create_uuid(), pkey)
256                         node_record = RegNode (hrn=node_hrn, gid=node_gid, 
257                                                pointer =node['node_id'],
258                                                authority=get_authority(node_hrn))
259                         node_record.just_created()
260                         global_dbsession.add(node_record)
261                         global_dbsession.commit()
262                         self.logger.info("PlImporter: imported node: %s" % node_record)  
263                         self.remember_record (node_record)
264                     except:
265                         self.logger.log_exc("PlImporter: failed to import node %s"%node_hrn) 
266                         continue
267                 else:
268                     # xxx update the record ...
269                     pass
270                 node_record.stale=False
271
272             site_pis=[]
273             # import persons
274             for person_id in site['person_ids']:
275                 proceed=False
276                 if person_id in persons_by_id:
277                     person=persons_by_id[person_id]
278                     proceed=True
279                 elif person_id in disabled_person_ids:
280                     pass
281                 else:
282                     self.logger.warning ("PlImporter: cannot locate person_id %s in site %s - ignored"%(person_id,site_hrn))
283                 # make sure to NOT run this if anything is wrong
284                 if not proceed: continue
285
286                 #person_hrn = email_to_hrn(site_hrn, person['email'])
287                 person_hrn = person['hrn']
288                 if person_hrn is None:
289                     self.logger.warn("Person %s has no hrn - skipped"%person['email'])
290                     continue
291                 # xxx suspicious again
292                 if len(person_hrn) > 64: person_hrn = person_hrn[:64]
293                 person_urn = hrn_to_urn(person_hrn, 'user')
294
295                 user_record = self.locate_by_type_hrn ( 'user', person_hrn)
296
297                 # return a tuple pubkey (a plc key object) and pkey (a Keypair object)
298                 def init_person_key (person, plc_keys):
299                     pubkey=None
300                     if  person['key_ids']:
301                         # randomly pick first key in set
302                         pubkey = plc_keys[0]
303                         try:
304                             pkey = convert_public_key(pubkey['key'])
305                         except:
306                             self.logger.warn('PlImporter: unable to convert public key for %s' % person_hrn)
307                             pkey = Keypair(create=True)
308                     else:
309                         # the user has no keys. Creating a random keypair for the user's gid
310                         self.logger.warn("PlImporter: person %s does not have a PL public key"%person_hrn)
311                         pkey = Keypair(create=True)
312                     return (pubkey, pkey)
313
314                 # new person
315                 try:
316                     plc_keys = keys_by_person_id.get(person['person_id'],[])
317                     if not user_record:
318                         (pubkey,pkey) = init_person_key (person, plc_keys )
319                         person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey, email=person['email'])
320                         user_record = RegUser (hrn=person_hrn, gid=person_gid, 
321                                                pointer=person['person_id'], 
322                                                authority=get_authority(person_hrn),
323                                                email=person['email'])
324                         if pubkey: 
325                             user_record.reg_keys=[RegKey (pubkey['key'], pubkey['key_id'])]
326                         else:
327                             self.logger.warning("No key found for user %s"%user_record)
328                         user_record.just_created()
329                         global_dbsession.add (user_record)
330                         global_dbsession.commit()
331                         self.logger.info("PlImporter: imported person: %s" % user_record)
332                         self.remember_record ( user_record )
333                     else:
334                         # update the record ?
335                         #
336                         # if a user key has changed then we need to update the
337                         # users gid by forcing an update here
338                         #
339                         # right now, SFA only has *one* key attached to a user, and this is
340                         # the key that the GID was made with
341                         # so the logic here is, we consider that things are OK (unchanged) if
342                         # all the SFA keys are present as PLC keys
343                         # otherwise we trigger the creation of a new gid from *some* plc key
344                         # and record this on the SFA side
345                         # it would make sense to add a feature in PLC so that one could pick a 'primary'
346                         # key but this is not available on the myplc side for now
347                         # = or = it would be much better to support several keys in SFA but that
348                         # does not seem doable without a major overhaul in the data model as
349                         # a GID is attached to a hrn, but it's also linked to a key, so...
350                         # NOTE: with this logic, the first key entered in PLC remains the one
351                         # current in SFA until it is removed from PLC
352                         sfa_keys = user_record.reg_keys
353                         def sfa_key_in_list (sfa_key,plc_keys):
354                             for plc_key in plc_keys:
355                                 if plc_key['key']==sfa_key.key:
356                                     return True
357                             return False
358                         # are all the SFA keys known to PLC ?
359                         new_keys=False
360                         if not sfa_keys and plc_keys:
361                             new_keys=True
362                         else: 
363                             for sfa_key in sfa_keys:
364                                  if not sfa_key_in_list (sfa_key,plc_keys):
365                                      new_keys = True
366                         if new_keys:
367                             (pubkey,pkey) = init_person_key (person, plc_keys)
368                             person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey)
369                             person_gid.set_email(person['email'])
370                             if not pubkey:
371                                 user_record.reg_keys=[]
372                             else:
373                                 user_record.reg_keys=[ RegKey (pubkey['key'], pubkey['key_id'])]
374                             user_record.gid = person_gid
375                             user_record.just_updated()
376                             self.logger.info("PlImporter: updated person: %s" % user_record)
377                     user_record.email = person['email']
378                     global_dbsession.commit()
379                     user_record.stale=False
380                     # accumulate PIs - PLCAPI has a limitation that when someone has PI role
381                     # this is valid for all sites she is in..
382                     # PI is coded with role_id==20
383                     if 20 in person['role_ids']:
384                         site_pis.append (user_record)
385
386                     # PL Admins need to marked as PI of the top authority record
387                     if 10 in person['role_ids'] and user_record not in top_auth_record.reg_pis:
388                         admins.append(user_record)
389
390                 except:
391                     self.logger.log_exc("PlImporter: failed to import person %d %s"%(person['person_id'],person['email']))
392     
393             # maintain the list of PIs for a given site
394             # for the record, Jordan had proposed the following addition as a welcome hotfix to a previous version:
395             # site_pis = list(set(site_pis)) 
396             # this was likely due to a bug in the above logic, that had to do with disabled persons
397             # being improperly handled, and where the whole loop on persons
398             # could be performed twice with the same person...
399             # so hopefully we do not need to eliminate duplicates explicitly here anymore
400             site_record.reg_pis = list(set(site_pis))
401             global_dbsession.commit()
402
403             # import slices
404             for slice_id in site['slice_ids']:
405                 try:
406                     slice = slices_by_id[slice_id]
407                 except:
408                     self.logger.warning ("PlImporter: cannot locate slice_id %s - ignored"%slice_id)
409                     continue
410                 #slice_hrn = slicename_to_hrn(interface_hrn, slice['name'])
411                 slice_hrn = slice['hrn']
412                 if slice_hrn is None:
413                     self.logger.warning("Slice %s has no hrn - skipped"%slice['name'])
414                     continue
415                 slice_record = self.locate_by_type_hrn ('slice', slice_hrn)
416                 if not slice_record:
417                     try:
418                         pkey = Keypair(create=True)
419                         urn = hrn_to_urn(slice_hrn, 'slice')
420                         slice_gid = self.auth_hierarchy.create_gid(urn, create_uuid(), pkey)
421                         slice_record = RegSlice (hrn=slice_hrn, gid=slice_gid, 
422                                                  pointer=slice['slice_id'],
423                                                  authority=get_authority(slice_hrn))
424                         slice_record.just_created()
425                         global_dbsession.add(slice_record)
426                         global_dbsession.commit()
427                         self.logger.info("PlImporter: imported slice: %s" % slice_record)  
428                         self.remember_record ( slice_record )
429                     except:
430                         self.logger.log_exc("PlImporter: failed to import slice %s (%s)"%(slice_hrn,slice['name']))
431                 else:
432                     # xxx update the record ...
433                     # given that we record the current set of users anyways, there does not seem to be much left to do here
434                     # self.logger.warning ("Slice update not yet implemented on slice %s (%s)"%(slice_hrn,slice['name']))
435                     pass
436                 # record current users affiliated with the slice
437                 slice_record.reg_researchers = \
438                     [ self.locate_by_type_pointer ('user',user_id) for user_id in slice['person_ids'] ]
439                 global_dbsession.commit()
440                 slice_record.stale=False
441
442         # Set PL Admins as PI's of the top authority
443         if admins:
444             top_auth_record.reg_pis = list(set(admins))
445             global_dbsession.commit()
446             self.logger.info('PlImporter: set PL admins %s as PIs of %s'%(admins,top_auth_record.hrn))
447
448         ### remove stale records
449         # special records must be preserved
450         system_hrns = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
451         for record in all_records: 
452             if record.hrn in system_hrns: 
453                 record.stale=False
454             if record.peer_authority:
455                 record.stale=False
456             if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
457                 record.hrn.endswith("internet2"):
458                 record.stale=False
459
460         for record in all_records:
461             try:        stale=record.stale
462             except:     
463                 stale=True
464                 self.logger.warning("stale not found with %s"%record)
465             if stale:
466                 self.logger.info("PlImporter: deleting stale record: %s" % record)
467                 global_dbsession.delete(record)
468                 global_dbsession.commit()