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'
60 self.jobstates = ["Terminated", "Running", "Error", "Waiting", "Launching","Hold"]
62 self.parser = OARGETParser(self)
65 def GETRequestToOARRestAPI(self, request, strval=None , username = None ):
66 self.oarserver['uri'] = OARrequests_get_uri_dict[request]
70 self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(strval))
71 print>>sys.stderr, "\r\n \r\n GETRequestToOARRestAPI replace : self.oarserver['uri'] %s", self.oarserver['uri']
73 headers['X-REMOTE_IDENT'] = username
75 #headers = {'X-REMOTE_IDENT':'avakian',\
76 #'content-length':'0'}
77 headers['content-length'] = '0' #seems that it does not work if we don't add this
79 #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
80 #conn.putheader(headers)
82 #conn.putrequest("GET",self.oarserver['uri'] )
83 conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
85 conn.request("GET",self.oarserver['uri'],data , headers )
86 resp = ( conn.getresponse()).read()
89 raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
94 print>>sys.stderr, " \r\n \r\n \t GETRequestToOARRestAPI strval %s js %s" %(strval,js)
98 raise ServerError("Failed to parse Server Response:" + js)
101 def POSTRequestToOARRestAPI(self, request, datadict, username=None):
102 #first check that all params for are OK
104 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI username",username
106 self.oarserver['uri'] = OARrequest_post_uri_dict[request]['uri']
109 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI request not in OARrequest_post_uri_dict"
112 if datadict and 'strval' in datadict:
113 self.oarserver['uri'] = self.oarserver['uri'].replace("id",str(datadict['strval']))
114 del datadict['strval']
116 print>>sys.stderr, " \r\n \r\n POSTRequestToOARRestAPI ERRRRRORRRRRR "
118 #if format in POSTformat:
119 #if format is 'json':
120 data = json.dumps(datadict)
121 headers = {'X-REMOTE_IDENT':username,\
122 'content-type':POSTformat['json']['content'],\
123 'content-length':str(len(data))}
125 #self.oarserver['postformat'] = POSTformat[format]
127 conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
128 conn.request("POST",self.oarserver['uri'],data,headers )
129 resp = ( conn.getresponse()).read()
132 #conn = httplib.HTTPConnection(self.oarserver['ip'],self.oarserver['port'])
133 #conn.putrequest("POST",self.oarserver['uri'] )
134 #self.oarserver['postformat'] = POSTformat[format]
135 #conn.putheader('HTTP X-REMOTE_IDENT', 'avakian')
136 #conn.putheader('content-type', self.oarserver['postformat']['content'])
137 #conn.putheader('content-length', str(len(data)))
140 #resp = ( conn.getresponse()).read()
144 print>>sys.stderr, "\r\n POSTRequestToOARRestAPI ERROR: data %s \r\n \t\n \t\t headers %s uri %s" %(data,headers,self.oarserver['uri'])
145 #raise ServerError("POST_OAR_SRVR : error")
148 answer = json.loads(resp)
149 print>>sys.stderr, "\r\n POSTRequestToOARRestAPI : ", answer
153 raise ServerError("Failed to parse Server Response:" + answer)
156 #def createjobrequest(self, nodelist):
157 #datadict = dict(zip(self.OARpostdatareqfields.keys(), self.OARpostdatareqfields.values())
160 #for node in nodelist:
161 #datadict[k] += str(nodelist)
166 #Insert a new node into the dictnode dictionary
167 def AddNodeId(self,dictnode,value):
168 #Inserts new key. The value associated is a tuple list.
170 dictnode[node_id] = [('node_id',node_id) ]
173 def AddNodeNetworkAddr(self,tuplelist,value):
174 tuplelist.append(('hostname',str(value)))
177 def AddNodeSite(self,tuplelist,value):
178 tuplelist.append(('site',str(value)))
181 def AddNodeRadio(self,tuplelist,value):
182 tuplelist.append(('radio',str(value)))
185 def AddMobility(self,tuplelist,value):
187 tuplelist.append(('mobile',int(value)))
191 def AddPosX(self,tuplelist,value):
192 tuplelist.append(('posx',value))
195 def AddPosY(self,tuplelist,value):
196 tuplelist.append(('posy',value))
198 def AddBootState(self,tuplelist,value):
199 tuplelist.append(('boot_state',str(value)))
201 def ParseVersion(self) :
203 #print >>sys.stderr, self.raw_json
204 if 'oar_version' in self.raw_json :
205 self.version_json_dict.update(api_version=self.raw_json['api_version'] ,
206 apilib_version=self.raw_json['apilib_version'],
207 api_timezone=self.raw_json['api_timezone'],
208 api_timestamp=self.raw_json['api_timestamp'],
209 oar_version=self.raw_json['oar_version'] )
211 self.version_json_dict.update(api_version=self.raw_json['api'] ,
212 apilib_version=self.raw_json['apilib'],
213 api_timezone=self.raw_json['api_timezone'],
214 api_timestamp=self.raw_json['api_timestamp'],
215 oar_version=self.raw_json['oar'] )
217 print self.version_json_dict['apilib_version']
220 def ParseTimezone(self) :
221 api_timestamp=self.raw_json['api_timestamp']
222 api_tz=self.raw_json['timezone']
223 #readable_time = strftime("%Y-%m-%d %H:%M:%S", gmtime(float(api_timestamp)))
225 return api_timestamp,api_tz
227 def ParseJobs(self) :
231 def ParseJobsTable(self) :
232 print "ParseJobsTable"
234 def ParseJobsDetails (self):
235 # currently, this function is not used a lot, so i have no idea what be usefull to parse, returning the full json. NT
236 print >>sys.stderr,"ParseJobsDetails %s " %(self.raw_json)
240 def ParseJobsIds(self):
242 job_resources =['assigned_network_address', 'assigned_resources','Job_Id', 'scheduledStart','state','job_user', 'startTime','walltime','message']
243 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']
245 job_info = self.raw_json
249 for k in job_resources:
250 values.append(job_info[k])
251 return dict(zip(job_resources,values))
254 print>>sys.stderr, " \r\n \t ParseJobsIds Key Error"
259 def ParseJobsIdResources(self):
260 print>>sys.stderr, "ParseJobsIdResources"
262 def ParseResources(self) :
263 print>>sys.stderr, " \r\n \t\t\t ParseResources__________________________ "
264 #resources are listed inside the 'items' list from the json
265 self.raw_json = self.raw_json['items']
269 def ParseDeleteJobs(self):
272 def ParseResourcesFull(self ) :
273 print>>sys.stderr, " \r\n \t\t\t ParseResourcesFull_____________________________ "
274 #print self.raw_json[1]
275 #resources are listed inside the 'items' list from the json
276 if self.version_json_dict['apilib_version'] != "0.2.10" :
277 self.raw_json = self.raw_json['items']
280 return self.node_dictlist
282 def ParseResourcesFullSites(self ) :
283 if self.version_json_dict['apilib_version'] != "0.2.10" :
284 self.raw_json = self.raw_json['items']
287 return self.site_dict
290 resources_fulljson_dict= {
291 'resource_id' : AddNodeId,
292 'network_address' : AddNodeNetworkAddr,
294 'radio': AddNodeRadio,
295 'mobile': AddMobility,
298 'state':AddBootState,
302 #Parse nodes properties from OAR
303 #Put them into a dictionary with key = node id and value is a dictionary
304 #of the node properties and properties'values.
305 def ParseNodes(self):
307 #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes self.raw_json %s" %(self.raw_json)
308 for dictline in self.raw_json:
309 #print >>sys.stderr, " \r\n \r\n \t\t OARrestapi.py ParseNodes dictline %s hey" %(dictline)
311 if k in self.resources_fulljson_dict:
312 # dictionary is empty and/or a new node has to be inserted
314 node_id = self.resources_fulljson_dict[k](self,self.node_dictlist, dictline[k])
316 ret = self.resources_fulljson_dict[k](self,self.node_dictlist[node_id], dictline[k])
318 #If last property has been inserted in the property tuple list, reset node_id
320 #Turn the property tuple list (=dict value) into a dictionary
321 self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
327 def hostname_to_hrn(self, root_auth, login_base, hostname):
328 return PlXrn(auth=root_auth,hostname=login_base+'_'+hostname).get_hrn()
329 #Retourne liste de dictionnaires contenant attributs des sites
330 def ParseSites(self):
333 # Create a list of nodes per site_id
334 for node_id in self.node_dictlist.keys():
335 node = self.node_dictlist[node_id]
336 if node['site'] not in nodes_per_site:
337 nodes_per_site[node['site']] = []
338 nodes_per_site[node['site']].append(node['node_id'])
340 if node['node_id'] not in nodes_per_site[node['site']]:
341 nodes_per_site[node['site']].append(node['node_id'])
343 #Create a site dictionary with key is site_login_base (name of the site)
344 # and value is a dictionary of properties, including the list of the node_ids
345 for node_id in self.node_dictlist.keys():
346 node = self.node_dictlist[node_id]
347 node.update({'hrn':self.hostname_to_hrn(self.interface_hrn, node['site'],node['hostname'])})
348 #node['hrn'] = self.hostname_to_hrn(self.interface_hrn, node['site_login_base'],node['hostname'])
349 self.node_dictlist.update({node_id:node})
351 if node['site'] not in self.site_dict:
352 self.site_dict[node['site']] = {'site':node['site'],
353 'node_ids':nodes_per_site[node['site']],
354 'latitude':"48.83726",
355 'longitude':"- 2.10336",'name':config.SFA_REGISTRY_ROOT_AUTH,
356 'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
357 'max_slivers':None, 'is_public':True, 'peer_site_id': None,
358 'abbreviated_name':"senslab", 'address_ids': [],
359 'url':"http,//www.senslab.info", 'person_ids':[],
360 'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
361 'date_created': None, 'peer_id': None }
362 #if node['site_login_base'] not in self.site_dict.keys():
363 #self.site_dict[node['site_login_base']] = {'login_base':node['site_login_base'],
364 #'node_ids':nodes_per_site[node['site_login_base']],
365 #'latitude':"48.83726",
366 #'longitude':"- 2.10336",'name':"senslab",
367 #'pcu_ids':[], 'max_slices':None, 'ext_consortium_id':None,
368 #'max_slivers':None, 'is_public':True, 'peer_site_id': None,
369 #'abbreviated_name':"senslab", 'address_ids': [],
370 #'url':"http,//www.senslab.info", 'person_ids':[],
371 #'site_tag_ids':[], 'enabled': True, 'slice_ids':[],
372 #'date_created': None, 'peer_id': None }
377 OARrequests_uri_dict = {
378 'GET_version': {'uri':'/oarapi/version.json', 'parse_func': ParseVersion},
379 'GET_timezone':{'uri':'/oarapi/timezone.json' ,'parse_func': ParseTimezone },
380 'GET_jobs': {'uri':'/oarapi/jobs.json','parse_func': ParseJobs},
381 'GET_jobs_id': {'uri':'/oarapi/jobs/id.json','parse_func': ParseJobsIds},
382 'GET_jobs_id_resources': {'uri':'/oarapi/jobs/id/resources.json','parse_func': ParseJobsIdResources},
383 'GET_jobs_table': {'uri':'/oarapi/jobs/table.json','parse_func': ParseJobsTable},
384 'GET_jobs_details': {'uri':'/oarapi/jobs/details.json','parse_func': ParseJobsDetails},
385 'GET_resources_full': {'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFull},
386 'GET_sites':{'uri':'/oarapi/resources/full.json','parse_func': ParseResourcesFullSites},
387 'GET_resources':{'uri':'/oarapi/resources.json' ,'parse_func': ParseResources},
388 'DELETE_jobs_id':{'uri':'/oarapi/jobs/id.json' ,'parse_func': ParseDeleteJobs}
392 def __init__(self, srv ):
393 self.version_json_dict= { 'api_version' : None , 'apilib_version' :None, 'api_timezone': None, 'api_timestamp': None, 'oar_version': None ,}
394 self.config = Config()
395 self.interface_hrn = self.config.SFA_INTERFACE_HRN
396 self.timezone_json_dict = { 'timezone': None, 'api_timestamp': None, }
397 self.jobs_json_dict = { 'total' : None, 'links' : [] , 'offset':None , 'items' : [] , }
398 self.jobs_table_json_dict = self.jobs_json_dict
399 self.jobs_details_json_dict = self.jobs_json_dict
401 self.node_dictlist = {}
404 self.SendRequest("GET_version")
406 def SendRequest(self,request, strval = None , username = None):
407 if request in OARrequests_get_uri_dict:
408 self.raw_json = self.server.GETRequestToOARRestAPI(request,strval,username)
409 return self.OARrequests_uri_dict[request]['parse_func'](self)
411 print>>sys.stderr, "\r\n OARGetParse __init__ : ERROR_REQUEST " ,request