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