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