Пример #1
0
    def update_license_info(self, new_license):

        if LICENSE.validation(new_license):
            # self.update_config("LICENSE", new_license)
            LICENSE.set_license(new_license)
        else:
            raise ParamsError("无效的license")
Пример #2
0
 def put(self, request, format=None):
     try:
         license = request.data.get("license")
         ok = LICENSE.validation(license)
         if ok:
             LICENSE.set_license(license)
             return APISuccessResponseJson()
         return APIErrResponseJson("Illegal license", "非法的LICESE信息", 400)
     except Exception as e:
         logger.exception(e)
         return APIErrResponseJson(e.message, u"系统错误", 500)
Пример #3
0
 def get(self, request, format=None):
     try:
         license_data = LICENSE.get_license()
         return APISuccessResponseJson(bean=license_data)
     except Exception as e:
         logger.exception(e)
         return APIErrResponseJson(e.message, u"系统错误", 500)
Пример #4
0
    def add_tenant(self, tenant_name, user, regions):
        if not user:
            user = Users.objects.get(user_id=1)
        creater = user.pk
        enterprise_id = user.enterprise_id
        tenants_num = Tenants.objects.count()
        allow_num = LICENSE.get_authorization_tenant_number()
        if tenants_num >= allow_num:
            raise TenantOverFlowError("租户数已超最大配额")
        if Tenants.objects.filter(
                tenant_name=tenant_name).exists():
            raise TenantExistError("租户{}已存在".format(tenant_name))
        expired_day = 7
        if hasattr(settings, "TENANT_VALID_TIME"):
            expired_day = int(settings.TENANT_VALID_TIME)
        expire_time = datetime.datetime.now() + datetime.timedelta(
            days=expired_day)
        # 计算此团队需要初始化的数据中心
        prepare_init_regions = []
        if regions:
            region_configs = RegionConfig.objects.filter(region_name__in=regions, status="1")
            prepare_init_regions.extend(region_configs)
        else:
            region_configs = RegionConfig.objects.filter(status="1")
            prepare_init_regions.extend(region_configs)

        if not prepare_init_regions:
            raise Exception('please init one region at least.')
        enterprise = TenantEnterprise.objects.get(enterprise_id=enterprise_id)
        # 团队管理的默认数据中心
        default_region = prepare_init_regions[0]
        tenant_alias = u'{0}的团队'.format(enterprise.enterprise_alias)
        is_private = sn.instance.is_private()
        if is_private:
            pay_type = 'payed'
            pay_level = 'company'
        else:
            pay_type = 'free'
            pay_level = 'company'
        tenant = Tenants.objects.create(tenant_name=tenant_name, pay_type=pay_type, pay_level=pay_level,
                                        creater=creater, region=default_region.region_name,
                                        expired_time=expire_time, tenant_alias=tenant_alias,
                                        enterprise_id=enterprise.enterprise_id)
        logger.info('create tenant:{}'.format(tenant.to_dict()))
        PermRelTenant.objects.create(user_id=creater, tenant_id=tenant.pk, identity='admin',
                                     enterprise_id=enterprise.pk)
        if regions:
            for r in regions:
                TenantRegionInfo.objects.create(tenant_id=tenant.tenant_id,
                                                region_name=r,
                                                enterprise_id=enterprise.enterprise_id,
                                                is_active=True,
                                                is_init=False,
                                                region_tenant_id=tenant.tenant_id,
                                                region_tenant_name=tenant.tenant_name,
                                                region_scope='public')

        # tenant = enterprise_svc.create_and_init_tenant(creater, tenant_name, regions, user.enterprise_id)
        return tenant
Пример #5
0
 def update_tenant_config(self, action, tenant_num):
     if not action:
         raise ParamsError("参数错误")
     if action == "set-num" and not tenant_num:
         raise ParamsError("参数错误")
     if action == "open":
         self.update_config("TENANT_CREATEABLE", 1)
     elif action == "close":
         self.update_config("TENANT_CREATEABLE", 0)
     elif action == "set-num":
         max_num = LICENSE.get_authorization_tenant_number()
         if int(tenant_num) > int(max_num):
             raise TenantOverFlowError("租户数量超出最大值")
         self.update_config("TENANT_NUM", tenant_num)
Пример #6
0
    def get(self, request, *args, **kwargs):
        """
        获取所有租户信息
        ---
        parameters:
            - name: page_num
              description: 页码
              required: false
              type: string
              paramType: query
            - name: page_size
              description: 每页数量
              required: false
              type: string
              paramType: query

        """
        try:
            page = request.GET.get("page_num", 1)
            page_size = request.GET.get("page_size", 20)
            tenant_list = tenant_service.get_all_tenants()
            tenant_paginator = JuncheePaginator(tenant_list, int(page_size))
            tenants = tenant_paginator.page(int(page))
            tenants_num = Tenants.objects.count()
            allow_num = LICENSE.get_authorization_tenant_number()

            list = []

            for tenant in tenants:
                tenant_dict = {}
                user_list = tenant_service.get_tenant_users(tenant["tenant_name"])
                tenant_dict["user_num"] = len(user_list)
                tenant_dict.update(tenant)
                list.append(tenant_dict)
            bean = {"total_tenant_num": allow_num, "cur_tenant_num": tenants_num}

            result = generate_result(
                "0000", "success", "查询成功", bean=bean, list=list, total=tenant_paginator.count
            )
        except Exception as e:
            logger.exception(e)
            result = generate_error_result()
        return Response(result)
Пример #7
0
    def get_safety_config(self):
        registerable = self.get_config_by_key("REGISTERABLE")
        if not registerable:
            config = self.add_config("REGISTERABLE", 1, "bool", "云帮可否注册")
            registerable = config.value

        tenant_createable = self.get_config_by_key("TENANT_CREATEABLE")
        if not tenant_createable:
            config = self.add_config("TENANT_CREATEABLE", 1, "bool", "云帮可否注册")
            tenant_createable = config.value

        max_num = LICENSE.get_authorization_tenant_number()

        tenant_num = self.get_config_by_key("TENANT_NUM")
        if not tenant_num:
            config = self.add_config("TENANT_NUM", max_num, "int", "最大团队个数")
            tenant_num = config.value
        config_map = {}
        config_map["registerable"] = registerable
        config_map["tenant_createable"] = tenant_createable
        config_map["tenant_num"] = tenant_num

        return config_map
Пример #8
0
        def view(request, *args, **kwargs):
            self = cls(request, *args, **kwargs)

            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get

            if self.request_method in self.http_method_names:
                handler = getattr(self, self.request_method,
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed
            # 判断license是否过期 更改判断方式
            try:
                is_lisence_expired = LICENSE.is_expired()
                if is_lisence_expired and request.path != "/license":
                    return self.redirect_to('/license')
            except Exception as e:
                logger.exception(e)
                return self.redirect_to('/license?errMsg')

            if request.user.is_authenticated() and request.path != "/logout":
                user_id = request.user.user_id
                prt_num = PermRelTenant.objects.filter(user_id=user_id).count()
                if prt_num == 0:
                    logger.warning(
                        "account.login",
                        "user:{0} does not have any tenant,pls relogin!".
                        format(user_id))
                    return self.redirect_to("/logout")

                if settings.MODULES.get('SSO_LOGIN'):
                    cookies_sso_uid = request.COOKIES.get('uid')
                    if request.user.sso_user_id != cookies_sso_uid:
                        return self.redirect_to('/logout')

            response = handler(request, *args, **kwargs)
            return self.update_response(response)
Пример #9
0
    def create_and_init_tenant(self,
                               user_id,
                               tenant_name='',
                               region_names=[],
                               enterprise_id='',
                               tenant_alias='',
                               rf_username=''):
        """
        创建一个团队,并完成团队对指定数据中心的初始化
        :param user_id: 用户id
        :param tenant_name: 团队英文, 兼容历史的tenant租户名称信息
        :param tenant_alias: 团队别名, 对团队显示名称
        :param region_names: 指定需要开通的数据中心名字列表
        :param enterprise_id: 企业ID,(兼容实现,如果未指定则使用团队的tenant_id)
        :param rf_username: 注册来源用户名
        :return: 
        """
        logger.debug('create_and_init_tenant.....')
        logger.debug('user_id: {}'.format(user_id))
        logger.debug('tenant_name: {}'.format(tenant_name))
        logger.debug('region_names: {}'.format(region_names))
        logger.debug('enterprise_id: {}:'.format(enterprise_id))
        logger.debug('tenant_alias: {}'.format(tenant_alias))
        # 判断用户是否存在, 如果有enterprise_id意味着用户与enterprise已经绑定
        if enterprise_id:
            user = Users.objects.get(user_id=user_id,
                                     enterprise_id=enterprise_id)
            enterprise = TenantEnterprise.objects.get(
                enterprise_id=enterprise_id)
        else:
            user = Users.objects.get(user_id=user_id)
            enterprise = None

        if user.is_active:
            logger.info('user is already active, return default tenant')
            return Tenants.objects.get(creater=user.user_id)

        tenant_name_regx = re.compile(r'^[a-z0-9-]*$')
        if tenant_name and not tenant_name_regx.match(tenant_name):
            logger.error('bad tenant_name!')
            raise Exception(
                'tenant_name  must consist of lower case alphanumeric characters or -'
            )

        # 判断团队是否存在
        if not tenant_name:
            tenant_name = self.random_tenant_name()
            logger.info(
                'tenant_name not specify, generator [{}]'.format(tenant_name))

        tenants_num = Tenants.objects.filter(tenant_name=tenant_name).count()
        if tenants_num > 0:
            raise Exception('team {} already existed!'.format(tenant_name))

        # 根据lisence确定是否可以创建新的团队
        is_private = sn.instance.is_private()
        if is_private:
            tenants_num = Tenants.objects.count()
            allow_num = LICENSE.get_authorization_tenant_number()
            # 如果租户数量>license允许值
            if tenants_num > allow_num:
                raise Exception('only {} team can create.'.format(allow_num))

        # 私有云用户默认都是企业付费用户,公有云默认用户是免费企业用户
        if is_private:
            pay_type = 'payed'
            pay_level = 'company'
        else:
            pay_type = 'free'
            pay_level = 'company'

        expired_day = 7
        if hasattr(settings, "TENANT_VALID_TIME"):
            expired_day = int(settings.TENANT_VALID_TIME)
        expire_time = dt.datetime.now() + dt.timedelta(days=expired_day)

        # 计算此团队需要初始化的数据中心
        region_configs = {r.get('name'): r for r in regionConfig.regions()}

        if not region_configs:
            raise Exception('please config one region at least.')

        prepare_init_regions = []
        if region_names:
            for region_name in region_names:
                if region_name in region_configs:
                    prepare_init_regions.append(
                        region_configs.get(region_name))
        else:
            prepare_init_regions.extend(region_configs.values())

        if not prepare_init_regions:
            raise Exception('please init one region at least.')

        logger.info('prepared init region: {}'.format(
            [r.get('name') for r in prepare_init_regions]))
        # 团队管理的默认数据中心
        default_region = prepare_init_regions[0]

        # 使用已存在的企业
        if enterprise:
            logger.info('enterprise existed: {}'.format(
                enterprise.enterprise_name))

            if not tenant_alias:
                tenant_alias = u'{0}的团队'.format(enterprise.enterprise_alias)
            # 创建团队
            tenant = Tenants.objects.create(
                tenant_name=tenant_name,
                pay_type=pay_type,
                pay_level=pay_level,
                creater=user_id,
                region=default_region.get('name'),
                expired_time=expire_time,
                tenant_alias=tenant_alias,
                enterprise_id=enterprise.enterprise_id,
                limit_memory=4096)
            logger.info('create tenant:{}'.format(tenant.to_dict()))

        # 兼容用现有的团队id建立企业信息
        else:
            logger.info(
                'enterprise not existed, use tenant for default enterprise.')
            if not tenant_alias:
                tenant_alias = u'{0}的团队'.format(tenant_name)

            # 创建团队
            tenant = Tenants.objects.create(tenant_name=tenant_name,
                                            pay_type=pay_type,
                                            pay_level=pay_level,
                                            creater=user_id,
                                            region=default_region.get('name'),
                                            expired_time=expire_time,
                                            tenant_alias=tenant_alias,
                                            limit_memory=4096)
            logger.info('create tenant:{}'.format(tenant.to_dict()))

            # 依赖团队信息创建企业信息
            enterprise = TenantEnterprise.objects.create(
                enterprise_name=tenant_name,
                enterprise_alias=tenant_name,
                enterprise_id=tenant.tenant_id)
            logger.info('create enterprise with tenant:{}'.format(
                enterprise.to_dict()))

            # 将企业id关联到团队之上
            tenant.enterprise_id = enterprise.enterprise_id
            tenant.save()

            # 将此用户与企业关系绑定
            user.enterprise_id = enterprise.enterprise_id

        monitor_hook.tenantMonitor(tenant, user, "create_tenant", True)

        # 创建用户团队企业关系及权限,创建团队的用户即为此团队的管理员
        logger.debug(
            'create tenant_perm! user_pk: {0}, tenant_pk:{1}, enterprise_pk:{2}'
            .format(user_id, tenant.pk, enterprise.pk))
        PermRelTenant.objects.create(user_id=user_id,
                                     tenant_id=tenant.pk,
                                     identity='owner',
                                     enterprise_id=enterprise.pk)

        # 初始化数据中心并建立团队与数据中心的关系
        api = RegionInvokeApi()
        for region in prepare_init_regions:
            tenant_region = TenantRegionInfo.objects.create(
                tenant_id=tenant.tenant_id,
                region_name=region.get('name'),
                enterprise_id=enterprise.enterprise_id)
            try:
                res, body = api.create_tenant(region.get('name'),
                                              tenant.tenant_name,
                                              tenant.tenant_id,
                                              enterprise.enterprise_id)
                logger.debug(res)
                logger.debug(body)
                tenant_region.is_active = True
                tenant_region.is_init = True

                # todo 将从数据中心获取的租户信息记录到tenant_region, 当前只是用tenant的数据填充
                tenant_region.region_tenant_id = tenant.tenant_id
                tenant_region.region_tenant_name = tenant.tenant_name
                tenant_region.region_scope = 'public'

                tenant_region.save()
                logger.info("tenant_region[{0}] = {1}, {2}, {3}".format(
                    tenant_region.region_name, tenant_region.region_tenant_id,
                    tenant_region.region_tenant_name,
                    tenant_region.region_scope))

                monitor_hook.tenantMonitor(tenant, user, "init_tenant", True)
                logger.info("init success!")
            except Exception as e:
                logger.error("init failed: {}".format(e.message))
                logger.exception(e)

                tenant_region.is_init = False
                tenant_region.is_active = False
                tenant_region.save()
                monitor_hook.tenantMonitor(tenant, user, "init_tenant", False)

        user.is_active = True
        user.save()

        try:
            content = '新用户: {0}, 手机号: {1}, 租户: {2}, 邮箱: {3}, 企业: {4}, 微信名: {5}'.format(
                user.nick_name, user.phone, tenant.tenant_name, user.email,
                enterprise.enterprise_alias, rf_username)
            send_mail("new user active tenant", content,
                      '*****@*****.**', notify_mail_list)
        except Exception:
            pass

        return tenant