Beispiel #1
0
def create_task():
    req = request.get_data().decode()
    response = dispatch(req)
    print(str(response), response.http_status)
    return Response(str(response),
                    response.http_status,
                    mimetype="application/json")
Beispiel #2
0
def run(parser):
    args = parser.parse_args()

    available_apps = list_apps()
    if not args.name:
        print json.dumps(available_apps)
    elif (args.name in available_apps) and args.jsonrpc:
        # Care must be taken that imported modules
        # do not write to std out or it will break the jsonrps parsing
        with Capturing() as output:
            func_dict = dict(app_functions(args.name))
            result = dispatch(func_dict, json.loads(args.jsonrpc))

        out = '\n'.join(output)
        print json.dumps({"result": result, "out": out})

    elif args.name in available_apps:
        funcs = app_functions(args.name)
        doc_dict = {}
        for name, func in funcs:
            doc = inspect.getdoc(func)
            sig = name + str(signature(func))
            doc_dict[name] = sig
            if doc:
                doc_dict[name] += '\n\n' + doc

        print json.dumps(doc_dict)
    else:
        print args
    def handle_jsonrpc(self, src, msg, topic=None):
        request = json.loads(msg.decode('UTF-8'))


        if 'error' in request:
            logging.error(str(request['error']))
            return

        if 'result' in request:
            logging.info(str(request['result']))
            return

        # include the 'ddsrc' parameter so the
        # dispatched method knows where the message came from
        if 'params' not in request:
            request['params'] = {}

        request['params']['ddsrc'] = src.decode()
        response = dispatch(self.methods, request)

        # if the http_status is 200, its request/response, otherwise notification
        if response.http_status == 200:
            logging.info("Replying to %s with %s" % (str(src), str(response)))
            self.sendmsg(src, str(response))
        # notification, correctly formatted
        elif response.http_status == 204:
            pass
        # if 400, some kind of error
        # return a message to the sender, even if it was a notification
        elif response.http_status == 400:
            self.sendmsg(src, str(response))
            logging.error("Recived bad JSON-RPC from %s, error %s" % (str(src), str(response)))
        else:
            logging.error(
                "Recived bad JSON-RPC from %s \nRequest: %s\nResponose: %s" % (str(src), msg.decode(), str(response)))
Beispiel #4
0
    def handle(self):
        logging.info("NEW STREAM: %s", self.client_address)
        while True:
            # self.request is the TCP socket connected to the client
            try:
                size_raw = self.request.recv(4)
            except ConnectionResetError:
                logging.info("CLOSED connection by client")
                return
            except ConnectionAbortedError:
                logging.info("ABORTED connection")
                return

            l = len(size_raw)
            if l == 0:
                logging.info("DISCONNECT (0 bytes read)")
                return
            elif l != 4:
                logging.warning("TOO FEW BYTES: %s", l)
                return
            size = common.bytes2int(size_raw)
            i = 0
            data_raw = bytes()
            while i < size:
                rest = size - i
                n = min(rest, common.BUFFER_SIZE)
                data_raw += self.request.recv(n)
                i += n
            data = data_raw.decode('utf-8')
            logging.info("REQUEST (%s): %s", size, data)
            # please see requests.py for individual requests' code
            response = dispatch(data, context=self.server.context)
            if response.wanted:
                self.send_data(response.deserialized())
Beispiel #5
0
 def handle(self):
     cl = 0
     addr = None
     while 1:
         hh = self.rfile.readline().strip()
         if b'POST /' in hh:
             addr = hh.split(b'POST /')[1].split(b' ')[0]
         if b'Content-Length: ' in hh:
             cl = int(hh.split(b'Content-Length: ')[1])
         if hh == b"":
             #print("done")
             break
     if addr is None:
         snd = "CONNECTED:" + str(xcnt) + "\n\n\nFOUND BLOCK:" + str(pcnt)
         self.wfile.write(b'HTTP/1.0 200 OK\r\n\r\n' + snd.encode('utf-8'))
         return
     if addre.fullmatch(addr) is None:
         print("BAD ADDRESS", addr)
         return
     idat = self.rfile.read(cl).decode('utf-8')
     print("<<", addr, idat)
     dat = dispatch(idat)
     print(">>", dat)
     print(pcnt)
     xcnt[addr] += 1
     if 'eth_submitWork' in idat:
         pcnt[addr] += 1
     self.wfile.write(b'HTTP/1.0 200 OK\r\n\r\n' + str(dat).encode('utf-8'))
Beispiel #6
0
def run(parser):
    args = parser.parse_args()

    available_apps = list_apps()
    if not args.name:
        print json.dumps(available_apps)
    elif (args.name in available_apps) and args.jsonrpc:
        # Care must be taken that imported modules
        # do not write to std out or it will break the jsonrps parsing
        with Capturing() as output:
            func_dict = dict(app_functions(args.name))
            result = dispatch(func_dict, json.loads(args.jsonrpc))

        #result['out'] = '\n'.join(output)
        print json.dumps(result)

    elif args.name in available_apps:
        funcs = app_functions(args.name)
        doc_dict = {}
        for name, func in funcs:
            doc = inspect.getdoc(func)
            sig = name + str(signature(func))
            doc_dict[name] = sig
            if doc:
                doc_dict[name] += '\n\n' + doc

        print json.dumps(doc_dict)
    else:
        print args
Beispiel #7
0
	def post(self):
		"""Accepts jsorpc post request.
		Retrieves data from request body.
		Calls log method for writung data to database
		"""
		data = json.loads(self.request.body.decode())
		response = dispatch([log],{'jsonrpc': '2.0', 
					'method': 'log', 'params': data, 'id': 1})
Beispiel #8
0
def handle_request():
    if request.remote_addr != '127.0.0.1':
        return "no", 403
    req = request.get_data().decode()
    response = dispatch(req)
    return Response(str(response),
                    response.http_status,
                    mimetype="application/json")
 def do_POST(self):
     # Process request
     request = self.rfile.read(int(self.headers["Content-Length"])).decode()
     response = dispatch(request)
     # Return response
     self.send_response(response.http_status)
     self.send_header("Content-type", "application/json")
     self.end_headers()
     self.wfile.write(str(response).encode())
Beispiel #10
0
 def post(self):
     request = self.request.body.decode()
     logging.info(f"Got a request {request}")
     response = dispatch(request)
     logging.info(f"Sending a response {response}")
     if response.wanted:
         self.write(str(response))
     else:
         logging.warning(f"Unknown request {request}")
Beispiel #11
0
 def jsonrpc():
     req = request.get_data().decode()
     response = jsonrpcserver.dispatch(req,
                                       methods=methods,
                                       debug=True,
                                       convert_camel_case=False)
     response_str = str(response)
     return Response(response_str,
                     response.http_status,
                     mimetype="application/json")
Beispiel #12
0
    def index():  # pragma pylint: disable=unused-variable
        """Index to run RPC POST requests.

        Returns:
            (Response) HTTP response to RPC call.

        """
        req = request.get_data().decode()
        response = dispatch(req, debug=True)
        return Response(str(response), 200, mimetype="application/json")
Beispiel #13
0
def create_task():
    req = request.get_data().decode()
    rnd = rand.randint(1, 20)
    print(rnd)
    time.sleep(rnd)
    #time.sleep(10)
    response = dispatch(req)
    return Response(str(response),
                    response.http_status,
                    mimetype="application/json")
def index():
    """
        Обработка всех запросов к api gateway
    """
    request = flask_request.get_data().decode()

    response = dispatch(request=request,
                        methods=methods,
                        debug=True,
                        basic_logging=True)
    return FlaskResponse(str(response),
                         response.http_status,
                         mimetype="application/json")
    def do_POST(self):
        # Process request
        request = self.rfile.read(int(self.headers["Content-Length"])).decode()
        J_LOGGER.info("{} processing request:\n\t\t{}", name, request)

        response = dispatch(request, methods=methods)

        J_LOGGER.info("Got Response:\n\t\t{}", response)

        # Return response
        self.send_response(response.http_status)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(str(response).encode())
Beispiel #16
0
    def call(self, *, method, params):
        req = {
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "id": 1,
        }
        req_str = json.dumps(req)

        response = dispatch(request=req_str,
                            methods=global_methods,
                            debug=True,
                            basic_logging=True)
        return response
Beispiel #17
0
def public():
    '''Generic route for public methods which doesn't require authentication.

    ### Currently dispatches below methods:
        get_token: Available to users at the discretion of ADMIN_USER

    ### Note:
        Typically used to acquire a token by proving the user identity.

    ### Please refer specific method docstrings for an example API call that \
        the function accepts.
    '''
    req = request.get_data().decode()
    response = dispatch(
        req,
        debug=True,
    )
    return Response(str(response),
                    response.http_status,
                    mimetype='application/json')
Beispiel #18
0
 def post(self):
     """Accepts jsorpc post request.
     Retrieves data from request body.
     """
     # type(data) = dict
     data = json.loads(self.request.body.decode())
     # type(method) = str
     method = data["method"]
     # type(params) = dict
     params = data["params"]
     if method == "sendmail":
         response = dispatch(
             [sendmail], {
                 'jsonrpc': '2.0',
                 'method': 'sendmail',
                 'params': [params],
                 'id': 1
             })
         #self.write(response)
     else:
         pass
def main():
    parser = argparse.ArgumentParser(description='Pacing Algorithm Deamon')
    parser.add_argument('--limit',
                        default=Config.getParam('pacing', 'defaultlimit'))
    parser.add_argument('--reset-time',
                        default=Config.getParam('pacing', 'defaultresettime'))
    args = parser.parse_args()
    pc = PacingController(args.limit, args.reset_time)

    # Start zmq socket
    context = zmq.Context(1)
    server = context.socket(zmq.REP)
    bind_address = Config.getParam('pacing', 'bindaddrserver')
    logger.info('Binding to %s' % bind_address)
    server.bind(bind_address)

    # Populate rpc methods dict
    methods = {'pa_push_bid': pc.pa_push_bid, 'pa_reset': pc.reset}
    stime = time.time()
    # Enter main loop
    try:
        logger.info('Entering main loop')
        while True:
            # reset campaigns bids count
            # if reset time has been reached
            ctime = time.time()
            if ctime - stime > 1000:
                stime = ctime
                pc.reset()
                logger.info('pacing reset performed')

            request = server.recv_json()
            logger.info('main loop req {0}'.format(request))
            response = dispatch(methods, request)
            server.send_json(response)
    finally:
        logger.info('Cleaning up')
        server.close()
        context.term()
Beispiel #20
0
def private(caller):
    '''Generic route for private methods which requires authentication.

    ### Currently dispatches below methods:
        get_all_users: Restricted to ADMIN_USER
        add_user: Restricted to ADMIN_USER
        to_done: Available to all authenticated users

    ### Note:
        Most of the times 'caller' will be inferred from token and
        'user' from JSON-API Call params

    ### Please refer specific method docstrings for an example API call that \
        the function accepts.
    '''
    req = request.get_data().decode()
    response = dispatch(
        req,
        context={'caller': caller},
        debug=True,
    )
    return Response(str(response),
                    response.http_status,
                    mimetype='application/json')
Beispiel #21
0
from jsonrpcserver import method, dispatch, serve

@method
def ping():
    return 'pssps'


if __name__ == '__main__':
    print(12)
    serve()
    response = dispatch('{"jsonrpc": "2.0", "method": "ping", "id":11023}')
    print(123)
    print(response.http_status)
Beispiel #22
0
def handle_message(request):
    response = dispatch(request)
    if response.wanted:
        send(response, json=True)
Beispiel #23
0
def index():
    return Response(dispatch(request.get_data().decode()),
                    content_type="application/json")
Beispiel #24
0
def application(request):
    return Response(dispatch(request.data.decode()),
                    200,
                    mimetype="application/json")
Beispiel #25
0
from jsonrpcserver import method, Result, Success, dispatch
import zmq

socket = zmq.Context().socket(zmq.REP)


@method
def ping() -> Result:
    return Success("pong")


if __name__ == "__main__":
    socket.bind("tcp://*:5000")
    while True:
        request = socket.recv().decode()
        socket.send_string(dispatch(request))
Beispiel #26
0
def jsonrpc(request):
    response = dispatch(request.body.decode())
    return JsonResponse(
        response.deserialized(), status=response.http_status, safe=False
    )
Beispiel #27
0
def jsonrpc(request):
    return HttpResponse(
        dispatch(request.body.decode()), content_type="application/json"
    )
Beispiel #28
0
def handle_message(request):
    if response := dispatch(request):
        send(response, json=True)
Beispiel #29
0
import zmq
from jsonrpcserver import method, dispatch

socket = zmq.Context().socket(zmq.REP)


@method
def ping():
    return "pong"


if __name__ == "__main__":
    socket.bind("tcp://*:5000")
    while True:
        request = socket.recv().decode()
        response = dispatch(request)
        socket.send_string(str(response))
def index():
    response = dispatch(request.get_data().decode())
    return Response(str(response),
                    response.http_status,
                    mimetype="application/json")
Beispiel #31
0
def index():
    print('request')
    r = dispatch([ludicode], request.get_data().decode('utf-8'))
    return Response(r.body, r.http_status, mimetype='application/json')
Beispiel #32
0
def index():
    print('request')
    r = dispatch([ludicode], request.get_data().decode('utf-8'))
    return Response(r.body, r.http_status, mimetype='application/json')
Beispiel #33
0
def application(request):
    response = dispatch(request.data.decode())
    return Response(str(response),
                    response.http_status,
                    mimetype="application/json")