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