Exemple #1
0
def create_view(request):
    floating = Floating.objects.create(
        ip="N/A",
        status=FLOATING_ALLOCATE,
        bandwidth=int(request.POST["bandwidth"]),
        user=request.user,
        user_data_center=UserDataCenter.objects.get(
            pk=request.session["UDC_ID"]))

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

    Operation.log(floating, obj_name=floating.ip, action='allocate', result=1)

    workflow = Workflow.get_default(ResourceType.FLOATING)

    if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:

        floating.status = FLOATING_APPLYING
        floating.save()

        FlowInstance.create(floating, request.user, workflow, None)
        msg = _(
            "Your application for %(bandwidth)d Mbps floating ip is successful, "
            "please waiting for approval result!") % {
                'bandwidth': floating.bandwidth
            }
    else:
        msg = _("Your operation is successful, please wait for allocation.")
        allocate_floating_task.delay(floating)
        Order.for_floating(floating, pay_type, pay_num)

    return Response({"OPERATION_STATUS": 1, 'msg': msg})
Exemple #2
0
def create_view(request):
    floating = Floating.objects.create(
        ip="N/A",
        status=FLOATING_ALLOCATE,
        bandwidth=int(request.POST["bandwidth"]),
        user=request.user,
        user_data_center=UserDataCenter.objects.get(pk=request.session["UDC_ID"])
    )

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

    Operation.log(floating, obj_name=floating.ip, action='allocate', result=1)

    workflow = Workflow.get_default(ResourceType.FLOATING)

    if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:

        floating.status = FLOATING_APPLYING
        floating.save()

        FlowInstance.create(floating, request.user, workflow, None)
        msg = _("Your application for %(bandwidth)d Mbps floating ip is successful, "
                "please waiting for approval result!") % {'bandwidth': floating.bandwidth}
    else:
        msg = _("Your operation is successful, please wait for allocation.")
        allocate_floating_task.delay(floating)
        Order.for_floating(floating, pay_type, pay_num)

    return Response({"OPERATION_STATUS": 1, 'msg': msg})
def volume_delete_task(volume):
    assert volume is not None
    LOG.info('Volume delete start, [%s].', volume)

    begin = datetime.datetime.now()
    if volume_get(volume) is None:
        volume.fake_delete()
        Order.disable_order_and_bills(volume)
        return False

    try:
        rc = create_rc_by_volume(volume)
        cinder.volume_delete(rc, volume.volume_id)
    except Exception:
        end = datetime.datetime.now()
        LOG.exception(
            "Volume delete api call failed, [%s], "
            "apply [%s] seconds.", volume, (end - begin).seconds)
        volume.change_status(VOLUME_STATE_ERROR_DELETING)
        return False
    else:
        end = datetime.datetime.now()
        LOG.info(
            "Volume delete api call succeed, [%s], "
            "apply [%s] seconds.", volume, (end - begin).seconds)
        Order.disable_order_and_bills(volume)

    begin = datetime.datetime.now()
    for count in xrange(settings.MAX_COUNT_SYNC * 2):
        time.sleep(settings.INSTANCE_SYNC_INTERVAL_SECOND)
        try:
            cinder_volume = volume_get(volume)
        except Exception:
            LOG.exception("Volume get api failed, when sync status, [%s].",
                          volume)
            volume.change_status(VOLUME_STATE_ERROR_DELETING)
            return False

        st = cinder_volume.status.upper() if cinder_volume else "None"
        LOG.info(
            'Volume synchronize status when delete, [Count:%s][%s][Status: %s].',
            count, volume, st)

        end = datetime.datetime.now()
        if cinder_volume is None:
            volume.volume_id = None
            volume.fake_delete()
            LOG.info("Volume delete succeed,[%s], apply [%s] seconds.", volume,
                     (end - begin).seconds)
            return True
        elif cinder_volume.status.upper() == 'ERROR_DELETING':
            volume.change_status(VOLUME_STATE_ERROR_DELETING)
            LOG.info("Volume delete failed, [%s], apply [%s] seconds.", volume,
                     (end - begin).seconds)
            return False
    else:
        end = datetime.datetime.now()
        LOG.info("Volume delete timeout, [%s], apply [%s] seconds.", volume,
                 (end - begin).seconds)
        return False
def volume_delete_task(volume):
    assert volume is not None
    LOG.info('Volume delete start, [%s].', volume)

    begin = datetime.datetime.now()
    if volume_get(volume) is None:
        volume.fake_delete()
        Order.disable_order_and_bills(volume)
        return False

    try:
        rc = create_rc_by_volume(volume)
        cinder.volume_delete(rc, volume.volume_id)
    except Exception:
        end = datetime.datetime.now() 
        LOG.exception("Volume delete api call failed, [%s], "
                      "apply [%s] seconds.",
                      volume, (end-begin).seconds)
        volume.change_status(VOLUME_STATE_ERROR_DELETING)
        return False
    else:
        end = datetime.datetime.now() 
        LOG.info("Volume delete api call succeed, [%s], "
                      "apply [%s] seconds.",
                      volume, (end-begin).seconds)
        Order.disable_order_and_bills(volume)

    begin = datetime.datetime.now()
    for count in xrange(settings.MAX_COUNT_SYNC * 2):
        time.sleep(settings.INSTANCE_SYNC_INTERVAL_SECOND)
        try:
            cinder_volume = volume_get(volume)
        except Exception:
            LOG.exception("Volume get api failed, when sync status, [%s].",
                            volume)
            volume.change_status(VOLUME_STATE_ERROR_DELETING)
            return False

        st = cinder_volume.status.upper() if cinder_volume else "None"
        LOG.info('Volume synchronize status when delete, [Count:%s][%s][Status: %s].',
                    count, volume, st)

        end = datetime.datetime.now() 
        if cinder_volume is None:
            volume.volume_id = None
            volume.fake_delete()
            LOG.info("Volume delete succeed,[%s], apply [%s] seconds.",
                        volume, (end-begin).seconds)
            return True
        elif cinder_volume.status.upper() == 'ERROR_DELETING':
            volume.change_status(VOLUME_STATE_ERROR_DELETING)
            LOG.info("Volume delete failed, [%s], apply [%s] seconds.",
                        volume, (end-begin).seconds)
            return False
    else:
        end = datetime.datetime.now() 
        LOG.info("Volume delete timeout, [%s], apply [%s] seconds.",
            volume, (end-begin).seconds)
        return False
Exemple #5
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)
Exemple #6
0
def volume_create_view(request):
    try:

        os_volume_type = request.data['os_volume_type']
        os_volume_type = ast.literal_eval(os_volume_type)
        os_volume_type = os_volume_type['name']

        LOG.info("********** os volume type is ************" +
                 str(os_volume_type))
        request.data['os_volume_type'] = os_volume_type
        LOG.info("********** os volume type is ************" +
                 str(os_volume_type))

        serializer = VolumeSerializer(data=request.data,
                                      context={"request": request})
        if not serializer.is_valid():
            #return fail(msg=_('Data is not valid.'),
            return fail(msg='{}'.format(serializer.errors),
                        status=status.HTTP_400_BAD_REQUEST)

        pay_type = request.data['pay_type']
        LOG.info("********** os volume type is ************" +
                 str(os_volume_type))
        pay_num = int(request.data['pay_num'])

        volume = serializer.save()
        Operation.log(volume, obj_name=volume.name, action="create", result=1)
        workflow = Workflow.get_default(ResourceType.VOLUME)

        if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:

            volume.status = VOLUME_STATE_APPLYING
            volume.save()

            FlowInstance.create(volume, request.data.user, workflow,
                                None)  # TODO test this
            msg = _("Your application for %(size)d GB volume is successful, "
                    "please waiting for approval result!") \
                % {'size': volume.size}
            return success(msg=msg)
        else:
            try:
                volume_create_task.delay(volume, os_volume_type)
                Order.for_volume(volume, pay_type=pay_type, pay_num=pay_num)
                return success(msg=_('Creating volume'),
                               status=status.HTTP_201_CREATED)
            except Exception as e:
                LOG.exception("Failed to create volume, msg: %s", e)
                volume.status = VOLUME_STATE_ERROR
                volume.save()
                return error()
    except Exception as e:
        LOG.exception("create volume error, msg:[%s]", e)
        return error()
Exemple #7
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'}
def floating_release(floating, **kwargs):
    rc = create_rc_by_floating(floating)
    result = True
    if floating.uuid:
        result = network.tenant_floating_ip_release(rc, floating.uuid)
        LOG.info("release floating associate instance, [%s]" % result)
    
    floating.status = FLOATING_RELEASED
    floating.deleted = 1
    floating.delete_date = datetime.datetime.now()
    floating.save()

    Order.disable_order_and_bills(floating)
    if floating.ip:
        ins = Instance.objects.filter(public_ip=floating.ip)
        ins.update(public_ip=None)

    LOG.info("floating action, [%s][relese][%s]" % (floating.id, result));
Exemple #9
0
def volume_create_view(request):
    try:
        serializer = VolumeSerializer(data=request.data,
                                      context={"request": request})
        if not serializer.is_valid():
            return fail(msg=_('Data is not valid.'),
                        status=status.HTTP_400_BAD_REQUEST)

        pay_type = request.data['pay_type']
        os_volume_type = request.data['os_volume_type']
        os_volume_type = ast.literal_eval(os_volume_type)
        LOG.info("********** os volume type is ************" + str(os_volume_type))
        os_volume_type = os_volume_type['name']
        LOG.info("********** os volume type is ************" + str(os_volume_type))
        pay_num = int(request.data['pay_num'])

        volume = serializer.save()
        Operation.log(volume, obj_name=volume.name, action="create", result=1)
        workflow = Workflow.get_default(ResourceType.VOLUME)

        if settings.SITE_CONFIG['WORKFLOW_ENABLED'] and workflow:

            volume.status = VOLUME_STATE_APPLYING
            volume.save()

            FlowInstance.create(volume, request.user, workflow, None)
            msg = _("Your application for %(size)d GB volume is successful, "
                    "please waiting for approval result!") \
                % {'size': volume.size}
            return success(msg=msg)
        else:
            try:
                volume_create_task.delay(volume, os_volume_type)
                Order.for_volume(volume, pay_type=pay_type, pay_num=pay_num)
                return success(msg=_('Creating volume'),
                               status=status.HTTP_201_CREATED)
            except Exception as e:
                LOG.exception("Failed to create volume, msg: %s", e)
                volume.status = VOLUME_STATE_ERROR
                volume.save()
                return error()
    except Exception as e:
        LOG.exception("create volume error, msg:[%s]", e)
        return error()
Exemple #10
0
def instance_action(user, instance_id, action):
    if action not in ALLOWED_INSTANCE_ACTIONS.keys():
        return {"OPERATION_STATUS": OPERATION_FAILED,
                "status": "Unsupported action [%s]" % action}
    #instance = Instance.objects.get(pk=instance_id, user=user, deleted=False)
    instance = Instance.objects.get(pk=instance_id, deleted=False)
    # restoring instance can't do any action!

    if BackupItem.is_any_restoring(instance):
        return {"OPERATION_STATUS": OPERATION_FORBID,
                "MSG": _("Cannot operate this instance because it's in "
                         "restore process."),
                "status": instance.status}

    if action in ('reboot', 'power_on'):
        for volume in instance.volume_set.all():

            if BackupItem.is_any_restoring(volume):
                return {"OPERATION_STATUS": OPERATION_FAILED,
                        "MSG": _("Cannot operate this instance because "
                                 "one volume attached to it is in "
                                 "restore process."),
                        "status": instance.status}

    if action == 'terminate' and \
        BackupItem.living.filter(
            resource_id=instance.id,
            resource_type=Instance.__name__).exists():

        return {"OPERATION_STATUS": OPERATION_FAILED,
                "MSG": _("This instance have backup chains, please delete "
                         "these first."),
                "status": instance.status}

    if action == 'terminate':
        Order.disable_order_and_bills(instance)

    Operation.log(instance, obj_name=instance.name, action=action)
    
    if action == "vnc_console":
        return get_instance_vnc_console(instance)

    _ACTION_MAPPING = {
        "reboot": _server_reboot,
        "terminate": _server_delete,
        "power_on": _server_start,
        "power_off": _server_stop,
        "restore": _server_unpause,
        "pause": _server_pause,
    }

    try:
        rc = create_rc_by_instance(instance)
        act = _ACTION_MAPPING.get(action)
        act(rc, instance)
        instance.status = INSTANCE_ACTION_NEXT_STATE[action]
        instance.save()
        instance_status_synchronize_task.delay(instance, action)
    except Exception as ex:
        LOG.exception("Instance action [%s] raise exception, [%s].",
                            action, instance)
        return {"OPERATION_STATUS": OPERATION_FAILED, 
                "status": "%s" % ex.message}
    else: 
        return {"OPERATION_STATUS": OPERATION_SUCCESS, "status": instance.status}