Cleaning.
[sfa.git] / sfa / senslab / OARrestapi.py
index 8fdf617..1bcd89d 100644 (file)
@@ -3,18 +3,15 @@ from httplib import HTTPConnection, HTTPException
 import json
 #import datetime
 #from time import gmtime, strftime 
-
+import os.path
 #import urllib
 #import urllib2
 from sfa.util.config import Config
-from sfa.planetlab.plxrn import PlXrn
 #from sfa.util.xrn import hrn_to_urn, get_authority, Xrn, get_leaf
 
 from sfa.util.sfalogging import logger
 
 
-OARIP = '194.199.16.161'
-
 OAR_REQUEST_POST_URI_DICT = {'POST_job':{'uri': '/oarapi/jobs.json'},
                             'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'},
                             }
@@ -29,14 +26,26 @@ POST_FORMAT = {'json' : {'content':"application/json", 'object':json},}
 
 
 class OARrestapi:
-    def __init__(self):
+    def __init__(self, config_file =  '/etc/sfa/oar_config.py'):
         self.oarserver = {}
-        self.oarserver['ip'] = OARIP
-        self.oarserver['port'] = 8800
+       
+        
         self.oarserver['uri'] = None
         self.oarserver['postformat'] = 'json'
+        
+        try:
+            execfile(config_file, self.__dict__)
+       
+            self.config_file = config_file
+            # path to configuration data
+            self.config_path = os.path.dirname(config_file)
+            
+        except IOError:
+            raise IOError, "Could not find or load the configuration file: %s" \
+                            % config_file
         #logger.setLevelDebug()
-
+        self.oarserver['ip'] = self.OAR_IP
+        self.oarserver['port'] = self.OAR_PORT
         self.jobstates  = ['Terminated', 'Hold', 'Waiting', 'toLaunch', \
                             'toError', 'toAckReservation', 'Launching', \
                             'Finishing', 'Running', 'Suspended', 'Resuming',\
@@ -48,6 +57,9 @@ class OARrestapi:
     def GETRequestToOARRestAPI(self, request, strval=None , username = None ): 
         self.oarserver['uri'] = \
                             OARGETParser.OARrequests_uri_dict[request]['uri']
+        #Get job details with username                   
+        if 'owner' in OARGETParser.OARrequests_uri_dict[request] and username:
+           self.oarserver['uri'] +=  OARGETParser.OARrequests_uri_dict[request]['owner'] + username
         headers = {}
         data = json.dumps({})
         logger.debug("OARrestapi \tGETRequestToOARRestAPI %s" %(request))
@@ -322,15 +334,24 @@ class OARGETParser:
         job = {}
         #Parse resources info
         for json_element in  self.raw_json['items']:
-            job['t_from'] = json_element['scheduled_start']
-            #Get resources id list for the job
-            job['resource_ids'] = \
-                [ node_dict['id'] for node_dict in json_element['resources'] ]
+            #In case it is a real reservation (not asap case)
+            if json_element['scheduled_start']:
+                job['t_from'] = json_element['scheduled_start']
+                job['t_until'] = int(json_element['scheduled_start']) + \
+                                                       int(json_element['walltime'])
+                #Get resources id list for the job
+                job['resource_ids'] = \
+                    [ node_dict['id'] for node_dict in json_element['resources'] ]
+            else:
+                job['t_from'] = "As soon as possible"
+                job['t_until'] = "As soon as possible"
+                job['resource_ids'] = ["Undefined"]
+                
            
             job['state'] = json_element['state'] 
             job['lease_id'] = json_element['id'] 
-            job['t_until'] = json_element['scheduled_start'] + \
-                                                    json_element['walltime']
+            
+            
             job['user'] = json_element['owner']
             #logger.debug("OARRestapi \tParseReservedNodes job %s" %(job))  
             reservation_list.append(job)
@@ -419,10 +440,9 @@ class OARGETParser:
             self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
             node_id = None
                     
-                
-    def hostname_to_hrn(self, root_auth, login_base, hostname):
-        return PlXrn(auth = root_auth, \
-                             hostname = login_base + '_' + hostname).get_hrn()
+    def slab_hostname_to_hrn(self, root_auth,  hostname):             
+        return root_auth + '.'+ hostname 
+
                              
 
     def ParseSites(self):
@@ -433,7 +453,7 @@ class OARGETParser:
         #logger.debug(" OARrestapi.py \tParseSites  self.node_dictlist %s"\
                                                         #%(self.node_dictlist))
         # Create a list of nodes per site_id
-        for node_id in self.node_dictlist.keys():
+        for node_id in self.node_dictlist:
             node  = self.node_dictlist[node_id]
             
             if node['site'] not in nodes_per_site:
@@ -443,14 +463,14 @@ class OARGETParser:
                 if node['node_id'] not in nodes_per_site[node['site']]:
                     nodes_per_site[node['site']].append(node['node_id'])
                         
-        #Create a site dictionary with key is site_login_base (name of the site)
+        #Create a site dictionary whose key is site_login_base (name of the site)
         # and value is a dictionary of properties, including the list 
         #of the node_ids
-        for node_id in self.node_dictlist.keys():
+        for node_id in self.node_dictlist:
             node  = self.node_dictlist[node_id]
-            node.update({'hrn':self.hostname_to_hrn(self.interface_hrn, \
-                                            node['site'],node['hostname'])})
-
+            #node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, \
+                                            #node['site'],node['hostname'])})
+            node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, node['hostname'])})
             self.node_dictlist.update({node_id:node})
 
             if node['site'] not in self.site_dict:
@@ -500,7 +520,10 @@ class OARGETParser:
         'GET_reserved_nodes':
                 {'uri':
                 '/oarapi/jobs/details.json?state=Running,Waiting,Launching',\
+                'owner':'&user=',
                 'parse_func':ParseReservedNodes},
+
+                
         'GET_running_jobs':  
                 {'uri':'/oarapi/jobs/details.json?state=Running',\
                 'parse_func':ParseRunningJobs},