3 # sfi -- slice-based facility interface
10 from types import StringTypes, ListType
11 from optparse import OptionParser
12 from sfa.trust.certificate import Keypair, Certificate
13 from sfa.trust.credential import Credential
14 from sfa.util.geniclient import GeniClient
15 from sfa.util.sfaticket import SfaTicket
16 from sfa.util.record import *
17 from sfa.util.misc import *
18 from sfa.util.rspec import RSpec
19 from sfa.util.xmlrpcprotocol import ServerException
20 import sfa.util.xmlrpcprotocol as xmlrpcprotocol
21 from sfa.util.config import Config
23 # utility methods here
25 def display_rspec(rspec, format = 'rspec'):
28 spec.parseString(rspec)
30 nodespecs = spec.getDictsByTagName('NodeSpec')
31 for nodespec in nodespecs:
32 if nodespec.has_key('name') and nodespec['name']:
33 if isinstance(nodespec['name'], ListType):
34 hostnames.extend(nodespec['name'])
35 elif isinstance(nodespec['name'], StringTypes):
36 hostnames.append(nodespec['name'])
38 elif format in ['ip']:
40 spec.parseString(rspec)
42 ifspecs = spec.getDictsByTagName('IfSpec')
43 for ifspec in ifspecs:
44 if ifspec.has_key('addr') and ifspec['addr']:
45 ips.append(ifspec['addr'])
53 def display_list(results):
54 for result in results:
58 def display_records(recordList, dump = False):
59 ''' Print all fields in the record'''
60 for record in recordList:
61 display_record(record, dump)
63 def display_record(record, dump = False):
67 info = record.getdict()
68 print "%s (%s)" % (info['hrn'], info['type'])
72 def filter_records(type, records):
74 for record in records:
75 if (record['type'] == type) or (type == "all"):
76 filtered_records.append(record)
77 return filtered_records
81 def save_rspec_to_file(rspec, filename):
82 if not filename.endswith(".rspec"):
83 filename = filename + ".rspec"
85 f = open(filename, 'w')
90 def save_records_to_file(filename, recordList):
92 for record in recordList:
94 save_record_to_file(filename + "." + str(index), record)
96 save_record_to_file(filename, record)
99 def save_record_to_file(filename, record):
100 if record['type'] in ['user']:
101 record = UserRecord(dict = record)
102 elif record['type'] in ['slice']:
103 record = SliceRecord(dict = record)
104 elif record['type'] in ['node']:
105 record = NodeRecord(dict = record)
106 elif record['type'] in ['authority', 'ma', 'sa']:
107 record = AuthorityRecord(dict = record)
109 record = GeniRecord(dict = record)
110 str = record.save_to_string()
111 file(filename, "w").write(str)
116 def load_record_from_file(filename):
117 str = file(filename, "r").read()
118 record = GeniRecord(string=str)
132 def create_cmd_parser(self,command, additional_cmdargs = None):
133 cmdargs = {"gid": "",
139 "aggregates": "[name]",
140 "registries": "[name]",
142 "resources": "[name]",
143 "create": "name rspec",
144 "get_trusted_certs": "cred",
145 "get_ticket": "name rspec",
146 "redeem_ticket": "ticket",
154 if additional_cmdargs:
155 cmdargs.update(additional_cmdargs)
157 if command not in cmdargs:
158 print "Invalid command\n"
160 for key in cmdargs.keys():
165 parser = OptionParser(usage="sfi [sfi_options] %s [options] %s" \
166 % (command, cmdargs[command]))
168 if command in ("resources"):
169 parser.add_option("-f", "--format", dest="format",type="choice",
170 help="display format ([xml]|dns|ip)",default="xml",
171 choices=("xml","dns","ip"))
172 parser.add_option("-a", "--aggregate", dest="aggregate",
173 default=None, help="aggregate hrn")
175 if command in ("create", "get_ticket"):
176 parser.add_option("-a", "--aggregate", dest="aggregate",default=None,
177 help="aggregate hrn")
179 if command in ("start", "stop", "reset", "delete", "slices"):
180 parser.add_option("-c", "--component", dest="component",default=None,
181 help="component hrn")
183 if command in ("list", "show", "remove"):
184 parser.add_option("-t", "--type", dest="type",type="choice",
185 help="type filter ([all]|user|slice|sa|ma|node|aggregate)",
186 choices=("all","user","slice","sa","ma","node","aggregate"),
189 if command in ("resources", "show", "list"):
190 parser.add_option("-o", "--output", dest="file",
191 help="output XML to file", metavar="FILE", default=None)
193 if command in ("show", "list"):
194 parser.add_option("-f", "--format", dest="format", type="choice",
195 help="display format ([text]|xml)",default="text",
196 choices=("text","xml"))
198 if command in ("delegate"):
199 parser.add_option("-u", "--user",
200 action="store_true", dest="delegate_user", default=False,
201 help="delegate user credential")
202 parser.add_option("-s", "--slice", dest="delegate_slice",
203 help="delegate slice credential", metavar="HRN", default=None)
207 def create_parser(self):
209 # Generate command line parser
210 parser = OptionParser(usage="sfi [options] command [command_options] [command_args]",
211 description="Commands: gid,list,show,remove,add,update,nodes,slices,resources,create,delete,start,stop,reset")
212 parser.add_option("-r", "--registry", dest="registry",
213 help="root registry", metavar="URL", default=None)
214 parser.add_option("-s", "--slicemgr", dest="sm",
215 help="slice manager", metavar="URL", default=None)
216 default_sfi_dir=os.path.expanduser("~/.sfi/")
217 parser.add_option("-d", "--dir", dest="sfi_dir",
218 help="config & working directory - default is " + default_sfi_dir,
219 metavar="PATH", default = default_sfi_dir)
220 parser.add_option("-u", "--user", dest="user",
221 help="user name", metavar="HRN", default=None)
222 parser.add_option("-a", "--auth", dest="auth",
223 help="authority name", metavar="HRN", default=None)
224 parser.add_option("-v", "--verbose",
225 action="store_true", dest="verbose", default=False,
227 parser.add_option("-p", "--protocol",
228 dest="protocol", default="xmlrpc",
229 help="RPC protocol (xmlrpc or soap)")
230 parser.add_option("-k", "--hashrequest",
231 action="store_true", dest="hashrequest", default=False,
232 help="Create a hash of the request that will be authenticated on the server")
233 parser.disable_interspersed_args()
239 # Establish Connection to SliceMgr and Registry Servers
241 def set_servers(self):
242 config_file = self.options.sfi_dir + os.sep + "sfi_config"
244 config = Config (config_file)
246 print "Failed to read configuration file",config_file
247 print "Make sure to remove the export clauses and to add quotes"
248 if not self.options.verbose:
249 print "Re-run with -v for more details"
251 traceback.print_exc()
256 if (self.options.sm is not None):
257 sm_url = self.options.sm
258 elif hasattr(config,"SFI_SM"):
259 sm_url = config.SFI_SM
261 print "You need to set e.g. SFI_SM='http://your.slicemanager.url:12347/' in %s"%config_file
265 if (self.options.registry is not None):
266 reg_url = self.options.registry
267 elif hasattr(config,"SFI_REGISTRY"):
268 reg_url = config.SFI_REGISTRY
270 print "You need to set e.g. SFI_REGISTRY='http://your.registry.url:12345/' in %s"%config_file
274 if (self.options.user is not None):
275 self.user = self.options.user
276 elif hasattr(config,"SFI_USER"):
277 self.user = config.SFI_USER
279 print "You need to set e.g. SFI_USER='plc.princeton.username' in %s"%config_file
283 if (self.options.auth is not None):
284 self.authority = self.options.auth
285 elif hasattr(config,"SFI_AUTH"):
286 self.authority = config.SFI_AUTH
288 print "You need to set e.g. SFI_AUTH='plc.princeton' in %s"%config_file
294 if self.options.verbose :
295 print "Contacting Slice Manager at:", sm_url
296 print "Contacting Registry at:", reg_url
298 # Get key and certificate
299 key_file = self.get_key_file()
300 cert_file = self.get_cert_file(key_file)
301 self.key = Keypair(filename=key_file)
302 self.key_file = key_file
303 self.cert_file = cert_file
304 self.cert = Certificate(filename=cert_file)
305 # Establish connection to server(s)
306 #self.slicemgr = GeniClient(sm_url, key_file, cert_file, self.options.protocol)
307 #self.registry = GeniClient(reg_url, key_file, cert_file, self.options.protocol)
308 self.registry = xmlrpcprotocol.get_server(reg_url, key_file, cert_file)
309 self.slicemgr = xmlrpcprotocol.get_server(sm_url, key_file, cert_file)
313 # Get various credential and spec files
315 # Establishes limiting conventions
316 # - conflates MAs and SAs
317 # - assumes last token in slice name is unique
319 # Bootstraps credentials
320 # - bootstrap user credential from self-signed certificate
321 # - bootstrap authority credential from user credential
322 # - bootstrap slice credential from user credential
326 def get_key_file(self):
327 file=os.path.join(self.options.sfi_dir, self.user.replace(self.authority + '.', '') + ".pkey")
328 #file = os.path.join(self.options.sfi_dir, get_leaf(self.user) + ".pkey")
329 if (os.path.isfile(file)):
332 print "Key file", file, "does not exist"
336 def get_cert_file(self,key_file):
338 #file = os.path.join(self.options.sfi_dir, get_leaf(self.user) + ".cert")
339 file=os.path.join(self.options.sfi_dir, self.user.replace(self.authority + '.', '') + ".cert")
340 if (os.path.isfile(file)):
343 k = Keypair(filename = key_file)
344 cert = Certificate(subject=self.user)
346 cert.set_issuer(k, self.user)
348 if self.options.verbose :
349 print "Writing self-signed certificate to", file
350 cert.save_to_file(file)
354 #file = os.path.join(self.options.sfi_dir, get_leaf(self.user) + ".gid")
355 file=os.path.join(self.options.sfi_dir, self.user.replace(self.authority + '.', '') + ".gid")
356 if (os.path.isfile(file)):
357 gid = GID(filename=file)
360 cert_str = self.cert.save_to_string(save_parents=True)
363 request_hash = self.key.compute_hash([cert_str, self.user, "user"])
364 gid_str = self.registry.get_gid(cert_str, self.user, "user", request_hash)
365 gid = GID(string=gid_str)
366 if self.options.verbose:
367 print "Writing user gid to", file
368 gid.save_to_file(file, save_parents=True)
371 def get_user_cred(self):
372 #file = os.path.join(self.options.sfi_dir, get_leaf(self.user) + ".cred")
373 file=os.path.join(self.options.sfi_dir, self.user.replace(self.authority + '.', '') + ".cred")
374 if (os.path.isfile(file)):
375 user_cred = Credential(filename=file)
378 # bootstrap user credential
379 cert_string = self.cert.save_to_string(save_parents=True)
382 request_hash = self.key.compute_hash([cert_string, "user", self.user])
383 user_name=self.user.replace(self.authority+".", '')
384 if user_name.count(".") > 0:
385 user_name = user_name.replace(".", '_')
386 self.user=self.authority + "." + user_name
387 user_cred = self.registry.get_self_credential(cert_string, "user", self.user, request_hash)
389 cred = Credential(string=user_cred)
390 cred.save_to_file(file, save_parents=True)
391 if self.options.verbose:
392 print "Writing user credential to", file
395 print "Failed to get user credential"
398 def get_auth_cred(self):
399 if not self.authority:
400 print "no authority specified. Use -a or set SF_AUTH"
403 file = os.path.join(self.options.sfi_dir, get_leaf("authority") +".cred")
404 if (os.path.isfile(file)):
405 auth_cred = Credential(filename=file)
408 # bootstrap authority credential from user credential
409 user_cred = self.get_user_cred().save_to_string(save_parents=True)
412 request_hash = self.key.compute_hash([user_cred, "authority", self.authority])
413 auth_cred = self.registry.get_credential(user_cred, "authority", self.authority, request_hash)
415 cred = Credential(string=auth_cred)
416 cred.save_to_file(file, save_parents=True)
417 if self.options.verbose:
418 print "Writing authority credential to", file
421 print "Failed to get authority credential"
424 def get_slice_cred(self,name):
425 file = os.path.join(self.options.sfi_dir, "slice_" + get_leaf(name) + ".cred")
426 if (os.path.isfile(file)):
427 slice_cred = Credential(filename=file)
430 # bootstrap slice credential from user credential
431 user_cred = self.get_user_cred().save_to_string(save_parents=True)
432 arg_list = [user_cred, "slice", name]
435 request_hash = self.key.compute_hash(arg_list)
436 slice_cred_str = self.registry.get_credential(user_cred, "slice", name, request_hash)
438 slice_cred = Credential(string=slice_cred_str)
439 slice_cred.save_to_file(file, save_parents=True)
440 if self.options.verbose:
441 print "Writing slice credential to", file
444 print "Failed to get slice credential"
447 def delegate_cred(self,cred, hrn, type = 'authority'):
448 # the gid and hrn of the object we are delegating
449 object_gid = cred.get_gid_object()
450 object_hrn = object_gid.get_hrn()
451 cred.set_delegate(True)
452 if not cred.get_delegate():
453 raise Exception, "Error: Object credential %(object_hrn)s does not have delegate bit set" % locals()
456 records = self.registry.resolve(cred, hrn)
457 records = filter_records(type, records)
460 raise Exception, "Error: Didn't find a %(type)s record for %(hrn)s" % locals()
462 # the gid of the user who will be delegated too
463 delegee_gid = records[0].get_gid_object()
464 delegee_hrn = delegee_gid.get_hrn()
466 # the key and hrn of the user who will be delegating
467 user_key = Keypair(filename = self.get_key_file())
468 user_hrn = cred.get_gid_caller().get_hrn()
470 dcred = Credential(subject=object_hrn + " delegated to " + delegee_hrn)
471 dcred.set_gid_caller(delegee_gid)
472 dcred.set_gid_object(object_gid)
473 dcred.set_privileges(cred.get_privileges())
474 dcred.set_delegate(True)
475 dcred.set_pubkey(object_gid.get_pubkey())
476 dcred.set_issuer(user_key, user_hrn)
477 dcred.set_parent(cred)
483 def get_rspec_file(self,rspec):
484 if (os.path.isabs(rspec)):
487 file = os.path.join(self.options.sfi_dir, rspec)
488 if (os.path.isfile(file)):
491 print "No such rspec file", rspec
494 def get_record_file(self,record):
495 if (os.path.isabs(record)):
498 file = os.path.join(self.options.sfi_dir, record)
499 if (os.path.isfile(file)):
502 print "No such registry record file", record
505 def load_publickey_string(self,fn):
507 key_string = f.read()
509 # if the filename is a private key file, then extract the public key
510 if "PRIVATE KEY" in key_string:
511 outfn = tempfile.mktemp()
512 cmd = "openssl rsa -in " + fn + " -pubout -outform PEM -out " + outfn
515 key_string = f.read()
520 def get_component_server_from_hrn(self, hrn):
521 # direct connection to the nodes component manager interface
522 user_cred = self.get_user_cred().save_to_string(save_parents=True)
523 request_hash = self.key.compute_hash([user_cred, hrn])
524 records = self.registry.resolve(user_cred, hrn, request_hash)
525 records = filter_records('node', records)
527 print "No such component:", opts.component
530 url = "https://%s:%s" % (record['hostname'], cm_port)
531 return xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
534 # Following functions implement the commands
536 # Registry-related commands
539 def dispatch(self,command, cmd_opts, cmd_args):
540 getattr(self,command)(cmd_opts, cmd_args)
542 def gid(self, opts, args):
544 print "GID: %s" % (gid.save_to_string(save_parents=True))
547 # list entires in named authority registry
548 def list(self,opts, args):
549 user_cred = self.get_user_cred().save_to_string(save_parents=True)
553 request_hash = self.key.compute_hash([user_cred, hrn])
555 list = self.registry.list(user_cred, hrn, request_hash)
557 raise Exception, "Not enough parameters for the 'list' command"
559 # filter on person, slice, site, node, etc.
560 # THis really should be in the self.filter_records funct def comment...
561 list = filter_records(opts.type, list)
563 print "%s (%s)" % (record['hrn'], record['type'])
566 if not file.startswith(os.sep):
567 file = os.path.join(self.options.sfi_dir, file)
568 save_records_to_file(file, list)
571 # show named registry record
572 def show(self,opts, args):
573 user_cred = self.get_user_cred().save_to_string(save_parents=True)
577 request_hash = self.key.compute_hash([user_cred, hrn])
578 records = self.registry.resolve(user_cred, hrn, request_hash)
579 records = filter_records(opts.type, records)
581 print "No record of type", opts.type
582 for record in records:
583 if record['type'] in ['user']:
584 record = UserRecord(dict = record)
585 elif record['type'] in ['slice']:
586 record = SliceRecord(dict = record)
587 elif record['type'] in ['node']:
588 record = NodeRecord(dict = record)
589 elif record['type'] in ['authority', 'ma', 'sa']:
590 record = AuthorityRecord(dict = record)
592 record = GeniRecord(dict = record)
593 if (opts.format=="text"):
596 print record.save_to_string()
600 if not file.startswith(os.sep):
601 file = os.path.join(self.options.sfi_dir, file)
602 save_records_to_file(file, records)
605 def delegate(self,opts, args):
606 user_cred = self.get_user_cred()
607 if opts.delegate_user:
608 object_cred = user_cred
609 elif opts.delegate_slice:
610 object_cred = self.get_slice_cred(opts.delegate_slice)
612 print "Must specify either --user or --slice <hrn>"
615 # the gid and hrn of the object we are delegating
616 object_gid = object_cred.get_gid_object()
617 object_hrn = object_gid.get_hrn()
619 if not object_cred.get_delegate():
620 print "Error: Object credential", object_hrn, "does not have delegate bit set"
623 records = self.registry.resolve(user_cred, args[0])
624 records = filter_records("user", records)
627 print "Error: Didn't find a user record for", args[0]
630 # the gid of the user who will be delegated too
631 delegee_gid = records[0].get_gid_object()
632 delegee_hrn = delegee_gid.get_hrn()
634 # the key and hrn of the user who will be delegating
635 user_key = Keypair(filename = self.get_key_file())
636 user_hrn = user_cred.get_gid_caller().get_hrn()
638 dcred = Credential(subject=object_hrn + " delegated to " + delegee_hrn)
639 dcred.set_gid_caller(delegee_gid)
640 dcred.set_gid_object(object_gid)
641 dcred.set_privileges(object_cred.get_privileges())
642 dcred.set_delegate(True)
643 dcred.set_pubkey(object_gid.get_pubkey())
644 dcred.set_issuer(user_key, user_hrn)
645 dcred.set_parent(object_cred)
649 if opts.delegate_user:
650 dest_fn = os.path.join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_"
651 + get_leaf(object_hrn) + ".cred")
652 elif opts.delegate_slice:
653 dest_fn = os.path_join(self.options.sfi_dir, get_leaf(delegee_hrn) + "_slice_"
654 + get_leaf(object_hrn) + ".cred")
656 dcred.save_to_file(dest_fn, save_parents = True)
658 print "delegated credential for", object_hrn, "to", delegee_hrn, "and wrote to", dest_fn
660 # removed named registry record
661 # - have to first retrieve the record to be removed
662 def remove(self,opts, args):
663 auth_cred = self.get_auth_cred().save_to_string(save_parents=True)
670 arg_list = [auth_cred, type, hrn]
671 request_hash = self.key.compute_hash(arg_list)
672 return self.registry.remove(auth_cred, type, hrn, request_hash)
674 # add named registry record
675 def add(self,opts, args):
676 auth_cred = self.get_auth_cred().save_to_string(save_parents=True)
677 record_filepath = args[0]
678 rec_file = self.get_record_file(record_filepath)
679 record = load_record_from_file(rec_file).as_dict()
682 arg_list = [auth_cred]
683 request_hash = self.key.compute_hash(arg_list)
684 return self.registry.register(auth_cred, record, request_hash)
686 # update named registry entry
687 def update(self,opts, args):
688 user_cred = self.get_user_cred()
689 rec_file = self.get_record_file(args[0])
690 record = load_record_from_file(rec_file)
691 if record['type'] == "user":
692 if record.get_name() == user_cred.get_gid_object().get_hrn():
693 cred = user_cred.save_to_string(save_parents=True)
695 cred = self.get_auth_cred().save_to_string(save_parents=True)
696 elif record['type'] in ["slice"]:
698 cred = self.get_slice_cred(record.get_name()).save_to_string(save_parents=True)
699 except ServerException, e:
700 # XXX smbaker -- once we have better error return codes, update this
701 # to do something better than a string compare
702 if "Permission error" in e.args[0]:
703 cred = self.get_auth_cred().save_to_string(save_parents=True)
706 elif record.get_type() in ["authority"]:
707 cred = self.get_auth_cred().save_to_string(save_parents=True)
708 elif record.get_type() == 'node':
709 cred = self.get_auth_cred().save_to_string(save_parents=True)
711 raise "unknown record type" + record.get_type()
712 record = record.as_dict()
716 request_hash = self.key.compute_hash(arg_list)
717 return self.registry.update(cred, record, request_hash)
719 def get_trusted_certs(self, opts, args):
721 return the trusted certs at this interface
723 trusted_certs = self.registry.get_trusted_certs()
724 for trusted_cert in trusted_certs:
725 cert = Certificate(string=trusted_cert)
726 print cert.get_subject()
729 def aggregates(self, opts, args):
731 return a list of details about known aggregates
733 user_cred = self.get_user_cred().save_to_string(save_parents=True)
739 arg_list = [user_cred, hrn]
740 request_hash = self.key.compute_hash(arg_list)
741 result = self.registry.get_aggregates(user_cred, hrn, request_hash)
745 def registries(self, opts, args):
747 return a list of details about known registries
749 user_cred = self.get_user_cred().save_to_string(save_parents=True)
755 arg_list = [user_cred, hrn]
756 request_hash = self.key.compute_hash(arg_list)
757 result = self.registry.get_registries(user_cred, hrn, request_hash)
763 # Slice-related commands
766 # list available nodes -- use 'resources' w/ no argument instead
768 # list instantiated slices
769 def slices(self,opts, args):
770 user_cred = self.get_user_cred().save_to_string(save_parents=True)
773 arg_list = [user_cred]
774 request_hash = self.key.compute_hash(arg_list)
776 server = self.slicemgr
777 # direct connection to the nodes component manager interface
779 server = self.get_component_server_from_hrn(opts.component)
780 results = server.get_slices(user_cred, request_hash)
781 display_list(results)
784 # show rspec for named slice
785 def resources(self,opts, args):
786 user_cred = self.get_user_cred().save_to_string(save_parents=True)
787 server = self.slicemgr
789 agg_hrn = opts.aggregate
790 arg_list = [user_cred, agg_hrn]
791 request_hash = self.key.compute_hash(arg_list)
792 aggregates = self.registry.get_aggregates(user_cred, agg_hrn, request_hash)
794 raise Exception, "No such aggregate %s" % agg_hrn
795 aggregate = aggregates[0]
796 url = "http://%s:%s" % (aggregate['addr'], aggregate['port'])
797 server = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
799 cred = self.get_slice_cred(args[0]).save_to_string(save_parents=True)
807 arg_list = [cred, hrn]
808 request_hash = self.key.compute_hash(arg_list)
809 result = server.get_resources(cred, hrn, request_hash)
812 display_rspec(result, format)
813 if (opts.file is not None):
815 if not file.startswith(os.sep):
816 file = os.path.join(self.options.sfi_dir, file)
817 save_rspec_to_file(result, file)
820 # created named slice with given rspec
821 def create(self,opts, args):
823 user_cred = self.get_user_cred()
824 slice_cred = self.get_slice_cred(slice_hrn).save_to_string(save_parents=True)
825 rspec_file = self.get_rspec_file(args[1])
826 rspec=open(rspec_file).read()
827 server = self.slicemgr
829 aggregates = self.registry.get_aggregates(user_cred, opts.aggregate)
831 raise Exception, "No such aggregate %s" % opts.aggregate
832 aggregate = aggregates[0]
833 url = "http://%s:%s" % (aggregate['addr'], aggregate['port'])
834 server = GeniClient(url, self.key_file, self.cert_file, self.options.protocol)
837 arg_list = [slice_cred, slice_hrn, rspec]
838 request_hash = self.key.compute_hash(arg_list)
839 return server.create_slice(slice_cred, slice_hrn, rspec, request_hash)
841 # get a ticket for the specified slice
842 def get_ticket(self, opts, args):
843 slice_hrn, rspec_path = args[0], args[1]
844 user_cred = self.get_user_cred()
845 slice_cred = self.get_slice_cred(slice_hrn).save_to_string(save_parents=True)
846 rspec_file = self.get_rspec_file(rspec_path)
847 rspec=open(rspec_file).read()
848 server = self.slicemgr
850 aggregates = self.registry.get_aggregates(user_cred, opts.aggregate)
852 raise Exception, "No such aggregate %s" % opts.aggregate
853 aggregate = aggregates[0]
854 url = "http://%s:%s" % (aggregate['addr'], aggregate['port'])
855 server = GeniClient(url, self.key_file, self.cert_file, self.options.protocol)
858 arg_list = [slice_cred, slice_hrn, rspec]
859 request_hash = self.key.compute_hash(arg_list)
860 ticket_string = server.get_ticket(slice_cred, slice_hrn, rspec, request_hash)
861 file = os.path.join(self.options.sfi_dir, get_leaf(slice_hrn) + ".ticket")
862 print "writing ticket to ", file
863 ticket = SfaTicket(string=ticket_string)
864 ticket.save_to_file(filename=file, save_parents=True)
866 def redeem_ticket(self, opts, args):
867 ticket_file = args[0]
869 # get slice hrn from the ticket
870 # use this to get the right slice credential
871 ticket = SfaTicket(filename=ticket_file)
873 slice_hrn = ticket.attributes['slivers'][0]['hrn']
874 user_cred = self.get_user_cred()
875 slice_cred = self.get_slice_cred(slice_hrn).save_to_string(save_parents=True)
877 # get a list node hostnames from the nodespecs in the rspec
879 rspec.parseString(ticket.rspec)
880 nodespecs = rspec.getDictsByTagName('NodeSpec')
881 hostnames = [nodespec['name'] for nodespec in nodespecs]
883 # create an xmlrpc connection to the component manager at each of these
884 # components and gall redeem_ticket
886 for hostname in hostnames:
889 url = "https://%(hostname)s:%(cm_port)s" % locals()
890 print "Calling get_ticket at %(url)s " % locals(),
891 cm = xmlrpcprotocol.get_server(url, self.key_file, self.cert_file)
892 cm.redeem_ticket(slice_cred, ticket.save_to_string(save_parents=True))
894 except socket.gaierror:
896 print "Componet Manager not accepting requests"
898 print "Failed:", e.message
903 def delete(self,opts, args):
905 server = self.slicemgr
906 # direct connection to the nodes component manager interface
908 server = self.get_component_server_from_hrn(opts.component)
910 slice_cred = self.get_slice_cred(slice_hrn).save_to_string(save_parents=True)
913 arg_list = [slice_cred, slice_hrn]
914 request_hash = self.key.compute_hash(arg_list)
915 return server.delete_slice(slice_cred, slice_hrn, request_hash)
918 def start(self,opts, args):
920 server = self.slicemgr
921 # direct connection to the nodes component manager interface
923 server = self.get_component_server_from_hrn(opts.component)
925 slice_cred = self.get_slice_cred(args[0]).save_to_string(save_parents=True)
928 arg_list = [slice_cred, slice_hrn]
929 request_hash = self.key.compute_hash(arg_list)
930 return server.start_slice(slice_cred, slice_hrn, request_hash)
933 def stop(self,opts, args):
935 server = self.slicemgr
936 # direct connection to the nodes component manager interface
938 server = self.get_component_server_from_hrn(opts.component)
940 slice_cred = self.get_slice_cred(args[0]).save_to_string(save_parents=True)
943 arg_list = [slice_cred, slice_hrn]
944 request_hash = self.key.compute_hash(arg_list)
945 return server.stop_slice(slice_cred, slice_hrn, request_hash)
948 def reset(self,opts, args):
950 server = self.slicemgr
951 # direct connection to the nodes component manager interface
953 server = self.get_component_server_from_hrn(opts.component)
954 slice_cred = self.get_slice_cred(args[0]).save_to_string(save_parents=True)
957 arg_list = [slice_cred, slice_hrn]
958 request_hash = self.key.compute_hash(arg_list)
959 return server.reset_slice(slice_cred, slice_hrn, request_hash)
962 # Main: parse arguments and dispatch to command
965 parser = self.create_parser()
966 (options, args) = parser.parse_args()
967 self.options = options
969 if options.hashrequest:
970 self.hashrequest=True
973 print "No command given. Use -h for help."
977 (cmd_opts, cmd_args) = self.create_cmd_parser(command).parse_args(args[1:])
978 if self.options.verbose :
979 print "Registry %s, sm %s, dir %s, user %s, auth %s" % (options.registry, options.sm,
980 options.sfi_dir, options.user,
982 print "Command %s" %command
983 if command in ("resources"):
984 print "resources cmd_opts %s" %cmd_opts.format
985 elif command in ("list","show","remove"):
986 print "cmd_opts.type %s" %cmd_opts.type
987 print "cmd_args %s" %cmd_args
992 self.dispatch(command, cmd_opts, cmd_args)
995 print "Command not found:", command
1000 if __name__=="__main__":