Merge branch 'master' into senslab2
[sfa.git] / sfa / plc / pldriver.py
index 1eaa7e3..b9db9b2 100644 (file)
@@ -6,12 +6,13 @@ from sfa.util.faults import MissingSfaInfo, UnknownSfaType, \
 
 from sfa.util.sfalogging import logger
 from sfa.util.defaultdict import defaultdict
-from sfa.util.sfatime import utcparse, epochparse
+from sfa.util.sfatime import utcparse, datetime_to_string, datetime_to_epoch
 from sfa.util.xrn import hrn_to_urn, get_leaf, urn_to_sliver_id
 from sfa.util.cache import Cache
 
 # one would think the driver should not need to mess with the SFA db, but..
-from sfa.storage.table import SfaTable
+from sfa.storage.alchemy import dbsession
+from sfa.storage.model import RegRecord
 
 # used to be used in get_ticket
 #from sfa.trust.sfaticket import SfaTicket
@@ -109,7 +110,15 @@ class PlDriver (Driver):
                 self.shell.AddPersonToSite(pointer, login_base)
     
             # What roles should this user have?
-            self.shell.AddRoleToPerson('user', pointer)
+            roles=[]
+            if 'roles' in sfa_record: 
+                # if specified in xml, but only low-level roles
+                roles = [ role for role in sfa_record['roles'] if role in ['user','tech'] ]
+            # at least user if no other cluse could be found
+            if not roles:
+                roles=['user']
+            for role in roles:
+                self.shell.AddRoleToPerson(role, pointer)
             # Add the user's key
             if pub_key:
                 self.shell.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
@@ -206,7 +215,7 @@ class PlDriver (Driver):
 
 
     ##
-    # Convert SFA fields to PLC fields for use when registering up updating
+    # Convert SFA fields to PLC fields for use when registering or updating
     # registry record in the PLC database
     #
 
@@ -224,8 +233,10 @@ class PlDriver (Driver):
                pl_record["url"] = sfa_record["url"]
            if "description" in sfa_record:
                pl_record["description"] = sfa_record["description"]
-           if "expires" in sfa_record:
-               pl_record["expires"] = int(sfa_record["expires"])
+            if "expires" in sfa_record:
+                date = utcparse(sfa_record['expires'])
+                expires = datetime_to_epoch(date)
+                pl_record["expires"] = expires
 
         elif type == "node":
             if not "hostname" in pl_record:
@@ -400,6 +411,11 @@ class PlDriver (Driver):
                                if site_id in sites]
                 site_hrns = [".".join([auth_hrn, lbase]) for lbase in login_bases]
                 record['sites'] = site_hrns
+
+            if 'expires' in record:
+                date = utcparse(record['expires'])
+                datestring = datetime_to_string(date)
+                record['expires'] = datestring 
             
         return records   
 
@@ -439,16 +455,15 @@ class PlDriver (Driver):
         # we'll replace pl ids (person_ids) with hrns from the sfa records
         # we obtain
         
-        # get the sfa records
-        table = SfaTable()
+        # get the registry records
         person_list, persons = [], {}
-        person_list = table.find({'type': 'user', 'pointer': person_ids})
+        person_list = dbsession.query (RegRecord).filter(RegRecord.pointer.in_(person_ids))
         # create a hrns keyed on the sfa record's pointer.
         # Its possible for multiple records to have the same pointer so
         # the dict's value will be a list of hrns.
         persons = defaultdict(list)
         for person in person_list:
-            persons[person['pointer']].append(person)
+            persons[person.pointer].append(person)
 
         # get the pl records
         pl_person_list, pl_persons = [], {}
@@ -462,13 +477,14 @@ class PlDriver (Driver):
             #    continue 
             sfa_info = {}
             type = record['type']
+            logger.info("fill_record_sfa_info - incoming record typed %s"%type)
             if (type == "slice"):
                 # all slice users are researchers
                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
                 record['PI'] = []
                 record['researcher'] = []
                 for person_id in record.get('person_ids', []):
-                    hrns = [person['hrn'] for person in persons[person_id]]
+                    hrns = [person.hrn for person in persons[person_id]]
                     record['researcher'].extend(hrns)                
 
                 # pis at the slice's site
@@ -476,12 +492,13 @@ class PlDriver (Driver):
                     pl_pis = site_pis[record['site_id']]
                     pi_ids = [pi['person_id'] for pi in pl_pis]
                     for person_id in pi_ids:
-                        hrns = [person['hrn'] for person in persons[person_id]]
+                        hrns = [person.hrn for person in persons[person_id]]
                         record['PI'].extend(hrns)
                         record['geni_creator'] = record['PI'] 
                 
             elif (type.startswith("authority")):
                 record['url'] = None
+                logger.info("fill_record_sfa_info - authority xherex")
                 if record['pointer'] != -1:
                     record['PI'] = []
                     record['operator'] = []
@@ -490,7 +507,7 @@ class PlDriver (Driver):
                         if pointer not in persons or pointer not in pl_persons:
                             # this means there is not sfa or pl record for this user
                             continue   
-                        hrns = [person['hrn'] for person in persons[pointer]] 
+                        hrns = [person.hrn for person in persons[pointer]] 
                         roles = pl_persons[pointer]['roles']   
                         if 'pi' in roles:
                             record['PI'].extend(hrns)
@@ -504,6 +521,7 @@ class PlDriver (Driver):
                 # xxx TODO: URI, LatLong, IP, DNS
     
             elif (type == "user"):
+                logger.info('setting user.email')
                 sfa_info['email'] = record.get("email", "")
                 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
                 sfa_info['geni_certificate'] = record['gid'] 
@@ -618,6 +636,10 @@ class PlDriver (Driver):
         # report about the local nodes only
         nodes = self.shell.GetNodes({'node_id':slice['node_ids'],'peer_id':None},
                               ['node_id', 'hostname', 'site_id', 'boot_state', 'last_contact'])
+
+        if len(nodes) == 0:
+            raise SliverDoesNotExist("You have not allocated any slivers here") 
+
         site_ids = [node['site_id'] for node in nodes]
     
         result = {}
@@ -626,7 +648,7 @@ class PlDriver (Driver):
             top_level_status = 'ready'
         result['geni_urn'] = slice_urn
         result['pl_login'] = slice['name']
-        result['pl_expires'] = epochparse(slice['expires'])
+        result['pl_expires'] = datetime_to_string(utcparse(slice['expires']))
         
         resources = []
         for node in nodes:
@@ -635,7 +657,8 @@ class PlDriver (Driver):
             res['pl_boot_state'] = node['boot_state']
             res['pl_last_contact'] = node['last_contact']
             if node['last_contact'] is not None:
-                res['pl_last_contact'] = epochparse(node['last_contact'])
+                
+                res['pl_last_contact'] = datetime_to_string(utcparse(node['last_contact']))
             sliver_id = urn_to_sliver_id(slice_urn, slice['slice_id'], node['node_id']) 
             res['geni_urn'] = sliver_id
             if node['boot_state'] == 'boot':
@@ -716,7 +739,7 @@ class PlDriver (Driver):
             raise RecordNotFound(slice_hrn)
         slice = slices[0]
         requested_time = utcparse(expiration_time)
-        record = {'expires': int(time.mktime(requested_time.timetuple()))}
+        record = {'expires': int(datetime_to_epoch(requested_time))}
         try:
             self.shell.UpdateSlice(slice['slice_id'], record)
             return True