more pep8-friendly
[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(
311                         "PlImporter: cannot locate person_id {} in site {} - ignored"
312                         .format(person_id, site_hrn))
313                 # make sure to NOT run this if anything is wrong
314                 if not proceed:
315                     continue
316
317                 #person_hrn = email_to_hrn(site_hrn, person['email'])
318                 person_hrn = person['hrn']
319                 if person_hrn is None:
320                     self.logger.warning(
321                         "Person {} has no hrn - skipped".format(person['email']))
322                     continue
323                 # xxx suspicious again
324                 if len(person_hrn) > 64:
325                     person_hrn = person_hrn[:64]
326                 person_urn = hrn_to_urn(person_hrn, 'user')
327
328                 user_record = self.locate_by_type_hrn('user', person_hrn)
329
330                 # return a tuple pubkey (a plc key object) and pkey (a Keypair
331                 # object)
332                 def init_person_key(person, plc_keys):
333                     pubkey = None
334                     if person['key_ids']:
335                         # randomly pick first key in set
336                         pubkey = plc_keys[0]
337                         try:
338                             pkey = convert_public_key(pubkey['key'])
339                         except:
340                             self.logger.warning(
341                                 'PlImporter: unable to convert public key for {}'
342                                 .format(person_hrn))
343                             pkey = Keypair(create=True)
344                     else:
345                         # the user has no keys. Creating a random keypair for
346                         # the user's gid
347                         self.logger.warning(
348                             "PlImporter: person {} does not have a PL public key"
349                             .format(person_hrn))
350                         pkey = Keypair(create=True)
351                     return (pubkey, pkey)
352
353                 # new person
354                 try:
355                     plc_keys = keys_by_person_id.get(person['person_id'], [])
356                     if not user_record:
357                         (pubkey, pkey) = init_person_key(person, plc_keys)
358                         person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey,
359                                                                     email=person['email'])
360                         user_record = RegUser(hrn=person_hrn, gid=person_gid,
361                                               pointer=person['person_id'],
362                                               authority=get_authority(
363                                                   person_hrn),
364                                               email=person['email'])
365                         if pubkey:
366                             user_record.reg_keys = [
367                                 RegKey(pubkey['key'], pubkey['key_id'])]
368                         else:
369                             self.logger.warning(
370                                 "No key found for user {}".format(user_record))
371                         user_record.just_created()
372                         global_dbsession.add(user_record)
373                         global_dbsession.commit()
374                         self.logger.info(
375                             "PlImporter: imported person: {}".format(user_record))
376                         self.remember_record(user_record)
377                     else:
378                         # update the record ?
379                         #
380                         # if a user key has changed then we need to update the
381                         # users gid by forcing an update here
382                         #
383                         # right now, SFA only has *one* key attached to a user, and this is
384                         # the key that the GID was made with
385                         # so the logic here is, we consider that things are OK (unchanged) if
386                         # all the SFA keys are present as PLC keys
387                         # otherwise we trigger the creation of a new gid from *some* plc key
388                         # and record this on the SFA side
389                         # it would make sense to add a feature in PLC so that one could pick a 'primary'
390                         # key but this is not available on the myplc side for now
391                         # = or = it would be much better to support several keys in SFA but that
392                         # does not seem doable without a major overhaul in the data model as
393                         # a GID is attached to a hrn, but it's also linked to a key, so...
394                         # NOTE: with this logic, the first key entered in PLC remains the one
395                         # current in SFA until it is removed from PLC
396                         sfa_keys = user_record.reg_keys
397
398                         def sfa_key_in_list(sfa_key, plc_keys):
399                             for plc_key in plc_keys:
400                                 if plc_key['key'] == sfa_key.key:
401                                     return True
402                             return False
403                         # are all the SFA keys known to PLC ?
404                         new_keys = False
405                         if not sfa_keys and plc_keys:
406                             new_keys = True
407                         else:
408                             for sfa_key in sfa_keys:
409                                 if not sfa_key_in_list(sfa_key, plc_keys):
410                                     new_keys = True
411                         if new_keys:
412                             (pubkey, pkey) = init_person_key(person, plc_keys)
413                             person_gid = self.auth_hierarchy.create_gid(
414                                 person_urn, create_uuid(), pkey)
415                             person_gid.set_email(person['email'])
416                             if not pubkey:
417                                 user_record.reg_keys = []
418                             else:
419                                 user_record.reg_keys = [
420                                     RegKey(pubkey['key'], pubkey['key_id'])]
421                             user_record.gid = person_gid
422                             user_record.just_updated()
423                             self.logger.info(
424                                 "PlImporter: updated person: {}".format(user_record))
425                     user_record.email = person['email']
426                     global_dbsession.commit()
427                     user_record.stale = False
428                     # accumulate PIs - PLCAPI has a limitation that when someone has PI role
429                     # this is valid for all sites she is in..
430                     # PI is coded with role_id == 20
431                     if 20 in person['role_ids']:
432                         site_pis.append(user_record)
433
434                     # PL Admins need to marked as PI of the top authority
435                     # record
436                     if 10 in person['role_ids'] and user_record not in top_auth_record.reg_pis:
437                         admins.append(user_record)
438
439                 except:
440                     self.logger.log_exc("PlImporter: failed to import person {} {}"
441                                         .format(person['person_id'], person['email']))
442
443             # maintain the list of PIs for a given site
444             # for the record, Jordan had proposed the following addition as a welcome hotfix to a previous version:
445             # site_pis = list(set(site_pis))
446             # this was likely due to a bug in the above logic, that had to do with disabled persons
447             # being improperly handled, and where the whole loop on persons
448             # could be performed twice with the same person...
449             # so hopefully we do not need to eliminate duplicates explicitly
450             # here anymore
451             site_record.reg_pis = list(set(site_pis))
452             global_dbsession.commit()
453
454             # import slices
455             for slice_id in site['slice_ids']:
456                 try:
457                     slice = slices_by_id[slice_id]
458                 except:
459                     self.logger.warning("PlImporter: cannot locate slice_id {} - ignored"
460                                         .format(slice_id))
461                     continue
462                 #slice_hrn = slicename_to_hrn(interface_hrn, slice['name'])
463                 slice_hrn = slice['hrn']
464                 if slice_hrn is None:
465                     self.logger.warning("Slice {} has no hrn - skipped"
466                                         .format(slice['name']))
467                     continue
468                 slice_record = self.locate_by_type_hrn('slice', slice_hrn)
469                 if not slice_record:
470                     try:
471                         pkey = Keypair(create=True)
472                         urn = hrn_to_urn(slice_hrn, 'slice')
473                         slice_gid = self.auth_hierarchy.create_gid(
474                             urn, create_uuid(), pkey)
475                         slice_record = RegSlice(hrn=slice_hrn, gid=slice_gid,
476                                                 pointer=slice['slice_id'],
477                                                 authority=get_authority(slice_hrn))
478                         slice_record.just_created()
479                         global_dbsession.add(slice_record)
480                         global_dbsession.commit()
481                         self.logger.info(
482                             "PlImporter: imported slice: {}".format(slice_record))
483                         self.remember_record(slice_record)
484                     except:
485                         self.logger.log_exc("PlImporter: failed to import slice {} ({})"
486                                             .format(slice_hrn, slice['name']))
487                 else:
488                     # xxx update the record ...
489                     # given that we record the current set of users anyways, there does not seem to be much left to do here
490                     # self.logger.warning ("Slice update not yet implemented on slice {} ({})"
491                     #                      .format(slice_hrn, slice['name']))
492                     pass
493                 # record current users affiliated with the slice
494                 slice_record.reg_researchers = \
495                     [self.locate_by_type_pointer('user', user_id) for user_id in slice[
496                         'person_ids']]
497                 # remove any weird value (looks like we can get 'None' here
498                 slice_record.reg_researchers = [
499                     x for x in slice_record.reg_researchers if x]
500                 global_dbsession.commit()
501                 slice_record.stale = False
502
503         # Set PL Admins as PI's of the top authority
504         if admins:
505             top_auth_record.reg_pis = list(set(admins))
506             global_dbsession.commit()
507             self.logger.info('PlImporter: set PL admins {} as PIs of {}'
508                              .format(admins, top_auth_record.hrn))
509
510         # remove stale records
511         # special records must be preserved
512         system_hrns = [interface_hrn, root_auth,
513                        interface_hrn + '.slicemanager']
514         for record in all_records:
515             if record.hrn in system_hrns:
516                 record.stale = False
517             if record.peer_authority:
518                 record.stale = False
519             if ".vini" in interface_hrn and interface_hrn.endswith('vini') and \
520                     record.hrn.endswith("internet2"):
521                 record.stale = False
522
523         for record in all_records:
524             try:
525                 stale = record.stale
526             except:
527                 stale = True
528                 self.logger.warning("stale not found with {}".format(record))
529             if stale:
530                 self.logger.info(
531                     "PlImporter: deleting stale record: {}".format(record))
532                 global_dbsession.delete(record)
533                 global_dbsession.commit()