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