Exemplo n.º 1
0
Arquivo: views.py Projeto: yeasy/cello
    def destroy(self, request, pk=None):
        """
        Delete agent

        :param request: destory parameter
        :param pk: primary key
        :return: none
        :rtype: rest_framework.status
        """
        try:
            try:
                if request.user.is_administrator:
                    agent = Agent.objects.get(id=pk)
                else:
                    raise CustomError("User can't delete agent!")
            except ObjectDoesNotExist:
                raise ResourceNotFound
            else:
                if agent.node.count():
                    raise ResourceInUse
                agent.delete()

                return Response(ok(None), status=status.HTTP_202_ACCEPTED)
        except (ResourceNotFound, ResourceInUse) as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 2
0
Arquivo: views.py Projeto: yeasy/cello
    def release(self, request, pk=None):
        """
        Release Agent

        Release Agent
        """
        try:
            try:
                if request.user.is_operator:
                    agent = Agent.objects.get(id=pk)
                else:
                    if request.user.organization is None:
                        raise CustomError("Need join in organization")
                    agent = Agent.objects.get(
                        id=pk, organization=request.user.organization)
            except ObjectDoesNotExist:
                raise ResourceNotFound
            else:
                agent.organization = None
                agent.save()

                return Response(ok(None), status=status.HTTP_204_NO_CONTENT)
        except ResourceNotFound as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 3
0
Arquivo: views.py Projeto: yeasy/cello
    def partial_update(self, request, pk=None):
        """
        Partial Update Agent

        Partial update special agent with id.
        """
        try:
            serializer = AgentPatchBody(data=request.data)
            if serializer.is_valid(raise_exception=True):
                name = serializer.validated_data.get("name")
                capacity = serializer.validated_data.get("capacity")
                log_level = serializer.validated_data.get("log_level")
                try:
                    agent = Agent.objects.get(id=pk)
                except ObjectDoesNotExist:
                    raise ResourceNotFound
                else:
                    if name:
                        agent.name = name
                    if capacity:
                        agent.capacity = capacity
                    if log_level:
                        agent.log_level = log_level
                    agent.save()

                    return Response(ok(None), status=status.HTTP_202_ACCEPTED)
        except ResourceNotFound as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 4
0
Arquivo: views.py Projeto: yeasy/cello
    def retrieve(self, request, pk=None):
        """
        Retrieve agent

        :param request: destory parameter
        :param pk: primary key
        :return: none
        :rtype: rest_framework.status
        """
        try:
            if request.user.is_operator:
                agent = Agent.objects.get(id=pk)
            else:
                agent = Agent.objects.get(
                    id=pk, organization=request.user.organization)
            k8s_config = None
            if agent.type == HostType.Kubernetes.name.lower():
                k8s_config = KubernetesConfig.objects.get(agent=agent)
        except ObjectDoesNotExist:
            raise ResourceNotFound
        else:
            data = agent.__dict__
            if k8s_config:
                data.update({"k8s_config": k8s_config.__dict__})
            response = AgentInfoSerializer(data=data)
            if response.is_valid(raise_exception=True):
                return Response(ok(response.validated_data),
                                status=status.HTTP_200_OK)
Exemplo n.º 5
0
Arquivo: views.py Projeto: yeasy/cello
    def create(self, request):
        """
        Create Node

        :param request: create parameter
        :return: node ID
        :rtype: uuid
        """
        try:
            serializer = NodeCreateBody(data=request.data)
            if serializer.is_valid(raise_exception=True):
                node_name = serializer.validated_data.get("name")
                node_type = serializer.validated_data.get("type")
                num = serializer.validated_data.get("num")
                organization = request.user.organization

                agent = organization.agent.get()
                if agent:
                    nodes = Node.objects.filter(name=node_name + "0",
                                                organization=organization,
                                                type=node_type)
                    if nodes:
                        raise ResourceExists
                else:
                    raise NoResource
                for n in range(num):

                    name = node_name + str(n)

                    urls = "http://{}.{}".format(name, organization.name)
                    nodes = {"type": node_type, "Specs": [name]}
                    CryptoConfig(organization.name).update(nodes)
                    CryptoGen(organization.name).extend()
                    self._generate_config(node_type, organization.name, name)
                    msp, tls, cfg = self._conversion_msp_tls_cfg(
                        node_type, organization.name, name)

                    node = Node(name=name,
                                organization=organization,
                                urls=urls,
                                type=node_type,
                                msp=msp,
                                tls=tls,
                                agent=agent,
                                config_file=cfg)
                    node.save()

                    self._set_port(node_type, node, agent)

                response = NodeIDSerializer(data=node.__dict__)
                if response.is_valid(raise_exception=True):
                    return Response(ok(response.validated_data),
                                    status=status.HTTP_201_CREATED)
        except (ResourceExists, NoResource) as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 6
0
 def list(self, request):
     """
     List network
     :param request: query parameter
     :return: network list
     :rtype: list
     """
     try:
         serializer = NetworkQuery(data=request.GET)
         if serializer.is_valid(raise_exception=True):
             page = serializer.validated_data.get("page", 1)
             per_page = serializer.validated_data.get("page", 10)
             org = request.user.organization
             networks = org.network
             if not networks:
                 return Response(ok(data={
                     "total": 0,
                     "data": None
                 }),
                                 status=status.HTTP_200_OK)
             p = Paginator([networks], per_page)
             networks = p.page(page)
             networks = [{
                 "id": network.id,
                 "name": network.name,
                 "created_at": network.created_at,
             } for network in networks]
             response = NetworkListResponse(data={
                 "total": p.count,
                 "data": networks
             })
             if response.is_valid(raise_exception=True):
                 return Response(ok(response.validated_data),
                                 status=status.HTTP_200_OK)
         return Response(ok(data={
             "total": 0,
             "data": None
         }),
                         status=status.HTTP_200_OK)
     except Exception as e:
         return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 7
0
Arquivo: views.py Projeto: yeasy/cello
    def create(self, request):
        """
        Create Agent

        :param request: create parameter
        :return: agent ID
        :rtype: uuid
        """
        try:
            serializer = AgentCreateBody(data=request.data)
            if serializer.is_valid(raise_exception=True):
                name = serializer.validated_data.get("name")
                agent_type = serializer.validated_data.get("type")
                urls = serializer.validated_data.get("urls")
                config_file = serializer.validated_data.get("config_file")

                body = {
                    "type": agent_type,
                    "urls": urls,
                    "name": name,
                }

                if name:
                    agent_count = Agent.objects.filter(name=name).count()
                    if agent_count > 0:
                        raise ResourceExists

                    body.update({"name": name})

                if config_file is not None:
                    body.update({"config_file": config_file})

                org = request.user.organization
                if org.agent.all():
                    raise ResourceExists
                else:
                    body.update({"organization": org})

                agent = Agent(**body)
                agent.save()

                response = AgentIDSerializer(data=agent.__dict__)
                if response.is_valid(raise_exception=True):
                    return Response(ok(response.validated_data),
                                    status=status.HTTP_201_CREATED)
        except ResourceExists as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 8
0
    def destroy(self, request, pk=None):
        """
        Delete Network
        :param request: destory parameter
        :param pk: primary key
        :return: none
        :rtype: rest_framework.status
        """
        try:
            network = Network.objects.get(pk=pk)
            path = "{}/{}".format(CELLO_HOME, network.name)
            if os.path.exists(path):
                shutil.rmtree(path, True)
            network.delete()
            return Response(ok(None), status=status.HTTP_202_ACCEPTED)

        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 9
0
Arquivo: views.py Projeto: yeasy/cello
    def apply(self, request):
        """
        Apply Agent

        Apply Agent
        """
        try:
            serializer = AgentApplySerializer(data=request.data)
            if serializer.is_valid(raise_exception=True):
                agent_type = serializer.validated_data.get("type")
                capacity = serializer.validated_data.get("capacity")

                if request.user.organization is None:
                    raise CustomError(detail="Need join in organization")
                agent_count = Agent.objects.filter(
                    organization=request.user.organization).count()
                if agent_count > 0:
                    raise CustomError(detail="Already applied agent.")

                agents = Agent.objects.filter(
                    organization__isnull=True,
                    type=agent_type,
                    capacity__gte=capacity,
                    schedulable=True,
                ).order_by("capacity")
                if len(agents) == 0:
                    raise NoResource

                agent = agents[0]
                agent.organization = request.user.organization
                agent.save()

                response = AgentIDSerializer(data=agent.__dict__)
                if response.is_valid(raise_exception=True):
                    return Response(ok(response.validated_data),
                                    status=status.HTTP_200_OK)
        except NoResource as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 10
0
Arquivo: views.py Projeto: yeasy/cello
    def destroy(self, request, pk=None):
        """
        Delete Node

        :param request: destory parameter
        :param pk: primary key
        :return: none
        :rtype: rest_framework.status
        """
        try:
            try:
                node = Node.objects.get(id=pk)
                if node.organization.network:
                    raise ResourceInUse
                node.delete()
                # todo delete node from agent
            except ObjectDoesNotExist:
                raise ResourceNotFound

            return Response(ok(None), status=status.HTTP_202_ACCEPTED)
        except (ResourceNotFound, ResourceInUse) as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 11
0
Arquivo: views.py Projeto: yeasy/cello
    def update(self, request, pk=None):
        """
        Update Agent

        Update special agent with id.
        """
        try:
            serializer = AgentUpdateBody(data=request.data)
            if serializer.is_valid(raise_exception=True):
                name = serializer.validated_data.get("name")
                #urls = serializer.validated_data.get("urls")
                #organization = request.user.organization
                try:
                    if Agent.objects.get(name=name):
                        raise ResourceExists
                except ObjectDoesNotExist:
                    pass
                Agent.objects.filter(id=pk).update(name=name)

                return Response(ok(None), status=status.HTTP_202_ACCEPTED)
        except ResourceExists as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 12
0
    def create(self, request):
        """
        Create Network
        :param request: create parameter
        :return: organization ID
        :rtype: uuid
        """
        try:
            serializer = NetworkCreateBody(data=request.data)
            if serializer.is_valid(raise_exception=True):
                name = serializer.validated_data.get("name")
                consensus = serializer.validated_data.get("consensus")
                database = serializer.validated_data.get("database")

                try:
                    if Network.objects.get(name=name):
                        raise ResourceExists
                except ObjectDoesNotExist:
                    pass
                org = request.user.organization
                if org.network:
                    raise ResourceExists

                orderers = []
                peers = []
                orderers.append({"name": org.name, "hosts": []})
                peers.append({"name": org.name, "hosts": []})
                nodes = Node.objects.filter(organization=org)
                for node in nodes:
                    if node.type == "peer":
                        peers[0]["hosts"].append({"name": node.name})
                    elif node.type == "orderer":
                        orderers[0]["hosts"].append({"name": node.name})

                ConfigTX(name).create(consensus=consensus,
                                      orderers=orderers,
                                      peers=peers)
                ConfigTxGen(name).genesis()

                block = self._genesis2base64(name)
                network = Network(name=name,
                                  consensus=consensus,
                                  genesisblock=block)
                network.save()
                org.network = network
                org.save()
                nodes = Node.objects.filter(organization=org)
                for node in nodes:
                    try:
                        threading.Thread(target=self._start_node,
                                         args=(node.id, )).start()
                    except Exception as e:
                        raise e

                response = NetworkIDSerializer(data=network.__dict__)
                if response.is_valid(raise_exception=True):
                    return Response(ok(response.validated_data),
                                    status=status.HTTP_201_CREATED)
        except ResourceExists as e:
            raise e
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 13
0
Arquivo: views.py Projeto: yeasy/cello
    def list(self, request, *args, **kwargs):
        """
        List node

        :param request: query parameter
        :return: node list
        :rtype: list
        """
        try:
            serializer = NodeQuery(data=request.GET)
            if serializer.is_valid(raise_exception=True):
                page = serializer.validated_data.get("page")
                per_page = serializer.validated_data.get("per_page")
                node_type = serializer.validated_data.get("type")
                name = serializer.validated_data.get("name")
                agent_id = serializer.validated_data.get("agent_id")

                # if agent_id is not None and not request.user.is_operator:
                #     raise PermissionDenied
                query_filter = {}

                if node_type:
                    query_filter.update({"type": node_type})
                if name:
                    query_filter.update({"name__icontains": name})
                if request.user.is_administrator:
                    query_filter.update(
                        {"organization": request.user.organization})
                # elif request.user.is_common_user:
                #     query_filter.update({"user": request.user})
                if agent_id:
                    query_filter.update({"agent__id": agent_id})
                nodes = Node.objects.filter(**query_filter)
                p = Paginator(nodes, per_page)
                nodes = p.page(page)
                nodes = [
                    {
                        "id":
                        str(node.id),
                        "name":
                        node.name,
                        "type":
                        node.type,
                        "organization":
                        node.organization,
                        "urls":
                        node.urls,
                        "network":
                        str(node.organization.network.id)
                        if node.organization.network else None,
                        "agents":
                        node.agent if node.agent else None,
                        #"channel": str(node.organization.channel.id) if node.organization.channel else None,
                        "ports":
                        node.port,
                        "created_at":
                        node.created_at,
                    } for node in nodes
                ]

                response = NodeListSerializer({
                    "total": p.count,
                    "data": nodes
                })
                return Response(data=ok(response.data),
                                status=status.HTTP_200_OK)
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)
Exemplo n.º 14
0
Arquivo: views.py Projeto: yeasy/cello
    def list(self, request):
        """
        List Agents

        :param request: query parameter
        :return: agent list
        :rtype: list
        """
        try:
            serializer = AgentQuery(data=request.GET)
            if serializer.is_valid(raise_exception=True):
                page = serializer.validated_data.get("page")
                per_page = serializer.validated_data.get("per_page")
                agent_status = serializer.validated_data.get("status")
                name = serializer.validated_data.get("name")
                agent_type = serializer.validated_data.get("type")
                organization = request.user.organization

                query_filters = {}
                # if organization:
                #     if not request.user.is_operator:
                #         raise PermissionDenied()
                #     query_filters.update({"organization": organization})
                # else:
                #     org_name = (
                #         request.user.organization.name
                #         if request.user.organization
                #         else ""
                #     )
                #     if request.user.is_administrator:
                #         query_filters.update({"organization__name": org_name})
                if name:
                    query_filters.update({"name__icontains": name})
                if agent_status:
                    query_filters.update({"status": agent_status})
                if agent_type:
                    query_filters.update({"type": agent_type})
                if organization:
                    query_filters.update({"organization": organization})

                agents = Agent.objects.filter(**query_filters)
                p = Paginator(agents, per_page)
                agents = p.page(page)
                # agents = [agent.__dict__ for agent in agents]
                agent_list = []
                # for agent in agents:
                #     agent_dict = agent.__dict__
                #     agent_list.append(agent_dict)
                agent_list = [{
                    "id":
                    agent.id,
                    "name":
                    agent.name,
                    "status":
                    agent.status,
                    "type":
                    agent.type,
                    "urls":
                    agent.urls,
                    "organization":
                    str(agent.organization.id) if agent.organization else None,
                    "created_at":
                    agent.created_at,
                } for agent in agents]

                response = AgentListResponse(data={
                    "data": agent_list,
                    "total": p.count
                })
                if response.is_valid(raise_exception=True):
                    return Response(ok(response.validated_data),
                                    status=status.HTTP_200_OK)
        except Exception as e:
            return Response(err(e.args), status=status.HTTP_400_BAD_REQUEST)