Beispiel #1
0
from django.views.decorators.cache import never_cache

from share.manager.region_provier import RegionProviderManager
from www.decorator import perm_required
from www.models import ServiceGroupRelation, ServiceEvent
from www.monitorservice.monitorhook import MonitorHook
from www.service_http import RegionServiceApi
from www.tenantservice.baseservice import CodeRepositoriesService
from www.utils.crypt import make_uuid
from www.views import AuthedView
from www.views.mixin import LeftSideBarMixin

logger = logging.getLogger('default')

monitorhook = MonitorHook()
rpmManager = RegionProviderManager()
codeRepositoriesService = CodeRepositoriesService()


class BasicInfoEditView(LeftSideBarMixin, AuthedView):
    @never_cache
    @perm_required("manage_service")
    def post(self, request, *args, **kwargs):
        service_name = request.POST.get("service_name", None)
        group_id = request.POST.get("group_id", None)
        git_url = request.POST.get("git_url", None)
        logger.debug(
            "update service info: new service name {0},group_id {1},git_url {2}"
            .format(service_name, group_id, git_url))
        result = {}
        service_id = self.service.service_id
class RegionResourceSettleView(ShareBaseView):
    region_provider_manager = RegionProviderManager()

    def get(self, request, *args, **kwargs):
        querymonth = request.GET.get("date", None)
        if querymonth:
            month_date = dt.strptime(querymonth, "%Y-%m")
        else:
            now = dt.now()
            month_date = dt(now.year, now.month, 1, 0, 0,
                            0) - clzdt.timedelta(days=1)
        querymonth = month_date.strftime("%Y-%m")

        start_date = dt(month_date.year, month_date.month, 1, 0, 0, 0)
        last_day = calendar.monthrange(month_date.year, month_date.month)[1]
        end_date = dt(month_date.year, month_date.month, last_day, 0, 0,
                      0) + clzdt.timedelta(days=1)
        logger.info("query from {} to {}".format(start_date, end_date))

        provider = self.provider.provider_name
        provider_settle_list = list(
            RegionResourceProviderSettle.objects.filter(provider=provider,
                                                        date=querymonth))

        region_settle_list = []
        for provider_settle in provider_settle_list:
            total_memory = provider_settle.used_memory + provider_settle.package_memory
            total_net = provider_settle.used_net + provider_settle.package_net
            total_disk = provider_settle.used_disk + provider_settle.package_disk

            total_resource_fee = self.cal_region_resource_fee(
                provider_settle.region, total_memory, total_disk, total_net)
            total_package_fee = self.cal_region_pacakge_fee(
                provider_settle.region, start_date, end_date)

            total_fee = total_resource_fee + total_package_fee

            partner_rate = Decimal(0.5)
            settle_fee = total_fee * partner_rate

            region_settle = dict()
            region_settle["region"] = provider_settle.region
            region_settle["total_memory"] = total_memory / 1024
            region_settle["total_net"] = total_net / 1024
            region_settle["total_disk"] = total_disk / 1024
            region_settle["total_resource_fee"] = total_resource_fee.quantize(
                Decimal('0.00'))
            region_settle["total_package_fee"] = total_package_fee.quantize(
                Decimal('0.00'))
            region_settle["total_fee"] = total_fee.quantize(Decimal('0.00'))
            region_settle["partner_rate"] = partner_rate
            region_settle["settle_fee"] = settle_fee.quantize(Decimal('0.00'))
            region_settle_list.append(region_settle)

        context = self.get_context()
        context.update({
            "region_settle_list": region_settle_list,
            "query_month": querymonth,
        })
        return TemplateResponse(request, "share/region_resource_settle.html",
                                context)

    def cal_region_resource_fee(self, region_name, memroy, disk, net):
        total_fee = Decimal(0)
        try:
            region_sales_price = self.region_provider_manager.get_work_region_by_name(
                region_name)
            memory_fee = region_sales_price.memory_price * Decimal.from_float(
                memroy / 1024.0)
            disk_fee = region_sales_price.disk_price * Decimal.from_float(
                disk / 1024.0)
            net_fee = region_sales_price.net_price * Decimal.from_float(
                net / 1024.0)

            total_fee = memory_fee + disk_fee + net_fee
        except Exception as e:
            logger.exception("", e)

        return total_fee

    def cal_region_pacakge_fee(self, region_name, static_start_date,
                               static_end_date):
        conn = MySQLConn()
        pay_model_data = conn.fetch_all("""
                    select  tenant_id, buy_start_time, buy_end_time, buy_money
                    from    tenant_region_pay_model
                    where   region_name = '{}'
                """.format(region_name))

        real_cost_money = 0.00
        for tenant_id, buy_start_time, buy_end_time, buy_money in pay_model_data:
            buy_start_date = buy_start_time
            buy_end_date = buy_end_time

            logger.info("{}: [{} - {}], cost:{}".format(
                tenant_id, buy_start_date, buy_end_date, buy_money))

            if buy_start_date >= static_end_date or buy_end_date <= static_start_date:
                continue

            single_price = float(
                str(buy_money)) / (buy_end_date - buy_start_date).days
            consume_days = 0
            if buy_end_date <= static_start_date or buy_start_date >= static_end_date:
                continue

            # 购买周期完全包含统计周期
            if buy_start_date <= static_start_date and buy_end_date >= static_end_date:
                consume_days = (static_end_date - static_start_date).days
            # 购买周期完全在统计周期之内, 则以天计算
            elif buy_start_date > static_start_date and buy_end_date < static_end_date:
                consume_days = (buy_end_date - buy_start_date).days
            elif buy_start_date <= static_start_date and buy_end_date < static_end_date:
                consume_days = (buy_end_date - static_start_date).days
            elif buy_start_date > static_start_date and buy_end_date >= static_end_date:
                consume_days = (static_end_date - buy_start_date).days
            package_cost = single_price * consume_days

            real_cost_money += package_cost
            logger.info("{} * {} = {}, total = {}".format(
                single_price, consume_days, package_cost, real_cost_money))

        return Decimal.from_float(real_cost_money)