Merge Master in geni-v3 conflict resolution
[sfa.git] / sfa / importer / plimporter.py
index 9fe4316..8d197b6 100644 (file)
@@ -82,17 +82,20 @@ class PlImporter:
     def locate_by_type_pointer (self, type, pointer):
         return self.records_by_type_pointer.get ( (type, pointer), None)
 
-    # convenience : try to locate first based on type+pointer
-    # if so, the record was created already even if e.g. its hrn has changed meanwhile
-    # otherwise we try by type+hrn (is this truly useful ?)
-    def locate (self, type, hrn=None, pointer=-1):
-        if pointer!=-1:
-            attempt = self.locate_by_type_pointer (type, pointer)
-            if attempt : return attempt
-        if hrn is not None:
-            attempt = self.locate_by_type_hrn (type, hrn,)
-            if attempt : return attempt
-        return None
+    # a convenience/helper function to see if a record is already known
+    # a former, broken, attempt (in 2.1-9) had been made 
+    # to try and use 'pointer' as a first, most significant attempt
+    # the idea being to preserve stuff as much as possible, and thus 
+    # to avoid creating a new gid in the case of a simple hrn rename
+    # however this of course doesn't work as the gid depends on the hrn...
+    #def locate (self, type, hrn=None, pointer=-1):
+    #    if pointer!=-1:
+    #        attempt = self.locate_by_type_pointer (type, pointer)
+    #        if attempt : return attempt
+    #    if hrn is not None:
+    #        attempt = self.locate_by_type_hrn (type, hrn,)
+    #        if attempt : return attempt
+    #    return None
 
     # this makes the run method a bit abtruse - out of the way
     def create_special_vini_record (self, interface_hrn):
@@ -150,6 +153,9 @@ class PlImporter:
                                    ['person_id', 'email', 'key_ids', 'site_ids', 'role_ids'])
         # create a hash of persons by person_id
         persons_by_id = dict ( [ ( person['person_id'], person) for person in persons ] )
+        # also gather non-enabled user accounts so as to issue relevant warnings
+        disabled_persons = shell.GetPersons({'peer_id': None, 'enabled': False}, ['person_id'])
+        disabled_person_ids = [ person['person_id'] for person in disabled_persons ] 
         # Get all plc public keys
         # accumulate key ids for keys retrieval
         key_ids = []
@@ -164,9 +170,13 @@ class PlImporter:
         for person in persons:
             pubkeys = []
             for key_id in person['key_ids']:
-                key = keys_by_id[key_id]
-                if key['key_type'] == 'ssh': 
+                # by construction all the keys we fetched are ssh keys
+                # so gpg keys won't be in there
+                try:
+                    key = keys_by_id[key_id]
                     pubkeys.append(key)
+                except:
+                    self.logger.warning("Could not spot key %d - probably non-ssh"%key_id)
             keys_by_person_id[person['person_id']] = pubkeys
         # Get all plc nodes  
         nodes = shell.GetNodes( {'peer_id': None}, ['node_id', 'hostname', 'site_id'])
@@ -185,7 +195,7 @@ class PlImporter:
             site_hrn = _get_site_hrn(interface_hrn, site)
             # import if hrn is not in list of existing hrns or if the hrn exists
             # but its not a site record
-            site_record=self.locate ('authority', site_hrn, site['site_id'])
+            site_record=self.locate_by_type_hrn ('authority', site_hrn)
             if not site_record:
                 try:
                     urn = hrn_to_urn(site_hrn, 'authority')
@@ -203,7 +213,7 @@ class PlImporter:
                 except:
                     # if the site import fails then there is no point in trying to import the
                     # site's child records (node, slices, persons), so skip them.
-                    self.logger.log_exc("PlImporter: failed to import site. Skipping child records"
+                    self.logger.log_exc("PlImporter: failed to import site %s. Skipping child records"%site_hrn
                     continue 
             else:
                 # xxx update the record ...
@@ -222,7 +232,7 @@ class PlImporter:
                 node_hrn =  hostname_to_hrn(site_auth, site_name, node['hostname'])
                 # xxx this sounds suspicious
                 if len(node_hrn) > 64: node_hrn = node_hrn[:64]
-                node_record = self.locate ( 'node', node_hrn , node['node_id'] )
+                node_record = self.locate_by_type_hrn ( 'node', node_hrn )
                 if not node_record:
                     try:
                         pkey = Keypair(create=True)
@@ -237,25 +247,33 @@ class PlImporter:
                         self.logger.info("PlImporter: imported node: %s" % node_record)  
                         self.remember_record (node_record)
                     except:
-                        self.logger.log_exc("PlImporter: failed to import node") 
+                        self.logger.log_exc("PlImporter: failed to import node %s"%node_hrn) 
+                        continue
                 else:
                     # xxx update the record ...
                     pass
                 node_record.stale=False
 
-            site_pis=[]
+            site_pis=set()
             # import persons
             for person_id in site['person_ids']:
-                try:
-                    person = persons_by_id[person_id]
-                except:
-                    self.logger.warning ("PlImporter: cannot locate person_id %s - ignored"%person_id)
+                proceed=False
+                if person_id in persons_by_id:
+                    person=persons_by_id[person_id]
+                    proceed=True
+                elif person_id in disabled_person_ids:
+                    pass
+                else:
+                    self.logger.warning ("PlImporter: cannot locate person_id %s in site %s - ignored"%(person_id,site_hrn))
+                # make sure to NOT run this if anything is wrong
+                if not proceed: continue
+
                 person_hrn = email_to_hrn(site_hrn, person['email'])
                 # xxx suspicious again
                 if len(person_hrn) > 64: person_hrn = person_hrn[:64]
                 person_urn = hrn_to_urn(person_hrn, 'user')
 
-                user_record = self.locate ( 'user', person_hrn, person['person_id'])
+                user_record = self.locate_by_type_hrn ( 'user', person_hrn)
 
                 # return a tuple pubkey (a plc key object) and pkey (a Keypair object)
                 def init_person_key (person, plc_keys):
@@ -279,12 +297,11 @@ class PlImporter:
                     plc_keys = keys_by_person_id.get(person['person_id'],[])
                     if not user_record:
                         (pubkey,pkey) = init_person_key (person, plc_keys )
-                        person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey)
-                        person_gid.set_email(person['email'])
+                        person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey, email=person['email'])
                         user_record = RegUser (hrn=person_hrn, gid=person_gid, 
-                                                 pointer=person['person_id'], 
-                                                 authority=get_authority(person_hrn),
-                                                 email=person['email'])
+                                               pointer=person['person_id'], 
+                                               authority=get_authority(person_hrn),
+                                               email=person['email'])
                         if pubkey: 
                             user_record.reg_keys=[RegKey (pubkey['key'], pubkey['key_id'])]
                         else:
@@ -296,25 +313,47 @@ class PlImporter:
                         self.remember_record ( user_record )
                     else:
                         # update the record ?
-                        # if user's primary key has changed then we need to update the 
+                        #
+                        # if a user key has changed then we need to update the
                         # users gid by forcing an update here
+                        #
+                        # right now, SFA only has *one* key attached to a user, and this is
+                        # the key that the GID was made with
+                        # so the logic here is, we consider that things are OK (unchanged) if
+                        # all the SFA keys are present as PLC keys
+                        # otherwise we trigger the creation of a new gid from *some* plc key
+                        # and record this on the SFA side
+                        # it would make sense to add a feature in PLC so that one could pick a 'primary'
+                        # key but this is not available on the myplc side for now
+                        # = or = it would be much better to support several keys in SFA but that
+                        # does not seem doable without a major overhaul in the data model as
+                        # a GID is attached to a hrn, but it's also linked to a key, so...
+                        # NOTE: with this logic, the first key entered in PLC remains the one
+                        # current in SFA until it is removed from PLC
                         sfa_keys = user_record.reg_keys
-                        def key_in_list (key,sfa_keys):
-                            for reg_key in sfa_keys:
-                                if reg_key.key==key['key']: return True
+                        def sfa_key_in_list (sfa_key,plc_keys):
+                            for plc_key in plc_keys:
+                                if plc_key['key']==sfa_key.key:
+                                    return True
                             return False
-                        # is there a new key in myplc ?
+                        # are all the SFA keys known to PLC ?
                         new_keys=False
-                        for key in plc_keys:
-                            if not key_in_list (key,sfa_keys):
-                                new_keys = True
+                        if not sfa_keys and plc_keys:
+                            new_keys=True
+                        else: 
+                            for sfa_key in sfa_keys:
+                                 if not sfa_key_in_list (sfa_key,plc_keys):
+                                     new_keys = True
                         if new_keys:
                             (pubkey,pkey) = init_person_key (person, plc_keys)
                             person_gid = self.auth_hierarchy.create_gid(person_urn, create_uuid(), pkey)
+                            person_gid.set_email(person['email'])
                             if not pubkey:
                                 user_record.reg_keys=[]
                             else:
                                 user_record.reg_keys=[ RegKey (pubkey['key'], pubkey['key_id'])]
+                            user_record.gid = person_gid
+                            user_record.just_updated()
                             self.logger.info("PlImporter: updated person: %s" % user_record)
                     user_record.email = person['email']
                     dbsession.commit()
@@ -323,12 +362,14 @@ class PlImporter:
                     # this is valid for all sites she is in..
                     # PI is coded with role_id==20
                     if 20 in person['role_ids']:
-                        site_pis.append (user_record)
+                        site_pis.add (user_record)
                 except:
                     self.logger.log_exc("PlImporter: failed to import person %d %s"%(person['person_id'],person['email']))
     
             # maintain the list of PIs for a given site
+            site_record.reg_pis = list(site_pis)
             site_record.reg_pis = site_pis
+            dbsession.commit()
 
             # import slices
             for slice_id in site['slice_ids']:
@@ -337,7 +378,7 @@ class PlImporter:
                 except:
                     self.logger.warning ("PlImporter: cannot locate slice_id %s - ignored"%slice_id)
                 slice_hrn = slicename_to_hrn(interface_hrn, slice['name'])
-                slice_record = self.locate ('slice', slice_hrn, slice['slice_id'])
+                slice_record = self.locate_by_type_hrn ('slice', slice_hrn)
                 if not slice_record:
                     try:
                         pkey = Keypair(create=True)
@@ -352,11 +393,15 @@ class PlImporter:
                         self.logger.info("PlImporter: imported slice: %s" % slice_record)  
                         self.remember_record ( slice_record )
                     except:
-                        self.logger.log_exc("PlImporter: failed to import slice")
+                        self.logger.log_exc("PlImporter: failed to import slice %s (%s)"%(slice_hrn,slice['name']))
                 else:
+                    # update the pointer if it has changed
+                    if slice_id != slice_record.pointer:
+                        self.logger.info("updating record (slice) pointer")
+                        slice_record.pointer = slice_id
+                        dbsession.commit()             
                     # xxx update the record ...
-                    self.logger.warning ("Slice update not yet implemented")
-                    pass
+                    #self.logger.warning ("Slice update not yet implemented")
                 # record current users affiliated with the slice
                 slice_record.reg_researchers = \
                     [ self.locate_by_type_pointer ('user',user_id) for user_id in slice['person_ids'] ]