Systemd学以致用:Yocto开机使用systemd启动网络服务

最近开发的产品使用基于Yocto SumoiMX6 BSP。基于SumoBSP的一个重大变化是使用Systemd代替System V Init文件。对于那些支持 Systemd 的服务,安装的时候,会自动在/usr/lib/systemd/system目录添加一个配置文件。我们以systemd-networkd.service为例来说明如何在Yocto开机启动网络服务。

配置Yocto默认使用systemd启动

BSP层的配置文件conf中添加systemd启动功能:

VIRTUAL-RUNTIME_init_manager = "systemd"
PREFERRED_PROVIDER_udev = "systemd"
PREFERRED_PROVIDER_udev-utils = "systemd"
DISTRO_FEATURES_BACKFILL_CONSIDERED = "sysvinit"
VIRTUAL-RUNTIME_initscripts = ""
IMX_DEFAULT_DISTRO_FEATURES += " systemd"
DISTRO_FEATURES_append = " systemd"
DISTRO_FEATURES_remove = " sysvinit"

在菜谱中添加systemd-networkd.service

在一个菜谱中添加systemd-networkd.service,并且在开机的时候启动它(Yocto最新的systemd启动包都默认安装了systemd-networkd.service,所以可以忽略这一步骤):

SYSTEMD_SERVICE_${PN} = "systemd-networkd.service"
SYSTEMD_AUTO_ENABLE_${PN} = "enable"

这样Yocto构建BSP完成后就会在rootfs目录生成如下的配置文件:

$ cd poky/build/tmp/work/qemux86-poky-linux/core-image-sato/1.0-r0/rootfs/
$ find . -name "*networkd*"
./etc/systemd/system/network-online.target.wants/systemd-networkd-wait-online.service
./etc/systemd/system/sockets.target.wants/systemd-networkd.socket
./etc/systemd/system/multi-user.target.wants/systemd-networkd.service
./usr/share/polkit-1/rules.d/systemd-networkd.rules
./lib/systemd/systemd-networkd-wait-online
./lib/systemd/system/systemd-networkd.socket
./lib/systemd/system/systemd-networkd-wait-online.service
./lib/systemd/system/systemd-networkd.service
./lib/systemd/systemd-networkd

添加eth0.network配置文件

recipes-core/base-files/base-files/目录下添加eth0.network文件,内容如下:

[Match]
Name=eth0

[Network]
DHCP=yes
 
[DHCP]
RouteMetric=0

然后在recipes-core/base-files/base-files_%.bbappend文件中添加该配置文件到rootfs

SRC_URI += "file://eth0.network"
do_install() {
       install -D -m 0644 ${WORKDIR}/eth0.network ${D}${sysconfdir}/systemd/network/
}

这样Yocto构建BSP完成后就会在rootfs目录生成如下的配置文件:

$ cd poky/build/tmp/work/qemux86-poky-linux/core-image-sato/1.0-r0/rootfs/
$ find . -name "*eth0*"
./etc/systemd/network/eth0.network

Yocto开机后检查systemd-networkd服务是否正常启动

systemd-networkd服务开机启动后会自动从/etc/systemd/network目录读取配置文件来管理网络设备,使用如下命令可以检查该服务的状态。

root# systemctl status systemd-networkd
● systemd-networkd.service - Network Service
   Loaded: loaded (/lib/systemd/system/systemd-networkd.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2019-03-08 09:02:14 UTC; 2min 42s ago
     Docs: man:systemd-networkd.service(8)
 Main PID: 906 (systemd-network)
   Status: "Processing requests..."
    Tasks: 1 (limit: 4915)
   CGroup: /system.slice/systemd-networkd.service
           └─906 /lib/systemd/systemd-networkd

Mar 08 09:02:22 lorank8 systemd-networkd[906]: br0: Lost carrier
Mar 08 09:02:22 lorank8 systemd-networkd[906]: br0: DHCPv6 lease lost
Mar 08 09:02:27 lorank8 systemd-networkd[906]: eth0: Gained IPv6LL

可以看到systemd-networkd服务启动后,eth0也自动获取到了ip地址。

你可能感兴趣的:(Yocto)