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.
83 #slices = self.GetSlices([slice_hrn])
84 slices = 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 slices %s \r\n " %(slice_urn,slice_hrn,slices)
89 if sl['oar_job_id'] is not -1:
91 # report about the local nodes only
92 nodes = self.GetNodes({'hostname':sl['node_ids']},
93 ['node_id', 'hostname','site_login_base','boot_state'])
95 raise SliverDoesNotExist("No slivers allocated ")
98 site_logins = [node['site_login_base'] for node in nodes]
101 top_level_status = 'unknown'
103 top_level_status = 'ready'
104 result['geni_urn'] = slice_urn
105 result['slab_login'] = sl['job_user']
107 timestamp = float(sl['startTime']) + float(sl['walltime'])
108 result['slab_expires'] = strftime(self.time_format, gmtime(float(timestamp)))
113 res['slab_hostname'] = node['hostname']
114 res['slab_boot_state'] = node['boot_state']
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'
121 res['geni_status'] = 'failed'
122 top_level_status = 'failed'
124 res['geni_error'] = ''
126 resources.append(res)
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)
134 def create_sliver (self, slice_urn, slice_hrn, creds, rspec_string, users, options):
135 aggregate = SlabAggregate(self)
136 #aggregate = SlabAggregate(self)
137 slices = SlabSlices(self)
138 peer = slices.get_peer(slice_hrn)
139 sfa_peer = slices.get_sfa_peer(slice_hrn)
141 #print>>sys.stderr, " \r\n \r\n create_sliver creds %s \r\n \r\n users %s " %(creds,users)
143 if not isinstance(creds, list):
147 #cred_obj=Credential(string=cred)
148 #print >>sys.stderr," \r\n \r\n create_sliver cred %s " %(cred)
149 #GIDcall = cred_obj.get_gid_caller()
150 #GIDobj = cred_obj.get_gid_object()
151 #print >>sys.stderr," \r\n \r\n create_sliver GIDobj pubkey %s hrn %s " %(GIDobj.get_pubkey().get_pubkey_string(), GIDobj.get_hrn())
152 #print >>sys.stderr," \r\n \r\n create_sliver GIDcall pubkey %s hrn %s" %(GIDcall.get_pubkey().get_pubkey_string(),GIDobj.get_hrn())
155 #tmpcert = GID(string = users[0]['gid'])
156 #print >>sys.stderr," \r\n \r\n create_sliver tmpcer pubkey %s hrn %s " %(tmpcert.get_pubkey().get_pubkey_string(), tmpcert.get_hrn())
159 slice_record = users[0].get('slice_record', {})
162 rspec = RSpec(rspec_string)
163 requested_attributes = rspec.version.get_slice_attributes()
165 # ensure site record exists
166 #site = slices.verify_site(slice_hrn, slice_record, peer, sfa_peer, options=options)
167 # ensure slice record exists
168 slice = slices.verify_slice(slice_hrn, slice_record, peer, sfa_peer, options=options)
169 # ensure person records exists
170 persons = slices.verify_persons(slice_hrn, slice, users, peer, sfa_peer, options=options)
171 # ensure slice attributes exists
172 #slices.verify_slice_attributes(slice, requested_attributes, options=options)
174 # add/remove slice from nodes
175 requested_slivers = [node.get('component_name') for node in rspec.version.get_nodes_with_slivers()]
176 nodes = slices.verify_slice_nodes(slice, requested_slivers, peer)
180 # handle MyPLC peer association.
181 # only used by plc and ple.
182 #slices.handle_peer(site, slice, persons, peer)
184 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
187 def delete_sliver (self, slice_urn, slice_hrn, creds, options):
189 slices = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
190 #slices = self.GetSlices({'slice_hrn': slice_hrn})
195 # determine if this is a peer slice
196 # xxx I wonder if this would not need to use PlSlices.get_peer instead
197 # in which case plc.peers could be deprecated as this here
198 # is the only/last call to this last method in plc.peers
199 peer = peers.get_peer(self, slice_hrn)
202 self.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
203 self.DeleteSliceFromNodes(slice_hrn, slice['node_ids'])
206 self.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
212 # first 2 args are None in case of resource discovery
213 def list_resources (self, slice_urn, slice_hrn, creds, options):
214 #cached_requested = options.get('cached', True)
216 version_manager = VersionManager()
217 # get the rspec's return format from options
218 rspec_version = version_manager.get_version(options.get('geni_rspec_version'))
219 version_string = "rspec_%s" % (rspec_version)
221 #panos adding the info option to the caching key (can be improved)
222 if options.get('info'):
223 version_string = version_string + "_"+options.get('info', 'default')
225 # look in cache first
226 #if cached_requested and self.cache and not slice_hrn:
227 #rspec = self.cache.get(version_string)
229 #logger.debug("SlabDriver.ListResources: returning cached advertisement")
232 #panos: passing user-defined options
233 #print "manager options = ",options
234 aggregate = SlabAggregate(self)
235 origin_hrn = Credential(string=creds[0]).get_gid_caller().get_hrn()
236 print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec origin_hrn %s" %(origin_hrn)
237 options.update({'origin_hrn':origin_hrn})
238 print>>sys.stderr, " \r\n \r\n \t SLABDRIVER get_rspec options %s" %(options)
239 rspec = aggregate.get_rspec(slice_xrn=slice_urn, version=rspec_version,
243 #if self.cache and not slice_hrn:
244 #logger.debug("Slab.ListResources: stores advertisement in cache")
245 #self.cache.add(version_string, rspec)
250 def list_slices (self, creds, options):
251 # look in cache first
253 #slices = self.cache.get('slices')
255 #logger.debug("PlDriver.list_slices returns from cache")
259 print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY list_slices"
260 slices = self.GetSlices()
261 slice_hrns = [slicename_to_hrn(self.hrn, slice['slice_hrn']) for slice in slices]
262 slice_urns = [hrn_to_urn(slice_hrn, 'slice') for slice_hrn in slice_hrns]
266 #logger.debug ("SlabDriver.list_slices stores value in cache")
267 #self.cache.add('slices', slice_urns)
271 #No site or node register supported
272 def register (self, sfa_record, hrn, pub_key):
273 type = sfa_record['type']
274 slab_record = self.sfa_fields_to_slab_fields(type, hrn, sfa_record)
276 #if type == 'authority':
277 #sites = self.shell.GetSites([slab_record['login_base']])
279 #pointer = self.shell.AddSite(slab_record)
281 #pointer = sites[0]['site_id']
284 acceptable_fields=['url', 'instantiation', 'name', 'description']
285 for key in slab_record.keys():
286 if key not in acceptable_fields:
288 print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY register"
289 slices = self.GetSlices(slice_filter =slab_record['hrn'], filter_type = 'slice_hrn')
290 #slices = self.GetSlices([slab_record['hrn']])
292 pointer = self.AddSlice(slab_record)
294 pointer = slices[0]['slice_id']
297 persons = self.GetPersons([sfa_record['hrn']])
299 pointer = self.AddPerson(dict(sfa_record))
302 pointer = persons[0]['person_id']
304 #Does this make sense to senslab ?
305 #if 'enabled' in sfa_record and sfa_record['enabled']:
306 #self.UpdatePerson(pointer, {'enabled': sfa_record['enabled']})
308 # add this person to the site only if she is being added for the first
309 # time by sfa and doesont already exist in plc
310 if not persons or not persons[0]['site_ids']:
311 login_base = get_leaf(sfa_record['authority'])
312 self.AddPersonToSite(pointer, login_base)
314 # What roles should this user have?
315 self.AddRoleToPerson('user', pointer)
318 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
320 #No node adding outside OAR
321 #elif type == 'node':
322 #login_base = hrn_to_slab_login_base(sfa_record['authority'])
323 #nodes = self.GetNodes([slab_record['hostname']])
325 #pointer = self.AddNode(login_base, slab_record)
327 #pointer = nodes[0]['node_id']
331 #No site or node record update allowed
332 def update (self, old_sfa_record, new_sfa_record, hrn, new_key):
333 pointer = old_sfa_record['pointer']
334 type = old_sfa_record['type']
336 # new_key implemented for users only
337 if new_key and type not in [ 'user' ]:
338 raise UnknownSfaType(type)
340 #if (type == "authority"):
341 #self.shell.UpdateSite(pointer, new_sfa_record)
344 slab_record=self.sfa_fields_to_slab_fields(type, hrn, new_sfa_record)
345 if 'name' in slab_record:
346 slab_record.pop('name')
347 self.UpdateSlice(pointer, slab_record)
351 all_fields = new_sfa_record
352 for key in all_fields.keys():
353 if key in ['first_name', 'last_name', 'title', 'email',
354 'password', 'phone', 'url', 'bio', 'accepted_aup',
356 update_fields[key] = all_fields[key]
357 self.UpdatePerson(pointer, update_fields)
360 # must check this key against the previous one if it exists
361 persons = self.GetPersons([pointer], ['key_ids'])
363 keys = person['key_ids']
364 keys = self.GetKeys(person['key_ids'])
366 # Delete all stale keys
369 if new_key != key['key']:
370 self.DeleteKey(key['key_id'])
374 self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
376 #elif type == "node":
377 #self.UpdateNode(pointer, new_sfa_record)
382 def remove (self, sfa_record):
383 type=sfa_record['type']
384 hrn=sfa_record['hrn']
385 record_id= sfa_record['record_id']
387 username = hrn.split(".")[len(hrn.split(".")) -1]
389 persons = self.GetPersons(username)
390 # only delete this person if he has site ids. if he doesnt, it probably means
391 # he was just removed from a site, not actually deleted
392 if persons and persons[0]['site_ids']:
393 self.DeletePerson(username)
394 elif type == 'slice':
395 if self.GetSlices(slice_filter = hrn, filter_type = 'slice_hrn'):
396 self.DeleteSlice(hrn)
398 #elif type == 'authority':
399 #if self.GetSites(pointer):
400 #self.DeleteSite(pointer)
404 def GetPeers (self,auth = None, peer_filter=None, return_fields=None):
406 existing_records = {}
407 existing_hrns_by_types= {}
408 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers auth = %s, peer_filter %s, return_field %s " %(auth , peer_filter, return_fields)
409 all_records = dbsession.query(RegRecord).filter(RegRecord.type.like('%authority%')).all()
410 for record in all_records:
411 existing_records[record.hrn] = record
412 if record.type not in existing_hrns_by_types:
413 existing_hrns_by_types[record.type] = [record.hrn]
414 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t NOT IN existing_hrns_by_types %s " %( existing_hrns_by_types)
417 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers \t INNN type %s hrn %s " %( record.type,record.hrn )
418 existing_hrns_by_types.update({record.type:(existing_hrns_by_types[record.type].append(record.hrn))})
420 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers existing_hrns_by_types %s " %( existing_hrns_by_types)
424 for hrn in existing_hrns_by_types['authority+sa']:
425 records_list.append(existing_records[hrn])
426 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers records_list %s " %(records_list)
431 if not peer_filter and not return_fields:
433 return_records = parse_filter(records_list,peer_filter, 'peers', return_fields)
435 return return_records
439 def GetPersons(self, person_filter=None, return_fields=None):
441 person_list = self.ldap.ldapFind({'authority': self.root_auth })
444 #if person_filter and isinstance(person_filter, dict):
445 #for k in person_filter.keys():
446 #if k in person_list[0].keys():
449 return_person_list = parse_filter(person_list,person_filter ,'persons', return_fields)
450 if return_person_list:
451 print>>sys.stderr, " \r\n GetPersons person_filter %s return_fields %s " %(person_filter,return_fields)
452 return return_person_list
454 def GetTimezone(self):
455 time = self.oar.parser.SendRequest("GET_timezone")
459 def DeleteJobs(self, job_id, username):
463 reqdict['method'] = "delete"
464 reqdict['strval'] = str(job_id)
465 answer = self.oar.POSTRequestToOARRestAPI('DELETE_jobs_id',reqdict,username)
466 print>>sys.stderr, "\r\n \r\n jobid DeleteJobs %s " %(answer)
469 def GetJobs(self,job_id= None, resources=True,return_fields=None, username = None):
470 #job_resources=['reserved_resources', 'assigned_resources','job_id', 'job_uri', 'assigned_nodes',\
472 #assigned_res = ['resource_id', 'resource_uri']
473 #assigned_n = ['node', 'node_uri']
476 if job_id and resources is False:
478 node_list_k = 'assigned_network_address'
480 if job_id and resources :
481 req = "GET_jobs_id_resources"
482 node_list_k = 'reserved_resources'
486 #Get job info from OAR
487 job_info = self.oar.parser.SendRequest(req, job_id, username)
488 print>>sys.stderr, "\r\n \r\n \t\t GetJobs %s " %(job_info)
490 if 'state' in job_info :
491 if job_info['state'] == 'Terminated':
492 print>>sys.stderr, "\r\n \r\n \t\t GetJobs TERMINELEBOUSIN "
494 if job_info['state'] == 'Error':
495 print>>sys.stderr, "\r\n \r\n \t\t GetJobs ERROR message %s " %(job_info)
498 #Get a dict of nodes . Key :hostname of the node
499 node_list = self.GetNodes()
500 node_hostname_list = []
501 for node in node_list:
502 node_hostname_list.append(node['hostname'])
503 node_dict = dict(zip(node_hostname_list,node_list))
505 #print>>sys.stderr, "\r\n \r\n \r\n \r\n \r\n \t\t GetJobs GetNODES %s " %(node_list)
508 #for n in job_info[node_list]:
509 #n = str(self.root_auth) + str(n)
511 liste =job_info[node_list_k]
512 print>>sys.stderr, "\r\n \r\n \t\t GetJobs resources job_info liste%s" %(liste)
513 for k in range(len(liste)):
514 job_info[node_list_k][k] = node_dict[job_info[node_list_k][k]]['hostname']
516 print>>sys.stderr, "\r\n \r\n \t\t YYYYYYYYYYYYGetJobs resources job_info %s" %(job_info)
517 job_info.update({'node_ids':job_info[node_list_k]})
518 del job_info[node_list_k]
522 print>>sys.stderr, "\r\n \r\n \t\t GetJobs KEYERROR "
529 def GetNodes(self,node_filter= None, return_fields=None):
531 node_dict =self.oar.parser.SendRequest("GET_resources_full")
532 print>>sys.stderr, "\r\n \r\n \t\t SLABDRIVER.PY GetNodes "
533 return_node_list = []
534 if not (node_filter or return_fields):
535 return_node_list = node_dict.values()
536 return return_node_list
538 return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
539 return return_node_list
542 def GetSites(self, site_filter = None, return_fields=None):
543 site_dict =self.oar.parser.SendRequest("GET_sites")
544 print>>sys.stderr, "\r\n \r\n \t\t SLABDRIVER.PY GetSites "
545 return_site_list = []
546 if not ( site_filter or return_fields):
547 return_site_list = site_dict.values()
548 return return_site_list
550 return_site_list = parse_filter(site_dict.values(), site_filter,'site', return_fields)
551 return return_site_list
553 #TODO : filtrer au niveau de la query voir sqlalchemy
554 #http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#returning-lists-and-scalars
555 def GetSlices(self,slice_filter = None, filter_type = None, return_fields=None):
556 return_slice_list = []
557 ftypes = ['slice_hrn', 'record_id_user']
558 if filter_type and filter_type in ftypes:
559 if filter_type == 'slice_hrn':
560 slicerec = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = slice_filter).first()
561 if filter_type == 'record_id_user':
562 slicerec = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = slice_filter).first()
563 #sliceslist = self.db.find('slice_senslab',columns = ['oar_job_id', 'slice_hrn', 'record_id_slice','record_id_user'], record_filter=slice_filter)
564 #sliceslist = slab_dbsession.query(SliceSenslab).all()
565 #return_slice_list = self.db.find('slice',slice_filter)
566 #sliceslist = slices_records.order_by("record_id_slice").all()
568 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices slices %s slice_filter %s " %(return_slice_list,slice_filter)
571 return_slice_list = parse_filter(sliceslist, slice_filter,'slice', return_fields)
574 rec = slicerec.dumpquerytodict()
575 login = slicerec.slice_hrn.split(".")[1].split("_")[0]
576 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY slicerec GetSlices %s " %(slicerec)
577 if slicerec.oar_job_id is not -1:
578 rslt = self.GetJobs( slicerec.oar_job_id, resources=False, username = login )
579 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices GetJobs %s " %(rslt)
582 rec.update({'hrn':str(rec['slice_hrn'])})
583 #If GetJobs is empty, this means the job is now in the 'Terminated' state
584 #Update the slice record
586 self.db.update_job('-1', slice_filter)
587 rec['oar_job_id'] = '-1'
588 rec.update({'hrn':str(rec['slice_hrn'])})
590 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices rec %s" %(rec)
597 #if return_slice_list:
598 #for sl in return_slice_list:
599 ##login = sl['slice_hrn'].split(".")[1].split("_")[0]
600 #login = sl['slice_hrn'].split(".")[1].split("_")[0]
601 #print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices sl %s " %(sl)
602 #if sl['oar_job_id'] is not -1:
603 #rslt = self.GetJobs( sl['oar_job_id'],resources=False, username = login )
604 #print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices GetJobs %s " %(rslt)
607 #sl.update({'hrn':str(sl['slice_hrn'])})
608 ##If GetJobs is empty, this means the job is now in the 'Terminated' state
609 ##Update the slice record
611 #sl['oar_job_id'] = '-1'
612 #sl.update({'hrn':str(sl['slice_hrn'])})
613 ##self.db.update_senslab_slice(sl)
615 #print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices return_slice_list %s" %(return_slice_list)
616 #return return_slice_list
620 def testbed_name (self): return "senslab2"
622 # 'geni_request_rspec_versions' and 'geni_ad_rspec_versions' are mandatory
623 def aggregate_version (self):
624 version_manager = VersionManager()
625 ad_rspec_versions = []
626 request_rspec_versions = []
627 for rspec_version in version_manager.versions:
628 if rspec_version.content_type in ['*', 'ad']:
629 ad_rspec_versions.append(rspec_version.to_dict())
630 if rspec_version.content_type in ['*', 'request']:
631 request_rspec_versions.append(rspec_version.to_dict())
633 'testbed':self.testbed_name(),
634 'geni_request_rspec_versions': request_rspec_versions,
635 'geni_ad_rspec_versions': ad_rspec_versions,
644 # Convert SFA fields to PLC fields for use when registering up updating
645 # registry record in the PLC database
647 # @param type type of record (user, slice, ...)
648 # @param hrn human readable name
649 # @param sfa_fields dictionary of SFA fields
650 # @param slab_fields dictionary of PLC fields (output)
652 def sfa_fields_to_slab_fields(self, type, hrn, record):
654 def convert_ints(tmpdict, int_fields):
655 for field in int_fields:
657 tmpdict[field] = int(tmpdict[field])
660 #for field in record:
661 # slab_record[field] = record[field]
664 #instantion used in get_slivers ?
665 if not "instantiation" in slab_record:
666 slab_record["instantiation"] = "senslab-instantiated"
667 slab_record["hrn"] = hrn_to_pl_slicename(hrn)
668 print >>sys.stderr, "\r\n \r\n \t SLABDRIVER.PY sfa_fields_to_slab_fields slab_record %s hrn_to_pl_slicename(hrn) hrn %s " %(slab_record['hrn'], hrn)
670 slab_record["url"] = record["url"]
671 if "description" in record:
672 slab_record["description"] = record["description"]
673 if "expires" in record:
674 slab_record["expires"] = int(record["expires"])
676 #nodes added by OAR only and then imported to SFA
677 #elif type == "node":
678 #if not "hostname" in slab_record:
679 #if not "hostname" in record:
680 #raise MissingSfaInfo("hostname")
681 #slab_record["hostname"] = record["hostname"]
682 #if not "model" in slab_record:
683 #slab_record["model"] = "geni"
686 #elif type == "authority":
687 #slab_record["login_base"] = hrn_to_slab_login_base(hrn)
689 #if not "name" in slab_record:
690 #slab_record["name"] = hrn
692 #if not "abbreviated_name" in slab_record:
693 #slab_record["abbreviated_name"] = hrn
695 #if not "enabled" in slab_record:
696 #slab_record["enabled"] = True
698 #if not "is_public" in slab_record:
699 #slab_record["is_public"] = True
706 def AddSliceToNodes(self, slice_name, added_nodes, slice_user=None):
712 reqdict['property'] ="network_address in ("
713 for node in added_nodes:
714 #Get the ID of the node : remove the root auth and put the site in a separate list
716 # NT: it's not clear for me if the nodenames will have the senslab prefix
717 # so lets take the last part only, for now.
719 #if s[0] == self.root_auth :
720 # Again here it's not clear if nodes will be prefixed with <site>_, lets split and tanke the last part for now.
721 s=lastpart.split("_")
723 reqdict['property'] += "'"+ nodeid +"', "
724 nodeid_list.append(nodeid)
725 #site_list.append( l[0] )
726 reqdict['property'] = reqdict['property'][0: len( reqdict['property'])-2] +")"
727 reqdict['resource'] ="network_address="+ str(len(nodeid_list))
728 reqdict['resource']+= ",walltime=" + str(00) + ":" + str(12) + ":" + str(20) #+2 min 20
729 reqdict['script_path'] = "/bin/sleep 620" #+20 sec
730 reqdict['type'] = "deploy"
731 reqdict['directory']= ""
732 reqdict['name']= "TestSandrine"
733 timestamp = self.GetTimezone()
734 print>>sys.stderr, "\r\n \r\n AddSliceToNodes slice_name %s added_nodes %s username %s reqdict %s " %(slice_name,added_nodes,slice_user, reqdict)
735 readable_time = strftime(self.time_format, gmtime(float(timestamp)))
736 print >>sys.stderr," \r\n \r\n \t\t\t\t AVANT ParseTimezone readable_time %s timestanp %s " %(readable_time, timestamp )
737 timestamp = timestamp+ 3620 #Add 3 min to server time
738 readable_time = strftime(self.time_format, gmtime(float(timestamp)))
740 print >>sys.stderr," \r\n \r\n \t\t\t\tAPRES ParseTimezone readable_time %s timestanp %s " %(readable_time , timestamp)
741 reqdict['reservation'] = readable_time
743 # first step : start the OAR job
744 print>>sys.stderr, "\r\n \r\n AddSliceToNodes reqdict %s \r\n site_list %s" %(reqdict,site_list)
746 answer = self.oar.POSTRequestToOARRestAPI('POST_job',reqdict,slice_user)
747 print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid %s " %(answer)
748 #self.db.update('slice',['oar_job_id'], [answer['id']], 'slice_hrn', slice_name)
751 self.db.update_job( answer['id'], slice_name)
753 print>>sys.stderr, "\r\n \r\n AddSliceToNodes jobid %s added_nodes %s slice_user %s" %(jobid,added_nodes,slice_user)
754 # second step : configure the experiment
755 # we need to store the nodes in a yaml (well...) file like this :
756 # [1,56,23,14,45,75] with name /tmp/sfa<jobid>.json
757 f=open('/tmp/sfa/'+str(jobid)+'.json','w')
759 f.write(str(added_nodes[0].strip('node')))
760 for node in added_nodes[1:len(added_nodes)] :
761 f.write(','+node.strip('node'))
765 # third step : call the senslab-experiment wrapper
766 #command= "java -jar target/sfa-1.0-jar-with-dependencies.jar "+str(jobid)+" "+slice_user
767 javacmdline="/usr/bin/java"
768 jarname="/opt/senslabexperimentwrapper/sfa-1.0-jar-with-dependencies.jar"
769 #ret=subprocess.check_output(["/usr/bin/java", "-jar", ", str(jobid), slice_user])
770 output = subprocess.Popen([javacmdline, "-jar", jarname, str(jobid), slice_user],stdout=subprocess.PIPE).communicate()[0]
772 print>>sys.stderr, "\r\n \r\n AddSliceToNodes wrapper returns %s " %(output)
778 def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
783 def fill_record_sfa_info(self, records):
785 def startswith(prefix, values):
786 return [value for value in values if value.startswith(prefix)]
791 for record in records:
792 person_ids.extend(record.get("person_ids", []))
793 site_ids.extend(record.get("site_ids", []))
794 if 'site_id' in record:
795 site_ids.append(record['site_id'])
797 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___person_ids %s \r\n \t\t site_ids %s " %(person_ids, site_ids)
799 # get all pis from the sites we've encountered
800 # and store them in a dictionary keyed on site_id
803 pi_filter = {'|roles': ['pi'], '|site_ids': site_ids}
804 pi_list = self.GetPersons( pi_filter, ['person_id', 'site_ids'])
805 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ GetPersons ['person_id', 'site_ids'] pi_ilist %s" %(pi_list)
808 # we will need the pi's hrns also
809 person_ids.append(pi['person_id'])
811 # we also need to keep track of the sites these pis
813 for site_id in pi['site_ids']:
814 if site_id in site_pis:
815 site_pis[site_id].append(pi)
817 site_pis[site_id] = [pi]
819 # get sfa records for all records associated with these records.
820 # we'll replace pl ids (person_ids) with hrns from the sfa records
823 # get the sfa records
825 existing_records = {}
826 all_records = dbsession.query(RegRecord).all()
827 for record in all_records:
828 existing_records[(record.type,record.pointer)] = record
830 print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info existing_records %s " %(existing_records)
831 person_list, persons = [], {}
832 #person_list = table.find({'type': 'user', 'pointer': person_ids})
834 for p_id in person_ids:
835 person_list.append( existing_records.get(('user',p_id)))
837 print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info ERRRRRRRRRROR"
839 # create a hrns keyed on the sfa record's pointer.
840 # Its possible for multiple records to have the same pointer so
841 # the dict's value will be a list of hrns.
842 persons = defaultdict(list)
843 for person in person_list:
844 persons[person['pointer']].append(person)
847 slab_person_list, slab_persons = [], {}
848 slab_person_list = self.GetPersons(person_ids, ['person_id', 'roles'])
849 slab_persons = list_to_dict(slab_person_list, 'person_id')
850 #print>>sys.stderr, "\r\n \r\n _fill_record_sfa_info ___ _list %s \r\n \t\t SenslabUsers.GetPersons ['person_id', 'roles'] slab_persons %s \r\n records %s" %(slab_person_list, slab_persons,records)
853 for record in records:
854 # skip records with no pl info (top level authorities)
855 #Sandrine 24 oct 11 2 lines
856 #if record['pointer'] == -1:
859 type = record['type']
860 if (type == "slice"):
861 # all slice users are researchers
862 #record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice') ? besoin ou pas ?
864 record['researcher'] = []
865 for person_id in record.get('person_ids', []):
866 #Sandrine 24 oct 11 line
867 #for person_id in record['person_ids']:
868 hrns = [person['hrn'] for person in persons[person_id]]
869 record['researcher'].extend(hrns)
871 # pis at the slice's site
872 slab_pis = site_pis[record['site_id']]
873 pi_ids = [pi['person_id'] for pi in slab_pis]
874 for person_id in pi_ids:
875 hrns = [person['hrn'] for person in persons[person_id]]
876 record['PI'].extend(hrns)
877 record['geni_urn'] = hrn_to_urn(record['hrn'], 'slice')
878 record['geni_creator'] = record['PI']
880 elif (type == "authority"):
882 record['operator'] = []
884 for pointer in record['person_ids']:
885 if pointer not in persons or pointer not in slab_persons:
886 # this means there is not sfa or pl record for this user
888 hrns = [person['hrn'] for person in persons[pointer]]
889 roles = slab_persons[pointer]['roles']
891 record['PI'].extend(hrns)
893 record['operator'].extend(hrns)
895 record['owner'].extend(hrns)
896 # xxx TODO: OrganizationName
897 elif (type == "node"):
898 sfa_info['dns'] = record.get("hostname", "")
899 # xxx TODO: URI, LatLong, IP, DNS
901 elif (type == "user"):
902 sfa_info['email'] = record.get("email", "")
903 sfa_info['geni_urn'] = hrn_to_urn(record['hrn'], 'user')
904 sfa_info['geni_certificate'] = record['gid']
905 # xxx TODO: PostalAddress, Phone
907 #print>>sys.stderr, "\r\n \r\rn \t\t \t <<<<<<<<<<<<<<<<<<<<<<<< fill_record_sfa_info sfa_info %s \r\n record %s : "%(sfa_info,record)
908 record.update(sfa_info)
910 def augment_records_with_testbed_info (self, sfa_records):
911 return self.fill_record_info (sfa_records)
913 def fill_record_info(self, records):
915 Given a SFA record, fill in the senslab specific and SFA specific
916 fields in the record.
918 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info 000000000 fill_record_info %s \t \t record['type'] %s " %(records, records[0]['type'])
919 if not isinstance(records, list):
924 for record in parkour:
926 if str(record['type']) == 'slice':
927 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t \t record %s" %(record)
928 #sfatable = SfaTable()
930 #existing_records_by_id = {}
931 #all_records = dbsession.query(RegRecord).all()
932 #for rec in all_records:
933 #existing_records_by_id[rec.record_id] = rec
934 #print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t existing_records_by_id %s" %(existing_records_by_id[record['record_id']])
936 #recslice = self.db.find('slice',{'slice_hrn':str(record['hrn'])})
937 #recslice = slab_dbsession.query(SliceSenslab).filter_by(slice_hrn = str(record['hrn'])).first()
938 recslice = self.GetSlices(slice_filter = str(record['hrn']), filter_type = 'slice_hrn')
939 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t HOY HOY reclise %s" %(recslice)
940 #if isinstance(recslice,list) and len(recslice) == 1:
941 #recslice = recslice[0]
943 recuser = dbsession.query(RegRecord).filter_by(record_id = recslice['record_id_user']).first()
944 #existing_records_by_id[recslice['record_id_user']]
945 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info \t\t recuser %s" %(recuser)
947 #if isinstance(recuser,list) and len(recuser) == 1:
948 #recuser = recuser[0]
949 record.update({'PI':[recuser.hrn],
950 'researcher': [recuser.hrn],
951 'name':record['hrn'],
952 'oar_job_id':recslice['oar_job_id'],
954 'person_ids':[recslice['record_id_user']]})
956 elif str(record['type']) == 'user':
957 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info USEEEEEEEEEERDESU!"
958 #recslice = self.db.find('slice', record_filter={'record_id_user':record['record_id']})
959 #recslice = slab_dbsession.query(SliceSenslab).filter_by(record_id_user = record['record_id']).first()
960 rec = self.GetSlices(slice_filter = record['record_id'], filter_type = 'record_id_user')
961 #Append record in records list, therfore fetches user and slice info again(one more loop)
962 #Will update PIs and researcher for the slice
963 #rec = recslice.dumpquerytodict()
964 rec.update({'type':'slice','hrn':rec['slice_hrn']})
966 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info ADDING SLIC EINFO rec %s" %(rec)
968 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info OKrecords %s" %(records)
970 print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info EXCEPTION RECORDS : %s" %(records)
973 #self.fill_record_slab_info(records)
974 ##print >>sys.stderr, "\r\n \t\t after fill_record_slab_info %s" %(records)
975 #self.fill_record_sfa_info(records)
976 #print >>sys.stderr, "\r\n \t\t after fill_record_sfa_info"
982 #def update_membership_list(self, oldRecord, record, listName, addFunc, delFunc):
983 ## get a list of the HRNs tht are members of the old and new records
985 #oldList = oldRecord.get(listName, [])
988 #newList = record.get(listName, [])
990 ## if the lists are the same, then we don't have to update anything
991 #if (oldList == newList):
994 ## build a list of the new person ids, by looking up each person to get
998 #records = table.find({'type': 'user', 'hrn': newList})
1000 #newIdList.append(rec['pointer'])
1002 ## build a list of the old person ids from the person_ids field
1004 #oldIdList = oldRecord.get("person_ids", [])
1005 #containerId = oldRecord.get_pointer()
1007 ## if oldRecord==None, then we are doing a Register, instead of an
1010 #containerId = record.get_pointer()
1012 ## add people who are in the new list, but not the oldList
1013 #for personId in newIdList:
1014 #if not (personId in oldIdList):
1015 #addFunc(self.plauth, personId, containerId)
1017 ## remove people who are in the old list, but not the new list
1018 #for personId in oldIdList:
1019 #if not (personId in newIdList):
1020 #delFunc(self.plauth, personId, containerId)
1022 #def update_membership(self, oldRecord, record):
1023 #print >>sys.stderr, " \r\n \r\n ***SLABDRIVER.PY update_membership record ", record
1024 #if record.type == "slice":
1025 #self.update_membership_list(oldRecord, record, 'researcher',
1026 #self.users.AddPersonToSlice,
1027 #self.users.DeletePersonFromSlice)
1028 #elif record.type == "authority":
1033 # I don't think you plan on running a component manager at this point
1034 # let me clean up the mess of ComponentAPI that is deprecated anyways