【问题标题】:Apache and Python threading strange resultsApache和Python线程奇怪的结果
【发布时间】:2017-02-01 05:40:22
【问题描述】:

我正在编写一些代码来查询 SteamAPI 以获取服务器上的数据,然后编译一个更大的列表并输出 JSON 数据。

它通过以下方式做到这一点:

  • 请求所有服务器IP的列表(ip,端口)
  • 然后向 ip/port 发送请求
  • 转换结果,
  • 将其附加到主列表
  • 使用 json.dumps() 格式化最终列表

它是用 python 2.7.6 编写的

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# gets all the miscreated servers

import Queue
import json
import unicodedata
from threading import Thread

import pyfscache
import valve.source.a2s
import valve.source.master_server

cache_it = pyfscache.FSCache('./cache/', days=0, hours=4, minutes=30)

# The main queue object
q = Queue.LifoQueue()
# this is the list we append to
final_servers_list = []


def print_headers():
    print "Content-type: application/json\n"
    print ""


def get_master_server_list():
    msq = valve.source.master_server.MasterServerQuerier()
    servers = msq.find(appid="299740")
    return servers


def normalize(data):
    if type(data) is unicode:
        return unicodedata.normalize('NFKD', data).encode('ascii', 'ignore')
    else:
        return data


def get_single_server_data():
    while not q.empty():  # check that the queue isn't empty
        try:
            server_address = q.get()
            _server = valve.source.a2s.ServerQuerier(server_address)
            info = _server.get_info()

            try:
                server_time = info['server_tags'].split(';')[0][-5:]
            except:
                server_time = '00:00'
            try:
                players = info['server_tags'].split(';')[1]
            except:
                players = '0'
            try:
                whitelisted = info['server_tags'].split(';')[2]
            except:
                whitelisted = '0'

            final_servers_list.append({'name': normalize(info['server_name']),
                                       'mapName': normalize(info['map']),
                                       'ip': normalize(server_address[0]),
                                       'port': normalize(server_address[1]),
                                       'time': normalize(server_time),
                                       'players': normalize(players),
                                       'whiteListed': normalize(whitelisted),
                                       'maxPlayers': normalize(info['max_players']),
                                       'version': normalize(info['version'])})
            q.task_done()
        except:
            q.task_done()


@cache_it
def get_server_list():
    master_server_list = get_master_server_list()
    for server in master_server_list:
        q.put(server)
    for i in range(200):
        t1 = Thread(target=get_single_server_data)  # target is the above function
        t1.start()  # start the thread
    q.join()
    return final_servers_list


if __name__ == '__main__':
    print_headers()
    print json.dumps(get_server_list())

现在这段代码在我运行 scotchbox vagrant 灯堆栈的本地机器上运行良好。python 与服务器/开发机器上的版本相同。

我在我的机器上得到了我期望的结果我得到了大约 500 台服务器,并且所有数据都完全符合我的期望。

但是,当我在运行 apache2 的网络服务器上运行它时,它会向我吐出一个在 10,000 范围内的列表,其中许多结果在列表中出现 10-20 次。即使我尝试过滤结果,某些数据也略有不同(因为它可能在一秒钟后或第二次被请求?并且服务器标签已更改?)

我认为这与 python 的线程和 apache 有关,并且由于某种原因它没有某种锁定文件,但我无法终生解决这个问题。我以为我已经解决了它通过做一个

source /etc/apache2/envvars

然后为 ssh 终端运行脚本

它开始工作,但下次缓存过期并运行代码时,它给了我相同的结果。

任何建议都将不胜感激,因为我在这里撞墙了。

在我运行apache2 -V时附带说明

它吐出一个错误:

[Wed Feb 01 05:35:59.192112 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOCK_DIR} is not defined
[Wed Feb 01 05:35:59.192531 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_PID_FILE} is not defined
[Wed Feb 01 05:35:59.193300 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.214298 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_RUN_DIR} is not defined
[Wed Feb 01 05:35:59.215112 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.215499 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.215708 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.216057 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.216272 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.216595 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.217080 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.217475 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.217812 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.218115 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.218369 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.218657 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.218885 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.219117 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.219348 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.219631 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Wed Feb 01 05:35:59.219845 2017] [core:warn] [pid 30832] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
AH00526: Syntax error on line 75 of /etc/apache2/apache2.conf:
Invalid Mutex directory in argument file:${APACHE_LOCK_DIR}

它在开发和生产机器上都这样做,所以我认为这不是什么大不了的事。

最后是网站的 apache 配置。

<VirtualHost *:80>
        ServerName "servers.miscreatedgame.com"
        ServerAdmin "csprance@entradainteractive.com"
        DocumentRoot "/var/www/servers.com/_build"

        # serverpanel appollo
        <Directory "/var/www/servers.com/_build">
                AddHandler cgi-script .py
                Options +ExecCGI
        </Directory>



        ErrorLog ${APACHE_LOG_DIR}/servers-error.log
        CustomLog ${APACHE_LOG_DIR}/servers-access.log combined

</VirtualHost>

【问题讨论】:

标签: python multithreading apache2


【解决方案1】:

正如@SergGr 所说,这绝对像是多个请求之间的线程竞争条件。我建议尝试使您的代码可重入。我会将实际创建线程并构建整个服务器列表的代码放在一个单独的进程中,然后将其返回给使用 ipc 处理来自用户的请求的进程。

【讨论】:

    【解决方案2】:

    该脚本实际在服务器上运行的环境是什么?它是一个独立的脚本还是作为 Web 服务器 (Apache) 的一部分运行?在后一种情况下,您不会碰巧对同一数据有多个并发 (HTTP) 请求吗?您的q = Queue.LifoQueue() 似乎是任何处理请求都可以访问的全局共享变量,因此所有并发请求都将填充相同的“队列”(q)。这可能是它随机发生的原因:它仅在有对该数据的并发请求时发生。如果是这种情况,解决它的明显方法是将q 局部变量设置为get_server_list,并使用Thread constructorargs 参数将其显式传递给get_single_server_data,这实际上是一件好事。显然,用于输出的 final_servers_list 也是如此。

    更新

    经过一番思考,是什么清理了final_servers_list?假设您只运行此 HTTP 请求 10 次(按顺序运行,而不是同时运行)。为什么您不希望在最后一个响应中得到 10 次报告的整个服务器列表?

    但正确的解决方案仍然是一样的:不要使用全局变量。与清除列表相比,它更加可靠和面向未来。

    【讨论】:

      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 2016-01-22
      • 2016-07-26
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多