prettyfied - spaces
[sfa.git] / sfa / planetlab / plslices.py
index 4211726..68681ca 100644 (file)
@@ -15,7 +15,7 @@ MAXINT =  2L**31-1
 
 class PlSlices:
 
-    rspec_to_slice_tag = {'max_rate':'net_max_rate'}
+    rspec_to_slice_tag = {'max_rate' : 'net_max_rate'}
 
     def __init__(self, driver):
         self.driver = driver
@@ -112,7 +112,8 @@ class PlSlices:
 
             # XXX Sanity check; though technically this should be a system invariant
             # checked with an assertion
-            if slice['expires'] > MAXINT:  slice['expires']= MAXINT
+            if slice['expires'] > MAXINT:
+                slice['expires'] = MAXINT
             
             slivers.append({
                 'hrn': hrn,
@@ -242,7 +243,7 @@ class PlSlices:
         for node in resulting_nodes:
             client_id = slivers[node['hostname']]['client_id']
             component_id = slivers[node['hostname']]['component_id']
-            sliver_hrn = '%s.%s-%s' % (self.driver.hrn, slice['slice_id'], node['node_id'])
+            sliver_hrn = '{}.{}-{}'.format(self.driver.hrn, slice['slice_id'], node['node_id'])
             sliver_id = Xrn(sliver_hrn, type='sliver').urn
             record = SliverAllocation(sliver_id=sliver_id, client_id=client_id, 
                                       component_id=component_id,
@@ -344,7 +345,7 @@ class PlSlices:
             site = sites[0]
         else:
             # create new site record
-            site = {'name': 'sfa:%s' % site_hrn,
+            site = {'name': 'sfa:{}'.format(site_hrn),
                     'abbreviated_name': site_hrn,
                     'login_base': login_base,
                     'max_slices': 100,
@@ -355,6 +356,8 @@ class PlSlices:
                     'sfa_created': 'True',
             }
             site_id = self.driver.shell.AddSite(site)
+            # plcapi tends to mess with the incoming hrn so let's make sure
+            self.driver.shell.SetSiteHrn (site_id, site_hrn)
             site['site_id'] = site_id
             # exempt federated sites from monitor policies
             self.driver.shell.AddSiteTag(site_id, 'exempt_site_until', "20200101")
@@ -396,10 +399,15 @@ class PlSlices:
                      'description': description,
                      'hrn': slice_hrn,
                      'sfa_created': 'True',
-                     'expires': expires,
+                     #'expires': expires,
             }
             # add the slice
             slice_id = self.driver.shell.AddSlice(slice)
+            # plcapi tends to mess with the incoming hrn so let's make sure
+            self.driver.shell.SetSliceHrn (slice_id, slice_hrn)
+            # cannot be set with AddSlice
+            # set the expiration
+            self.driver.shell.UpdateSlice(slice_id, {'expires': expires})
 
         return self.driver.shell.GetSlices(slice_id)[0]
 
@@ -410,24 +418,45 @@ class PlSlices:
     #        'slice_record': it seems like the first of these 'users' also contains a 'slice_record' 
     #           key that holds stuff like 'hrn', 'slice_id', 'authority',...
     # 
-    def create_person (self, user, site_id):
+    def create_person_from_user (self, user, site_id):
         user_hrn = user['hrn']
-        # the value to use if 'user' has no 'email' attached - xxx should be configurable
-        default_email = "%s@geni.net"%user_hrn.split('.')[-1]
-        # PLCAPI requires at least these to be set
+        # the value to use if 'user' has no 'email' attached - or if the attached email already exists
+        # typically 
+        ( auth_hrn, _ , leaf ) = user_hrn.rpartition('.')
+        # somehow this has backslashes, get rid of them
+        auth_hrn = auth_hrn.replace('\\','')
+        default_email = "{}@{}.stub".format(leaf, auth_hrn)
 
         person_record = { 
+            # required
             'first_name': user.get('first_name',user_hrn),
             'last_name': user.get('last_name',user_hrn),
             'email': user.get('email', default_email),
+            # our additions
             'enabled': True,
             'sfa_created': 'True',
             'hrn': user_hrn,
         }
 
-        person_id = int (self.driver.shell.AddPerson(person_record))
+        logger.debug ("about to attempt to AddPerson with {}".format(person_record))
+        try:
+            # the thing is, the PLE db has a limitation on re-using the same e-mail
+            # in the case where people have an account on ple.upmc and then then come 
+            # again from onelab.upmc, they will most likely have the same e-mail, and so kaboom..
+            # so we first try with the accurate email
+            person_id = int (self.driver.shell.AddPerson(person_record))
+        except:
+            logger.log_exc("caught during first attempt at AddPerson")
+            # and if that fails we start again with the email based on the hrn, which this time is unique..
+            person_record['email'] = default_email
+            logger.debug ("second chance with email={}".format(person_record['email']))
+            person_id = int (self.driver.shell.AddPerson(person_record))
         self.driver.shell.AddRoleToPerson('user', person_id)
-        self.driver.shell.AddPersonToSite(person_id, site['site_id'])
+        self.driver.shell.AddPersonToSite(person_id, site_id)
+        # plcapi tends to mess with the incoming hrn so let's make sure
+        self.driver.shell.SetPersonHrn (person_id, user_hrn)
+        # also 'enabled':True does not seem to pass through with AddPerson
+        self.driver.shell.UpdatePerson (person_id, {'enabled': True})
 
         return person_id
 
@@ -440,6 +469,8 @@ class PlSlices:
         # this is for retrieving users from a hrn
         users_by_hrn = { user['hrn'] : user for user in users }
 
+        for user in users: logger.debug("incoming user {}".format(user))
+
         # compute the hrn's for the authority and site
         top_auth_hrn = top_auth(slice_hrn)
         site_hrn = '.'.join(slice_hrn.split('.')[:-1])
@@ -472,7 +503,7 @@ class PlSlices:
         existing_hrns = [ person['hrn'] for person in target_existing_persons ]
         tocreate_hrns = set (target_hrns) - set (existing_hrns)
         # create these
-        target_created_person_ids = [ self.create_person (users_by_hrn[hrn], site_id) for hrn in tocreate_hrns ]
+        target_created_person_ids = [ self.create_person_from_user (users_by_hrn[hrn], site_id) for hrn in tocreate_hrns ]
 
         # we can partition the persons of interest into one of these 3 classes
         add_person_ids  = set(target_created_person_ids) | set(target_existing_person_ids) - set(slice_person_ids)
@@ -487,8 +518,8 @@ class PlSlices:
         # and for this we need all the Person objects; we already have the target_existing ones
         # also we avoid issuing a call if possible
         target_created_persons = [] if not target_created_person_ids \
-                                 else driver.shell.GetPersons ({'peer_id':None, 'person_id':target_created_person_ids},
-                                                               person_fields)
+                                 else self.driver.shell.GetPersons \
+                                      ({'peer_id':None, 'person_id':target_created_person_ids}, person_fields)
         persons_by_person_id = { person['person_id'] : person \
                                  for person in target_existing_persons + target_created_persons }
 
@@ -526,71 +557,83 @@ class PlSlices:
                   self.driver.shell.AddPersonKey(int(person_id), key)
 
 
+    # incoming data (attributes) have a (name, value) pair
+    # while PLC data (tags) have a (tagname, value) pair
+    # we must be careful not to mix these up
     def verify_slice_attributes(self, slice, requested_slice_attributes, options=None, admin=False):
         if options is None: options={}
         append = options.get('append', True)
-        # get list of attributes users ar able to manage
+        logger.debug("verify_slice_attributes, append mode: {}".format(append))
+        for requested_slice_attribute in requested_slice_attributes:
+            logger.debug("verify_slice_attributes, incoming req : {}".format(requested_slice_attribute))
+        # get list of tags users are able to manage - based on category
         filter = {'category': '*slice*'}
         if not admin:
             filter['|roles'] = ['user']
-        slice_attributes = self.driver.shell.GetTagTypes(filter)
-        valid_slice_attribute_names = [attribute['tagname'] for attribute in slice_attributes]
+        valid_tag_types = self.driver.shell.GetTagTypes(filter)
+        valid_tag_names = [ tag_type['tagname'] for tag_type in valid_tag_types ]
+        logger.debug("verify_slice_attributes: valid names={}".format(valid_tag_names))
 
-        # get sliver attributes
-        added_slice_attributes = []
-        removed_slice_attributes = []
+        # get slice tags
+        slice_attributes_to_add = []
+        slice_tags_to_remove = []
         # we need to keep the slice hrn anyway
-        ignored_slice_attribute_names = ['hrn']
-        existing_slice_attributes = self.driver.shell.GetSliceTags({'slice_id': slice['slice_id']})
+        ignored_slice_tag_names = ['hrn']
+        existing_slice_tags = self.driver.shell.GetSliceTags({'slice_id': slice['slice_id']})
 
-        # get attributes that should be removed
-        for slice_tag in existing_slice_attributes:
-            if slice_tag['tagname'] in ignored_slice_attribute_names:
+        # get tags that should be removed
+        for slice_tag in existing_slice_tags:
+            if slice_tag['tagname'] in ignored_slice_tag_names:
                 # If a slice already has a admin only role it was probably given to them by an
                 # admin, so we should ignore it.
-                ignored_slice_attribute_names.append(slice_tag['tagname'])
-                attribute_found=True
+                ignored_slice_tag_names.append(slice_tag['tagname'])
+                tag_found = True
             else:
-                # If an existing slice attribute was not found in the request it should
+                # If an existing slice tag was not found in the request it should
                 # be removed
-                attribute_found=False
+                tag_found = False
                 for requested_attribute in requested_slice_attributes:
                     if requested_attribute['name'] == slice_tag['tagname'] and \
                        requested_attribute['value'] == slice_tag['value']:
-                        attribute_found=True
+                        tag_found = True
                         break
+            # preserve missing tags in append mode
+            if not tag_found and not append:
+                slice_tags_to_remove.append(slice_tag)
 
-            if not attribute_found and not append:
-                removed_slice_attributes.append(slice_tag)
-
-        # get attributes that should be added:
+        # get tags that should be added:
         for requested_attribute in requested_slice_attributes:
             # if the requested attribute wasn't found  we should add it
-            if requested_attribute['name'] in valid_slice_attribute_names:
-                attribute_found = False
-                for existing_attribute in existing_slice_attributes:
+            if requested_attribute['name'] in valid_tag_names:
+                tag_found = False
+                for existing_attribute in existing_slice_tags:
                     if requested_attribute['name'] == existing_attribute['tagname'] and \
                        requested_attribute['value'] == existing_attribute['value']:
-                        attribute_found=True
+                        tag_found = True
                         break
-                if not attribute_found:
-                    added_slice_attributes.append(requested_attribute)
-
-
-        # remove stale attributes
-        for attribute in removed_slice_attributes:
+                if not tag_found:
+                    slice_attributes_to_add.append(requested_attribute)
+
+        def friendly_message (tag_or_att):
+            name = tag_or_att['tagname'] if 'tagname' in tag_or_att else tag_or_att['name']
+            return "SliceTag slice={}, tagname={} value={}, node_id={}"\
+                .format(slice['name'], tag_or_att['name'], tag_or_att['value'], tag_or_att.get('node_id'))
+                    
+        # remove stale tags
+        for tag in slice_tags_to_remove:
             try:
-                self.driver.shell.DeleteSliceTag(attribute['slice_tag_id'])
-            except Exception, e:
-                logger.warn('Failed to remove sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
-                                % (slice['name'], attribute['value'],  attribute.get('node_id'), str(e)))
-
-        # add requested_attributes
-        for attribute in added_slice_attributes:
+                logger.info("Removing Slice Tag {}".format(friendly_message(tag)))
+                self.driver.shell.DeleteSliceTag(tag['slice_tag_id'])
+            except Exception as e:
+                logger.warn("Failed to remove slice tag {}\nCause:{}"\
+                            .format(friendly_message(tag), e))
+
+        # add requested_tags
+        for attribute in slice_attributes_to_add:
             try:
+                logger.info("Adding Slice Tag {}".format(friendly_message(attribute)))
                 self.driver.shell.AddSliceTag(slice['name'], attribute['name'], 
                                               attribute['value'], attribute.get('node_id', None))
-            except Exception, e:
-                logger.warn('Failed to add sliver attribute. name: %s, value: %s, node_id: %s\nCause:%s'\
-                                % (slice['name'], attribute['value'],  attribute.get('node_id'), str(e)))
-
+            except Exception as e:
+                logger.warn("Failed to add slice tag {}\nCause:{}"\
+                            .format(friendly_message(attribute), e))