Ejemplo n.º 1
0
    def post(self, actor_id):
        def get_hypermedia(actor, exc):
            return {
                '_links': {
                    'self':
                    '{}/actors/v2/{}/executions/{}'.format(
                        actor.api_server, actor.id, exc),
                    'owner':
                    '{}/profiles/v2/{}'.format(actor.api_server, actor.owner),
                    'messages':
                    '{}/actors/v2/{}/messages'.format(actor.api_server,
                                                      actor.id)
                },
            }

        args = self.validate_post()
        d = {}
        # build a dictionary of k:v pairs from the query parameters, and pass a single
        # additional object 'message' from within the post payload. Note that 'message'
        # need not be JSON data.
        for k, v in request.args.items():
            if k == 'message':
                continue
            d[k] = v
        if hasattr(g, 'user'):
            d['_abaco_username'] = g.user
        if hasattr(g, 'api_server'):
            d['_abaco_api_server'] = g.api_server
        # if hasattr(g, 'jwt'):
        #     d['_abaco_jwt'] = g.jwt
        # if hasattr(g, 'jwt_server'):
        #     d['_abaco_jwt_server'] = g.jwt_server
        if hasattr(g, 'jwt_header_name'):
            d['_abaco_jwt_header_name'] = g.jwt_header_name
        dbid = Actor.get_dbid(g.tenant, actor_id)
        # create an execution
        exc = Execution.add_execution(
            dbid, {
                'cpu': 0,
                'io': 0,
                'runtime': 0,
                'status': SUBMITTED,
                'executor': g.user
            })
        d['_abaco_execution_id'] = exc
        d['_abaco_Content-Type'] = args.get('_abaco_Content-Type', '')
        ch = ActorMsgChannel(actor_id=dbid)
        ch.put_msg(message=args['message'], d=d)
        # make sure at least one worker is available
        actor = Actor.from_db(actors_store[dbid])
        actor.ensure_one_worker()
        result = {'execution_id': exc, 'msg': args['message']}
        result.update(get_hypermedia(actor, exc))
        case = Config.get('web', 'case')
        if not case == 'camel':
            return ok(result)
        else:
            return ok(dict_to_camel(result))
Ejemplo n.º 2
0
    def post(self, actor_id):
        def get_hypermedia(actor, exc):
            return {'_links': {'self': '{}/actors/v2/{}/executions/{}'.format(actor.api_server, actor.id, exc),
                               'owner': '{}/profiles/v2/{}'.format(actor.api_server, actor.owner),
                               'messages': '{}/actors/v2/{}/messages'.format(actor.api_server, actor.id)},}

        args = self.validate_post()
        d = {}
        # build a dictionary of k:v pairs from the query parameters, and pass a single
        # additional object 'message' from within the post payload. Note that 'message'
        # need not be JSON data.
        for k, v in request.args.items():
            if k == 'message':
                continue
            d[k] = v
        if hasattr(g, 'user'):
            d['_abaco_username'] = g.user
        if hasattr(g, 'api_server'):
            d['_abaco_api_server'] = g.api_server
        # if hasattr(g, 'jwt'):
        #     d['_abaco_jwt'] = g.jwt
        # if hasattr(g, 'jwt_server'):
        #     d['_abaco_jwt_server'] = g.jwt_server
        if hasattr(g, 'jwt_header_name'):
            d['_abaco_jwt_header_name'] = g.jwt_header_name
        dbid = Actor.get_dbid(g.tenant, actor_id)
        # create an execution
        exc = Execution.add_execution(dbid, {'cpu': 0,
                                             'io': 0,
                                             'runtime': 0,
                                             'status': SUBMITTED,
                                             'executor': g.user})
        d['_abaco_execution_id'] = exc
        d['_abaco_Content-Type'] = args.get('_abaco_Content-Type', '')
        ch = ActorMsgChannel(actor_id=dbid)
        ch.put_msg(message=args['message'], d=d)
        # make sure at least one worker is available
        workers = Worker.get_workers(dbid)
        actor = Actor.from_db(actors_store[dbid])
        if len(workers.items()) < 1:
            ch = CommandChannel()
            ch.put_cmd(actor_id=dbid, image=actor.image, tenant=g.tenant, num=1, stop_existing=False)
        result={'execution_id': exc, 'msg': args['message']}
        result.update(get_hypermedia(actor, exc))
        case = Config.get('web', 'case')
        if not case == 'camel':
            return ok(result)
        else:
            return ok(dict_to_camel(result))
Ejemplo n.º 3
0
    def post(self, actor_id):
        def get_hypermedia(actor, exc):
            return {'_links': {'self': '{}/actors/v2/{}/executions/{}'.format(actor.api_server, actor.id, exc),
                               'owner': '{}/profiles/v2/{}'.format(actor.api_server, actor.owner),
                               'messages': '{}/actors/v2/{}/messages'.format(actor.api_server, actor.id)},}

        logger.debug("top of POST /actors/{}/messages.".format(actor_id))
        dbid = Actor.get_dbid(g.tenant, actor_id)
        try:
            Actor.from_db(actors_store[dbid])
        except KeyError:
            logger.debug("did not find actor: {}.".format(actor_id))
            raise ResourceError("No actor found with id: {}.".format(actor_id), 404)
        args = self.validate_post()
        d = {}
        # build a dictionary of k:v pairs from the query parameters, and pass a single
        # additional object 'message' from within the post payload. Note that 'message'
        # need not be JSON data.
        logger.debug("POST body validated. actor: {}.".format(actor_id))
        for k, v in request.args.items():
            if k == 'message':
                continue
            d[k] = v
        logger.debug("extra fields added to message from query parameters: {}.".format(d))
        if hasattr(g, 'user'):
            d['_abaco_username'] = g.user
            logger.debug("_abaco_username: {} added to message.".format(g.user))
        if hasattr(g, 'api_server'):
            d['_abaco_api_server'] = g.api_server
            logger.debug("_abaco_api_server: {} added to message.".format(g.api_server))
        # if hasattr(g, 'jwt'):
        #     d['_abaco_jwt'] = g.jwt
        # if hasattr(g, 'jwt_server'):
        #     d['_abaco_jwt_server'] = g.jwt_server
        if hasattr(g, 'jwt_header_name'):
            d['_abaco_jwt_header_name'] = g.jwt_header_name
            logger.debug("abaco_jwt_header_name: {} added to message.".format(g.jwt_header_name))

        # create an execution
        exc = Execution.add_execution(dbid, {'cpu': 0,
                                             'io': 0,
                                             'runtime': 0,
                                             'status': SUBMITTED,
                                             'executor': g.user})
        logger.info("Execution {} added for actor {}".format(exc, actor_id))
        d['_abaco_execution_id'] = exc
        d['_abaco_Content_Type'] = args.get('_abaco_Content_Type', '')
        logger.debug("Final message dictionary: {}".format(d))
        ch = ActorMsgChannel(actor_id=dbid)
        ch.put_msg(message=args['message'], d=d)
        ch.close()
        logger.debug("Message added to actor inbox. id: {}.".format(actor_id))
        # make sure at least one worker is available
        actor = Actor.from_db(actors_store[dbid])
        actor.ensure_one_worker()
        logger.debug("ensure_one_worker() called. id: {}.".format(actor_id))
        if args.get('_abaco_Content_Type') == 'application/octet-stream':
            result = {'execution_id': exc, 'msg': 'binary - omitted'}
        else:
            result={'execution_id': exc, 'msg': args['message']}
        result.update(get_hypermedia(actor, exc))
        case = Config.get('web', 'case')
        if not case == 'camel':
            return ok(result)
        else:
            return ok(dict_to_camel(result))
Ejemplo n.º 4
0
def dashboard():
    # default to using the local instance
    try:
        jwt = g.jwt
    except AttributeError:
        error = "JWT mising. context: {}".format(dir(g))
        return render_template('dashboard.html',
                               actors=[],
                               jwt="",
                               jwt_header="",
                               base_url="",
                               url="",
                               error=error)

    jwt_header = g.jwt_header_name
    base_url = 'http://172.17.0.1:8000'
    url = "{}/admin/actors".format(base_url)
    error = None
    actors = None
    logger.info("jwt_header from context: {}".format(jwt_header))
    logger.debug("jwt from context: {}".format(jwt))
    logger.info("url: {}".format(url))
    if request.method == 'POST':
        logger.info("validating post params.")
        # validate POST parameters
        form_base_url = request.form.get('base_url')
        form_jwt_header = request.form.get('jwt_header')
        form_jwt = request.form.get('jwt')
        if not form_base_url:
            logger.info("Empty base url.")
            error = 'The Base URL is required.'
        elif not form_jwt_header:
            logger.info("Empty JWT header.")
            error = "The JWT Header is required."
        elif not form_jwt:
            logger.info("Empty JWT.")
            error = 'The JWT is required.'
        else:
            logger.info("Using form data.")
            base_url = form_base_url
            jwt_header = form_jwt_header
            jwt = form_jwt

    if not error:
        # try and make a request to get the actors
        headers = {jwt_header: jwt}
        url = "{}/admin/actors".format(base_url)
        logger.info("Submitting GET to: {}".format(url))
        try:
            rsp = requests.get(url, headers=headers)
        except Exception as e:
            logger.error("Got an exception from /admin/actors. Exception: {}".format(e))
            error = "Unable to retrieve actors: {}".format(e)
            return render_template('dashboard.html',
                                   actors=None,
                                   jwt=jwt,
                                   jwt_header=jwt_header,
                                   base_url=base_url,
                                   error=error)
        if rsp.status_code not in [200, 201]:
            logger.error("Did not get 200 from /admin/actors. Status: {}. content: {}".format(
                rsp.status_code, rsp.content))
            if "message" in rsp:
                msg = rsp.get("message")
            else:
                msg = rsp.content
            error = "Unable to retrieve actors. Error was: {}".format(msg)
        else:
            logger.info("Request to /admin/actors successful.")
            data = json.loads(rsp.content.decode('utf-8'))
            actors_data = data.get("result")
            if not actors_data and request.method == 'POST':
                error = "No actors found."
            else:
                actors = []
                for actor in actors_data:
                    a = dict_to_camel(actor)
                    worker = a.get('worker')
                    if worker:
                        try:
                            a['worker'] = dict_to_camel(worker)
                            a['worker']['lastHealthCheckTime'] = display_time(a['worker'].get('lastHealthCheckTime'))
                            a['worker']['lastExecutionTime'] = display_time(a['worker'].get('lastExecutionTime'))
                        except KeyError as e:
                            logger.error("Error pulling worker data from admin api. Exception: {}".format(e))
                    else:
                        a['worker'] = {'lastHealthCheckTime': '',
                                       'lastExecutionTime': '',
                                       'id': '',
                                       'status': ''}
                    logger.info("Adding actor data after converting to camel: {}".format(a))
                    a['createTime'] = display_time(a.get('createTime'))
                    a['lastUpdateTime'] = display_time(a.get('lastUpdateTime'))
                    actors.append(a)

    return render_template('dashboard.html',
                           actors=actors,
                           jwt=jwt,
                           jwt_header=jwt_header,
                           base_url=base_url,
                           url=url,
                           error=error)