source: fedd/federation/ns2topdl.py @ 8cb269a

compt_changesinfo-ops
Last change on this file since 8cb269a was 8cb269a, checked in by Ted Faber <faber@…>, 12 years ago

Send the ns pasring error back to the caller (and back to the user)
closes #40

  • Property mode set to 100644
File size: 5.0 KB
Line 
1#!/usr/local/bin/python
2
3import os,sys
4import subprocess
5import tempfile
6import logging
7import topdl
8
9import os.path
10
11from util import *
12from fedid import fedid
13from remote_service import xmlrpc_handler, soap_handler
14from service_error import *
15from authorizer import authorizer, abac_authorizer
16
17
18class nullHandler(logging.Handler):
19    def emit(self, record): pass
20
21fl = logging.getLogger("fedd.splitter")
22fl.addHandler(nullHandler())
23
24class ns2topdl_local:
25    def __init__(self, config=None, auth=None):
26        """
27        Intialize the various attributes, most from the config object
28        """
29        self.debug = config.getboolean("ns2topdl", "debug")
30        self.muxmax = config.getint("ns2topdl", "muxmax", 3)
31        self.tclsh = config.get("ns2topdl", "tclsh", 
32                "/usr/local/bin/otclsh")
33        self.tcl_splitter = config.get("ns2topdl", "tcl_splitter",
34                "/usr/testbed/lib/ns2ir/parse.tcl")
35        self.auth_type = config.get('ns2topdl', 'auth_type') or 'legacy'
36        access_db = config.get("ns2topdl", "accessdb", None)
37        self.allow_any = config.getboolean("ns2topdl", "allow_any", False)
38        auth_dir = config.get('ns2topdl', 'auth_dir')
39
40        self.log = logging.getLogger("fedd.ns2topdl")
41        set_log_level(config, "ns2topdl", self.log)
42        self.trace_file = sys.stderr
43
44        set_log_level(config, "ns2topdl", self.log)
45
46        if auth:
47            self.auth= auth
48        else:
49            self.auth = authorizer()
50            self.log.warning("[ns2topdl] No authorizer passed in, " +\
51                    "using local one")
52
53
54        if self.auth_type == 'legacy':
55            if access_db and self.allow_any: 
56                raise service_error(service_error.internal, 
57                        "Cannot specify both an access database and " + 
58                        "allow_any for ns2topdl")
59           
60            if access_db:
61                try:
62                    read_simple_accessdb(access_db, self.auth, 'ns2topdl')
63                except EnvironmentError, e:
64                    raise service_error(service_error.internal,
65                            "Error reading accessDB %s: %s" % (access_db, e))
66                except ValueError:
67                    raise service_error(service_error.internal, "%s" % e)
68            elif self.allow_any:
69                auth.set_global_attribute("ns2topdl")
70        elif self.auth_type == 'abac':
71            self.auth = abac_authorizer(load=auth_dir)
72        else:
73            raise service_error(service_error.internal, 
74                    "Unknown auth_type: %s" % self.auth_type)
75
76
77        # Dispatch tables
78        self.soap_services = {\
79                'Ns2Topdl': soap_handler("Ns2Topdl", self.run_ns2topdl),
80        }
81
82        self.xmlrpc_services = {\
83                'Ns2Topdl': xmlrpc_handler('Ns2Topdl', self.run_ns2topdl),
84        }
85
86    def run_ns2topdl(self, req, fid):
87        """
88        The external interface to tcl to topdl translation.
89
90        Creates a working directory, translates the incoming description using
91        the tcl script.
92        """
93
94        if self.allow_any:
95            self.auth.set_attribute(fid, 'ns2topdl')
96
97        access_ok, proof = self.auth.check_attribute(fid, 'ns2topdl',
98            with_proof=True)
99
100        if not access_ok:
101            raise service_error(service_error.access, "Access Denied", 
102                proof=proof)
103
104        try:
105            tmpdir = tempfile.mkdtemp(prefix="ns2topdl-")
106        except EnvironmentError:
107            raise service_error(service_error.internal, "Cannot create tmp dir")
108
109        tclfile = os.path.join(tmpdir, "experiment.tcl")
110        # save error output in case the parse fails.
111        errfile = os.path.join(tmpdir, "errfile")
112        pid = "dummy"
113        gid = "dummy"
114        eid = "dummy"
115        master = "dummy"
116
117        req = req.get('Ns2TopdlRequestBody', None)
118        if not req:
119            raise service_error(service_error.req,
120                    "Bad request format (no Ns2TopdlRequestBody)")
121        # The tcl parser needs to read a file so put the content into that file
122        descr=req.get('description', None)
123        if descr:
124            file_content=descr.get('ns2description', None)
125            if file_content:
126                try:
127                    f = open(tclfile, 'w')
128                    f.write(file_content)
129                    f.close()
130                    ef = open(errfile, 'w')
131                except EnvironmentError:
132                    raise service_error(service_error.internal,
133                            "Cannot write temp experiment description")
134            else:
135                raise service_error(service_error.req, 
136                        "Only ns2descriptions supported")
137        else:
138            raise service_error(service_error.req, "No description")
139
140       
141        tclcmd = [self.tclsh, self.tcl_splitter, '-t', '-x', 
142            str(self.muxmax), '-m', master]
143        tclcmd.extend([pid, gid, eid, tclfile])
144        self.log.debug("Calling splitter %s" % " ".join(tclcmd))
145        tclparser = subprocess.Popen(tclcmd, stdout=subprocess.PIPE, stderr=ef)
146
147        try:
148            top = topdl.topology_from_xml(file=tclparser.stdout, 
149                    top="experiment")
150        except:
151            top = None
152
153        if top is None:
154            # There was an ns parsing error, gather up the error from the
155            # errfile and raise a service_error containing the error text
156            try:
157                ef = open(errfile, 'r')
158                parse_err = ef.read()
159                ef.close()
160            except EnvironmentError:
161                raise service_error(service_error.internal,
162                        "Cannot read error string")
163
164            raise service_error(service_error.req, 
165                    "Cannot parse ns file: %s" % parse_err)
166
167        # Walk up tmpdir, deleting as we go
168        for path, dirs, files in os.walk(tmpdir, topdown=False):
169            for f in files:
170                os.remove(os.path.join(path, f))
171            for d in dirs:
172                os.rmdir(os.path.join(path, d))
173        os.rmdir(tmpdir)
174
175        resp = { 
176                'experimentdescription':  { 
177                    'topdldescription': top.to_dict(),
178                    },
179                'proof': proof.to_dict(),
180                }
181
182        return resp
183
184
Note: See TracBrowser for help on using the repository browser.