Adding more error check in OARrestapi.
[sfa.git] / sfa / iotlab / OARrestapi.py
1 """
2 File used to handle issuing request to OAR and parse OAR's JSON responses.
3 Contains the following classes:
4 - JsonPage : handles multiple pages OAR answers.
5 - OARRestapi : handles issuing POST or GET requests to OAR.
6 - ParsingResourcesFull : dedicated to parsing OAR's answer to a get resources
7 full request.
8 - OARGETParser : handles parsing the Json answers to different GET requests.
9
10 """
11 from httplib import HTTPConnection, HTTPException, NotConnected
12 import json
13 from sfa.util.config import Config
14 from sfa.util.sfalogging import logger
15 import os.path
16
17
18 class JsonPage:
19
20     """Class used to manipulate json pages given by OAR.
21
22     In case the json answer from a GET request is too big to fit in one json
23     page, this class provides helper methods to retrieve all the pages and
24     store them in a list before putting them into one single json dictionary,
25     facilitating the parsing.
26
27     """
28
29     def __init__(self):
30         """Defines attributes to manipulate and parse the json pages.
31
32         """
33         #All are boolean variables
34         self.concatenate = False
35         #Indicates end of data, no more pages to be loaded.
36         self.end = False
37         self.next_page = False
38         #Next query address
39         self.next_offset = None
40         #Json page
41         self.raw_json = None
42
43     def FindNextPage(self):
44         """
45         Gets next data page from OAR when the query's results are too big to
46         be transmitted in a single page. Uses the "links' item in the json
47         returned to check if an additionnal page has to be loaded. Updates
48         object attributes next_page, next_offset, and end.
49
50         """
51         if "links" in self.raw_json:
52             for page in self.raw_json['links']:
53                 if page['rel'] == 'next':
54                     self.concatenate = True
55                     self.next_page = True
56                     self.next_offset = "?" + page['href'].split("?")[1]
57                     return
58
59         if self.concatenate:
60             self.end = True
61             self.next_page = False
62             self.next_offset = None
63
64             return
65
66         #Otherwise, no next page and no concatenate, must be a single page
67         #Concatenate the single page and get out of here.
68         else:
69             self.next_page = False
70             self.concatenate = True
71             self.next_offset = None
72             return
73
74     @staticmethod
75     def ConcatenateJsonPages(saved_json_list):
76         """
77         If the json answer is too big to be contained in a single page,
78         all the pages have to be loaded and saved before being appended to the
79         first page.
80
81         :param saved_json_list: list of all the stored pages, including the
82             first page.
83         :type saved_json_list: list
84         :returns: Returns a dictionary with all the pages saved in the
85             saved_json_list. The key of the dictionary is 'items'.
86         :rtype: dict
87
88
89         .. seealso:: SendRequest
90         .. warning:: Assumes the apilib is 0.2.10 (with the 'items' key in the
91             raw json dictionary)
92
93         """
94         #reset items list
95
96         tmp = {}
97         tmp['items'] = []
98
99         for page in saved_json_list:
100             tmp['items'].extend(page['items'])
101         return tmp
102
103     def ResetNextPage(self):
104         """
105         Resets all the Json page attributes (next_page, next_offset,
106         concatenate, end). Has to be done before getting another json answer
107         so that the previous page status does not affect the new json load.
108
109         """
110         self.next_page = True
111         self.next_offset = None
112         self.concatenate = False
113         self.end = False
114
115
116 class OARrestapi:
117     """Class used to connect to the OAR server and to send GET and POST
118     requests.
119
120     """
121
122     # classes attributes
123
124     OAR_REQUEST_POST_URI_DICT = {'POST_job': {'uri': '/oarapi/jobs.json'},
125                                  'DELETE_jobs_id':
126                                  {'uri': '/oarapi/jobs/id.json'},
127                                  }
128
129     POST_FORMAT = {'json': {'content': "application/json", 'object': json}}
130
131     #OARpostdatareqfields = {'resource' :"/nodes=", 'command':"sleep", \
132                             #'workdir':"/home/", 'walltime':""}
133
134     def __init__(self, config_file='/etc/sfa/oar_config.py'):
135         self.oarserver = {}
136         self.oarserver['uri'] = None
137         self.oarserver['postformat'] = 'json'
138
139         try:
140             execfile(config_file, self.__dict__)
141
142             self.config_file = config_file
143             # path to configuration data
144             self.config_path = os.path.dirname(config_file)
145
146         except IOError:
147             raise IOError, "Could not find or load the configuration file: %s" \
148                 % config_file
149         #logger.setLevelDebug()
150         self.oarserver['ip'] = self.OAR_IP
151         self.oarserver['port'] = self.OAR_PORT
152         self.jobstates = ['Terminated', 'Hold', 'Waiting', 'toLaunch',
153                           'toError', 'toAckReservation', 'Launching',
154                           'Finishing', 'Running', 'Suspended', 'Resuming',
155                           'Error']
156
157         self.parser = OARGETParser(self)
158
159
160     def GETRequestToOARRestAPI(self, request, strval=None,
161                                next_page=None, username=None):
162
163         """Makes a GET request to OAR.
164
165         Fetch the uri associated with the resquest stored in
166         OARrequests_uri_dict, adds the username if needed and if available, adds
167         strval to the request uri if needed, connects to OAR and issues the GET
168         request. Gets the json reply.
169
170         :param request: One of the known get requests that are keys in the
171             OARrequests_uri_dict.
172         :param strval: used when a job id has to be specified.
173         :param next_page: used to tell OAR to send the next page for this
174             Get request. Is appended to the GET uri.
175         :param username: used when a username has to be specified, when looking
176             for jobs scheduled by a particular user  for instance.
177
178         :type request: string
179         :type strval: integer
180         :type next_page: boolean
181         :type username: string
182         :returns: a json dictionary if OAR successfully processed the GET
183             request.
184
185         .. seealso:: OARrequests_uri_dict
186         """
187         self.oarserver['uri'] = \
188             OARGETParser.OARrequests_uri_dict[request]['uri']
189         #Get job details with username
190         if 'owner' in OARGETParser.OARrequests_uri_dict[request] and username:
191             self.oarserver['uri'] += \
192                 OARGETParser.OARrequests_uri_dict[request]['owner'] + username
193         headers = {}
194         data = json.dumps({})
195         logger.debug("OARrestapi \tGETRequestToOARRestAPI %s" % (request))
196         if strval:
197             self.oarserver['uri'] = self.oarserver['uri'].\
198                 replace("id", str(strval))
199
200         if next_page:
201             self.oarserver['uri'] += next_page
202
203         if username:
204             headers['X-REMOTE_IDENT'] = username
205
206         logger.debug("OARrestapi: \t  GETRequestToOARRestAPI  \
207                         self.oarserver['uri'] %s strval %s"
208                      % (self.oarserver['uri'], strval))
209         try:
210             #seems that it does not work if we don't add this
211             headers['content-length'] = '0'
212
213             conn = HTTPConnection(self.oarserver['ip'],
214                                   self.oarserver['port'])
215             conn.request("GET", self.oarserver['uri'], data, headers)
216             resp = conn.getresponse()
217             body = resp.read()
218         except Exception as error:
219             logger.log_exc("GET_OAR_SRVR : Connection error: %s "
220                 % (error))
221             raise Exception ("GET_OAR_SRVR : Connection error %s " %(error))
222
223         finally:
224             conn.close()
225
226         # except HTTPException, error:
227         #     logger.log_exc("GET_OAR_SRVR : Problem with OAR server : %s "
228         #                    % (error))
229             #raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
230         if resp.status >= 400:
231             raise ValueError ("Response Error %s, %s" %(resp.status,
232                 resp.reason))
233         try:
234             js_dict = json.loads(body)
235             #print "\r\n \t\t\t js_dict keys" , js_dict.keys(), " \r\n", js_dict
236             return js_dict
237
238         except ValueError, error:
239             logger.log_exc("Failed to parse Server Response: %s ERROR %s"
240                            % (body, error))
241             #raise ServerError("Failed to parse Server Response:" + js)
242
243
244     def POSTRequestToOARRestAPI(self, request, datadict, username=None):
245         """ Used to post a job on OAR , along with data associated
246         with the job.
247
248         """
249
250         #first check that all params for are OK
251         try:
252             self.oarserver['uri'] = \
253                 self.OAR_REQUEST_POST_URI_DICT[request]['uri']
254
255         except KeyError:
256             logger.log_exc("OARrestapi \tPOSTRequestToOARRestAPI request not \
257                              valid")
258             return
259         if datadict and 'strval' in datadict:
260             self.oarserver['uri'] = self.oarserver['uri'].replace("id", \
261                                                 str(datadict['strval']))
262             del datadict['strval']
263
264         data = json.dumps(datadict)
265         headers = {'X-REMOTE_IDENT':username, \
266                 'content-type': self.POST_FORMAT['json']['content'], \
267                 'content-length':str(len(data))}
268         try :
269
270             conn = HTTPConnection(self.oarserver['ip'], \
271                                         self.oarserver['port'])
272             conn.request("POST", self.oarserver['uri'], data, headers)
273             resp = conn.getresponse()
274             body = resp.read()
275
276         except NotConnected:
277             logger.log_exc("POSTRequestToOARRestAPI NotConnected ERROR: \
278                             data %s \r\n \t\n \t\t headers %s uri %s" \
279                             %(data,headers,self.oarserver['uri']))
280         except Exception as error:
281             logger.log_exc("POST_OAR_SERVER : Connection error: %s "
282                 % (error))
283             raise Exception ("POST_OAR_SERVER : Connection error %s " %(error))
284
285         finally:
286             conn.close()
287
288         if resp.status >= 400:
289             raise ValueError ("Response Error %s, %s" %(resp.status,
290                 resp.reason))
291
292
293         try:
294             answer = json.loads(body)
295             logger.debug("POSTRequestToOARRestAPI : answer %s" % (answer))
296             return answer
297
298         except ValueError, error:
299             logger.log_exc("Failed to parse Server Response: error %s  \
300                             %s" %(error))
301             #raise ServerError("Failed to parse Server Response:" + answer)
302
303
304 class ParsingResourcesFull():
305     """
306     Class dedicated to parse the json response from a GET_resources_full from
307     OAR.
308
309     """
310     def __init__(self):
311         """
312         Set the parsing dictionary. Works like a switch case, if the key is
313         found in the dictionary, then the associated function is called.
314         This is used in ParseNodes to create an usable dictionary from
315         the Json returned by OAR when issuing a GET resources full request.
316
317         .. seealso:: ParseNodes
318
319         """
320         self.resources_fulljson_dict = {
321         'network_address': self.AddNodeNetworkAddr,
322         'site':  self.AddNodeSite,
323         # 'radio':  self.AddNodeRadio,
324         'mobile':  self.AddMobility,
325         'x':  self.AddPosX,
326         'y':  self.AddPosY,
327         'z': self.AddPosZ,
328         'archi': self.AddHardwareType,
329         'state': self.AddBootState,
330         'id': self.AddOarNodeId,
331         'mobility_type': self.AddMobilityType,
332         }
333
334
335
336     def AddOarNodeId(self, tuplelist, value):
337         """Adds Oar internal node id to the nodes' attributes.
338
339         Appends tuple ('oar_id', node_id) to the tuplelist. Used by ParseNodes.
340
341         .. seealso:: ParseNodes
342
343         """
344
345         tuplelist.append(('oar_id', int(value)))
346
347
348     def AddNodeNetworkAddr(self, dictnode, value):
349         """First parsing function to be called to parse the json returned by OAR
350         answering a GET_resources (/oarapi/resources.json) request.
351
352         When a new node is found in the json, this function is responsible for
353         creating a new entry in the dictionary for storing information on this
354         specific node. The key is the node network address, which is also the
355         node's hostname.
356         The value associated with the key is a tuple list.It contains all
357         the nodes attributes. The tuplelist will later be turned into a dict.
358
359         :param dictnode: should be set to the OARGETParser atribute
360             node_dictlist. It will store the information on the nodes.
361         :param value: the node_id is the network_address in the raw json.
362         :type value: string
363         :type dictnode: dictionary
364
365         .. seealso: ParseResources, ParseNodes
366         """
367
368         node_id = value
369         dictnode[node_id] = [('node_id', node_id),('hostname', node_id) ]
370
371         return node_id
372
373     def AddNodeSite(self, tuplelist, value):
374         """Add the site's node to the dictionary.
375
376
377         :param tuplelist: tuple list on which to add the node's site.
378             Contains the other node attributes as well.
379         :param value: value to add to the tuple list, in this case the node's
380             site.
381         :type tuplelist: list
382         :type value: string
383
384         .. seealso:: AddNodeNetworkAddr
385
386         """
387         tuplelist.append(('site', str(value)))
388
389     # def AddNodeRadio(tuplelist, value):
390     #     """Add thenode's radio chipset type to the tuple list.
391
392     #     :param tuplelist: tuple list on which to add the node's mobility
393                 # status. The tuplelist is the value associated with the node's
394                 # id in the OARGETParser
395     #          's dictionary node_dictlist.
396     #     :param value: name of the radio chipset on the node.
397     #     :type tuplelist: list
398     #     :type value: string
399
400     #     .. seealso:: AddNodeNetworkAddr
401
402     #     """
403     #     tuplelist.append(('radio', str(value)))
404
405     def AddMobilityType(self, tuplelist, value):
406         """Adds  which kind of mobility it is, train or roomba robot.
407
408         :param tuplelist: tuple list on which to add the node's mobility status.
409             The tuplelist is the value associated with the node's id in the
410             OARGETParser's dictionary node_dictlist.
411         :param value: tells if a node is a mobile node or not. The value is
412             found in the json.
413
414         :type tuplelist: list
415         :type value: integer
416
417         """
418         tuplelist.append(('mobility_type', str(value)))
419
420
421     def AddMobility(self, tuplelist, value):
422         """Add if the node is a mobile node or not to the tuple list.
423
424         :param tuplelist: tuple list on which to add the node's mobility status.
425             The tuplelist is the value associated with the node's id in the
426             OARGETParser's dictionary node_dictlist.
427         :param value: tells if a node is a mobile node or not. The value is found
428             in the json.
429
430         :type tuplelist: list
431         :type value: integer
432
433         .. seealso:: AddNodeNetworkAddr
434
435         """
436         if value is 0:
437             tuplelist.append(('mobile', 'False'))
438         else:
439             tuplelist.append(('mobile', 'True'))
440
441
442     def AddPosX(self, tuplelist, value):
443         """Add the node's position on the x axis.
444
445         :param tuplelist: tuple list on which to add the node's position . The
446             tuplelist is the value associated with the node's id in the
447             OARGETParser's dictionary node_dictlist.
448         :param value: the position x.
449
450         :type tuplelist: list
451         :type value: integer
452
453          .. seealso:: AddNodeNetworkAddr
454
455         """
456         tuplelist.append(('posx', value ))
457
458
459
460     def AddPosY(self, tuplelist, value):
461         """Add the node's position on the y axis.
462
463         :param tuplelist: tuple list on which to add the node's position . The
464             tuplelist is the value associated with the node's id in the
465             OARGETParser's dictionary node_dictlist.
466         :param value: the position y.
467
468         :type tuplelist: list
469         :type value: integer
470
471          .. seealso:: AddNodeNetworkAddr
472
473         """
474         tuplelist.append(('posy', value))
475
476
477
478     def AddPosZ(self, tuplelist, value):
479         """Add the node's position on the z axis.
480
481         :param tuplelist: tuple list on which to add the node's position . The
482             tuplelist is the value associated with the node's id in the
483             OARGETParser's dictionary node_dictlist.
484         :param value: the position z.
485
486         :type tuplelist: list
487         :type value: integer
488
489          .. seealso:: AddNodeNetworkAddr
490
491         """
492
493         tuplelist.append(('posz', value))
494
495
496
497     def AddBootState(tself, tuplelist, value):
498         """Add the node's state, Alive or Suspected.
499
500         :param tuplelist: tuple list on which to add the node's state . The
501             tuplelist is the value associated with the node's id in the
502             OARGETParser 's dictionary node_dictlist.
503         :param value: node's state.
504
505         :type tuplelist: list
506         :type value: string
507
508          .. seealso:: AddNodeNetworkAddr
509
510         """
511         tuplelist.append(('boot_state', str(value)))
512
513
514     def AddHardwareType(self, tuplelist, value):
515         """Add the node's hardware model and radio chipset type to the tuple
516         list.
517
518         :param tuplelist: tuple list on which to add the node's architecture
519             and radio chipset type.
520         :param value: hardware type: radio chipset. The value contains both the
521             architecture and the radio chipset, separated by a colon.
522         :type tuplelist: list
523         :type value: string
524
525         .. seealso:: AddNodeNetworkAddr
526
527         """
528
529         value_list = value.split(':')
530         tuplelist.append(('archi', value_list[0]))
531         tuplelist.append(('radio', value_list[1]))
532
533
534 class OARGETParser:
535     """Class providing parsing methods associated to specific GET requests.
536
537     """
538
539     def __init__(self, srv):
540         self.version_json_dict = {
541             'api_version': None, 'apilib_version': None,
542             'api_timezone': None, 'api_timestamp': None, 'oar_version': None}
543         self.config = Config()
544         self.interface_hrn = self.config.SFA_INTERFACE_HRN
545         self.timezone_json_dict = {
546             'timezone': None, 'api_timestamp': None, }
547         #self.jobs_json_dict = {
548             #'total' : None, 'links' : [],\
549             #'offset':None , 'items' : [], }
550         #self.jobs_table_json_dict = self.jobs_json_dict
551         #self.jobs_details_json_dict = self.jobs_json_dict
552         self.server = srv
553         self.node_dictlist = {}
554
555         self.json_page = JsonPage()
556         self.parsing_resourcesfull = ParsingResourcesFull()
557         self.site_dict = {}
558         self.jobs_list = []
559         self.SendRequest("GET_version")
560
561
562     def ParseVersion(self):
563         """Parses the OAR answer to the GET_version ( /oarapi/version.json.)
564
565         Finds the OAR apilib version currently used. Has an impact on the json
566         structure returned by OAR, so the version has to be known before trying
567         to parse the jsons returned after a get request has been issued.
568         Updates the attribute version_json_dict.
569
570         """
571
572         if 'oar_version' in self.json_page.raw_json:
573             self.version_json_dict.update(
574                 api_version=self.json_page.raw_json['api_version'],
575                 apilib_version=self.json_page.raw_json['apilib_version'],
576                 api_timezone=self.json_page.raw_json['api_timezone'],
577                 api_timestamp=self.json_page.raw_json['api_timestamp'],
578                 oar_version=self.json_page.raw_json['oar_version'])
579         else:
580             self.version_json_dict.update(
581                 api_version=self.json_page.raw_json['api'],
582                 apilib_version=self.json_page.raw_json['apilib'],
583                 api_timezone=self.json_page.raw_json['api_timezone'],
584                 api_timestamp=self.json_page.raw_json['api_timestamp'],
585                 oar_version=self.json_page.raw_json['oar'])
586
587         print self.version_json_dict['apilib_version']
588
589
590     def ParseTimezone(self):
591         """Get the timezone used by OAR.
592
593         Get the timezone from the answer to the GET_timezone request.
594         :return: api_timestamp and api timezone.
595         :rype: integer, integer
596
597         .. warning:: unused.
598         """
599         api_timestamp = self.json_page.raw_json['api_timestamp']
600         api_tz = self.json_page.raw_json['timezone']
601         return api_timestamp, api_tz
602
603     def ParseJobs(self):
604         """Called when a GET_jobs request has been issued to OAR.
605
606         Corresponds to /oarapi/jobs.json uri. Currently returns the raw json
607         information dict.
608         :returns: json_page.raw_json
609         :rtype: dictionary
610
611         .. warning:: Does not actually parse the information in the json. SA
612             15/07/13.
613
614         """
615         self.jobs_list = []
616         print " ParseJobs "
617         return self.json_page.raw_json
618
619     def ParseJobsTable(self):
620         """In case we need to use the job table in the future.
621
622         Associated with the GET_jobs_table : '/oarapi/jobs/table.json uri.
623         .. warning:: NOT USED. DOES NOTHING.
624         """
625         print "ParseJobsTable"
626
627     def ParseJobsDetails(self):
628         """Currently only returns the same json in self.json_page.raw_json.
629
630         .. todo:: actually parse the json
631         .. warning:: currently, this function is not used a lot, so I have no
632             idea what could  be useful to parse, returning the full json. NT
633         """
634
635         #logger.debug("ParseJobsDetails %s " %(self.json_page.raw_json))
636         return self.json_page.raw_json
637
638
639     def ParseJobsIds(self):
640         """Associated with the GET_jobs_id OAR request.
641
642         Parses the json dict (OAR answer) to the GET_jobs_id request
643         /oarapi/jobs/id.json.
644
645
646         :returns: dictionary whose keys are listed in the local variable
647             job_resources and values that are in the json dictionary returned
648             by OAR with the job information.
649         :rtype: dict
650
651         """
652         job_resources = ['wanted_resources', 'name', 'id', 'start_time',
653                          'state', 'owner', 'walltime', 'message']
654
655         # Unused variable providing the contents of the json dict returned from
656         # get job resources full request
657         job_resources_full = [
658             'launching_directory', 'links',
659             'resubmit_job_id', 'owner', 'events', 'message',
660             'scheduled_start', 'id', 'array_id', 'exit_code',
661             'properties', 'state', 'array_index', 'walltime',
662             'type', 'initial_request', 'stop_time', 'project',
663             'start_time',  'dependencies', 'api_timestamp', 'submission_time',
664             'reservation', 'stdout_file', 'types', 'cpuset_name',
665             'name', 'wanted_resources', 'queue', 'stderr_file', 'command']
666
667
668         job_info = self.json_page.raw_json
669         #logger.debug("OARESTAPI ParseJobsIds %s" %(self.json_page.raw_json))
670         values = []
671         try:
672             for k in job_resources:
673                 values.append(job_info[k])
674             return dict(zip(job_resources, values))
675
676         except KeyError:
677             logger.log_exc("ParseJobsIds KeyError ")
678
679
680     def ParseJobsIdResources(self):
681         """ Parses the json produced by the request
682         /oarapi/jobs/id/resources.json.
683         Returns a list of oar node ids that are scheduled for the
684         given job id.
685
686         """
687         job_resources = []
688         for resource in self.json_page.raw_json['items']:
689             job_resources.append(resource['id'])
690
691         return job_resources
692
693     def ParseResources(self):
694         """ Parses the json produced by a get_resources request on oar."""
695
696         #logger.debug("OARESTAPI \tParseResources " )
697         #resources are listed inside the 'items' list from the json
698         self.json_page.raw_json = self.json_page.raw_json['items']
699         self.ParseNodes()
700
701     def ParseReservedNodes(self):
702         """  Returns an array containing the list of the jobs scheduled
703         with the reserved nodes if available.
704
705         :returns: list of job dicts, each dict containing the following keys:
706             t_from, t_until, resources_ids (of the reserved nodes for this job).
707             If the information is not available, default values will be set for
708             these keys. The other keys are : state, lease_id and user.
709         :rtype: list
710
711         """
712
713         #resources are listed inside the 'items' list from the json
714         reservation_list = []
715         job = {}
716         #Parse resources info
717         for json_element in self.json_page.raw_json['items']:
718             #In case it is a real reservation (not asap case)
719             if json_element['scheduled_start']:
720                 job['t_from'] = json_element['scheduled_start']
721                 job['t_until'] = int(json_element['scheduled_start']) + \
722                     int(json_element['walltime'])
723                 #Get resources id list for the job
724                 job['resource_ids'] = [node_dict['id'] for node_dict
725                                        in json_element['resources']]
726             else:
727                 job['t_from'] = "As soon as possible"
728                 job['t_until'] = "As soon as possible"
729                 job['resource_ids'] = ["Undefined"]
730
731             job['state'] = json_element['state']
732             job['lease_id'] = json_element['id']
733
734             job['user'] = json_element['owner']
735             #logger.debug("OARRestapi \tParseReservedNodes job %s" %(job))
736             reservation_list.append(job)
737             #reset dict
738             job = {}
739         return reservation_list
740
741     def ParseRunningJobs(self):
742         """ Gets the list of nodes currently in use from the attributes of the
743         running jobs.
744
745         :returns: list of hostnames, the nodes that are currently involved in
746             running jobs.
747         :rtype: list
748
749
750         """
751         logger.debug("OARESTAPI \tParseRunningJobs_________________ ")
752         #resources are listed inside the 'items' list from the json
753         nodes = []
754         for job in self.json_page.raw_json['items']:
755             for node in job['nodes']:
756                 nodes.append(node['network_address'])
757         return nodes
758
759     def ChangeRawJsonDependingOnApilibVersion(self):
760         """
761         Check if the OAR apilib version is different from 0.2.10, in which case
762         the Json answer is also dict instead as a plain list.
763
764         .. warning:: the whole code is assuming the json contains a 'items' key
765         .. seealso:: ConcatenateJsonPages, ParseJobs, ParseReservedNodes,
766             ParseJobsIdResources, ParseResources, ParseRunningJobs
767         .. todo:: Clean the whole code. Either suppose the  apilib will always
768             provide the 'items' key, or handle different options.
769         """
770
771         if self.version_json_dict['apilib_version'] != "0.2.10":
772             self.json_page.raw_json = self.json_page.raw_json['items']
773
774     def ParseDeleteJobs(self):
775         """ No need to parse anything in this function.A POST
776         is done to delete the job.
777
778         """
779         return
780
781     def ParseResourcesFull(self):
782         """ This method is responsible for parsing all the attributes
783         of all the nodes returned by OAR when issuing a get resources full.
784         The information from the nodes and the sites are separated.
785         Updates the node_dictlist so that the dictionnary of the platform's
786         nodes is available afterwards.
787
788         :returns: node_dictlist, a list of dictionaries about the nodes and
789             their properties.
790         :rtype: list
791
792         """
793         logger.debug("OARRESTAPI ParseResourcesFull___________ ")
794         #print self.json_page.raw_json[1]
795         #resources are listed inside the 'items' list from the json
796         self.ChangeRawJsonDependingOnApilibVersion()
797         self.ParseNodes()
798         self.ParseSites()
799         return self.node_dictlist
800
801     def ParseResourcesFullSites(self):
802         """ Called by GetSites which is unused.
803         Originally used to get information from the sites, with for each site
804         the list of nodes it has, along with their properties.
805
806         :return: site_dict, dictionary of sites
807         :rtype: dict
808
809         .. warning:: unused
810         .. seealso:: GetSites (IotlabTestbedAPI)
811
812         """
813         self.ChangeRawJsonDependingOnApilibVersion()
814         self.ParseNodes()
815         self.ParseSites()
816         return self.site_dict
817
818
819     def ParseNodes(self):
820         """ Parse nodes properties from OAR
821         Put them into a dictionary with key = node id and value is a dictionary
822         of the node properties and properties'values.
823
824         """
825         node_id = None
826         _resources_fulljson_dict = \
827             self.parsing_resourcesfull.resources_fulljson_dict
828         keys = _resources_fulljson_dict.keys()
829         keys.sort()
830
831         for dictline in self.json_page.raw_json:
832             node_id = None
833             # dictionary is empty and/or a new node has to be inserted
834             node_id = _resources_fulljson_dict['network_address'](
835                 self.node_dictlist, dictline['network_address'])
836             for k in keys:
837                 if k in dictline:
838                     if k == 'network_address':
839                         continue
840
841                     _resources_fulljson_dict[k](
842                         self.node_dictlist[node_id], dictline[k])
843
844             #The last property has been inserted in the property tuple list,
845             #reset node_id
846             #Turn the property tuple list (=dict value) into a dictionary
847             self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
848             node_id = None
849
850     @staticmethod
851     def iotlab_hostname_to_hrn(root_auth,  hostname):
852         """
853         Transforms a node hostname into a SFA hrn.
854
855         :param root_auth: Name of the root authority of the SFA server. In
856             our case, it is set to iotlab.
857         :param hostname: node's hotname, given by OAR.
858         :type root_auth: string
859         :type hostname: string
860         :returns: inserts the root_auth and '.' before the hostname.
861         :rtype: string
862
863         """
864         return root_auth + '.' + hostname
865
866     def ParseSites(self):
867         """ Returns a list of dictionnaries containing the sites' attributes."""
868
869         nodes_per_site = {}
870         config = Config()
871         #logger.debug(" OARrestapi.py \tParseSites  self.node_dictlist %s"\
872                                                         #%(self.node_dictlist))
873         # Create a list of nodes per site_id
874         for node_id in self.node_dictlist:
875             node = self.node_dictlist[node_id]
876
877             if node['site'] not in nodes_per_site:
878                 nodes_per_site[node['site']] = []
879                 nodes_per_site[node['site']].append(node['node_id'])
880             else:
881                 if node['node_id'] not in nodes_per_site[node['site']]:
882                     nodes_per_site[node['site']].append(node['node_id'])
883
884         #Create a site dictionary whose key is site_login_base
885         # (name of the site) and value is a dictionary of properties,
886         # including the list of the node_ids
887         for node_id in self.node_dictlist:
888             node = self.node_dictlist[node_id]
889             node.update({'hrn': self.iotlab_hostname_to_hrn(self.interface_hrn,
890                                                             node['hostname'])})
891             self.node_dictlist.update({node_id: node})
892
893             if node['site'] not in self.site_dict:
894                 self.site_dict[node['site']] = {
895                     'site': node['site'],
896                     'node_ids': nodes_per_site[node['site']],
897                     'latitude': "48.83726",
898                     'longitude': "- 2.10336",
899                     'name': config.SFA_REGISTRY_ROOT_AUTH,
900                     'pcu_ids': [], 'max_slices': None,
901                     'ext_consortium_id': None,
902                     'max_slivers': None, 'is_public': True,
903                     'peer_site_id': None,
904                     'abbreviated_name': "iotlab", 'address_ids': [],
905                     'url': "https://portal.senslab.info", 'person_ids': [],
906                     'site_tag_ids': [], 'enabled': True,  'slice_ids': [],
907                     'date_created': None, 'peer_id': None
908                 }
909
910     OARrequests_uri_dict = {
911         'GET_version':
912         {'uri': '/oarapi/version.json', 'parse_func': ParseVersion},
913
914         'GET_timezone':
915         {'uri': '/oarapi/timezone.json', 'parse_func': ParseTimezone},
916
917         'GET_jobs':
918         {'uri': '/oarapi/jobs.json', 'parse_func': ParseJobs},
919
920         'GET_jobs_id':
921         {'uri': '/oarapi/jobs/id.json', 'parse_func': ParseJobsIds},
922
923         'GET_jobs_id_resources':
924         {'uri': '/oarapi/jobs/id/resources.json',
925         'parse_func': ParseJobsIdResources},
926
927         'GET_jobs_table':
928         {'uri': '/oarapi/jobs/table.json', 'parse_func': ParseJobsTable},
929
930         'GET_jobs_details':
931         {'uri': '/oarapi/jobs/details.json', 'parse_func': ParseJobsDetails},
932
933         'GET_reserved_nodes':
934         {'uri':
935         '/oarapi/jobs/details.json?state=Running,Waiting,Launching',
936         'owner': '&user=', 'parse_func': ParseReservedNodes},
937
938         'GET_running_jobs':
939         {'uri': '/oarapi/jobs/details.json?state=Running',
940         'parse_func': ParseRunningJobs},
941
942         'GET_resources_full':
943         {'uri': '/oarapi/resources/full.json',
944         'parse_func': ParseResourcesFull},
945
946         'GET_sites':
947         {'uri': '/oarapi/resources/full.json',
948         'parse_func': ParseResourcesFullSites},
949
950         'GET_resources':
951         {'uri': '/oarapi/resources.json', 'parse_func': ParseResources},
952
953         'DELETE_jobs_id':
954         {'uri': '/oarapi/jobs/id.json', 'parse_func': ParseDeleteJobs}}
955
956
957     def SendRequest(self, request, strval=None, username=None):
958         """ Connects to OAR , sends the valid GET requests and uses
959         the appropriate json parsing functions.
960
961         :returns: calls to the appropriate parsing function, associated with the
962             GET request
963         :rtype: depends on the parsing function called.
964
965         .. seealso:: OARrequests_uri_dict
966         """
967         save_json = None
968
969         self.json_page.ResetNextPage()
970         save_json = []
971
972         if request in self.OARrequests_uri_dict:
973             while self.json_page.next_page:
974                 self.json_page.raw_json = self.server.GETRequestToOARRestAPI(
975                     request,
976                     strval,
977                     self.json_page.next_offset,
978                     username)
979                 self.json_page.FindNextPage()
980                 if self.json_page.concatenate:
981                     save_json.append(self.json_page.raw_json)
982
983             if self.json_page.concatenate and self.json_page.end:
984                 self.json_page.raw_json = \
985                     self.json_page.ConcatenateJsonPages(save_json)
986
987             return self.OARrequests_uri_dict[request]['parse_func'](self)
988         else:
989             logger.error("OARRESTAPI OARGetParse __init__ : ERROR_REQUEST "
990                          % (request))