source: fedd/fedd_create.py @ 66879a0

compt_changesinfo-ops
Last change on this file since 66879a0 was 66879a0, checked in by Ted Faber <faber@…>, 13 years ago

Add debugging messages to catch delegation failures because the cert is
not a fedid.

  • Property mode set to 100755
File size: 10.4 KB
RevLine 
[2e46f35]1#!/usr/bin/env python
[d743d60]2
[6e63513]3import sys, os
[b10375f]4import re
[6e63513]5import subprocess
[d743d60]6
[c573278]7import ABAC
8
[990b746]9from string import join, ascii_letters
10from random import choice
[6e63513]11
[e83f2f2]12from federation.proof import proof
[6e63513]13from federation.fedid import fedid, generate_fedid
[d743d60]14from federation.remote_service import service_caller
15from federation.client_lib import client_opts, exit_with_fault, RPCException, \
[6e63513]16        wrangle_standard_options, do_rpc, get_experiment_names, save_certfile,\
[e83f2f2]17        get_abac_certs, log_authentication
[c573278]18from federation.util import abac_split_cert, abac_context_to_creds
[a7c0bcb]19from federation import topdl
20
21from xml.parsers.expat import ExpatError
[d743d60]22
23class fedd_create_opts(client_opts):
24    """
25    Extra options that create needs.  Help entries should explain them.
26    """
27    def __init__(self):
28        client_opts.__init__(self)
29        self.add_option("--experiment_cert", dest="out_certfile",
[62f3dd9]30                action="callback", callback=self.expand_file,
[d743d60]31                type="string", help="output certificate file")
32        self.add_option("--experiment_name", dest="exp_name",
33                type="string", help="Suggested experiment name")
[62f3dd9]34        self.add_option("--file", dest="file", action="callback",
35                callback=self.expand_file, type="str",
[d743d60]36                help="experiment description file")
37        self.add_option("--project", action="store", dest="project", 
38                type="string",
39                help="Project to export from master")
40        self.add_option("--master", dest="master",
41                help="Master testbed in the federation (pseudo project export)")
42        self.add_option("--service", dest="service", action="append",
43                type="string", default=[],
44                help="Service description name:exporters:importers:attrs")
[fd07c48]45        self.add_option("--map", dest="map", action="append",
46                type="string", default=[],
47                help="Explicit map from testbed label to URI - " + \
48                        "deter:https://users.isi.deterlab/net:13232")
[353db8c]49        self.add_option('--gen_cert', action='store_true', dest='gen_cert',
50                default=False,
51                help='generate a cert to which to delegate rights')
52        self.add_option('--delegate', action='store_true', dest='generate',
53                help='Delegate rights to a generated cert (default)')
54        self.add_option('--no-delegate', action='store_true', dest='generate',
55                help='Do not delegate rights to a generated cert')
56
[6e63513]57        self.set_defaults(delegate=True)
[d743d60]58
59def parse_service(svc):
60    """
61    Pasre a service entry into a hash representing a service entry in a
62    message.  The format is:
63        svc_name:exporter(s):importer(s):attr=val,attr=val
64    The svc_name is teh service name, exporter is the exporting testbeds
65    (comma-separated) importer is the importing testbeds (if any) and the rest
66    are attr=val pairs that will become attributes of the service.  These
67    include parameters and other such stuff.
68    """
69
70    terms = svc.split(':')
71    svcd = { }
72    if len(terms) < 2 or len(terms[0]) == 0 or len(terms[1]) == 0:
73        sys.exit("Bad service description '%s': Not enough terms" % svc)
74   
75    svcd['name'] = terms[0]
76    svcd['export'] = terms[1].split(",")
77    if len(terms) > 2 and len(terms[2]) > 0:
78        svcd['import'] = terms[2].split(",")
79    if len(terms) > 3 and len(terms[3]) > 0:
80        svcd['fedAttr'] = [ ]
[0de1b94]81        for t in terms[3].split(";"):
[d743d60]82            i = t.find("=")
83            if i != -1 :
84                svcd['fedAttr'].append(
85                        {'attribute': t[0:i], 'value': t[i+1:]})
86            else:
87                sys.exit("Bad service attribute '%s': no equals sign" % t)
88    return svcd
89
90def project_export_service(master, project):
91    """
92    Output the dict representation of a project_export service for this project
93    and master.
94    """
95    return {
96            'name': 'project_export', 
97            'export': [master], 
98            'importall': True,
99            'fedAttr': [ 
100                { 'attribute': 'project', 'value': project },
101                ],
102            }
103
[353db8c]104def delegate(fedid, cert, dir, name=None, debug=False, 
105        creddy='/usr/local/bin/creddy'):
106    '''
107    Make the creddy call to create an attribute delegating rights to the new
108    experiment.  The cert parameter points to a conventional cert & key combo,
109    which we split out into tempfiles, which we delete on return.  The return
110    value if the filename in which the certificate was stored.
111    '''
112    certfile = keyfile = None
113    expid = "%s" % fedid
114
115    # Trim the "fedid:"
116    if expid.startswith("fedid:"): expid = expid[6:]
117
118    try:
[6e63513]119        keyfile, certfile = abac_split_cert(cert)
[353db8c]120
121        rv = 0
[c573278]122        if name: 
123            fn ='%s/%s_attr.der' % (dir, name) 
124            id_fn = '%s/%s_id.pem' % (dir, name)
125        else: 
126            fn = '%s/%s_attr.der' % (dir, expid)
127            id_fn = '%s/%s_id.pem' % (dir, expid)
[353db8c]128
129        cmd = [creddy, '--attribute', '--issuer=%s' % certfile, 
130                '--key=%s' % keyfile,
131                '--role=acting_for', '--subject-id=%s' % expid, 
132                '--out=%s' % fn ]
[6e63513]133        if not debug:
134            if subprocess.call(cmd) != 0:
[66879a0]135                print >>sys.stderr, "Cannot delegate, things may fail"
[c573278]136                return []
[353db8c]137        else:
[6e63513]138            print join(cmd)
[c573278]139            return []
140
141        context = ABAC.Context()
142        if context.load_id_file(certfile) != ABAC.ABAC_CERT_SUCCESS or \
143                context.load_attribute_file(fn) != ABAC.ABAC_CERT_SUCCESS:
[66879a0]144            print >>sys.stderr, "Cannot load delegation into ABAC. " + \
145                    "Did you run cert_to_fedid.py on your X.509 cert?"
[c573278]146            return []
147        ids, attrs = abac_context_to_creds(context)
148
149        return ids + attrs
[6e63513]150
151
[353db8c]152    finally:
153        if keyfile: os.unlink(keyfile)
154        if certfile: os.unlink(certfile)
155
[6e63513]156
[d743d60]157# Main line
[b10375f]158service_re = re.compile('^\\s*#\\s*SERVICE:\\s*([\\S]+)')
[d743d60]159parser = fedd_create_opts()
160(opts, args) = parser.parse_args()
161
[cd60510]162svcs = []
[353db8c]163# Option processing
[a0c2866]164try:
165    cert, fid, url = wrangle_standard_options(opts)
166except RuntimeError, e:
167    sys.exit("%s" %e)
[d743d60]168
169if opts.file:
[a7c0bcb]170
171    top = None
172    # Try the file as a topdl description
[d743d60]173    try:
[a7c0bcb]174        top = topdl.topology_from_xml(filename=opts.file, top='experiment')
[d743d60]175    except EnvironmentError:
[a7c0bcb]176        # Can't read the file, fail now
[d743d60]177        sys.exit("Cannot read description file (%s)" %opts.file)
[a7c0bcb]178    except ExpatError:
179        # The file is not topdl, fall and assume it's ns2
180        pass
181
182    if top is None:
183        try:
184            lines = [ line for line in open(opts.file, 'r')]
185            exp_desc = "".join(lines)
186            # Parse all the strings that we can pull out of the file using the
187            # service_re.
188            svcs.extend([parse_service(service_re.match(l).group(1)) \
189                    for l in lines if service_re.match(l)])
190        except EnvironmentError:
191            sys.exit("Cannot read description file (%s)" %opts.file)
[d743d60]192else:
193    sys.exit("Must specify an experiment description (--file)")
194
195out_certfile = opts.out_certfile
196
[353db8c]197# If there is no abac directory in which to store a delegated credential, don't
198# delegate.
199if not opts.abac_dir and opts.delegate:
200    opts.delegate = False
201
202# Load ABAC certs
203if opts.abac_dir:
204    try:
205        acerts = get_abac_certs(opts.abac_dir)
206    except EnvironmentError, e:
207        sys.exit('%s: %s' % (e.filename, e.strerror))
[725c55d]208else:
209    acerts = None
[353db8c]210
[d743d60]211# Fill in services
212if opts.master and opts.project:
213    svcs.append(project_export_service(opts.master, opts.project))
214svcs.extend([ parse_service(s) for s in opts.service])
[353db8c]215
[fd07c48]216# Create a testbed map if one is specified
217tbmap = { }
218for m in opts.map:
219    i = m.find(":")
220    if i != -1: tbmap[m[0:i]] = m[i+1:]
221    else: sys.exit("Bad mapping argument: %s" %m )
222
223
[d743d60]224if not svcs:
225    print >>sys.stderr, "Warning:Neither master/project nor services requested"
226
[353db8c]227# Construct the New experiment request
[d743d60]228msg = { }
229
[353db8c]230
231# Generate a certificate if requested and put it into the message
232if opts.gen_cert:
233    expid, expcert = generate_fedid(opts.exp_name or 'dummy')
234    msg['experimentAccess'] = { 'X509': expcert }
235else:
236    expid = expcert = None
237
[d743d60]238if opts.exp_name:
239    msg['experimentID'] = { 'localname': opts.exp_name }
240
[353db8c]241if acerts:
242    msg['credential'] = acerts
243
[990b746]244# ZSI will not properly construct an empty message.  If nothing has been added
245# to msg, pick a random localname to ensure the message is created
246if not msg:
247    msg['experimentID'] = { 
248            'localname': join([choice(ascii_letters) for i in range(0,8)],""),
249            }
250
251
[d743d60]252if opts.debug > 1: print >>sys.stderr, msg
253
[353db8c]254# The New call
[d743d60]255try:
256    resp_dict = do_rpc(msg, 
[5d854e1]257            url, opts.transport, cert, opts.trusted, 
[d743d60]258            serialize_only=opts.serialize_only,
259            tracefile=opts.tracefile,
260            caller=service_caller('New'), responseBody="NewResponseBody")
261except RPCException, e:
[e83f2f2]262    exit_with_fault(e, 'New (create)', opts)
[d743d60]263except RuntimeError, e:
264    sys.exit("Error processing RPC: %s" % e)
265
266if opts.debug > 1: print >>sys.stderr, resp_dict
267
[e83f2f2]268proof = proof.from_dict(resp_dict.get('proof', {}))
269if proof and opts.auth_log:
270    log_authentication(opts.auth_log, 'New (create)', 'succeeded', proof)
[353db8c]271# Save the experiment ID certificate if we need it
[d743d60]272try:
273    save_certfile(opts.out_certfile, resp_dict.get('experimentAccess', None))
274except EnvironmentError, e:
275    sys.exit('Could not write to %s: %s' %  (opts.out_certfile, e))
276
277e_fedid, e_local = get_experiment_names(resp_dict.get('experimentID', None))
278if not e_fedid and not e_local and opts.serialize_only:
279    e_local = "serialize"
280
[353db8c]281# If delegation is requested and we have a target, make the delegation, and add
282# the credential to acerts.
283if e_fedid and opts.delegate:
[6e63513]284    try:
[c573278]285        creds = delegate(e_fedid, cert, opts.abac_dir, name=opts.exp_name)
286        if creds:
287            acerts.extend(creds)
[6e63513]288    except EnvironmentError, e:
289        sys.exit("Cannot delegate rights %s: %s" % (e.filename, e.strerror));
[353db8c]290
291# Construct the Create message
[a7c0bcb]292if top: 
293    msg = { 'experimentdescription' : { 'topdldescription': top.to_dict() }, }
294else: 
295    msg = { 'experimentdescription': { 'ns2description': exp_desc }, }
[d743d60]296
297if svcs:
298    msg['service'] = svcs
299
300if e_fedid:
301    msg['experimentID'] = { 'fedid': e_fedid }
302elif e_local:
303    msg['experimentID'] = { 'localname': e_local }
304else:
305    sys.exit("New did not return an experiment ID??")
306
[353db8c]307if acerts:
308    msg['credential'] = acerts
309
[fd07c48]310if tbmap:
311    msg['testbedmap'] = [ { 'testbed': t, 'uri': u } for t, u in tbmap.items() ]
312
[d743d60]313if opts.debug > 1: print >>sys.stderr, msg
314
[353db8c]315# make the call
[d743d60]316try:
317    resp_dict = do_rpc(msg, 
[5d854e1]318            url, opts.transport, cert, opts.trusted, 
[d743d60]319            serialize_only=opts.serialize_only,
320            tracefile=opts.tracefile,
[e83f2f2]321            caller=service_caller('Create', max_retries=1), responseBody="CreateResponseBody")
[d743d60]322except RPCException, e:
[e83f2f2]323    exit_with_fault(e, 'Create', opts)
[d743d60]324except RuntimeError, e:
325    sys.exit("Error processing RPC: %s" % e)
326
327if opts.debug > 1: print >>sys.stderr, resp_dict
328
[353db8c]329# output
[d743d60]330e_fedid, e_local = get_experiment_names(resp_dict.get('experimentID', None))
331st = resp_dict.get('experimentStatus', None)
332
333if e_local: print "localname: %s" % e_local
334if e_fedid: print "fedid: %s" % e_fedid
335if st: print "status: %s" % st
[e83f2f2]336proof = proof.from_dict(resp_dict.get('proof', {}))
337if proof and opts.auth_log:
338    log_authentication(opts.auth_log, 'Create', 'succeeded', proof)
Note: See TracBrowser for help on using the repository browser.