# Dublin CSE 衝刺計畫 (linux)
https://www.amazon.jobs/en/jobs/1395426/cloud-support-engineer-mandarin-speaker
可搭配:https://hackmd.io/K1ScOp5iRjOd73AP9_cCqw
* Linux 之鬼的書:https://tldp.org/LDP/sag/html/index.html
* A cloud guru Red Hat Certified System Administrator 也可[](https://)
* 現在 RHEL 的版本是 8 以上,所以套件管理會用 DNF 來管理。
11/7 複習全部,並且把會考的重點記錄一下 ( trouble shooting 工具,開機流程,log 檔案紀錄,process, nice 值, top 與 ps , tuned profile, grep, networking, SElinux, )
11/8 早上把網路複習一遍還有常見指令。
network , SElinux
## Linux 來源
為了方便管理硬體而有的作業系統。
硬體 -> 核心 -> 系統呼叫 -> 應用程式
系統呼叫 -> 為核心提供一列函式庫,programmer 只要參考呼叫系統就可以去設計相關應用程式
作業系統包含:核心 + 系統呼叫
發展史很多,可從 1991 年芬蘭大學學生 Linus Torvalds 開始
1994 年世上最知名的商業公司 Red Hat 才誕生
## Boot Process
1. Managing the Boot Process on RHEL 8
* GRUB Bootloader Experience
Understand how the `GRUB bootloader` works and how to interact with it.
* Systemd experience
Experience with `systemd`, and how to poweroff or reboot the system using `systemctl`
* X86 hardware (BIOS) experience
Understand how to configure boot devices in a real or emulated X86 BIOS, and are familiar with the `POST` process.

Restart the system, and remount it
`mount -o rw,remount /sysroot` then `chroot /sysroot` and `passwd root`

詳細開機流程。
1. BIOS/POST (Basic Input/Output System)
Server/VM is powered on, BIOS loads and executes POST(Power on self-test)
2. Master Boot Record (MBR)
BIOS loads the contents of the MBR
3. GRUB
The GRUB bootloader loads the kernel, the GRUB bootloader provide you with the a menu to select different boot options, and you can edit the boot options as well. Once the times out, hit Crtl + X to move on , and the GRUB Bootloader to the kernel.
4. Kernel
The kernel loads drivers and starts systemd
5. systemd
Reads /etc/systemd configuration file and `default.target` file.
6. default.target
System brought to state as defined by `default.target`
* Type `systemctl get-default` that you would see the graphical.target it was the GUI interface.
You could type `grep -i storage /etc/systemd/journald.conf
`

## Troubleshooting
Troubleshoot using the EC2 Serial Console
Troubleshoot Linux using GRUB. From the GRUB menu, you can select which kernel to boot into, or modify menu entries to change how the kernel will boot. This can be useful when troubleshooting a failing instance.
Troubleshoot Linux using Magic SysRq. For example, you can trigger a Magic SysRq command to generate a crash dump or to kill processes.
Troubleshoot Windows. You can interrupt the boot process and boot Windows in safe mode by following OS-specific procedures, for example, Emergency Management Service (EMS) and Special Admin Console (SAC).
## Run Level
A run level is a state of `init` and the whole system that defines what system services are operating. Run levels are identified by numbers. Some system administrators use run levels to define which subsystems are working, e.g., whether X is running, whether the network is operational, and so on. Others have all subsystems always running or start and stop them individually, without changing run levels, since run levels are too coarse for controlling their systems. You need to decide for yourself, but it might be easiest to follow the way your Linux distribution does things.
The following table defines how most Linux Distributions define the different run levels. However, run-levels 2 through 5 can be modified to suit your own tastes.
0 Halt the system.
1 Single-user mode (for special administration).
2 Local Multiuser with Networking but without network service (like NFS)
3 Full Multiuser with Networking
4 Not Used
5 Full Multiuser with Networking and X Windows(GUI)
6 Reboot.
## Run Level
執行級別(Runlevel)指的是Unix或者Linux等類Unix作業系統下不同的執行模式。執行級別通常分為7等,分別是從0到6,但如果必要的話也可以更多。
例如在大多數Linux作業系統下一共有如下7個典型的執行級別:
0 停機,關機
1 單使用者,無網路連接,不執行守護行程,不允許非超級使用者登入
2 多使用者,無網路連接,不執行守護行程
3 多使用者,正常啟動系統
4 使用者自訂
5 多使用者,帶圖形介面
6 重新啟動
To see current run level
`runlevel`
To view current default target
`systemctl get-default`
To set a default target TARGET=runlevel0-6
`systemctl set-default TARGET.target`

https://www.freecodecamp.org/news/the-linux-booting-process-6-steps-described-in-detail/
## Logging. What is journal?
Linux 登錄檔的初探 -
Linux Distribution 大多檔案放在 /var/log 下
會依照看的東西而有所不同如:
/var/log/dmesg: 紀錄系統在開機的時候核心偵測過程所產生的各項資訊。
不過在 CentOS7 之後已經改由 systemd 管理系統,systemd-journald 這個服務來管理登錄檔日誌服務,不過還是保留舊有的 **rsyslog** 服務。
記錄檔案本身負荷比較高,因此還需要一個輪替登錄檔的功能,那就是 logrotate.
- systemd-journald.service: 最主要的訊息接受者,由 systemd 提供的
- rsyslog.service: 主要登錄系統與網路等服務的訊息
- logrotate:主要在進行登錄檔輪替
### Daemon 守護行程
在一個多工的電腦作業系統中,守護行程(英語:daemon,/ˈdiːmən/或/ˈdeɪmən/)是一種在後台執行的電腦程式。此類程式會被以行程的形式初始化。守護行程程式的名稱通常以字母「d」結尾:例如,syslogd就是指管理系統紀錄檔的守護行程。
通常,守護行程沒有任何存在的父行程(即PPID=1),且在UNIX系統行程層級中直接位於init之下。守護行程程式通常通過如下方法使自己成為守護行程:對一個子行程執行fork,然後使其父行程立即終止,使得這個子行程能在init下執行。這種方法通常被稱為「脫殼」。
系統通常在啟動時一同啟動守護行程。守護行程為對網路請求,硬體活動等進行回應,或其他通過某些任務對其他應用程式的請求進行回應提供支援。守護行程也能夠對硬體進行組態(如在某些Linux系統上的devfsd),執行計劃任務(例如cron),以及執行其他任務。
登錄檔伺服器設定 (現在有 AD 可以不用這樣幹)
Server 端設定只需要讓 rsyslogd 啟動 port 514 即可。
**現在系統都是由 systemd 來管理,systemd 提供了 systemd-journald 來協助記載登錄檔,因此在開機過程中的所有資訊(包括啟動服務或啟動失敗的) 都可以直接紀錄到 systemd-journald 當中**。
不過由于他是用記憶體的登錄檔紀錄方式,因此重新開機過後,開機前的登陸檔資訊當然就不會被記載。因此還是建議用 **rsyslogd** 來協助分類
(EC2 -> Get System log) With **in-memory** journaling, `systemd` creates its journal files under the **/run/log/journal** directory.
The directory is created if it doesn’t exist. With **persistent storage**, the journal is created under **/var/log/journal** directory; again, the directory is created by systemd if needed. If this directory is deleted for some reason, systemd-journald will not re-create it automatically; rather, it will write the logs under **/run/log/journal** in a non-persistent way. It will re-create the directory when the daemon is restarted.
/var/log/journal is persistent
/run/log/journal is non-persistent (in-memory)

* chrgrp 是啥
* 2775 特殊權限問題


[Chronyd 是什麼?](https://dywang.csie.cyut.edu.tw/dywang/rhel7/node70.html)
* How to use grep and pipping
Linux 的 grep 是一個很好用的指令,可以從串流資料或檔案中,使用關鍵字或正規表示法(regular expression)篩選出想要尋找的資料,並且顯示出來,以下是 grep 的用法教學以及實際範例。
Grep means that (global search RE and print it)
you can you grep directly or | grep!
ETC is a folder which contain all your system configuration files in it. Then why the etc name?
If we want to send our our journal to new log
1. mkdir /var/log/journal
2. journalctl --flush
## CPU High or Memory High
使用 `ps` or `top` 找出最耗費 CPU 與記憶體資源的程式
`top` is mostly used interactively (try reading man page or pressing "h" while top is running) and `ps` is designed for non-interactive use (scripts, extracting some information with shell pipelines etc.)
* 查閱系統負載(loading)與行程(process)的狀況最常用的就是 ps 與 top 這兩個指令,以下我們示範如何利用這兩個指令撰寫簡單的指令稿,自動找出系統上最耗費資源的程式。
### PS 指令
這行指令可利用 ps 指令列出行程的一些基本資訊,按照每個行程所使用的記憶體排序後,列出排名最前面的幾個行程,也就是列出系統上最耗費記憶體的程式:
```bash
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head
```
> 這裡的 -e 參數是代表輸出所有行程的資訊,而 -o 參數則是用來指定輸出欄位用的,後面接著所有想要輸出的欄位名稱,這裡我們讓 ps 輸出以下幾個欄位:
* pid:行程 ID(process ID)。
* ppid:父行程 ID(parent process ID)。
* cmd:程式名稱。
* %mem:記憶體使用量(百分比)。
* %cpu:CPU 使用量(百分比

### TOP 指令
top 指令是一個互動式(interactive)的工具,可以顯示即時的系統負載狀態,而它也可以用於指令稿中,輸出各種系統資訊。
這行指令可將系統行程以記憶體的使用賴排序後,以 batch 模式輸出報表,並且只保留前 10 個最耗費記憶體的行程:
```bash
top -b -o +%MEM | head -n 17
```
其中 -b 參數是 batch 模式的意思,而 -o 參數則是設定以記憶體用量來排序行程,最後面的 head -n 17 則是篩選 top 輸出的文字內容,只保留前 17 行,剩餘的內容則捨棄。輸出會類似這樣:

通常如果發現異常的程式佔用了太多的 CPU 或記憶體,最好的處理方式就是把這些程式正常關閉,如果程式當掉無法關閉的話,就可以使用 kill 或 killall 這類的指令,中止不正常程式的執行,由於上面的報表中都有每個程式的 PID,所以使用 PID 來中止特定的程式是最直接的方式。
### CPU usage
`%Cpu(s): 24.8 us, 0.5 sy, 0.0 ni, 73.6 id, 0.4 wa, 0.0 hi, 0.2 si, 0.0 st`
* **24.8 us** - This tells us that the processor is spending 24.8% of its time running **user space processes**. A user space program is any process that doesn't belong to the kernel.
* **0.5 sy** - This is the amount of time that the CPU spent running the **kernel**. All the processes and **system resources** are handled by the Linux kernel.
* **73.6 id** -Skipping over a few of the other statistics, just for a moment, the id statistic tell us that the processor was **idle** just over 73% of the time during the last sampling period.
* **0.0 ni** - The priority level a user space process can be tweaked by adjusting its niceness. The `ni` stat shows **how much time the CPU spent running user space processes that have been niced**. On a system where no processes have been niced then the number will be 0.
* **0.4 wa** - Input and output operations, like reading or writing to a disk, are slow compared to the speed of a CPU. **There are times when the processor has initiated a read or write operation and then it has to wait for the result, but has nothing else to do**. In other words it is idle while waiting for an I/O operation to complete. **The time the CPU spends in this state is shown by the `wa` statistic.**
* **0.0 hi & 0.2 si** - These two statistics show how much time the processor has spent servicing **interrupts**. `hi` is for **hardware** interrupts, and `si` is for **software** interrupts.
* **0.0 st** - This last number only applies to virtual machines. When Linux is running as a virtual machine on a hypervisor, the `st` (short for stolen) statistic shows **how long the virtual CPU has spent waiting for the hypervisor to service another virtual CPU running on a different virtual machine.**
### Columns

* **PID**: Process ID.
* **USER**: The owner of the process.
* **PR**: Process priority.
* **NI**: The nice value of the process.
* **VIRT**: Amount of virtual memory used by the process.
* **RES**: Amount of resident memory used by the process.
* **SHR**: Amount of shared memory used by the process.
* **S**: Status of the process. (See the list below for the values this field can take).
* **%CPU**: The share of CPU time used by the process since the last update.
* **%MEM**: The share of physical memory used.
* **TIME**+: Total CPU time used by the task in hundredths of a second.
* **COMMAND**: The command name or command line (name + options).
### State
* **D** uninterruptible sleep (waiting for an **I/O operation** to complete)
* **R** running or runnable (on run queue)
* **I** idle
* **S** interruptible sleep (waiting for an **event** to complete)
* **T** stopped by job control signal
* **t** stopped by debugger during the tracing
* **X** dead (should never be seen)
* **Z** defunct ("zombie") process, terminated but not reaped by
### Sorting the process list (超屌)
* Press "**M**" to sort by memory usage
* Press "**P**" to sort by CPU usage
* Press "**N**" to sort by process ID
* Press "**T**" to sort by the running time
### Trouble shooting
https://scoutapm.com/blog/understanding-linuxs-cpu-stats
Standard syntax: `ps -ef`

`ps aux | greep httpd` is similar to `pgrep httpd - l`
幾個常用參數說明:
列出所有正在執行中的程式: `aux`
只找符合特定關鍵字的內容: `| grep string`
### ps -ef 與 ps aux 的差異
欄位顯示的不同,ps aux 細節比較多
https://www.itread01.com/content/1550321778.html
### Individual Process

Linux system is the collection of the processes, and process management is a crtical skill for system administrator.
* Create a stress process:
Stress 是 linux的一個壓力測試工具,可依照需求去建置:
https://www.gushiciku.cn/pl/g6qa/zh-tw
## nice 值
在 Linux 中每個執行中的程式都會有一個 niceness 值,系統的 scheduler 在對每個行程在排程時,就會參考這個數值來決定執行的先後順序,niceness 可用的數值從 `-20(最高優先權)到 19(最低優先權`,數值越小代表執行優先權越高。這裡介紹如何使用 nice 指令指定程式執行時的 niceness 值。
niceness 與排程優先權(scheduling priority)是不一樣的,排程優先權是真正決定程式執行的先後順序,而 niceness 值只是提供給 scheduler 參考用,scheduler 甚至可以忽略這個值。
* Restart the application
`systemctl restart service`
* renice priority
Press "**r**" -> `renice` -20~20, priority high to low
renice -n `your-niceness process number` and PID
* kill process
Press "**k**" -> `kill` , you could use kill -9 to do it.
* Use `chrt` command to manipulate real-time process, what types of scheduling queue are available what the value you could set for those are.
*

* `pgrep` and `pkill` command
You can use `pgrep` to do more quicker command
### Tuning Profile
*使用場景可能會被問用來降低 opex 的費用。

The Tuned service is an intelligent application that uses system monitoring to optimize system performance for specific types of workloads.
The tuned profile locations : /etc/tuned/tuned-main.conf

Type `tuned-adm list profiles`
- powersave is to optimize power consumption
- if we want to open the specific optimize profile
type `tuned-adm profile <profile-name>` , and then `tuned-adm active`。
You can merge profile just enter two profile together.
**You could use dynamic tuned on tuned-main.conf**
just set dynamic_tuning = 1
type `grep dynamic_tuning /etc/tuned/tuned-main.conf`
use vi to set 1
## Lab time
### If the probelem always happen when running the app
* Update the package
`yum update package`
#### OR
* Downgrade the package
`yum downgrade package`
### If not resolved the problematic application
1. Remove package
`yum remove package`
2. Install package
`yum install package`
### If still not resolved the probelem, Check configure file for that application
If in need, make a copy of the config file then delete it then reinstall the package.
## yum vs rpm
目前主流 Linux distribution 使用的軟體管理機制,大概是底下兩種:
distribution | 軟體管理機制 | 使用指令 | 線上升級指令| |
--------------|:-----:|-----:| ----:|------------------------
Red Hat/Fedora/ CentOS | RPM | rpm, rpmbuild | YUM (yum)|
Debian/Ubuntu | DPKG | dpkg | APT(apt-get) |
RPM - RedHat Package Manager
先將你安裝的軟體編譯過,所以現在很少使用 rpm 指令去看相關資訊。
CentOs 使用的數位簽章系統為 GNU 計畫的 GnuPG (GNU privacy Guard, GPG)
若要找到這把金鑰,可以下 `rpm -qa | grep pubkey`

### RPM v.s YUM

## Kernel log
`dmesg`
## Zombie Process
### What is a zombie process?
殭屍進程:一個進程使用fork創建子進程,如果子進程退出,而父進程並沒有調用wait或waitpid獲取子進程的狀態信息,那麼子進程的進程描述符仍然保存在系統中。這種進程稱之為僵死進程。
為何會有殭屍進程?
當你在啟動一個程序的時候,會有一個父進程跟很多的子進程一起出現,這些進程會消耗 kernel 給的內存和 cpu 資源。
這些子進程完成執行後會發送一個 Exit 信號然後死掉。這個 Exit 信號需要被父進程所讀取。父進程需要隨後調用 wait 命令來讀取子進程的退出狀態,並將子進程從進程表中移除。
若父進程正確第讀取了子進程的 Exit 信號,則子進程會從進程表中刪掉。
但若父進程未能讀取到子進程的 Exit 信號,則這個子進程雖然完成執行處於死亡的狀態,但也不會從進程表中刪掉。
### Solutions
`kill -s SIGCHLD PARENT_PID`
### If it doesn't work
`Kill PARENT_PID`
When a process loses its parent, `init` becomes its new parent. `init` periodically executes the `wait `system call to reap any zombies with `init` as parent.
## Orphan Process
### What is an orphan process?
孤兒進程:一個父進程退出,而它的一個或多個子進程還在運行,那麼那些子進程將成為孤兒進程。孤兒進程將被init進程(進程號為1)所收養,並由init進程對它們完成狀態收集工作。
在類UNIX系統中,殭屍進程是指完成執行(通過exit系統調用,或運行時發生致命錯誤或收到終止信號所致),但在作業系統的進程表中仍然存在其進程控制塊,處於"終止狀態"的進程。這發生於子進程需要保留表項以允許其父進程讀取子進程的退出狀態:一旦退出態通過wait系統調用讀取,殭屍進程條目就從進程表中刪除,稱之為"回收"(reaped)。正常情況下,進程直接被其父進程wait並由系統回收。進程長時間保持殭屍狀態一般是錯誤的並導致資源泄漏。
英文術語zombie process源自喪屍——不死之人,隱喻子進程已死但仍然沒有被回收。與正常進程不同,kill命令對殭屍進程無效。孤兒進程不同於殭屍進程,其父進程已經死掉,但孤兒進程仍能正常執行,但並不會變為殭屍進程,因為被init(進程ID號為1)收養並wait其退出。
### Solutions
* **Extermination (終止機制)** is the most commonly used technique; in this case the orphan is `kill`ed.
* **Reincarnation (再生機制)** is a technique in which machines periodically try to **locate the parents** of any remote computations; at which point orphaned processes are `kill`ed.
* **Expiration (逾時機制)** is a technique where each process is allotted a **certain amount of time** to finish before being `kill`ed. If need be a process may "ask" for more time to finish before the allotted time expires.
## Differences between /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin(目錄樹系統介紹)
都會按照檔案系統的階層標準 (Filesystem Hierarchy Stadard, FHS)
/bin -> The directory contains user executable files.
很多目錄名稱,可參考鳥哥 2-14 頁數
* /bin
For binaries usable before the /usr partition is mounted. This is used for trivial binaries used in the very early boot stage or ones that you need to have available in booting **single-user** mode. Think of binaries like **cat, ls, etc**.
* /sbin
Same, but for binaries with **superuser** (root) privileges required.
* /usr
是 unix software resource 的縮寫,系統相關的所有軟體和服務均放置在這。
These are shareable, read-only files, including executable binaries and libraries, man files, and other types of documentation
* /usr/bin
Same as first, but for general system-wide binaries.
* /usr/sbin
Same as above, but for binaries with **superuser** (root) privileges required.
## Service
### What is a service?
Service is an application or set of applications that are running in the background. Services are also known as daemons ending in d.
### How can I check the logs of a service?
### Where are they located?
Logs can be found in **/lib/systemd/system**
### How can I check the status of a service?
`systemctl status`
OR
`systemctl list-unit-files --type service –all`
OR
`systemctl | grep running`
### How can I start a service?
`systemctl start`
## Hard link vs Softlink
https://claire-chang.com/2019/10/03/hard-link%E8%88%87symbolic-link%E7%9A%84%E6%AF%94%E8%BC%83/
inode (index node)是指在許多「類Unix檔案系統」中的一種資料結構,用於描述檔案系統物件(包括檔案、目錄、裝置檔案、socket、管道等)。每個inode儲存了檔案系統物件資料的屬性和磁碟塊位置[1]。檔案系統物件屬性包含了各種元資料(如:最後修改時間[2]) ,也包含使用者群組(owner )和權限資料[3]。


* HardLink:
1. 以相同的i-node指向相同的檔案。
2. 主要用於備份。
3. 只能在同一個磁區 (Partition)中建立。
4. 只能連結檔案,不能連結目錄。
5. 指令為`ln` (原始檔案) (目地檔案)如果我們對某個檔案做了硬連結,那麼若刪掉了其中一個,另一個仍然會可以讀去,但是,hard link 是有限制的:
* 不能跨 Filesystem
* 不能 link 目錄。
* SoftLink:
1. 以絕對路徑或相對路徑指向原始的檔案。
2. 主要用於簡化路徑。
3. 類似MS-Windows下的「建立捷徑」的功能。
4. `ln -fsv` (原始檔案) (目地檔案)
5. 這個的概念就很像windows裡面的捷徑概念,當來源檔被刪除之後,symbolic link 的檔案會開不了。
6. 但是他可以跨FileSystem也可以link目錄,在使用上相對會較為方便。
有demo過,hard link 的話 檔案還是 cat 的出來
## Hard Drive vs Memory vs Virtual memory (Swap)
The term "memory" usually means RAM (**Random Access Memory**); RAM is hardware that allows the computer to **efficiently perform** more than one task at a time (i.e., multi-task).
The terms "disk space" and "storage" usually refer to **hard drive** storage. Hard drive storage is typically used for **long-term** storage of various types of files. Higher capacity hard drives can store larger amounts and sizes of files, such as videos, music, pictures, and documents.
"**Virtual memory (SWAP)**" is hard disk space that has been **designated to act like RAM**. It assists the computer with multi-tasking when there is not a sufficient amount of RAM for the tasks.
## Cache vs buffer
A **buffer** is something that has yet to be “**written**” to disk. A **cache** is something that has been “**read**” from the disk and stored for later use.
**Buffer: 緩衝區**,顧名思義,在快與慢的裝置中設置一個緩衝的區域,讓快的裝置在把資料丟入緩衝區後,可以再去執行其他的命令,不受慢的裝置影響。
例如:硬碟、光碟機,設定一個緩衝區讓電腦放資料,讓電腦不用為了這個裝置忙番天。
**Cache: 快取區**,顧名思義,為經常用到的資料設置一個區域,讓週邊裝置可以快速的找到這筆資料.而不用去龐大的資料庫中尋找,
例如: CPU中的L1 Cache與L2 Cache,經常用得到的指令都會放這邊,不常用的指令會放在記憶體裡面,更不常用的會放硬碟。
### Check
Linux 的 free 指令可以檢查系統內實體記憶體及 Swap 的使用情況, 以下是 free 的基本用法:
顯示系統內實體記憶體及 Swap 的使用情況, 預設會以 KB 為單位:
`free`

`vmstat`

**vmstat** 是`Virtual Meomory Statistics`(虛擬內存統計)的縮寫,可對操作系統的虛擬內存、進程、CPU活動進行監控。他是對系統的整體情況進行統計,不足之處是無法對某個進程進行深入分析。
vmstat 工具提供了一種低開銷的系統性能觀察方式。因爲 vmstat 本身就是低開銷工具,在非常高負荷的服務器上,需要查看並監控系統的健康情況,在控制窗口還是能夠使用vmstat 輸出結果。在學習vmstat命令前,我們先了解一下Linux系統中關於物理內存和虛擬內存相關信息。
**物理內存**和**虛擬內存**區別:
我們知道,直接從`物理內存讀寫數據`要比從`硬盤讀寫數據要快`的多,因此,我們希望所有數據的讀取和寫入都在內存完成,而內存是有限的,這樣就引出了`物理內存`與`虛擬內存`的概念。
**物理內存就是系統硬件提供的內存大小,是真正的內存**,相對於物理內存,在linux下還有一個虛擬內存的概念,`虛擬內存就是爲了滿足物理內存的不足而提出的策略,它是利用磁盤空間虛擬出的一塊邏輯內存,用作虛擬內存的磁盤空間被稱爲交換空間(Swap Space)。
`
作爲物理內存的擴展,linux會在物理內存不足時,使用交換分區的虛擬內存,更詳細的說,就是內核會將暫時不用的內存塊信息寫到交換空間,這樣以來,物理內存得到了釋放,這塊內存就可以用於其它目的,當需要用到原始的內容時,這些信息會被重新從交換空間讀入物理內存。
linux的內存管理採取的是分頁存取機制,爲了保證物理內存能得到充分的利用,內核會在適當的時候將物理內存中不經常使用的數據塊自動交換到虛擬內存中,而將經常使用的信息保留到物理內存。
## RAID
著重在於加大容量,磁碟容錯,加快效能等方面問題
將多個較小的磁碟整合成一個較大的磁碟裝置,不只是儲存,還有資料保護的功能。

### How do you add disks to an array?
有硬體的磁碟陣列跟軟體的
硬體磁碟陣列:中高階的硬體 RAID為獨立的 RAID 晶片,內含 CPU 運算功能,可以運算至 RAID 5/6 parity 的資料,已寫入磁碟中。
越高階的 RAID 還有更多的快取 (cache memory),可以加速讀/寫的性能。 檔名為 /dev/sd
軟體磁碟陣列:由作業系統提供模擬,透過 CPU 與 mdadm 軟體模擬出中高階磁碟陣列卡的功能。很常見於 NAS 伺服器
#### Create a Redundant Array of Inexpensive (or Independent) Disks (RAID1)
`mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/xvdf /dev/xvdg`
就是 multiple device admin 的意思。
#### Stop it
`mdadm --stop /dev/md0`
要做磁碟切割前先把磁碟區區分出來,用 fdisk
## LVM (Logical Volume Manager)
因為 RAID 沒有辦法在既有的檔案系統架構下, 直接將容量放大的限制.
此時需要透過彈性放大和縮小 LVM 的輔助
不過 LVM 主要是在彈性的管理檔案系統,不在於效能與容錯上,可將 LVM 裝在 RAID上
## 面試前要去看這些指令的用意:
## fstab
開機自動掛載
## iptable
iptables 是一套 Linux 下的防火牆,可以按需要建立 iptables 規則,允許或阻擋網路流量。但透過 SSH 設定 iptables 時要格外小心,因為如果設定錯誤,可能會阻擋外部連線,需要到機器面前進行修復,多年前我試過輸入一道錯誤的 iptables 指令,搞到要立即趕到 data center 修復。
## netcat
## netstat
一般遇到問題時,第一個檢查步驟就是查閱系統記錄檔(log),必要時可以嘗試提升記錄層級(logging level)來獲得更詳盡的資訊。如果 netstat 所提供的資訊不夠時,亦可使用 Wireshark、tshark、tcpdump 或 nmap 等檢測工具。
在每個 Linux 系統中預設都會有安裝 netstat,而且他不需要使用管理者權限即可執行,也同時支援 IPv4 與 IPv6,不過不同的 UNIX/Linux 系統可能在參數上會有一些差異,所以如果您寫好的指令要在不同的系統上執行時,可能要稍微注意一下。
iptables 設定時主要分三種類型,分別是 INPUT, FORWARD 及 OUTPUT。
INPUT: 這個行為是外來的連線,例如從遠端 SSH 到伺服器,iptables 會將這個連線定義為 INPUT。
FORWARD: 這是外來的連線,但最終目的地不是伺服器本身,只是轉送到其他機器,例如路由器,除了 routing, NAT 等網路服務外,一般上不會用到這種類型。
OUTPUT: 從本機連接到外部的連線,這個可以允許或阻擋本機連接對外的服務。
## iostat
https://iter01.com/566348.html
## crontab
How to schedule task in Linux
Crontab is cron daemon to schedule repetitive scheduling task.

## tracert 來檢測和追蹤我們路由
Tracert 是一個網路檢測工具,可以追蹤網路封包經過的路由指令,例如當發現瀏覽一個網站很慢時,可以用 tracert 檢查,結果會顯示經過的每一個網路節點,以及每個節點返回的時間。tracert 會對經過的網路設備送出封包 3 次,返回的時間單位是 ms。
> 當然可以透過一些參數減少送封包的次數,例如 可以透過 -q 這個參數指定要送的封包次數 tracert -q 1 ip_address 可限定只傳送一次封包至此 IP 位址。
會收到此次路由到目的地位址的節點數量與速度,其中 * 表示在此節點上有封包遺失或者對方拒絕回應你的 request。
像第四筆紀錄中間的 * 代表著封包遺失,而第七筆的三個 * 則表示別人的設備不想回你的 ICMP request(不代表它封包遺失),所以才直接跳站。
> 假設第 7 筆之後都是星號,表示被對方防火牆擋下來,追不到後面的路由。
> 注意!! Windows 的指令為 tracert 而不是 traceroute。
https://medium.com/starbugs/do-you-understand-htop-ffb72b3d5629
## Networking
The procedure to turn off eth0 interface is as follows. Run:
`ifdown eth0`
To turn on eth0 interface run:
`ifup eth0`
See ip address info using the ip command:
Every time a host sends a TCP packet, it will contain a sequence number which is the total number of sent bytes. The sequence number is not initialized with zero, it's initialized with a random number ISN for each side of the connection.
https://notfalse.net/26/tcp-seq (+1 -1 的機制)

### ip network configuration , DNS configuration
1. Using nmtui (TUI -> text-based user interface) for NetworkManager
2. Using nmcli (Powerful CLI for NetworkManager)
## Curl v.s Wget
Curl 是一個在 Linux 上用來透過 HTTP Protocol(HTTP HyperText Transfer Protocol 定義存取網路資源的協定,讓我們可以使用 client / server 模式來取得網路資源)下載和上傳檔案的指令(**比起 wget 只能下載強大許多**)。它基本的指令格式如下:
```txt
-X/--request [GET|POST|PUT|DELETE|PATCH] 使用指定的 http method 來發出 http request
-H/--header 設定 request 裡所攜帶的 header
-i/--include 在 output 顯示 response 的 header
-d/--data 攜帶 HTTP POST Data
-v/--verbose 輸出更多的訊息方便 debug
-u/--user 攜帶使用者帳號、密碼
-b/--cookie 攜帶 cookie(可以是參數或是檔案位置)
```
## SELinux
1. Managing the firewall

* firewall-cmd --help | less
* firewall-cmd --add-service=mysql --permanent
* firewall-cmd --reload
* firewall-cmd --list-all
2. Using file ACL(access control lists)
3. Troubleshooting SElinux
## (Optional Podman)
https://ithelp.ithome.com.tw/articles/10238749
## Networking Troubleshooting