Systemd 任务和限制

Systemd 任务和限制

首先:请不要将此问题标记为 Stack Overflow(是的,Python 是上下文的主要部分,但我的问题最终是关于 Systemd)

我目前正在编写一个Python程序,该程序将位于服务器上并通过Systemd进行控制(启用后,如果服务器出现故障等情况,它会重新启动)。我担心的是“任务”部分systemctl status不断增加。

...
Active: active (running) since Wed 2020-08-26 18:31:12 UTC; 14min ago
Main PID: 1657 (python3)
Tasks: 178 (limit: 637)  <--
...

据此信息推断,需要 50 分钟多一点(从服务开始算起)才能达到限制。我的问题不是“为什么我的代码被破坏了”,“我如何提高这个限制”之类的。相反,我的问题是:Systemd 认为什么任务以及达到限制时会发生什么(是否发送信号来终止服务等)?

有了这些信息,我希望了解为什么我的 Python 脚本(看起来)任务数量呈线性增加(并随后修复此问题)。

答案1

systemd.资源控制(5)给了我们一个提示:

   TasksMax=N
      Specify the maximum number of tasks that may be created in the unit. This 
      ensures that the number of tasks accounted for the unit (see above) stays
      below a specific limit. This either takes an absolute number of tasks or a
      percentage value that is taken relative to the configured maximum number of 
      tasks on the system. If assigned the special value "infinity", no tasks 
      limit is applied. This controls the "pids.max" control group attribute. For
      details about this control group attribute, see Process Number Controller[7].

      The system default for this setting may be controlled with DefaultTasksMax= 
      in systemd-system.conf(5).

所以这个限制是基于“pids.max”的。每当您的进程调用时都会生成 PIDfork()或者clone()。在Python的上下文中,有一个os.fork()它可能调用同名的系统调用。我不确定在哪些其他情况下python会进行这些系统调用,但如果您没有生成数百个进程,那么我预计它与生成的线程数有关。

手册页引用了一些很好的文献:[7] 进程号控制器

答案2

只需将此命令添加到您的脚本中即可:systemctl restart yourproject.service

说明:使用systemctl restart,您的项目始终有新任务。

相关内容