Example #1
0
def get_nodes(node_link=None):
    author = to_object_id(g.user._id)
    # if node_link is a base node
    if node_link in node_collection.name_to_class:
        return JSONEncoder().encode({
            'data': node_collection.name_to_class[node_link].get_default().to_dict(),
            'status': 'success'})
    # if node_link is defined (Node id)
    elif node_link:
        try:
            node_id = to_object_id(node_link)
        except Exception:
            return 'Invalid ID', 404
        node = node_collection_manager.get_db_node(node_id, author)
        if node:
            return JSONEncoder().encode({
                'data': node,
                'status': 'success'})
        else:
            return 'Node `{}` was not found'.format(node_link), 404
    else:
        query = json.loads(request.args.get('query', "{}"))
        query["author"] = to_object_id(g.user._id)
        nodes_query = {k: v for k, v in query.items() if k in PAGINATION_QUERY_KEYS}
        count_query = {k: v for k, v in query.items() if k in COUNT_QUERY_KEYS}
        return JSONEncoder().encode({
            'nodes': node_collection_manager.get_db_nodes(**nodes_query),
            'total_count': node_collection_manager.get_db_nodes_count(**count_query),
            'status': 'success'})
Example #2
0
def get_graph(graph_id=None):
    if graph_id == 'new':
        return JSONEncoder().encode({
            'data': Graph().to_dict(),
            'status': 'success'
        })
    elif graph_id:
        graph = graph_collection_manager.get_db_graph(graph_id)
        if graph:
            return JSONEncoder().encode({'data': graph, 'status': 'success'})
        else:
            return 'Graph was not found', 404
    else:
        query = json.loads(request.args.get('query', "{}"))
        query["author"] = to_object_id(g.user._id)
        count_query = {k: v for k, v in query.items() if k in COUNT_QUERY_KEYS}
        graphs_query = {
            k: v
            for k, v in query.items() if k in PAGINATION_QUERY_KEYS
        }
        return JSONEncoder().encode({
            'graphs': [
                graph for graph in graph_collection_manager.get_db_graphs(
                    **graphs_query)
            ],
            'total_count':
            graph_collection_manager.get_db_graphs_count(**count_query),
            'status':
            'success'
        })
Example #3
0
def get_nodes(node_link=None):
    user_id = to_object_id(g.user._id)
    # if node_link is a base node
    if node_link in node_collection.name_to_class:
        return JSONEncoder().encode({
            'data':
            node_collection.name_to_class[node_link].get_default().to_dict(),
            'resources_dict':
            resource_manager.resources_dict,
            'status':
            'success'
        })
    else:
        try:
            node_id = to_object_id(node_link)
        except Exception:
            return make_fail_response('Invalid ID'), 404
        node = node_collection_manager.get_db_node(node_id, user_id)
        if node:
            return JSONEncoder().encode({
                'data': node,
                'resources_dict': resource_manager.resources_dict,
                'status': 'success'
            })
        else:
            return make_fail_response(
                'Node `{}` was not found'.format(node_link)), 404
Example #4
0
def get_nodes(collection, node_link=None):
    user_id = to_object_id(g.user._id)
    # if node_link is a base node
    if node_link in executor_manager.kind_to_executor_class and collection == Collections.TEMPLATES:
        kind = node_link
        node = executor_manager.kind_to_executor_class[kind].get_default_node(
            is_workflow=kind in workflow_manager.kind_to_workflow_dict)
        if isinstance(node, tuple):
            data = node[0].to_dict()
            tour_steps = node[1]
        else:
            data = node.to_dict()
            tour_steps = []
        data['kind'] = kind
        return JSONEncoder().encode({
            'node': data,
            'tour_steps': tour_steps,
            'plugins_dict': PLUGINS_DICT,
            'status': 'success'
        })
    elif node_link in workflow_manager.kind_to_workflow_dict and collection == Collections.GROUPS:
        # TODO move group to a separate class
        group_dict = Group().to_dict()
        group_dict['kind'] = node_link
        return JSONEncoder().encode({
            'group': group_dict,
            'plugins_dict': PLUGINS_DICT,
            'status': 'success'
        })
    else:
        try:
            node_id = to_object_id(node_link)
        except Exception:
            return make_fail_response('Invalid ID'), 404
        if collection == Collections.GROUPS:
            # TODO move group to a separate class
            group = node_collection_managers[collection].get_db_object(
                node_id, user_id)
            if group:
                return JSONEncoder().encode({
                    'group': group,
                    'plugins_dict': PLUGINS_DICT,
                    'status': 'success',
                })
            else:
                make_fail_response(
                    'Group `{}` was not found'.format(node_link)), 404
        node = node_collection_managers[collection].get_db_node(
            node_id, user_id)
        app.logger.debug(node)
        if node:
            return JSONEncoder().encode({
                'node': node,
                'plugins_dict': PLUGINS_DICT,
                'status': 'success'
            })
        else:
            return make_fail_response(
                'Node `{}` was not found'.format(node_link)), 404
Example #5
0
def update_graph(graph_id):
    app.logger.debug(request.data)
    data = json.loads(request.data)
    if not data:
        return make_fail_response('Expected json data'), 400

    graph_dict = graph_collection_manager.get_db_graph(graph_id, g.user._id)
    if not graph_dict:
        return make_fail_response('Graph was not found'), 404
    if graph_dict['_readonly']:
        return make_fail_response('Permission denied'), 403

    if graph_dict['graph_running_status'] != GraphRunningStatus.CREATED:
        return make_fail_response('Cannot save graph with status `{}`'.format(graph_dict['graph_running_status']))

    update_dict_recursively(graph_dict, data)

    graph = Graph.from_dict(graph_dict)
    graph.save()

    return JSONEncoder().encode({
            'status': 'success',
            'message': 'Successfully updated',
            'graph': graph.to_dict(),
        })
Example #6
0
def get_auth_token():
    access_token = g.user.generate_access_token()
    refresh_token = g.user.generate_refresh_token()
    return JSONEncoder().encode({
        'access_token': access_token.decode('ascii'),
        'refresh_token': refresh_token.decode('ascii')
    })
Example #7
0
def create_template(user,
                    kind,
                    cmd,
                    title,
                    description,
                    inputs=None,
                    parameters=None,
                    outputs=None):
    node = executor_manager.kind_to_executor_class[kind].get_default_node(
        is_workflow=kind in workflow_manager.kind_to_workflow_dict)
    node.author = user._id
    node.title = title
    node.description = description
    node.kind = kind

    cmd_parameter = next(
        filter(lambda parameter: parameter.name == '_cmd', node.parameters))
    cmd_parameter.value.value = cmd

    node.inputs.extend(inputs or [])
    node.parameters.extend(parameters or [])
    node.outputs.extend(outputs or [])

    import logging
    from plynx.utils.common import JSONEncoder
    logging.info(JSONEncoder().encode(node.to_dict()))

    validation_error = executor_manager.kind_to_executor_class[kind](
        node).validate()
    if validation_error:
        raise Exception('Validation failed')

    node.node_status = plynx.constants.NodeStatus.READY

    node.save(force=True)
Example #8
0
def get_graph(graph_id=None):
    if graph_id == 'new':
        return JSONEncoder().encode({
            'data': Graph().to_dict(),
            'status': 'success',
            'resources_dict': resource_manager.resources_dict,
            })
    else:
        graph = graph_collection_manager.get_db_graph(graph_id)
        if graph:
            return JSONEncoder().encode({
                'data': graph,
                'status': 'success',
                'resources_dict': resource_manager.resources_dict,
                })
        else:
            return make_fail_response('Graph was not found'), 404
Example #9
0
File: common.py Project: rbax/plynx
def make_success_response(extra_response=None):
    return JSONEncoder().encode(
        dict(
            {
                'status': ResponseStatus.SUCCESS,
                'message': 'Success',
                'settings': g.user.settings.to_dict(),
            }, **(extra_response or {})))
Example #10
0
def master_state():
    try:
        return JSONEncoder().encode({
            'status': 'success',
            'master_state': get_master_state()
        })
    except Exception as e:
        app.logger.error(e)
        return make_fail_response('Internal error: "{}"'.format(str(e)))
Example #11
0
def worker_states():
    try:
        return JSONEncoder().encode({
            'status': 'success',
            'items': get_worker_states(),
            'plugins_dict': PLUGINS_DICT,
        })
    except Exception as e:
        app.logger.error(e)
        return make_fail_response('Internal error: "{}"'.format(str(e)))
Example #12
0
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')

    message = register_user(username, password)

    if message:
        abort(400, message)

    return JSONEncoder().encode({'status': 'success'})
Example #13
0
def post_resource():
    try:
        resource_id = upload_file_stream(request.files['data'])
        return JSONEncoder().encode({
            'status': ResourcePostStatus.SUCCESS,
            'resource_id': resource_id
        })
    except Exception as e:
        app.logger.error(e)
        return _make_fail_response('Internal error: "{}"'.format(str(e)))
Example #14
0
def post_demo_user():
    user = demo_user_manager.create_demo_user()
    demo_user_manager.create_demo_graphs(user)

    access_token = user.generate_access_token(expiration=1800)
    return JSONEncoder().encode({
        'access_token': access_token.decode('ascii'),
        'refresh_token': 'Not assigned',
        'username': user.username
    })
Example #15
0
def post_demo_user():
    user = demo_user_manager.create_demo_user()
    if not user:
        return make_fail_response('Failed to create demo user')
    demo_user_manager.create_demo_graphs(user)

    access_token = user.generate_access_token(expiration=1800)
    return JSONEncoder().encode({
        'access_token': access_token.decode('ascii'),
        'refresh_token': 'Not assigned',
        'username': user.username
    })
Example #16
0
def post_search_graphs():
    app.logger.debug(request.data)
    query = json.loads(request.data)
    if len(query.keys() - PAGINATION_QUERY_KEYS):
        return make_fail_response('Unknown keys: `{}`'.format(query.keys() - PAGINATION_QUERY_KEYS)), 400

    res = graph_collection_manager.get_db_graphs(**query)

    return JSONEncoder().encode({
        'items': res['list'],
        'total_count': res['metadata'][0]['total'] if res['metadata'] else 0,
        'status': 'success'})
Example #17
0
def post_demo_user():
    user = demo_user_manager.create_demo_user()
    if not user:
        return make_fail_response('Failed to create a demo user')

    access_token = user.generate_access_token(expiration=1800)
    return JSONEncoder().encode({
        'access_token':
        access_token.decode('ascii'),
        'refresh_token':
        'Not assigned',
        'username':
        user.username,
        'url':
        '/{}/{}'.format(Collections.TEMPLATES,
                        DemoUserManager.demo_config.kind),
    })
Example #18
0
def upload_file():
    assert len(request.files) == 1
    title = request.form.get('title', '{title}')
    description = request.form.get('description', '{description}')
    file_type = request.form.get('file_type', FILE_KIND)
    node_kind = request.form.get('node_kind', 'basic-file')
    app.logger.debug(request)
    if file_type not in RESOURCE_TYPES:
        app.logger.debug(file_type)
        app.logger.debug(RESOURCE_TYPES)
        return make_fail_response(
            'Unknown file type `{}`'.format(file_type)), 400

    resource_id = upload_file_stream(request.files['data'])

    file = plynx.db.node.Node.from_dict({
        'title':
        title,
        'description':
        description,
        'kind':
        node_kind,
        'node_running_status':
        NodeRunningStatus.STATIC,
        'node_status':
        NodeStatus.READY,
    })
    file.outputs.append(
        plynx.db.node.Output.from_dict({
            'name': 'file',
            'file_type': file_type,
            'values': [resource_id],
        }))

    file.author = g.user._id
    file.save()

    return JSONEncoder().encode({
        'status': ResourcePostStatus.SUCCESS,
        'resource_id': resource_id,
        'node': file.to_dict(),
    })
Example #19
0
def post_search_nodes():
    query = json.loads(request.data)
    user_id = to_object_id(g.user._id)
    if len(query.keys() - PAGINATION_QUERY_KEYS):
        return make_fail_response(
            'Unknown keys: `{}`'.format(query.keys() -
                                        PAGINATION_QUERY_KEYS)), 400

    res = node_collection_manager.get_db_nodes(user_id=user_id, **query)

    return JSONEncoder().encode({
        'items':
        res['list'],
        'total_count':
        res['metadata'][0]['total'] if res['metadata'] else 0,
        'resources_dict':
        resource_manager.resources_dict,
        'status':
        'success'
    })
Example #20
0
File: user.py Project: rbax/plynx
def post_demo_user():
    user = demo_user_manager.create_demo_user()
    if not user:
        return make_fail_response('Failed to create a demo user')

    template_id = DemoUserManager.demo_config.kind
    if DemoUserManager.demo_config.template_id:
        try:
            node_id = to_object_id(DemoUserManager.demo_config.template_id)
        except Exception as e:
            app.logger.error('node_id `{}` is invalid'.format(
                DemoUserManager.demo_config.template_id))
            app.logger.error(e)
            return make_fail_response('Failed to create a demo node')
        try:
            user_id = user._id
            node = template_collection_manager.get_db_node(node_id, user_id)
            node = get_class(node['_type'])(node).clone(
                NodeClonePolicy.NODE_TO_NODE)
            node.author = user_id
            node.save()
            template_id = node._id
        except Exception as e:
            app.logger.error('Failed to create a demo node')
            app.logger.error(e)
            return make_fail_response(str(e)), 500

    access_token = user.generate_access_token(expiration=1800)
    user_obj = user.to_dict()
    user_obj['hash_password'] = ''
    return JSONEncoder().encode({
        'access_token':
        access_token.decode('ascii'),
        'refresh_token':
        'Not assigned',
        'user':
        user_obj,
        'url':
        '/{}/{}'.format(Collections.TEMPLATES, template_id),
    })
Example #21
0
def upload_file():
    assert len(request.files) == 1
    title = request.form.get('title', '{title}')
    description = request.form.get('description', '{description}')
    file_type = request.form.get('file_type', FileCls.NAME)
    if file_type not in RESOURCE_TYPES:
        return make_fail_response(
            'Unknown file type `{}`'.format(file_type)), 400

    resource_id = upload_file_stream(request.files['data'])
    file = FileNodeClass.get_default()
    file.author = g.user._id
    file.title = title
    file.description = description
    file.outputs[0].resource_id = resource_id
    file.outputs[0].file_type = file_type
    file.save()

    return JSONEncoder().encode({
        'status': ResourcePostStatus.SUCCESS,
        'resource_id': resource_id,
        'node': file.to_dict(),
    })
Example #22
0
def post_group():
    app.logger.debug(request.data)

    data = json.loads(request.data)

    group = Group.from_dict(data['group'])
    group.author = g.user._id
    db_group = node_collection_managers[Collections.GROUPS].get_db_object(
        group._id, g.user._id)
    action = data['action']
    if db_group and db_group[
            '_readonly'] and action not in PERMITTED_READONLY_POST_ACTIONS:
        return make_fail_response('Permission denied'), 403

    if action == NodePostAction.SAVE:
        group.save(force=True)

    return JSONEncoder().encode({
        'status':
        NodePostStatus.SUCCESS,
        'message':
        'Group(_id=`{}`) successfully updated'.format(str(group._id))
    })
Example #23
0
def post_search_nodes(collection):
    query = json.loads(request.data)
    app.logger.debug(request.data)

    query['user_id'] = to_object_id(g.user._id)

    virtual_collection = query.pop('virtual_collection', None)

    if len(query.keys() - PAGINATION_QUERY_KEYS):
        return make_fail_response(
            'Unknown keys: `{}`'.format(query.keys() -
                                        PAGINATION_QUERY_KEYS)), 400

    if collection == 'in_hubs':
        hub = query.pop('hub')
        res = hub_manager.kind_to_hub_class[hub].search(
            plynx.base.hub.Query(**query))
    else:
        if virtual_collection == NodeVirtualCollection.OPERATIONS:
            query['node_kinds'] = list(
                operation_manager.kind_to_operation_dict.keys())
        elif virtual_collection == NodeVirtualCollection.WORKFLOWS:
            query['node_kinds'] = list(
                workflow_manager.kind_to_workflow_dict.keys())
        res = node_collection_managers[collection].get_db_objects(**query)

    return JSONEncoder().encode({
        'items':
        res['list'],
        'total_count':
        res['metadata'][0]['total'] if res['metadata'] else 0,
        'plugins_dict':
        PLUGINS_DICT,
        'status':
        'success'
    })
Example #24
0
def post_node():
    app.logger.debug(request.data)
    try:
        body = json.loads(request.data)['body']

        node = Node.from_dict(body['node'])
        node.author = g.user._id

        action = body['action']
        if action == NodePostAction.SAVE:
            if node.node_status != NodeStatus.CREATED and node.base_node_name != 'file':
                return _make_fail_response('Cannot save node with status `{}`'.format(node.node_status))

            node.save(force=True)

        elif action == NodePostAction.APPROVE:
            if node.node_status != NodeStatus.CREATED:
                return _make_fail_response('Node status `{}` expected. Found `{}`'.format(NodeStatus.CREATED, node.node_status))
            validation_error = node.get_validation_error()
            if validation_error:
                return JSONEncoder().encode({
                    'status': NodePostStatus.VALIDATION_FAILED,
                    'message': 'Node validation failed',
                    'validation_error': validation_error.to_dict()
                })

            node.node_status = NodeStatus.READY
            node.save(force=True)

        elif action == NodePostAction.VALIDATE:
            validation_error = node.get_validation_error()

            if validation_error:
                return JSONEncoder().encode({
                    'status': NodePostStatus.VALIDATION_FAILED,
                    'message': 'Node validation failed',
                    'validation_error': validation_error.to_dict()
                })
        elif action == NodePostAction.DEPRECATE:
            if node.node_status == NodeStatus.CREATED:
                return _make_fail_response('Node status `{}` not expected.'.format(node.node_status))

            node.node_status = NodeStatus.DEPRECATED
            node.save(force=True)
        elif action == NodePostAction.MANDATORY_DEPRECATE:
            if node.node_status == NodeStatus.CREATED:
                return _make_fail_response('Node status `{}` not expected.'.format(node.node_status))

            node.node_status = NodeStatus.MANDATORY_DEPRECATED
            node.save(force=True)
        elif action == NodePostAction.PREVIEW_CMD:
            job = node_collection.make_job(node)

            return JSONEncoder().encode(
                {
                    'status': NodePostStatus.SUCCESS,
                    'message': 'Successfully created preview',
                    'preview_text': job.run(preview=True)
                })

        else:
            return _make_fail_response('Unknown action `{}`'.format(action))

        return JSONEncoder().encode(
            {
                'status': NodePostStatus.SUCCESS,
                'message': 'Node(_id=`{}`) successfully updated'.format(str(node._id))
            })
    except Exception as e:
        app.logger.error(e)
        return _make_fail_response('Internal error: "{}"'.format(str(e)))
Example #25
0
def _make_fail_response(message):
    return JSONEncoder().encode({
        'status': ResourcePostStatus.FAILED,
        'message': message
    })
Example #26
0
def post_graph():
    app.logger.debug(request.data)
    try:
        body = json.loads(request.data)['body']

        graph = Graph.from_dict(body['graph'])
        graph.author = g.user._id
        actions = body['actions']
        extra_response = {}

        for action in actions:
            if action == GraphPostAction.SAVE:
                if graph.graph_running_status != GraphRunningStatus.CREATED:
                    return _make_fail_response('Cannot save graph with status `{}`'.format(graph.graph_running_status))
                graph.save(force=True)

            elif action == GraphPostAction.AUTO_LAYOUT:
                graph.arrange_auto_layout()

            elif action == GraphPostAction.UPGRADE_NODES:
                upd = graph_collection_manager.upgrade_nodes(graph)
                extra_response['upgraded_nodes_count'] = upd

            elif action == GraphPostAction.APPROVE:
                if graph.graph_running_status != GraphRunningStatus.CREATED:
                    return _make_fail_response('Graph status `{}` expected. Found `{}`'.format(GraphRunningStatus.CREATED, graph.graph_running_status))

                validation_error = graph.get_validation_error()
                if validation_error:
                    return JSONEncoder().encode({
                        'status': GraphPostStatus.VALIDATION_FAILED,
                        'message': 'Graph validation failed',
                        'validation_error': validation_error.to_dict()
                    })

                graph.graph_running_status = GraphRunningStatus.READY
                graph.save(force=True)

            elif action == GraphPostAction.VALIDATE:
                validation_error = graph.get_validation_error()

                if validation_error:
                    return JSONEncoder().encode({
                        'status': GraphPostStatus.VALIDATION_FAILED,
                        'message': 'Graph validation failed',
                        'validation_error': validation_error.to_dict()
                    })
            elif action == GraphPostAction.CANCEL:
                if graph.graph_running_status not in [
                        GraphRunningStatus.RUNNING,
                        GraphRunningStatus.FAILED_WAITING
                        ]:
                    return _make_fail_response('Graph status `{}` expected. Found `{}`'.format(GraphRunningStatus.RUNNING, graph.graph_running_status))
                graph_cancellation_manager.cancel_graph(graph._id)
            else:
                return _make_fail_response('Unknown action `{}`'.format(action))

        return JSONEncoder().encode(dict(
            {
                'status': GraphPostStatus.SUCCESS,
                'message': 'Graph(_id=`{}`) successfully updated'.format(str(graph._id)),
                'graph': graph.to_dict(),
                'url': '{}/graphs/{}'.format(WEB_CONFIG.endpoint.rstrip('/'), str(graph._id))
            }, **extra_response))
    except Exception as e:
        app.logger.error(traceback.format_exc())
        return _make_fail_response('Internal error: "{}"'.format(repr(e)))
Example #27
0
def post_resource():
    resource_id = upload_file_stream(request.files['data'])
    return JSONEncoder().encode({
        'status': ResourcePostStatus.SUCCESS,
        'resource_id': resource_id
    })
Example #28
0
def post_node():
    app.logger.debug(request.data)

    data = json.loads(request.data)

    node = Node.from_dict(data['node'])
    node.author = g.user._id
    node.starred = False
    db_node = node_collection_manager.get_db_node(node._id, g.user._id)
    action = data['action']
    if db_node and db_node[
            '_readonly'] and action not in PERMITTED_READONLY_POST_ACTIONS:
        return make_fail_response('Permission denied'), 403

    if action == NodePostAction.SAVE:
        if node.node_status != NodeStatus.CREATED and node.base_node_name != 'file':
            return make_fail_response(
                'Cannot save node with status `{}`'.format(node.node_status))

        node.save(force=True)

    elif action == NodePostAction.APPROVE:
        if node.node_status != NodeStatus.CREATED:
            return make_fail_response(
                'Node status `{}` expected. Found `{}`'.format(
                    NodeStatus.CREATED, node.node_status))
        validation_error = node.get_validation_error()
        if validation_error:
            return JSONEncoder().encode({
                'status':
                NodePostStatus.VALIDATION_FAILED,
                'message':
                'Node validation failed',
                'validation_error':
                validation_error.to_dict()
            })

        node.node_status = NodeStatus.READY
        node.save(force=True)

    elif action == NodePostAction.VALIDATE:
        validation_error = node.get_validation_error()

        if validation_error:
            return JSONEncoder().encode({
                'status':
                NodePostStatus.VALIDATION_FAILED,
                'message':
                'Node validation failed',
                'validation_error':
                validation_error.to_dict()
            })
    elif action == NodePostAction.DEPRECATE:
        if node.node_status == NodeStatus.CREATED:
            return make_fail_response('Node status `{}` not expected.'.format(
                node.node_status))

        node.node_status = NodeStatus.DEPRECATED
        node.save(force=True)
    elif action == NodePostAction.MANDATORY_DEPRECATE:
        if node.node_status == NodeStatus.CREATED:
            return make_fail_response('Node status `{}` not expected.'.format(
                node.node_status))

        node.node_status = NodeStatus.MANDATORY_DEPRECATED
        node.save(force=True)
    elif action == NodePostAction.PREVIEW_CMD:
        job = node_collection.make_job(node)

        return JSONEncoder().encode({
            'status': NodePostStatus.SUCCESS,
            'message': 'Successfully created preview',
            'preview_text': job.run(preview=True)
        })

    else:
        return make_fail_response('Unknown action `{}`'.format(action))

    return JSONEncoder().encode({
        'status':
        NodePostStatus.SUCCESS,
        'message':
        'Node(_id=`{}`) successfully updated'.format(str(node._id))
    })
Example #29
0
def post_node(collection):
    app.logger.debug(request.data)

    data = json.loads(request.data)

    node = Node.from_dict(data['node'])
    node.author = g.user._id
    node.starred = False
    db_node = node_collection_managers[collection].get_db_node(
        node._id, g.user._id)
    action = data['action']
    if db_node and db_node[
            '_readonly'] and action not in PERMITTED_READONLY_POST_ACTIONS:
        return make_fail_response('Permission denied'), 403

    if action == NodePostAction.SAVE:
        if node.node_status != NodeStatus.CREATED and node.base_node_name != 'file':
            return make_fail_response(
                'Cannot save node with status `{}`'.format(node.node_status))

        node.save(force=True)

    elif action == NodePostAction.APPROVE:
        if node.node_status != NodeStatus.CREATED:
            return make_fail_response(
                'Node status `{}` expected. Found `{}`'.format(
                    NodeStatus.CREATED, node.node_status))
        validation_error = executor_manager.kind_to_executor_class[node.kind](
            node).validate()
        if validation_error:
            return JSONEncoder().encode({
                'status':
                NodePostStatus.VALIDATION_FAILED,
                'message':
                'Node validation failed',
                'validation_error':
                validation_error.to_dict()
            })

        node.node_status = NodeStatus.READY
        node.save(force=True)

    elif action == NodePostAction.CREATE_RUN:
        if node.node_status != NodeStatus.CREATED:
            return make_fail_response(
                'Node status `{}` expected. Found `{}`'.format(
                    NodeStatus.CREATED, node.node_status))
        validation_error = executor_manager.kind_to_executor_class[node.kind](
            node).validate()
        if validation_error:
            return JSONEncoder().encode({
                'status':
                NodePostStatus.VALIDATION_FAILED,
                'message':
                'Node validation failed',
                'validation_error':
                validation_error.to_dict()
            })

        node = node.clone(NodeClonePolicy.NODE_TO_RUN)
        node.save(collection=Collections.RUNS)
        return JSONEncoder().encode({
            'status':
            NodePostStatus.SUCCESS,
            'message':
            'Run(_id=`{}`) successfully created'.format(str(node._id)),
            'run_id':
            str(node._id),
            'url':
            '/{}/{}'.format(Collections.RUNS, node._id),
        })

    elif action == NodePostAction.CLONE:
        node_clone_policy = None
        if collection == Collections.TEMPLATES:
            node_clone_policy = NodeClonePolicy.NODE_TO_NODE
        elif collection == Collections.RUNS:
            node_clone_policy = NodeClonePolicy.RUN_TO_NODE

        node = node.clone(node_clone_policy)
        node.save(collection=Collections.TEMPLATES)

        return JSONEncoder().encode({
            'status':
            NodePostStatus.SUCCESS,
            'message':
            'Node(_id=`{}`) successfully created'.format(str(node._id)),
            'node_id':
            str(node._id),
            'url':
            '/{}/{}'.format(Collections.TEMPLATES, node._id),
        })

    elif action == NodePostAction.VALIDATE:
        validation_error = executor_manager.kind_to_executor_class[node.kind](
            node).validate()

        if validation_error:
            return JSONEncoder().encode({
                'status':
                NodePostStatus.VALIDATION_FAILED,
                'message':
                'Node validation failed',
                'validation_error':
                validation_error.to_dict()
            })
    elif action == NodePostAction.DEPRECATE:
        if node.node_status == NodeStatus.CREATED:
            return make_fail_response('Node status `{}` not expected.'.format(
                node.node_status))

        node.node_status = NodeStatus.DEPRECATED
        node.save(force=True)
    elif action == NodePostAction.MANDATORY_DEPRECATE:
        if node.node_status == NodeStatus.CREATED:
            return make_fail_response('Node status `{}` not expected.'.format(
                node.node_status))

        node.node_status = NodeStatus.MANDATORY_DEPRECATED
        node.save(force=True)
    elif action == NodePostAction.PREVIEW_CMD:

        return JSONEncoder().encode({
            'status':
            NodePostStatus.SUCCESS,
            'message':
            'Successfully created preview',
            'preview_text':
            executor_manager.kind_to_executor_class[node.kind](node).run(
                preview=True)
        })

    elif action == NodePostAction.REARRANGE_NODES:
        node.arrange_auto_layout()
        return JSONEncoder().encode(
            dict({
                'status': NodePostStatus.SUCCESS,
                'message': 'Successfully created preview',
                'node': node.to_dict(),
            }))
    elif action == NodePostAction.UPGRADE_NODES:
        upd = node_collection_managers[collection].upgrade_sub_nodes(node)
        return JSONEncoder().encode(
            dict({
                'status': NodePostStatus.SUCCESS,
                'message': 'Successfully updated nodes',
                'node': node.to_dict(),
                'upgraded_nodes_count': upd,
            }))
    elif action == NodePostAction.CANCEL:
        run_cancellation_manager.cancel_run(node._id)
    elif action == NodePostAction.GENERATE_CODE:
        raise NotImplementedError()
    else:
        return make_fail_response('Unknown action `{}`'.format(action))

    return JSONEncoder().encode({
        'status':
        NodePostStatus.SUCCESS,
        'message':
        'Node(_id=`{}`) successfully updated'.format(str(node._id))
    })
Example #30
0
File: common.py Project: rbax/plynx
def make_fail_response(message, **kwargs):
    return JSONEncoder().encode({
        'status': ResponseStatus.FAILED,
        'message': message,
        **kwargs
    })