fix error code checking in update
[sfa.git] / cmdline / sfi.py
index c7998bf..db716f5 100755 (executable)
@@ -12,6 +12,8 @@ from geni.util.credential import Credential
 from geni.util.geniclient import GeniClient, ServerException
 from geni.util.gid import create_uuid
 from geni.util.record import GeniRecord
+from geni.util.rspec import Rspec
+from types import StringTypes, ListType
 
 sfi_dir = os.path.expanduser("~/.sfi/")
 slicemgr = None
@@ -233,7 +235,8 @@ def create_cmd_parser(command, additional_cmdargs = None):
               "delete": "name",
               "reset": "name",
               "start": "name",
-              "stop": "name"
+              "stop": "name",
+              "delegate": "name"
              }
 
    if additional_cmdargs:
@@ -261,6 +264,12 @@ def create_cmd_parser(command, additional_cmdargs = None):
    if command in ("show", "list", "resources"):
       parser.add_option("-o", "--output", dest="file",
            help="output XML to file", metavar="FILE", default=None)
+   if command in ("delegate"):
+      parser.add_option("-u", "--user",
+        action="store_true", dest="delegate_user", default=False,
+        help="delegate user credential")
+      parser.add_option("-s", "--slice", dest="delegate_slice",
+        help="delegate slice credential", metavar="HRN", default=None)
    return parser
 
 def create_parser():
@@ -304,10 +313,10 @@ def main():
    (cmd_opts, cmd_args) = create_cmd_parser(command).parse_args(args[1:])
    verbose = options.verbose
    if verbose :
-      print "Resgistry %s, sm %s, dir %s, user %s, auth %s" % (options.registry, 
-                                            options.sm, 
+      print "Resgistry %s, sm %s, dir %s, user %s, auth %s" % (options.registry,
+                                            options.sm,
                                             options.dir,
-                                            options.user, 
+                                            options.user,
                                             options.auth)
       print "Command %s" %command
       if command in ("resources"):
@@ -358,6 +367,60 @@ def show(opts, args):
        save_records_to_file(opts.file, records)
    return
 
+def delegate(opts, args):
+   global registry
+   user_cred = get_user_cred()
+   if opts.delegate_user:
+       object_cred = user_cred
+   elif opts.delegate_slice:
+       object_cred = get_slice_cred(opts.delegate_slice)
+   else:
+       print "Must specify either --user or --slice <hrn>"
+       return
+
+   # the gid and hrn of the object we are delegating
+   object_gid = object_cred.get_gid_object()
+   object_hrn = object_gid.get_hrn()
+
+   if not object_cred.get_delegate():
+       print "Error: Object credential", object_hrn, "does not have delegate bit set"
+       return
+
+   records = registry.resolve(user_cred, args[0])
+   records = filter_records("user", records)
+
+   if not records:
+       print "Error: Didn't find a user record for", delegee_name
+       return
+
+   # the gid of the user who will be delegated too
+   delegee_gid = records[0].get_gid_object()
+   delegee_hrn = delegee_gid.get_hrn()
+
+   # the key and hrn of the user who will be delegating
+   user_key = Keypair(filename = get_key_file())
+   user_hrn = user_cred.get_gid_caller().get_hrn()
+
+   dcred = Credential(subject=object_hrn + " delegated to " + delegee_hrn)
+   dcred.set_gid_caller(delegee_gid)
+   dcred.set_gid_object(object_gid)
+   dcred.set_privileges(object_cred.get_privileges())
+   dcred.set_delegate(True)
+   dcred.set_pubkey(object_gid.get_pubkey())
+   dcred.set_issuer(user_key, user_hrn)
+   dcred.set_parent(object_cred)
+   dcred.encode()
+   dcred.sign()
+
+   if opts.delegate_user:
+       dest_fn = os.path.join(sfi_dir, get_leaf(delegee_hrn) + "_" + get_leaf(object_hrn) + ".cred")
+   elif opts.delegate_slice:
+       dest_fn = os.path_join(sfi_dir, get_leaf(delegee_hrn) + "_slice_" + get_leaf(object_hrn) + ".cred")
+
+   dcred.save_to_file(dest_fn, save_parents = True)
+
+   print "delegated credential for", object_hrn, "to", delegee_hrn, "and wrote to", dest_fn
+
 # removed named registry record
 #   - have to first retrieve the record to be removed
 def remove(opts, args):
@@ -379,7 +442,8 @@ def add(opts, args):
    #   broken and has no way for us to get the key back out of the gid)
    geni_info = record.get_geni_info()
    if "create_gid" in geni_info:
-       gid = registry.create_gid(auth_cred, geni_info["create_gid_hrn"], create_uuid(), geni_info["create_gid_key"])
+       key_string = geni_info["create_gid_key"].replace("|","\n") # XXX smbaker: the rspec kills newlines
+       gid = registry.create_gid(auth_cred, geni_info["create_gid_hrn"], create_uuid(), key_string)
        record.set_gid(gid)
 
        del geni_info["create_gid"]
@@ -403,11 +467,13 @@ def update(opts, args):
        try:
            cred = get_slice_cred(record.get_name())
        except ServerException, e:
-           if "PermissionError" in e.args[0]:
+           # XXX smbaker -- once we have better error return codes, update this
+           # to do something better than a string compare
+           if "Permission error" in e.args[0]:
                cred = get_auth_cred()
            else:
                raise
-   elif record.get_type() in ["sa", "ma", "node"]:
+   elif record.get_type() in ["authority"]:
        cred = get_auth_cred()
    else:
        raise "unknown record type" + record.get_type()
@@ -438,8 +504,8 @@ def update(opts, args):
 # list instantiated slices
 def slices(opts, args):
    global slicemgr
-   user_cred = get_user_cred() 
-   results = slicemgr.list_slices(user_cred)
+   user_cred = get_user_cred()
+   results = slicemgr.get_slices(user_cred)
    display_list(results)
    return
 
@@ -451,8 +517,9 @@ def resources(opts, args):
        result = slicemgr.get_resources(slice_cred, args[0])
    else:
        user_cred = get_user_cred()
-       result = slicemgr.get_resources(user_cred)   
-   display_rspec(result)
+       result = slicemgr.get_resources(user_cred)
+   format = opts.format      
+   display_rspec(result, format)
    if (opts.file is not None):
       save_rspec_to_file(opts.file, result)
    return
@@ -500,9 +567,33 @@ def reset(opts, args):
 #
 #
 
-def display_rspec(rspec):
-   print rspec
-   return
+def display_rspec(rspec, format = 'rspec'):
+    if format in ['dns']:
+        spec = Rspec()
+        spec.parseString(rspec)
+        hostnames = []
+        nodespecs = spec.getDictsByTagName('NodeSpec')
+        for nodespec in nodespecs:
+            if nodespec.has_key('name') and nodespec['name']:
+                if isinstance(nodespec['name'], ListType):
+                    hostnames.extend(nodespec['name'])
+                elif isinstance(nodespec['name'], StringTypes):
+                    hostnames.append(nodespec['name'])
+        result = hostnames
+    elif format in ['ip']:
+        spec = Rspec()
+        spec.parseString(rspec)
+        ips = []
+        ifspecs = spec.getDictsByTagName('IfSpec')
+        for ifspec in ifspecs:
+            if ifspec.has_key('addr') and ifspec['addr']:
+                ips.append(ifspec['addr'])
+        result = ips 
+    else:     
+        result = rspec
+
+    print result
+    return
 
 def display_list(results):
     for result in results: