Exemple #1
0
    def set_user_id():
        """在请求之前设置 session uid,方便 APM 标识用户"""
        from everyclass.server.consts import SESSION_CURRENT_USER

        if not session.get('user_id', None) and request.endpoint not in (
                "main.health_check", "static"):
            logger.info(
                f"Give a new user ID for new user. endpoint: {request.endpoint}"
            )
            session['user_id'] = new_user_id_sequence()
        if session.get('user_id', None):
            tracer.current_root_span().set_tag("user_id",
                                               session['user_id'])  # 唯一用户 ID
        if session.get(SESSION_CURRENT_USER, None):
            tracer.current_root_span().set_tag(
                "username", session[SESSION_CURRENT_USER])  # 学号
Exemple #2
0
def get_all_pointsre():
    dict = {}
    i = 0
    s1 = 'latitude '
    s2 = 'longitude '
    points = CrashLocationPoint.query.all()
    try:
        r = redis.Redis(host = host, port = redis_port)
        r.set("crashpoint-redis", "working")
        msg = r.keys() 
        log.info('Connection to redis suceeded')
    except Exception as e:
        print(e)
        log.info('Connection to redis failled')
        root_span = tracer.current_root_span()
        root_span.set_tag('error', 'true')
        root_span.set_tag('error.message', 'connection to redis failed')

    for point in points:
        t1 = s1 + str(i)
        t2 = s2 + str(i)
        dict[t1] = point.latitude
        dict[t2] = point.longitude
        i = i + 1
        r.set("key", "value")
        msg = r.get("key") 
    jdict = json.dumps(dict)

    return Response(jdict, status = 200, mimetype = 'application/json')
Exemple #3
0
    def set_user_id():
        """在请求之前设置 session uid,方便 APM 标识用户"""
        from everyclass.server.utils.web_consts import SESSION_CURRENT_USER, SESSION_USER_SEQ
        from everyclass.server.user import service as user_service

        if not session.get('user_id', None) and request.endpoint not in (
                "main.health_check", "static"):
            logger.info(
                f"Give a new user ID for new user. endpoint: {request.endpoint}"
            )
            session['user_id'] = user_service.get_user_id()
        if session.get('user_id', None):
            tracer.current_root_span().set_tag(
                "user_id", session[SESSION_USER_SEQ])  # 唯一用户 ID
        if session.get(SESSION_CURRENT_USER, None):
            tracer.current_root_span().set_tag(
                "username", session[SESSION_CURRENT_USER].identifier)  # 学号或教工号
Exemple #4
0
 def middleware(request):
     span = tracer.current_root_span()
     if span:
         for header in request.headers:
             span.set_tag("http.headers.%s" % header,
                          request.headers[header])
     response = get_response(request)
     return response
Exemple #5
0
def call_generate_requests_user():
    users = requests.get('http://noder:5004/users').json()
    user = random.choice(users)
    span = tracer.current_root_span()
    span.context.sampling_priority = USER_KEEP
    span.set_tags({'user_id': user['id']})

    output = subprocess.check_output([
        '/app/traffic_generator.py', '20', '100',
        'http://noder:5004/users/' + user['uid']
    ])
    app.logger.info(f"Chose random user {user['name']} for requests: {output}")
    return jsonify({'random_user': user['name']})
Exemple #6
0
def call_generate_requests():
    payload = flask_request.get_json()
    span = tracer.current_root_span()
    span.context.sampling_priority = USER_KEEP
    span.set_tags({
        'requests': payload['total'],
        'concurrent': payload['concurrent']
    })

    output = subprocess.check_output([
        '/app/traffic_generator.py',
        str(payload['concurrent']),
        str(payload['total']),
        str(payload['url'])
    ])
    app.logger.info(f"Result for subprocess call: {output}")
    return jsonify({
        'traffic':
        str(payload['concurrent']) + ' concurrent requests generated, ' +
        str(payload['total']) + ' requests total.',
        'url':
        payload['url']
    })
Exemple #7
0
class suppress(AbstractContextManager[None]):
    """
    Suppresses any exceptions from the given set.

    Logs the given log message whenever an exception is suppressed. String interpolation
    parameters should be embedded into the log message as `%(name)s` and provided
    coresponding values via keyword argument. For example:

        with suppress(YourError, log="whatever %s(wotnot)s", wotnot="I don't know"):
            ...

    Note that you should NOT use `return` within the context of `suppress()`. Instead
    use The Single Return Law pattern. This is because static analysis tools will not
    be able to understand that code following the context is reachable.
    """
    def __init__(self, *exceptions: Type[Exception], log: str, **kwargs: Any):
        self._exceptions = exceptions
        self._log = log
        self._kwargs = kwargs

    def __enter__(self):
        pass

    def __exit__(self, exctype: Type[Exception], excinst: Exception,
                 exctb: Traceback):
        if captured := exctype is not None and issubclass(
                exctype, self._exceptions):
            log_warning(self._log, exec_info=True, **self._kwargs)
            if span := tracer.current_span():  # pragma: no cover
                span.set_exc_info(exctype, excinst, exctb)
            if root := tracer.current_root_span():  # pragma: no cover
                root.set_tags(
                    {
                        ERROR_TYPE: "OperationalError",
                        ERROR_MSG: "An error occurred during bot operation",
                    }, )
                root.error = 1
Exemple #8
0

@skip_if_no_metrics
def add_span_context(interaction: Any):  # pragma: no cover
    if span := tracer.current_span():
        for prop in CTX_PROPS:
            if value := getattr(interaction, prop, None):
                span.set_tag(prop, value)


@skip_if_no_metrics
def add_span_error(ex: BaseException):  # pragma: no cover
    if span := tracer.current_span():
        span.set_exc_info(ex.__class__, ex, getattr(ex, "__traceback__", None))

    if root := tracer.current_root_span():
        root.set_tags(
            {
                ERROR_TYPE: "OperationalError",
                ERROR_MSG: "An error occurred during bot operation",
            }, )
        root.error = 1


@skip_if_no_metrics
def setup_ignored_errors(span: Span):  # pragma: no cover
    span._ignore_exception(UserBannedError)  # type: ignore
    span._ignore_exception(UserVerifiedError)  # type: ignore
    span._ignore_exception(UserUnverifiedError)  # type: ignore
    span._ignore_exception(AdminOnlyError)  # type: ignore
Exemple #9
0
def query():
    """
    All in one 搜索入口,可以查询学生、老师、教室,然后跳转到具体资源页面

    正常情况应该是 post 方法,但是也兼容 get 防止意外情况,提高用户体验

    埋点:
    - `query_resource_type`, 查询的资源类型: classroom, single_student, single_teacher, multiple_people, or not_exist.
    - `query_type`, 查询方式(姓名、学工号): by_name, by_id, other
    """

    # if under maintenance, return to maintenance.html
    if app.config["MAINTENANCE"]:
        return render_template("maintenance.html")

    keyword = request.values.get('id')

    if not keyword or len(keyword) < 2:
        flash('请输入需要查询的姓名、学号、教工号或教室名称,长度不要小于2个字符')
        return redirect(url_for('main.main'))

    # 调用 api-server 搜索
    with tracer.trace('rpc_search'):
        try:
            rpc_result = Entity.search(keyword)
        except Exception as e:
            return handle_exception_with_error_page(e)

    # 不同类型渲染不同模板
    if len(rpc_result.classrooms) >= 1:  # 优先展示教室
        # 我们在 kibana 中使用服务名过滤 apm 文档,所以 tag 不用增加服务名前缀
        tracer.current_root_span().set_tag("query_resource_type", "classroom")
        tracer.current_root_span().set_tag("query_type", "by_name")

        if len(rpc_result.classrooms) > 1:  # 多个教室选择
            return render_template('query/multipleClassroomChoice.html',
                                   name=keyword,
                                   classrooms=rpc_result.classrooms)
        return redirect('/classroom/{}/{}'.format(
            rpc_result.classrooms[0].room_id_encoded,
            rpc_result.classrooms[0].semesters[-1]))
    elif len(rpc_result.students) == 1 and len(
            rpc_result.teachers) == 0:  # 一个学生
        tracer.current_root_span().set_tag("query_resource_type",
                                           "single_student")
        if contains_chinese(keyword):
            tracer.current_root_span().set_tag("query_type", "by_name")
        else:
            tracer.current_root_span().set_tag("query_type", "by_id")

        if len(rpc_result.students[0].semesters) < 1:
            flash('没有可用学期')
            return redirect(url_for('main.main'))

        return redirect('/student/{}/{}'.format(
            rpc_result.students[0].student_id_encoded,
            rpc_result.students[0].semesters[-1]))
    elif len(rpc_result.teachers) == 1 and len(
            rpc_result.students) == 0:  # 一个老师
        tracer.current_root_span().set_tag("query_resource_type",
                                           "single_teacher")
        if contains_chinese(keyword):
            tracer.current_root_span().set_tag("query_type", "by_name")
        else:
            tracer.current_root_span().set_tag("query_type", "by_id")

        if len(rpc_result.teachers[0].semesters) < 1:
            flash('没有可用学期')
            return redirect(url_for('main.main'))

        return redirect('/teacher/{}/{}'.format(
            rpc_result.teachers[0].teacher_id_encoded,
            rpc_result.teachers[0].semesters[-1]))
    elif len(rpc_result.teachers) >= 1 or len(rpc_result.students) >= 1:
        # multiple students, multiple teachers, or mix of both
        tracer.current_root_span().set_tag("query_resource_type",
                                           "multiple_people")

        if contains_chinese(keyword):
            tracer.current_root_span().set_tag("query_type", "by_name")

        else:
            tracer.current_root_span().set_tag("query_type", "by_id")

        return render_template('query/peopleWithSameName.html',
                               name=keyword,
                               students=rpc_result.students,
                               teachers=rpc_result.teachers)
    else:
        logger.info("No result for user search",
                    extra={"keyword": request.values.get('id')})
        tracer.current_root_span().set_tag("query_resource_type", "not_exist")
        tracer.current_root_span().set_tag("query_type", "other")

        flash('没有找到任何有关 {} 的信息,如果你认为这不应该发生,请联系我们。'.format(
            escape(request.values.get('id'))))
        return redirect(url_for('main.main'))
Exemple #10
0
 def job_schedule_retry(namespace, job, **kwargs):
     root_span = tracer.current_root_span()
     root_span.set_traceback()
Exemple #11
0
 def job_failed(namespace, job, **kwargs):
     root_span = tracer.current_root_span()
     root_span.set_traceback()
Exemple #12
0
 def job_finished(namespace, job, **kwargs):
     root_span = tracer.current_root_span()
     for attr in job.__slots__:
         root_span.set_tag(attr, getattr(job, attr))
     root_span.finish()
Exemple #13
0
def alter_resource(request):
    root = tracer.current_root_span()
    root.resource = "custom django.request resource"

    return HttpResponse("")
Exemple #14
0
def not_found(e): 
    root_span = tracer.current_root_span()
    ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    root_span.set_tag("originating_ip", ip)
    root_span.set_tag('http.status_code', '404')
    return render_template('404.html', applicationId = applicationId, clientToken = clientToken)