Пример #1
0
def main():
    tasks = [
        hoarder_payment_tracking, hoarder_redeem_tracking,
        hoarder_asset_fetching
    ]

    for task in tasks:
        mq = task.get_broker()
        counter = Counter()
        while True:
            job = mq.peek_buried()
            if not job:
                break

            info = {'body': job.body, 'task': task}
            if counter[job.body] >= MAX_RETRY:
                log = 'Job of tube is deleted'
                rsyslog.send('%s: %r' % (log, info),
                             tag='cron_hoarder_sync_kick_ruined')
                sentry.captureMessage(log, extra=info)
                job.delete()
                continue
            mq.kick()
            rsyslog.send('Kicking job %(body)s of tube %(task)s' % info,
                         tag='cron_hoarder_sync_kick_history')
            counter[job.body] += 1
Пример #2
0
def login():
    '''
        login method
    '''
    login_form = LoginForm()
    rsyslog.send(u'login request(%s,%s,%s)' %
                 (login_form.alias.data, login_form.password.data, datetime.now()),
                 tag='login')
    try:
        if login_form.validate():
            res = _login(login_form.alias.data, login_form.password.data, True)
            sentry.captureMessage('Login Result',
                                  extra={'result': res, 'alias': login_form.alias.data})
            rsyslog.send(u'login result --- (%s,%s,%s)' %
                         (login_form.alias.data, res, datetime.now()),
                         tag='login')
            if errors.err_ok == res:
                return '', 204
            else:
                return jsonify(errors=[{
                    'message': login_err_msg_dict[res]}]), 403
        sentry.captureMessage(login_form.failure, extra={'alias': login_form.alias})
        return jsonify(errors=login_form.failure), 400

    except Exception as ex:
        sentry.captureException(ex, extra={'id': login_form.alias, 'pass': '******'})
        rsyslog.send(u'login error --- (%s,%s,%s)' %
                     (login_form.alias.data, ex.message, datetime.now()),
                     tag='login')
        return jsonify(errors=ex.message), 500
Пример #3
0
def yxpay_placebo_notify():
    if request.remote_addr not in ['111.207.203.195', '219.143.6.195']:
        abort(403)

    try:
        response = make_response(json.loads(request.form['msg']),
                                 SinglePaymentResult)
        status = YixinPaymentStatus(int(response.state))
    except (ValueError, TypeError):
        abort(400)

    order = PlaceboOrder.get_by_biz_id(response.biz_id)
    if not order:
        abort(404)

    if status is YixinPaymentStatus.SUCCESS:
        order.mark_as_exited(response)
    else:
        sentry.captureMessage('体验金订单回款失败',
                              extra={
                                  'order_id': order.id_,
                                  'biz_id': response.biz_id,
                                  'status': status,
                              })

    return '', 204
Пример #4
0
def warn_for_broken_account(sender, previous_status, current_status):
    if current_status is not WalletAccount.Status.broken:
        return
    ids = WalletTransaction.get_ids_by_account(sender.id_)
    if ids:
        sentry.captureMessage(u'有交易的零钱包帐号被报异常', extra={
            'previous_status': previous_status,
            'current_status': current_status,
            'wallet_account_id': sentry.id_,
            'transaction_ids': ids,
        })
Пример #5
0
 def _add(self, order, package):
     sql = ('insert into {.table_name} (order_id, package_id,'
            'creation_time) values (%s, %s, %s)').format(self)
     params = (order.id_, package.id_, datetime.now())
     try:
         db.execute(sql, params)
     except MySQLdb.IntegrityError:
         sentry.captureMessage(
             'Error: repeatedly distribute package to %s ' % order.id_)
         return
     db.commit()
Пример #6
0
    def change_owner(self, new_user):
        """为设备调整所属登录用户"""
        if new_user.id_ == self.user_id:
            sentry.captureMessage('try to change owner to self %s' %
                                  self.user_id)
            return

        sql = ('update {.table_name} set user_id=%s, status=%s '
               'where user_id=%s and device_id=%s').format(self)
        params = (new_user.id_, self.Status.active.value, self.user_id,
                  self.device_id)

        #: 清除原用户相关缓存
        self.clear_all_cache(self.id_, self.user_id, self.device_id,
                             self.platform)

        #: 更新所属为新用户
        self.user_id = new_user.id_
        self.clear_cached_properties()
        self._commit_and_refresh(sql, params)
Пример #7
0
def bind_mobile():
    if not g.user:
        return jsonify(r=False, error=u'登录会话已过期,请重新登录')

    if g.user.mobile:
        return jsonify(r=False, error=u'您已经绑定了手机号,无需再次绑定')

    # check referer
    if not request.environ.get('HTTP_REFERER'):
        sentry.captureMessage('No HTTP_REFERER when %s visits' % g.user.id)
        return jsonify(r=False, error=u'未知错误,错误代码BM01,请联系客服处理')
    referer = url_parse(request.environ.get('HTTP_REFERER'))

    if not all([referer.scheme == request.scheme,
                referer.netloc == request.host,
                referer.path in BIND_MOBILE_WHITELIST]):
        sentry.captureMessage('Invalid bind request from %s' % g.user.id)
        return jsonify(r=False, error=u'未知错误,错误代码BM02,请联系客服处理')

    mobile = request.form.get('mobile')
    # limit phone
    l = Limit.get(LIMIT.MOBILE_BIND % mobile, timeout=60 * 60, limit=5)
    if l.is_limited():
        return jsonify(r=False, error=u'发送短信过于频繁, 请您稍后再试')
    l.touch()

    # limit ip
    l = Limit.get(LIMIT.IP_MOBILE_BIND % request.remote_addr,
                  timeout=10 * 60, limit=10)
    if l.is_limited():
        return jsonify(r=False, error=u'发送短信过于频繁, 请您稍后再试')
    l.touch()

    try:
        pre_bind(mobile)
    except BindError as e:
        return jsonify(r=False, error=e.args[0])
    else:
        return jsonify(r=True)
Пример #8
0
    def say(self,
            text,
            markdown=True,
            channel=None,
            attachments=None,
            skip_duplication=True):
        data = {'text': unicode(text), 'markdown': bool(markdown)}
        channel = channel or self.channel
        if channel is not None:
            data['channel'] = unicode(channel)
        if attachments is not None:
            data['attachments'] = list(attachments)

        payload = json.dumps(data, sort_keys=True)
        payload_digest = hashlib.sha1(bytes(payload)).hexdigest()
        payload_extra = {'payload': data, 'channel': self.channel}

        if skip_duplication and mc.sismember(self.url, payload_digest):
            sentry.captureMessage(
                'BearyChat Robot "%s" skipped duplicated messages' % self.name,
                level=logging.INFO,
                extra=payload_extra)
            return

        response = self.session.post(self.url, data={'payload': payload})
        if response.status_code == 410:
            sentry.captureMessage('BearyChat Robot "%s" has been paused' %
                                  self.name,
                                  level=logging.INFO,
                                  extra=payload_extra)
            return
        else:
            response.raise_for_status()

        # mark as sent
        mc.sadd(self.url, payload_digest)

        return response
Пример #9
0
def warning(message, **kwargs):
    extra = {'user': request.oauth.user}
    extra.update(kwargs)
    return sentry.captureMessage(message, extra=extra, level=WARNING)
Пример #10
0
    def add(cls, product_info):
        from .wrapped_product import ZhiwangWrappedProduct
        from .wrapper_kind import WrapperKind

        pid = product_info.pop('product_id')
        ptype = product_info.pop('product_type')
        start_sell_date = product_info.pop('start_sell_date')
        end_sell_date = product_info.pop('end_sell_date')

        # 判断产品类型是否被支持
        try:
            ptype = cls.Type(ptype)
        except ValueError:
            raise InvalidProductError(ptype)

        # 将产品基本属性记入数据库
        existence = cls.get(pid)
        if existence:
            original_total_amount = existence.total_amount

        sql = (
            'insert into {.table_name} (product_id, product_type, start_sell_date, '
            'end_sell_date, creation_time) values (%s, %s, %s, %s, %s) '
            'on duplicate key update product_id=product_id').format(cls)
        params = (pid, ptype.value, start_sell_date, end_sell_date,
                  datetime.datetime.now())
        db.execute(sql, params)
        db.commit()

        cls.clear_cache(pid)
        cls.clear_cache_by_date(datetime.date.today())

        instance = cls.get(pid)

        # FIXME: 对不定期产品房贷宝的利率阶梯的数据加工应当在包中处理完毕
        if ptype is cls.Type.fangdaibao:
            detail_dict = {
                'last_due_date':
                product_info.detail_config.last_due_date,
                'annual_rate_layers':
                product_info.detail_config.annual_rate_layers,
            }
            product_info.update(detail_dict)
            vars(product_info).update(detail_dict)
            product_info.pop('detail_config')

        # 更新指旺产品最新参数
        for name in product_info:
            # 检查是否有未支持的属性
            if not isinstance(getattr(instance.__class__, name, None),
                              PropsItem):
                sentry.captureMessage('Follow attribute is not supported',
                                      attr_name=name)
                continue

            value = getattr(product_info, name)
            if isinstance(value, Decimal) or isinstance(value, datetime.date):
                value = str(value)
            if isinstance(value, Arrow):
                value = value.isoformat()
            setattr(instance, name, value)

        # 当销售周期内产品额度发生变化时,发出BC通知
        if existence:
            increment = instance.total_amount - original_total_amount
            if increment > 0 and bearychat.configured:
                bearychat.say(u'指旺端刚刚为%s增加了%s额度,请周知。' %
                              (existence.local_name, increment))

        # 对于房贷宝产品还需创建包装产品和调整额度分配
        if instance.product_type is cls.Type.fangdaibao:
            if existence:
                # 当销售周期内产品总额度发生变化且销售模式为互斥时,将新增额度默认分配给主产品(自选到期产品)
                if existence.sale_mode is SaleMode.mutex and increment > 0:
                    instance.allocated_amount = str(instance.allocated_amount +
                                                    increment)
            else:
                # 将房贷宝产品销售模式置为互斥模式
                instance.sale_mode = SaleMode.mutex
                # 房贷宝产品创建子产品
                wrappeds = [
                    ZhiwangWrappedProduct.create(instance, k)
                    for k in (WrapperKind.get_multi_by_raw_product_type(
                        instance.product_type))
                ]
                # 根据既定规则及当前销售模式进行额度分配
                raw_allocation, sub_allocation = coordinate_fdb_allocation(
                    instance, wrappeds)
                adjust_products_allocation(SaleMode.mutex, instance,
                                           raw_allocation, sub_allocation)
        return instance