4 from time import gmtime, strftime
6 from sfa.util.faults import MissingSfaInfo , SliverDoesNotExist
7 from sfa.util.sfalogging import logger
8 from sfa.util.defaultdict import defaultdict
10 from sfa.storage.record import Record
11 from sfa.storage.alchemy import dbsession
12 from sfa.storage.model import RegRecord
15 from sfa.trust.certificate import *
16 from sfa.trust.credential import *
17 from sfa.trust.gid import GID
19 from sfa.managers.driver import Driver
20 from sfa.rspecs.version_manager import VersionManager
21 from sfa.rspecs.rspec import RSpec
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
26 ## thierry: everything that is API-related (i.e. handling incoming requests)
28 # SlabDriver should be really only about talking to the senslab testbed
30 ## thierry : please avoid wildcard imports :)
31 from sfa.senslab.OARrestapi import OARrestapi
32 from sfa.senslab.LDAPapi import LDAPapi
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
39 def list_to_dict(recs, key):
41 convert a list of dictionaries into a dictionary keyed on the
42 specified dictionary key
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))
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):
55 def __init__(self, config):
56 Driver.__init__ (self, config)
58 self.hrn = config.SFA_INTERFACE_HRN
60 self.root_auth = config.SFA_REGISTRY_ROOT_AUTH
63 print >>sys.stderr, "\r\n_____________ SFA SENSLAB DRIVER \r\n"
64 # thierry - just to not break the rest of this code
68 self.oar = OARrestapi()
70 #self.users = SenslabImportUsers()
71 self.time_format = "%Y-%m-%d %H:%M:%S"
72 self.db = SlabDB(config)
73 #self.logger=sfa_logger()
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.
84 sl = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
86 raise SliverDoesNotExist("%s slice_hrn" % (slice_hrn))
88 print >>sys.stderr, "\r\n \r\n_____________ Sliver status urn %s hrn %s sl %s \r\n " %(slice_urn,slice_hrn,sl)
89 if sl['oar_job_id'] is not -1:
91 # report about the local nodes only
92 nodes_all = self.GetNodes({'hostname':sl['node_ids']},
93 ['node_id', 'hostname','site','boot_state'])
94 nodeall_byhostname = dict([(n['hostname'], n) for n in nodes_all])
95 nodes = sl['node_ids']
97 raise SliverDoesNotExist("No slivers allocated ")
103 top_level_status = 'unknown'
105 top_level_status = 'ready'
106 result['geni_urn'] = slice_urn
107 result['pl_login'] = sl['job_user']
108 #result['slab_login'] = sl['job_user']
110 timestamp = float(sl['startTime']) + float(sl['walltime'])
111 result['pl_expires'] = strftime(self.time_format, gmtime(float(timestamp)))
112 #result['slab_expires'] = strftime(self.time_format, gmtime(float(timestamp)))
117 #res['slab_hostname'] = node['hostname']
118 #res['slab_boot_state'] = node['boot_state']
120 res['pl_hostname'] = nodeall_byhostname[node['hostname']]['hostname']
121 res['pl_boot_state'] = nodeall_byhostname[node['hostname']]['boot_state']
122 res['pl_last_contact'] = strftime(self.time_format, gmtime(float(timestamp)))
123 sliver_id = urn_to_sliver_id(slice_urn, sl['record_id_slice'],nodeall_byhostname[node['hostname']]['node_id'] )
124 res['geni_urn'] = sliver_id
125 if nodeall_byhostname[node['hostname']]['boot_state'] == 'Alive':
126 #if node['boot_state'] == 'Alive':
127 res['geni_status'] = 'ready'
129 res['geni_status'] = 'failed'
130 top_level_status = 'failed'
132 res['geni_error'] = ''
134 resources.append(res)
136 result['geni_status'] = top_level_status
137 result['geni_resources'] = resources
138 print >>sys.stderr, "\r\n \r\n_____________ Sliver status resources %s res %s \r\n " %(resources,res)
142 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
143 aggregate = SlabAggregate(self)
145 slices = SlabSlices(self)
146 peer = slices.get_peer(slice_hrn)
147 sfa_peer = slices.get_sfa_peer(slice_hrn)
151 if not isinstance(creds, list):
156 slice_record = users[0].get('slice_record', {})
159 rspec = RSpec(rspec_string)
160 requested_attributes = rspec.version.get_slice_attributes()
162 # ensure site record exists
163 #site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer, options=options)
164 # ensure slice record exists
165 slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer, options=options)
166 # ensure person records exists
167 persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer, options=options)
168 # ensure slice attributes exists
169 #slices.verify_slice_attributes(slice, requested_attributes, options=options)
171 # add/remove slice from nodes
172 requested_slivers = [node.get('component_name') for node in rspec.version.get_nodes_with_slivers()]
173 nodes = slices.verify_slice_nodes(slice, requested_slivers, peer)
177 # handle MyPLC peer association.
178 # only used by plc and ple.
179 #slices.handle_peer(site, slice, persons, peer)
181 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
184 def delete_sliver (self, slice_urn, slice_hrn, creds, options):
186 slices = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
191 # determine if this is a peer slice
192 # xxx I wonder if this would not need to use PlSlices.get_peer instead
193 # in which case plc.peers could be deprecated as this here
194 # is the only/last call to this last method in plc.peers
195 peer = peers.get_peer(self, slice_hrn)
198 self.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
199 self.DeleteSliceFromNodes(slice_hrn, slice['node_ids'])
202 self.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
208 # first 2 args are None in case of resource discovery
209 def list_resources (self, slice_urn, slice_hrn, creds, options):
210 #cached_requested = options.get('cached', True)
212 version_manager = VersionManager()
213 # get the rspec's return format from options
214 rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
215 version_string = "rspec_%s" % (rspec_version)
217 #panos adding the info option to the caching key (can be improved)
218 if options.get('info'):
219 version_string = version_string + "_"+options.get('info', 'default')
221 # look in cache first
222 #if cached_requested and self.cache and not slice_hrn:
223 #rspec = self.cache.get(version_string)
225 #logger.debug("SlabDriver.ListResources: returning cached advertisement")
228 #panos: passing user-defined options
229 #print "manager options = ",options
230 aggregate = SlabAggregate(self)
231 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
232 print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec origin_hrn %s" %(origin_hrn)
233 options.update({'origin_hrn':origin_hrn})
234 print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec options %s" %(options)
235 rspec = aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version,
239 #if self.cache and not slice_hrn:
240 #logger.debug("Slab.ListResources: stores advertisement in cache")
241 #self.cache.add(version_string, rspec)
246 def list_slices (self, creds, options):
247 # look in cache first
249 #slices = self.cache.get('slices')
251 #logger.debug("PlDriver.list_slices returns from cache")
255 print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY list_slices"
256 slices = self.GetSlices()
257 slice_hrns = [slicename_to_hrn(self.hrn, slice['slice_hrn']) for slice in slices]
258 slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
262 #logger.debug ("SlabDriver.list_slices stores value in cache")
263 #self.cache.add('slices', slice_urns)
267 #No site or node register supported
268 def register (self, sfa_record, hrn, pub_key):
269 type = sfa_record['type']
270 slab_record = self.sfa_fields_to_slab_fields(type, hrn, sfa_record)
272 #if type == 'authority':
273 #sites = self.shell.GetSites([slab_record['login_base']])
275 #pointer = self.shell.AddSite(slab_record)
277 #pointer = sites[0]['site_id']
280 acceptable_fields=['url', 'instantiation', 'name', 'description']
281 for key in slab_record.keys():
282 if key not in acceptable_fields:
284 print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY register"
285 slices = self.GetSlices(slice_filter =slab_record['hrn'], filter_type = 'slice_hrn')
287 pointer = self.AddSlice(slab_record)
289 pointer = slices[0]['slice_id']
292 persons = self.GetPersons([sfa_record['hrn']])
294 pointer = self.AddPerson(dict(sfa_record))
297 pointer = persons[0]['person_id']
299 #Does this make sense to senslab ?
300 #if 'enabled' in sfa_record and sfa_record['enabled']:
301 #self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
303 # add this person to the site only if she is being added for the first
304 # time by sfa and doesont already exist in plc
305 if not persons or not persons[0]['site_ids']:
306 login_base = get_leaf(sfa_record['authority'])
307 self.AddPersonToSite(pointer, login_base)
309 # What roles should this user have?
310 self.AddRoleToPerson('user', pointer)
313 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
315 #No node adding outside OAR
316 #elif type == 'node':
317 #login_base = hrn_to_slab_login_base(sfa_record['authority'])
318 #nodes = self.GetNodes([slab_record['hostname']])
320 #pointer = self.AddNode(login_base, slab_record)
322 #pointer = nodes[0]['node_id']
326 #No site or node record update allowed
327 def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
328 pointer = old_sfa_record['pointer']
329 type = old_sfa_record['type']
331 # new_key implemented for users only
332 if new_key and type not in [ 'user' ]:
333 raise UnknownSfaType(type)
335 #if (type == "authority"):
336 #self.shell.UpdateSite(pointer, new_sfa_record)
339 slab_record=self.sfa_fields_to_slab_fields(type, hrn, new_sfa_record)
340 if 'name' in slab_record:
341 slab_record.pop('name')
342 self.UpdateSlice(pointer, slab_record)
346 all_fields = new_sfa_record
347 for key in all_fields.keys():
348 if key in ['first_name', 'last_name', 'title', 'email',
349 'password', 'phone', 'url', 'bio', 'accepted_aup',
351 update_fields[key] = all_fields[key]
352 self.UpdatePerson(pointer, update_fields)
355 # must check this key against the previous one if it exists
356 persons = self.GetPersons([pointer], ['key_ids'])
358 keys = person['key_ids']
359 keys = self.GetKeys(person['key_ids'])
361 # Delete all stale keys
364 if new_key != key['key']:
365 self.DeleteKey(key['key_id'])
369 self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
371 #elif type == "node":
372 #self.UpdateNode(pointer, new_sfa_record)
377 def remove (self, sfa_record):
378 type=sfa_record['type']
379 hrn=sfa_record['hrn']
380 record_id= sfa_record['record_id']
382 username = hrn.split(".")[len(hrn.split(".")) -1]
384 persons = self.GetPersons(username)
385 # only delete this person if he has site ids. if he doesnt, it probably means
386 # he was just removed from a site, not actually deleted
387 if persons and persons[0]['site_ids']:
388 self.DeletePerson(username)
389 elif type == 'slice':
390 if self.GetSlices(slice_filter = hrn, filter_type = 'slice_hrn'):
391 self.DeleteSlice(hrn)
393 #elif type == 'authority':
394 #if self.GetSites(pointer):
395 #self.DeleteSite(pointer)
399 def GetPeers (self,auth = None, peer_filter=None, return_fields=None):
401 existing_records = {}
402 existing_hrns_by_types= {}
403 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers auth = %s, peer_filter %s, return_field %s " %(auth , peer_filter, return_fields)
404 all_records = dbsession.query(RegRecord).filter(RegRecord.type.like('%authority%')).all()
405 for record in all_records:
406 existing_records[record.hrn] = record
407 if record.type not in existing_hrns_by_types:
408 existing_hrns_by_types[record.type] = [record.hrn]
409 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t NOT IN existing_hrns_by_types %s " %( existing_hrns_by_types)
412 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t INNN type %s hrn %s " %( record.type,record.hrn )
413 existing_hrns_by_types.update({record.type:(existing_hrns_by_types[record.type].append(record.hrn))})
415 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers existing_hrns_by_types %s " %( existing_hrns_by_types)
419 for hrn in existing_hrns_by_types['authority+sa']:
420 records_list.append(existing_records[hrn])
421 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers records_list %s " %(records_list)
426 if not peer_filter and not return_fields:
428 return_records = parse_filter(records_list,peer_filter, 'peers', return_fields)
430 return return_records
434 def GetPersons(self, person_filter=None, return_fields=None):
436 person_list = self.ldap.ldapFind({'authority': self.root_auth })
439 #if person_filter and isinstance(person_filter, dict):
440 #for k in person_filter.keys():
441 #if k in person_list[0].keys():
444 return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
445 if return_person_list:
446 print>>sys.stderr, " \r\n GetPersons person_filter %s return_fields %s " %(person_filter,return_fields)
447 return return_person_list
449 def GetTimezone(self):
450 time = self.oar.parser.SendRequest("GET_timezone")
454 def DeleteJobs(self, job_id, username):
458 reqdict['method'] = "delete"
459 reqdict['strval'] = str(job_id)
460 answer = self.oar.POSTRequestToOARRestAPI('DELETE_jobs_id',reqdict,username)
461 print>>sys.stderr, "\r\n \r\n jobid DeleteJobs %s " %(answer)
464 def GetJobs(self,job_id= None, resources=True,return_fields=None, username = None):
465 #job_resources=['reserved_resources', 'assigned_resources','job_id', 'job_uri', 'assigned_nodes',\
467 #assigned_res = ['resource_id', 'resource_uri']
468 #assigned_n = ['node', 'node_uri']
471 if job_id and resources is False:
473 node_list_k = 'assigned_network_address'
475 if job_id and resources :
476 req = "GET_jobs_id_resources"
477 node_list_k = 'reserved_resources'
481 #Get job info from OAR
482 job_info = self.oar.parser.SendRequest(req, job_id, username)
483 print>>sys.stderr, "\r\n \r\n \t\t GetJobs %s " %(job_info)
485 if 'state' in job_info :
486 if job_info['state'] == 'Terminated':
487 print>>sys.stderr, "\r\n \r\n \t\t GetJobs TERMINELEBOUSIN "
489 if job_info['state'] == 'Error':
490 print>>sys.stderr, "\r\n \r\n \t\t GetJobs ERROR message %s " %(job_info)
493 #Get a dict of nodes . Key :hostname of the node
494 node_list = self.GetNodes()
495 node_hostname_list = []
496 for node in node_list:
497 node_hostname_list.append(node['hostname'])
498 node_dict = dict(zip(node_hostname_list,node_list))
504 liste =job_info[node_list_k]
505 print>>sys.stderr, "\r\n \r\n \t\t GetJobs resources job_info liste%s" %(liste)
506 for k in range(len(liste)):
507 job_info[node_list_k][k] = node_dict[job_info[node_list_k][k]]['hostname']
509 print>>sys.stderr, "\r\n \r\n \t\t YYYYYYYYYYYYGetJobs resources job_info %s" %(job_info)
510 #Replaces the previous entry "assigned_network_address" / "reserved_resources"
512 job_info.update({'node_ids':job_info[node_list_k]})
513 del job_info[node_list_k]
517 print>>sys.stderr, "\r\n \r\n \t\t GetJobs KEYERROR "
524 def GetNodes(self,node_filter= None, return_fields=None):
526 node_dict =self.oar.parser.SendRequest("GET_resources_full")
527 print>>sys.stderr, "\r\n \r\n \t\t SLABDRIVER.PY GetNodes "
528 return_node_list = []
529 if not (node_filter or return_fields):
530 return_node_list = node_dict.values()
531 return return_node_list
533 return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
534 return return_node_list
537 def GetSites(self, site_filter = None, return_fields=None):
538 site_dict =self.oar.parser.SendRequest("GET_sites")
539 print>>sys.stderr, "\r\n \r\n \t\t SLABDRIVER.PY GetSites "
540 return_site_list = []
541 if not ( site_filter or return_fields):
542 return_site_list = site_dict.values()
543 return return_site_list
545 return_site_list = parse_filter(site_dict.values(), site_filter,'site', return_fields)
546 return return_site_list
549 def GetSlices(self,slice_filter = None, filter_type = None, return_fields=None):
550 return_slice_list = []
553 ftypes = ['slice_hrn', 'record_id_user']
554 if filter_type and filter_type in ftypes:
555 if filter_type == 'slice_hrn':
556 slicerec = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = slice_filter).first()
557 if filter_type == 'record_id_user':
558 slicerec = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = slice_filter).first()
561 rec = slicerec.dumpquerytodict()
562 login = slicerec.slice_hrn.split(".")[1].split("_")[0]
563 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY slicerec GetSlices %s " %(slicerec)
564 if slicerec.oar_job_id is not -1:
565 rslt = self.GetJobs( slicerec.oar_job_id, resources=False, username = login )
566 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices GetJobs %s " %(rslt)
569 rec.update({'hrn':str(rec['slice_hrn'])})
570 #If GetJobs is empty, this means the job is now in the 'Terminated' state
571 #Update the slice record
573 self.db.update_job(slice_filter, job_id = -1)
574 rec['oar_job_id'] = -1
575 rec.update({'hrn':str(rec['slice_hrn'])})
577 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices rec %s" %(rec)
583 return_slice_list = slab_dbsession.query(SliceSenslab).all()
585 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices slices %s slice_filter %s " %(return_slice_list,slice_filter)
588 #return_slice_list = parse_filter(sliceslist, slice_filter,'slice', return_fields)
592 return return_slice_list
597 def testbed_name (self): return "senslab2"
599 # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
600 def aggregate_version (self):
601 version_manager = VersionManager()
602 ad_rspec_versions = []
603 request_rspec_versions = []
604 for rspec_version in version_manager.versions:
605 if rspec_version.content_type in ['*', 'ad']:
606 ad_rspec_versions.append(rspec_version.to_dict())
607 if rspec_version.content_type in ['*', 'request']:
608 request_rspec_versions.append(rspec_version.to_dict())
610 'testbed':self.testbed_name(),
611 'geni_request_rspec_versions': request_rspec_versions,
612 'geni_ad_rspec_versions': ad_rspec_versions,
621 # Convert SFA fields to PLC fields for use when registering up updating
622 # registry record in the PLC database
624 # @param type type of record (user, slice, ...)
625 # @param hrn human readable name
626 # @param sfa_fields dictionary of SFA fields
627 # @param slab_fields dictionary of PLC fields (output)
629 def sfa_fields_to_slab_fields(self, type, hrn, record):
631 def convert_ints(tmpdict, int_fields):
632 for field in int_fields:
634 tmpdict[field] = int(tmpdict[field])
637 #for field in record:
638 # slab_record[field] = record[field]
641 #instantion used in get_slivers ?
642 if not "instantiation" in slab_record:
643 slab_record["instantiation"] = "senslab-instantiated"
644 slab_record["hrn"] = hrn_to_pl_slicename(hrn)
645 print >>sys.stderr, "\r\n \r\n \t SLABDRIVER.PY sfa_fields_to_slab_fields slab_record %s hrn_to_pl_slicename(hrn) hrn %s " %(slab_record['hrn'], hrn)
647 slab_record["url"] = record["url"]
648 if "description" in record:
649 slab_record["description"] = record["description"]
650 if "expires" in record:
651 slab_record["expires"] = int(record["expires"])
653 #nodes added by OAR only and then imported to SFA
654 #elif type == "node":
655 #if not "hostname" in slab_record:
656 #if not "hostname" in record:
657 #raise MissingSfaInfo("hostname")
658 #slab_record["hostname"] = record["hostname"]
659 #if not "model" in slab_record:
660 #slab_record["model"] = "geni"
663 #elif type == "authority":
664 #slab_record["login_base"] = hrn_to_slab_login_base(hrn)
666 #if not "name" in slab_record:
667 #slab_record["name"] = hrn
669 #if not "abbreviated_name" in slab_record:
670 #slab_record["abbreviated_name"] = hrn
672 #if not "enabled" in slab_record:
673 #slab_record["enabled"] = True
675 #if not "is_public" in slab_record:
676 #slab_record["is_public"] = True
683 def AddSliceToNodes(self, slice_name, added_nodes, slice_user=None):
689 reqdict['property'] ="network_address in ("
690 for node in added_nodes:
691 #Get the ID of the node : remove the root auth and put the site in a separate list
693 # NT: it's not clear for me if the nodenames will have the senslab prefix
694 # so lets take the last part only, for now.
696 #if s[0] == self.root_auth :
697 # Again here it's not clear if nodes will be prefixed with <site>_, lets split and tanke the last part for now.
698 s=lastpart.split("_")
700 reqdict['property'] += "'"+ nodeid +"', "
701 nodeid_list.append(nodeid)
702 #site_list.append( l[0] )
703 reqdict['property'] = reqdict['property'][0: len( reqdict['property'])-2] +")"
704 reqdict['resource'] ="network_address="+ str(len(nodeid_list))
705 reqdict['resource']+= ",walltime=" + str(00) + ":" + str(12) + ":" + str(20) #+2 min 20
706 reqdict['script_path'] = "/bin/sleep 620" #+20 sec
707 reqdict['type'] = "deploy"
708 reqdict['directory']= ""
709 reqdict['name']= "TestSandrine"
710 timestamp = self.GetTimezone()
711 print>>sys.stderr, "\r\n \r\n AddSliceToNodes slice_name %s added_nodes %s username %s reqdict %s " %(slice_name,added_nodes,slice_user, reqdict)
712 readable_time = strftime(self.time_format, gmtime(float(timestamp)))
713 print >>sys.stderr," \r\n \r\n \t\t\t\t AVANT ParseTimezone readable_time %s timestanp %s " %(readable_time, timestamp )
714 timestamp = timestamp+ 3620 #Add 3 min to server time
715 readable_time = strftime(self.time_format, gmtime(float(timestamp)))
717 print >>sys.stderr," \r\n \r\n \t\t\t\tAPRES ParseTimezone readable_time %s timestanp %s " %(readable_time , timestamp)
718 reqdict['reservation'] = readable_time
720 # first step : start the OAR job
721 print>>sys.stderr, "\r\n \r\n AddSliceToNodes reqdict %s \r\n site_list %s" %(reqdict,site_list)
723 answer = self.oar.POSTRequestToOARRestAPI('POST_job',reqdict,slice_user)
724 print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid %s " %(answer)
725 #self.db.update('slice',['oar_job_id'], [answer['id']], 'slice_hrn', slice_name)
728 self.db.update_job( slice_name, job_id = answer['id'] )
730 print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid %s added_nodes %s slice_user %s" %(jobid,added_nodes,slice_user)
731 # second step : configure the experiment
732 # we need to store the nodes in a yaml (well...) file like this :
733 # [1,56,23,14,45,75] with name /tmp/sfa<jobid>.json
734 f=open('/tmp/sfa/'+str(jobid)+'.json','w')
736 f.write(str(added_nodes[0].strip('node')))
737 for node in added_nodes[1:len(added_nodes)] :
738 f.write(','+node.strip('node'))
742 # third step : call the senslab-experiment wrapper
743 #command= "java -jar target/sfa-1.0-jar-with-dependencies.jar "+str(jobid)+" "+slice_user
744 javacmdline="/usr/bin/java"
745 jarname="/opt/senslabexperimentwrapper/sfa-1.0-jar-with-dependencies.jar"
746 #ret=subprocess.check_output(["/usr/bin/java", "-jar", ", str(jobid), slice_user])
747 output = subprocess.Popen([javacmdline, "-jar", jarname, str(jobid), slice_user],stdout=subprocess.PIPE).communicate()[0]
749 print>>sys.stderr, "\r\n \r\n AddSliceToNodes wrapper returns %s " %(output)
755 def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
760 def fill_record_sfa_info(self, records):
762 def startswith(prefix, values):
763 return [value for value in values if value.startswith(prefix)]
768 for record in records:
769 person_ids.extend(record.get("person_ids", []))
770 site_ids.extend(record.get("site_ids", []))
771 if 'site_id' in record:
772 site_ids.append(record['site_id'])
774 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___person_ids %s \r\n \t\t site_ids %s " %(person_ids, site_ids)
776 # get all pis from the sites we've encountered
777 # and store them in a dictionary keyed on site_id
780 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
781 pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
782 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
785 # we will need the pi's hrns also
786 person_ids.append(pi['person_id'])
788 # we also need to keep track of the sites these pis
790 for site_id in pi['site_ids']:
791 if site_id in site_pis:
792 site_pis[site_id].append(pi)
794 site_pis[site_id] = [pi]
796 # get sfa records for all records associated with these records.
797 # we'll replace pl ids (person_ids) with hrns from the sfa records
800 # get the sfa records
802 existing_records = {}
803 all_records = dbsession.query(RegRecord).all()
804 for record in all_records:
805 existing_records[(record.type,record.pointer)] = record
807 print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info existing_records %s " %(existing_records)
808 person_list, persons = [], {}
809 #person_list = table.find({'type': 'user', 'pointer': person_ids})
811 for p_id in person_ids:
812 person_list.append( existing_records.get(('user',p_id)))
814 print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info ERRRRRRRRRROR"
816 # create a hrns keyed on the sfa record's pointer.
817 # Its possible for multiple records to have the same pointer so
818 # the dict's value will be a list of hrns.
819 persons = defaultdict(list)
820 for person in person_list:
821 persons[person['pointer']].append(person)
824 slab_person_list, slab_persons = [], {}
825 slab_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
826 slab_persons = list_to_dict(slab_person_list, 'person_id')
827 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ _list %s \r\n \t\t SenslabUsers.GetPersons ['person_id', 'roles'] slab_persons %s \r\n records %s" %(slab_person_list, slab_persons,records)
830 for record in records:
831 # skip records with no pl info (top level authorities)
832 #Sandrine 24 oct 11 2 lines
833 #if record['pointer'] == -1:
836 type = record['type']
837 if (type == "slice"):
838 # all slice users are researchers
839 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice') ? besoin ou pas ?
841 record['researcher'] = []
842 for person_id in record.get('person_ids', []):
843 #Sandrine 24 oct 11 line
844 #for person_id in record['person_ids']:
845 hrns = [person['hrn'] for person in persons[person_id]]
846 record['researcher'].extend(hrns)
848 # pis at the slice's site
849 slab_pis = site_pis[record['site_id']]
850 pi_ids = [pi['person_id'] for pi in slab_pis]
851 for person_id in pi_ids:
852 hrns = [person['hrn'] for person in persons[person_id]]
853 record['PI'].extend(hrns)
854 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
855 record['geni_creator'] = record['PI']
857 elif (type == "authority"):
859 record['operator'] = []
861 for pointer in record['person_ids']:
862 if pointer not in persons or pointer not in slab_persons:
863 # this means there is not sfa or pl record for this user
865 hrns = [person['hrn'] for person in persons[pointer]]
866 roles = slab_persons[pointer]['roles']
868 record['PI'].extend(hrns)
870 record['operator'].extend(hrns)
872 record['owner'].extend(hrns)
873 # xxx TODO: OrganizationName
874 elif (type == "node"):
875 sfa_info['dns'] = record.get("hostname", "")
876 # xxx TODO: URI, LatLong, IP, DNS
878 elif (type == "user"):
879 sfa_info['email'] = record.get("email", "")
880 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
881 sfa_info['geni_certificate'] = record['gid']
882 # xxx TODO: PostalAddress, Phone
884 #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<< fill_record_sfa_info sfa_info %s \r\n record %s : "%(sfa_info,record)
885 record.update(sfa_info)
887 def augment_records_with_testbed_info (self, sfa_records):
888 return self.fill_record_info (sfa_records)
890 def fill_record_info(self, records):
892 Given a SFA record, fill in the senslab specific and SFA specific
893 fields in the record.
896 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info 000000000 fill_record_info %s " %(records)
897 if not isinstance(records, list):
902 for record in parkour:
904 if str(record['type']) == 'slice':
905 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t \t record %s" %(record)
906 #sfatable = SfaTable()
908 #existing_records_by_id = {}
909 #all_records = dbsession.query(RegRecord).all()
910 #for rec in all_records:
911 #existing_records_by_id[rec.record_id] = rec
912 #print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t existing_records_by_id %s" %(existing_records_by_id[record['record_id']])
914 #recslice = self.db.find('slice',{'slice_hrn':str(record['hrn'])})
915 #recslice = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = str(record['hrn'])).first()
916 recslice = self.GetSlices(slice_filter = str(record['hrn']), filter_type = 'slice_hrn')
917 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t HOY HOY reclise %s" %(recslice)
918 #if isinstance(recslice,list) and len(recslice) == 1:
919 #recslice = recslice[0]
921 recuser = dbsession.query(RegRecord).filter_by(record_id = recslice['record_id_user']).first()
922 #existing_records_by_id[recslice['record_id_user']]
923 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t recuser %s" %(recuser)
926 record.update({'PI':[recuser.hrn],
927 'researcher': [recuser.hrn],
928 'name':record['hrn'],
929 'oar_job_id':recslice['oar_job_id'],
931 'person_ids':[recslice['record_id_user']]})
933 elif str(record['type']) == 'user':
934 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info USEEEEEEEEEERDESU!"
936 rec = self.GetSlices(slice_filter = record['record_id'], filter_type = 'record_id_user')
937 #Append record in records list, therfore fetches user and slice info again(one more loop)
938 #Will update PIs and researcher for the slice
940 rec.update({'type':'slice','hrn':rec['slice_hrn']})
942 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info ADDING SLIC EINFO rec %s" %(rec)
944 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info OKrecords %s" %(records)
946 print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info EXCEPTION RECORDS : %s" %(records)
949 #self.fill_record_slab_info(records)
950 ##print >>sys.stderr, "\r\n \t\t after fill_record_slab_info %s" %(records)
951 #self.fill_record_sfa_info(records)
952 #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
958 #def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
959 ## get a list of the HRNs tht are members of the old and new records
961 #oldList = oldRecord.get(listName, [])
964 #newList = record.get(listName, [])
966 ## if the lists are the same, then we don't have to update anything
967 #if (oldList == newList):
970 ## build a list of the new person ids, by looking up each person to get
974 #records = table.find({'type': 'user', 'hrn': newList})
976 #newIdList.append(rec['pointer'])
978 ## build a list of the old person ids from the person_ids field
980 #oldIdList = oldRecord.get("person_ids", [])
981 #containerId = oldRecord.get_pointer()
983 ## if oldRecord==None, then we are doing a Register, instead of an
986 #containerId = record.get_pointer()
988 ## add people who are in the new list, but not the oldList
989 #for personId in newIdList:
990 #if not (personId in oldIdList):
991 #addFunc(self.plauth, personId, containerId)
993 ## remove people who are in the old list, but not the new list
994 #for personId in oldIdList:
995 #if not (personId in newIdList):
996 #delFunc(self.plauth, personId, containerId)
998 #def update_membership(self, oldRecord, record):
999 #print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
1000 #if record.type == "slice":
1001 #self.update_membership_list(oldRecord, record, 'researcher',
1002 #self.users.AddPersonToSlice,
1003 #self.users.DeletePersonFromSlice)
1004 #elif record.type == "authority":
1009 # I don't think you plan on running a component manager at this point
1010 # let me clean up the mess of ComponentAPI that is deprecated anyways