X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=sfa%2Fsenslab%2FOARrestapi.py;h=3ca883a6dfb659d635aefb3a5f62d0211c46b9f9;hb=fa77e36e57e78fb3f589818782cbdf327414fee5;hp=7799f99bdf96cd6267a516ba898caf8e06651e59;hpb=1b884d2ef453b025da10ec856f829a34d0fbb411;p=sfa.git diff --git a/sfa/senslab/OARrestapi.py b/sfa/senslab/OARrestapi.py index 7799f99b..3ca883a6 100644 --- a/sfa/senslab/OARrestapi.py +++ b/sfa/senslab/OARrestapi.py @@ -1,28 +1,20 @@ -# import modules used here -- sys is a very standard one import sys import httplib import json import datetime from time import gmtime, strftime -from sfa.senslab.parsing import * -#from sfa.senslab.SenslabImportUsers import * + import urllib import urllib2 from sfa.util.config import Config -from sfa.util.plxrn import PlXrn +from sfa.planetlab.plxrn import PlXrn from sfa.util.xrn import hrn_to_urn, get_authority,Xrn,get_leaf from sfa.util.config import Config - -#OARIP='10.127.255.254' -OARIP='192.168.0.109' +from sfa.util.sfalogging import logger -OARrequests_list = ["GET_version", "GET_timezone", "GET_jobs", "GET_jobs_table", "GET_jobs_details", -"GET_resources_full", "GET_resources"] - -OARrequests_uri_list = ['/oarapi/version.json','/oarapi/timezone.json', '/oarapi/jobs.json', -'/oarapi/jobs/details.json', '/oarapi/resources/full.json', '/oarapi/resources.json'] +OARIP ='194.199.16.161' OARrequests_get_uri_dict = { 'GET_version': '/oarapi/version.json', 'GET_timezone':'/oarapi/timezone.json' , @@ -32,34 +24,35 @@ OARrequests_get_uri_dict = { 'GET_version': '/oarapi/version.json', 'GET_resources_id': '/oarapi/resources/id.json', 'GET_jobs_table': '/oarapi/jobs/table.json', 'GET_jobs_details': '/oarapi/jobs/details.json', + 'GET_reserved_nodes': '/oarapi/jobs/details.json?state=Running,Waiting,Launching', 'GET_resources_full': '/oarapi/resources/full.json', 'GET_resources':'/oarapi/resources.json', 'GET_sites' : '/oarapi/resources/full.json', - - -} + } -OARrequest_post_uri_dict = { - 'POST_job':{'uri': '/oarapi/jobs.json'}, - 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'},} +OARrequest_post_uri_dict = { 'POST_job':{'uri': '/oarapi/jobs.json'}, + 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'}, + } -POSTformat = { #'yaml': {'content':"text/yaml", 'object':yaml} -'json' : {'content':"application/json",'object':json}, -#'http': {'content':"applicaton/x-www-form-urlencoded",'object': html}, -} +POSTformat = { 'json' : {'content':"application/json",'object':json}, + } -OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", 'workdir':"/home/", 'walltime':""} +OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", \ + 'workdir':"/home/", 'walltime':""} class OARrestapi: def __init__(self): self.oarserver= {} self.oarserver['ip'] = OARIP - self.oarserver['port'] = 80 + self.oarserver['port'] = 8800 self.oarserver['uri'] = None self.oarserver['postformat'] = 'json' - - self.jobstates = ["Terminated", "Running", "Error", "Waiting", "Launching","Hold"] - + #logger.setLevelDebug() + + self.jobstates = ['Terminated','Hold','Waiting','toLaunch','toError',\ + 'toAckReservation','Launching','Finishing',\ + 'Running','Suspended','Resuming','Error'] + self.parser = OARGETParser(self) @@ -67,96 +60,86 @@ class OARrestapi: self.oarserver['uri'] = OARrequests_get_uri_dict[request] headers = {} data = json.dumps({}) + logger.debug("OARrestapi \tGETRequestToOARRestAPI %s" %(request)) if strval: self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(strval)) - print>>sys.stderr, "\r\n \r\n GETRequestToOARRestAPI replace : self.oarserver['uri'] %s", self.oarserver['uri'] + logger.debug("OARrestapi: \t GETRequestToOARRestAPI \ + self.oarserver['uri'] %s strval %s" \ + %(self.oarserver['uri'], strval)) if username: headers['X-REMOTE_IDENT'] = username try : - #headers = {'X-REMOTE_IDENT':'avakian',\ - #'content-length':'0'} - headers['content-length'] = '0' #seems that it does not work if we don't add this - - #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port']) - #conn.putheader(headers) - #conn.endheaders() - #conn.putrequest("GET",self.oarserver['uri'] ) + #seems that it does not work if we don't add this + headers['content-length'] = '0' + conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port']) - conn.request("GET",self.oarserver['uri'],data , headers ) resp = ( conn.getresponse()).read() + #logger.debug("OARrestapi: \t GETRequestToOARRestAPI resp %s" %(resp)) conn.close() except: - raise ServerError("GET_OAR_SRVR : Could not reach OARserver") + logger.log_exc("GET_OAR_SRVR : Could not reach OARserver") + #raise ServerError("GET_OAR_SRVR : Could not reach OARserver") try: js = json.loads(resp) - - if strval: - print>>sys.stderr, " \r\n \r\n \t GETRequestToOARRestAPI strval %s js %s" %(strval,js) return js - except ValueError: - raise ServerError("Failed to parse Server Response:" + js) + except ValueError,error: + logger.log_exc("Failed to parse Server Response: %s ERROR %s"\ + %(js, error)) + #raise ServerError("Failed to parse Server Response:" + js) def POSTRequestToOARRestAPI(self, request, datadict, username=None): - #first check that all params for are OK + """ Used to post a job on OAR , along with data associated + with the job. - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI username",username + """ + + #first check that all params for are OK try: self.oarserver['uri'] = OARrequest_post_uri_dict[request]['uri'] - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI rq %s datadict %s " % ( self.oarserver['uri'] ,datadict) - except: - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI request not in OARrequest_post_uri_dict" + except KeyError: + logger.log_exc("OARrestapi \tPOSTRequestToOARRestAPI request not \ + valid") return try: - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI %s " %( 'strval' in datadict) if datadict and 'strval' in datadict: - self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(datadict['strval'])) - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI REPLACE OK %s"%(self.oarserver['uri']) + self.oarserver['uri'] = self.oarserver['uri'].replace("id",\ + str(datadict['strval'])) del datadict['strval'] - print>>sys.stderr, " \r\n \r\n \t POSTRequestToOARRestAPI datadict %s rq %s" %(datadict, self.oarserver['uri'] ) except: - print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI ERRRRRORRRRRR " + logger.log_exc("OARrestapi.py POSTRequestToOARRestAPI Error") return - #if format in POSTformat: - #if format is 'json': + data = json.dumps(datadict) headers = {'X-REMOTE_IDENT':username,\ 'content-type':POSTformat['json']['content'],\ 'content-length':str(len(data))} try : - #self.oarserver['postformat'] = POSTformat[format] - - print>>sys.stderr, "\r\n POSTRequestToOARRestAPI headers %s uri %s" %(headers,self.oarserver['uri']) - conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port']) + + conn = httplib.HTTPConnection(self.oarserver['ip'], \ + self.oarserver['port']) conn.request("POST",self.oarserver['uri'],data,headers ) resp = ( conn.getresponse()).read() conn.close() - - #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port']) - #conn.putrequest("POST",self.oarserver['uri'] ) - #self.oarserver['postformat'] = POSTformat[format] - #conn.putheader('HTTP X-REMOTE_IDENT', 'avakian') - #conn.putheader('content-type', self.oarserver['postformat']['content']) - #conn.putheader('content-length', str(len(data))) - #conn.endheaders() - #conn.send(data) - #resp = ( conn.getresponse()).read() - #conn.close() - except: - print>>sys.stderr, "\r\n POSTRequestToOARRestAPI ERROR: data %s \r\n \t\n \t\t headers %s uri %s" %(data,headers,self.oarserver['uri']) + logger.log_exc("POSTRequestToOARRestAPI ERROR: \ + data %s \r\n \t\n \t\t headers %s uri %s" \ + %(data,headers,self.oarserver['uri'])) + #raise ServerError("POST_OAR_SRVR : error") try: answer = json.loads(resp) - print>>sys.stderr, "\r\n POSTRequestToOARRestAPI : ", answer + logger.debug("POSTRequestToOARRestAPI : answer %s" %(answer)) return answer - except ValueError: - raise ServerError("Failed to parse Server Response:" + answer) + except ValueError,error: + logger.log_exc("Failed to parse Server Response: error %s answer \ + %s" %(error,answer)) + #raise ServerError("Failed to parse Server Response:" + answer) #def createjobrequest(self, nodelist): @@ -167,18 +150,20 @@ class OARrestapi: #datadict[k] += str(nodelist) + class OARGETParser: - #Insert a new node into the dictnode dictionary - def AddNodeId(self,dictnode,value): - #Inserts new key. The value associated is a tuple list. - node_id = int(value) - dictnode[node_id] = [('node_id',node_id) ] - return node_id - - def AddNodeNetworkAddr(self,tuplelist,value): - tuplelist.append(('hostname',str(value))) - + + #def AddNodeNetworkAddr(self,tuplelist,value): + #tuplelist.append(('hostname',str(value))) + + def AddNodeNetworkAddr(self,dictnode,value): + #Inserts new key. The value associated is a tuple list + node_id = value + + dictnode[node_id] = [('node_id',node_id),('hostname',node_id) ] + + return node_id def AddNodeSite(self,tuplelist,value): tuplelist.append(('site',str(value))) @@ -188,10 +173,10 @@ class OARGETParser: tuplelist.append(('radio',str(value))) - def AddMobility(self,tuplelist,value): + def AddMobility(self,tuplelist,value): if value : tuplelist.append(('mobile',int(value))) - return 0 + def AddPosX(self,tuplelist,value): @@ -202,7 +187,15 @@ class OARGETParser: tuplelist.append(('posy',value)) def AddBootState(self,tuplelist,value): - tuplelist.append(('boot_state',str(value))) + tuplelist.append(('boot_state',str(value))) + + #Insert a new node into the dictnode dictionary + def AddNodeId(self,dictnode,value): + #Inserts new key. The value associated is a tuple list + node_id = int(value) + + dictnode[node_id] = [('node_id',node_id) ] + return node_id def ParseVersion(self) : #print self.raw_json @@ -233,20 +226,25 @@ class OARGETParser: def ParseJobs(self) : self.jobs_list = [] print " ParseJobs " + return self.raw_json def ParseJobsTable(self) : print "ParseJobsTable" - def ParseJobsDetails (self): - + def ParseJobsDetails (self): + # currently, this function is not used a lot, so i have no idea what be usefull to parse, returning the full json. NT print >>sys.stderr,"ParseJobsDetails %s " %(self.raw_json) + return self.raw_json def ParseJobsIds(self): - job_resources =['assigned_network_address', 'assigned_resources','Job_Id', 'scheduledStart','state','job_user', 'startTime','walltime','message'] - job_resources_full = ['Job_Id', 'scheduledStart', 'resubmit_job_id', 'owner', 'submissionTime', 'message', 'id', 'jobType', 'queue', 'launchingDirectory', 'exit_code', 'state', 'array_index', 'events', 'assigned_network_address', 'cpuset_name', 'initial_request', 'job_user', 'assigned_resources', 'array_id', 'job_id', 'resources_uri', 'dependencies', 'api_timestamp', 'startTime', 'reservation', 'properties', 'types', 'walltime', 'name', 'uri', 'wanted_resources', 'project', 'command'] - + job_resources =['wanted_resources', 'name','id', 'start_time','state','owner','walltime','message'] + + + job_resources_full = ['launching_directory', 'links', 'resubmit_job_id', 'owner', 'events', 'message', 'scheduled_start', 'id', 'array_id', 'exit_code','properties', 'state','array_index', 'walltime', 'type', 'initial_request', 'stop_time', 'project', 'start_time', 'dependencies','api_timestamp','submission_time', 'reservation', 'stdout_file', 'types', 'cpuset_name', 'name', 'wanted_resources','queue','stderr_file','command'] + + job_info = self.raw_json values=[] @@ -262,7 +260,9 @@ class OARGETParser: def ParseJobsIdResources(self): + logger.debug("OARESTAPI ParseJobsIdResources %s" %(self.raw_json)) print>>sys.stderr, "ParseJobsIdResources" + return self.raw_json def ParseResources(self) : print>>sys.stderr, " \r\n \t\t\t ParseResources__________________________ " @@ -270,7 +270,11 @@ class OARGETParser: self.raw_json = self.raw_json['items'] self.ParseNodes() - + def ParseReservedNodes(self): + print>>sys.stderr, " \r\n \t\t\t ParseReservedNodes__________________________ " + #resources are listed inside the 'items' list from the json + return self.raw_json + def ParseDeleteJobs(self): return @@ -293,7 +297,6 @@ class OARGETParser: resources_fulljson_dict= { - 'resource_id' : AddNodeId, 'network_address' : AddNodeNetworkAddr, 'site': AddNodeSite, 'radio': AddNodeRadio, @@ -301,6 +304,7 @@ class OARGETParser: 'posx': AddPosX, 'posy': AddPosY, 'state':AddBootState, + #'id' : AddNodeId, } @@ -309,35 +313,39 @@ class OARGETParser: #of the node properties and properties'values. def ParseNodes(self): node_id = None + keys = self.resources_fulljson_dict.keys() + keys.sort() + #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes self.raw_json %s" %(self.raw_json) for dictline in self.raw_json: - #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes dictline %s hey" %(dictline) - for k in dictline: - if k in self.resources_fulljson_dict: - # dictionary is empty and/or a new node has to be inserted - if node_id is None : - node_id = self.resources_fulljson_dict[k](self,self.node_dictlist, dictline[k]) - else: - ret = self.resources_fulljson_dict[k](self,self.node_dictlist[node_id], dictline[k]) + node_id = None + # dictionary is empty and/or a new node has to be inserted + node_id = self.resources_fulljson_dict['network_address'](self,self.node_dictlist, dictline['network_address']) + for k in keys: + if k in dictline: + if k == 'network_address': + continue + - #If last property has been inserted in the property tuple list, reset node_id - if ret == 0: - #Turn the property tuple list (=dict value) into a dictionary - self.node_dictlist[node_id] = dict(self.node_dictlist[node_id]) - node_id = None + self.resources_fulljson_dict[k](self,self.node_dictlist[node_id], dictline[k]) + + #The last property has been inserted in the property tuple list, reset node_id + #Turn the property tuple list (=dict value) into a dictionary + self.node_dictlist[node_id] = dict(self.node_dictlist[node_id]) + node_id = None - else: - pass def hostname_to_hrn(self, root_auth, login_base, hostname): - return PlXrn(auth=root_auth,hostname=login_base+'_'+hostname).get_hrn() + return PlXrn(auth=root_auth,hostname= login_base + '_' + hostname).get_hrn() #Retourne liste de dictionnaires contenant attributs des sites def ParseSites(self): nodes_per_site = {} config = Config() + logger.debug(" OARrestapi.py \t ParseSites self.node_dictlist %s"%(self.node_dictlist)) # Create a list of nodes per site_id for node_id in self.node_dictlist.keys(): node = self.node_dictlist[node_id] + if node['site'] not in nodes_per_site: nodes_per_site[node['site']] = [] nodes_per_site[node['site']].append(node['node_id']) @@ -353,7 +361,6 @@ class OARGETParser: #node['hrn'] = self.hostname_to_hrn(self.interface_hrn, node['site_login_base'],node['hostname']) self.node_dictlist.update({node_id:node}) #if node_id is 1: - #print>>sys.stderr, " \r\n \r\n \t \t\t\t OARESTAPI Parse Sites self.node_dictlist %s " %(self.node_dictlist) if node['site'] not in self.site_dict: self.site_dict[node['site']] = {'site':node['site'], 'node_ids':nodes_per_site[node['site']], @@ -388,6 +395,7 @@ class OARGETParser: 'GET_jobs_id_resources': {'uri':'/oarapi/jobs/id/resources.json','parse_func': ParseJobsIdResources}, 'GET_jobs_table': {'uri':'/oarapi/jobs/table.json','parse_func': ParseJobsTable}, 'GET_jobs_details': {'uri':'/oarapi/jobs/details.json','parse_func': ParseJobsDetails}, + 'GET_reserved_nodes':{'uri':'/oarapi/jobs/details.json?state=Running,Waiting,Launching','parse_func':ParseReservedNodes}, 'GET_resources_full': {'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFull}, 'GET_sites':{'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFullSites}, 'GET_resources':{'uri':'/oarapi/resources.json' ,'parse_func': ParseResources}, @@ -412,7 +420,6 @@ class OARGETParser: def SendRequest(self,request, strval = None , username = None): if request in OARrequests_get_uri_dict: self.raw_json = self.server.GETRequestToOARRestAPI(request,strval,username) - #print>>sys.stderr, "\r\n OARGetParse __init__ : request %s result %s "%(request,self.raw_json) return self.OARrequests_uri_dict[request]['parse_func'](self) else: print>>sys.stderr, "\r\n OARGetParse __init__ : ERROR_REQUEST " ,request