Example #1
0
    def list(self, request):
        try:
            # filter instances which assigned to users
            udc_id = request.session["UDC_ID"]
            if request.user.is_superuser:
                serializer = InstanceSerializer(self.queryset, many=True)
                return Response(serializer.data)
            """
            system = False
            security = False
            audit = False
            member = False
            UDC = UserDataCenter.objects.get(pk=udc_id)
            LOG.info(UDC)
            LOG.info("4")
            keystone_user_id = UDC.keystone_user_id
            LOG.info("4")
            tenant_uuid = UDC.tenant_uuid
            LOG.info("4")
            rc = create_rc_by_dc(DataCenter.objects.all()[0])
            LOG.info("4")
            user_roles = keystone.roles_for_user(rc, keystone_user_id, tenant_uuid)
            LOG.info("4")
            for user_role in user_roles:
                LOG.info("5")
                LOG.info(user_role.name)
                if user_role.name == "system":
                    LOG.info("5")
                    system = True
                    break
                if user_role.name == "security":
                    security = True
                    break
                if user_role.name == "audit":
                    audit = True
                    break

                if not system and not security and not audit:
                    member = True
            if system or security or audit:
                LOG.info("*** system user ***" + str(system))
                serializer = InstanceSerializer(self.queryset, many=True)
                return Response(serializer.data)
            """
            serializer = InstanceSerializer(self.queryset, many=True)
            return Response(serializer.data)
            queryset = self.get_queryset().filter(user=request.user)
            serializer = self.serializer_class(queryset, many=True)
            #serializer = self.serializer_class(self.get_queryset(), many=True)
            LOG.info("********* serializer.data is ********" +
                     str(serializer.data))
            return Response(serializer.data)
        except Exception as e:
            LOG.exception(e)
            return Response()
Example #2
0
    def list(self, request):
        try:
            udc_id = request.session["UDC_ID"]
            if request.user.is_superuser:
                serializer = InstanceSerializer(queryset, many=True)
                return Response(serializer.data)

            system = False
            security = False
            audit = False
            member = False
            UDC = UserDataCenter.objects.get(pk=udc_id)
            LOG.info(UDC)
            LOG.info("4")
            keystone_user_id = UDC.keystone_user_id
            LOG.info("4")
            tenant_uuid = UDC.tenant_uuid
            LOG.info("4")
            rc = create_rc_by_dc(DataCenter.objects.all()[0])
            LOG.info("4")
            user_roles = keystone.roles_for_user(rc, keystone_user_id,
                                                 tenant_uuid)
            LOG.info("4")
            for user_role in user_roles:
                LOG.info("5")
                LOG.info(user_role.name)
                if user_role.name == "system":
                    LOG.info("5")
                    system = True
                    break
                if user_role.name == "security":
                    security = True
                    break
                if user_role.name == "audit":
                    audit = True
                    break

                if not system and not security and not audit:
                    member = True
            if request.user.is_superuser or system:
                serializer = InstanceSerializer(queryset, many=True)
                return Response(serializer.data)

            UDC = UserDataCenter.objects.all().filter(user=request.user)[0]
            project_id = UDC.tenant_uuid
            queryset = self.get_queryset().filter(
                Q(user=request.user, user_data_center__pk=udc_id)
                | Q(tenant_uuid=project_id) | Q(assigneduser=request.user))
            serializer = InstanceSerializer(queryset, many=True)
            return Response(serializer.data)
        except Exception as e:
            LOG.exception(e)
            return Response()
Example #3
0
def instance_detail_view(request, pk):
    tag = request.GET.get("tag", 'instance_detail')
    try:
        instance = Instance.objects.get(pk=pk, user=request.user)
    except Exception as e:
        LOG.error("Get instance error, msg:%s" % e)
        return Response({"OPERATION_STATUS": 0, "MSG": "Instance no exist"}, status=status.HTTP_200_OK)

    if "instance_detail" == tag:
        instance_data = dict(InstanceSerializer(instance).data)

        try:
            server = instance_get(instance)
            instance_data['host'] = getattr(server, 'OS-EXT-SRV-ATTR:host', None)
            instance_data['instance_name'] = getattr(server, 'OS-EXT-SRV-ATTR:instance_name', None)
        except Exception as e:
            LOG.error("Obtain host fail,msg: %s" % e)

        try:
            firewall = Firewall.objects.get(pk=instance.firewall_group.id)
            firewall_data = FirewallSerializer(firewall).data
            instance_data['firewall'] = firewall_data
        except Exception as e:
            LOG.exception("Obtain firewall fail, msg:%s" % e)

        # 挂载的所有硬盘
        volume_set = Volume.objects.filter(instance=instance, deleted=False)
        volume_data = VolumeSerializer(volume_set, many=True).data
        instance_data['volume_list'] = volume_data
        return Response(instance_data)
    elif 'instance_log' == tag:
        log_data = instance_get_console_log(instance)
        return Response(log_data)
Example #4
0
def _get_instance_detail(instance):

    instance_data = InstanceSerializer(instance).data

    try:
        server = instance_get(instance)
        instance_data['host'] = getattr(server, 'OS-EXT-SRV-ATTR:host', None)
        instance_data['instance_name'] = getattr(
            server, 'OS-EXT-SRV-ATTR:instance_name', None)
        instance_data['fault'] = getattr(server, 'fault', None)

    except Exception as e:
        LOG.error("Obtain host fail,msg: %s" % e)

    try:
        firewall = Firewall.objects.get(pk=instance.firewall_group.id)
        firewall_data = FirewallSerializer(firewall).data
        instance_data['firewall'] = firewall_data
    except Exception as e:
        LOG.exception("Obtain firewall fail, msg:%s" % e)

    # 挂载的所有硬盘
    volume_set = Volume.objects.filter(instance=instance, deleted=False)
    volume_data = VolumeSerializer(volume_set, many=True).data
    instance_data['volume_list'] = volume_data

    return Response(instance_data)
Example #5
0
class BalancerMemberSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(),
                                              required=False,
                                              allow_null=True,
                                              default=None)
    user_data_center = serializers.PrimaryKeyRelatedField(
        queryset=UserDataCenter.objects.all(),
        required=False,
        allow_null=True,
        default=None)
    create_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M",
                                            required=False,
                                            allow_null=True)

    instance_info = InstanceSerializer(source="instance",
                                       required=False,
                                       allow_null=True,
                                       default=None,
                                       read_only=True)

    def validate_user(self, value):
        request = self.context.get('request', None)
        return request.user

    def validate_user_data_center(self, value):
        request = self.context.get('request', None)
        return UserDataCenter.objects.get(pk=request.session["UDC_ID"])

    class Meta:
        model = BalancerMember
Example #6
0
def qos_get_instance_detail(instance):
    instance_data = InstanceSerializer(instance).data

    try:
        server = instance_get(instance)
        instance_data['host'] = getattr(server, 'OS-EXT-SRV-ATTR:host', None)
        instance_data['instance_name'] = getattr(
            server, 'OS-EXT-SRV-ATTR:instance_name', None)
    except Exception as e:
        LOG.error("Obtain host fail,msg: %s" % e)
    try:
        ports = instance_get_port(instance)
        if ports:
            instance_data['port'] = ports[0].port_id
        else:
            instance_data['port'] = False
    except Exception as e:
        LOG.error("Obtain instance port fail,msg: %s" % e)

    try:
        from biz.floating.models import Floating
        floating = Floating.get_instance_ip(instance.id)
        if floating:
            instance_data["bandwidth"] = floating.bandwidth
        else:
            instance_data["bandwidth"] = settings.DEFAULT_BANDWIDTH
    except Exception as e:
        LOG.error("Obtain instance bandwidth fail,msg: %s" % e)

    return instance_data
Example #7
0
def instance_search_view(request):
    instance_set = Instance.objects.filter(
        deleted=False,
        user=request.user,
        status=INSTANCE_STATE_RUNNING,
        user_data_center=request.session["UDC_ID"])
    serializer = InstanceSerializer(instance_set, many=True)
    return Response(serializer.data)
Example #8
0
def instance_search_view(request):

    UDC = UserDataCenter.objects.all().filter(user=request.user)[0]
    project_id = UDC.tenant_uuid
    instance_set = Instance.objects.filter(Q(deleted=False, user=request.user, status=INSTANCE_STATE_RUNNING,
        user_data_center=request.session["UDC_ID"]) | Q(tenant_uuid=project_id))
    serializer = InstanceSerializer(instance_set, many=True)
    return Response(serializer.data)
Example #9
0
def instance_create_view(request):
    count = request.DATA.get("instance", u"1")
    try:
        count = int(count)
    except:
        count = 1

    pay_type = request.data['pay_type']
    pay_num = int(request.data['pay_num'])

    if count > settings.BATCH_INSTANCE:
        return Response({"OPERATION_STATUS": OPERATION_FAILED},
                    status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE)

    network_id = request.DATA.get("network_id", u"0")
    try:
        network = Network.objects.get(pk=network_id)
    except Network.DoesNotExist:
        pass
    else:
        if not network.router:
            msg = _("Your selected network has not linked to any router.")
            return Response({"OPERATION_STATUS": OPERATION_FAILED,
                            "msg": msg}, status=status.HTTP_409_CONFLICT)

    has_error, msg = False, None
    for i in range(count):
        serializer = InstanceSerializer(data=request.data, context={"request": request}) 
        if serializer.is_valid():
            name = request.DATA.get("name", "Server")
            if i > 0:
                name = "%s-%04d" % (name, i)
            ins = serializer.save(name=name)

            Operation.log(ins, obj_name=ins.name, action="launch", result=1)
            workflow = Workflow.get_default(ResourceType.INSTANCE)

            if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:
                ins.status = INSTANCE_STATE_APPLYING
                ins.save()

                FlowInstance.create(ins, request.user, workflow, request.DATA['password'])
                msg = _("Your application for instance \"%(instance_name)s\" is successful, "
                        "please waiting for approval result!") % {'instance_name': ins.name}
            else:
                instance_create_task.delay(ins, password=request.DATA["password"])
                Order.for_instance(ins, pay_type=pay_type, pay_num=pay_num)
                msg = _("Your instance is created, please wait for instance booting.")
        else:
            has_error = True
            break

    if has_error: 
        return Response({"OPERATION_STATUS": OPERATION_FAILED},
                        status=status.HTTP_400_BAD_REQUEST) 
    else:
        return Response({"OPERATION_STATUS": OPERATION_SUCCESS,
                          "msg": msg}, status=status.HTTP_201_CREATED)
Example #10
0
 def get(self, request, *args, **kwargs):
     try:
         obj = self.get_object()
         if obj and obj.user == request.user:
             serializer = InstanceSerializer(obj)
             return Response(serializer.data)
         else:
             raise
     except Exception as e:
         return Response(status=status.HTTP_404_NOT_FOUND)
Example #11
0
 def list(self, request):
     try:
         udc_id = request.session["UDC_ID"]
         queryset = self.get_queryset().filter(
                         user=request.user,
                         user_data_center__pk=udc_id)
         serializer = InstanceSerializer(queryset, many=True)
         return Response(serializer.data)
     except Exception as e:
         return Response()
Example #12
0
def network_topology_data_view(request):
    routers = Router.objects.filter(deleted=False,  user=request.user, user_data_center=request.session["UDC_ID"])

    router_interface = RouterInterface.objects.filter(deleted=False, user=request.user, user_data_center=request.session["UDC_ID"])
    networks = Network.objects.filter(deleted=False,  user=request.user, user_data_center=request.session["UDC_ID"])
    instances = Instance.objects.filter(deleted=False,  user=request.user, user_data_center=request.session["UDC_ID"])
    network_data = dict()
    network_data['routers'] = RouterSerializer(routers, many=True).data
    network_data['networks'] = NetworkSerializer(networks, many=True).data
    network_data['router_interfaces'] = RouterInterfaceSerializer(router_interface, many=True).data
    network_data['instances'] = InstanceSerializer(instances, many=True).data
    return Response(network_data)
Example #13
0
 def list(self, request):
     try:
         udc_id = request.session["UDC_ID"]
         UDC = UserDataCenter.objects.all().filter(user=request.user)[0]
         project_id = UDC.tenant_uuid
         queryset = self.get_queryset().filter(
             Q(user=request.user, user_data_center__pk=udc_id) | Q(tenant_uuid=project_id))
         serializer = InstanceSerializer(queryset, many=True)
         return Response(serializer.data)
     except Exception as e:
         LOG.exception(e)
         return Response()
Example #14
0
def batch_create(request, user_id):
    LOG.info("** user_id is ***" + str(user_id))
    user_data_center = UserDataCenter.objects.filter(
        user__id=request.user.id)[0]
    LOG.info("*** user_data_center ***" + str(user_data_center))
    user_tenant_uuid = user_data_center.tenant_uuid
    LOG.info("*** user_tenant_uuid is ***" + str(user_tenant_uuid))

    pay_type = request.data['pay_type']
    pay_num = int(request.data['pay_num'])

    network_id = request.DATA.get("network_id", u"0")
    try:
        network = Network.objects.get(pk=network_id)
    except Network.DoesNotExist:
        pass
    else:
        # VLAN mode: we do not have to add router to network.
        if settings.VLAN_ENABLED == False:
            if not network.router:
                msg = _("Your selected network has not linked to any router.")
                return Response(
                    {
                        "OPERATION_STATUS": OPERATION_FAILED,
                        "msg": msg
                    },
                    status=status.HTTP_409_CONFLICT)
    has_error, msg = False, None
    user = User.objects.all().get(id=user_id)
    username = user.username
    serializer = InstanceSerializer(data=request.data,
                                    context={"request": request})
    if serializer.is_valid():
        name = request.DATA.get("name", "Server")
        name = "%s-%s" % (name, username)
        #name = "%s-%04d" % (name, i)
        LOG.info(name)
        ins = serializer.save(name=name, assigneduser=user)
        Operation.log(ins, obj_name=ins.name, action="launch", result=1)
        workflow = Workflow.get_default(ResourceType.INSTANCE)
        instance_create_task.delay(ins,
                                   password=request.DATA["password"],
                                   user_tenant_uuid=user_tenant_uuid)
        Order.for_instance(ins, pay_type=pay_type, pay_num=pay_num)

        #msg = _("Your instance is created, please wait for instance booting.")
    else:
        has_error = True
    if has_error:
        return {'name': name, 'user': user_id, 'status': 'failed'}
    else:
        return {'name': name, 'user': user_id, 'status': 'succeed'}
Example #15
0
def instance_search_view(request):
    user_id = request.query_params.get('uid', None)
    LOG.info("*** user_id is ***" + str(user_id))
    LOG.info("*** user_id is ***" + str(request.query_params))
    if not user_id:
        LOG.info(" user_id is none")
        UDC = UserDataCenter.objects.all().filter(user=request.user)[0]
        project_id = UDC.tenant_uuid
        instance_set = Instance.objects.filter(
            Q(deleted=False,
              user=request.user,
              status=INSTANCE_STATE_RUNNING,
              user_data_center=request.session["UDC_ID"])
            | Q(tenant_uuid=project_id))
    else:
        LOG.info("user id is not none")
        instance_set = Instance.objects.filter(deleted=False,
                                               assigneduser_id=user_id)

    serializer = InstanceSerializer(instance_set, many=True)
    return Response(serializer.data)
Example #16
0
def instance_create_view(request):
    serializer = InstanceSerializer(data=request.data, context={"request": request}) 
    if serializer.is_valid():
        ins = serializer.save()

        Operation.log(ins, obj_name=ins.name, action="launch", result=1)

        workflow = Workflow.get_default(ResourceType.INSTANCE)

        if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:
            ins.status = INSTANCE_STATE_APPLYING
            ins.save()

            FlowInstance.create(ins, request.user, workflow, request.DATA['password'])
            msg = _("Your application for instance \"%(instance_name)s\" is successful, "
                    "please waiting for approval result!") % {'instance_name': ins.name}
        else:
            instance_create_task.delay(ins, password=request.DATA["password"])
            msg = _("Your instance is created, please wait for instance booting.")
        return Response({"OPERATION_STATUS": 1,
                         "msg": msg}, status=status.HTTP_201_CREATED)
    else:
        return Response({"OPERATION_STATUS": 0}, status=status.HTTP_400_BAD_REQUEST)