运行 Python 脚本作为 systemd 服务,连接到 InfluxDB 导致 ConnectionError

Running Python script as systemd service, connecting to InfluxDB results in ConnectionError

我是 运行 一个 shell 脚本作为 Ubuntu 的 systemd 服务在启动时启动。该脚本在内部执行一个 Python 脚本 (python_simulator.py) 连接到 InfluxDB(通过 Python 的 influxdb 包)。

Python 脚本无法在启动时启动,检查日志表明这是因为连接到 InfluxDB 时出现“ConnectionError”。我将其解释为可能 Python 服务在启动时激活时 influxdb 服务尚未启动。因此,我尝试通过添加“After”和“Wants”作为“[=”来在服务中添加订单依赖项61=]" 在 influxdb 服务几秒后激活 Python 服务。但是,我仍然遇到相同的连接错误。

systemd 服务 (myservice.service) 看起来像:

[Unit]
Description= Python startup service.
After=influxdb.service
Wants=influxdb.service

[Service]
Type=forking
ExecStart=/bin/bash /home/test_user/Deploy/start.sh
ExecStop=/bin/bash /home/test_user/Deploy/stop.sh

[Install]
WantedBy=multi-user.target

Python脚本的日志文件(python_simulator.py):

Traceback (most recent call last):
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 80, in create_connection
    raise err
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/util/connection.py", line 70, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/usr/lib/python3.6/http/client.py", line 1239, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.6/http/client.py", line 1026, in _send_output
    self.send(msg)
  File "/usr/lib/python3.6/http/client.py", line 964, in send
    self.connect()
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connection.py", line 181, in connect
    conn = self._new_conn()
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f817d91b400>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/urllib3/util/retry.py", line 399, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?q=SHOW+DATABASES (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f817d91b400>: Failed to establish a new connection: [$

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "python_simulator.py", line 467, in <module>
    main(host=args.host, port=args.port)
  File "python_simulator.py", line 312, in main
    for db_dict in client.get_list_database():
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/influxdb/client.py", line 570, in get_list_database
    return list(self.query("SHOW DATABASES").get_points())
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/influxdb/client.py", line 416, in query
    expected_response_code=expected_response_code
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/influxdb/client.py", line 267, in request
    timeout=self._timeout
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/requests/sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/requests/sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "/home/test_user/Deploy/py_venv/lib/python3.6/site-packages/requests/adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?q=SHOW+DATABASES (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f817d91b400>: Failed to establish a new connection$

最后,守护进程的阻塞树显示 myservice.serviceinfluxdb.service 之后执行:

myservice.service +6.872s
└─influxdb.service @11.344s
  └─network-online.target @11.337s
    └─NetworkManager-wait-online.service @4.706s +6.630s
      └─NetworkManager.service @3.940s +674ms
        └─dbus.service @3.914s
          └─basic.target @3.728s
            └─sockets.target @3.728s
              └─snapd.socket @3.722s +5ms
                └─sysinit.target @3.712s
                  └─apparmor.service @3.276s +435ms
                    └─local-fs.target @3.266s
                      └─run-user-1000.mount @49.841s
                        └─swap.target @3.160s
                          └─dev-disk-by\x2duuid-16e1b46a\x2d79fc\x2d4965\x2d9932\x2d8f589e9e7057.swap @3.132s +23ms
                            └─dev-disk-by\x2duuid-16e1b46a\x2d79fc\x2d4965\x2d9932\x2d8f589e9e7057.device @3.130s

我不确定为什么我仍然无法执行带有 influxdb 的脚本 (python_simulator.py)。还有其他依赖吗? myservice.service 是否需要任何更改?任何帮助将不胜感激。

编辑 1:

原因可能是 ConnectionRefusedError 而不是 ConnectionError 并且这可能是因为当它连接到 [=39= 处的涌入时]端口 8086,没有什么正在监听吗?如果是这样,我怎样才能把它放在依赖顺序中?

即使您创建了服务依赖性,您仍然可能 运行 遇到问题(因为 influxdb 可能需要一段时间才能准备好接受连接,在此期间 Python 代码可能开始)。解决方案是:

  • 编写您的 Python 代码以在连接被拒绝时重试连接或
  • 将 systemd 配置为在失败时重新启动您的服务。

没有看到您的 Python 代码,很难提出第一个解决方案可能是什么样子,但是配置您的设备以在失败时重新启动就像将以下内容添加到您的 [Service] 部分一样简单:

Restart=on-failure

您可以延迟 Python 代码的启动,直到 influxdb 准备就绪,方法是向您的 systemd 单元添加一个小 shell 脚本:

ExecStartPre=/bin/sh -c 'while ! curl -sf http://localhost:8086/ping; do sleep 1; done'

这将无限循环(从而阻止服务启动),直到 influxdb 成功响应 /ping 端点。