2 from httplib import HTTPConnection, HTTPException
5 #from time import gmtime, strftime
9 from sfa.util.config import Config
10 #from sfa.util.xrn import hrn_to_urn, get_authority, Xrn, get_leaf
12 from sfa.util.sfalogging import logger
15 OAR_REQUEST_POST_URI_DICT = {'POST_job':{'uri': '/oarapi/jobs.json'},
16 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'},
19 POST_FORMAT = {'json' : {'content':"application/json", 'object':json},}
21 #OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", \
22 #'workdir':"/home/", 'walltime':""}
29 def __init__(self, config_file = '/etc/sfa/oar_config.py'):
33 self.oarserver['uri'] = None
34 self.oarserver['postformat'] = 'json'
37 execfile(config_file, self.__dict__)
39 self.config_file = config_file
40 # path to configuration data
41 self.config_path = os.path.dirname(config_file)
44 raise IOError, "Could not find or load the configuration file: %s" \
46 #logger.setLevelDebug()
47 self.oarserver['ip'] = self.OAR_IP
48 self.oarserver['port'] = self.OAR_PORT
49 self.jobstates = ['Terminated', 'Hold', 'Waiting', 'toLaunch', \
50 'toError', 'toAckReservation', 'Launching', \
51 'Finishing', 'Running', 'Suspended', 'Resuming',\
54 self.parser = OARGETParser(self)
57 def GETRequestToOARRestAPI(self, request, strval=None , username = None ):
58 self.oarserver['uri'] = \
59 OARGETParser.OARrequests_uri_dict[request]['uri']
60 #Get job details with username
61 if 'owner' in OARGETParser.OARrequests_uri_dict[request] and username:
62 self.oarserver['uri'] += OARGETParser.OARrequests_uri_dict[request]['owner'] + username
65 logger.debug("OARrestapi \tGETRequestToOARRestAPI %s" %(request))
67 self.oarserver['uri'] = self.oarserver['uri'].\
68 replace("id",str(strval))
69 logger.debug("OARrestapi: \t GETRequestToOARRestAPI \
70 self.oarserver['uri'] %s strval %s" \
71 %(self.oarserver['uri'], strval))
73 headers['X-REMOTE_IDENT'] = username
75 #seems that it does not work if we don't add this
76 headers['content-length'] = '0'
78 conn = HTTPConnection(self.oarserver['ip'], \
79 self.oarserver['port'])
80 conn.request("GET", self.oarserver['uri'], data, headers)
81 resp = ( conn.getresponse()).read()
83 except HTTPException, error :
84 logger.log_exc("GET_OAR_SRVR : Problem with OAR server : %s " \
86 #raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
88 js_dict = json.loads(resp)
91 except ValueError, error:
92 logger.log_exc("Failed to parse Server Response: %s ERROR %s"\
94 #raise ServerError("Failed to parse Server Response:" + js)
97 def POSTRequestToOARRestAPI(self, request, datadict, username=None):
98 """ Used to post a job on OAR , along with data associated
103 #first check that all params for are OK
105 self.oarserver['uri'] = OAR_REQUEST_POST_URI_DICT[request]['uri']
108 logger.log_exc("OARrestapi \tPOSTRequestToOARRestAPI request not \
111 if datadict and 'strval' in datadict:
112 self.oarserver['uri'] = self.oarserver['uri'].replace("id", \
113 str(datadict['strval']))
114 del datadict['strval']
116 data = json.dumps(datadict)
117 headers = {'X-REMOTE_IDENT':username, \
118 'content-type': POST_FORMAT['json']['content'], \
119 'content-length':str(len(data))}
122 conn = HTTPConnection(self.oarserver['ip'], \
123 self.oarserver['port'])
124 conn.request("POST", self.oarserver['uri'], data, headers)
125 resp = (conn.getresponse()).read()
128 logger.log_exc("POSTRequestToOARRestAPI NotConnected ERROR: \
129 data %s \r\n \t\n \t\t headers %s uri %s" \
130 %(data,headers,self.oarserver['uri']))
132 #raise ServerError("POST_OAR_SRVR : error")
135 answer = json.loads(resp)
136 logger.debug("POSTRequestToOARRestAPI : answer %s" %(answer))
139 except ValueError, error:
140 logger.log_exc("Failed to parse Server Response: error %s answer \
141 %s" %(error, answer))
142 #raise ServerError("Failed to parse Server Response:" + answer)
146 def AddOarNodeId(tuplelist, value):
147 """ Adds Oar internal node id to the nodes attributes """
149 tuplelist.append(('oar_id', int(value)))
152 def AddNodeNetworkAddr(dictnode, value):
153 #Inserts new key. The value associated is a tuple list
156 dictnode[node_id] = [('node_id', node_id),('hostname', node_id) ]
160 def AddNodeSite(tuplelist, value):
161 tuplelist.append(('site', str(value)))
163 def AddNodeRadio(tuplelist, value):
164 tuplelist.append(('radio', str(value)))
167 def AddMobility(tuplelist, value):
169 tuplelist.append(('mobile', 'False'))
171 tuplelist.append(('mobile', 'True'))
173 def AddPosX(tuplelist, value):
174 tuplelist.append(('posx', value))
176 def AddPosY(tuplelist, value):
177 tuplelist.append(('posy', value))
179 def AddPosZ(tuplelist, value):
180 tuplelist.append(('posz', value))
182 def AddBootState(tuplelist, value):
183 tuplelist.append(('boot_state', str(value)))
185 #Insert a new node into the dictnode dictionary
186 def AddNodeId(dictnode, value):
187 #Inserts new key. The value associated is a tuple list
190 dictnode[node_id] = [('node_id', node_id)]
193 def AddHardwareType(tuplelist, value):
194 value_list = value.split(':')
195 tuplelist.append(('archi', value_list[0]))
196 tuplelist.append(('radio', value_list[1]))
200 resources_fulljson_dict = {
201 'network_address' : AddNodeNetworkAddr,
203 'radio': AddNodeRadio,
204 'mobile': AddMobility,
208 'archi':AddHardwareType,
209 'state':AddBootState,
214 def __init__(self, srv) :
215 self.version_json_dict = {
216 'api_version' : None , 'apilib_version' :None,\
217 'api_timezone': None, 'api_timestamp': None, 'oar_version': None ,}
218 self.config = Config()
219 self.interface_hrn = self.config.SFA_INTERFACE_HRN
220 self.timezone_json_dict = {
221 'timezone': None, 'api_timestamp': None, }
222 self.jobs_json_dict = {
223 'total' : None, 'links' : [],\
224 'offset':None , 'items' : [], }
225 self.jobs_table_json_dict = self.jobs_json_dict
226 self.jobs_details_json_dict = self.jobs_json_dict
228 self.node_dictlist = {}
231 self.SendRequest("GET_version")
237 def ParseVersion(self) :
239 #print >>sys.stderr, self.raw_json
240 if 'oar_version' in self.raw_json :
241 self.version_json_dict.update(api_version = \
242 self.raw_json['api_version'],
243 apilib_version = self.raw_json['apilib_version'],
244 api_timezone = self.raw_json['api_timezone'],
245 api_timestamp = self.raw_json['api_timestamp'],
246 oar_version = self.raw_json['oar_version'] )
248 self.version_json_dict.update(api_version = self.raw_json['api'] ,
249 apilib_version = self.raw_json['apilib'],
250 api_timezone = self.raw_json['api_timezone'],
251 api_timestamp = self.raw_json['api_timestamp'],
252 oar_version = self.raw_json['oar'] )
254 print self.version_json_dict['apilib_version']
257 def ParseTimezone(self) :
258 api_timestamp = self.raw_json['api_timestamp']
259 api_tz = self.raw_json['timezone']
260 return api_timestamp, api_tz
262 def ParseJobs(self) :
267 def ParseJobsTable(self) :
268 print "ParseJobsTable"
270 def ParseJobsDetails (self):
271 # currently, this function is not used a lot,
272 #so i have no idea what be usefull to parse,
273 #returning the full json. NT
274 #logger.debug("ParseJobsDetails %s " %(self.raw_json))
278 def ParseJobsIds(self):
280 job_resources = ['wanted_resources', 'name', 'id', 'start_time', \
281 'state','owner','walltime','message']
284 job_resources_full = ['launching_directory', 'links', \
285 'resubmit_job_id', 'owner', 'events', 'message', \
286 'scheduled_start', 'id', 'array_id', 'exit_code', \
287 'properties', 'state','array_index', 'walltime', \
288 'type', 'initial_request', 'stop_time', 'project',\
289 'start_time', 'dependencies','api_timestamp','submission_time', \
290 'reservation', 'stdout_file', 'types', 'cpuset_name', \
291 'name', 'wanted_resources','queue','stderr_file','command']
294 job_info = self.raw_json
295 #logger.debug("OARESTAPI ParseJobsIds %s" %(self.raw_json))
298 for k in job_resources:
299 values.append(job_info[k])
300 return dict(zip(job_resources, values))
303 logger.log_exc("ParseJobsIds KeyError ")
306 def ParseJobsIdResources(self):
307 """ Parses the json produced by the request
308 /oarapi/jobs/id/resources.json.
309 Returns a list of oar node ids that are scheduled for the
314 for resource in self.raw_json['items']:
315 job_resources.append(resource['id'])
317 #logger.debug("OARESTAPI \tParseJobsIdResources %s" %(self.raw_json))
320 def ParseResources(self) :
321 """ Parses the json produced by a get_resources request on oar."""
323 #logger.debug("OARESTAPI \tParseResources " )
324 #resources are listed inside the 'items' list from the json
325 self.raw_json = self.raw_json['items']
328 def ParseReservedNodes(self):
329 """ Returns an array containing the list of the reserved nodes """
331 #resources are listed inside the 'items' list from the json
332 reservation_list = []
333 print "ParseReservedNodes_%s" %(self.raw_json['items'])
335 #Parse resources info
336 for json_element in self.raw_json['items']:
337 #In case it is a real reservation (not asap case)
338 if json_element['scheduled_start']:
339 job['t_from'] = json_element['scheduled_start']
340 job['t_until'] = int(json_element['scheduled_start']) + \
341 int(json_element['walltime'])
342 #Get resources id list for the job
343 job['resource_ids'] = \
344 [ node_dict['id'] for node_dict in json_element['resources'] ]
346 job['t_from'] = "As soon as possible"
347 job['t_until'] = "As soon as possible"
348 job['resource_ids'] = ["Undefined"]
351 job['state'] = json_element['state']
352 job['lease_id'] = json_element['id']
355 job['user'] = json_element['owner']
356 #logger.debug("OARRestapi \tParseReservedNodes job %s" %(job))
357 reservation_list.append(job)
360 return reservation_list
362 def ParseRunningJobs(self):
363 """ Gets the list of nodes currently in use from the attributes of the
367 logger.debug("OARESTAPI \tParseRunningJobs__________________________ ")
368 #resources are listed inside the 'items' list from the json
370 for job in self.raw_json['items']:
371 for node in job['nodes']:
372 nodes.append(node['network_address'])
377 def ParseDeleteJobs(self):
378 """ No need to parse anything in this function.A POST
379 is done to delete the job.
384 def ParseResourcesFull(self) :
385 """ This method is responsible for parsing all the attributes
386 of all the nodes returned by OAR when issuing a get resources full.
387 The information from the nodes and the sites are separated.
388 Updates the node_dictlist so that the dictionnary of the platform's
389 nodes is available afterwards.
392 logger.debug("OARRESTAPI ParseResourcesFull________________________ ")
393 #print self.raw_json[1]
394 #resources are listed inside the 'items' list from the json
395 if self.version_json_dict['apilib_version'] != "0.2.10" :
396 self.raw_json = self.raw_json['items']
399 return self.node_dictlist
401 def ParseResourcesFullSites(self) :
402 """ UNUSED. Originally used to get information from the sites.
403 ParseResourcesFull is used instead.
406 if self.version_json_dict['apilib_version'] != "0.2.10" :
407 self.raw_json = self.raw_json['items']
410 return self.site_dict
414 def ParseNodes(self):
415 """ Parse nodes properties from OAR
416 Put them into a dictionary with key = node id and value is a dictionary
417 of the node properties and properties'values.
421 keys = self.resources_fulljson_dict.keys()
424 for dictline in self.raw_json:
426 # dictionary is empty and/or a new node has to be inserted
427 node_id = self.resources_fulljson_dict['network_address'](\
428 self.node_dictlist, dictline['network_address'])
431 if k == 'network_address':
434 self.resources_fulljson_dict[k](\
435 self.node_dictlist[node_id], dictline[k])
437 #The last property has been inserted in the property tuple list,
439 #Turn the property tuple list (=dict value) into a dictionary
440 self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
443 def slab_hostname_to_hrn(self, root_auth, hostname):
444 return root_auth + '.'+ hostname
448 def ParseSites(self):
449 """ Returns a list of dictionnaries containing the sites' attributes."""
453 #logger.debug(" OARrestapi.py \tParseSites self.node_dictlist %s"\
454 #%(self.node_dictlist))
455 # Create a list of nodes per site_id
456 for node_id in self.node_dictlist:
457 node = self.node_dictlist[node_id]
459 if node['site'] not in nodes_per_site:
460 nodes_per_site[node['site']] = []
461 nodes_per_site[node['site']].append(node['node_id'])
463 if node['node_id'] not in nodes_per_site[node['site']]:
464 nodes_per_site[node['site']].append(node['node_id'])
466 #Create a site dictionary whose key is site_login_base (name of the site)
467 # and value is a dictionary of properties, including the list
469 for node_id in self.node_dictlist:
470 node = self.node_dictlist[node_id]
471 #node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, \
472 #node['site'],node['hostname'])})
473 node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, node['hostname'])})
474 self.node_dictlist.update({node_id:node})
476 if node['site'] not in self.site_dict:
477 self.site_dict[node['site']] = {
479 'node_ids':nodes_per_site[node['site']],
480 'latitude':"48.83726",
481 'longitude':"- 2.10336",'name':config.SFA_REGISTRY_ROOT_AUTH,
482 'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
483 'max_slivers':None, 'is_public':True, 'peer_site_id': None,
484 'abbreviated_name':"senslab", 'address_ids': [],
485 'url':"http,//www.senslab.info", 'person_ids':[],
486 'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
487 'date_created': None, 'peer_id': None }
488 #if node['site_login_base'] not in self.site_dict.keys():
489 #self.site_dict[node['site_login_base']] = {'login_base':node['site_login_base'],
490 #'node_ids':nodes_per_site[node['site_login_base']],
491 #'latitude':"48.83726",
492 #'longitude':"- 2.10336",'name':"senslab",
493 #'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
494 #'max_slivers':None, 'is_public':True, 'peer_site_id': None,
495 #'abbreviated_name':"senslab", 'address_ids': [],
496 #'url':"http,//www.senslab.info", 'person_ids':[],
497 #'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
498 #'date_created': None, 'peer_id': None }
503 OARrequests_uri_dict = {
505 {'uri':'/oarapi/version.json', 'parse_func': ParseVersion},
507 {'uri':'/oarapi/timezone.json' ,'parse_func': ParseTimezone },
509 {'uri':'/oarapi/jobs.json','parse_func': ParseJobs},
511 {'uri':'/oarapi/jobs/id.json','parse_func': ParseJobsIds},
512 'GET_jobs_id_resources':
513 {'uri':'/oarapi/jobs/id/resources.json',\
514 'parse_func': ParseJobsIdResources},
516 {'uri':'/oarapi/jobs/table.json','parse_func': ParseJobsTable},
518 {'uri':'/oarapi/jobs/details.json',\
519 'parse_func': ParseJobsDetails},
520 'GET_reserved_nodes':
522 '/oarapi/jobs/details.json?state=Running,Waiting,Launching',\
524 'parse_func':ParseReservedNodes},
528 {'uri':'/oarapi/jobs/details.json?state=Running',\
529 'parse_func':ParseRunningJobs},
530 'GET_resources_full':
531 {'uri':'/oarapi/resources/full.json',\
532 'parse_func': ParseResourcesFull},
534 {'uri':'/oarapi/resources/full.json',\
535 'parse_func': ParseResourcesFullSites},
537 {'uri':'/oarapi/resources.json' ,'parse_func': ParseResources},
539 {'uri':'/oarapi/jobs/id.json' ,'parse_func': ParseDeleteJobs}
544 def SendRequest(self, request, strval = None , username = None):
545 """ Connects to OAR , sends the valid GET requests and uses
546 the appropriate json parsing functions.
549 if request in self.OARrequests_uri_dict :
550 self.raw_json = self.server.GETRequestToOARRestAPI(request, \
553 return self.OARrequests_uri_dict[request]['parse_func'](self)
555 logger.error("OARRESTAPI OARGetParse __init__ : ERROR_REQUEST " \