40aad500fea41ef845bd7597e629a272a8aed17f
[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()).read()
217             conn.close()
218
219         except HTTPException, error:
220             logger.log_exc("GET_OAR_SRVR : Problem with OAR server : %s "
221                            % (error))
222             #raise ServerError("GET_OAR_SRVR : Could not reach OARserver")
223         try:
224             js_dict = json.loads(resp)
225             #print "\r\n \t\t\t js_dict keys" , js_dict.keys(), " \r\n", js_dict
226             return js_dict
227
228         except ValueError, error:
229             logger.log_exc("Failed to parse Server Response: %s ERROR %s"
230                            % (js_dict, error))
231             #raise ServerError("Failed to parse Server Response:" + js)
232
233
234     def POSTRequestToOARRestAPI(self, request, datadict, username=None):
235         """ Used to post a job on OAR , along with data associated
236         with the job.
237
238         """
239
240         #first check that all params for are OK
241         try:
242             self.oarserver['uri'] = \
243                 self.OAR_REQUEST_POST_URI_DICT[request]['uri']
244
245         except KeyError:
246             logger.log_exc("OARrestapi \tPOSTRequestToOARRestAPI request not \
247                              valid")
248             return
249         if datadict and 'strval' in datadict:
250             self.oarserver['uri'] = self.oarserver['uri'].replace("id", \
251                                                 str(datadict['strval']))
252             del datadict['strval']
253
254         data = json.dumps(datadict)
255         headers = {'X-REMOTE_IDENT':username, \
256                 'content-type': self.POST_FORMAT['json']['content'], \
257                 'content-length':str(len(data))}
258         try :
259
260             conn = HTTPConnection(self.oarserver['ip'], \
261                                         self.oarserver['port'])
262             conn.request("POST", self.oarserver['uri'], data, headers)
263             resp = (conn.getresponse()).read()
264             conn.close()
265         except NotConnected:
266             logger.log_exc("POSTRequestToOARRestAPI NotConnected ERROR: \
267                             data %s \r\n \t\n \t\t headers %s uri %s" \
268                             %(data,headers,self.oarserver['uri']))
269
270             #raise ServerError("POST_OAR_SRVR : error")
271
272         try:
273             answer = json.loads(resp)
274             logger.debug("POSTRequestToOARRestAPI : answer %s" % (answer))
275             return answer
276
277         except ValueError, error:
278             logger.log_exc("Failed to parse Server Response: error %s  \
279                             %s" %(error))
280             #raise ServerError("Failed to parse Server Response:" + answer)
281
282
283 class ParsingResourcesFull():
284     """
285     Class dedicated to parse the json response from a GET_resources_full from
286     OAR.
287
288     """
289     def __init__(self):
290         """
291         Set the parsing dictionary. Works like a switch case, if the key is
292         found in the dictionary, then the associated function is called.
293         This is used in ParseNodes to create an usable dictionary from
294         the Json returned by OAR when issuing a GET resources full request.
295
296         .. seealso:: ParseNodes
297
298         """
299         self.resources_fulljson_dict = {
300         'network_address': self.AddNodeNetworkAddr,
301         'site':  self.AddNodeSite,
302         # 'radio':  self.AddNodeRadio,
303         'mobile':  self.AddMobility,
304         'x':  self.AddPosX,
305         'y':  self.AddPosY,
306         'z': self.AddPosZ,
307         'archi': self.AddHardwareType,
308         'state': self.AddBootState,
309         'id': self.AddOarNodeId,
310         }
311
312
313
314     def AddOarNodeId(self, tuplelist, value):
315         """Adds Oar internal node id to the nodes' attributes.
316
317         Appends tuple ('oar_id', node_id) to the tuplelist. Used by ParseNodes.
318
319         .. seealso:: ParseNodes
320
321         """
322
323         tuplelist.append(('oar_id', int(value)))
324
325
326     def AddNodeNetworkAddr(self, dictnode, value):
327         """First parsing function to be called to parse the json returned by OAR
328         answering a GET_resources (/oarapi/resources.json) request.
329
330         When a new node is found in the json, this function is responsible for
331         creating a new entry in the dictionary for storing information on this
332         specific node. The key is the node network address, which is also the
333         node's hostname.
334         The value associated with the key is a tuple list.It contains all
335         the nodes attributes. The tuplelist will later be turned into a dict.
336
337         :param dictnode: should be set to the OARGETParser atribute
338             node_dictlist. It will store the information on the nodes.
339         :param value: the node_id is the network_address in the raw json.
340         :type value: string
341         :type dictnode: dictionary
342
343         .. seealso: ParseResources, ParseNodes
344         """
345
346         node_id = value
347         dictnode[node_id] = [('node_id', node_id),('hostname', node_id) ]
348
349         return node_id
350
351     def AddNodeSite(self, tuplelist, value):
352         """Add the site's node to the dictionary.
353
354
355         :param tuplelist: tuple list on which to add the node's site.
356             Contains the other node attributes as well.
357         :param value: value to add to the tuple list, in this case the node's
358             site.
359         :type tuplelist: list
360         :type value: string
361
362         .. seealso:: AddNodeNetworkAddr
363
364         """
365         tuplelist.append(('site', str(value)))
366
367     # def AddNodeRadio(tuplelist, value):
368     #     """Add thenode's radio chipset type to the tuple list.
369
370     #     :param tuplelist: tuple list on which to add the node's mobility
371                 # status. The tuplelist is the value associated with the node's
372                 # id in the OARGETParser
373     #          's dictionary node_dictlist.
374     #     :param value: name of the radio chipset on the node.
375     #     :type tuplelist: list
376     #     :type value: string
377
378     #     .. seealso:: AddNodeNetworkAddr
379
380     #     """
381     #     tuplelist.append(('radio', str(value)))
382
383     def AddMobilityType(self, tuplelist, value):
384         """Adds  which kind of mobility it is, train or roomba robot.
385
386         :param tuplelist: tuple list on which to add the node's mobility status.
387             The tuplelist is the value associated with the node's id in the
388             OARGETParser's dictionary node_dictlist.
389         :param value: tells if a node is a mobile node or not. The value is
390             found in the json.
391
392         :type tuplelist: list
393         :type value: integer
394
395         """
396         tuplelist.append(('mobility-type', str(value)))
397
398
399     def AddMobility(self, tuplelist, value):
400         """Add if the node is a mobile node or not to the tuple list.
401
402         :param tuplelist: tuple list on which to add the node's mobility status.
403             The tuplelist is the value associated with the node's id in the
404             OARGETParser's dictionary node_dictlist.
405         :param value: tells if a node is a mobile node or not. The value is
406             found in the json.
407
408         :type tuplelist: list
409         :type value: integer
410
411         .. seealso:: AddNodeNetworkAddr
412
413         """
414         # future support of mobility type
415
416         if value is 0:
417             tuplelist.append(('mobile', 'False'))
418         else:
419             tuplelist.append(('mobile', 'True'))
420
421
422     def AddPosX(self, tuplelist, value):
423         """Add the node's position on the x axis.
424
425         :param tuplelist: tuple list on which to add the node's position . The
426             tuplelist is the value associated with the node's id in the
427             OARGETParser's dictionary node_dictlist.
428         :param value: the position x.
429
430         :type tuplelist: list
431         :type value: integer
432
433          .. seealso:: AddNodeNetworkAddr
434
435         """
436         tuplelist.append(('posx', value))
437
438
439
440     def AddPosY(self, tuplelist, value):
441         """Add the node's position on the y axis.
442
443         :param tuplelist: tuple list on which to add the node's position . The
444             tuplelist is the value associated with the node's id in the
445             OARGETParser's dictionary node_dictlist.
446         :param value: the position y.
447
448         :type tuplelist: list
449         :type value: integer
450
451          .. seealso:: AddNodeNetworkAddr
452
453         """
454         tuplelist.append(('posy', value))
455
456
457
458     def AddPosZ(self, tuplelist, value):
459         """Add the node's position on the z axis.
460
461         :param tuplelist: tuple list on which to add the node's position . The
462             tuplelist is the value associated with the node's id in the
463             OARGETParser's dictionary node_dictlist.
464         :param value: the position z.
465
466         :type tuplelist: list
467         :type value: integer
468
469          .. seealso:: AddNodeNetworkAddr
470
471         """
472
473         tuplelist.append(('posz', value))
474
475
476
477     def AddBootState(tself, tuplelist, value):
478         """Add the node's state, Alive or Suspected.
479
480         :param tuplelist: tuple list on which to add the node's state . The
481             tuplelist is the value associated with the node's id in the
482             OARGETParser 's dictionary node_dictlist.
483         :param value: node's state.
484
485         :type tuplelist: list
486         :type value: string
487
488          .. seealso:: AddNodeNetworkAddr
489
490         """
491         tuplelist.append(('boot_state', str(value)))
492
493
494     def AddHardwareType(self, tuplelist, value):
495         """Add the node's hardware model and radio chipset type to the tuple
496         list.
497
498         :param tuplelist: tuple list on which to add the node's architecture
499             and radio chipset type.
500         :param value: hardware type: radio chipset. The value contains both the
501             architecture and the radio chipset, separated by a colon.
502         :type tuplelist: list
503         :type value: string
504
505         .. seealso:: AddNodeNetworkAddr
506
507         """
508
509         value_list = value.split(':')
510         tuplelist.append(('archi', value_list[0]))
511         tuplelist.append(('radio', value_list[1]))
512
513
514 class OARGETParser:
515     """Class providing parsing methods associated to specific GET requests.
516
517     """
518
519     def __init__(self, srv):
520         self.version_json_dict = {
521             'api_version': None, 'apilib_version': None,
522             'api_timezone': None, 'api_timestamp': None, 'oar_version': None}
523         self.config = Config()
524         self.interface_hrn = self.config.SFA_INTERFACE_HRN
525         self.timezone_json_dict = {
526             'timezone': None, 'api_timestamp': None, }
527         #self.jobs_json_dict = {
528             #'total' : None, 'links' : [],\
529             #'offset':None , 'items' : [], }
530         #self.jobs_table_json_dict = self.jobs_json_dict
531         #self.jobs_details_json_dict = self.jobs_json_dict
532         self.server = srv
533         self.node_dictlist = {}
534
535         self.json_page = JsonPage()
536         self.parsing_resourcesfull = ParsingResourcesFull()
537         self.site_dict = {}
538         self.jobs_list = []
539         self.SendRequest("GET_version")
540
541
542     def ParseVersion(self):
543         """Parses the OAR answer to the GET_version ( /oarapi/version.json.)
544
545         Finds the OAR apilib version currently used. Has an impact on the json
546         structure returned by OAR, so the version has to be known before trying
547         to parse the jsons returned after a get request has been issued.
548         Updates the attribute version_json_dict.
549
550         """
551
552         if 'oar_version' in self.json_page.raw_json:
553             self.version_json_dict.update(
554                 api_version=self.json_page.raw_json['api_version'],
555                 apilib_version=self.json_page.raw_json['apilib_version'],
556                 api_timezone=self.json_page.raw_json['api_timezone'],
557                 api_timestamp=self.json_page.raw_json['api_timestamp'],
558                 oar_version=self.json_page.raw_json['oar_version'])
559         else:
560             self.version_json_dict.update(
561                 api_version=self.json_page.raw_json['api'],
562                 apilib_version=self.json_page.raw_json['apilib'],
563                 api_timezone=self.json_page.raw_json['api_timezone'],
564                 api_timestamp=self.json_page.raw_json['api_timestamp'],
565                 oar_version=self.json_page.raw_json['oar'])
566
567         print self.version_json_dict['apilib_version']
568
569
570     def ParseTimezone(self):
571         """Get the timezone used by OAR.
572
573         Get the timezone from the answer to the GET_timezone request.
574         :return: api_timestamp and api timezone.
575         :rype: integer, integer
576
577         .. warning:: unused.
578         """
579         api_timestamp = self.json_page.raw_json['api_timestamp']
580         api_tz = self.json_page.raw_json['timezone']
581         return api_timestamp, api_tz
582
583     def ParseJobs(self):
584         """Called when a GET_jobs request has been issued to OAR.
585
586         Corresponds to /oarapi/jobs.json uri. Currently returns the raw json
587         information dict.
588         :returns: json_page.raw_json
589         :rtype: dictionary
590
591         .. warning:: Does not actually parse the information in the json. SA
592             15/07/13.
593
594         """
595         self.jobs_list = []
596         print " ParseJobs "
597         return self.json_page.raw_json
598
599     def ParseJobsTable(self):
600         """In case we need to use the job table in the future.
601
602         Associated with the GET_jobs_table : '/oarapi/jobs/table.json uri.
603         .. warning:: NOT USED. DOES NOTHING.
604         """
605         print "ParseJobsTable"
606
607     def ParseJobsDetails(self):
608         """Currently only returns the same json in self.json_page.raw_json.
609
610         .. todo:: actually parse the json
611         .. warning:: currently, this function is not used a lot, so I have no
612             idea what could  be useful to parse, returning the full json. NT
613         """
614
615         #logger.debug("ParseJobsDetails %s " %(self.json_page.raw_json))
616         return self.json_page.raw_json
617
618
619     def ParseJobsIds(self):
620         """Associated with the GET_jobs_id OAR request.
621
622         Parses the json dict (OAR answer) to the GET_jobs_id request
623         /oarapi/jobs/id.json.
624
625
626         :returns: dictionary whose keys are listed in the local variable
627             job_resources and values that are in the json dictionary returned
628             by OAR with the job information.
629         :rtype: dict
630
631         """
632         job_resources = ['wanted_resources', 'name', 'id', 'start_time',
633                          'state', 'owner', 'walltime', 'message']
634
635         # Unused variable providing the contents of the json dict returned from
636         # get job resources full request
637         job_resources_full = [
638             'launching_directory', 'links',
639             'resubmit_job_id', 'owner', 'events', 'message',
640             'scheduled_start', 'id', 'array_id', 'exit_code',
641             'properties', 'state', 'array_index', 'walltime',
642             'type', 'initial_request', 'stop_time', 'project',
643             'start_time',  'dependencies', 'api_timestamp', 'submission_time',
644             'reservation', 'stdout_file', 'types', 'cpuset_name',
645             'name', 'wanted_resources', 'queue', 'stderr_file', 'command']
646
647
648         job_info = self.json_page.raw_json
649         #logger.debug("OARESTAPI ParseJobsIds %s" %(self.json_page.raw_json))
650         values = []
651         try:
652             for k in job_resources:
653                 values.append(job_info[k])
654             return dict(zip(job_resources, values))
655
656         except KeyError:
657             logger.log_exc("ParseJobsIds KeyError ")
658
659
660     def ParseJobsIdResources(self):
661         """ Parses the json produced by the request
662         /oarapi/jobs/id/resources.json.
663         Returns a list of oar node ids that are scheduled for the
664         given job id.
665
666         """
667         job_resources = []
668         for resource in self.json_page.raw_json['items']:
669             job_resources.append(resource['id'])
670
671         return job_resources
672
673     def ParseResources(self):
674         """ Parses the json produced by a get_resources request on oar."""
675
676         #logger.debug("OARESTAPI \tParseResources " )
677         #resources are listed inside the 'items' list from the json
678         self.json_page.raw_json = self.json_page.raw_json['items']
679         self.ParseNodes()
680
681     def ParseReservedNodes(self):
682         """  Returns an array containing the list of the jobs scheduled
683         with the reserved nodes if available.
684
685         :returns: list of job dicts, each dict containing the following keys:
686             t_from, t_until, resources_ids (of the reserved nodes for this job).
687             If the information is not available, default values will be set for
688             these keys. The other keys are : state, lease_id and user.
689         :rtype: list
690
691         """
692
693         #resources are listed inside the 'items' list from the json
694         reservation_list = []
695         job = {}
696         #Parse resources info
697         for json_element in self.json_page.raw_json['items']:
698             #In case it is a real reservation (not asap case)
699             if json_element['scheduled_start']:
700                 job['t_from'] = json_element['scheduled_start']
701                 job['t_until'] = int(json_element['scheduled_start']) + \
702                     int(json_element['walltime'])
703                 #Get resources id list for the job
704                 job['resource_ids'] = [node_dict['id'] for node_dict
705                                        in json_element['resources']]
706             else:
707                 job['t_from'] = "As soon as possible"
708                 job['t_until'] = "As soon as possible"
709                 job['resource_ids'] = ["Undefined"]
710
711             job['state'] = json_element['state']
712             job['lease_id'] = json_element['id']
713
714             job['user'] = json_element['owner']
715             #logger.debug("OARRestapi \tParseReservedNodes job %s" %(job))
716             reservation_list.append(job)
717             #reset dict
718             job = {}
719         return reservation_list
720
721     def ParseRunningJobs(self):
722         """ Gets the list of nodes currently in use from the attributes of the
723         running jobs.
724
725         :returns: list of hostnames, the nodes that are currently involved in
726             running jobs.
727         :rtype: list
728
729
730         """
731         logger.debug("OARESTAPI \tParseRunningJobs_________________ ")
732         #resources are listed inside the 'items' list from the json
733         nodes = []
734         for job in self.json_page.raw_json['items']:
735             for node in job['nodes']:
736                 nodes.append(node['network_address'])
737         return nodes
738
739     def ChangeRawJsonDependingOnApilibVersion(self):
740         """
741         Check if the OAR apilib version is different from 0.2.10, in which case
742         the Json answer is also dict instead as a plain list.
743
744         .. warning:: the whole code is assuming the json contains a 'items' key
745         .. seealso:: ConcatenateJsonPages, ParseJobs, ParseReservedNodes,
746             ParseJobsIdResources, ParseResources, ParseRunningJobs
747         .. todo:: Clean the whole code. Either suppose the  apilib will always
748             provide the 'items' key, or handle different options.
749         """
750
751         if self.version_json_dict['apilib_version'] != "0.2.10":
752             self.json_page.raw_json = self.json_page.raw_json['items']
753
754     def ParseDeleteJobs(self):
755         """ No need to parse anything in this function.A POST
756         is done to delete the job.
757
758         """
759         return
760
761     def ParseResourcesFull(self):
762         """ This method is responsible for parsing all the attributes
763         of all the nodes returned by OAR when issuing a get resources full.
764         The information from the nodes and the sites are separated.
765         Updates the node_dictlist so that the dictionnary of the platform's
766         nodes is available afterwards.
767
768         :returns: node_dictlist, a list of dictionaries about the nodes and
769             their properties.
770         :rtype: list
771
772         """
773         logger.debug("OARRESTAPI ParseResourcesFull___________ ")
774         #print self.json_page.raw_json[1]
775         #resources are listed inside the 'items' list from the json
776         self.ChangeRawJsonDependingOnApilibVersion()
777         self.ParseNodes()
778         self.ParseSites()
779         return self.node_dictlist
780
781     def ParseResourcesFullSites(self):
782         """ Called by GetSites which is unused.
783         Originally used to get information from the sites, with for each site
784         the list of nodes it has, along with their properties.
785
786         :return: site_dict, dictionary of sites
787         :rtype: dict
788
789         .. warning:: unused
790         .. seealso:: GetSites (IotlabTestbedAPI)
791
792         """
793         self.ChangeRawJsonDependingOnApilibVersion()
794         self.ParseNodes()
795         self.ParseSites()
796         return self.site_dict
797
798
799     def ParseNodes(self):
800         """ Parse nodes properties from OAR
801         Put them into a dictionary with key = node id and value is a dictionary
802         of the node properties and properties'values.
803
804         """
805         node_id = None
806         _resources_fulljson_dict = \
807             self.parsing_resourcesfull.resources_fulljson_dict
808         keys = _resources_fulljson_dict.keys()
809         keys.sort()
810
811         for dictline in self.json_page.raw_json:
812             node_id = None
813             # dictionary is empty and/or a new node has to be inserted
814             node_id = _resources_fulljson_dict['network_address'](
815                 self.node_dictlist, dictline['network_address'])
816             for k in keys:
817                 if k in dictline:
818                     if k == 'network_address':
819                         continue
820
821                     _resources_fulljson_dict[k](
822                         self.node_dictlist[node_id], dictline[k])
823
824             #The last property has been inserted in the property tuple list,
825             #reset node_id
826             #Turn the property tuple list (=dict value) into a dictionary
827             self.node_dictlist[node_id] = dict(self.node_dictlist[node_id])
828             node_id = None
829
830     @staticmethod
831     def iotlab_hostname_to_hrn(root_auth,  hostname):
832         """
833         Transforms a node hostname into a SFA hrn.
834
835         :param root_auth: Name of the root authority of the SFA server. In
836             our case, it is set to iotlab.
837         :param hostname: node's hotname, given by OAR.
838         :type root_auth: string
839         :type hostname: string
840         :returns: inserts the root_auth and '.' before the hostname.
841         :rtype: string
842
843         """
844         return root_auth + '.' + hostname
845
846     def ParseSites(self):
847         """ Returns a list of dictionnaries containing the sites' attributes."""
848
849         nodes_per_site = {}
850         config = Config()
851         #logger.debug(" OARrestapi.py \tParseSites  self.node_dictlist %s"\
852                                                         #%(self.node_dictlist))
853         # Create a list of nodes per site_id
854         for node_id in self.node_dictlist:
855             node = self.node_dictlist[node_id]
856
857             if node['site'] not in nodes_per_site:
858                 nodes_per_site[node['site']] = []
859                 nodes_per_site[node['site']].append(node['node_id'])
860             else:
861                 if node['node_id'] not in nodes_per_site[node['site']]:
862                     nodes_per_site[node['site']].append(node['node_id'])
863
864         #Create a site dictionary whose key is site_login_base
865         # (name of the site) and value is a dictionary of properties,
866         # including the list of the node_ids
867         for node_id in self.node_dictlist:
868             node = self.node_dictlist[node_id]
869             node.update({'hrn': self.iotlab_hostname_to_hrn(self.interface_hrn,
870                                                             node['hostname'])})
871             self.node_dictlist.update({node_id: node})
872
873             if node['site'] not in self.site_dict:
874                 self.site_dict[node['site']] = {
875                     'site': node['site'],
876                     'node_ids': nodes_per_site[node['site']],
877                     'latitude': "48.83726",
878                     'longitude': "- 2.10336",
879                     'name': config.SFA_REGISTRY_ROOT_AUTH,
880                     'pcu_ids': [], 'max_slices': None,
881                     'ext_consortium_id': None,
882                     'max_slivers': None, 'is_public': True,
883                     'peer_site_id': None,
884                     'abbreviated_name': "iotlab", 'address_ids': [],
885                     'url': "https://portal.senslab.info", 'person_ids': [],
886                     'site_tag_ids': [], 'enabled': True,  'slice_ids': [],
887                     'date_created': None, 'peer_id': None
888                 }
889
890     OARrequests_uri_dict = {
891         'GET_version':
892         {'uri': '/oarapi/version.json', 'parse_func': ParseVersion},
893
894         'GET_timezone':
895         {'uri': '/oarapi/timezone.json', 'parse_func': ParseTimezone},
896
897         'GET_jobs':
898         {'uri': '/oarapi/jobs.json', 'parse_func': ParseJobs},
899
900         'GET_jobs_id':
901         {'uri': '/oarapi/jobs/id.json', 'parse_func': ParseJobsIds},
902
903         'GET_jobs_id_resources':
904         {'uri': '/oarapi/jobs/id/resources.json',
905         'parse_func': ParseJobsIdResources},
906
907         'GET_jobs_table':
908         {'uri': '/oarapi/jobs/table.json', 'parse_func': ParseJobsTable},
909
910         'GET_jobs_details':
911         {'uri': '/oarapi/jobs/details.json', 'parse_func': ParseJobsDetails},
912
913         'GET_reserved_nodes':
914         {'uri':
915         '/oarapi/jobs/details.json?state=Running,Waiting,Launching',
916         'owner': '&user=', 'parse_func': ParseReservedNodes},
917
918         'GET_running_jobs':
919         {'uri': '/oarapi/jobs/details.json?state=Running',
920         'parse_func': ParseRunningJobs},
921
922         'GET_resources_full':
923         {'uri': '/oarapi/resources/full.json',
924         'parse_func': ParseResourcesFull},
925
926         'GET_sites':
927         {'uri': '/oarapi/resources/full.json',
928         'parse_func': ParseResourcesFullSites},
929
930         'GET_resources':
931         {'uri': '/oarapi/resources.json', 'parse_func': ParseResources},
932
933         'DELETE_jobs_id':
934         {'uri': '/oarapi/jobs/id.json', 'parse_func': ParseDeleteJobs}}
935
936
937     def SendRequest(self, request, strval=None, username=None):
938         """ Connects to OAR , sends the valid GET requests and uses
939         the appropriate json parsing functions.
940
941         :returns: calls to the appropriate parsing function, associated with the
942             GET request
943         :rtype: depends on the parsing function called.
944
945         .. seealso:: OARrequests_uri_dict
946         """
947         save_json = None
948
949         self.json_page.ResetNextPage()
950         save_json = []
951
952         if request in self.OARrequests_uri_dict:
953             while self.json_page.next_page:
954                 self.json_page.raw_json = self.server.GETRequestToOARRestAPI(
955                     request,
956                     strval,
957                     self.json_page.next_offset,
958                     username)
959                 self.json_page.FindNextPage()
960                 if self.json_page.concatenate:
961                     save_json.append(self.json_page.raw_json)
962
963             if self.json_page.concatenate and self.json_page.end:
964                 self.json_page.raw_json = \
965                     self.json_page.ConcatenateJsonPages(save_json)
966
967             return self.OARrequests_uri_dict[request]['parse_func'](self)
968         else:
969             logger.error("OARRESTAPI OARGetParse __init__ : ERROR_REQUEST "
970                          % (request))