0

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

Python 脚本无法在启动时启动,检查日志表明这是因为连接到 InfluxDB 时出现“ ConnectionError ”。我将其解释为,在 Python 服务在启动时激活时,influxdb 服务可能尚未启动。因此,我尝试通过将“ After ”和“ Wants ”添加为“ influxdb.service ”来在服务中添加订单依赖项,这会在 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.service在influxdb.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,这可能是因为当它连接到端口 8086的流入时,没有任何东西在监听它?如果是这样,我怎样才能把它放在依赖顺序中?

4

1 回答 1

1

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

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

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

Restart=on-failure

您可以通过向 systemd 单元添加一个小的 shell 脚本来延迟 Python 代码的启动,直到 influxdb 准备好:

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

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

于 2019-04-24T17:51:03.353 回答