5 from time import gmtime, strftime
6 from sfa.senslab.parsing import *
9 from sfa.util.config import Config
10 from sfa.util.plxrn import PlXrn
11 from sfa.util.xrn import hrn_to_urn, get_authority,Xrn,get_leaf
13 from sfa.util.config import Config
19 OARrequests_list = ["GET_version", "GET_timezone", "GET_jobs", "GET_jobs_table", "GET_jobs_details",
20 "GET_resources_full", "GET_resources"]
22 OARrequests_uri_list = ['/oarapi/version.json','/oarapi/timezone.json', '/oarapi/jobs.json',
23 '/oarapi/jobs/details.json', '/oarapi/resources/full.json', '/oarapi/resources.json']
25 OARrequests_get_uri_dict = { 'GET_version': '/oarapi/version.json',
26 'GET_timezone':'/oarapi/timezone.json' ,
27 'GET_jobs': '/oarapi/jobs.json',
28 'GET_jobs_id': '/oarapi/jobs/id.json',
29 'GET_jobs_id_resources': '/oarapi/jobs/id/resources.json',
30 'GET_resources_id': '/oarapi/resources/id.json',
31 'GET_jobs_table': '/oarapi/jobs/table.json',
32 'GET_jobs_details': '/oarapi/jobs/details.json',
33 'GET_reserved_nodes': '/oarapi/jobs/details.json?state=Runnng,Waiting,Launching',
34 'GET_resources_full': '/oarapi/resources/full.json',
35 'GET_resources':'/oarapi/resources.json',
36 'GET_sites' : '/oarapi/resources/full.json',
41 OARrequest_post_uri_dict = {
42 'POST_job':{'uri': '/oarapi/jobs.json'},
43 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'},}
45 POSTformat = { #'yaml': {'content':"text/yaml", 'object':yaml}
46 'json' : {'content':"application/json",'object':json},
47 #'http': {'content':"applicaton/x-www-form-urlencoded",'object': html},
50 OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", 'workdir':"/home/", 'walltime':""}
55 self.oarserver['ip'] = OARIP
56 self.oarserver['port'] = 80
57 self.oarserver['uri'] = None
58 self.oarserver['postformat'] = 'json'
61 self.jobstates = ['Terminated','Hold','Waiting','toLaunch','toError',\
62 'toAckReservation','Launching','Finishing',\
63 'Running','Suspended','Resuming','Error']
65 self.parser = OARGETParser(self)
68 def GETRequestToOARRestAPI(self, request, strval=None , username = None ):
69 self.oarserver['uri'] = OARrequests_get_uri_dict[request]
73 self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(strval))
74 print>>sys.stderr, "\r\n \r\n GETRequestToOARRestAPI replace : self.oarserver['uri'] %s", self.oarserver['uri']
76 headers['X-REMOTE_IDENT'] = username
78 #headers = {'X-REMOTE_IDENT':'avakian',\
79 #'content-length':'0'}
80 headers['content-length'] = '0' #seems that it does not work if we don't add this
82 #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
83 #conn.putheader(headers)
85 #conn.putrequest("GET",self.oarserver['uri'] )
86 conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
88 conn.request("GET",self.oarserver['uri'],data , headers )
89 resp = ( conn.getresponse()).read()
92 raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
97 print>>sys.stderr, " \r\n \r\n \t GETRequestToOARRestAPI strval %s js %s" %(strval,js)
101 raise ServerError("Failed to parse Server Response:" + js)
104 def POSTRequestToOARRestAPI(self, request, datadict, username=None):
105 #first check that all params for are OK
107 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI username",username
109 self.oarserver['uri'] = OARrequest_post_uri_dict[request]['uri']
112 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI request not in OARrequest_post_uri_dict"
115 if datadict and 'strval' in datadict:
116 self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(datadict['strval']))
117 del datadict['strval']
119 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI ERRRRRORRRRRR "
121 #if format in POSTformat:
122 #if format is 'json':
123 data = json.dumps(datadict)
124 headers = {'X-REMOTE_IDENT':username,\
125 'content-type':POSTformat['json']['content'],\
126 'content-length':str(len(data))}
128 #self.oarserver['postformat'] = POSTformat[format]
130 conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
131 conn.request("POST",self.oarserver['uri'],data,headers )
132 resp = ( conn.getresponse()).read()
135 #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
136 #conn.putrequest("POST",self.oarserver['uri'] )
137 #self.oarserver['postformat'] = POSTformat[format]
138 #conn.putheader('HTTP X-REMOTE_IDENT', 'avakian')
139 #conn.putheader('content-type', self.oarserver['postformat']['content'])
140 #conn.putheader('content-length', str(len(data)))
143 #resp = ( conn.getresponse()).read()
147 print>>sys.stderr, "\r\n POSTRequestToOARRestAPI ERROR: data %s \r\n \t\n \t\t headers %s uri %s" %(data,headers,self.oarserver['uri'])
148 #raise ServerError("POST_OAR_SRVR : error")
151 answer = json.loads(resp)
152 print>>sys.stderr, "\r\n POSTRequestToOARRestAPI : ", answer
156 raise ServerError("Failed to parse Server Response:" + answer)
159 #def createjobrequest(self, nodelist):
160 #datadict = dict(zip(self.OARpostdatareqfields.keys(), self.OARpostdatareqfields.values())
163 #for node in nodelist:
164 #datadict[k] += str(nodelist)
169 #Insert a new node into the dictnode dictionary
170 def AddNodeId(self,dictnode,value):
171 #Inserts new key. The value associated is a tuple list.
173 dictnode[node_id] = [('node_id',node_id) ]
176 def AddNodeNetworkAddr(self,tuplelist,value):
177 tuplelist.append(('hostname',str(value)))
180 def AddNodeSite(self,tuplelist,value):
181 tuplelist.append(('site',str(value)))
184 def AddNodeRadio(self,tuplelist,value):
185 tuplelist.append(('radio',str(value)))
188 def AddMobility(self,tuplelist,value):
190 tuplelist.append(('mobile',int(value)))
194 def AddPosX(self,tuplelist,value):
195 tuplelist.append(('posx',value))
198 def AddPosY(self,tuplelist,value):
199 tuplelist.append(('posy',value))
201 def AddBootState(self,tuplelist,value):
202 tuplelist.append(('boot_state',str(value)))
204 def ParseVersion(self) :
206 #print >>sys.stderr, self.raw_json
207 if 'oar_version' in self.raw_json :
208 self.version_json_dict.update(api_version=self.raw_json['api_version'] ,
209 apilib_version=self.raw_json['apilib_version'],
210 api_timezone=self.raw_json['api_timezone'],
211 api_timestamp=self.raw_json['api_timestamp'],
212 oar_version=self.raw_json['oar_version'] )
214 self.version_json_dict.update(api_version=self.raw_json['api'] ,
215 apilib_version=self.raw_json['apilib'],
216 api_timezone=self.raw_json['api_timezone'],
217 api_timestamp=self.raw_json['api_timestamp'],
218 oar_version=self.raw_json['oar'] )
220 print self.version_json_dict['apilib_version']
223 def ParseTimezone(self) :
224 api_timestamp=self.raw_json['api_timestamp']
225 api_tz=self.raw_json['timezone']
226 #readable_time = strftime("%Y-%m-%d %H:%M:%S", gmtime(float(api_timestamp)))
228 return api_timestamp,api_tz
230 def ParseJobs(self) :
234 def ParseJobsTable(self) :
235 print "ParseJobsTable"
237 def ParseJobsDetails (self):
238 # currently, this function is not used a lot, so i have no idea what be usefull to parse, returning the full json. NT
239 print >>sys.stderr,"ParseJobsDetails %s " %(self.raw_json)
243 def ParseJobsIds(self):
245 job_resources =['assigned_network_address', 'assigned_resources','Job_Id', 'scheduledStart','state','job_user', 'startTime','walltime','message']
246 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']
248 job_info = self.raw_json
252 for k in job_resources:
253 values.append(job_info[k])
254 return dict(zip(job_resources,values))
257 print>>sys.stderr, " \r\n \t ParseJobsIds Key Error"
262 def ParseJobsIdResources(self):
263 print>>sys.stderr, "ParseJobsIdResources"
265 def ParseResources(self) :
266 print>>sys.stderr, " \r\n \t\t\t ParseResources__________________________ "
267 #resources are listed inside the 'items' list from the json
268 self.raw_json = self.raw_json['items']
272 def ParseDeleteJobs(self):
275 def ParseResourcesFull(self ) :
276 print>>sys.stderr, " \r\n \t\t\t ParseResourcesFull_____________________________ "
277 #print self.raw_json[1]
278 #resources are listed inside the 'items' list from the json
279 if self.version_json_dict['apilib_version'] != "0.2.10" :
280 self.raw_json = self.raw_json['items']
283 return self.node_dictlist
285 def ParseResourcesFullSites(self ) :
286 if self.version_json_dict['apilib_version'] != "0.2.10" :
287 self.raw_json = self.raw_json['items']
290 return self.site_dict
293 resources_fulljson_dict= {
294 'resource_id' : AddNodeId,
295 'network_address' : AddNodeNetworkAddr,
297 'radio': AddNodeRadio,
298 'mobile': AddMobility,
301 'state':AddBootState,
305 #Parse nodes properties from OAR
306 #Put them into a dictionary with key = node id and value is a dictionary
307 #of the node properties and properties'values.
308 def ParseNodes(self):
310 #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes self.raw_json %s" %(self.raw_json)
311 for dictline in self.raw_json:
312 #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes dictline %s hey" %(dictline)
314 if k in self.resources_fulljson_dict:
315 # dictionary is empty and/or a new node has to be inserted
317 node_id = self.resources_fulljson_dict[k](self,self.node_dictlist, dictline[k])
319 ret = self.resources_fulljson_dict[k](self,self.node_dictlist[node_id], dictline[k])
321 #If last property has been inserted in the property tuple list, reset node_id
323 #Turn the property tuple list (=dict value) into a dictionary
324 self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
330 def hostname_to_hrn(self, root_auth, login_base, hostname):
331 return PlXrn(auth=root_auth,hostname=login_base+'_'+hostname).get_hrn()
332 #Retourne liste de dictionnaires contenant attributs des sites
333 def ParseSites(self):
336 # Create a list of nodes per site_id
337 for node_id in self.node_dictlist.keys():
338 node = self.node_dictlist[node_id]
339 if node['site'] not in nodes_per_site:
340 nodes_per_site[node['site']] = []
341 nodes_per_site[node['site']].append(node['node_id'])
343 if node['node_id'] not in nodes_per_site[node['site']]:
344 nodes_per_site[node['site']].append(node['node_id'])
346 #Create a site dictionary with key is site_login_base (name of the site)
347 # and value is a dictionary of properties, including the list of the node_ids
348 for node_id in self.node_dictlist.keys():
349 node = self.node_dictlist[node_id]
350 node.update({'hrn':self.hostname_to_hrn(self.interface_hrn, node['site'],node['hostname'])})
351 #node['hrn'] = self.hostname_to_hrn(self.interface_hrn, node['site_login_base'],node['hostname'])
352 self.node_dictlist.update({node_id:node})
354 if node['site'] not in self.site_dict:
355 self.site_dict[node['site']] = {'site':node['site'],
356 'node_ids':nodes_per_site[node['site']],
357 'latitude':"48.83726",
358 'longitude':"- 2.10336",'name':config.SFA_REGISTRY_ROOT_AUTH,
359 'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
360 'max_slivers':None, 'is_public':True, 'peer_site_id': None,
361 'abbreviated_name':"senslab", 'address_ids': [],
362 'url':"http,//www.senslab.info", 'person_ids':[],
363 'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
364 'date_created': None, 'peer_id': None }
365 #if node['site_login_base'] not in self.site_dict.keys():
366 #self.site_dict[node['site_login_base']] = {'login_base':node['site_login_base'],
367 #'node_ids':nodes_per_site[node['site_login_base']],
368 #'latitude':"48.83726",
369 #'longitude':"- 2.10336",'name':"senslab",
370 #'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
371 #'max_slivers':None, 'is_public':True, 'peer_site_id': None,
372 #'abbreviated_name':"senslab", 'address_ids': [],
373 #'url':"http,//www.senslab.info", 'person_ids':[],
374 #'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
375 #'date_created': None, 'peer_id': None }
380 OARrequests_uri_dict = {
381 'GET_version': {'uri':'/oarapi/version.json', 'parse_func': ParseVersion},
382 'GET_timezone':{'uri':'/oarapi/timezone.json' ,'parse_func': ParseTimezone },
383 'GET_jobs': {'uri':'/oarapi/jobs.json','parse_func': ParseJobs},
384 'GET_jobs_id': {'uri':'/oarapi/jobs/id.json','parse_func': ParseJobsIds},
385 'GET_jobs_id_resources': {'uri':'/oarapi/jobs/id/resources.json','parse_func': ParseJobsIdResources},
386 'GET_jobs_table': {'uri':'/oarapi/jobs/table.json','parse_func': ParseJobsTable},
387 'GET_jobs_details': {'uri':'/oarapi/jobs/details.json','parse_func': ParseJobsDetails},
388 'GET_resources_full': {'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFull},
389 'GET_sites':{'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFullSites},
390 'GET_resources':{'uri':'/oarapi/resources.json' ,'parse_func': ParseResources},
391 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json' ,'parse_func': ParseDeleteJobs}
395 def __init__(self, srv ):
396 self.version_json_dict= { 'api_version' : None , 'apilib_version' :None, 'api_timezone': None, 'api_timestamp': None, 'oar_version': None ,}
397 self.config = Config()
398 self.interface_hrn = self.config.SFA_INTERFACE_HRN
399 self.timezone_json_dict = { 'timezone': None, 'api_timestamp': None, }
400 self.jobs_json_dict = { 'total' : None, 'links' : [] , 'offset':None , 'items' : [] , }
401 self.jobs_table_json_dict = self.jobs_json_dict
402 self.jobs_details_json_dict = self.jobs_json_dict
404 self.node_dictlist = {}
407 self.SendRequest("GET_version")
409 def SendRequest(self,request, strval = None , username = None):
410 if request in OARrequests_get_uri_dict:
411 self.raw_json = self.server.GETRequestToOARRestAPI(request,strval,username)
412 return self.OARrequests_uri_dict[request]['parse_func'](self)
414 print>>sys.stderr, "\r\n OARGetParse __init__ : ERROR_REQUEST " ,request