Systemd
==============================================================================
概述:
CentOS 6和之前版本采用SysVinit的系统启动进程管理体系,一般用户都可通过在/etc/inittab文件的配置,来个性化自己的系统启动序列。但也经常会由于特殊环境的硬件等关系问题,造成其串行的启动进程控制流,因为可能任务的阻塞而影响启动过程。
CentOS 7开始使用SystemD,所以我们必须要了解SystemD.本章将从CentOS 7 的启动流程、Unit、服务管理,启动排错,破解口令以及修复grub2 等方面来介绍Systemd的相关内容。
==============================================================================
systemd介绍
★启动流程
POST --> Boot Sequence --> Bootloader --> kernel + initramfs(initrd) --> rootfs(根切换)--> /sbin/init
☉init:
CentOS 5: SysVinit;
CentOS 6: Upstart;
CentOS 7: Systemd;
★Systemd:
系统启动和服务器守护进程管理器,负责在系统启动或运行时,激活系统资源,服务器进程和其它进程;
☉Systemd新特性
系统引导时实现服务并行启动;
按需启动守护进程;
自动化的服务依赖关系管理;
同时采用socket式与D-Bus总线式激活服务;
系统状态快照。
核心概念:Unit
unit表示不同类型的systemd对象,通过配置文件进行标识和配置;
文件中主要包含了系统服务、监听socket、保存的系统快照以及其它与init相关的信息;
配置文件
★/usr/lib/systemd/system:
每个服务最主要的启动脚本设置,类似于之前的/etc/init.d/
★/run/systemd/system:
系统执行过程中所产生的服务脚本,比上面目录优先运行
★/etc/systemd/system:
管理员建立的执行脚本,类似于/etc/rc.d/rcN.d/Sxx类的功能,比上面目录优先运行
[root@centos7 ~]# cd /usr/lib/systemd/system [root@centos7 system]# ls abrt-ccpp.service gdm.service ntpdate.service sys-fs-fuse-connections.mount abrtd.service geoclue.service oddjobd.service sysinit.target abrt-oops.service [email protected] paths.target sysinit.target.wants abrt-pstoreoops.service getty.target plymouth-halt.service sys-kernel-config.mount abrt-vmcore.service graphical.target plymouth-kexec.service sys-kernel-debug.mount anaconda.service hybrid-sleep.target postfix.service systemd-ask-password-wall.service [email protected] initial-setup-graphical.service poweroff.target [email protected] anaconda-sshd.service initial-setup-text.service poweroff.target.wants s
Unit 类型
systemctl –t help:查看unit类型;
Service unit:文件扩展名为.service, 用于定义系统服务;
Target unit:文件扩展名为.target,用于模拟实现“运行级别”;
Device unit:.device, 用于定义内核识别的设备;
Mount unit:.mount, 定义文件系统挂载点;
Socket unit:.socket, 用于标识进程间通信用的socket文件,也可在系统启动时,延迟启动服务,实现按需启动;
Snapshot unit:.snapshot, 管理系统快照;
Swap unit:.swap, 用于标识swap设备;
Automount unit:.automount,文件系统的自动挂载点;
Path unit:.path,用于定义文件系统中的一个文件或目录使用,常用于当文件系统变化时,延迟激活服务,如:spool 目录
演示:
[root@centos7 ~]# systemctl -t help Available unit types: service socket busname target snapshot device mount automount swap timer path slice scope
特性
★关键特性:
基于socket的激活机制:socket与服务程序分离
基于d-bus的激活机制:
基于device的激活机制:
基于path的激活机制:
系统快照:保存各unit的当前状态信息于持久存储设备中
向后兼容sysvinit脚本
★不兼容
systemctl命令固定不变,不可扩展
非由systemd启动的服务,systemctl无法与之通信和控制
管理服务(重点)
1.管理系统服务
centos 7:service 类型的 unit 文件
注意:能兼容早期的服务脚本
★命令:
systemctl COMMAND name.service
☉用法如下:
◆启动:
service name start ==> systemctl start name.service
◆停止:
service name stop ==> systemctl stop name.service
◆重启:
service name restart ==> systemctl restart name.service
◆状态:
service name status ==> systemctl status name.service
◆条件式重启:已启动才重启,否则不做操作
service name condrestart==> systemctl try-restart name.service
◆重载或重启服务:先加载,再启动
systemctl reload-or-restart name.service
◆重载或条件式重启服务:
systemctl reload-or-try-restart name.service
◆禁止某服务设定开机自启:
systemctl mask name.service
◆取消如上禁止:
systemctl unmask name.service
演示:
[root@CentOS6 ~]# service httpd status # CentOS 6 显示的状态信息 httpd is stopped [root@centos7 ~]# systemctl status httpd.service # CentOS 7 显示的状态信息 ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: inactive (dead) Docs: man:httpd(8) man:apachectl(8)
2.服务查看
☉查看某服务当前激活与否的状态
systemctl is-active name.service
☉查看所有已经激活的服务:
systemctl list-units --type|-t service
☉查看所有服务(已激活及未激活):
systemctl list-units --type|-t service –all|-a
演示:
[root@centos7 ~]# systemctl is-active httpd.service # 查看某服务当前激活与否的状态 active [root@centos7 ~]# systemctl stop httpd.service [root@centos7 ~]# systemctl is-active httpd.service unknown [root@centos7 ~]# systemctl list-units -t service # 查看所有已激活的服务 UNIT LOAD ACTIVE SUB DESCRIPTION abrt-ccpp.service loaded active exited Install ABRT coredump hook abrt-oops.service loaded active running ABRT kernel log watcher abrt-xorg.service loaded active running ABRT Xorg log watcher abrtd.service loaded active running ABRT Automated Bug Reporting Tool alsa-state.service loaded active running Manage Sound Card State (restore and store) atd.service loaded active running Job spooling tools auditd.service loaded active running Security Auditing Service autofs.service loaded active running Automounts filesystems on demand blk-availability.service loaded active exited Availability of block devices chronyd.service loaded active running NTP client/server crond.service loaded active running Command Scheduler cups.service loaded active running CUPS Printing Service dbus.service loaded active running D-Bus System Message Bus [email protected] loaded active running Getty on tty1 [root@centos7 ~]# systemctl list-units -t service --all # 查看所有服务状态 UNIT LOAD ACTIVE SUB DESCRIPTION abrt-ccpp.service loaded active exited Install ABRT coredump hook abrt-oops.service loaded active running ABRT kernel log watcher abrt-vmcore.service loaded inactive dead Harvest vmcores for ABRT abrt-xorg.service loaded active running ABRT Xorg log watcher abrtd.service loaded active running ABRT Automated Bug Reporting Tool accounts-daemon.service loaded inactive dead Accounts Service alsa-restore.service loaded inactive dead Restore Sound Card State
3.服务状态:
★systemctl list-units --type service --all显示状态
loaded:Unit配置文件已处理
active(running):一次或多次持续处理的运行
active(exited):成功完成一次性的配置
active(waiting):运行中,等待一个事件
inactive:不运行
enabled:开机启动
disabled:开机不启动
static:开机不启动,但可被另一个启用的服务激活
CentOS 6和7 命令的对应关系
☉设定某服务开机自启:
chkconfig name on ==> systemctl enable name.service
☉设定某服务开机禁止启动:
chkconfig name off ==> systemctl disable name.service
☉查看所有服务的开机自启状态:
chkconfig --list ==> systemctl list-unit-files --type service
☉用来列出该服务在哪些运行级别下启用和禁用
chkconfig sshd –list==> ls /etc/systemd/system/*.wants/sshd.service
☉查看服务能否开机自启:
chkconfig --list name ==> systemctl is-enabled name.service
☉查看服务的依赖关系:
systemctll ist-dependencies name.service
☉杀掉进程:
systemctl kill 进程名、
演示:
[root@centos7 ~]# systemctl is-enabled httpd disabled [root@centos7 ~]# systemctl is-enabled sshd # 查看某服务能否开机自启 enabled
运行级别(管理target unit)
★target units:
☉unit配置文件:.target
ls /usr/lib/systemd/system/*.target
systemctl list-unit-files --type target --all
★运行级别:
0 ==> runlevel0.target, poweroff.target
1 ==> runlevel1.target, rescue.target 单用户模式或者救援模式
2 ==> runlevel2.target, multi-user.target
3 ==> runlevel3.target, multi-user.target 正常级别,字符型界面
4 ==> runlevel4.target, multi-user.target
5 ==> runlevel5.target, graphical.target 图形模式
6 ==> runlevel6.target, reboot.target 重启
★查看依赖性:
systemctl list-dependencies graphical.target
★级别切换:
init N ==> systemctl isolate name.target
如:systemctl isolate multi-user.target # 切换到级别3
注意:
只有/lib/systemd/system/*.target文件中AllowIsolate=yes 才能切换(修改文件需执行systemctl daemon-reload才能生效)
★查看级别:
runlevel,who -r ==> systemctl list-units --type target
★获取默认运行级别:
/etc/inittab ==> systemctl get-default
★修改默认级别:
/etc/inittab==> systemctl set-default name.target
如:
systemctl set-default multi-user.target //修改为3级别
ls –l /etc/systemd/system/default.target
演示:
[root@centos7 ~]# ls /usr/lib/systemd/system/*.target # 显示的所有级别 /usr/lib/systemd/system/anaconda.target /usr/lib/systemd/system/local-fs-pre.target /usr/lib/systemd/system/runlevel2.target /usr/lib/systemd/system/basic.target /usr/lib/systemd/system/local-fs.target /usr/lib/systemd/system/runlevel3.target /usr/lib/systemd/system/bluetooth.target /usr/lib/systemd/system/machines.target /usr/lib/systemd/system/runlevel4.target /usr/lib/systemd/system/initrd-root-fs.target /usr/lib/systemd/system/remote-fs.target /usr/lib/systemd/system/sysinit.target /usr/lib/systemd/system/initrd-switch-root.target /usr/lib/systemd/system/rescue.target /usr/lib/systemd/system/system-update.target /usr/lib/systemd/system/initrd.target /usr/lib/systemd/system/rpcbind.target /usr/lib/systemd/system/timers.target /usr/lib/systemd/system/iprutils.target /usr/lib/systemd/system/runlevel0.target /usr/lib/systemd/system/time-sync.target /usr/lib/systemd/system/kexec.target /usr/lib/systemd/system/runlevel1.target /usr/lib/systemd/system/umount.target
[root@centos7 ~]# who -r run-level 3 2016-09-23 07:10 [root@centos7 ~]# runlevel # 具有旧版本兼容性,也可以使用centos6的命令来查看 N 3 [root@centos7 ~]# systemctl list-units --type target # 查看运行级别 UNIT LOAD ACTIVE SUB DESCRIPTION basic.target loaded active active Basic System cryptsetup.target loaded active active Encrypted Volumes getty.target loaded active active Login Prompts local-fs-pre.target loaded active active Local File Systems (Pre) local-fs.target loaded active active Local File Systems multi-user.target loaded active active Multi-User System # 当前级别为3 network-online.target loaded active active Network is Online sysinit.target loaded active active System Initialization timers.target loaded active active Timers LOAD = Reflects whether the unit definition was properly loaded. ACTIVE = The high-level unit activation state, i.e. generalization of SUB. SUB = The low-level unit activation state, values depend on unit type. 18 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'.
[root@centos7 ~]# systemctl get-default # 获取默认运行级别 multi-user.target [root@centos7 ~]# systemctl isolate graphical.target # 切换到5级别 PolicyKit daemon disconnected from the bus.
其他命令
★切换至紧急救援模式:
systemctl rescue
★切换至emergency(紧急)模式:
systemctlemergency
★其它常用命令:
传统命令 init,poweroff,halt,reboot都成为systemctl的软链接
关机:systemctl halt 或者 systemctl poweroff
重启:systemctl reboot
挂起:systemctl suspend
快照(休眠):systemctl hibernate
快照并挂起:systemctl hybrid-sleep
service unit 文件格式
★文件及格式:
☉文件位置及使用
/etc/systemd/system:系统管理员和用户使用;
/usr/lib/systemd/system:发行版打包者使用;
☉说明:
以“#” 开头的行后面的内容会被认为是注释;
相关布尔值,1、yes、on、true 都是开启,0、no、off、false 都是关闭;
时间单位默认是秒,所以要用毫秒(ms)分钟(m)等请显式说明;
★service unit file文件通常由三部分组成:
☉[Unit]:
定义与Unit类型无关的通用选项;用于提供unit的描述信息、unit行为及依赖关系等;
☉[Service]:
与特定类型相关的专用选项;此处为Service类型;
☉[Install]:
定义由“systemctl enable”以及"systemctl disable“命令在实现服务启用或禁用时用到的一些选项。
文件格式如下:
[root@centos7 system]# pwd /usr/lib/systemd/system [root@centos7 system]# cat httpd.service [Unit] Description=The Apache HTTP Server # 描述信息 After=network.target remote-fs.target nss-lookup.target # 定义启动顺序 Documentation=man:httpd(8) Documentation=man:apachectl(8) [Service] Type=notify EnvironmentFile=/etc/sysconfig/httpd ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND ExecReload=/usr/sbin/httpd $OPTIONS -k graceful ExecStop=/bin/kill -WINCH ${MAINPID} # We want systemd to give httpd some time to finish gracefully, but still want # it to kill httpd after TimeoutStopSec if something went wrong during the # graceful stop. Normally, Systemd sends SIGTERM signal right after the # ExecStop, which would kill httpd. We are sending useless SIGCONT here to give # httpd time to finish. KillSignal=SIGCONT PrivateTmp=true [Install] WantedBy=multi-user.target
1.Unit段的常用选项意义:
Description:描述信息,意义性描述;
After:定义unit的启动次序,表示当前unit应该晚于哪些unit启动,其功能与Before相反
Requires:依赖到的其它units,强依赖,被依赖的units无法激活时,当前unit即无法激活
Wants:依赖到的其它units,弱依赖;
Conflicts:定义units间的冲突关系
2.Service段的常用选项意义:
★Type:定义影响ExecStart及相关参数的功能的unit进程启动类型
☉类型:
simple:默认值,这个daemon主要由ExecStart接的指令串来启动,启动后常驻于内存中
forking:由ExecStart启动的程序透过spawns延伸出其他子程序来作为此daemon的主要服务。原生父程序在启动结束后就会终止
oneshot:与simple类似,不过这个程序在工作完毕后就结束了,不会常驻在内存中
dbus:与simple类似,但这个daemon必须要在取得一个D-Bus的名称后,才会继续运作.因此通常也要同时设定BusNname= 才行
notify:在启动完成后会发送一个通知消息。还需要配合NotifyAccess 来让Systemd 接收消息
idle:与simple类似,要执行这个daemon必须要所有的工作都顺利执行完毕后才会执行。这类的daemon通常是开机到最后才执行即可的服务
★EnvironmentFile:环境配置文件;
★ExecStart:指明启动unit要运行命令或脚本的绝对路径;
★ExecStartPre:ExecStart前运行;
★ExecStartPost:ExecStart后运行;
★ExecStop:指明停止unit要运行的命令或脚本;
★Restart:当设定Restart=1 时,则当次daemon服务意外终止后,会再次自动启动此服务
3.Install段的常用选项意义:
Alias:别名,可使用systemctl command Alias.service
RequiredBy:被哪些units所依赖,强依赖
WantedBy:被哪些units所依赖,弱依赖
Also:安装本服务的时候还要安装别的相关服务
注意:
对于新创建的unit文件,或者修改了的unit文件,要通知systemd重载此配置文件,而后可以选择重启
# systemctl daemon-reload
服务Unit 文件示例
(1)创建一个脚本,用于被创建的服务调用
[root@localhost system]# cat /testdir/bak.sh
#!/bin/bash
# 备份/etc/目录
tar -Jcvf /testdir/etc-`date +%F`.tar.xz /etc/ &> dev/null
(2)给bak.sh脚本添加执行权限
[root@localhost ~]# chmod u+x /testdir/bak.sh
(3)创建bak.service服务
[root@localhost ~]# vim /etc/systemd/system/bak.service
[Unit]
Description=backup my etc
Requires=atd.service
[Service]
Type=simple
ExecStart=/bin/bash -c "echo /testdir/bak.sh|at now"
[Install]
WantedBy=multi-user.target
systemctl daemon-reload
systemctl start bak
(4)启用服务
[root@localhost system]# systemctl daemon-reload
[root@localhost system]# systemctl start bak
(5)验证
[root@localhost system]# ll /testdir/
total 8132
-rwxr--r-- 1 root root 91 Sep 21 19:14 bak.sh
-rw-r--r-- 1 root root 4546560 Sep 21 19:15 etc-2016-09-21.tar.xz
CentOS 7 引导顺序
UEFi或BIOS初始化,运行POST开机自检
选择启动设备
引导装载程序, centos7是grub2
加载装载程序的配置文件:/etc/grub.d/ /etc/default/grub /boot/grub2/grub.cfg
加载initramfs驱动模块
加载内核选项
内核初始化,centos7使用systemd代替init
执行initrd.target所有单元,包括挂载/etc/fstab
从initramfs根文件系统切换到磁盘根目录
systemd执行默认target配置,配置文件/etc/systemd/default.target /etc/systemd/system/
systemd执行sysinit.target初始化系统及basic.target准备操作系统
systemd启动multi-user.target下的本机与服务器服务
systemd执行multi-user.target下的/etc/rc.d/rc.local
Systemd执行multi-user.target下的getty.target及登入服务
systemd执行graphical需要的服务
1.设置内核参数:
★设置内核参数,只影响当次启动
★启动时,在linux16行后添加
systemd.unit=desired.target
systemd.unit=emergency.target
systemd.unit=recure.target
recure.target 比emergency 支持更多的功能,例如日志等
2.启动排错:
★文件系统损坏
先尝试自动修复,失败则进入emergency shell,提示用户修复
★在/etc/fstab不存在对应的设备和UUID
等一段时间,如不可用,进入emergency shell
★在/etc/fstab不存在对应挂载点
systemd尝试创建挂载点,否则提示进入emergency shell.
★在/etc/fstab不正确的挂载选项
提示进入emergency shell