systemd

Systemd 的簡介和特點

   Systemd 是 Linux 系統中最新的初始化系統(init),它主要的設計目標是克服 sysvinit 固有的缺點,提高系統的啓動速度。系統啓動和服務器守護進程管理器,負責在系統啓動或運行時,激活系統資源,服務器進程和其它進程,向下兼容,但是效率沒有systemd高。

      Systemd新特性:

       系統引導時實現服務並行啓動

       按需啓動守護進程

       自動化的服務依賴關係管理

        同時採用socket式與D-Bus總線式激活服務

       系統狀態快照  

[root@localhost ~]# pstree
systemd─┬─NetworkManager─┬─2*[dhclient]
        │                ├─teamd
        │                └─2*[{NetworkManager}]
        ├─abrt-watch-log
        ├─abrtd
        ├─agetty
        ├─auditd───{auditd}
        ├─crond
        ├─dbus-daemon───{dbus-daemon}
        ├─firewalld───{firewalld}
        ├─httpd───5*[httpd]
        ├─irqbalance
        ├─lvmetad
        ├─master─┬─pickup
        │        └─qmgr
        ├─polkitd───5*[{polkitd}]
        ├─rpcbind
        ├─rsyslogd───2*[{rsyslogd}]

wKiom1lsqMjwx0NlAAD-2b37foE581.png

wKiom1lsqQuAFLYHAABNNgTaqyY779.png

systemd提供了併發啓動能力,開機不會啓動所有服務,按需激活的方式,提高了啓動速度。

核心概念: unit

     unit表示不同類型的systemd對象,通過配置文件進行標識和配置;文件中主要包含了系統服務、監聽socket、保存的系統快照以及其它與init相關的信息

      配置文件:

/usr/lib/systemd/system:每個服務最主要的啓動腳本設置,類似於之前的/etc/init.d/

/run/systemd/system:系統執行過程中所產生的服務腳本,比上面目錄優先運行

/etc/systemd/system:管理員建立的執行腳本,類似於/etc/rc.d/rcN.d/Sxx類的功能,比上面目錄優先運行

     Unit類型

          service unit:擴展名爲 .service

               不需要執行權限,只是配置文件,用於定義系統服務

          target unit   : 擴展名爲  . target

                用於模擬實現"運行級別"

          Divice unit   :  .divice  

               用於定義內核識別的設備

          Mount unit    :  .mount

                 定義文件系統掛載點

          Socket unit: .socket

            用於標識進程間通信用的socket文件,也可在系統啓動時,延遲啓動服務,實現按需啓動

          Snapshot unit: .snapshot,

                管理系統快照

          Swap unit: .swap,

                用於標識swap設備

          Automount unit: .automount,

                文件系統的自動掛載點

         Automount unit: .automount,

                文件系統的自動掛載點

       Path unit: .path,

             用於定義文件系統中的一個文件或目錄使用,常用於當文件系統變化時,延遲激活服務,如: spool 目錄

特性


  關鍵特性:

          基於socket的激活機制: socket與服務程序分離

      #爲每個服務預先創建激活socket,systemd監聽對應socket,當需要使用時啓動服務

        基於d-bus的激活機制:

        基於device的激活機制:

        基於path的激活機制:

        系統快照:保存各unit的當前狀態信息於持久存儲設備中 

        向後兼容sysv init腳本(在cenos7上不建議init級別和init切換運行級別)

不兼容:

        systemctl命令固定不變,不可擴展

        非由systemd啓動的服務, systemctl無法與之通信和控制

   系統服務不會讀取標準輸入流,系統服務啓動不會讀取任何用戶環境變量,服務中需要使用絕對路徑超過5分鐘,就會強制退出

管理系統服務:

    

    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 tryrestart name.service
重載或重啓服務:先加載,再啓動
systemctl reload-or-restart name.service
重載或條件式重啓服務:
systemctl reload-or-try-restart name.service
禁止自動和手動啓動:
systemctl mask name.service
取消禁止:
systemctl unmask name.service

查看活動服務

    查看某服務當前激活與否的狀態:

    systemctl is-active name.service

    

[root@localhost system]# systemctl list-units
  UNIT                                LOAD   ACTIVE SUB       DESCRIPTION
  proc-sys-fs-binfmt_misc.automount   loaded active waiting   Arbitrary Executable File Formats Fi
  sys-devices-pci0000:00-0000:00:07.1-ata2-host1-target1:0:0-1:0:0:0-block-sr0.device loaded activ
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda1.device loaded activ
  sys-devices-pci0000:00-0000:00:10.0-host2-target2:0:0-2:0:0:0-block-sda-sda2.device loaded acti

查看激活服務

         systemctl list-units --type|-t service

[root@localhost system]# systemctl list-units --type service

  查看所有服務:

        systemctl list-units --type service –all|-a

[root@localhost system]# systemctl list-units --type service all

  chkconfig命令的對應關係:

           設定某服務開機自啓:

               chkconfig name on ==> systemctl enable name.service

          設定某服務開機禁止啓動:

               chkconfig name off ==> systemctl disable name.service

          查看所有服務的開機自啓狀態:

               chkconfig --list ==> systemctl list-unit-files --type service

 列出該服務在哪些運行級別下啓用和禁用

    ls /etc/systemd/system/*.wants/sshd.service

[root@localhost system]# ls /etc/systemd/system/
basic.target.wants                           default.target.wants
dbus-org.fedoraproject.FirewallD1.service    getty.target.wants
dbus-org.freedesktop.ModemManager1.service   multi-user.target.wants
dbus-org.freedesktop.NetworkManager.service  sockets.target.wants
dbus-org.freedesktop.nm-dispatcher.service   sysinit.target.wants
default.target                               system-update.target.wants

 查看服務是否開機自啓:

           systemctl is-enabled name.service

[root@localhost system]# systemctl is-enabled sshd.service
enabled
[root@localhost system]# systemctl is-enabled network.service
network.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig network --level=5
enabled

 查看服務的依賴關係:

        systemctl list-dependencies name.service

[root@localhost system]# systemctl list-dependencies network.service
network.service
● ├─system.slice
● ├─basic.target
● │ ├─firewalld.service
● │ ├─microcode.service
● │ ├─rhel-autorelabel-mark.service
[root@localhost system]# systemctl list-dependencies emergency.service
emergency.service
● ├─-.mount
● └─system.slice

 殺掉進程:

    systemctl kill 進程名

服務狀態

systemctl list-unit-files --type service --all顯示狀態

     loaded:Unit配置文件已處理


     active(running):一次或多次持續處理的運行

     active(exited):成功完成一次性的配置

     active(waiting):運行中,等待一個事件

     inactive:不運行

     enabled:開機啓動

     disabled:開機不啓動

     static:開機不啓動,但可被另一個啓用的服務激活

systemctl 命令示例

顯示所有單元狀態

    systemctl 或 systemctl list-units

[root@localhost getty.target.wants]# systemctl list-units 
 sys-subsystem-rfkill-devices-rfkill1.device loaded active plugged   /sys/subsystem/rfkill/device
  -.mount                             loaded active mounted   /
  app.mount                           loaded active mounted   /app
  boot.mount                          loaded active mounted   /boot
  dev-hugepages.mount                 loaded active mounted   Huge Pages File System
  dev-mqueue.mount                    loaded active mounted   POSIX Message Queue File System
  home.mount                          loaded active mounted   /home
  mnt.mount                           loaded active mounted   /mnt
  run-user-0.mount                    loaded active mounted   /run/user/0

只顯示服務單元的狀態

    systemctl --type=service

[root@localhost getty.target.wants]# systemctl --type=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
  abrtd.service                      loaded active running ABRT Automated Bug Reporting Tool
  auditd.service                     loaded active running Security Auditing Service
  crond.service                      loaded active running Command Scheduler
  dbus.service                       loaded active running D-Bus System Message Bus
  firewalld.service                  loaded active running firewalld - dynamic firewall daemon
  [email protected]                 loaded active running Getty on tty1
  httpd.service                      loaded active running The Apache HTTP Server

 顯示sshd服務單元

    systemctl status sshd.service –l

[root@localhost getty.target.wants]# systemctl status httpd.service
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-07-14 09:39:24 CST; 6h ago
     Docs: man:httpd(8)
           man:apachectl(8)
 Main PID: 68544 (httpd)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"
   CGroup: /system.slice/httpd.service
           ├─68544 /usr/sbin/httpd -DFOREGROUND
           ├─68545 /usr/sbin/httpd -DFOREGROUND
           ├─68546 /usr/sbin/httpd -DFOREGROUND
           ├─68547 /usr/sbin/httpd -DFOREGROUND
           ├─68548 /usr/sbin/httpd -DFOREGROUND
           └─68549 /usr/sbin/httpd -DFOREGROUND
Jul 14 09:39:23 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
Jul 14 09:39:24 localhost.localdomain httpd[68544]: AH00558: httpd: Could not reliably determ...ge
Jul 14 09:39:24 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
Hint: Some lines were ellipsized, use -l to show in full.

 驗證sshd服務當前是否活動

    systemctl is-active sshd

[root@localhost getty.target.wants]# systemctl is-active sshd
active
[root@localhost getty.target.wants]# systemctl is-active httpd
active

  啓動,停止和重啓sshd服務

    systemctl start sshd.service
    systemctl stop sshd.service

    systemctl restart sshd.service

[root@localhost getty.target.wants]# systemctl restart httpd
[root@localhost getty.target.wants]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-07-14 15:47:48 CST; 9s ago

  

重新加載配置

    systemctl reload sshd.service

   用於修改配置文件後修改

[root@localhost getty.target.wants]# systemctl reload sshd.service &&echo $?
0

列出活動狀態的所有服務單元

    systemctl list-units --type=service

root@localhost getty.target.wants]# systemctl list-units --type 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

列出所有服務單元

      systemctl list-units --type=service --all

[root@localhost getty.target.wants]# systemctl list-units --type service -a
  UNIT                                LOAD      ACTIVE   SUB     DESCRIPTION
  abrt-ccpp.service                   loaded    active   exited  Install ABRT coredump hook
  abrt-oops.service

查看服務單元的啓用和禁用狀態

     systemctl list-unit-files --type=service

[root@localhost getty.target.wants]# systemctl list-unit-files --type service
UNIT FILE                                     STATE   
abrt-ccpp.service                             enabled
abrt-oops.service                             enabled
abrt-pstoreoops.service                       disabled
abrt-vmcore.service                           enabled
abrt-xorg.service                             enabled
abrtd.service                                 enabled
arp-ethers.service                            disabled
atd.service                                   enabled
auditd.service                                enabled
[email protected]                               enabled
blk-availability.service                      disabled
brandbot.service                              static 
chrony-dn***[email protected]                        static
[root@localhost getty.target.wants]# systemctl list-unit-files --type service |grep enabled
abrt-ccpp.service                             enabled
abrt-oops.service                             enabled
abrt-vmcore.service                           enabled

列出失敗的服務

      systemctl --failed --type=service

[root@localhost getty.target.wants]# systemctl --failed --type service
  UNIT          LOAD   ACTIVE SUB    DESCRIPTION
● kdump.service loaded failed failed Crash recovery kernel arming
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.
1 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

列出依賴的單元

     systemctl list-dependencies sshd

[root@localhost getty.target.wants]# systemctl list-dependencies sshd
sshd.service
● ├─sshd-keygen.service
● ├─system.slice
● └─basic.target
●   ├─firewalld.service
●   ├─microcode.service
●   ├─rhel-autorelabel-mark.service
●   ├─rhel-autorelabel.service
●   ├─rhel-configure.service
●   ├─rhel-dmesg.service

驗證sshd服務是否開機啓動

     systemctl is-enabled sshd

[root@localhost getty.target.wants]# systemctl is-enabled sshd
enabled

禁用network,使之不能自動啓動,但手動可以

     systemctl disable network

[root@localhost getty.target.wants]# systemctl disable network
network.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig network off
[root@localhost getty.target.wants]# systemctl is-enabled network
network.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig network --level=5
disabled

啓用network

      systemctl enable network

[root@localhost getty.target.wants]# systemctl is-enabled network
network.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig network --level=5
enabled

禁用network,使之不能手動或自動啓動

          systemctl mask network

[root@localhost getty.target.wants]# systemctl mask network
Created symlink from /etc/systemd/system/network.service to /dev/null.
[root@localhost getty.target.wants]# systemctl enable network
Failed to execute operation: Cannot send after transport endpoint shutdown

啓用network

          systemctl unmask network

[root@localhost getty.target.wants]# systemctl unmask network.service
Removed symlink /etc/systemd/system/network.service.
[root@localhost getty.target.wants]# systemctl enable network
network.service is not a native service, redirecting to /sbin/chkconfig.
Executing /sbin/chkconfig network on

運行級別

      target units:

unit配置文件: .target

ls /usr/lib/systemd/system/*.target
systemctl list-unit-files --type target --all
[root@localhost getty.target.wants]# ls /usr/lib/systemd/system
abrt-ccpp.service                       proc-sys-fs-binfmt_misc.automount
abrtd.service                           proc-sys-fs-binfmt_misc.mount
abrt-oops.service                       psacct.service
abrt-pstoreoops.service                 quotaon.service
abrt-vmcore.service                     rc-local.service
abrt-xorg.service                       rdisc.service
arp-ethers.service                      rdma.service
atd.service                             reboot.target
auditd.service                          reboot.target.wants
[email protected]                         remote-fs-pre.target
basic.target                            remote-fs.target
basic.target.wants                      rescue.service
blk-availability.service                rescue.target
bluetooth.target                        rescue.target.wants
[root@localhost getty.target.wants]# systemctl list-unit-files --type target -a
UNIT FILE                 STATE   
basic.target              static 
bluetooth.target          static 
cryptsetup-pre.target     static 
cryptsetup.target         static 
ctrl-alt-del.target       disabled
cvs.target                static 
default.target            enabled
emergency.target          static 
final.target              static 
getty.target              static 
graphical.target          static 
halt.target               disabled
hibernate.target          static 
hybrid-sleep.target       static 
initrd-fs.target          static 
initrd-root-fs.target     static 
initrd-switch-root.target static 
initrd.target             static 
iprutils.target           disabled

級別切換: init N ==> systemctl isolate name.target

                  systemctl isolate multi-user.target

注: 只有/lib/systemd/system/*.target文件中AllowIsolate=yes 才能切換(修改文件需執行systemctl daemonreload才能生效)

      查看target:

runlevel ; who -r

systemctl list-units --type target

[root@localhost getty.target.wants]# who -r
         run-level 3  2017-07-12 18:48
[root@localhost getty.target.wants]# systemctl list-units --type target
UNIT                  LOAD   ACTIVE SUB    DESCRIPTION
basic.target          loaded active active Basic System
bluetooth.target      loaded active active Bluetooth
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
network-online.target loaded active active Network is Online
network.target        loaded active active Network
paths.target          loaded active active Paths
remote-fs.target      loaded active active Remote File Systems
slices.target         loaded active active Slices
sockets.target        loaded active active Sockets
sound.target          loaded active active Sound Card
swap.target           loaded active active Swap
sysinit.target        loaded active active System Initialization
timers.target         loaded active active Timers

獲取默認運行級別:

               /etc/inittab ==> systemctl get-default

[root@localhost getty.target.wants]# systemctl get-default
multi-user.target

修改默認級別:

    /etc/inittab ==> systemctl set-default name.target

    systemctl set-default multi-user.target

    ls –l /etc/systemd/system/default.target


切換至緊急救援模式:

          systemctl rescue

切換至emergency模式:

          systemctl emergency

其它常用命令:

傳統命令init, poweroff, halt, reboot都成爲systemctl的軟鏈接

    關機: systemctl halt、 systemctl poweroff

    重啓: systemctl reboot

    掛起: systemctl suspend

    休眠: systemctl hibernate

    休眠並掛起: systemctl hybrid-sleep

[root@localhost getty.target.wants]# ls -l /sbin/{init,poweroff,halt,reboot}
lrwxrwxrwx. 1 root root 16 Jul 13 16:10 /sbin/halt -> ../bin/systemctl
lrwxrwxrwx. 1 root root 22 Jul 13 16:10 /sbin/init -> ../lib/systemd/systemd
lrwxrwxrwx. 1 root root 16 Jul 13 16:10 /sbin/poweroff -> ../bin/systemctl
lrwxrwxrwx. 1 root root 16 Jul 13 16:10 /sbin/reboot -> ../bin/systemctl

CentOS7引導順序

wKioL1lsrsbwCxiRAADGzDkrnsY162.png

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“命令在實現服務啓用或禁用時用到的一些選項

    Unit段的常用選項

 Description:描述信息

 After:定義unit的啓動次序,表示當前unit應該晚於哪些unit啓動,其功能與Before相反

 Requires:依賴到的其它units,強依賴,被依賴的units無法激活時,當前unit也無法激活

 Wants:依賴到的其它units,弱依賴

 Conflicts:定義units間的衝突關係

   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服務意外終止後,會再次自動啓動此服務

    Install段的常用選項:

Alias:別名,可使用systemctl command Alias.service
RequiredBy:被哪些units所依賴,強依賴
WantedBy:被哪些units所依賴,弱依賴

Also:安裝本服務的時候還要安裝別的相關服務

注意:對於新創建的unit文件,或者修改了的unit文件,要通知systemd重載此配置文件,而後可以選擇重啓

    systemctl daemon-reload

設置內核參數

設置內核參數,隻影響當次啓動
 啓動時,在linux16行後添加systemd.unit=desired.target
 systemd.unit=emergency.target
 systemd.unit=recure.target

 recure.target 比emergency 支持更多的功能,例如日誌等

啓動排錯

           文件系統損壞

先嚐試自動修復,失敗則進入emergency shell,提示用戶修復

 在/etc/fstab不存在對應的設備和UUID

等一段時間,如不可用,進入emergency shell

 在/etc/fstab不存在對應掛載點

systemd 嘗試創建掛載點,否則提示進入emergency shell.

 在/etc/fstab不正確的掛載選項

提示進入emergency shell

破解CentOS7的root口令

    方法1

 啓動時任意鍵暫停啓動
 按e鍵進入編輯模式
 將光標移動linux16開始的行,添加內核參數rd.break
 按ctrl-x啓動
 mount –o remount,rw /sysroot
 chroot /sysroot
 passwd root
 touch /.autorelabel
 exit

 reboot

   方法2

 啓動時任意鍵暫停啓動
 按e鍵進入編輯模式

 將光標移動linux16開始的行,改爲rw init=/sysroot/bin/sh
 按ctrl-x啓動
 chroot /sysroot
 passwd root

 touch /.autorelabel
 exit

 reboot

修復GRUB2

   GRUB“the Grand Unified Bootloader”

引導提示時可以使用命令行界面

可從文件系統引導

 主要配置文件 /boot/grub2/grub.cfg

 修復配置文件

grub2-mkconfig > /boot/grub2/grub.cfg

 修復grub

grub2-install /dev/sda BIOS環境

grub2-install UEFI環境

  調整默認啓動內核

vim /etc/default/grub

GRUB_DEFAULT=0





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章