Example #1
0
def tcp_link(sock, addr, alive_sock_queue, _db, _img_db):
    t_start = time.time()
    my_print('Accept new connection from {0}...'.format(addr, ))
    exception_trace_id = generate_trace_id()
    exception_message = None
    has_exception = True

    req = HttpRequest(sock,
                      addr,
                      _db=_db,
                      _img_db=_img_db,
                      trace_id=exception_trace_id)
    need_send = False
    try:
        success = req.do()
        if success:  # 成功的请求,以后可以缓存
            pass
        has_exception = False
        need_send = True
    except Exception as e:
        tb = traceback.format_exc()
        if str(e).find('client socket closed.') != -1:
            return
        exception_message = str(e)
    except BaseException as be:
        tb = traceback.format_exc()
        exception_message = str(be)

    if has_exception:
        my_print('tcp_link TraceId:{0} {1} {2}'.format(exception_trace_id,
                                                       exception_message, tb))
        req.res_command = ResponseCode.INNER_ERROR
        body = dict()
        body['status'] = 9999
        body['message'] = exception_message
        body['traceId'] = exception_trace_id
        ymp = json.dumps(body, ensure_ascii=False)
        req.res_body = ymp.encode('UTF-8')
        req.res_head['Content-Type'] = 'text/html; charset=UTF-8'
        need_send = True

    if need_send:
        if req.res_body is None or 0 == len(req.res_body):
            my_print("trace_id:{} header:{} body:{}".format(
                req.trace_id, req._raw_head, get_print_string(req._raw_body)))
            req.res_body = 'UNKNOWN ERROR,trace_id:{} req.trace_id:{}'.format(
                req.trace_id, req.parameters.get('trace_id',
                                                 None)).encode('utf-8')
            req.res_command = b"HTTP/1.1 500 OK\r\n"
        req.res_head['Content-Length'] = str(len(req.res_body))
        response_header = dict2header(req.res_head).encode('UTF-8')
        if Conf.get('is_save_response'):
            write_to_file(Conf.get('save_response_file_path'),
                          req.get_res_data())
        sock.sendall(req.res_command)
        sock.sendall(response_header)
        sock.sendall(req.res_body)

        if req.res_head.get('Connection', 'Close').lower() == 'keep-alive':
            data = types.SimpleNamespace(sock=sock, addr=addr)
            alive_sock_queue.put(data)
        else:
            sock.close()
    else:
        sock.close()

    t_stop = time.time()
    print(
        "[%d] %s,%s %s %.5f" %
        (os.getpid(), addr[0], addr[1], req.command.command, t_stop - t_start))