Small typo error corrected. NT.
[sfa.git] / sfa / senslab / slabdriver.py
1 import sys
2 import subprocess
3 import datetime
4 from time import gmtime, strftime 
5
6 from sfa.util.faults import MissingSfaInfo , SliverDoesNotExist
7 from sfa.util.sfalogging import logger
8 from sfa.util.defaultdict import defaultdict
9
10 from sfa.storage.record import Record
11 from sfa.storage.alchemy import dbsession
12 from sfa.storage.model import RegRecord
13
14
15 from sfa.trust.certificate import *
16 from sfa.trust.credential import *
17 from sfa.trust.gid import GID
18
19 from sfa.managers.driver import Driver
20 from sfa.rspecs.version_manager import VersionManager
21 from sfa.rspecs.rspec import RSpec
22
23 from sfa.util.xrn import hrn_to_urn, urn_to_sliver_id
24 from sfa.util.plxrn import slicename_to_hrn, hostname_to_hrn, hrn_to_pl_slicename
25
26 ## thierry: everything that is API-related (i.e. handling incoming requests) 
27 # is taken care of 
28 # SlabDriver should be really only about talking to the senslab testbed
29
30 ## thierry : please avoid wildcard imports :)
31 from sfa.senslab.OARrestapi import  OARrestapi
32 from sfa.senslab.LDAPapi import LDAPapi
33
34 from sfa.senslab.parsing import parse_filter
35 from sfa.senslab.slabpostgres import SlabDB, slab_dbsession,SliceSenslab
36 from sfa.senslab.slabaggregate import SlabAggregate
37 from sfa.senslab.slabslices import SlabSlices
38
39 def list_to_dict(recs, key):
40     """
41     convert a list of dictionaries into a dictionary keyed on the 
42     specified dictionary key 
43     """
44    # print>>sys.stderr, " \r\n \t\t 1list_to_dict : rec %s  \r\n \t\t list_to_dict key %s" %(recs,key)   
45     keys = [rec[key] for rec in recs]
46     #print>>sys.stderr, " \r\n \t\t list_to_dict : rec %s  \r\n \t\t list_to_dict keys %s" %(recs,keys)   
47     return dict(zip(keys, recs))
48
49 # thierry : note
50 # this inheritance scheme is so that the driver object can receive
51 # GetNodes or GetSites sorts of calls directly
52 # and thus minimize the differences in the managers with the pl version
53 class SlabDriver(Driver):
54
55     def __init__(self, config):
56         Driver.__init__ (self, config)
57         self.config=config
58         self.hrn = config.SFA_INTERFACE_HRN
59     
60         self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
61
62         
63         print >>sys.stderr, "\r\n_____________ SFA SENSLAB DRIVER \r\n" 
64         # thierry - just to not break the rest of this code
65
66
67         #self.oar = OARapi()
68         self.oar = OARrestapi()
69         self.ldap = LDAPapi()
70         #self.users = SenslabImportUsers()
71         self.time_format = "%Y-%m-%d %H:%M:%S"
72         self.db = SlabDB(config)
73         #self.logger=sfa_logger()
74         self.cache=None
75         
76
77     def sliver_status(self,slice_urn,slice_hrn):
78         # receive a status request for slice named urn/hrn urn:publicid:IDN+senslab+nturro_slice hrn senslab.nturro_slice
79         # shall return a structure as described in
80         # http://groups.geni.net/geni/wiki/GAPI_AM_API_V2#SliverStatus
81         # NT : not sure if we should implement this or not, but used by sface.
82         
83
84         sl = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
85         if len(sl) is 0:
86             raise SliverDoesNotExist("%s  slice_hrn" % (slice_hrn))
87
88         print >>sys.stderr, "\r\n \r\n_____________ Sliver status urn %s hrn %s sl %s \r\n " %(slice_urn,slice_hrn,sl)
89         if sl['oar_job_id'] is not -1:
90     
91             # report about the local nodes only
92             nodes_all = self.GetNodes({'hostname':sl['node_ids']},
93                             ['node_id', 'hostname','site','boot_state'])
94             nodeall_byhostname = dict([(n['hostname'], n) for n in nodes_all])
95             nodes = sl['node_ids']
96             if len(nodes) is 0:
97                 raise SliverDoesNotExist("No slivers allocated ") 
98                     
99              
100            
101     
102             result = {}
103             top_level_status = 'unknown'
104             if nodes:
105                 top_level_status = 'ready'
106             result['geni_urn'] = slice_urn
107             result['pl_login'] = sl['job_user']
108             #result['slab_login'] = sl['job_user']
109             
110             timestamp = float(sl['startTime']) + float(sl['walltime']) 
111             result['pl_expires'] = strftime(self.time_format, gmtime(float(timestamp)))
112             #result['slab_expires'] = strftime(self.time_format, gmtime(float(timestamp)))
113             
114             resources = []
115             for node in nodes:
116                 res = {}
117                 #res['slab_hostname'] = node['hostname']
118                 #res['slab_boot_state'] = node['boot_state']
119                 
120                 res['pl_hostname'] = nodeall_byhostname[node]['hostname']
121                 res['pl_boot_state'] = nodeall_byhostname[node]['boot_state']
122                 res['pl_last_contact'] = strftime(self.time_format, gmtime(float(timestamp)))
123                 sliver_id = urn_to_sliver_id(slice_urn, sl['record_id_slice'],nodeall_byhostname[node]['node_id'] ) 
124                 res['geni_urn'] = sliver_id 
125                 if nodeall_byhostname[node]['boot_state'] == 'Alive':
126                 #if node['boot_state'] == 'Alive':
127                     res['geni_status'] = 'ready'
128                 else:
129                     res['geni_status'] = 'failed'
130                     top_level_status = 'failed' 
131                     
132                 res['geni_error'] = ''
133         
134                 resources.append(res)
135                 
136             result['geni_status'] = top_level_status
137             result['geni_resources'] = resources 
138             print >>sys.stderr, "\r\n \r\n_____________ Sliver status resources %s res %s \r\n " %(resources,res)
139             return result        
140         
141         
142     def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
143         aggregate = SlabAggregate(self)
144
145         slices = SlabSlices(self)
146         peer = slices.get_peer(slice_hrn)
147         sfa_peer = slices.get_sfa_peer(slice_hrn)
148         slice_record=None 
149
150        
151         if not isinstance(creds, list):
152             creds = [creds]
153
154            
155         if users:
156             slice_record = users[0].get('slice_record', {})
157     
158         # parse rspec
159         rspec = RSpec(rspec_string)
160         requested_attributes = rspec.version.get_slice_attributes()
161         
162         # ensure site record exists
163         #site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer, options=options)
164         # ensure slice record exists
165         slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer, options=options)
166         # ensure person records exists
167         persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer, options=options)
168         # ensure slice attributes exists
169         #slices.verify_slice_attributes(slice, requested_attributes, options=options)
170         
171         # add/remove slice from nodes
172         requested_slivers = [node.get('component_name') for node in rspec.version.get_nodes_with_slivers()]
173         nodes = slices.verify_slice_nodes(slice, requested_slivers, peer) 
174     
175       
176     
177         # handle MyPLC peer association.
178         # only used by plc and ple.
179         #slices.handle_peer(site, slice, persons, peer)
180         
181         return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
182         
183         
184     def delete_sliver (self, slice_urn, slice_hrn, creds, options):
185         
186         slices = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
187         if not slices:
188             return 1
189         slice = slices[0]
190     
191         # determine if this is a peer slice
192         # xxx I wonder if this would not need to use PlSlices.get_peer instead 
193         # in which case plc.peers could be deprecated as this here
194         # is the only/last call to this last method in plc.peers
195         peer = peers.get_peer(self, slice_hrn)
196         try:
197             if peer:
198                 self.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
199             self.DeleteSliceFromNodes(slice_hrn, slice['node_ids'])
200         finally:
201             if peer:
202                 self.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
203         return 1
204             
205             
206             
207             
208     # first 2 args are None in case of resource discovery
209     def list_resources (self, slice_urn, slice_hrn, creds, options):
210         #cached_requested = options.get('cached', True) 
211     
212         version_manager = VersionManager()
213         # get the rspec's return format from options
214         rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
215         version_string = "rspec_%s" % (rspec_version)
216     
217         #panos adding the info option to the caching key (can be improved)
218         if options.get('info'):
219             version_string = version_string + "_"+options.get('info', 'default')
220     
221         # look in cache first
222         #if cached_requested and self.cache and not slice_hrn:
223             #rspec = self.cache.get(version_string)
224             #if rspec:
225                 #logger.debug("SlabDriver.ListResources: returning cached advertisement")
226                 #return rspec 
227     
228         #panos: passing user-defined options
229         #print "manager options = ",options
230         aggregate = SlabAggregate(self)
231         origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
232         print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec origin_hrn %s" %(origin_hrn)
233         options.update({'origin_hrn':origin_hrn})
234         print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec options %s" %(options)
235         rspec =  aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version, 
236                                      options=options)
237     
238         # cache the result
239         #if self.cache and not slice_hrn:
240             #logger.debug("Slab.ListResources: stores advertisement in cache")
241             #self.cache.add(version_string, rspec)
242     
243         return rspec
244         
245         
246     def list_slices (self, creds, options):
247         # look in cache first
248         #if self.cache:
249             #slices = self.cache.get('slices')
250             #if slices:
251                 #logger.debug("PlDriver.list_slices returns from cache")
252                 #return slices
253     
254         # get data from db 
255         print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY list_slices"
256         slices = self.GetSlices()
257         slice_hrns = [slicename_to_hrn(self.hrn, slice['slice_hrn']) for slice in slices]
258         slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
259     
260         # cache the result
261         #if self.cache:
262             #logger.debug ("SlabDriver.list_slices stores value in cache")
263             #self.cache.add('slices', slice_urns) 
264     
265         return slice_urns
266     
267     #No site or node register supported
268     def register (self, sfa_record, hrn, pub_key):
269         type = sfa_record['type']
270         slab_record = self.sfa_fields_to_slab_fields(type, hrn, sfa_record)
271     
272         #if type == 'authority':
273             #sites = self.shell.GetSites([slab_record['login_base']])
274             #if not sites:
275                 #pointer = self.shell.AddSite(slab_record)
276             #else:
277                 #pointer = sites[0]['site_id']
278     
279         if type == 'slice':
280             acceptable_fields=['url', 'instantiation', 'name', 'description']
281             for key in slab_record.keys():
282                 if key not in acceptable_fields:
283                     slab_record.pop(key) 
284             print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY register"
285             slices = self.GetSlices(slice_filter =slab_record['hrn'], filter_type = 'slice_hrn')
286             if not slices:
287                     pointer = self.AddSlice(slab_record)
288             else:
289                     pointer = slices[0]['slice_id']
290     
291         elif type == 'user':
292             persons = self.GetPersons([sfa_record['hrn']])
293             if not persons:
294                 pointer = self.AddPerson(dict(sfa_record))
295                 #add in LDAP 
296             else:
297                 pointer = persons[0]['person_id']
298                 
299             #Does this make sense to senslab ?
300             #if 'enabled' in sfa_record and sfa_record['enabled']:
301                 #self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
302                 
303             # add this person to the site only if she is being added for the first
304             # time by sfa and doesont already exist in plc
305             if not persons or not persons[0]['site_ids']:
306                 login_base = get_leaf(sfa_record['authority'])
307                 self.AddPersonToSite(pointer, login_base)
308     
309             # What roles should this user have?
310             self.AddRoleToPerson('user', pointer)
311             # Add the user's key
312             if pub_key:
313                 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
314                 
315         #No node adding outside OAR
316         #elif type == 'node':
317             #login_base = hrn_to_slab_login_base(sfa_record['authority'])
318             #nodes = self.GetNodes([slab_record['hostname']])
319             #if not nodes:
320                 #pointer = self.AddNode(login_base, slab_record)
321             #else:
322                 #pointer = nodes[0]['node_id']
323     
324         return pointer
325             
326     #No site or node record update allowed       
327     def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
328         pointer = old_sfa_record['pointer']
329         type = old_sfa_record['type']
330
331         # new_key implemented for users only
332         if new_key and type not in [ 'user' ]:
333             raise UnknownSfaType(type)
334         
335         #if (type == "authority"):
336             #self.shell.UpdateSite(pointer, new_sfa_record)
337     
338         if type == "slice":
339             slab_record=self.sfa_fields_to_slab_fields(type, hrn, new_sfa_record)
340             if 'name' in slab_record:
341                 slab_record.pop('name')
342                 self.UpdateSlice(pointer, slab_record)
343     
344         elif type == "user":
345             update_fields = {}
346             all_fields = new_sfa_record
347             for key in all_fields.keys():
348                 if key in ['first_name', 'last_name', 'title', 'email',
349                            'password', 'phone', 'url', 'bio', 'accepted_aup',
350                            'enabled']:
351                     update_fields[key] = all_fields[key]
352             self.UpdatePerson(pointer, update_fields)
353     
354             if new_key:
355                 # must check this key against the previous one if it exists
356                 persons = self.GetPersons([pointer], ['key_ids'])
357                 person = persons[0]
358                 keys = person['key_ids']
359                 keys = self.GetKeys(person['key_ids'])
360                 
361                 # Delete all stale keys
362                 key_exists = False
363                 for key in keys:
364                     if new_key != key['key']:
365                         self.DeleteKey(key['key_id'])
366                     else:
367                         key_exists = True
368                 if not key_exists:
369                     self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
370     
371         #elif type == "node":
372             #self.UpdateNode(pointer, new_sfa_record)
373
374         return True
375         
376
377     def remove (self, sfa_record):
378         type=sfa_record['type']
379         hrn=sfa_record['hrn']
380         record_id= sfa_record['record_id']
381         if type == 'user':
382             username = hrn.split(".")[len(hrn.split(".")) -1]
383             #get user in ldap
384             persons = self.GetPersons(username)
385             # only delete this person if he has site ids. if he doesnt, it probably means
386             # he was just removed from a site, not actually deleted
387             if persons and persons[0]['site_ids']:
388                 self.DeletePerson(username)
389         elif type == 'slice':
390             if self.GetSlices(slice_filter = hrn, filter_type = 'slice_hrn'):
391                 self.DeleteSlice(hrn)
392
393         #elif type == 'authority':
394             #if self.GetSites(pointer):
395                 #self.DeleteSite(pointer)
396
397         return True
398             
399     def GetPeers (self,auth = None, peer_filter=None, return_fields=None):
400
401         existing_records = {}
402         existing_hrns_by_types= {}
403         print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers auth = %s, peer_filter %s, return_field %s " %(auth , peer_filter, return_fields)
404         all_records = dbsession.query(RegRecord).filter(RegRecord.type.like('%authority%')).all()
405         for record in all_records:
406             existing_records[record.hrn] = record
407             if record.type not in existing_hrns_by_types:
408                 existing_hrns_by_types[record.type] = [record.hrn]
409                 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t NOT IN existing_hrns_by_types %s " %( existing_hrns_by_types)
410             else:
411                 
412                 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t INNN  type %s hrn %s " %( record.type,record.hrn )
413                 existing_hrns_by_types.update({record.type:(existing_hrns_by_types[record.type].append(record.hrn))})
414                         
415         print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers        existing_hrns_by_types %s " %( existing_hrns_by_types)
416         records_list= [] 
417       
418         try:
419             for hrn in existing_hrns_by_types['authority+sa']:
420                 records_list.append(existing_records[hrn])
421                 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers  records_list  %s " %(records_list)
422                 
423         except:
424                 pass
425
426         if not peer_filter and not return_fields:
427             return records_list
428         return_records = parse_filter(records_list,peer_filter, 'peers', return_fields) 
429  
430         return return_records
431         
432      
433             
434     def GetPersons(self, person_filter=None, return_fields=None):
435         
436         person_list = self.ldap.ldapFind({'authority': self.root_auth })
437         
438         #check = False
439         #if person_filter and isinstance(person_filter, dict):
440             #for k in  person_filter.keys():
441                 #if k in person_list[0].keys():
442                     #check = True
443                     
444         return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
445         if return_person_list:
446             print>>sys.stderr, " \r\n GetPersons person_filter %s return_fields %s  " %(person_filter,return_fields)
447             return return_person_list
448
449     def GetTimezone(self):
450         time = self.oar.parser.SendRequest("GET_timezone")
451         return time
452     
453
454     def DeleteJobs(self, job_id, username):
455         if not job_id:
456             return
457         reqdict = {}
458         reqdict['method'] = "delete"
459         reqdict['strval'] = str(job_id)
460         answer = self.oar.POSTRequestToOARRestAPI('DELETE_jobs_id',reqdict,username)
461         print>>sys.stderr, "\r\n \r\n  jobid  DeleteJobs %s "  %(answer)
462         
463                 
464     def GetJobs(self,job_id= None, resources=True,return_fields=None, username = None):
465         #job_resources=['reserved_resources', 'assigned_resources','job_id', 'job_uri', 'assigned_nodes',\
466         #'api_timestamp']
467         #assigned_res = ['resource_id', 'resource_uri']
468         #assigned_n = ['node', 'node_uri']
469       
470      
471         if job_id and resources is False:
472             req = "GET_jobs_id"
473             node_list_k = 'assigned_network_address'
474            
475         if job_id and resources :
476             req = "GET_jobs_id_resources"
477             node_list_k = 'reserved_resources' 
478
479       
480                
481         #Get job info from OAR    
482         job_info = self.oar.parser.SendRequest(req, job_id, username)
483         print>>sys.stderr, "\r\n \r\n \t\t GetJobs  %s " %(job_info)
484         
485         if 'state' in job_info :
486             if job_info['state'] == 'Terminated':
487                 print>>sys.stderr, "\r\n \r\n \t\t GetJobs TERMINELEBOUSIN "
488                 return None
489             if job_info['state'] == 'Error':
490                 print>>sys.stderr, "\r\n \r\n \t\t GetJobs ERROR message %s " %(job_info)
491                 return None
492         
493         #Get a dict of nodes . Key :hostname of the node
494         node_list = self.GetNodes() 
495         node_hostname_list = []
496         for node in node_list:
497             node_hostname_list.append(node['hostname'])
498         node_dict = dict(zip(node_hostname_list,node_list))
499         
500
501         try :
502
503
504             liste =job_info[node_list_k] 
505             print>>sys.stderr, "\r\n \r\n \t\t GetJobs resources  job_info liste%s" %(liste)
506             for k in range(len(liste)):
507                job_info[node_list_k][k] = node_dict[job_info[node_list_k][k]]['hostname']
508             
509             print>>sys.stderr, "\r\n \r\n \t\t YYYYYYYYYYYYGetJobs resources  job_info %s" %(job_info)  
510             #Replaces the previous entry "assigned_network_address" / "reserved_resources"
511             #with "node_ids"
512             job_info.update({'node_ids':job_info[node_list_k]})
513             del job_info[node_list_k]
514             return job_info
515             
516         except KeyError:
517             print>>sys.stderr, "\r\n \r\n \t\t GetJobs KEYERROR " 
518             
519   
520             
521
522        
523      
524     def GetNodes(self,node_filter= None, return_fields=None):
525                 
526         node_dict =self.oar.parser.SendRequest("GET_resources_full")
527         print>>sys.stderr, "\r\n \r\n \t\t  SLABDRIVER.PY GetNodes " 
528         return_node_list = []
529         if not (node_filter or return_fields):
530                 return_node_list = node_dict.values()
531                 return return_node_list
532     
533         return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
534         return return_node_list
535     
536   
537     def GetSites(self, site_filter = None, return_fields=None):
538         site_dict =self.oar.parser.SendRequest("GET_sites")
539         print>>sys.stderr, "\r\n \r\n \t\t  SLABDRIVER.PY GetSites " 
540         return_site_list = []
541         if not ( site_filter or return_fields):
542                 return_site_list = site_dict.values()
543                 return return_site_list
544     
545         return_site_list = parse_filter(site_dict.values(), site_filter,'site', return_fields)
546         return return_site_list
547         
548
549     def GetSlices(self,slice_filter = None, filter_type = None, return_fields=None):
550         return_slice_list = []
551         slicerec  = {}
552         rec = {}
553         ftypes = ['slice_hrn', 'record_id_user']
554         if filter_type and filter_type in ftypes:
555             if filter_type == 'slice_hrn':
556                 slicerec = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = slice_filter).first()    
557             if filter_type == 'record_id_user':
558                 slicerec = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = slice_filter).first()
559                 
560             if slicerec:
561                 rec = slicerec.dumpquerytodict()
562                 login = slicerec.slice_hrn.split(".")[1].split("_")[0]
563                 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY slicerec GetSlices   %s " %(slicerec)
564                 if slicerec.oar_job_id is not -1:
565                     rslt = self.GetJobs( slicerec.oar_job_id, resources=False, username = login )
566                     print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  GetJobs  %s " %(rslt)     
567                     if rslt :
568                         rec.update(rslt)
569                         rec.update({'hrn':str(rec['slice_hrn'])})
570                         #If GetJobs is empty, this means the job is now in the 'Terminated' state
571                         #Update the slice record
572                     else :
573                         self.db.update_job(slice_filter, job_id = -1)
574                         rec['oar_job_id'] = -1
575                         rec.update({'hrn':str(rec['slice_hrn'])})
576             
577                 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  rec  %s" %(rec)
578                               
579             return rec
580                 
581                 
582         else:
583             return_slice_list = slab_dbsession.query(SliceSenslab).all()
584
585         print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY  GetSlices  slices %s slice_filter %s " %(return_slice_list,slice_filter)
586         
587         #if return_fields:
588             #return_slice_list  = parse_filter(sliceslist, slice_filter,'slice', return_fields)
589         
590         
591                     
592         return return_slice_list
593         
594
595         
596     
597     def testbed_name (self): return "senslab2" 
598          
599     # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
600     def aggregate_version (self):
601         version_manager = VersionManager()
602         ad_rspec_versions = []
603         request_rspec_versions = []
604         for rspec_version in version_manager.versions:
605             if rspec_version.content_type in ['*', 'ad']:
606                 ad_rspec_versions.append(rspec_version.to_dict())
607             if rspec_version.content_type in ['*', 'request']:
608                 request_rspec_versions.append(rspec_version.to_dict()) 
609         return {
610             'testbed':self.testbed_name(),
611             'geni_request_rspec_versions': request_rspec_versions,
612             'geni_ad_rspec_versions': ad_rspec_versions,
613             }
614           
615           
616           
617           
618           
619           
620     ##
621     # Convert SFA fields to PLC fields for use when registering up updating
622     # registry record in the PLC database
623     #
624     # @param type type of record (user, slice, ...)
625     # @param hrn human readable name
626     # @param sfa_fields dictionary of SFA fields
627     # @param slab_fields dictionary of PLC fields (output)
628
629     def sfa_fields_to_slab_fields(self, type, hrn, record):
630
631         def convert_ints(tmpdict, int_fields):
632             for field in int_fields:
633                 if field in tmpdict:
634                     tmpdict[field] = int(tmpdict[field])
635
636         slab_record = {}
637         #for field in record:
638         #    slab_record[field] = record[field]
639  
640         if type == "slice":
641             #instantion used in get_slivers ? 
642             if not "instantiation" in slab_record:
643                 slab_record["instantiation"] = "senslab-instantiated"
644             slab_record["hrn"] = hrn_to_pl_slicename(hrn)
645             print >>sys.stderr, "\r\n \r\n \t SLABDRIVER.PY sfa_fields_to_slab_fields slab_record %s hrn_to_pl_slicename(hrn) hrn %s " %(slab_record['hrn'], hrn)
646             if "url" in record:
647                slab_record["url"] = record["url"]
648             if "description" in record:
649                 slab_record["description"] = record["description"]
650             if "expires" in record:
651                 slab_record["expires"] = int(record["expires"])
652                 
653         #nodes added by OAR only and then imported to SFA
654         #elif type == "node":
655             #if not "hostname" in slab_record:
656                 #if not "hostname" in record:
657                     #raise MissingSfaInfo("hostname")
658                 #slab_record["hostname"] = record["hostname"]
659             #if not "model" in slab_record:
660                 #slab_record["model"] = "geni"
661                 
662         #One authority only 
663         #elif type == "authority":
664             #slab_record["login_base"] = hrn_to_slab_login_base(hrn)
665
666             #if not "name" in slab_record:
667                 #slab_record["name"] = hrn
668
669             #if not "abbreviated_name" in slab_record:
670                 #slab_record["abbreviated_name"] = hrn
671
672             #if not "enabled" in slab_record:
673                 #slab_record["enabled"] = True
674
675             #if not "is_public" in slab_record:
676                 #slab_record["is_public"] = True
677
678         return slab_record
679
680   
681                  
682                  
683     def AddSliceToNodes(self,  slice_name, added_nodes, slice_user=None):
684        
685         site_list = []
686         nodeid_list =[]
687         resource = ""
688         reqdict = {}
689         reqdict['property'] ="network_address in ("
690         for node in added_nodes:
691             #Get the ID of the node : remove the root auth and put the site in a separate list
692             s=node.split(".")
693             # NT: it's not clear for me if the nodenames will have the senslab prefix
694             # so lets take the last part only, for now.
695             lastpart=s[-1]
696             #if s[0] == self.root_auth :
697             # Again here it's not clear if nodes will be prefixed with <site>_, lets split and tanke the last part for now.
698             s=lastpart.split("_")
699             nodeid=s[-1]
700             reqdict['property'] += "'"+ nodeid +"', "
701             nodeid_list.append(nodeid)
702             #site_list.append( l[0] )
703         reqdict['property'] =  reqdict['property'][0: len( reqdict['property'])-2] +")"
704         reqdict['resource'] ="network_address="+ str(len(nodeid_list))
705         reqdict['resource']+= ",walltime=" + str(00) + ":" + str(12) + ":" + str(20) #+2 min 20
706         reqdict['script_path'] = "/bin/sleep 620" #+20 sec
707         reqdict['type'] = "deploy" 
708         reqdict['directory']= ""
709         reqdict['name']= "TestSandrine"
710         timestamp = self.GetTimezone()
711         print>>sys.stderr, "\r\n \r\n AddSliceToNodes  slice_name %s added_nodes %s username %s reqdict %s " %(slice_name,added_nodes,slice_user, reqdict)
712         readable_time = strftime(self.time_format, gmtime(float(timestamp))) 
713         print >>sys.stderr," \r\n \r\n \t\t\t\t AVANT ParseTimezone readable_time %s timestanp %s " %(readable_time, timestamp )
714         timestamp =  timestamp+ 3620 #Add 3 min to server time
715         readable_time = strftime(self.time_format, gmtime(float(timestamp))) 
716
717         print >>sys.stderr,"  \r\n \r\n \t\t\t\tAPRES ParseTimezone readable_time %s timestanp %s  " %(readable_time , timestamp)
718         reqdict['reservation'] = readable_time
719          
720         # first step : start the OAR job
721         print>>sys.stderr, "\r\n \r\n AddSliceToNodes reqdict   %s \r\n site_list   %s"  %(reqdict,site_list)   
722         #OAR = OARrestapi()
723         answer = self.oar.POSTRequestToOARRestAPI('POST_job',reqdict,slice_user)
724         print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid   %s "  %(answer)
725         #self.db.update('slice',['oar_job_id'], [answer['id']], 'slice_hrn', slice_name)
726                
727
728         self.db.update_job( slice_name, job_id = answer['id'] )
729         jobid=answer['id']
730         print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid    %s added_nodes  %s slice_user %s"  %(jobid,added_nodes,slice_user)  
731         # second step : configure the experiment
732         # we need to store the nodes in a yaml (well...) file like this :
733         # [1,56,23,14,45,75] with name /tmp/sfa<jobid>.json
734         f=open('/tmp/sfa/'+str(jobid)+'.json','w')
735         f.write('[')
736         f.write(str(added_nodes[0].strip('node')))
737         for node in added_nodes[1:len(added_nodes)] :
738             f.write(','+node.strip('node'))
739         f.write(']')
740         f.close()
741         
742         # third step : call the senslab-experiment wrapper
743         #command= "java -jar target/sfa-1.0-jar-with-dependencies.jar "+str(jobid)+" "+slice_user
744         javacmdline="/usr/bin/java"
745         jarname="/opt/senslabexperimentwrapper/sfa-1.0-jar-with-dependencies.jar"
746         #ret=subprocess.check_output(["/usr/bin/java", "-jar", ", str(jobid), slice_user])
747         output = subprocess.Popen([javacmdline, "-jar", jarname, str(jobid), slice_user],stdout=subprocess.PIPE).communicate()[0]
748
749         print>>sys.stderr, "\r\n \r\n AddSliceToNodes wrapper returns   %s "  %(output)
750         return 
751     
752
753         
754         
755     def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
756         return   
757     
758  
759
760     def fill_record_sfa_info(self, records):
761
762         def startswith(prefix, values):
763             return [value for value in values if value.startswith(prefix)]
764
765         # get person ids
766         person_ids = []
767         site_ids = []
768         for record in records:
769             person_ids.extend(record.get("person_ids", []))
770             site_ids.extend(record.get("site_ids", [])) 
771             if 'site_id' in record:
772                 site_ids.append(record['site_id']) 
773                 
774         #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___person_ids %s \r\n \t\t site_ids %s " %(person_ids, site_ids)
775         
776         # get all pis from the sites we've encountered
777         # and store them in a dictionary keyed on site_id 
778         site_pis = {}
779         if site_ids:
780             pi_filter = {'|roles': ['pi'], '|site_ids': site_ids} 
781             pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
782             #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
783
784             for pi in pi_list:
785                 # we will need the pi's hrns also
786                 person_ids.append(pi['person_id'])
787                 
788                 # we also need to keep track of the sites these pis
789                 # belong to
790                 for site_id in pi['site_ids']:
791                     if site_id in site_pis:
792                         site_pis[site_id].append(pi)
793                     else:
794                         site_pis[site_id] = [pi]
795                  
796         # get sfa records for all records associated with these records.   
797         # we'll replace pl ids (person_ids) with hrns from the sfa records
798         # we obtain
799         
800         # get the sfa records
801         #table = SfaTable()
802         existing_records = {}
803         all_records = dbsession.query(RegRecord).all()
804         for record in all_records:
805             existing_records[(record.type,record.pointer)] = record
806             
807         print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info existing_records %s "  %(existing_records)
808         person_list, persons = [], {}
809         #person_list = table.find({'type': 'user', 'pointer': person_ids})
810         try:
811             for p_id in person_ids:
812                 person_list.append( existing_records.get(('user',p_id)))
813         except KeyError:
814             print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info ERRRRRRRRRROR"
815                  
816         # create a hrns keyed on the sfa record's pointer.
817         # Its possible for  multiple records to have the same pointer so
818         # the dict's value will be a list of hrns.
819         persons = defaultdict(list)
820         for person in person_list:
821             persons[person['pointer']].append(person)
822
823         # get the pl records
824         slab_person_list, slab_persons = [], {}
825         slab_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
826         slab_persons = list_to_dict(slab_person_list, 'person_id')
827         #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___  _list %s \r\n \t\t SenslabUsers.GetPersons ['person_id', 'roles'] slab_persons %s \r\n records %s" %(slab_person_list, slab_persons,records) 
828         # fill sfa info
829         
830         for record in records:
831             # skip records with no pl info (top level authorities)
832             #Sandrine 24 oct 11 2 lines
833             #if record['pointer'] == -1:
834                 #continue 
835             sfa_info = {}
836             type = record['type']
837             if (type == "slice"):
838                 # all slice users are researchers
839                 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')  ? besoin ou pas ?
840                 record['PI'] = []
841                 record['researcher'] = []
842                 for person_id in record.get('person_ids', []):
843                          #Sandrine 24 oct 11 line
844                 #for person_id in record['person_ids']:
845                     hrns = [person['hrn'] for person in persons[person_id]]
846                     record['researcher'].extend(hrns)                
847
848                 # pis at the slice's site
849                 slab_pis = site_pis[record['site_id']]
850                 pi_ids = [pi['person_id'] for pi in slab_pis]
851                 for person_id in pi_ids:
852                     hrns = [person['hrn'] for person in persons[person_id]]
853                     record['PI'].extend(hrns)
854                 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
855                 record['geni_creator'] = record['PI'] 
856                 
857             elif (type == "authority"):
858                 record['PI'] = []
859                 record['operator'] = []
860                 record['owner'] = []
861                 for pointer in record['person_ids']:
862                     if pointer not in persons or pointer not in slab_persons:
863                         # this means there is not sfa or pl record for this user
864                         continue   
865                     hrns = [person['hrn'] for person in persons[pointer]] 
866                     roles = slab_persons[pointer]['roles']   
867                     if 'pi' in roles:
868                         record['PI'].extend(hrns)
869                     if 'tech' in roles:
870                         record['operator'].extend(hrns)
871                     if 'admin' in roles:
872                         record['owner'].extend(hrns)
873                     # xxx TODO: OrganizationName
874             elif (type == "node"):
875                 sfa_info['dns'] = record.get("hostname", "")
876                 # xxx TODO: URI, LatLong, IP, DNS
877     
878             elif (type == "user"):
879                  sfa_info['email'] = record.get("email", "")
880                  sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
881                  sfa_info['geni_certificate'] = record['gid'] 
882                 # xxx TODO: PostalAddress, Phone
883                 
884             #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<<  fill_record_sfa_info sfa_info %s  \r\n record %s : "%(sfa_info,record)  
885             record.update(sfa_info)
886             
887     def augment_records_with_testbed_info (self, sfa_records):
888         return self.fill_record_info (sfa_records)
889     
890     def fill_record_info(self, records):
891         """
892         Given a SFA record, fill in the senslab specific and SFA specific
893         fields in the record. 
894         """
895                     
896         print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info 000000000 fill_record_info %s  " %(records)
897         if not isinstance(records, list):
898             records = [records]
899
900         parkour = records 
901         try:
902             for record in parkour:
903                     
904                 if str(record['type']) == 'slice':
905                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY  fill_record_info \t \t record %s" %(record)
906                     #sfatable = SfaTable()
907                     
908                     #existing_records_by_id = {}
909                     #all_records = dbsession.query(RegRecord).all()
910                     #for rec in all_records:
911                         #existing_records_by_id[rec.record_id] = rec
912                     #print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY  fill_record_info \t\t existing_records_by_id %s" %(existing_records_by_id[record['record_id']])
913                         
914                     #recslice = self.db.find('slice',{'slice_hrn':str(record['hrn'])}) 
915                     #recslice = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = str(record['hrn'])).first()
916                     recslice = self.GetSlices(slice_filter =  str(record['hrn']), filter_type = 'slice_hrn')
917                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info \t\t HOY HOY reclise %s" %(recslice)
918                     #if isinstance(recslice,list) and len(recslice) == 1:
919                         #recslice = recslice[0]
920                    
921                     recuser = dbsession.query(RegRecord).filter_by(record_id = recslice['record_id_user']).first()
922                     #existing_records_by_id[recslice['record_id_user']]
923                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info \t\t recuser %s" %(recuser)
924                     
925           
926                     record.update({'PI':[recuser.hrn],
927                     'researcher': [recuser.hrn],
928                     'name':record['hrn'], 
929                     'oar_job_id':recslice['oar_job_id'],
930                     'node_ids': [],
931                     'person_ids':[recslice['record_id_user']]})
932                     
933                 elif str(record['type']) == 'user':
934                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info USEEEEEEEEEERDESU!" 
935
936                     rec = self.GetSlices(slice_filter = record['record_id'], filter_type = 'record_id_user')
937                     #Append record in records list, therfore fetches user and slice info again(one more loop)
938                     #Will update PIs and researcher for the slice
939
940                     rec.update({'type':'slice','hrn':rec['slice_hrn']})
941                     records.append(rec)
942                     print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info ADDING SLIC EINFO rec %s" %(rec) 
943                     
944             print >>sys.stderr, "\r\n \t\t  SLABDRIVER.PY fill_record_info OKrecords %s" %(records) 
945         except TypeError:
946             print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info  EXCEPTION RECORDS : %s" %(records)      
947             return
948         
949         #self.fill_record_slab_info(records)
950         ##print >>sys.stderr, "\r\n \t\t after fill_record_slab_info %s" %(records)     
951         #self.fill_record_sfa_info(records)
952         #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
953         
954         
955
956     
957         
958     #def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
959         ## get a list of the HRNs tht are members of the old and new records
960         #if oldRecord:
961             #oldList = oldRecord.get(listName, [])
962         #else:
963             #oldList = []     
964         #newList = record.get(listName, [])
965
966         ## if the lists are the same, then we don't have to update anything
967         #if (oldList == newList):
968             #return
969
970         ## build a list of the new person ids, by looking up each person to get
971         ## their pointer
972         #newIdList = []
973         #table = SfaTable()
974         #records = table.find({'type': 'user', 'hrn': newList})
975         #for rec in records:
976             #newIdList.append(rec['pointer'])
977
978         ## build a list of the old person ids from the person_ids field 
979         #if oldRecord:
980             #oldIdList = oldRecord.get("person_ids", [])
981             #containerId = oldRecord.get_pointer()
982         #else:
983             ## if oldRecord==None, then we are doing a Register, instead of an
984             ## update.
985             #oldIdList = []
986             #containerId = record.get_pointer()
987
988     ## add people who are in the new list, but not the oldList
989         #for personId in newIdList:
990             #if not (personId in oldIdList):
991                 #addFunc(self.plauth, personId, containerId)
992
993         ## remove people who are in the old list, but not the new list
994         #for personId in oldIdList:
995             #if not (personId in newIdList):
996                 #delFunc(self.plauth, personId, containerId)
997
998     #def update_membership(self, oldRecord, record):
999         #print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
1000         #if record.type == "slice":
1001             #self.update_membership_list(oldRecord, record, 'researcher',
1002                                         #self.users.AddPersonToSlice,
1003                                         #self.users.DeletePersonFromSlice)
1004         #elif record.type == "authority":
1005             ## xxx TODO
1006             #pass
1007
1008 ### thierry
1009 # I don't think you plan on running a component manager at this point
1010 # let me clean up the mess of ComponentAPI that is deprecated anyways