2020年11月4日 星期三

Linux rpm build (3) .service 開機可自動執行

參考來源:

Linux systemd 系統服務管理基礎教學與範例

如何在Linux上將任意應用程式變成開機可自動執行


Systemd 基本服務管理

在 Systemd 中每一個系統服務就稱為一個服務單位(unit),而服務單位又可以區分為 service、socket、target、path、snapshot、timer 等多種不同的類型(type),

我們可以從設定檔的附檔名來判斷該服務單位所屬的類型,最常見的就是以 .service 結尾的系統服務,大部分的伺服器都是屬於這種。


如果要管理 Systemd 中的各種服務,可以使用 systemctl 這個指令,配合各種操作指令來進行各種操作。


systemctl 操作指令 服務名稱.service

若要啟動系統服務,可以使用 start 操作指令,例如啟動 accusys.service:

當我們在指定服務名稱時,可以將結尾的 .service 省略,這樣可以少打一些字,例如:


# 套用Systemd Unit的設定檔變更

在新增、或是修改Systemd Unit的設定檔後,要在終端機執行以下指令才會重新載入:

sudo systemctl daemon-reload


# 啟動 service

sudo systemctl start accusys


# 顯示 service 服務狀態

systemctl status accusys


# 停止 service 服務

sudo systemctl stop accusys


# 設定開機自動啟動 service

sudo systemctl enable accusy


# 取消開機自動啟動 service

sudo systemctl disable accusys


# 檢查 service 服務是否正在運行

systemctl is-active accusys


# 檢查 service 服務是否有設定開機自動啟動

systemctl is-enabled accusys


# 檢查 service 服務是否啟動失敗

systemctl is-failed accusys


列出 Systemd 所有服務

若想要列出所有已啟動的服務,可以使用 list-units 操作指令:


# 列出所有已啟動的服務

systemctl list-units


# 查看服務內部設定檔

systemctl cat accusys.service


---------------------------------------------------------------->

[Unit]

Description=Accusys GUI GS

After=network.target

 

[Service]

# User=user

# Group=group

# WorkingDirectory=/path/to/folder

ExecStart=/lib/modules/3.10.0-514.el7.x86_64/kernel/drivers/scsi/accusys/RGX_GS_3.6.8/DTRGuiSrv_64

Restart=always

RestartSec=10s


# Environment="VARIABLE_1=VALUE_1" "VARIABLE_2=VALUE_2"

# Environment="VARIABLE_3=VALUE_3" "VARIABLE_4=VALUE_4"

 

[Install]

WantedBy=multi-user.target

<----------------------------------------------------------------


[Unit]區塊中,我們撰寫了兩個項目。

Description用來設定這個Systemd Service Unit設定檔案的描述,可以讓管理員在日後查看時還能想起這個Systemd Service Unit的目的是什麼。

另一個After項目可以用來指定一個Systemd Target Unit,可以確保目前正在設定的這個Unit,會在Systemd Target Unit運行完後再運行。

如果是用來提供Web服務的應用程式,那麼通常就必須要在作業系統環境的網路功能被啟用之後才能夠正常啟動,

所以After項目設定為network.target可以確保該程式在第一次執行時候就順利啟動。


[Service]區塊中有五個使用井字號#註解掉的項目,這些先不要管它,稍候會再提到。

ExecStart項目可以用來設定當這個Systemd Service Unit項目啟動時要執行的應用程式(需使用完整絕對路徑),並且如果需要的話,

可以利用空白字元來分隔多個不同的引數。若是這個程式需要搭配shell的命令列功能(例如變數、管線等)來執行,

那就使用如以下的方式先執行shell之後,再運行shell的命令吧!


ExecStart=/bin/bash -c 'shell命令'

Restart項目可以設定ExecStart所執行的程式要在什麼樣的情況被關閉時,以相同的指令再重新執行一次。有效的設定值如下:


no:不重啟。(預設值)

always:不管什麼原因都會重啟。

on-success:只在成功運行結束後(也就是行程回傳的Exit Status為0的時候)才進行重啟。(這蠻少用)

on-failure:在運行失敗後(行程回傳的Exit Status非為0、被使用Kill信號強制關閉、逾時或是餵狗沒反應時)才進行重啟。

on-abnormal:在意外地運行失敗後(被使用Kill信號強制關閉、逾時或是餵狗沒反應時)才進行重啟。

on-abort:被使用Kill信號強制關閉時才進行重啟。

on-watchdog:餵狗沒反應時才進行重啟。

上述提到的「逾時」,可以在[Service]區塊中用TimeoutSec項目來設定程式在執行多久後算是逾時,一般我們是用不到這個機制啦!

而「餵狗」則是使用Systemd提供的看門狗(Watchdog)機制,使程式在固定時間內(可以在[Service]區塊中用WatchdogSec項目來設定),

必須主動呼叫Systemd函式庫的sd_notify函數,以利Systemd判斷該程式是否還是正常運作的狀態,一般我們也是用不到這個機制的啦!


至於RestartSec這個項目,就是設定程式在被關閉後,到下次自動重啟的間隔時間,預設是100ms(毫秒)。

最後的[Install]區塊中,只有WantedBy這一個設定項目,它可以用來指定一個Systemd Target Unit,讓目前正在設定的這個Unit,

會在運行該Systemd Target Unit時,也跟著被運行。

接著來談談被註解掉的項目,首先是User和Group這兩個項目,它們可以分別用來設定要運行ExecStart項目所指定的程式時所使用的使用者名稱和群組名稱。

另外如果程式的運行必須仰賴工作目錄的支援的話,就要使用WorkingDirectory項目來手動指定程式工作目錄的路徑。

而如果要替執行的程式設定環境變數的話,可以透過一個或是數個Environment項目來設定,一個Environment項目可以設定多個環境變數。



Linux rpm build (2) - RPM 如何打包

相關參考網址:

RPM 打包︰由一竅不通到動手濫用

RPM打包原理、示例、詳解及備查


** rpmbuild 建置指令

rpmbuild -bb accusys.spec


** 撰寫 rpm SPEC

---------------------------------------------------------------->

# Some metadata required by an RPM package

Name: accusys

Summary: Install Accusys linux driver and GUI.

Version: 1.0

Release: 1

License: GPLv2


%description

Install Accusys driver for "DaVinci-Resolve-Linux-16.0-CentOS_7.3"

Install Accusys GUI GC and GS.


# Get the kernel headers version installed, not based on uname.

%define kversion %(rpm -q kernel%{?bt_ext}-devel | sort --version-sort | tail -1 | sed 's/kernel%{?bt_ext}-devel-//')

%define RGX_GC RGX_GC_3.6.8

%define RGX_GS RGX_GS_3.6.8


%install

mkdir -p %{buildroot}/lib/modules/`uname -r`/extra/accusys

cp -pdf /home/Sam/rpmbuild/SOURCES/ACS6x.ko %{buildroot}/lib/modules/`uname -r`/extra/accusys/ACS6x.ko

chmod 755 %{buildroot}/lib/modules/`uname -r`/extra/accusys/ACS6x.ko

cp -pdfr /home/Sam/rpmbuild/SOURCES/%{RGX_GS} %{buildroot}/lib/modules/`uname -r`/extra/accusys/%{RGX_GS}

cp -pdfr /home/Sam/rpmbuild/SOURCES/%{RGX_GC} %{buildroot}/lib/modules/`uname -r`/extra/accusys/%{RGX_GC}

mkdir -p %{buildroot}/usr/lib/systemd/system

cat <<EOF> %{buildroot}/usr/lib/systemd/system/accusys.service

[Unit]

Description=Accusys GUI GS

After=network.target

 

[Service]

# User=user

# Group=group

# WorkingDirectory=/path/to/folder

ExecStart=/lib/modules/3.10.0-514.el7.x86_64/extra/accusys/RGX_GS_3.6.8/DTRGuiSrv_64

Restart=always

RestartSec=10s


[Install]

WantedBy=multi-user.target

EOF


%post

depmod

systemctl start accusys

systemctl status accusys

systemctl enable accusys


%preun

systemctl stop accusys

systemctl disable accusys


%postun

depmod


%files

/lib/modules/%{kversion}/extra/accusys/ACS6x.ko

/lib/modules/%{kversion}/extra/accusys/%{RGX_GS}

/lib/modules/%{kversion}/extra/accusys/%{RGX_GC}

/usr/lib/systemd/system/accusys.service

<----------------------------------------------------------------


SPEC 檔︰ 參數定義


** SPEC 檔︰表頭 (Preamble) 的基本內容

Name:           所包裝軟件的名稱。

Summary:        軟件的簡短介紹。

Version:        軟件的版本編號。

Release:        同一版本軟件的發佈次數。預設為 1%{?dist},每打包一次應該 +1,直到版本編號更新為止。

License:        軟件的使用授權模式,像是「GPLv3」或者「MIT」之類。


URL:            軟件的官方網站。

Source0:        下載軟件源代碼的路徑或完整網址。如果有多於一個,可繼續用 Source1, Source2, … SourceX 去定義。

Patch0:         下載第一個源代碼補丁的網址。只在有需要時定義。同樣可以有 Patch1, Patch2, … PatchX。

BuildArch:      如果只支援在特定硬體架構編譯,需要在這裏定義,像是「x86_64」之類。

BuildRequires:  定義編譯軟件所需要的套件。需要用逗號或空白分隔套件名稱,亦可以分開多次定義 BuildRequires。

Requires:       定義執行軟件所需要的套件。需要用逗號或空白分隔套件名稱,亦可以分開多次定義 BuildRequires。

ExcludeArch:    如果軟件不能在特定架硬件架構下運作,需要在此定義。


** SPEC 檔︰內文 (Body) 的基本內容

%install:       安裝編譯好軟件的 shell 程序。一般包括將你要安裝的執行檔、軟件庫、設定檔、說明文件等等,

                由編譯的資料匣(如 %_builddir)移放到 %buildroot 去。

                在理想的世界裏,是預備好 ~/rpmbuild/BUILDROOT 的資料匣結構,然後把檔案由 ~/rpmbuild/BUILD 搬到 ~/rpmbuild/BUILDROOT 的程序。

%check:         檢查軟件的 shell 程序,一般擺放 unit test 的指令。

%files:         需要打包的檔案列表,每行一個定義,可以使用 bash 通用的「*」萬用字元 。

                留意這裏的檔案路徑以 %buildroot 定義的資料匣為根目錄,換言之沒放在這裏的檔案,是無法被打包的。

%changelog:     軟件變化的紀錄,定義不同版本 (version) 或建置版本 (build) 的變化。


在軟體包安裝之前( %pre)或之後( %post)執行

在軟體包卸載之前( %preun)或之後( %postun)執行

在事務開始( %pretrans)或結束( %posttrans)時執行















2020年11月3日 星期二

Linux rpm build (1) - rpmbulid

    rpm命令使用簡介

    什麼是rpm?

    rpm是RPM package manager的縮寫,最早由RedHat公司提出的軟體包標準,後來隨著rpm的不斷髮展而又增加許多功能,

    逐漸的成為linux公認的軟體包管理標準。支援該格式的廠商有RedHat linux、suse linux、Mandriva linux。


    rpm命令十分強大,那麼rpm命令究竟有什麼功能呢?

    1 查詢已安裝在linux系統中的rpm軟體包的資訊

    2 查詢rpm軟體包安裝檔案的資訊

    3 安裝rpm軟體包到當前linux系統

    4 從linux系統中解除安裝已安裝的rpm軟體包

    5 升級當前linux系統的rpm軟體包

    (1)#rpm -qa       後面不接引數用於檢視系統中已經安裝的所有的rpm

    (2)#rpm -q rpm    用於檢視系統中是否安裝了該軟體包,如果安裝了,系統會顯示完整的包名;如果沒有安裝,系統會提示”package bas is not installed”。

    (3)#rpm -qi rpm   用於檢視系統中已經安裝的rpm包的完整資訊,包括該包的版本資訊,安裝時間和大小等。

    (4)#rpm -ql rpm   用於檢視該軟體包都安裝到了那些位置。

    (5)#rpm -qf 檔名  用於檢視某個檔案使用那個rpm包安裝的。

    (6)#rpm -qpi rpm  和#rpm -qpl分別用於檢視沒有安裝的包的資訊,注意下和(4)、(5)的區別。

    (7)#rpm -ivh      用於安裝rpm軟體包,i代表安裝、v代表視覺化安裝、h代表安裝的時候顯示進度。

    (8)#rpm –force -irpm 用於強制安裝rpm軟體包,–force引數用於安裝存在依存關係的rpm包。不過一般我們並不怎做,解決依存關係的較好的方法是使用#rpm -i 命令一起安裝。

    (9)#rpm -e rpm    用於刪除rpm軟體包。

              #rpm -e –nodeps rpm 用於刪除存在依存關係的軟體包,該命令可以將和該包存在依存關係的所有的軟體包統統刪除。

   (10)#rpm -Urpm     用於對rpm包的升級。


    **解壓縮rpm檔

    在 Redhat 系列的發行版內, 所有安裝的套件都會打包成 rpm 檔, 安裝時只要安裝一個檔案便可以, 就如同 Debian 的 deb 檔,

    使用 rpm 安裝套件十分方便, 但有時只想解開 rpm 檔的內容, 而不要安裝套件, 這時可以用 rpm2cpio cpio 指令。

    解開 rpm 不像解開 deb 可以用單一指令完成, 需要先用 rpm2cpio 轉換 rpm 成為 cpio 格式, 再用 cpio 解開,

    這個動作可以透過管線 (pipe) 完成。

    例如有一個 example.rpm 要解開, 指令是這樣:

    # rpm2cpio example.rpm | cpio -idmv

    以上指令會將 example.rpm 的內容解開到當前目錄。


    ** rpmbuild  手動建立自己的rpm

    動手打包前,首先得安裝相關的軟件。我們需要使用的程式是 rpmbuild

    如果你是 RHEL、CentOS

    sudo yum install rpm-build


    如果你是 Ubuntu 或者 Debian 的用戶,

    sudo apt-get install rpm

    

    安裝之後,我們來試一試 rpmbuild是否存在︰

    rpmbuild --version

    RPM version 4.4.2.3



文章參考:

https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/392870/

https://www.opencli.com/linux/extract-rpm-files

 

2020年7月23日 星期四

How to compile Kernel Ubuntu 20.04


Copy from https://linuxguides.co.uk/guides/how-to-compile-kernel-ubuntu-20-04/

How to compile Kernel Ubuntu 20.04


In this guide I am going to show you how to compile a Kernel on Ubuntu 20.04 x86_64
First of all we are going to install the missing dependencies
apt-get update && apt-get upgrade && apt-get install -y build-essential libncurses5-dev gcc libssl-dev grub2 bc bison flex libelf-dev
Then we are going to download the kernel from kernel.org
wget https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.7.5.tar.xz
tar -xvf linux-5.7.5.tar.xz
Then we need to copy the existing config file so that the correct modules for the Hardware of the machine you are compiling the kernel for
You need to enter the command below to find the current kernel config file.
ls -l /boot
cp /boot/config-4.4.0-21-generic /root/linux-5.7.5/.config
Then we are going to compile the kernel firstly you want to cd into the kernel folder
cd /root/linux-5.7.5
(Adjust -j8 to the amount of cores the machine has that you are compiling the kernel for)
make menuconfig
make -j8 deb-pkg
dpkg -i ,,/linux-*.deb
update-grub
Then you can proceed to rebooting the machine by typing the following
reboot
Once the machine is rebooted you can confirm the latest kernel by entering the following command
uname -a

2020年6月11日 星期四

Mac loaded driver script

#!/bin/bash
 
# MacOS Catalina (10.15):  Darwin 19.x.0
kernelver=`uname -a | awk '{print $3}'`
kernelver1=$(echo $kernelver | cut -d "." -f 1)
kernelver2=$(echo $kernelver | cut -d "." -f 2)
kernelver=$kernelver1.$kernelver2
echo "Check Mac OS kernel version: Darwin kernel version : $kernelver"


if [ $(echo "$kernelver >= 19.0" |bc) -eq 1 ]; then
    echo "  Mac OS version >= 10.15.x"
   
    kernelpath=`sudo pwd`
    if [ "$kernelpath" != "/Library/Extensions" ]; then
        echo "  In path $kernelpath"
        if [ -d "/Library/Extensions/ACS6x.kext" ]; then
            # 目錄 存在
            echo "  Directory /Library/Extensions/ACS6x.kext exists."
           
            echo "  Remove ACS6x.kext driver"
            sudo rm -rf /Library/Extensions/ACS6x.kext
           
            echo "  Copy driver to system"
            sudo cp -R ACS6x.kext /Library/Extensions/
            sudo cd /Library/Extensions/
           
        else
            # 目錄 不存在
            echo "  Directory /Library/Extensions/ACS6x.kext does not exists."
           
            echo "  Copy driver to system"
            sudo cp -R ACS6x.kext /Library/Extensions/
            sudo cd /Library/Extensions/
        fi
       
    else
        if [! -d "/Library/Extensions/ACS6x.kext" ]; then
            # 目錄 不存在
            echo "  Error: Directory /Library/Extensions/ACS6x.kext does not exists."
            exit 0
        fi
       
    fi
   
    echo "  Change ACS6x.kext driver owner"
    sudo chmod -R 755 ACS6x.kext
    sudo chown -R root:wheel ACS6x.kext
    sudo xattr -d -r ACS6x.kext
   
    driverstat=`sudo kextstat|grep Accusys`
    if [ "$driverstat" != "" ]; then
        echo "  Kextunload ACS6x.kext driver"
        sudo kextunload ACS6x.kext
        sudo kextunload ACS6x.kext
    fi
   
    echo "  Clear system cache"
    sudo kextcache -clear-staging
   
    echo "  Loaded ACS6x.kext driver"
    sudo kextload ACS6x.kext
   
    echo "  Rebiuld system cache"
    #sudo kextcache -system-prelinked-kernel
    #sudo kextcache -system-caches
    sudo kextcache -i /

else
    echo "Mac OS version < 10.15.x"
   
    driverstat=`sudo kextstat|grep Accusys`
    if [ "$driverstat" != "" ]; then
        echo "  Kextunload ACS6x.kext driver"
        sudo kextunload ACS6x.kext
        sudo kextunload ACS6x.kext
    fi
   
    echo "Kextload ACS6x.kext driver"
    sudo chmod -R 755 ACS6x.kext
    sudo chown -R root:wheel ACS6x.kext
    sudo kextload ACS6x.kext
   
    if [ $(echo "$kernelver >= 14.0" |bc) -eq 1 ]; then
        sudo touch /Library/Extensions
    else
        sudo touch /System/Library/Extensions
    fi
   
fi

2020年6月9日 星期二

Linux grep 用法

*** 用‘grep’搜索文本文件
    如果您要在幾個文本文件中查找一字符串,可以使用‘grep’命令。‘grep’在文本中搜索指定的字符串。
    假設您正在‘/usr/src/linux/Documentation’目錄下搜索帶字符串‘magic’的文件:
 
    $ grep magic /usr/src/linux/Documentation/*
    sysrq.txt:* How do I enable the magic SysRQ key?
    sysrq.txt:* How do I use the magic SysRQ key?
 
    其中文件‘sysrp.txt’包含該字符串,討論的是 SysRQ 的功能。
 
    默認情況下,‘grep’隻搜索當前目錄。如果此目錄下有許多子目錄,‘grep’會以如下形式列出:
 
    grep: sound: Is a directory
 
    這可能會使‘grep’的輸出難於閱讀。這裡有兩種解決的辦法:
 
    明確要求搜索子目錄:grep -r
    或忽略子目錄:grep -d skip
    當然,如果預料到有許多輸出,您可以通過 管道 將其轉到‘less’上閱讀:
 
    $ grep magic /usr/src/linux/Documentation/* | less
 
    這樣,您就可以更方便地閱讀。
    有一點要注意,您必需提供一個文件過濾方式(搜索全部文件的話用 *)。如果您忘了,‘grep’會一直等著,直到該程序被中斷。如果您遇到了這樣的情況,按 ,然後再試。
 
 
    命令行參數:
    grep -i pattern files :不區分大小寫地搜索。默認情況區分大小寫,
    grep -l pattern files :隻列出匹配的文件名,
    grep -L pattern files :列出不匹配的文件名,
    grep -w pattern files :隻匹配整個單詞,而不是字符串的一部分(如匹配‘magic’,而不是‘magical’),
    grep -C number pattern files :匹配的上下文分別顯示[number]行,
    grep pattern1 | pattern2 files :顯示匹配 pattern1 或 pattern2 的行,
    grep pattern1 files | grep pattern2 :顯示既匹配 pattern1 又匹配 pattern2 的行。


*** grep OR
    以下幾種方法,也可以實現 or 搜索,會對兩種字串進行搜索,只要符合其中一個條件,即會印出那行的內容:
    $ grep ‘pattern1\|patten2’ file.txt
    $ grep -E ‘pattern1|pattern2’ file.txt
    $ egrep ‘pattern1|pattern2’ file.txt
    $ grep -e pattern1 -e pattern2 file.txt

*** grep AND
    $ grep -E ‘pattern1.*pattern2’ file.txt
    $ grep -E ‘pattern1.*pattern2|pattern2.*pattern1’ file.txt
    $ grep -e pattern1 -e pattern2 file.txt


*** grep 要看前兩行或後一行的資訊,該怎麼找呢?

    $ grep -A1 -B2 "5_keyword" file.txt
    3
    4
    5_keyword
    6
 
    grep 參數說明 OPTIONS
    -A NUM, --after-context=NUM  從關鍵字點往後顯示 NUM 行數
       Print NUM lines of trailing context after matching lines. Places a line containing -- between con-
       tiguous groups of matches.
    -B NUM, --before-context=NUM 從關鍵字點往前顯示 NUM 行數
       Print NUM lines of leading context before matching lines. Places a line containing -- between con-
       tiguous groups of matches.
 
 
*** grep 參數說明 OPTIONS
    -n:顯示行數,顯示關鍵字在文件的第幾行出現
    --color=auto:顯示顏色,顯示符合字串的特徵會以顏色來表示
 
    例:dmesg | grep -n -A3 -B2 --color=auto sda
 
*** 用‘grep’搜索文本文件
    如果您要在幾個文本文件中查找一字符串,可以使用‘grep’命令。‘grep’在文本中搜索指定的字符串。
    假設您正在‘/usr/src/linux/Documentation’目錄下搜索帶字符串‘magic’的文件:
 
    $ grep magic /usr/src/linux/Documentation/*
    sysrq.txt:* How do I enable the magic SysRQ key?
    sysrq.txt:* How do I use the magic SysRQ key?

*** find /usr/local/ -name "*.php" -exec grep -l 'function do_action' {} \;

    /usr/local 要尋找的路徑
    *.php 要尋找的檔案類型
    -exec 找到符合的檔案後接著執行那個指令
    -l 顯示檔路路徑
    function do_action 檔案內容有這個keyword的檔名
 
*** 如何殺死defunct殭屍程序
    ps aux | grep defunct ,如果程序為defunct
    ps -ef | grep defunct | grep -v grep | awk '{print "kill -9 " $2,$3}'  //PS. $2 PID $3 PPID

*** linux下find與grep管道命令的組合使用:

    ** 使用find與grep
    
    1.查找所有".h"文件(非組合命令)
    find /PATH -name "*.h"
    
    2.查找所有".h"文件中的含有"helloworld"字符串的文件(組合命令)
    find /PATH -name "*.h" -exec grep -in "helloworld" {} \;
    find /PATH -name "*.h" | xargs grep -in "helloworld"
    
    3. 查找所有".h"和".c"文件中的含有"helloworld"字符串的文件
    find /PATH /( -name "*.h" -or -name "*.c" /) -exec grep -in "helloworld" {} \;
    
    4. 查找非備份文件中的含有"helloworld"字符串的文件
    find /PATH /( -not -name "*~" /) -exec grep -in "helloworld" {} \;
    注:/PATH為查找路徑,默認為當前路徑。帶-exec參數時必須以\;結尾,否則會提示“find:遺漏“-exec”的參數”。
    
    ** 使用find和xargs
    
    1. find pathname -options [-print -exec -ok]
    -optinos
    1)-name:按照文件名查找
        find ~ -name “*.txt” -print
        find ~ -name “[az][0-9]. txt” -print
    2)-perm:按照權限查找文件
        find ~ -perm 755 -print查找權限為755的文件
        find ~ -perm 007 -print查找o位置上具有7權限的文件
        find ~ -perm 4000 -print查找具有suid的文件
    3)-prune
        不在當前目錄下查找
    4)-user和-nouser
        find ~ -user zhao -print查找文件屬主是zhao的文件
        find ~ -nouser -print查找文件屬主已經被刪除的文件
    5)-group和-nogroup
        find ~ -group zhao -print查找文件群組是zhao的文件
    6)按照時間
        find ~ -mtime -5 -print文件更改時間在5天內的文件
        find ~ -mtime +3 -print文件更改時間在3天前的文件
        find ~ -newer file1 -print查找比文件file1新的文件
    7)按照類型查找
        find ~ -type d -print查找所有目錄
    8)按照大小
        find ~ -size +1000000C -print查找文件大小大於1000000字節(1M)的文件
    9)查找位於本文件系統裡面的文件
        find / -name “* .txt” -mount -print
        -exec,-ok:find命令對於匹配文件執行該參數所給出shell命令,相應命令形式為: 'command' {} \;
        -ok在執行命令前要確認
        find ~ - type f -exec ls -l {} \;
        find / -name “*.log” -mtime +5 -ok rm {} \;
        find . -name core -exec rm {} \;
        使用-x dev參數    防止find搜索其他分區
        find . -size 0 -exec rm {} \;
        刪除尺寸為0的文件
    2. xargs與-exec功能類似
        find ~ -type f | xargs ls -l
        find / -name “*.log” -type f -print| xargs grep -i DB0
        find . -type f |xargs grep -i “Mary”
        在所有文件中檢索字符串Mary
        ls *~ |xargs rm -rf
        刪除所有以~結尾的文件
     
    
    ** svn過濾svn文件夾
    
    1.使用管道進行雙層“過濾”,其中第二次grep使用了-v選項,即逆向匹配,打印出不匹配的行
        grep -r ' function_name ' * | grep -v '.svn'
     
    2.或者更簡單一些,直接使用--exclude-dir選項,即指定排除目錄,注意svn前的  \.
        grep -r --exclude-dir=\.svn 'function_name' * 
        grep多個過濾條件
    
    1、or操作
      grep -E '123|abc' filename //找出文件(filename)中包含123或者包含abc的行
      egrep '123|abc' filename //用egrep同樣可以實現
      awk  '/123|abc/' filename // awk的實現方式
    
    2、and操作
      grep pattern1 files  |  grep pattern2 :顯示既匹配pattern1又匹配pattern2的行。
    
    3、其他操作
    grep  - i pattern files :不區分大小寫地搜索。默認情況區分大小寫,
    grep  - l pattern files :只列出匹配的文件名,
    grep  - L pattern files :列出不匹配的文件名,
    grep  - w pattern files :只匹配整個單詞,而不是字符串的一部分(如匹配'magic',而不是'magical'),
    grep  - C number pattern files :匹配的上下文分別顯示[ number ]行,

find / -name Info.plist -exec grep -i "Accusys" {} \;
    

 
 

2020年5月29日 星期五

linux irqbalance setting

[Ubuntu] 關閉 停用 irqbalance

關閉 停用 irqbalance

編輯 ~# vi /etc/default/irqbalance 修改以下設定:
# 找到下面這行設定
#ENABLED="1"
# 更改設定為0
ENABLED="0"


關閉 irqbalance 服務
~# service irqbalance stop
irqbalance stop/waiting

2020年5月27日 星期三

Mac log 查看

log show --predicate 'processImagePath contains "kernel"' --style syslog --last 1d
log
usage:
    log <command>

global options:
    -?, --help
    -q, --quiet
    -v, --verbose

commands:
    collect         gather system logs into a log archive
    config          view/change logging system settings
    erase           delete system logging data
    show            view/search system logs
    stream          watch live system logs
    stats           show system logging statistics

further help:
    log help <command>
    log help predicates
log config is mainly aimed at developers, although it may sometimes be useful if you are trying to solve a problem in a specific app.

log erase (which I suspect also requires sudo) is probably more damaging than useful.

log stream is for prospective collection, one of the few things that Console 1.0 does well.

This leaves the log show command, which is of greatest use for historical data. Although it does support some other options, for our purposes this will normally be used with the following:
log show --predicate [] --style syslog --start [] --end [] --info --last []
where [] represent values which we supply. I’ll take each of those options in turn.

--predicate filters the log content according to the criteria supplied, as predicates. At a simple level, these are straightforward, but can get elaborate and at times confusing. The main types of predicate which you are likely to use are:

eventMessage, as in eventMessage contains "launchd", which selects entries where the message content contains the string launchd
messageType, as in messageType == error, which selects entries which are classified as errors
processID, as in processID < 100, which selects entries from processes with IDs less than 100, i.e. early and low-level
subsystem, as in subsystem == "com.apple.TimeMachine", which selects entries for that specified ‘subsystem’. One neat way to discover subsystems is to use Console 1.0’s info panel; select a log entry and it will give you the applicable subsystem. You will also note how many important processes are not associated with subsystems, which limits the value of this predicate
eventType, processImagePath, senderImagePath, and category are also described in the man page, but so far I have seen little use for them.
You can combine predicates using and or &&, and or, according to Cocoa’s predicate-based filtering.

--style is omitted if you want the output in full form, set to syslog for more compact text form, or to json if you want JSON which you can parse into other software (a powerful feature).

--start and --end set starting and finishing dates and times for the log extraction, given in standard UTC format. These are very valuable for limiting the amount of output, but you will then have to work out the correct values to use.

--info shows all messages down to info level, which is ideal for most purposes.

--last specifies a period of log to extract, for the last minutes, hours, or days, e.g. 3m for 3 minutes, 2h for 2 hours, or 1d for one day. This is an alternative to giving start and end times.

The output from log show is often then piped through additional tools such as grep and cut, and may then be poured into a text file. We shall see these in examples below.

Example commands

John Galt’s suggested command to inspect log entries for Time Machine backups is:
log show --predicate 'subsystem == "com.apple.TimeMachine"' --info | grep 'upd: (' | cut -c 1-19,140-999

This filters log entries to those for the Time Machine subsystem, and accesses them down to info level. That output is passed through grep to extract only those entries containing the string ‘upd: (‘, and then cuts out a chunk of text from the middle of each line. Note how the predicate is given inside single quotes, to ensure that the command line copes with its spaces properly.

An alternative which just captures the last couple of backups might be
log show --predicate 'subsystem == "com.apple.TimeMachine"' --style syslog --info --last 3h | cut -c 1-22,43-999

This uses the same predicate, but works on the syslog format output, and only uses log entries over the last 3 hours. The final cut gives a slightly different layout.

If you want to look in detail at a relatively short section of log, use
log show --style syslog --start '2016-09-30 06:58:10' --end '2016-09-30 06:59:00' --info

This does not use a predicate filter, so will result in many log entries, but does restrict the time window. Note that the dates and times are given in single quotes to ensure that they are properly handled.

To capture just the errors logged over a period, try something like
log show --predicate 'messageType == error' --style syslog --start '2016-09-30 06:58:10' --end '2016-09-30 06:59:00' --info | cut -c 1-22,43-999
or, to capture just those over the last minute,
log show --predicate 'messageType == error' --style syslog --info --last 1m | cut -c 1-22,43-999

Bear in mind that the logs can contain 70,000 or more entries in any given minute, so these could still be very hefty log excerpts.

Here are the two commands to create an empty text file, and then dump a short log extract to it:
touch ~/Documents/logrestart.text
(which creates the empty file, and)
log show --start '2016-09-30 06:58:10' --end '2016-09-30 06:59:50' --info > ~/Documents/logrestart.text
which then extracts the log excerpt into that text file, ready for you to browse.

Strategies

Here are some suggestions as to how you can use these commands in common situations.

To check your Time Machine backups, you can use either of the commands above,
log show --predicate 'subsystem == "com.apple.TimeMachine"' --info | grep 'upd: (' | cut -c 1-19,140-999
or
log show --predicate 'subsystem == "com.apple.TimeMachine"' --style syslog --info --last 3h | cut -c 1-22,43-999

If you’d prefer to put their output into a text file rather than the Terminal window, create the file first using
touch ~/Documents/logtmbackups.text
then pipe log’s output into that
log show --predicate 'subsystem == "com.apple.TimeMachine"' --style syslog --info --last 1d | cut -c 1-22,43-999 > ~/Documents/logtmbackups.text

To look for a startup entry,
log show --predicate 'eventMessage contains "BOOT_TIME"' --style syslog --info | cut -c 1-22,43-999

To look for a system waking up,
log show --predicate 'eventMessage contains "System Wake"' --style syslog --info | cut -c 1-22,43-999

You can then look at errors immediately before and after that date and time, e.g.
log show --predicate 'messageType == error' --style syslog --start '2016-09-30 06:57:10' --end '2016-09-30 06:59:00' --info | cut -c 1-22,43-999
and if that doesn’t tell you what went wrong, try dumping that window into a text file and browsing through it, with
touch ~/Documents/logrestart.text
log show --start '2016-09-30 06:57:10' --end '2016-09-30 06:59:00' --info > ~/Documents/logrestart.text

To look for error messages from an app, you will need to discover that app’s identifier, such as com.company.product. Then roll that into a command like
log show --predicate '(messageType == error) and (subsystem == "com.company.product")' --style syslog --info | cut -c 1-22,43-999

If you come up with some neat log commands, and solutions, please share them here. My next task is to package these into something which doesn’t require Terminal, so that I can send tools out to those whose problems I am trying to diagnose. I will make those tools available here.

2020年4月28日 星期二

修正Mac當機後不要直接重開機

Adjust Whether a Mac Restarts Automatically on System Freeze

sudo systemsetup -getrestartfreeze

You’ll either see one of two reports, indicating the status of the feature:

Restart After Freeze: On

or:

Restart After Freeze: Off

Again, the default Mac setting now is to be “On” – it is highly recommended to leave that setting enabled as is and not adjust it.

Adjusting the Automatic Mac Restart Upon Freeze Feature
If you’re advanced user and you wish to toggle the auto-restart on freeze feature, the following command syntax will do so. Adjust the ‘on’ or ‘off’ component of the command to achieve the desired effect:

Turn automatic restarting upon freeze on:

sudo systemsetup -setrestartfreeze on

Turn automatic restarting upon freeze off:

sudo systemsetup -setrestartfreeze off

Keep in mind if you turn this feature off, an unattended frozen Mac will stay frozen at whatever is on screen for however long it takes a user to come an force the computer to reboot, if not for some other power event taking place. This is one of many reasons why the average user should leave the setting turned on.

Even with the automatic restart on freeze feature left enabled, sometimes, a frozen Mac can be so stuck that it requires forcibly rebooting to get the computer to behave again.

Note this setting was actually contained in the System Preferences for a while in earlier versions of OS X, but newer versions of Mac OS X removed the option and instead simply default to having the feature on.

systemsetup Help Information
-------------------------------------
Usage: systemsetup -getdate
        Display current date.

Usage: systemsetup -setdate <mm:dd:yy>
        Set current date to <mm:dd:yy>.

Usage: systemsetup -gettime
        Display current time.

Usage: systemsetup -settime <hh:mm:ss>
        Set current time to <hh:mm:ss>.

Usage: systemsetup -gettimezone
        Display current time zone.

Usage: systemsetup -settimezone <timezone>
        Set current time zone to <timezone>. Use "-listtimezones" to list time zones.

Usage: systemsetup -listtimezones
        List time zones supported by this machine.

Usage: systemsetup -getusingnetworktime
        Display whether network time is on or off.

Usage: systemsetup -setusingnetworktime <on off>
        Set using network time to either <on> or <off>.

Usage: systemsetup -getnetworktimeserver
        Display network time server.

Usage: systemsetup -setnetworktimeserver <timeserver>
        Set network time server to <timeserver>.

Usage: systemsetup -getsleep
        Display amount of idle time until computer, display and hard disk sleep.

Usage: systemsetup -setsleep <minutes>
        Set amount of idle time until computer, display and hard disk sleep to <minutes>.
        Specify "Never" or "Off" for never.

Usage: systemsetup -getcomputersleep
        Display amount of idle time until computer sleeps.

Usage: systemsetup -setcomputersleep <minutes>
        Set amount of idle time until compputer sleeps to <minutes>.
        Specify "Never" or "Off" for never.

Usage: systemsetup -getdisplaysleep
        Display amount of idle time until display sleeps.

Usage: systemsetup -setdisplaysleep <minutes>
        Set amount of idle time until display sleeps to <minutes>.
        Specify "Never" or "Off" for never.

Usage: systemsetup -getharddisksleep
        Display amount of idle time until hard disk sleeps.

Usage: systemsetup -setharddisksleep <minutes>
        Set amount of idle time until hard disk sleeps to <minutes>.
        Specify "Never" or "Off" for never.

Usage: systemsetup -getwakeonmodem
        Display whether wake on modem is on or off.

Usage: systemsetup -setwakeonmodem <on off>
        Set wake on modem to either <on> or <off>.

Usage: systemsetup -getwakeonnetworkaccess
        Display whether wake on network access is on or off.

Usage: systemsetup -setwakeonnetworkaccess <on off>
        Set wake on network access to either <on> or <off>.

Usage: systemsetup -getrestartpowerfailure
        Display whether restart on power failure is on or off.

Usage: systemsetup -setrestartpowerfailure <on off>
        Set restart on power failure to either <on> or <off>.

Usage: systemsetup -getrestartfreeze
        Display whether restart on freeze is on or off.

Usage: systemsetup -setrestartfreeze <on off>
        Set restart on freeze to either <on> or <off>.

Usage: systemsetup -getallowpowerbuttontosleepcomputer
        Display whether the power button is able to sleep the computer.

Usage: systemsetup -setallowpowerbuttontosleepcomputer <on off>
        Enable or disable whether the power button can sleep the computer.

Usage: systemsetup -getremotelogin
        Display whether remote login is on or off.

Usage: systemsetup -setremotelogin <on off>
        Set remote login to either <on> or <off>. Use "systemsetup -f -setremotelogin off" to suppress prompting when turning remote login off. Requires Full Disk Access privileges.

Usage: systemsetup -getremoteappleevents
        Display whether remote apple events are on or off.

Usage: systemsetup -setremoteappleevents <on off>
        Set remote apple events to either <on> or <off>. Requires Full Disk Access privileges.

Usage: systemsetup -getcomputername
        Display computer name.

Usage: systemsetup -setcomputername <computername>
        Set computer name to <computername>.

Usage: systemsetup -getlocalsubnetname
        Display local subnet name.

Usage: systemsetup -setlocalsubnetname <name>
        Set local subnet name to <name>.

Usage: systemsetup -getstartupdisk
        Display current startup disk.

Usage: systemsetup -setstartupdisk <disk>
        Set current startup disk to <disk>.

Usage: systemsetup -liststartupdisks
        List startup disks on this machine.

Usage: systemsetup -getwaitforstartupafterpowerfailure
        Get the number of seconds after which the computer will start up after a power failure.

Usage: systemsetup -setwaitforstartupafterpowerfailure <seconds>
        Set the number of seconds after which the computer will start up after a power failure. The <seconds> value must be a multiple of 30 seconds.

Usage: systemsetup -getdisablekeyboardwhenenclosurelockisengaged
        Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged.

Usage: systemsetup -setdisablekeyboardwhenenclosurelockisengaged <yes no>
        Set whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged.

Usage: systemsetup -version
        Display version of systemsetup tool.

Usage: systemsetup -help
        Display help.

Usage: systemsetup -printCommands
        Display commands.

Mac 的启动组合键

Mac 的啟動組合鍵

了解可通過在啟動時按住一個或多個按鍵來訪問的Mac 功能和工具。 
要使用這些組合鍵中的任何一個,請在按下電源按鈕以開啟Mac  後或在Mac開始重新啟動後,立即按住相應按鍵。請一直按住,直至電腦出現對應的行為。


你可以在Mac開機時,按住如下的組合鍵,去進入其功能設定:
  1. 按住〈C〉,從CD 或DVD 光碟機啟動,如:Mac OS X 安裝光碟。
  2. 按住〈D〉,如果插入安裝DVD 1,則啟動為Apple Hardware Test (AHT)。
  3. 按住〈Option〉+〈Command〉+〈P〉+〈R〉,直到聽到兩聲BB聲-->Reset NVRAM。
  4. 按住〈Option〉 ,開機後進入Startup Manager,你可以在這些選項中,選擇從一個你想的Mac OS X 項目去開機。注意:按住〈N〉 鍵,可顯示出第一個可啟動的網絡選項。你也可以選擇從UEFI磁碟作開機,去做一些內部設定。
  5. 按住〈Eject〉or〈F12〉 ,或者按住鼠標鍵(/觸控板),退出所有可移動的媒體,如光碟,USB。
  6. 按住〈N〉,試著從相容的網絡伺服器(NetBoot)去作開機的動作。
  7. 按住〈T〉,開機後成為FireWire 目標(Taget)的磁碟模式。
  8. 按住〈Shift〉,開機後成為安全模式,並且暫時關閉登錄選項。
  9. 按住〈Command〉+〈V〉,開機後成為Verbose 模式。
  10. 按住〈Command〉+〈S〉,開機後成為單一使用者模式。
  11. 按住〈Option〉+〈N〉,使用系統預設執的開機鏡像,從NetBoot伺服器開機。
若要從「macOS 復原」啟動,請將 Mac 開機,然後立即在鍵盤上按住下列其中一套組合鍵。在您看到 Apple 標誌、旋轉的地球或其他啟動畫面時,放開按鍵。

Command(⌘)-R

重新安裝 Mac 上所安裝的最新版 macOS(建議做法)。

Option-⌘-R

升級到與 Mac 相容的最新版 macOS。

Shift-Option-⌘-R

重新安裝 Mac 隨附的 macOS,或仍提供使用的最接近版本。

Mac 開機啟動 詳細 message

我們知道任何作業系統都會有發生故障的時候,macOS也不例外,而通過作業系統產生的日誌,有助於判斷故障產生的原因並解決故障。
通過蘋果官方網站的幫助信息^,在Mac啟動時按住Command + V可以進入詳細模式(經常玩黑蘋果的同學會稱之為囉嗦模式),按住Command + S可以進入單用戶模式,按住Shift可以進入安全模式。
除了在Mac啟動時按住鍵盤的快捷鍵,你還可以通過終端的「nvram」命令來為Mac設置啟動參數,這樣就不需要每次在Mac啟動時按住這些快捷鍵了。
通過終端為Mac設置啟動參數
1、打開Finder,點選菜單欄的「前往「,然後選擇」應用程式「,找到」實用工具「文件夾並打開,找到並打開」終端「應用程式;



2、在終端窗口中,輸入以下命令並按回車執行:
sudo nvram boot-args="-v"
3、執行後會出現Password提示,這時候輸入你當前帳戶的密碼,Unix系統在輸入密碼時不會有任何提示,輸入完成後按回車繼續;
4、此時啟動參數已經被添加到了nvram里,當啟動macOS時系統會以-v參數啟動,進入詳細模式;
5、如果需要檢查參數是否已經添加了,執行以下命令:
nvram -p | grep boot-args



看到如圖紅線處所示,boot-args -v,則表示添加參數成功。
這個方法適用於運行所有基於Intel處理器的Mac和部分PowerPC架構的Mac
最終效果



通過這個方法除了可以添加詳細模式外還可以添加其他模式的參數:
sudo nvram boot-args="-x"
讓系統在啟動時進入安全模式
sudo nvram boot-args="-s"
讓系統在啟動時進入單用戶模式
sudo nvram boot-args="-x -v"
讓系統以詳細模式啟動安全模式
如果希望清除啟動參數,執行以下命令即可:
sudo nvram boot-args=""
完!
能力有限,如有錯誤還請指出,謝謝!
^:蘋果官方幫助信息連結https://support.apple.com/zh-cn/HT201255

啟動Mac系統時,您可以選擇在啟動時提供鍵盤命令以將系統引導至備用環境。例如,常用選項是按住Shift鍵以啟動到安全模式,但您也可以將Command-V保持為詳細模式(加載時項目的文本輸出)或Command-S for Single User模式,將您作為“root”用戶轉到命令行,以便執行故障排除任務。

除了啟動時的鍵盤命令,您還可以使用“nvram”terminal命令設置許多不同的啟動選項,這在對Mac進行故障排除時可能很有用。Apple的機器有許多可以使用的隱藏啟動選項,但請記住,其中大多數都是用於故障排除目的,並且只對程序員有用。

sudo nvram boot-args =“iog = 0x0”
這反轉了蘋果筆記本電腦系統的“翻蓋”模式,當你關閉顯示器但將系統連接到外部顯示器和鍵盤時,系統將保持清醒狀態。運行此命令後,連接外部顯示器時,內部顯示器將被禁用,這在某些情況下是有益的,例如您鏡像桌面但希望以比筆記本電腦可以運行的更高分辨率運行外部顯示器的情況。

sudo nvram boot-args =“debug = 0x144”
這是內核調試功能的組合,它將向您顯示有關內核進程的額外信息,如果系統遇到內核恐慌,這可能非常有用。另一種選擇是使用debug = 0x14e,它將顯示更多的日誌記錄選項。這樣做的主要用途是它能夠在屏幕上顯示滾動文本的舊式內核恐慌,說明系統恐慌的原因,而不是顯示灰色背景和僅重新啟動系統的消息。替代調試選項如下,但這些可能僅對內核程序員有用:

0x01 – 在引導時停止並等待調試器附加
0x02 – 將內核調試輸出發送到控制台
0x04 – 在不可屏蔽的中斷上進入調試器
0x08 – 將內核調試信息發送到串行端口
0x10 – 使ddb成為默認調試器
0x20 – 將診斷信息輸出到系統日誌
0x40 – 允許調試器進行ARP和路由
0x80 – 在較新的系統上支持舊版本的gdb
0x100 – 禁用圖形應急對話框屏幕

sudo nvram boot-args =“arch = x86_64”
在Snow Leopard系統上,即使64位內核可用,系統默認也會引導至32位內核。此命令將更改此值,以便系統始終引導至64位內核。要將系統更改為始終引導至32位內核,請將命令的“x86_64”部分替換為“i386”。在某些情況下,第三方內核擴展可能只是32位或64位,這需要引導到相應的內核類型才能加載。

sudo nvram boot-args =“maxmem = 32”
將可尋址內存限制為指定的數量,在本例中為32GB。這是另一個可能只對程序員有用的東西。如果沒有它,系統會將內存限制設置為硬件可以解決的最大值或安裝量。

sudo nvram boot-args =“cpus = 1”
將系統中活動處理器的數量限制為設置級別。Apple的開發人員工具可以選擇啟用或禁用系統上的某些CPU,但您可以通過運行此命令並指定要使用的CPU核心數來手動執行此操作。在某些情況下,例如筆記本電腦系統,這可能有助於保持功率,但除非您正在測試和編程,否則可能對其他許多功能沒用。
使用這些選項,您可以通過一次運行上述命令來單獨設置它們,也可以根據需要組合它們。例如,要將系統設置為啟動到安全模式並在啟動期間詳細顯示項目,您可以運行上面列出的兩個命令來執行此操作,也可以將它們組合到以下命令中:
sudo nvram boot-args =“ – x -v”

要禁用這些功能並讓系統正常啟動而不需要任何額外選項,您可以通過重置它或者更具體地說,通過在終端中運行以下任一命令來從nvram中刪除它們(這些將重置引導參數而不是重置所有nvram變量):

如果希望清除啟動參數,執行以下命令即可:
sudo nvram boot-args=""

Mac 重置系統管理控制器(SMC)

作者:知乎用户
链接:https://www.zhihu.com/question/20401972/answer/48146602
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

SHIFT+CTRL+OPTION+POWER十秒鐘:重置系統管理控制器(SMC)
  • 關閉電腦。
  • 將MagSafe 電源適配器連接到電源和Mac(如果尚未連接的話)。
  • 在內建鍵盤上,同時按下(左側)Shift-Control-Option 鍵和電源按鈕。
  • 同時鬆開所有鍵和電源按鈕。
  • 按電源按鈕打開電腦。
:重置SMC時,MagSafe電源適配器上的LED指示燈可能會更改狀態或暫時關閉。
在風扇、電源指示燈、系統性能、視頻出現某些異常時候,可以通過上述方法進行重置來解決。具體的症狀判斷和說明可以參考" 基於Intel的Mac:重置系統管理控制器(SMC) "。
OPTION+CMD+R+P+POWER:重置NVRAM 或PRAM
Mac 會將某些設置儲存在特殊內存區域中,而且即使關機這些設置也不會丟失(除非存在電池問題)。在基於Intel 的Mac 上,存儲位置是稱為NVRAM 的內存;而在基於PowerPC 的Mac 上,存儲位置則是稱為PRAM 的內存。操作步驟為:
  • 關閉電腦。
  • 在鍵盤上找到以下按鍵:Command、Option、P 和R。您需要在步驟4 中同時按下這些鍵。
  • 啟動電腦。
  • 按住Command-Option-PR 鍵。必須在出現灰屏前按下此組合鍵。
  • 按住上述鍵,直到電腦重新啟動,您會再次聽到啟動聲。
  • 鬆開這些鍵。

2020年4月13日 星期一

Ubuntu 18.04 setting null_blk, test fio


先確認/lib/modules/4.15.0-96-generic/kernel/drivers/block/ 是否有null_blk.ko 
若沒有,請先自行build出此driver. 或是使用apt-get install 安裝

** apt-get install extra driver

# uname -a
Linux sam 4.15.0-96-generic #97-Ubuntu SMP Wed Apr 1 03:25:46 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

# apt-cache search linux-modules-extra-4.15.0.96
linux-modules-extra-4.15.0-96-generic - Linux kernel extra modules for version 4.15.0 on 64 bit x86 SMP

apt-get install linux-modules-extra-4.15.0-96-generic


** 自動掛載 null_blk driver

vi /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
null_blk

** 設定 null_blk 參數,只能以 module 形式,在開機讀取設定.
# vi /etc/modprobe.d/null_blk.conf 

寫入下行資料, nr_devices=1 建立 nullb0, queue_mode=0 初步測試沒queue能測出較高IOPS.
options null_blk nr_devices=1 queue_mode=0

reboot

如何確認queue_mode=0, queue 被關閉,請確認 mq 不存在,即表示queue_mode=0 設定成功.

#  ls /sys/class/block/nullb0
alignment_offset  bdi  capability  dev  discard_alignment  ext_range  hidden  holders  inflight  integrity  mq  power  queue  range  removable  ro  size  slaves  stat  subsystem  trace  uevent

# ls /sys/class/block/nullb0

alignment_offset  bdi  capability  dev  discard_alignment  ext_range  hidden  holders  inflight  integrity  power  queue  range  removable  ro  size  slaves  stat  subsystem  trace  uevent


Null block device driver
https://www.kernel.org/doc/Documentation/block/null_blk.txt

Null block device driver
================================================================================

I. Overview

The null block device (/dev/nullb*) is used for benchmarking the various
block-layer implementations. It emulates a block device of X gigabytes in size.
The following instances are possible:

  Single-queue block-layer
    - Request-based.
    - Single submission queue per device.
    - Implements IO scheduling algorithms (CFQ, Deadline, noop).
  Multi-queue block-layer
    - Request-based.
    - Configurable submission queues per device.
  No block-layer (Known as bio-based)
    - Bio-based. IO requests are submitted directly to the device driver.
    - Directly accepts bio data structure and returns them.

All of them have a completion queue for each core in the system.

II. Module parameters applicable for all instances:

queue_mode=[0-2]: Default: 2-Multi-queue
  Selects which block-layer the module should instantiate with.

  0: Bio-based.
  1: Single-queue.
  2: Multi-queue.

home_node=[0--nr_nodes]: Default: NUMA_NO_NODE
  Selects what CPU node the data structures are allocated from.

gb=[Size in GB]: Default: 250GB
  The size of the device reported to the system.

bs=[Block size (in bytes)]: Default: 512 bytes
  The block size reported to the system.

nr_devices=[Number of devices]: Default: 1
  Number of block devices instantiated. They are instantiated as /dev/nullb0,
  etc.

irqmode=[0-2]: Default: 1-Soft-irq
  The completion mode used for completing IOs to the block-layer.

  0: None.
  1: Soft-irq. Uses IPI to complete IOs across CPU nodes. Simulates the overhead
     when IOs are issued from another CPU node than the home the device is
     connected to.
  2: Timer: Waits a specific period (completion_nsec) for each IO before
     completion.

completion_nsec=[ns]: Default: 10,000ns
  Combined with irqmode=2 (timer). The time each completion event must wait.

submit_queues=[1..nr_cpus]:
  The number of submission queues attached to the device driver. If unset, it
  defaults to 1. For multi-queue, it is ignored when use_per_node_hctx module
  parameter is 1.

hw_queue_depth=[0..qdepth]: Default: 64
  The hardware queue depth of the device.

III: Multi-queue specific parameters

use_per_node_hctx=[0/1]: Default: 0
  0: The number of submit queues are set to the value of the submit_queues
     parameter.
  1: The multi-queue block layer is instantiated with a hardware dispatch
     queue for each CPU node in the system.

no_sched=[0/1]: Default: 0
  0: nullb* use default blk-mq io scheduler.
  1: nullb* doesn't use io scheduler.

blocking=[0/1]: Default: 0
  0: Register as a non-blocking blk-mq driver device.
  1: Register as a blocking blk-mq driver device, null_blk will set
     the BLK_MQ_F_BLOCKING flag, indicating that it sometimes/always
     needs to block in its ->queue_rq() function.

shared_tags=[0/1]: Default: 0
  0: Tag set is not shared.
  1: Tag set shared between devices for blk-mq. Only makes sense with
     nr_devices > 1, otherwise there's no tag set to share.

zoned=[0/1]: Default: 0
  0: Block device is exposed as a random-access block device.
  1: Block device is exposed as a host-managed zoned block device. Requires
     CONFIG_BLK_DEV_ZONED.

zone_size=[MB]: Default: 256
  Per zone size when exposed as a zoned block device. Must be a power of two.

zone_nr_conv=[nr_conv]: Default: 0
  The number of conventional zones to create when block device is zoned.  If
  zone_nr_conv >= nr_zones, it will be reduced to nr_zones - 1.