Esempio n. 1
0
    def __call__(self, *args, **kwargs):

        self.data['args'] = args
        self.data['kwargs'] = kwargs

        results = nlan.main(router=self.target, operation='--rpc', doc=str(self.data), output_stdout=True)
        if self.detailed_results or self.target=='_ALL':
            return results
        elif not self.detailed_results and self.target != '_ALL':
            return results[0]['stdout']
Esempio n. 2
0
    def __call__(self, *args, **kwargs):

        self.data['args'] = args
        self.data['kwargs'] = kwargs

        results = nlan.main(router=self.target,
                            operation='--rpc',
                            doc=str(self.data),
                            output_stdout=True)
        if self.detailed_results or self.target == '_ALL':
            return results
        elif not self.detailed_results and self.target != '_ALL':
            return results[0]['stdout']
Esempio n. 3
0
    def __call__(self, environ, start_response):
       
        # Request method
        method = environ['REQUEST_METHOD']

        # /// URLs ///
        # /<router>/config/<module>/<_index>
        # /<router>/rpc/<module>/<func>
        path = environ['PATH_INFO'].split('/')
        router = None
        module_type = None # 'config' or 'rpc'
        module = None # name of a config module or a rpc module
        _index = None
        module_func = None
        if len(path) > 1:
            router = path[1]
        if len(path) > 2:
            module_type = path[2]
        if len(path) > 3:
            module = path[3]
        if len(path) > 4:
            if module_type == 'config': # Calls a config module
                _index = path[4]
            elif module_type == 'rpc': # Calls a rpc module
                module_func = '{}.{}'.format(module,path[4])
       
        # /// Methods ///
        # Method    NLAN operation
        # ------------------------
        # POST      --add or none(rpc) 
        # PUT       --update
        # DELETE    --delete
        # GET       --get
        # OPTIONS   --schema
        # /// Query parameters ///
        # -------------------------------------------------------
        # For POST(config)/PUT
        # Query parameters correspond to those --schema outputs
        # (excluding "_index").
        # -------------------------------------------------------
        # For POST(rpc)/DELETE/GET
        # args=<value1>,<value2>,...
        # -------------------------------------------------------
        # For OPTIONS
        # args=<module_name>
        # -------------------------------------------------------
        operations = {'POST': '--add',
                      'PUT': '--update',
                      'DELETE': '--delete',
                      'GET': '--get'}
        doc = None
        query = environ['QUERY_STRING'] 
        if method == 'POST' and module_type == 'config' or method == 'PUT': # add/update
            q = query.split('&')
            if _index:
                q.append('_index={}'.format(_index))
            doc = str(argsmodel.parse_args('add', module, *q))
        elif method == 'DELETE' or method == 'GET': # delete/get
            qq = query.split('=') 
            q = [] 
            if qq[0] == 'params':
                q = qq[1].split(',')
            if _index:
                q.append('_index={}'.format(_index))
            doc = str(argsmodel.parse_args('get', module, *q))
        elif method == 'POST' and module_type == 'rpc':
            doc = [] 
            doc.append(module_func)
            q = query.split('=') 
            if q[0] == 'params':
                doc.extend(q[1].split(','))
        elif method == 'OPTIONS': # schema
            if query: 
                qq = query.split('=')
                module = qq[1]

        # String buffer as a HTTP Response body
        out = StringIO()

        try:
            if method in operations and module_type == 'config': 
                operation = operations[method]
                results = nlan.main(router=router, operation=operation, doc=doc, output_stdout=True, rest_output=True)
                print >>out, json.dumps(results)
                start_response('200 OK', [('Content-type', 'application/json')])
            elif method == 'POST' and module_type == 'rpc':
                results = nlan.main(router=router, doc=doc, output_stdout=True, rest_output=True)
                print >>out, json.dumps(results)
                start_response('200 OK', [('Content-type', 'application/json')])
            elif method == 'OPTIONS':
                print >>out, argsmodel.schema_help(module, list_output=True)
                start_response('200 OK', [('Content-type', 'application/json')])
            else:
                print >>out, 'Not Implemented'
                start_response('501 Not Implemented', [('Content-type', 'text/plain')])
        except NlanException as e:
            results = e.get_result()
            print >>out, json.dumps(results)
            start_response('500 Internal Server Error', [('Content-type', 'application/json')])
        except Exception as e:
            print >>out, traceback.format_exc()
            start_response('500 Internal Server Error', [('Content-type', 'application/json')])

        # Return the result as a body of HTTP Response
        out.seek(0)
        return out 
Esempio n. 4
0
def do(scenario, dirname, interactive):

    for l in scenario:
        if 'do' in l:
            do_file = os.path.join(dirname, l['do'])
            with open(do_file, 'r') as f:
                scenario = yaml.load(f.read())
            do(scenario, dirname, interactive)
        if 'sleep' in l:
            time.sleep(int(l['sleep']))
        if 'comment' in l:
            rp = "TEST: {}".format(l['comment'])
            print bar[:5], rp, bar[5+len(rp):]
        if interactive:
            raw_input("Press Enter to continue...") 
        if 'command' in l:
            cmdutil.check_cmd(l['command'])
        if 'nlan' in l:
            ll = l['nlan']
            options = None
            args = None
            if 'options' in ll:
                options = ll['options']
            if 'args' in ll:
                v = ll['args']
                if isinstance(v, dict):
                    if options == '--delete':
                        args = _args_od(v, reverse=True)
                    else:
                        args = _args_od(v)
                    prev = args
                    args = str(args)
                else:
                    args = v.split()
            if 'router' in ll:
                router = ll['router']
            try:
                result = nlan.main(router=router, operation=options, doc=args, output_stdout=True)
                if 'assert' in ll:
                    if ll['assert']:  # not null
                        #args1 = dict(eval(result[0]['stdout']))
                        args1 = dict(result[0]['stdout'])
                        args2 = ll['assert']
                        if args2 == '_prev':
                            args2 = remove_item(prev, '_index')
                        diff = None
                        try:
                            diff = list(dictdiffer.diff(args1, args2))
                            assert len(diff) == 0
                            _print_success()
                        except Exception as e:
                            _print_failure()
                            print diff 
                            print traceback.format_exc()
                    else:  # null
                        if result[0]['stdout']:
                            _print_failure()
                            print result[0]['stdout']
                        else:
                            _print_success()
            except NlanException as e:
                result = e.get_result() 
                type_ = result[0]['response']['exception']
                if 'assertRaises' in ll:
                    assert type_ == ll['assertRaises']['type'] 
                    _print_success()
                else:
                    raise
Esempio n. 5
0
    def __call__(self, environ, start_response):

        # Request method
        method = environ['REQUEST_METHOD']

        # /// URLs ///
        # /<router>/config/<module>/<_index>
        # /<router>/rpc/<module>/<func>
        path = environ['PATH_INFO'].split('/')
        router = None
        module_type = None  # 'config' or 'rpc'
        module = None  # name of a config module or a rpc module
        _index = None
        module_func = None
        if len(path) > 1:
            router = path[1]
        if len(path) > 2:
            module_type = path[2]
        if len(path) > 3:
            module = path[3]
        if len(path) > 4:
            if module_type == 'config':  # Calls a config module
                _index = path[4]
            elif module_type == 'rpc':  # Calls a rpc module
                module_func = '{}.{}'.format(module, path[4])

        # /// Methods ///
        # Method    NLAN operation
        # ------------------------
        # POST      --add or none(rpc)
        # PUT       --update
        # DELETE    --delete
        # GET       --get
        # OPTIONS   --schema
        # /// Query parameters ///
        # -------------------------------------------------------
        # For POST(config)/PUT
        # Query parameters correspond to those --schema outputs
        # (excluding "_index").
        # -------------------------------------------------------
        # For POST(rpc)/DELETE/GET
        # args=<value1>,<value2>,...
        # -------------------------------------------------------
        # For OPTIONS
        # args=<module_name>
        # -------------------------------------------------------
        operations = {
            'POST': '--add',
            'PUT': '--update',
            'DELETE': '--delete',
            'GET': '--get'
        }
        doc = None
        query = environ['QUERY_STRING']
        if method == 'POST' and module_type == 'config' or method == 'PUT':  # add/update
            q = query.split('&')
            if _index:
                q.append('_index={}'.format(_index))
            doc = str(argsmodel.parse_args('add', module, *q))
        elif method == 'DELETE' or method == 'GET':  # delete/get
            qq = query.split('=')
            q = []
            if qq[0] == 'params':
                q = qq[1].split(',')
            if _index:
                q.append('_index={}'.format(_index))
            doc = str(argsmodel.parse_args('get', module, *q))
        elif method == 'POST' and module_type == 'rpc':
            doc = []
            doc.append(module_func)
            q = query.split('=')
            if q[0] == 'params':
                doc.extend(q[1].split(','))
        elif method == 'OPTIONS':  # schema
            if query:
                qq = query.split('=')
                module = qq[1]

        # String buffer as a HTTP Response body
        out = StringIO()

        try:
            if method in operations and module_type == 'config':
                operation = operations[method]
                results = nlan.main(router=router,
                                    operation=operation,
                                    doc=doc,
                                    output_stdout=True,
                                    rest_output=True)
                print >> out, json.dumps(results)
                start_response('200 OK',
                               [('Content-type', 'application/json')])
            elif method == 'POST' and module_type == 'rpc':
                results = nlan.main(router=router,
                                    doc=doc,
                                    output_stdout=True,
                                    rest_output=True)
                print >> out, json.dumps(results)
                start_response('200 OK',
                               [('Content-type', 'application/json')])
            elif method == 'OPTIONS':
                print >> out, argsmodel.schema_help(module, list_output=True)
                start_response('200 OK',
                               [('Content-type', 'application/json')])
            else:
                print >> out, 'Not Implemented'
                start_response('501 Not Implemented',
                               [('Content-type', 'text/plain')])
        except NlanException as e:
            results = e.get_result()
            print >> out, json.dumps(results)
            start_response('500 Internal Server Error',
                           [('Content-type', 'application/json')])
        except Exception as e:
            print >> out, traceback.format_exc()
            start_response('500 Internal Server Error',
                           [('Content-type', 'application/json')])

        # Return the result as a body of HTTP Response
        out.seek(0)
        return out