Пример #1
0
 def post(self, request):
     email = request.data.get('email')
     password = request.data.get('password')
     if email is None or password is None:
         raise CommonException(detail=gettext(messages.NO_CREDENTIALS),
                               code=codes.NO_CREDENTIALS)
     try:
         user = MainUser.objects.get(email=email)
         if not user.check_password(password):
             raise CommonException(detail=gettext(
                 messages.WRONG_EMAIL_OR_PASSWORD),
                                   code=codes.WRONG_EMAIL_OR_PASSWORD)
     except MainUser.DoesNotExist:
         raise CommonException(
             detail={gettext(messages.EMAIL_DOESNT_EXIST)},
             code=codes.EMAIL_DOESNT_EXIST)
     token = get_token(user)
     user.last_login = datetime.now()
     user.save()
     url = "http://dev.cheesenology.kz:8080/camunda/app/admin/default/#/login"
     serializer = MainUserSerializer(user)
     return Response({
         'token': token,
         'user': serializer.data
     },
                     status=status.HTTP_200_OK)
Пример #2
0
 def validate(self, attrs):
     if not self.context['request'].user.check_password(attrs['password']):
         raise CommonException(detail=messages.WRONG_PASSWORD,
                               code=codes.WRONG_PASSWORD)
     if attrs['password1'] != attrs['password2']:
         raise CommonException(detail=messages.PASSWORDS_NOT_SAME,
                               code=codes.PASSWORDS_NOT_SAME)
     return attrs
Пример #3
0
    def do_when_remove_cluster(self):
        def check():
            for container_node in self.container_nodes:
                container_status = zk_opers.retrieve_container_status_value(
                    self.cluster, container_node)
                if container_status.get('status') != Status.destroyed:
                    return
            return True

        zk_opers = Container_ZkOpers()
        ret = handleTimeout(check, (50, 4))
        if not ret:
            raise CommonException(
                'remove containers %s in containerCluster:%s failed' %
                (self.containers, self.cluster))
        for container_node in self.container_nodes:
            logging.info('do delete container node :%s info in zookeeper' %
                         container_node)
            zk_opers.delete_container_node(self.cluster, container_node)

        cluster_info = zk_opers.retrieve_container_cluster_info(self.cluster)
        node_count = cluster_info.get('containerCount')
        _node_count = int(node_count) - len(self.containers)
        cluster_info.update({'containerCount': _node_count})
        cluster_info.update({'start_flag': Status.succeed})
        zk_opers.write_container_cluster_info(cluster_info)
Пример #4
0
    def validateResource(self, component_container_cluster_config):
        zkOper = Common_ZkOpers()
        ip_list = zkOper.get_ips_from_ipPool()
        nodeCount = component_container_cluster_config.nodeCount

        if len(ip_list) < nodeCount:
            raise CommonException('ips are not enough!')
Пример #5
0
    def cal_price(self, price, coupon_record):
        """
         price:原价格
         coupon_record:优惠券对象
         目的:计算优惠后的价格
        :param price:
        :param coupon_record:
        :return:
        """
        # 获取优惠券的类型
        coupon_type = coupon_record.coupon.coupon_type

        if coupon_type == 0:  # 立减券
            money_equivalent_value = coupon_record.coupon.money_equivalent_value
            rebate_price = price - money_equivalent_value
            if rebate_price < 0:
                rebate_price = 0
        elif coupon_type == 1:  # 满减券
            minimum_consume = coupon_record.coupon.minimum_consume
            if price > minimum_consume:
                money_equivalent_value = coupon_record.coupon.money_equivalent_value
                rebate_price = price - money_equivalent_value
            else:
                raise CommonException("优惠券不符合条件", 1008)
        elif coupon_type == 2:
            off_percent = coupon_record.coupon.off_percent
            rebate_price = price * (off_percent / 100)
        else:
            rebate_price = price

        return rebate_price
Пример #6
0
 def issue_image(self):
     image = self.docker_model.image
     logging.info('create container image :%s' % image)
     exist = self.image_opers.image_exist(image)
     if not exist:
         if not self.image_opers.pull(image):
             raise CommonException(
                 'pull image %s failed, please check reason' % image)
Пример #7
0
    def create(self, args={}):
        logging.info('args:%s' % str(args))

        _component_type = args.get('componentType')
        cluster = args.get('containerClusterName')
        logging.info('component_type : %s' % str(_component_type))
        logging.info('containerClusterName : %s' % cluster)

        _component_container_cluster_config = args.get('component_config')
        """
            ---------------------------------  resource validate ---------------------------------------------
        """

        is_res_verify = _component_container_cluster_config.is_res_verify
        if is_res_verify:
            self.resource.validateResource(_component_container_cluster_config)

        host_ip_list = self.resource.elect_servers(
            _component_container_cluster_config)

        logging.info('host_ip_list:%s' % str(host_ip_list))
        args.setdefault('host_ip_list', host_ip_list)

        NIC = self.retrieve_cluster_NIC()
        args.setdefault('NIC', NIC)

        ip_port_resource_list = self.resource.retrieve_ip_port_resource(
            host_ip_list, _component_container_cluster_config)
        args.setdefault('ip_port_resource_list', ip_port_resource_list)
        """
            ---------------------------------  get create container params--------------------------------------
        """

        logging.info('show args to get create containers args list: %s' %
                     str(args))
        container_model_list = self.base_container_model_creator.create(args)
        """
            ---------------------------- dispatch creating task and check the result----------------------------
        """

        self.__dispatch_create_container_task(container_model_list)

        created = self.__check_containers_started(
            _component_container_cluster_config)
        if not created:
            raise CommonException(
                'cluster started failed, maybe part of nodes started, other failed!'
            )

        _action_flag = True
        if _component_container_cluster_config.need_validate_manager_status:
            _action_flag = self.component_manager_status_validator.validate_manager_status_for_cluster(
                _component_type, container_model_list)

        logging.info('validator manager status result:%s' % str(_action_flag))
        _action_result = Status.failed if not _action_flag else Status.succeed
        return _action_result
Пример #8
0
 def __get_needed_ports(self, host_ip, start_port, port_count):
     port_list = []
     while True:
         start_port += 1
         if start_port > 65535:
             raise CommonException('port are not enough, maybe start port are too small')
         if not nc_ip_port_available(host_ip, start_port):
             port_list.append(start_port)
         if len(port_list) >= port_count:
             break
     return port_list
Пример #9
0
 def validate(self, attrs):
     try:
         attrs['email']
     except:
         return attrs
     if attrs['email'] is not None:
         if self.context['request'].user.email != attrs['email']:
             if MainUser.objects.filter(email=attrs['email']).exists():
                 raise CommonException(detail=messages.ALREADY_EXIST,
                                       code=codes.ALREADY_EXIST)
     return attrs
Пример #10
0
    def __issue_create_action(self):

        self.__make_mount_dir()

        self.issue_image()

        _log_docker_run_command(self.docker_model)
        '''
        orginal:
            image=image_name,
            hostname=container_name,
            name=container_name,
            environment=env,
            ports=_ports,
            mem_limit=_mem_limit,
            volumes=_volumes
        '''
        self.docker_opers.create(self.docker_model)
        '''
        orginal:
            container_name,
            privileged=True,
            network_mode='bridge',
            binds=_binds
        '''
        self.docker_opers.start(self.docker_model)

        container_node_info = self._get_container_info()
        logging.info('get container info: %s' % str(container_node_info))
        self.container_opers.write_container_node_info_to_zk(
            Status.starting, container_node_info)
        '''
            set route if use ip to create containers
        '''
        container_name = self.docker_model.name
        '''
            check if create successful
        '''
        result = self.__check_create_status()
        if not result:
            error_message = 'container created exited'
            logging.error(error_message)
            failed_flag = {'status': Status.failed, 'message': error_message}
            self.container_opers.write_container_status_by_containerName(
                container_name, failed_flag)
            raise CommonException(error_message)

        started_flag = {'status': Status.started, 'message': ''}
        self.container_opers.write_container_status_by_containerName(
            container_name, started_flag)
Пример #11
0
    def pull(self, image):
        image_name_list = self.image_name_list()
        if image in image_name_list:
            logging.info('image exist, no need to pull')
            return True

        repository, tag = self.tag(image)
        pull_result = self.client.pull(repository=repository,
                                       tag=tag,
                                       stream=True)
        for line in pull_result:
            parsed = json.loads(line)
            if 'error' in parsed:
                raise CommonException(parsed['error'])
Пример #12
0
    def elect_servers(self, component_container_cluster_config):
        '''
            get usable servers and their resource.
        '''
        host_resource_dict = self.retrieve_usable_host_resource(
            component_container_cluster_config)
        if not host_resource_dict:
            raise CommonException('there is no usable servers!')
        '''
           count servers' scores
        '''

        resource_weight__score = component_container_cluster_config.resource_weight__score

        host_score_dict = self.__count_score(host_resource_dict,
                                             resource_weight__score)
        logging.info('host and score:%s' % str(host_score_dict))
        '''
            elect servers by their scores
        '''
        host_score_list = sorted(host_score_dict.items(),
                                 key=lambda i: i[1],
                                 reverse=True)
        logging.info('host score list:%s' % host_score_list)
        host_list = [i[0] for i in host_score_list]
        logging.info('select host list :%s' % str(host_list))
        '''
            servers available after validating
        '''

        node_count = component_container_cluster_config.nodeCount
        if len(host_list) < node_count:
            raise CommonException(
                'the number of usable servers are not enough!')

        return host_list[:node_count]
Пример #13
0
def dispatch_mutil_task(request_ip_port_params_list, uri, http_method):
    http_client = AsyncHTTPClient()
    _error_record_dict = {}
    adminUser, adminPasswd = _retrieve_userName_passwd()
    try:
        _key_sets = set()
        for (req_ip, req_port, params) in request_ip_port_params_list:
            requesturl = "http://%s:%s%s" % (req_ip, req_port, uri)
            logging.info('requesturi: %s' % requesturl)
            logging.info('dispatch mutil task params :%s' % str(params))
            request = HTTPRequest(url=requesturl,
                                  method=http_method,
                                  body=urllib.urlencode(params),
                                  connect_timeout=40,
                                  request_timeout=40,
                                  auth_username=adminUser,
                                  auth_password=adminPasswd)

            callback_key = "%s_%s_%s" % (uri, req_ip, req_port)
            _key_sets.add(callback_key)
            http_client.fetch(request, callback=(yield Callback(callback_key)))

        for callback_key in _key_sets:
            response = yield Wait(callback_key)

            if response.error:
                return_result = False
                error_record_msg = "remote access,the key:%s,error message:%s" % (
                    callback_key, response.error)
            else:
                return_result = response.body.strip()

            if cmp('false', return_result) == 0:
                callback_key_ip = callback_key.split("_")[-1]
                _error_record_dict.setdefault(callback_key_ip,
                                              error_record_msg)

        if len(_error_record_dict) > 0:
            raise CommonException('request occurs error! detail: %s' %
                                  str(_error_record_dict))
        else:
            logging.info('request finished all!')

    finally:
        http_client.close()
Пример #14
0
    def cal_coupon_price(self, price, coupon_record):

        coupon_type = coupon_record.coupon.coupon_type
        money_equivalent_value = coupon_record.coupon.money_equivalent_value
        off_percent = coupon_record.coupon.off_percent
        minimum_consume = coupon_record.coupon.minimum_consume
        rebate_price = 0
        if coupon_type == 0:  # 立减卷
            rebate_price = price - money_equivalent_value
            if rebate_price < 0:
                rebate_price = 0
        elif coupon_type == 1:  # 满减卷
            if price < minimum_consume:  # 不满足最低消费
                raise CommonException('不满足最低消费', 1060)
            rebate_price = price - money_equivalent_value
        else:  # 折扣
            rebate_price = price * off_percent / 100
            print(rebate_price)
        return rebate_price
Пример #15
0
    def post(self, request, *args, **kwargs):
        res = BaseResponse()
        # 1 获取数据
        user = request.user
        course_id_list = request.data.get('course_id_list')
        try:
            # 清空操作
            # 找到所有的account_user_id_*,全部清空
            # del_list = REDIS_CONN.keys(ACCOUNT_KEY % (user.pk, "*"))
            # REDIS_CONN.delete(*del_list)
            # 2 循环课程列表为每个课程建立数据结构
            for course_id in course_id_list:
                account_key = ACCOUNT_KEY % (user.pk, course_id)
                account_dict = {}
                shopping_car_key = SHOPPING_CAR_KEY % (user.pk, course_id)
                # 判断课程是否存在购物车中
                if not REDIS_CONN.exists(shopping_car_key):
                    raise CommonException('购物车中该课程不存在', 1040)
                # 将课程信息加入到结算字典中
                course_info = REDIS_CONN.hgetall(shopping_car_key)
                account_dict['course_info'] = course_info

                # 将课程优惠卷加入到每一个课程结算字典中
                # 查询与当前用户拥有没使用的,在有效期且与课程相关的优惠卷
                account_dict['course_coupons'] = self.get_coupon_dict(
                    request, course_id)

                # 存储结算信息
                REDIS_CONN.set(account_key, json.dumps(account_dict))
                # 存储通用优惠卷,加入到redis中
                REDIS_CONN.set('global_coupon_%s' % user.pk,
                               json.dumps(self.get_coupon_dict(request)))
                res.code = 1044
                res.data = '成功'
                # print(json.loads(REDIS_CONN.get(account_key)))
        except CommonException as e:
            res.code = e.code
            res.error = e.msg
        except Exception as e:
            res.code = 500
            res.error = str(e)
        return Response(res.dict)
Пример #16
0
    def write_container_node_info_to_zk(self, container_stat, containerProps):

        inspect = containerProps.get('inspect')
        is_use_ip = containerProps.get('isUseIp')
        con = Container_Model(inspect=inspect)
        container_name = con.name()
        cluster = con.cluster(container_name)
        logging.info('get container cluster :%s' % cluster)
        if is_use_ip:
            container_node = con.ip()
            logging.info('get container ip :%s' % container_node)
            if not (container_node and cluster):
                raise CommonException(
                    'get container ip or cluster name failed, not write this info, inspect:%s'
                    % (inspect))

            container_node = container_node
        else:
            container_node = container_name

        zkOper = Container_ZkOpers()
        zkOper.write_container_node_info(cluster, container_node,
                                         container_stat, containerProps)
Пример #17
0
def _request_fetch(request):
    #access to the target ip machine to retrieve the dict,then modify the config
    http_client = HTTPClient()

    response = None
    try:
        response = http_client.fetch(request)
    finally:
        http_client.close()

    return_result = False
    if response is None:
        raise CommonException('response is None!')

    if response.error:
        return_result = False
        message = "remote access,the key:%s,error message:%s" % (
            request, response.error)
        logging.error(message)
    else:
        return_result = response.body.strip()

    return return_result
Пример #18
0
    def post(self, request):
        '''
        {

        "courses_info":[
                     {
                      course_id:1,
                      price_policy_id:1,
                      coupon_record_id:2
                     },
                      {
                      course_id:2,
                      price_policy_id:5,
                      coupon_record_id:3
                     }
                     ]

        global_coupon_id:1,
        beli:1000,
        "pay_money":268,

        }

        :param request:
        :return:
        '''
        # 1 获取数据
        user = request.user
        courses_info = request.data.get('courses_info')
        global_coupon_id = request.data.get('global_coupon_id')
        beili = request.data.get('beili')
        pay_money = request.data.get('pay_money')
        res = BaseResponse()
        now = datetime.datetime.utcnow()
        # 2 循环课程信息
        try:
            course_price_list = []
            for course_info in courses_info:
                course_id = course_info.get('course_id')
                price_policy_id = course_info.get('price_policy_id')
                coupon_record_id = course_info.get('coupon_record_id')
                # 3 校验数据
                # 3.1 课程是否存在
                course_obj = models.Course.objects.get(pk=course_id)

                # 3.2 价格策略是否合法
                if price_policy_id not in [
                        obj.pk for obj in course_obj.price_policy.all()
                ]:
                    raise CommonException('价格策略不存在', 1050)
                # 3.3 课程优惠卷是否合法
                coupon_record = models.CouponRecord.objects.filter(
                    pk=coupon_record_id,
                    user=request.user,
                    status=0,  # 此优惠卷是否被使用
                    coupon__valid_begin_date__lte=now,  # 有效期开始时间
                    coupon__valid_end_date__gt=now,  # 有效期结束时间
                    coupon__object_id=course_id,
                    coupon__content_type=10,
                ).first()

                if not coupon_record:
                    raise CommonException('课程优惠卷不合法', 1052)
                # 3.4 计算课程优惠卷的惠后价格
                course_price = models.PricePolicy.objects.get(
                    pk=price_policy_id).price
                coupon_price = self.cal_coupon_price(course_price,
                                                     coupon_record)
                course_price_list.append(coupon_price)
            # 4 通用优惠卷处理
            # 4.1 校验通用优惠卷是否合法
            global_coupon_record = models.CouponRecord.objects.filter(
                pk=global_coupon_id,
                user=request.user,
                status=0,  # 此优惠卷是否被使用
                coupon__valid_begin_date__lte=now,  # 有效期开始时间
                coupon__valid_end_date__gt=now,  # 有效期结束时间
                coupon__object_id=None,
                coupon__content_type=10,
            ).first()
            if not global_coupon_record:
                raise CommonException('通用优惠卷不合法', 1053)
            # 4.2 计算通用优惠卷优惠后的价格
            global_coupon_price = self.cal_coupon_price(
                sum(course_price_list), global_coupon_record)
            # 5 处理贝利
            # 5.1 校验贝利是否充足
            if beili > request.user.beili:
                raise CommonException('贝利不足', 1054)
            # 5.2 计算贝利后的价格
            final_price = global_coupon_price - beili / 10
            print(final_price)
            if final_price < 0:
                final_price = 0
            # 6 比较前端传来的结果(pay_money)和我算出的价格是否一致
            if final_price != pay_money:
                raise CommonException('实际支付价格与参数价格不一致', 1055)
            # 7 订单信息
            # Order记录
            # OrderDetail
            # OrderDetail
            # OrderDetail

            # 8 构建支付宝二维码页面
            import time
            alipay = self.get_alipay()
            # 生成支付的url
            query_params = alipay.direct_pay(
                subject="Django课程",  # 商品简单描述
                out_trade_no="x2" + str(time.time()),  # 商户订单号
                total_amount=pay_money,  # 交易金额(单位: 元 保留俩位小数)
            )

            pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(
                query_params)
            res.data = '订单创建成功'
            res.url = pay_url

        except ObjectDoesNotExist as e:
            print(e)
            res.code = 1050
            res.error = '课程不存在'

        except CommonException as e:
            res.code = e.code
            res.error = e.msg

        except Exception as e:
            res.code = 500
            res.error = str(e)
        return Response(res.dict)
Пример #19
0
    def create(self, request, *args, **kwargs):
        '''
        请求发送的数据:
        {
          courses:{
                        1:{
                           choose_price_id:1,
                           coupon_id:2,
                        },
                        2:{
                          choose_price_id:4,
                          coupon_record_id:3,
                          },
                    },

          global_coupon_id:3,

          beli:2000,
          total_money:2000

        }

        计算价格优先级

           (课程1原价格*课程1优惠券+课程2原价格*课程2优惠券)*通用优惠券-贝里/10

        '''

        res = BaseResponse()

        try:
            # 1 获取数据
            user = request.user
            beli = int(request.data.get("beli", 0))
            courses_dict = request.data.get("courses")
            global_coupon_id = request.data.get("global_coupon_id")
            total_money = request.data.get("total_money")

            # 2 校验数据

            # 2.1 校验内里数是否在登录用户实际拥有范围内
            if user.beli < beli:
                raise CommonException("贝里数有问题!", 1004)

            # 2.2 校验课程信息
            now = datetime.datetime.now()
            course_price_list = []
            for course_pk, course_info in courses_dict.items():

                # 2.2.2 校验课程是否存在
                course_obj = Course.objects.filter(pk=course_pk).first()
                if not course_obj:
                    raise CommonException("课程不存在!", 1002)

                if course_obj.status != 0:
                    raise CommonException("课程未上线或者已下线!", 1005)

                # 2.2.3 校验价格策略
                choose_price_id = course_info.get("choose_price_id")

                price_policy_all = course_obj.price_policy.all()

                if choose_price_id not in [obj.pk for obj in price_policy_all]:
                    raise CommonException("价格策略错误!", 1003)

                # 2.2.4 校验课程优惠券

                coupon_record_id = course_info.get("coupon_record_id")

                coupon_record = CouponRecord.objects.filter(
                    pk=coupon_record_id,
                    user=user,
                    status=0,
                    coupon__valid_begin_date__lt=now,
                    coupon__valid_end_date__gt=now,
                ).first()

                if not coupon_record:
                    raise CommonException("优惠券有问题!", 1006)

                rel_course_obj = coupon_record.coupon.content_object
                if course_obj != rel_course_obj:
                    raise CommonException("优惠券与课程不匹配!", 1007)

                # 计算优惠后的价格
                price = PricePolicy.objects.filter(
                    pk=choose_price_id).first().price
                rebate_price = self.cal_price(price, coupon_record)
                course_price_list.append(rebate_price)

            # 2.3 校验通用优惠券合法性
            global_coupon_record = CouponRecord.objects.filter(
                pk=global_coupon_id,
                user=user,
                status=0,
                coupon__valid_begin_date__lt=now,
                coupon__valid_end_date__gt=now,
            ).first()

            if not global_coupon_record:
                raise CommonException("通用优惠券有问题!", 1009)

            # 2.4 校验最终价格是否一致
            cal_price = self.cal_price(sum(course_price_list),
                                       global_coupon_record)

            final_price = cal_price - beli / 10

            if final_price < 0:
                final_price = 0

            if total_money != final_price:
                raise CommonException("支付价格有问题!", 1010)

            # 3 生成订单
            # Order记录
            # OrderDetail
            # OrderDetail

            # 4 调用支付宝接口

            # alipay = ali()
            # 生成支付的url
            # query_params = alipay.direct_pay(
            #     subject="Django课程",  # 商品简单描述
            #     out_trade_no="x2" + str(time.time()),  # 商户订单号
            #     total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
            # )
            #
            # pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
            #
            # return redirect(pay_url)

            # 注意:
            # POST请求访问notify_url:
            # 更改订单
            # 更改优惠券
            # 更改贝里数

            # GET请求return_url,用于页面的跳转展示

        except CommonException as e:
            res.code = 1004
            res.error = e.error

        return Response(res.dict)