Systemd 套接字激活标准输入

Systemd 套接字激活标准输入

我必须将旧的 xinetd 配置转移到 systemd。要求是打开一个 TCP 端口并侦听传入的传输。应用程序只需通过将文件联网到端口即可为每个连接传输一个文件。当注册传输时,将调用 shell 脚本,该脚本通过将 stdin 重定向到该文件来将传入数据保存到该文件中。这个结构在 xined 中工作了很多年。这是我所拥有的:

[root@localhost ~]# cat /etc/systemd/system/foo.socket
[Unit]
Description=Foo Socket
PartOf=foo.service

[Socket]
ListenStream=127.0.0.1:9999
Accept=yes

[Install]
WantedBy=sockets.target
[root@localhost ~]# cat /etc/systemd/system/[email protected]
[Unit]
Description=Foo Service
After=network.target foo.socket
Requires=foo.socket

[Service]
Type=simple
ExecStart=/usr/local/bin/foo.sh
TimeoutStopSec=5

[Install]
WantedBy=default.target
[root@localhost ~]# cat /usr/local/bin/foo.sh
#!/bin/bash

cat > /tmp/foo.$$
[root@localhost ~]# systemctl start foo.socket
[root@localhost ~]# echo "Hello World" > testfile
[root@localhost ~]# socat -u FILE:testfile TCP:127.0.0.1:9999
[root@localhost ~]# ls -al /tmp/foo.*
-rw-r--r--. 1 root root 0 Nov  7 21:20 /tmp/foo.19820
[root@localhost ~]#

tcp端口打开,调用服务并执行shell脚本。但输出文件大小为零。如果我停止套接字并使用以下命令:

[root@localhost system]# systemctl stop foo.socket
[root@localhost system]# /usr/lib/systemd/systemd-activate -l 127.0.0.1:9999 -a /usr/local/bin/foo.sh &
[1] 19833
[root@localhost system]# Listening on 127.0.0.1:9999 as 3.
[root@localhost ~]# socat -u FILE:testfile TCP:127.0.0.1:9999
Communication attempt on fd 3.
Connection from 127.0.0.1:39924 to 127.0.0.1:9999
Spawned /usr/local/bin/foo.sh (/usr/local/bin/foo.sh) as PID 19840
[root@localhost ~]# Child 19840 died with code 0
[root@localhost ~]# ls -al /tmp/foo*
-rw-r--r--. 1 root root   12 Nov  7 21:26 /tmp/foo.19840
[root@localhost ~]# cat /tmp/foo.19840
Hello World
[root@localhost ~]#

它像预期的那样工作。我想念什么?

答案1

知道了。服务单元文件需要选项 StandardInput=socket 才能从套接字接受数据。完整的文件应如下所示:

# cat /etc/systemd/system/[email protected] 
[Unit]
Description=Foo Service
After=network.target foo.socket
Requires=foo.socket

[Service]
Type=simple
ExecStart=/usr/local/bin/foo.sh
TimeoutStopSec=5
StandardInput=socket

[Install]
WantedBy=default.target

相关内容