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 = self.GetNodes({'hostname':sl['node_ids']},
93 ['node_id', 'hostname','site','boot_state'])
95 raise SliverDoesNotExist("No slivers allocated ")
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)
137 slices = SlabSlices(self)
138 peer = slices.get_peer(slice_hrn)
139 sfa_peer = slices.get_sfa_peer(slice_hrn)
143 if not isinstance(creds, list):
148 slice_record = users[0].get('slice_record', {})
151 rspec = RSpec(rspec_string)
152 requested_attributes = rspec.version.get_slice_attributes()
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)
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)
169 # handle MyPLC peer association.
170 # only used by plc and ple.
171 #slices.handle_peer(site, slice, persons, peer)
173 return aggregate.get_rspec(slice_xrn=slice_urn, version=rspec.version)
176 def delete_sliver (self, slice_urn, slice_hrn, creds, options):
178 slices = self.GetSlices(slice_filter= slice_hrn, filter_type = 'slice_hrn')
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)
190 self.UnBindObjectFromPeer('slice', slice['slice_id'], peer)
191 self.DeleteSliceFromNodes(slice_hrn, slice['node_ids'])
194 self.BindObjectToPeer('slice', slice['slice_id'], peer, slice['peer_slice_id'])
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)
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)
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')
213 # look in cache first
214 #if cached_requested and self.cache and not slice_hrn:
215 #rspec = self.cache.get(version_string)
217 #logger.debug("SlabDriver.ListResources: returning cached advertisement")
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,
231 #if self.cache and not slice_hrn:
232 #logger.debug("Slab.ListResources: stores advertisement in cache")
233 #self.cache.add(version_string, rspec)
238 def list_slices (self, creds, options):
239 # look in cache first
241 #slices = self.cache.get('slices')
243 #logger.debug("PlDriver.list_slices returns from cache")
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]
254 #logger.debug ("SlabDriver.list_slices stores value in cache")
255 #self.cache.add('slices', slice_urns)
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)
264 #if type == 'authority':
265 #sites = self.shell.GetSites([slab_record['login_base']])
267 #pointer = self.shell.AddSite(slab_record)
269 #pointer = sites[0]['site_id']
272 acceptable_fields=['url', 'instantiation', 'name', 'description']
273 for key in slab_record.keys():
274 if key not in acceptable_fields:
276 print>>sys.stderr, " \r\n \t\t SLABDRIVER.PY register"
277 slices = self.GetSlices(slice_filter =slab_record['hrn'], filter_type = 'slice_hrn')
279 pointer = self.AddSlice(slab_record)
281 pointer = slices[0]['slice_id']
284 persons = self.GetPersons([sfa_record['hrn']])
286 pointer = self.AddPerson(dict(sfa_record))
289 pointer = persons[0]['person_id']
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']})
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)
301 # What roles should this user have?
302 self.AddRoleToPerson('user', pointer)
305 self.AddPersonKey(pointer, {'key_type' : 'ssh', 'key' : pub_key})
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']])
312 #pointer = self.AddNode(login_base, slab_record)
314 #pointer = nodes[0]['node_id']
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']
323 # new_key implemented for users only
324 if new_key and type not in [ 'user' ]:
325 raise UnknownSfaType(type)
327 #if (type == "authority"):
328 #self.shell.UpdateSite(pointer, new_sfa_record)
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)
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',
343 update_fields[key] = all_fields[key]
344 self.UpdatePerson(pointer, update_fields)
347 # must check this key against the previous one if it exists
348 persons = self.GetPersons([pointer], ['key_ids'])
350 keys = person['key_ids']
351 keys = self.GetKeys(person['key_ids'])
353 # Delete all stale keys
356 if new_key != key['key']:
357 self.DeleteKey(key['key_id'])
361 self.AddPersonKey(pointer, {'key_type': 'ssh', 'key': new_key})
363 #elif type == "node":
364 #self.UpdateNode(pointer, new_sfa_record)
369 def remove (self, sfa_record):
370 type=sfa_record['type']
371 hrn=sfa_record['hrn']
372 record_id= sfa_record['record_id']
374 username = hrn.split(".")[len(hrn.split(".")) -1]
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)
385 #elif type == 'authority':
386 #if self.GetSites(pointer):
387 #self.DeleteSite(pointer)
391 def GetPeers (self,auth = None, peer_filter=None, return_fields=None):
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)
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))})
407 print >>sys.stderr, "\r\n \r\n SLABDRIVER GetPeers existing_hrns_by_types %s " %( existing_hrns_by_types)
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)
418 if not peer_filter and not return_fields:
420 return_records = parse_filter(records_list,peer_filter, 'peers', return_fields)
422 return return_records
426 def GetPersons(self, person_filter=None, return_fields=None):
428 person_list = self.ldap.ldapFind({'authority': self.root_auth })
431 #if person_filter and isinstance(person_filter, dict):
432 #for k in person_filter.keys():
433 #if k in person_list[0].keys():
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
441 def GetTimezone(self):
442 time = self.oar.parser.SendRequest("GET_timezone")
446 def DeleteJobs(self, job_id, username):
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)
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',\
459 #assigned_res = ['resource_id', 'resource_uri']
460 #assigned_n = ['node', 'node_uri']
463 if job_id and resources is False:
465 node_list_k = 'assigned_network_address'
467 if job_id and resources :
468 req = "GET_jobs_id_resources"
469 node_list_k = 'reserved_resources'
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)
477 if 'state' in job_info :
478 if job_info['state'] == 'Terminated':
479 print>>sys.stderr, "\r\n \r\n \t\t GetJobs TERMINELEBOUSIN "
481 if job_info['state'] == 'Error':
482 print>>sys.stderr, "\r\n \r\n \t\t GetJobs ERROR message %s " %(job_info)
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))
492 #print>>sys.stderr, "\r\n \r\n \r\n \r\n \r\n \t\t GetJobs GetNODES %s " %(node_list)
495 #for n in job_info[node_list]:
496 #n = str(self.root_auth) + str(n)
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']
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]
509 print>>sys.stderr, "\r\n \r\n \t\t GetJobs KEYERROR "
516 def GetNodes(self,node_filter= None, return_fields=None):
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
525 return_node_list= parse_filter(node_dict.values(),node_filter ,'node', return_fields)
526 return return_node_list
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
537 return_site_list = parse_filter(site_dict.values(), site_filter,'site', return_fields)
538 return return_site_list
541 def GetSlices(self,slice_filter = None, filter_type = None, return_fields=None):
542 return_slice_list = []
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()
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)
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
563 self.db.update_job(slice_filter, job_id = -1)
564 rec['oar_job_id'] = -1
565 rec.update({'hrn':str(rec['slice_hrn'])})
567 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices rec %s" %(rec)
572 return_slice_list = slab_dbsession.query(SliceSenslab).all()
574 print >>sys.stderr, " \r\n \r\n \tSLABDRIVER.PY GetSlices slices %s slice_filter %s " %(return_slice_list,slice_filter)
577 #return_slice_list = parse_filter(sliceslist, slice_filter,'slice', return_fields)
581 return return_slice_list
586 def testbed_name (self): return "senslab2"
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())
599 'testbed':self.testbed_name(),
600 'geni_request_rspec_versions': request_rspec_versions,
601 'geni_ad_rspec_versions': ad_rspec_versions,
610 # Convert SFA fields to PLC fields for use when registering up updating
611 # registry record in the PLC database
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)
618 def sfa_fields_to_slab_fields(self, type, hrn, record):
620 def convert_ints(tmpdict, int_fields):
621 for field in int_fields:
623 tmpdict[field] = int(tmpdict[field])
626 #for field in record:
627 # slab_record[field] = record[field]
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)
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"])
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"
652 #elif type == "authority":
653 #slab_record["login_base"] = hrn_to_slab_login_base(hrn)
655 #if not "name" in slab_record:
656 #slab_record["name"] = hrn
658 #if not "abbreviated_name" in slab_record:
659 #slab_record["abbreviated_name"] = hrn
661 #if not "enabled" in slab_record:
662 #slab_record["enabled"] = True
664 #if not "is_public" in slab_record:
665 #slab_record["is_public"] = True
672 def AddSliceToNodes(self, slice_name, added_nodes, slice_user=None):
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
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.
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("_")
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)))
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
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)
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)
717 self.db.update_job( slice_name, job_id = 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')
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'))
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]
738 print>>sys.stderr, "\r\n \r\n AddSliceToNodes wrapper returns %s " %(output)
744 def DeleteSliceFromNodes(self, slice_name, deleted_nodes):
749 def fill_record_sfa_info(self, records):
751 def startswith(prefix, values):
752 return [value for value in values if value.startswith(prefix)]
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'])
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)
765 # get all pis from the sites we've encountered
766 # and store them in a dictionary keyed on site_id
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)
774 # we will need the pi's hrns also
775 person_ids.append(pi['person_id'])
777 # we also need to keep track of the sites these pis
779 for site_id in pi['site_ids']:
780 if site_id in site_pis:
781 site_pis[site_id].append(pi)
783 site_pis[site_id] = [pi]
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
789 # get the sfa records
791 existing_records = {}
792 all_records = dbsession.query(RegRecord).all()
793 for record in all_records:
794 existing_records[(record.type,record.pointer)] = record
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})
800 for p_id in person_ids:
801 person_list.append( existing_records.get(('user',p_id)))
803 print >>sys.stderr, " \r\r\n SLABDRIVER fill_record_sfa_info ERRRRRRRRRROR"
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)
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)
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:
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 ?
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)
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']
846 elif (type == "authority"):
848 record['operator'] = []
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
854 hrns = [person['hrn'] for person in persons[pointer]]
855 roles = slab_persons[pointer]['roles']
857 record['PI'].extend(hrns)
859 record['operator'].extend(hrns)
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
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
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)
876 def augment_records_with_testbed_info (self, sfa_records):
877 return self.fill_record_info (sfa_records)
879 def fill_record_info(self, records):
881 Given a SFA record, fill in the senslab specific and SFA specific
882 fields in the record.
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):
891 for record in parkour:
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()
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']])
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]
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)
915 record.update({'PI':[recuser.hrn],
916 'researcher': [recuser.hrn],
917 'name':record['hrn'],
918 'oar_job_id':recslice['oar_job_id'],
920 'person_ids':[recslice['record_id_user']]})
922 elif str(record['type']) == 'user':
923 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info USEEEEEEEEEERDESU!"
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
929 rec.update({'type':'slice','hrn':rec['slice_hrn']})
931 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info ADDING SLIC EINFO rec %s" %(rec)
933 print >>sys.stderr, "\r\n \t\t SLABDRIVER.PY fill_record_info OKrecords %s" %(records)
935 print >>sys.stderr, "\r\n \t\t SLABDRIVER fill_record_info EXCEPTION RECORDS : %s" %(records)
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"
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
950 #oldList = oldRecord.get(listName, [])
953 #newList = record.get(listName, [])
955 ## if the lists are the same, then we don't have to update anything
956 #if (oldList == newList):
959 ## build a list of the new person ids, by looking up each person to get
963 #records = table.find({'type': 'user', 'hrn': newList})
965 #newIdList.append(rec['pointer'])
967 ## build a list of the old person ids from the person_ids field
969 #oldIdList = oldRecord.get("person_ids", [])
970 #containerId = oldRecord.get_pointer()
972 ## if oldRecord==None, then we are doing a Register, instead of an
975 #containerId = record.get_pointer()
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)
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)
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":
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