A Sample Socket-Based Activation

This is an example of a socket-activated per-connection service (which is usually referred to as inetd-like service).A thorough explanation can be found at http://0pointer.de/blog/projects/inetd.html.


Define a socket unit

The key point here is to specify Accept=yes, which will make the socket accept connections (behaving like inetd) and passonly the resulting connection socket to the service handler.

Create /etc/systemd/system/baz.socket:

[Unit]
Description=Baz Socket

[Socket]
ListenStream=127.0.0.1:9999
Accept=yes

[Install]
WantedBy=sockets.target

Define a service template unit

We now create a service template from which the actual service will be instantiated on-demand. The lifetime of this service isusually very short (thus it may not appear at systemctl).

Create /etc/systemd/system/baz@.service:

[Unit]
Description=Baz Service
Requires=baz.socket

[Service]
Type=simple
ExecStart=/usr/bin/python /opt/baz-service/serve.py %i
StandardInput=socket
StandardError=journal
TimeoutStopSec=5

[Install]
WantedBy=multi-user.target

An example service handler would be (located at /opt/baz-service/serve.py as specified at the service unit file):

#!/usr/bin/python
import sys
import logging
logging.basicConfig(level=logging.INFO)

instance = sys.argv[1]

# The connected socket is duplicated to stdin/stdout
data = sys.stdin.readline().strip()
logging.info('baz-service: at instance %s, got request: %s', instance, data)
sys.stdout.write(data.upper() + '\r\n')

Test

Start (or enable it to start at boot time) the socket (verify it via systemctl status baz.socket), and make a request to the service:

echo Hello| nc localhost 9999

You 'll notice that the socket's status has changed (i.e. Accepted: 1). Also, any log message generated by the on-demandservice should be present at the journal (e.g. journalctl --all| grep -e baz).

 systemctl  status baz.socket
● baz.socket - Baz Socket
   Loaded: loaded (/etc/systemd/system/baz.socket; enabled; vendor preset: enabled)
   Active: active (listening) since Mon 2017-04-10 00:08:22 CST; 1h 13min ago
   Listen: 127.0.0.1:9999 (Stream)
 Accepted: 3; Connected: 0

Apr 10 00:08:22 china systemd[1]: Listening on Baz Socket.



----------------------

To enable socket, run command:

systemctl enable baz.socket
systemctl start baz.socket

https://gist.github.com/drmalex07/28de61c95b8ba7e5017c


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值