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
14 OARIP = '194.199.16.166'
17 OAR_REQUEST_POST_URI_DICT = {'POST_job':{'uri': '/oarapi/jobs.json'},
18 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json'},
21 POST_FORMAT = {'json' : {'content':"application/json", 'object':json},}
23 #OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", \
24 #'workdir':"/home/", 'walltime':""}
31 def __init__(self, config_file = '/etc/sfa/oar_config.py'):
35 self.oarserver['uri'] = None
36 self.oarserver['postformat'] = 'json'
39 execfile(config_file, self.__dict__)
41 self.config_file = config_file
42 # path to configuration data
43 self.config_path = os.path.dirname(config_file)
46 raise IOError, "Could not find or load the configuration file: %s" \
48 #logger.setLevelDebug()
49 self.oarserver['ip'] = self.OAR_IP
50 self.oarserver['port'] = self.OAR_PORT
51 self.jobstates = ['Terminated', 'Hold', 'Waiting', 'toLaunch', \
52 'toError', 'toAckReservation', 'Launching', \
53 'Finishing', 'Running', 'Suspended', 'Resuming',\
56 self.parser = OARGETParser(self)
59 def GETRequestToOARRestAPI(self, request, strval=None , username = None ):
60 self.oarserver['uri'] = \
61 OARGETParser.OARrequests_uri_dict[request]['uri']
62 #Get job details with username
63 if 'owner' in OARGETParser.OARrequests_uri_dict[request] and username:
64 self.oarserver['uri'] += OARGETParser.OARrequests_uri_dict[request]['owner'] + username
67 logger.debug("OARrestapi \tGETRequestToOARRestAPI %s" %(request))
69 self.oarserver['uri'] = self.oarserver['uri'].\
70 replace("id",str(strval))
71 logger.debug("OARrestapi: \t GETRequestToOARRestAPI \
72 self.oarserver['uri'] %s strval %s" \
73 %(self.oarserver['uri'], strval))
75 headers['X-REMOTE_IDENT'] = username
77 #seems that it does not work if we don't add this
78 headers['content-length'] = '0'
80 conn = HTTPConnection(self.oarserver['ip'], \
81 self.oarserver['port'])
82 conn.request("GET", self.oarserver['uri'], data, headers)
83 resp = ( conn.getresponse()).read()
85 except HTTPException, error :
86 logger.log_exc("GET_OAR_SRVR : Problem with OAR server : %s " \
88 #raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
90 js_dict = json.loads(resp)
93 except ValueError, error:
94 logger.log_exc("Failed to parse Server Response: %s ERROR %s"\
96 #raise ServerError("Failed to parse Server Response:" + js)
99 def POSTRequestToOARRestAPI(self, request, datadict, username=None):
100 """ Used to post a job on OAR , along with data associated
105 #first check that all params for are OK
107 self.oarserver['uri'] = OAR_REQUEST_POST_URI_DICT[request]['uri']
110 logger.log_exc("OARrestapi \tPOSTRequestToOARRestAPI request not \
113 if datadict and 'strval' in datadict:
114 self.oarserver['uri'] = self.oarserver['uri'].replace("id", \
115 str(datadict['strval']))
116 del datadict['strval']
118 data = json.dumps(datadict)
119 headers = {'X-REMOTE_IDENT':username, \
120 'content-type': POST_FORMAT['json']['content'], \
121 'content-length':str(len(data))}
124 conn = HTTPConnection(self.oarserver['ip'], \
125 self.oarserver['port'])
126 conn.request("POST", self.oarserver['uri'], data, headers)
127 resp = (conn.getresponse()).read()
130 logger.log_exc("POSTRequestToOARRestAPI NotConnected ERROR: \
131 data %s \r\n \t\n \t\t headers %s uri %s" \
132 %(data,headers,self.oarserver['uri']))
134 #raise ServerError("POST_OAR_SRVR : error")
137 answer = json.loads(resp)
138 logger.debug("POSTRequestToOARRestAPI : answer %s" %(answer))
141 except ValueError, error:
142 logger.log_exc("Failed to parse Server Response: error %s answer \
143 %s" %(error, answer))
144 #raise ServerError("Failed to parse Server Response:" + answer)
148 def AddOarNodeId(tuplelist, value):
149 """ Adds Oar internal node id to the nodes attributes """
151 tuplelist.append(('oar_id', int(value)))
154 def AddNodeNetworkAddr(dictnode, value):
155 #Inserts new key. The value associated is a tuple list
158 dictnode[node_id] = [('node_id', node_id),('hostname', node_id) ]
162 def AddNodeSite(tuplelist, value):
163 tuplelist.append(('site', str(value)))
165 def AddNodeRadio(tuplelist, value):
166 tuplelist.append(('radio', str(value)))
169 def AddMobility(tuplelist, value):
171 tuplelist.append(('mobile', 'False'))
173 tuplelist.append(('mobile', 'True'))
175 def AddPosX(tuplelist, value):
176 tuplelist.append(('posx', value))
178 def AddPosY(tuplelist, value):
179 tuplelist.append(('posy', value))
181 def AddPosZ(tuplelist, value):
182 tuplelist.append(('posz', value))
184 def AddBootState(tuplelist, value):
185 tuplelist.append(('boot_state', str(value)))
187 #Insert a new node into the dictnode dictionary
188 def AddNodeId(dictnode, value):
189 #Inserts new key. The value associated is a tuple list
192 dictnode[node_id] = [('node_id', node_id)]
195 def AddHardwareType(tuplelist, value):
196 value_list = value.split(':')
197 tuplelist.append(('archi', value_list[0]))
198 tuplelist.append(('radio', value_list[1]))
202 resources_fulljson_dict = {
203 'network_address' : AddNodeNetworkAddr,
205 'radio': AddNodeRadio,
206 'mobile': AddMobility,
210 'archi':AddHardwareType,
211 'state':AddBootState,
216 def __init__(self, srv) :
217 self.version_json_dict = {
218 'api_version' : None , 'apilib_version' :None,\
219 'api_timezone': None, 'api_timestamp': None, 'oar_version': None ,}
220 self.config = Config()
221 self.interface_hrn = self.config.SFA_INTERFACE_HRN
222 self.timezone_json_dict = {
223 'timezone': None, 'api_timestamp': None, }
224 self.jobs_json_dict = {
225 'total' : None, 'links' : [],\
226 'offset':None , 'items' : [], }
227 self.jobs_table_json_dict = self.jobs_json_dict
228 self.jobs_details_json_dict = self.jobs_json_dict
230 self.node_dictlist = {}
233 self.SendRequest("GET_version")
239 def ParseVersion(self) :
241 #print >>sys.stderr, self.raw_json
242 if 'oar_version' in self.raw_json :
243 self.version_json_dict.update(api_version = \
244 self.raw_json['api_version'],
245 apilib_version = self.raw_json['apilib_version'],
246 api_timezone = self.raw_json['api_timezone'],
247 api_timestamp = self.raw_json['api_timestamp'],
248 oar_version = self.raw_json['oar_version'] )
250 self.version_json_dict.update(api_version = self.raw_json['api'] ,
251 apilib_version = self.raw_json['apilib'],
252 api_timezone = self.raw_json['api_timezone'],
253 api_timestamp = self.raw_json['api_timestamp'],
254 oar_version = self.raw_json['oar'] )
256 print self.version_json_dict['apilib_version']
259 def ParseTimezone(self) :
260 api_timestamp = self.raw_json['api_timestamp']
261 api_tz = self.raw_json['timezone']
262 return api_timestamp, api_tz
264 def ParseJobs(self) :
269 def ParseJobsTable(self) :
270 print "ParseJobsTable"
272 def ParseJobsDetails (self):
273 # currently, this function is not used a lot,
274 #so i have no idea what be usefull to parse,
275 #returning the full json. NT
276 #logger.debug("ParseJobsDetails %s " %(self.raw_json))
280 def ParseJobsIds(self):
282 job_resources = ['wanted_resources', 'name', 'id', 'start_time', \
283 'state','owner','walltime','message']
286 job_resources_full = ['launching_directory', 'links', \
287 'resubmit_job_id', 'owner', 'events', 'message', \
288 'scheduled_start', 'id', 'array_id', 'exit_code', \
289 'properties', 'state','array_index', 'walltime', \
290 'type', 'initial_request', 'stop_time', 'project',\
291 'start_time', 'dependencies','api_timestamp','submission_time', \
292 'reservation', 'stdout_file', 'types', 'cpuset_name', \
293 'name', 'wanted_resources','queue','stderr_file','command']
296 job_info = self.raw_json
297 #logger.debug("OARESTAPI ParseJobsIds %s" %(self.raw_json))
300 for k in job_resources:
301 values.append(job_info[k])
302 return dict(zip(job_resources, values))
305 logger.log_exc("ParseJobsIds KeyError ")
308 def ParseJobsIdResources(self):
309 """ Parses the json produced by the request
310 /oarapi/jobs/id/resources.json.
311 Returns a list of oar node ids that are scheduled for the
316 for resource in self.raw_json['items']:
317 job_resources.append(resource['id'])
319 #logger.debug("OARESTAPI \tParseJobsIdResources %s" %(self.raw_json))
322 def ParseResources(self) :
323 """ Parses the json produced by a get_resources request on oar."""
325 #logger.debug("OARESTAPI \tParseResources " )
326 #resources are listed inside the 'items' list from the json
327 self.raw_json = self.raw_json['items']
330 def ParseReservedNodes(self):
331 """ Returns an array containing the list of the reserved nodes """
333 #resources are listed inside the 'items' list from the json
334 reservation_list = []
335 print "ParseReservedNodes_%s" %(self.raw_json['items'])
337 #Parse resources info
338 for json_element in self.raw_json['items']:
339 #In case it is a real reservation (not asap case)
340 if json_element['scheduled_start']:
341 job['t_from'] = json_element['scheduled_start']
342 job['t_until'] = int(json_element['scheduled_start']) + \
343 int(json_element['walltime'])
344 #Get resources id list for the job
345 job['resource_ids'] = \
346 [ node_dict['id'] for node_dict in json_element['resources'] ]
348 job['t_from'] = "As soon as possible"
349 job['t_until'] = "As soon as possible"
350 job['resource_ids'] = ["Undefined"]
353 job['state'] = json_element['state']
354 job['lease_id'] = json_element['id']
357 job['user'] = json_element['owner']
358 #logger.debug("OARRestapi \tParseReservedNodes job %s" %(job))
359 reservation_list.append(job)
362 return reservation_list
364 def ParseRunningJobs(self):
365 """ Gets the list of nodes currently in use from the attributes of the
369 logger.debug("OARESTAPI \tParseRunningJobs__________________________ ")
370 #resources are listed inside the 'items' list from the json
372 for job in self.raw_json['items']:
373 for node in job['nodes']:
374 nodes.append(node['network_address'])
379 def ParseDeleteJobs(self):
380 """ No need to parse anything in this function.A POST
381 is done to delete the job.
386 def ParseResourcesFull(self) :
387 """ This method is responsible for parsing all the attributes
388 of all the nodes returned by OAR when issuing a get resources full.
389 The information from the nodes and the sites are separated.
390 Updates the node_dictlist so that the dictionnary of the platform's
391 nodes is available afterwards.
394 logger.debug("OARRESTAPI ParseResourcesFull________________________ ")
395 #print self.raw_json[1]
396 #resources are listed inside the 'items' list from the json
397 if self.version_json_dict['apilib_version'] != "0.2.10" :
398 self.raw_json = self.raw_json['items']
401 return self.node_dictlist
403 def ParseResourcesFullSites(self) :
404 """ UNUSED. Originally used to get information from the sites.
405 ParseResourcesFull is used instead.
408 if self.version_json_dict['apilib_version'] != "0.2.10" :
409 self.raw_json = self.raw_json['items']
412 return self.site_dict
416 def ParseNodes(self):
417 """ Parse nodes properties from OAR
418 Put them into a dictionary with key = node id and value is a dictionary
419 of the node properties and properties'values.
423 keys = self.resources_fulljson_dict.keys()
426 for dictline in self.raw_json:
428 # dictionary is empty and/or a new node has to be inserted
429 node_id = self.resources_fulljson_dict['network_address'](\
430 self.node_dictlist, dictline['network_address'])
433 if k == 'network_address':
436 self.resources_fulljson_dict[k](\
437 self.node_dictlist[node_id], dictline[k])
439 #The last property has been inserted in the property tuple list,
441 #Turn the property tuple list (=dict value) into a dictionary
442 self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
445 def slab_hostname_to_hrn(self, root_auth, hostname):
446 return root_auth + '.'+ hostname
450 def ParseSites(self):
451 """ Returns a list of dictionnaries containing the sites' attributes."""
455 #logger.debug(" OARrestapi.py \tParseSites self.node_dictlist %s"\
456 #%(self.node_dictlist))
457 # Create a list of nodes per site_id
458 for node_id in self.node_dictlist:
459 node = self.node_dictlist[node_id]
461 if node['site'] not in nodes_per_site:
462 nodes_per_site[node['site']] = []
463 nodes_per_site[node['site']].append(node['node_id'])
465 if node['node_id'] not in nodes_per_site[node['site']]:
466 nodes_per_site[node['site']].append(node['node_id'])
468 #Create a site dictionary whose key is site_login_base (name of the site)
469 # and value is a dictionary of properties, including the list
471 for node_id in self.node_dictlist:
472 node = self.node_dictlist[node_id]
473 #node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, \
474 #node['site'],node['hostname'])})
475 node.update({'hrn':self.slab_hostname_to_hrn(self.interface_hrn, node['hostname'])})
476 self.node_dictlist.update({node_id:node})
478 if node['site'] not in self.site_dict:
479 self.site_dict[node['site']] = {
481 'node_ids':nodes_per_site[node['site']],
482 'latitude':"48.83726",
483 'longitude':"- 2.10336",'name':config.SFA_REGISTRY_ROOT_AUTH,
484 'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
485 'max_slivers':None, 'is_public':True, 'peer_site_id': None,
486 'abbreviated_name':"senslab", 'address_ids': [],
487 'url':"http,//www.senslab.info", 'person_ids':[],
488 'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
489 'date_created': None, 'peer_id': None }
490 #if node['site_login_base'] not in self.site_dict.keys():
491 #self.site_dict[node['site_login_base']] = {'login_base':node['site_login_base'],
492 #'node_ids':nodes_per_site[node['site_login_base']],
493 #'latitude':"48.83726",
494 #'longitude':"- 2.10336",'name':"senslab",
495 #'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
496 #'max_slivers':None, 'is_public':True, 'peer_site_id': None,
497 #'abbreviated_name':"senslab", 'address_ids': [],
498 #'url':"http,//www.senslab.info", 'person_ids':[],
499 #'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
500 #'date_created': None, 'peer_id': None }
505 OARrequests_uri_dict = {
507 {'uri':'/oarapi/version.json', 'parse_func': ParseVersion},
509 {'uri':'/oarapi/timezone.json' ,'parse_func': ParseTimezone },
511 {'uri':'/oarapi/jobs.json','parse_func': ParseJobs},
513 {'uri':'/oarapi/jobs/id.json','parse_func': ParseJobsIds},
514 'GET_jobs_id_resources':
515 {'uri':'/oarapi/jobs/id/resources.json',\
516 'parse_func': ParseJobsIdResources},
518 {'uri':'/oarapi/jobs/table.json','parse_func': ParseJobsTable},
520 {'uri':'/oarapi/jobs/details.json',\
521 'parse_func': ParseJobsDetails},
522 'GET_reserved_nodes':
524 '/oarapi/jobs/details.json?state=Running,Waiting,Launching',\
526 'parse_func':ParseReservedNodes},
530 {'uri':'/oarapi/jobs/details.json?state=Running',\
531 'parse_func':ParseRunningJobs},
532 'GET_resources_full':
533 {'uri':'/oarapi/resources/full.json',\
534 'parse_func': ParseResourcesFull},
536 {'uri':'/oarapi/resources/full.json',\
537 'parse_func': ParseResourcesFullSites},
539 {'uri':'/oarapi/resources.json' ,'parse_func': ParseResources},
541 {'uri':'/oarapi/jobs/id.json' ,'parse_func': ParseDeleteJobs}
546 def SendRequest(self, request, strval = None , username = None):
547 """ Connects to OAR , sends the valid GET requests and uses
548 the appropriate json parsing functions.
551 if request in self.OARrequests_uri_dict :
552 self.raw_json = self.server.GETRequestToOARRestAPI(request, \
555 return self.OARrequests_uri_dict[request]['parse_func'](self)
557 logger.error("OARRESTAPI OARGetParse __init__ : ERROR_REQUEST " \