Ejemplo n.º 1
0
    def __init_market_app(self, tenant, region, user, app,
                          tenant_service_group_id, service_origin):
        """
        初始化应用市场创建的应用默认数据
        """
        is_slug = bool(app["image"].startswith('goodrain.me/runner')
                       and app["language"] not in ("dockerfile", "docker"))

        tenant_service = TenantServiceInfo()
        tenant_service.tenant_id = tenant.tenant_id
        tenant_service.service_id = make_uuid()
        tenant_service.service_cname = app_service.generate_service_cname(
            tenant, app["service_cname"], region)
        tenant_service.service_alias = "gr" + tenant_service.service_id[-6:]
        tenant_service.creater = user.pk
        if is_slug:
            tenant_service.image = app["image"]
        else:
            tenant_service.image = app.get("share_image", app["image"])
        tenant_service.cmd = app.get("cmd", "")
        tenant_service.service_region = region
        tenant_service.service_key = app["service_key"]
        tenant_service.desc = "market app "
        tenant_service.category = "app_publish"
        tenant_service.setting = ""
        tenant_service.extend_method = app["extend_method"]
        tenant_service.env = ","
        tenant_service.min_node = app["extend_method_map"]["min_node"]
        tenant_service.min_memory = app["extend_method_map"]["min_memory"]
        tenant_service.min_cpu = baseService.calculate_service_cpu(
            region, tenant_service.min_memory)
        tenant_service.inner_port = 0
        tenant_service.version = app["version"]
        if is_slug:
            if app.get("service_slug", None):
                tenant_service.namespace = app["service_slug"]["namespace"]
        else:
            if app.get("service_image", None):
                tenant_service.namespace = app["service_image"]["namespace"]
        tenant_service.update_version = 1
        tenant_service.port_type = "multi_outer"
        tenant_service.create_time = datetime.now().strftime(
            '%Y-%m-%d %H:%M:%S')
        tenant_service.deploy_version = ""
        tenant_service.git_project_id = 0
        tenant_service.service_type = "application"
        tenant_service.total_memory = tenant_service.min_node * tenant_service.min_memory
        tenant_service.volume_mount_path = ""
        tenant_service.host_path = ""
        tenant_service.code_from = ""
        tenant_service.language = ""
        tenant_service.service_source = "market"
        tenant_service.create_status = "creating"
        tenant_service.service_origin = service_origin
        tenant_service.tenant_service_group_id = tenant_service_group_id
        self.__init_service_source(tenant_service, app)
        # 存储并返回
        tenant_service.save()
        return tenant_service
Ejemplo n.º 2
0
 def __init_compose_service(self, tenant, user, service_cname, image,
                            region):
     """
     初始化docker compose创建的应用默认数据
     """
     tenant_service = TenantServiceInfo()
     tenant_service.tenant_id = tenant.tenant_id
     tenant_service.service_id = make_uuid()
     tenant_service.service_cname = app_service.generate_service_cname(
         tenant, service_cname, region)
     tenant_service.service_alias = "gr" + tenant_service.service_id[-6:]
     tenant_service.creater = user.pk
     tenant_service.image = image
     tenant_service.service_region = region
     tenant_service.service_key = "0000"
     tenant_service.desc = "docker compose application"
     tenant_service.category = "app_publish"
     tenant_service.setting = ""
     tenant_service.extend_method = "stateless"
     tenant_service.env = ","
     tenant_service.min_node = 1
     tenant_service.min_memory = 128
     tenant_service.min_cpu = baseService.calculate_service_cpu(region, 128)
     tenant_service.inner_port = 0
     tenant_service.version = "latest"
     tenant_service.namespace = "goodrain"
     tenant_service.update_version = 1
     tenant_service.port_type = "multi_outer"
     tenant_service.create_time = datetime.datetime.now().strftime(
         '%Y-%m-%d %H:%M:%S')
     tenant_service.deploy_version = ""
     tenant_service.git_project_id = 0
     tenant_service.service_type = "application"
     tenant_service.total_memory = 128
     tenant_service.volume_mount_path = ""
     tenant_service.host_path = "/grdata/tenant/" + tenant.tenant_id + "/service/" + tenant_service.service_id
     tenant_service.code_from = "image_manual"
     tenant_service.language = "docker-compose"
     tenant_service.service_source = AppConstants.DOCKER_COMPOSE
     tenant_service.create_status = "creating"
     # 保存并返回
     tenant_service.save()
     return tenant_service
Ejemplo n.º 3
0
    def post(self, request, *args, **kwargs):
        service_alias = ""
        service_code_from = ""
        tenant_id = self.tenant.tenant_id
        service_id = make_uuid(tenant_id)
        data = {}
        try:
            success = tenant_svc.init_for_region(self.response_region,
                                                 self.tenantName, tenant_id,
                                                 self.user)
            if not success:
                data["status"] = "failure"
                return JsonResponse(data, status=200)

            service_desc = ""
            service_cname = request.POST.get("create_app_name", "")
            service_code_from = request.POST.get("service_code_from", "")
            if service_code_from is None or service_code_from == "":
                data["status"] = "code_from"
                return JsonResponse(data, status=200)
            service_cname = service_cname.rstrip().lstrip()
            if service_cname is None or service_cname == "":
                data["status"] = "empty"
                return JsonResponse(data, status=200)
            # get base service
            service = ServiceInfo.objects.get(service_key="application")
            # 根据页面参数获取节点数和每个节点的内存大小
            # min_memory = int(request.POST.get("service_min_memory", 128))
            # # 将G转换为M
            # if min_memory < 128:
            #     min_memory *= 1024
            # min_node = int(request.POST.get("service_min_node", 1))
            # service.min_memory = min_memory
            # service.min_node = min_node
            service.min_cpu = baseService.calculate_service_cpu(
                self.response_region, service.min_memory)
            service_alias = "gr" + service_id[-6:]
            # calculate resource
            tempService = TenantServiceInfo()
            tempService.min_memory = service.min_memory
            tempService.service_region = self.response_region
            tempService.min_node = service.min_node
            tempService.service_alias = service_alias
            diffMemory = service.min_node * service.min_memory
            rt_type, flag = tenantUsedResource.predict_next_memory(
                self.tenant, tempService, diffMemory, False)
            if not flag:
                if rt_type == "memory":
                    data["status"] = "over_memory"
                    data["tenant_type"] = self.tenant.pay_type
                else:
                    data["status"] = "over_money"
                return JsonResponse(data, status=200)

            # save service attach info
            pre_paid_period = int(request.POST.get("pre_paid_period", 0))
            disk = int(request.POST.get("disk_num", 0)) * 1024

            create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            # create console service
            service.desc = service_desc
            newTenantService = baseService.create_service(
                service_id,
                tenant_id,
                service_alias,
                service_cname,
                service,
                self.user.pk,
                region=self.response_region)
            monitorhook.serviceMonitor(self.user.nick_name, newTenantService,
                                       'create_service', True)
            baseService.addServicePort(newTenantService,
                                       False,
                                       container_port=5000,
                                       protocol='http',
                                       port_alias=service_alias.upper() +
                                       str(5000),
                                       is_inner_service=False,
                                       is_outer_service=True)

            sai = attach_info_mamage.create_service_attach_info(
                newTenantService,
                newTenantService.min_memory * newTenantService.min_node, disk)
            if sai.pre_paid_money > 0:
                ServiceFeeBill.objects.create(tenant_id=tenant_id,
                                              service_id=service_id,
                                              prepaid_money=sai.pre_paid_money,
                                              pay_status="unpayed",
                                              cost_type="first_create",
                                              node_memory=service.min_memory,
                                              node_num=service.min_node,
                                              disk=disk,
                                              buy_period=pre_paid_period * 24 *
                                              30,
                                              create_time=create_time,
                                              pay_time=create_time)

            # code repos
            # 自建git (gitlab_self)与gitlab_manual一样
            if service_code_from == "gitlab_self":
                service_code_from = "gitlab_manual"

            if service_code_from == "gitlab_new":
                codeRepositoriesService.initRepositories(
                    self.tenant, self.user, newTenantService,
                    service_code_from, "", "", "")
            elif service_code_from == "gitlab_exit":
                code_clone_url = request.POST.get("service_code_clone_url", "")
                code_id = request.POST.get("service_code_id", "")
                code_version = request.POST.get("service_code_version",
                                                "master")
                if code_id == "" or code_clone_url == "" or code_version == "":
                    data["status"] = "code_repos"
                    TenantServiceInfo.objects.get(
                        service_id=service_id).delete()
                    return JsonResponse(data, status=200)
                codeRepositoriesService.initRepositories(
                    self.tenant, self.user, newTenantService,
                    service_code_from, code_clone_url, code_id, code_version)
            elif service_code_from == "gitlab_manual":
                code_clone_url = request.POST.get("service_code_clone_url", "")
                code_version = request.POST.get("service_code_version",
                                                "master")
                code_id = 0
                if code_clone_url == "" or code_version == "":
                    data["status"] = "code_repos"
                    TenantServiceInfo.objects.get(
                        service_id=service_id).delete()
                    return JsonResponse(data, status=200)
                codeRepositoriesService.initRepositories(
                    self.tenant, self.user, newTenantService,
                    service_code_from, code_clone_url, code_id, code_version)
            elif service_code_from == "github":
                code_id = request.POST.get("service_code_id", "")
                code_clone_url = request.POST.get("service_code_clone_url", "")
                code_version = request.POST.get("service_code_version",
                                                "master")
                if code_id == "" or code_clone_url == "" or code_version == "":
                    data["status"] = "code_repos"
                    TenantServiceInfo.objects.get(
                        service_id=service_id).delete()
                    return JsonResponse(data, status=200)
                codeRepositoriesService.initRepositories(
                    self.tenant, self.user, newTenantService,
                    service_code_from, code_clone_url, code_id, code_version)

            group_id = request.POST.get("select_group_id", "")
            # 创建关系
            if group_id != "":
                group_id = int(group_id)
                if group_id > 0:
                    ServiceGroupRelation.objects.create(
                        service_id=service_id,
                        group_id=group_id,
                        tenant_id=self.tenant.tenant_id,
                        region_name=self.response_region)
            monitorhook.serviceMonitor(self.user.nick_name, newTenantService,
                                       'init_region_service', True)

            data["status"] = "success"
            data["service_alias"] = service_alias
            data["service_id"] = service_id
        except Exception as e:
            logger.exception("create console service failed!")
            logger.exception(e)
            tempTenantService = TenantServiceInfo.objects.get(
                service_id=service_id)
            codeRepositoriesService.deleteProject(tempTenantService)
            TenantServiceInfo.objects.filter(service_id=service_id).delete()
            TenantServiceAuth.objects.filter(service_id=service_id).delete()
            TenantServiceRelation.objects.filter(
                service_id=service_id).delete()
            ServiceGroupRelation.objects.filter(service_id=service_id)
            ServiceAttachInfo.objects.filter(service_id=service_id)
            monitorhook.serviceMonitor(self.user.nick_name, tempTenantService,
                                       'create_service_error', False)
            data["status"] = "failure"
        return JsonResponse(data, status=200)