def router_create_view(request): data = request.data if (not request.POST.get('id', '')) and \ settings.SITE_CONFIG.get("MULTI_ROUTER_ENABLED", False): try: serializer = RouterSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): router = serializer.save() router_create_task.delay(router) Operation.log(obj=router, obj_name=router.name, action='create', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Create router success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Valid Router fail')}) except Exception as e: LOG.error("Create router error ,msg:%s" % e) return Response({"OPERATION_STATUS": 0, "MSG": _('Create router fail')}) else: router = Router.objects.get(pk=data.get('id')) if router is None: return Response({"OPERATION_STATUS": 0, "MSG": _('The selected router not exist')}) router.name = data.get('name') router.deleted = False Operation.log(obj=router, obj_name=router.name, action='update', result=1) if not router.is_gateway and request.POST.get('is_gateway') == u'true': router.status = NETWORK_STATE_UPDATING router.save() router_add_gateway_task.delay(router) elif router.is_gateway and request.POST.get('is_gateway') == u'false': router.status = NETWORK_STATE_UPDATING router.save() router_remove_gateway_task.delay(router) else: router.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Update router success')})
def delete_network(request): try: network = Network.objects.get(pk=request.data["network_id"], user=request.user) except Network.DoesNotExist: return Response({"OPERATION_STATUS": 0, "MSG": _('The selected network does not exist')}) # Defalut network can not be deleted if network.is_default: return Response({"OPERATION_STATUS": 0, "MSG": _('Default network can not be deleted')}) # Was unable to delete the network when it is being used if network.is_in_use: return Response({ "OPERATION_STATUS": 0, "MSG": _('This network is being used!')}) network.change_status(NETWORK_STATE_DELETING) try: tasks.delete_network.delay(network) except Exception as e: network.change_status(NETWORK_STATE_ACTIVE) LOG.exception("Failed to delete network[%s], reason:[%s] ", network.name, e) return Response({"OPERATION_STATUS": 1, "MSG": _('Network deleted error')}) else: Operation.log(obj=network, obj_name=network.name, action='terminate', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Network deleted success')})
def attach_network_to_router(request): """ 现在是单子网 操作连接和断开操作传入network_id 取第一个子网操作, 如果改为多子网,则需要页面传入指定子网进行连接和断开操作 :param request: :return: """ network_id = request.data['network_id'] router_id = request.data['router_id'] if not router_id: return Response({"OPERATION_STATUS": 0, "MSG": _('Unkown router')}) network = Network.objects.get(pk=network_id) subnet = network.subnet_set.all()[0] if check_router_isexits_subnet(subnet): return Response({"OPERATION_STATUS": 0, "MSG": _('network exist address , not operation')}) network.change_status(NETWORK_STATE_UPDATING) Operation.log(obj=network, obj_name=network.name, action='attach_router') try: tasks.attach_network_to_router.delay(network_id, router_id, subnet.id) return Response({"OPERATION_STATUS": 1, "MSG": _('Link router success')}) except Exception as e: LOG.exception("Attach router error, msg: %s", e) return Response({"OPERATION_STATUS": 0, "MSG": _('Link router error')})
def create_quotas(request): try: contract = Contract.objects.get(pk=request.data['contract_id']) quota_ids = request.data.getlist('ids[]') resources = request.data.getlist('resources[]') limits = request.data.getlist('limits[]') for index, quota_id in enumerate(quota_ids): resource, limit = resources[index], limits[index] if quota_id and Quota.living.filter(contract=contract, pk=quota_id).exists(): Quota.objects.filter(pk=quota_id).update(resource=resource, limit=limit, update_date=timezone.now()) else: Quota.objects.create(resource=resource, limit=limit, contract=contract) Operation.log(contract, contract.name + " quota", 'update', udc=contract.udc, user=request.user) return Response({'success': True, "msg": _('Quotas have been saved successfully!')}, status=status.HTTP_201_CREATED) except Exception as e: LOG.error("Failed to save quotas, msg:[%s]" % e) return Response({"success": False, "msg": _('Failed to save quotas for unknown reason.')})
def floating_action(user, DATA): """ floating action, action is a string """ floating_id = DATA.get("floating_id") act = DATA.get("action") kwargs = DATA if act not in ALLOWED_FLOATING_ACTIONS.keys(): return {"OPERATION_STATUS": OPERATION_FAILED, "status": "un supported action [%s]" % act} floating = Floating.objects.get(pk=floating_id, user=user) floating.status = FLOATING_ACTION_NEXT_STATE[act] if act == ACTION_FLOATING_ASSOCIATE: resource_type = DATA.get('resource_type') resource = DATA.get('resource') if resource: floating.resource = resource floating.resource_type = resource_type floating.save() Operation.log(floating, obj_name=floating.ip, action=act, result=1) floating_action_task.delay(floating, act, **kwargs) return {"OPERATION_STATUS": OPERATION_SUCCESS, "status": floating.status}
def firewall_delete_view(request, **kwargs): data = request.data if data.get('id') is None or data.get('id') == '': return Response({"OPERATION_STATUS": 0, "MSG": _('Not selected Firewall')}) firewall = Firewall.objects.get(pk=data.get('id')) if firewall is None: return Response({"OPERATION_STATUS": 0, "MSG": _('Firewall not exists')}) if firewall.is_default: return Response({"OPERATION_STATUS": 0, "MSG": _('Firewall default can not delete')}) if check_firewall_use(request, firewall.id): return Response({"OPERATION_STATUS": 0, "MSG": _('Firewall used can not delete')}) else: if firewall.firewall_id: try: security_group_delete_task.delay(firewall) except Exception as e: LOG.error("Delete firewall error, msg:%s" % e) return Response({"OPERATION_STATUS": 0, "MSG": _('Firewall delete error')}) firewall.deleted = True firewall.save() Operation.log(firewall, obj_name=firewall.name, action="terminate", result=1) else: firewall.deleted = True firewall.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Firewall delete success')})
def instance_change_firewall_view(request, **kwargs): data = request.data if data.get('instance_id') is None: return Response({"OPERATION_STATUS": 0, 'MSG': 'No Select Instance'}, status=status.HTTP_200_OK) if data.get("firewall_id") is None: return Response({"OPERATION_STATUS": 0, 'MSG': 'No Select Firewall'}, status=status.HTTP_200_OK) try: instance = Instance.objects.get(pk=data.get('instance_id')) except Exception as e: LOG.error("No find Instance,msg: %s" % e) return Response({"OPERATION_STATUS": 0, 'MSG': 'No find Instance'}, status=status.HTTP_200_OK) try: firewall = Firewall.objects.get(pk=data.get('firewall_id')) except Exception as e: LOG.error("No find Firewall,msg: %s" % e) return Response({"OPERATION_STATUS": 0, 'MSG': 'No find Firewall'}, status=status.HTTP_200_OK) try: server_update_security_groups_task.delay(instance, firewall) instance.firewall_group = firewall instance.save() Operation.log(instance, obj_name=instance.name, action="change_firewall", result=1) return Response({"OPERATION_STATUS": 1, 'MSG': 'Security update firewall success'}, status=status.HTTP_200_OK) except Exception as e: LOG.error("Server update security group error,msg: %s" % e) return Response({"OPERATION_STATUS": 0, 'MSG': 'No find Firewall'}, status=status.HTTP_200_OK)
def pool_monitor_delete_view(request): monitor_id = request.POST.get('monitor_id', '') monitor = BalancerMonitor.objects.get(pk=monitor_id, user=request.user) pool_monitor = BalancerPoolMonitor.objects.filter(monitor=monitor_id) if len(pool_monitor) > 0: return Response({ "OPERATION_STATUS": 0, "MSG": _('Monitor is used,can\'t deleted') }) if monitor: pool_monitor_delete(monitor) monitor.deleted = True monitor.save() Operation.log(monitor, obj_name=monitor.get_type_display(), action='delete', result=1) return Response({ "OPERATION_STATUS": 1, "MSG": _('Delete balancer monitor success') }) else: return Response({ "OPERATION_STATUS": 0, "MSG": _('Balancer monitor no exist') })
def router_delete_view(request): if not settings.MULTI_ROUTER_ENABLED: return Response({"OPERATION_STATUS": 0, "MSG": _('Cannot delete router ' 'under single router mode.')}) router_id = request.data['router_id'] try: router = Router.objects.get(pk=router_id) except Router.DoesNotExist: return Response({"OPERATION_STATUS": 0, "MSG": _('The selected router does not exist')}) if router.is_default: return Response({"OPERATION_STATUS": 0, "MSG": _('Default Router can not be deleted')}) if router.is_in_use: return Response({"OPERATION_STATUS": 0, "MSG": _('This router is being used.')}) router.fake_delete() Operation.log(obj=router, obj_name=router.name, action='terminate') router_delete_task.delay(router) return Response({"OPERATION_STATUS": 1, "MSG": _('Router deleted success')})
def pool_vip_associate_view(request): vip_id = request.POST.get("vip_id", "") float_ip_id = request.POST.get("floating_ip_id", "") action = request.POST.get("action", '') if not vip_id or not float_ip_id: return Response({"OPERATION_STATUS": 0, "MSG": _('No select float ip or vip')}) try: vip = BalancerVIP.objects.get(pk=vip_id, user=request.user) floating = Floating.objects.get(pk=float_ip_id, user=request.user) if action == 'bind': p = vip_associate_floating_ip(vip, floating.uuid) Operation.log(vip, obj_name=vip.name, action='associate', result=1) if p: vip.public_address = floating.ip vip.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Vip association floating success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Vip association floating fail')}) elif action == 'unbind': p = vip_disassociate_floating_ip(vip, floating.uuid) if p: vip.public_address = '' vip.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Vip disassociation floating success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Vip disassociation floating fail')}) except Exception as e: LOG.error(e) return Response({"OPERATION_STATUS": 0, "MSG": _('Vip or Floating no exist')})
def delete_action(volume): if volume.instance is not None: msg = _('Operation Failed. ' 'Volume %(volume)s is attached to instance: %(instance)s') \ % {'instance': volume.instance.name, 'volume': volume.name} return fail(msg=msg) if BackupItem.living.filter(resource_id=volume.id, resource_type=Volume.__name__).exists(): return fail(_("This volume has backups, please delete them first.")) if volume.volume_id: volume.change_status(VOLUME_STATE_DELETING) try: volume_delete_task.delay(volume) Operation.log(volume, obj_name=volume.name, action="terminate", result=1) return success(msg=_('Deleting volume')) except Exception: LOG.exception("Delete volume error") volume.change_status(VOLUME_STATE_ERROR) return error() else: volume.fake_delete() return success(msg=_('Volume is deleted.'))
def volume_attach_or_detach(data, volume, action): if 'attach' == action: instance = Instance.objects.get(pk=data.get('instance_id')) volume.change_status(VOLUME_STATE_ATTACHING) Operation.log(volume, obj_name=volume.name, action="attach_volume") try: tasks.attach_volume_to_instance.delay( instance=instance, volume=volume) except Exception: volume.change_status(VOLUME_STATE_AVAILABLE) LOG.exception("Attach volume error") return error() else: return success(msg=_('Attaching volume'), status=status.HTTP_201_CREATED) elif 'detach' == action: volume.change_status(VOLUME_STATE_DETACHING) Operation.log(volume, obj_name=volume.name, action="detach_volume") try: tasks.detach_volume_from_instance.delay(volume) except Exception: LOG.exception("Detach volume error") volume.change_status(VOLUME_STATE_IN_USE) return error() else: return success(msg=_('Detaching volume'), status=status.HTTP_201_CREATED)
def router_create_view(request): data = request.data if (not request.POST.get('id', '')) and \ settings.SITE_CONFIG.get("MULTI_ROUTER_ENABLED", False): try: serializer = RouterSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): router = serializer.save() router_create_task.delay(router) Operation.log(obj=router, obj_name=router.name, action='create', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Create router success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Valid Router fail')}) except Exception as e: LOG.error("Create router error ,msg:%s" % e) return Response({"OPERATION_STATUS": 0, "MSG": _('Create router fail')}) else: router = Router.objects.get(pk=data.get('id')) if router is None: return Response({"OPERATION_STATUS": 0, "MSG": _('The selected router not exist')}) router.name = data.get('name') router.deleted = False Operation.log(obj=router, obj_name=router.name, action='update', result=1) if not router.is_gateway and request.POST.get('is_gateway') == u'true': router.status = NETWORK_STATE_UPDATING router.save() router_add_gateway_task.delay(router) elif router.is_gateway and request.POST.get('is_gateway') == u'false': router.status = NETWORK_STATE_UPDATING router.save() router_remove_gateway_task.delay(router) else: router.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Update router success')})
def delete_action(request): try: network = Network.objects.get(pk=request.POST.get("network_id", ''), user=request.user) # Defalut network can not be deleted if network.is_default: return Response({"OPERATION_STATUS": 0, "MSG": _('Default network can not be deleted')}) # Was unable to delete the use of the network if check_network_is_use(network.id): return Response({"OPERATION_STATUS": 0, "MSG": _('Was unable to delete the use of the network')}) if not network.network_id: network.deleted = True network.save() return Response({"OPERATION_STATUS": 1, "MSG": _('Network deleted success')}) network.status = NETWORK_STATE_DELETING network.save() try: network_delete_task.delay(network) Operation.log(obj=network, obj_name=network.name, action='terminate', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Network deleted success')}) except Exception as e: network.status = NETWORK_STATE_ACTIVE network.save() LOG.error(e) return Response({"OPERATION_STATUS": 1, "MSG": _('Network deleted error')}) except Network.DoesNotExist: return Response({"OPERATION_STATUS": 0, "MSG": _('The selected network does not exist')})
def update_contract(request): try: pk = request.data['id'] contract = Contract.objects.get(pk=pk) contract.name = request.data['name'] contract.customer = request.data['customer'] contract.start_date = datetime.strptime(request.data['start_date'], '%Y-%m-%d %H:%M:%S') contract.end_date = datetime.strptime(request.data['end_date'], '%Y-%m-%d %H:%M:%S') contract.save() Operation.log(contract, contract.name, 'update', udc=contract.udc, user=request.user) return Response( { 'success': True, "msg": _('Contract is updated successfully!') }, status=status.HTTP_201_CREATED) except Exception as e: LOG.error("Failed to update contract, msg:[%s]" % e) return Response({ "success": False, "msg": _('Failed to update contract for unknown reason.') })
def delete_contracts(request): try: contract_ids = request.data.getlist('contract_ids[]') for contract_id in contract_ids: contract = Contract.objects.get(pk=contract_id) contract.deleted = True contract.save() Quota.living.filter(contract__pk=contract_id).update( deleted=True, update_date=timezone.now()) Operation.log(contract, contract.name, 'delete', udc=contract.udc, user=request.user) return Response( { 'success': True, "msg": _('Contracts have been deleted!') }, status=status.HTTP_201_CREATED) except Exception as e: LOG.error("Failed to delete contracts, msg:[%s]" % e) return Response({ "success": False, "msg": _('Failed to delete contracts for unknown reason.') })
def create_contract(request): try: serializer = ContractSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): contract = serializer.save() Operation.log(contract, contract.name, 'create', udc=contract.udc, user=request.user) return Response( { 'success': True, "msg": _('Contract is created successfully!') }, status=status.HTTP_201_CREATED) else: return Response( { "success": False, "msg": _('Contract data is not valid!'), 'errors': serializer.errors }, status=status.HTTP_400_BAD_REQUEST) except Exception as e: LOG.error("Failed to create contract, msg:[%s]" % e) return Response({ "success": False, "msg": _('Failed to create contract for unknown reason.') })
def instance_change_firewall_view(request): data = request.data try: instance = Instance.objects.get(pk=data['instance_id']) except Instance.DoesNotExist: return fail(_("Instance is not found")) try: firewall = Firewall.objects.get(pk=data.get('firewall_id')) except Firewall.DoesNotExist: return fail(_("Firewall is not found")) Operation.log(instance, obj_name=instance.name, action="change_firewall") try: server_update_security_groups_task.delay(instance, firewall) except Exception: LOG.exception("Failed to change firewall group of instance. %s", instance) return error() return success( _("Instance %(name)s's firewall is changed.") % {'name': instance.name})
def backup_volume(request): volume_id, name, is_full = retrieve_params(request.data, 'volume_id', 'name', 'is_full') udc = UserDataCenter.objects.get(pk=request.session["UDC_ID"]) is_full = True if is_full == 'true' else False volume = Volume.objects.get(pk=volume_id) if BackupItem.is_any_unstable(resource=volume): return fail( _("Volume %(name)s has one backup task now.") % {'name': volume.name}) if BackupItem.has_error_node_on_default_chain(resource=volume): return fail( _("Volume %(name)s has one error backup node on " "default backup chain. Please delete it first") % {'name': volume.name}) item = BackupItem.create(volume, name, request.user, udc, is_full=is_full) Operation.log(volume, obj_name=volume.name, action="backup") tasks.execute_backup.delay(item.id) return success(_("Backup is in process."))
def delete_action(volume): if volume.instance is not None: msg = _('Operation Failed. ' 'Volume %(volume)s is attached to instance: %(instance)s') \ % {'instance': volume.instance.name, 'volume': volume.name} return fail(msg=msg) if BackupItem.living.filter(resource_id=volume.id, resource_type=Volume.__name__).exists(): return fail(_("This volume has backups, please delete them first.")) if volume.volume_id: volume.change_status(VOLUME_STATE_DELETING) try: volume_delete_task.delay(volume) Operation.log(volume, obj_name=volume.name, action="terminate", result=1) return success(msg=_('Deleting volume')) except Exception: LOG.exception("Delete volume error") volume.change_status(VOLUME_STATE_ERROR) return error() else: volume.fake_delete() return success(msg=_('Volume is deleted.'))
def create_pool_vip(request): pool_id = request.data['pool_id'] try: pool = BalancerPool.objects.get( pk=pool_id, user=request.user, user_data_center=request.session["UDC_ID"]) except BalancerPool.DoesNotExist: return fail(_("No balancer pool found!")) serializer = BalancerVIPSerializer(data=request.data, context={'request': request}) if not serializer.is_valid(): return fail(_('Data is not valid')) vip = serializer.save() Operation.log(vip, obj_name=vip.name, action='create') pool.status = POOL_UPDATING pool.save() try: pool_vip_create_task.delay(vip, pool) except Exception: vip.delete() return error() return success(_('Creating balancer vip.'))
def pool_delete_view(request): pool_id = request.POST.get('pool_id', '') pool = BalancerPool.objects.get(pk=pool_id, user=request.user, user_data_center=request.session["UDC_ID"]) if pool: if not pool.pool_uuid: pool.deleted = True pool.save() return Response({ "OPERATION_STATUS": 1, "MSG": _('Delete balancer pool') }) pool.status = POOL_DELETING pool.save() pool_delete_task.delay(pool) Operation.log(pool, obj_name=pool.name, action='delete', result=1) return Response({ "OPERATION_STATUS": 1, "MSG": _('Delete balancer pool') }) else: return Response({ "OPERATION_STATUS": 0, "MSG": _('Balancer pool no exist') })
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) 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) 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()
def delete_action(volume): if volume.instance is not None: msg = _('Operation Failed. ' 'Volume %(volume)s is attached to instance:%(instance)s') \ % {'instance': volume.instance.name, 'volume': volume.name} return fail(msg=msg) if volume.volume_id: volume.status = VOLUME_STATE_DELETING volume.save() try: volume_delete_action_task.delay(volume) Operation.log(volume, obj_name=volume.name, action="terminate", result=1) return success(msg=_('Deleting volume')) except Exception as e: LOG.exception("Delete volume error, msg:%s", e) volume.status = VOLUME_STATE_ERROR volume.save() return error() else: volume.deleted = True volume.save() return success(msg=_('Volume is deleted.'))
def pool_create_view(request): serializer = BalancerPoolSerializer(data=request.data, context={"request": request}) if serializer.is_valid(): pool_id = request.POST.get("pool_id", '') ''' if pool_id is '' add pool ,else update pool ''' if not pool_id: pool = serializer.save() try: pool_create_task.delay(pool) Operation.log(pool, obj_name=pool.name, action='create', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Create balancer pool success')}) except Exception as e: LOG.error("Create pool error, msg: %s " % e) pool.status = POOL_ERROR pool.save() else: try: pool = BalancerPool.objects.get(pk=pool_id, user=request.user) pool.lb_method = request.POST.get("lb_method", pool.lb_method) pool.name = request.POST.get("name", pool.name) pool.description = request.POST.get('description', pool.description) pool.status = POOL_UPDATING pool.save() pool_update_task.delay(pool) Operation.log(pool, obj_name=pool.name, action='update', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Update balancer pool success')}) except Exception as e: LOG.error(e) return Response({"OPERATION_STATUS": 0, "MSG": _('Selected balancer no exist')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Balancer data valid no pass')})
def pool_monitor_create_view(request): serializer = BalancerMonitorSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): monitor_id = request.POST.get('monitor_id','') ''' if monitor_id is '' add monitor ,else update monitor ''' if monitor_id == '': monitor = serializer.save() m = pool_monitor_create(monitor) if m: monitor.monitor_uuid = m.id monitor.save() Operation.log(monitor, obj_name=monitor.get_type_display(), action='create', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Create balancer monitor success')}) else: monitor.delete() return Response({"OPERATION_STATUS": 0, "MSG": _('Create balancer monitor Fail')}) else: monitor = BalancerMonitor.objects.get(pk=monitor_id, user=request.user) if not monitor: return Response({"OPERATION_STATUS": 0, "MSG": _('Monitor no exists')}) monitor.delay = request.POST.get('delay', monitor.delay) monitor.timeout = request.POST.get('timeout', monitor.timeout) monitor.max_retries = request.POST.get('max_retries', monitor.max_retries) m = pool_monitor_update(monitor) if m: monitor.save() Operation.log(monitor, obj_name=monitor.get_type_display(), action='update', result=1) return Response({"OPERATION_STATUS": 1, "MSG": _('Update balancer monitor success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Update balancer monitor Fail')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Monitor data valid no pass')})
def delete_backup_item(request, pk): backup_item = BackupItem.objects.get(pk=pk) if backup_item.status == BACKUP_STATE_ERROR or \ backup_item.rbd_image is None: backup_item.deleted = True backup_item.change_status(BACKUP_STATE_DELETED) backup_item.save() return success(_("Backup item Deleted.")) if BackupItem.is_any_node_untable(backup_item.chain_id): return fail(_("There is one task running on this chain.")) BackupItem.mark_chain_delete(backup_item) Operation.log(backup_item, obj_name=backup_item.name, action="delete") try: tasks.delete_backup.delay(backup_item.id) except Exception: LOG.exception("Failed to delete backup item. %s", backup_item) return error() else: return success(_("Deleting"))
def update_pool_monitor(request): monitor_id = request.data['id'] try: monitor = BalancerMonitor.objects.get(pk=monitor_id, user=request.user) except BalancerMonitor.DoesNotExist: return fail(_("No monitor found!")) serializer = BalancerMonitorSerializer(data=request.data, instance=monitor, context={'request': request}) if not serializer.is_valid(): return fail(_("Monitor data is not valid")) monitor.delay = int(request.data['delay']) monitor.timeout = int(request.data['timeout']) monitor.max_retries = int(request.data['max_retries']) if pool_monitor_update(monitor): monitor.save() Operation.log(monitor, obj_name=monitor.get_type_display(), action='update') return success(_('Balancer monitor is updated!')) else: return error()
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) 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) 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()
def delete_pool(request): pool_id = request.data['pool_id'] try: pool = BalancerPool.objects.get( pk=pool_id, user=request.user, user_data_center=request.session["UDC_ID"]) except BalancerPool.DoesNotExist: return fail(_('No balancer found.')) if not pool.pool_uuid: pool.deleted = True pool.save() return success( _('Balancer pool %(name)s is deleted') % {'name': pool.name}) pool.status = POOL_DELETING pool.save() Operation.log(pool, obj_name=pool.name, action='delete') try: pool_delete_task.delay(pool) except Exception: LOG.exception("Failed to delete balancer pool[%s]", pool) return error() return success(_('Deleting balancer pool %(name)s') % {'name': pool.name})
def backup_volume(request): volume_id, name, is_full = retrieve_params( request.data, 'volume_id', 'name', 'is_full') udc = UserDataCenter.objects.get(pk=request.session["UDC_ID"]) is_full = True if is_full == 'true' else False volume = Volume.objects.get(pk=volume_id) if BackupItem.is_any_unstable(resource=volume): return fail(_("Volume %(name)s has one backup task now.") % {'name': volume.name}) if BackupItem.has_error_node_on_default_chain(resource=volume): return fail(_("Volume %(name)s has one error backup node on " "default backup chain. Please delete it first") % {'name': volume.name}) item = BackupItem.create(volume, name, request.user, udc, is_full=is_full) Operation.log(volume, obj_name=volume.name, action="backup") tasks.execute_backup.delay(item.id) return success(_("Backup is in process."))
def delete_action(volume): if volume.instance is not None: msg = _('Operation Failed. ' 'Volume %(volume)s is attached to instance:%(instance)s') \ % {'instance': volume.instance.name, 'volume': volume.name} return fail(msg=msg) if volume.volume_id: volume.status = VOLUME_STATE_DELETING volume.save() try: volume_delete_action_task.delay(volume) Operation.log(volume, obj_name=volume.name, action="terminate", result=1) return success(msg=_('Deleting volume')) except Exception as e: LOG.exception("Delete volume error, msg:%s", e) volume.status = VOLUME_STATE_ERROR volume.save() return error() else: volume.deleted = True volume.save() return success(msg=_('Volume is deleted.'))
def management(request): if request.user.is_superuser or request.user.has_perm("workflow.system_user") or request.user.has_perm("workflow.safety_user") or request.user.has_perm("workflow.audit_user"): return render(request, 'management.html', {'inited': DataCenter.objects.exists()}) else: Operation.log(request.user, obj_name="management", action="access_manage", result=0) return render(request, "cloud.html")
def delete_backup_item(request, pk): backup_item = BackupItem.objects.get(pk=pk) if backup_item.status == BACKUP_STATE_ERROR or \ backup_item.rbd_image is None: backup_item.deleted = True backup_item.change_status(BACKUP_STATE_DELETED) backup_item.save() return success(_("Backup item Deleted.")) if BackupItem.is_any_node_untable(backup_item.chain_id): return fail(_("There is one task running on this chain.")) BackupItem.mark_chain_delete(backup_item) Operation.log(backup_item, obj_name=backup_item.name, action="delete") try: tasks.delete_backup.delay(backup_item.id) except Exception: LOG.exception("Failed to delete backup item. %s", backup_item) return error() else: return success(_("Deleting"))
def create_quotas(request): try: contract = Contract.objects.get(pk=request.data['contract_id']) quota_ids = request.data.getlist('ids[]') resources = request.data.getlist('resources[]') limits = request.data.getlist('limits[]') for index, quota_id in enumerate(quota_ids): resource, limit = resources[index], limits[index] if quota_id and Quota.living.filter(contract=contract, pk=quota_id).exists(): Quota.objects.filter(pk=quota_id).update(resource=resource, limit=limit, update_date=timezone.now()) else: Quota.objects.create(resource=resource, limit=limit, contract=contract) Operation.log(contract, contract.name + " quota", 'update', udc=contract.udc, user=request.user) return Response({'success': True, "msg": _('Quotas have been saved successfully!')}, status=status.HTTP_201_CREATED) except Exception as e: LOG.error("Failed to save quotas, msg:[%s]" % e) return Response({"success": False, "msg": _('Failed to save quotas for unknown reason.')})
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 pool_monitor_association_option_view(request): pool_id = request.POST.get("pool_id", "") monitor_id = request.POST.get("monitor_id", "") action = request.POST.get("action", '') if not pool_id or not monitor_id: return Response({"OPERATION_STATUS": 0, "MSG": _('No select balancer or monitor')}) try: pool = BalancerPool.objects.get(pk=pool_id, user=request.user) monitor = BalancerMonitor.objects.get(pk=monitor_id, user=request.user) if action == 'attach': p = pool_monitor_association_create(pool, monitor.monitor_uuid) Operation.log(pool, obj_name=pool.name, action='attach', result=1) if p: BalancerPoolMonitor.objects.create(pool=pool, monitor=monitor) return Response({"OPERATION_STATUS": 1, "MSG": _('Balancer monitor association success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Balancer monitor association fail')}) elif action == 'detach': p = pool_monitor_association_delete(pool, monitor.monitor_uuid) Operation.log(pool, obj_name=pool.name, action='detach', result=1) if p: pool_monitor_set = BalancerPoolMonitor.objects.filter(pool=pool.id, monitor=monitor.id) for pool_monitor in pool_monitor_set: pool_monitor.delete() return Response({"OPERATION_STATUS": 1, "MSG": _('Balancer monitor cancel association success')}) else: return Response({"OPERATION_STATUS": 0, "MSG": _('Balancer monitor cancel association fail')}) except Exception as e: LOG.error(e) return Response({"OPERATION_STATUS": 0, "MSG": _('balancer or monitor no exist')})
def update_contract(request): try: pk = request.data['id'] contract = Contract.objects.get(pk=pk) contract.name = request.data['name'] contract.customer = request.data['customer'] contract.start_date = datetime.strptime(request.data['start_date'], '%Y-%m-%d %H:%M:%S') contract.end_date = datetime.strptime(request.data['end_date'], '%Y-%m-%d %H:%M:%S') contract.save() Operation.log(contract, contract.name, 'update', udc=contract.udc, user=request.user) return Response( {'success': True, "msg": _('Contract is updated successfully!')}, status=status.HTTP_201_CREATED) except Exception as e: LOG.error("Failed to update contract, msg:[%s]" % e) return Response({"success": False, "msg": _( 'Failed to update contract for unknown reason.')})
def volume_attach_or_detach(data, volume, action): if 'attach' == action: instance = Instance.objects.get(pk=data.get('instance_id')) volume.change_status(VOLUME_STATE_ATTACHING) Operation.log(volume, obj_name=volume.name, action="attach_volume") try: tasks.attach_volume_to_instance.delay(instance=instance, volume=volume) except Exception: volume.change_status(VOLUME_STATE_AVAILABLE) LOG.exception("Attach volume error") return error() else: return success(msg=_('Attaching volume'), status=status.HTTP_201_CREATED) elif 'detach' == action: volume.change_status(VOLUME_STATE_DETACHING) Operation.log(volume, obj_name=volume.name, action="detach_volume") try: tasks.detach_volume_from_instance.delay(volume) except Exception: LOG.exception("Detach volume error") volume.change_status(VOLUME_STATE_IN_USE) return error() else: return success(msg=_('Detaching volume'), status=status.HTTP_201_CREATED)
def create_pool_member(request): serializer = BalancerMemberSerializer(data=request.data, context={'request': request}) if not serializer.is_valid(): return fail(_('Data is not valid.')) pool_id = request.data['pool_id'] user = request.user udc = UserDataCenter.objects.get(pk=request.session["UDC_ID"]) try: pool = BalancerPool.objects.get(pk=pool_id, user=request.user) except BalancerPool.DoesNotExist: return fail(_('Selected balancer not found.')) weight = int(request.data['weight']) protocol_port = int(request.data['protocol_port']) for instance_id in request.data.getlist('instance_ids[]'): instance = Instance.objects.get(pk=instance_id, user=request.user) member = BalancerMember.objects.create(pool=pool, weight=weight, protocol_port=protocol_port, user=user, user_data_center=udc, instance=instance) Operation.log(member, obj_name=instance.name, action='create') pool_member_create_task.delay(member) return success(_("Load balancer members are being created."))
def detach_monitor_from_pool(pool, monitor): Operation.log(pool, obj_name=pool.name, action='detach', result=1) if pool_monitor_association_delete(pool, monitor): return success(_('Monitor is detached')) else: return error()
def attach_monitor_to_pool(pool, monitor): Operation.log(pool, obj_name=pool.name, action='attach') if pool_monitor_association_create(pool, monitor): return success(_('Monitor is attached.')) else: return error()
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)
def pool_monitor_association_option_view(request): pool_id = request.POST.get("pool_id", "") monitor_id = request.POST.get("monitor_id", "") action = request.POST.get("action", '') if not pool_id or not monitor_id: return Response({ "OPERATION_STATUS": 0, "MSG": _('No select balancer or monitor') }) try: pool = BalancerPool.objects.get(pk=pool_id, user=request.user) monitor = BalancerMonitor.objects.get(pk=monitor_id, user=request.user) if action == 'attach': p = pool_monitor_association_create(pool, monitor.monitor_uuid) Operation.log(pool, obj_name=pool.name, action='attach', result=1) if p: BalancerPoolMonitor.objects.create(pool=pool, monitor=monitor) return Response({ "OPERATION_STATUS": 1, "MSG": _('Balancer monitor association success') }) else: return Response({ "OPERATION_STATUS": 0, "MSG": _('Balancer monitor association fail') }) elif action == 'detach': p = pool_monitor_association_delete(pool, monitor.monitor_uuid) Operation.log(pool, obj_name=pool.name, action='detach', result=1) if p: pool_monitor_set = BalancerPoolMonitor.objects.filter( pool=pool.id, monitor=monitor.id) for pool_monitor in pool_monitor_set: pool_monitor.delete() return Response({ "OPERATION_STATUS": 1, "MSG": _('Balancer monitor cancel association success') }) else: return Response({ "OPERATION_STATUS": 0, "MSG": _('Balancer monitor cancel association fail') }) except Exception as e: LOG.error(e) return Response({ "OPERATION_STATUS": 0, "MSG": _('balancer or monitor no exist') })
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()