linux磁盘管理系列二:软RAID的实现

1、什么是RAID

RAID全称是独立磁盘冗余阵列(Redundant Array of Independent Disks),基本思想是把多个磁盘组合起来,组合一个磁盘阵列组,使得性能大幅提高。

RAID分为几个不同的等级,各个不同的等级均在数据可靠性及读写性能做了不同的权衡。实际工作中根据自己的业务需求选择不同的RAID方案。

2、RAID的实现方式

  • 外接式磁盘阵列:通过扩展卡提供适配能力
  • 内接式RAID:主板集成RAID控制器安装OS前在BIOS里配置
  • 软件RAID:通过OS实现

3、标准的RAID

3.1 RAID0

RAID0称为条带化存储,将数据分段存储在各个磁盘中,读写均可以并行处理,因此读写速率为单个磁盘的N倍,没有冗余功能,任何一个磁盘的损坏就会导致的数据不可用。

未分类

3.2 RAID1

RADI1是镜像存储,没有数据校验,数据被同等的写入到2个或者多个磁盘中,写入速度相对慢, 但是读取速度比较快。

未分类

3.3 RAID 4

RADI4在RAID1的基础上,N个盘用于数据存储,另外加入了1个磁盘作为校验盘。一共N+1个盘,任何一个盘坏掉也不影响数据的访问

3.4 RAID 5

RAID5在RAID4的基础上,由原来的一个盘来存储校验数据,改为每个盘都有数据和校验信息的。

未分类

4、混合RAID

4.1 RAID01

先组成RAID0,然后组成RAID1.

未分类

4.2 RAID10

先组成RAID1,然后组成RAID0

未分类

5、软RAID的实现

5.1 RAID5的实现

创建由三块硬盘组成的可用空间为2G的RAID5设备,要求其chunk大小为256k,文件系统为ext4,开机可自动挂载至/mydata目录

5.1.1 先看看我们的磁盘情况

[root@centos7 Bash]$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0  200G  0 disk
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0  128G  0 part
├─sda3   8:3    0 48.8G  0 part /
├─sda4   8:4    0  512B  0 part
└─sda5   8:5    0 19.5G  0 part /app
sdb      8:16   0  100G  0 disk
sdc      8:32   0   20G  0 disk
sdd      8:48   0   20G  0 disk
sde      8:64   0   20G  0 disk
sdf      8:80   0   20G  0 disk
sr0     11:0    1  8.1G  0 rom  /run/media/root/CentOS 7 x86_64 

这里我们使用sdb,sdc,sdd,每个盘创建一个主分区1G,构建RADI5.

5.1.2 根据实际情况分区

[root@centos7 Bash]$ fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0x93d380cf.

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-209715199, default 2048): 
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-209715199, default 209715199): +1G
Partition 1 of type Linux and of size 1 GiB is set

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): fd
Changed type of partition 'Linux' to 'Linux raid autodetect'

Command (m for help): p

Disk /dev/sdb: 107.4 GB, 107374182400 bytes, 209715200 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x93d380cf

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048     2099199     1048576   fd  Linux raid autodetect

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[root@centos7 Bash]$ fdisk /dev/sdc
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0xc56b90d8.

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-41943039, default 2048): 
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-41943039, default 41943039): +1G
Partition 1 of type Linux and of size 1 GiB is set

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): fd
Changed type of partition 'Linux' to 'Linux raid autodetect'

Command (m for help): p

Disk /dev/sdc: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0xc56b90d8

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1            2048     2099199     1048576   fd  Linux raid autodetect

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[root@centos7 Bash]$ fdisk /dev/sdd
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0x7e0900d8.

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-41943039, default 2048): 
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-41943039, default 41943039): +1G
Partition 1 of type Linux and of size 1 GiB is set

Command (m for help): p

Disk /dev/sdd: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x7e0900d8

   Device Boot      Start         End      Blocks   Id  System
/dev/sdd1            2048     2099199     1048576   83  Linux

Command (m for help): t
Selected partition 1
Hex code (type L to list all codes): fd
Changed type of partition 'Linux' to 'Linux raid autodetect'

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

5.1.3 创建raid

[root@centos7 Bash]$ mdadm -C /dev/md5 -a yes -l 5 -n 3 /dev/sd{b1,c1,d1} -c 256       # -C指定创建, -a yes 自动创建设备 , -l 设定level , -n 设定磁盘个数, -c chunk大小
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md5 started.
[root@centos7 Bash]$ mdadm -Ds                                                          # 查看信息
ARRAY /dev/md5 metadata=1.2 name=centos7.magedu.com:5 UUID=2c8ae60d:a799fcb7:9008a046:ae6ea430
[root@centos7 Bash]$ mdadm -Ds >/etc/mdadm.conf                                         # 将软raid信息写入到配置文件中去
[root@centos7 Bash]$ mkdir /mnt/md5                                                     # 创建挂载点目录 
[root@centos7 Bash]$ mkfs.ext4 /dev/md5                                                 # 创建文件系统
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=64 blocks, Stripe width=128 blocks
131072 inodes, 523776 blocks
26188 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=536870912
16 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done 

[root@centos7 Bash]$ mount /dev/md5 /mnt/md5                                          # 挂载设备 
[root@centos7 Bash]$ tail -n 1 /etc/mtab
/dev/md5 /mnt/md5 ext4 rw,seclabel,relatime,stripe=128,data=ordered 0 0               # 查看挂载信息
[root@centos7 Bash]$ tail -n 1 /etc/mtab >>/etc/fstab                                 #添加到fstab文件中,确保开机启动,这里建议使用uuid

5.1.4 验证raid

[root@centos7 md5]$ mdadm -D /dev/md5                                                 #查看详细raid5详细信息,可以发现有3个都是working状态的
/dev/md5:
           Version : 1.2
     Creation Time : Wed Dec  6 19:28:22 2017
        Raid Level : raid5
        Array Size : 2095104 (2046.00 MiB 2145.39 MB)
     Used Dev Size : 1047552 (1023.00 MiB 1072.69 MB)
      Raid Devices : 3
     Total Devices : 3
       Persistence : Superblock is persistent

       Update Time : Wed Dec  6 19:39:06 2017
             State : clean 
    Active Devices : 3
   Working Devices : 3
    Failed Devices : 0
     Spare Devices : 0

            Layout : left-symmetric
        Chunk Size : 256K

Consistency Policy : resync

              Name : centos7.magedu.com:5  (local to host centos7.magedu.com)
              UUID : 2c8ae60d:a799fcb7:9008a046:ae6ea430
            Events : 18

    Number   Major   Minor   RaidDevice State
       0       8       17        0      active sync   /dev/sdb1
       1       8       33        1      active sync   /dev/sdc1
       3       8       49        2      active sync   /dev/sdd1
[root@centos7 md5]$ man mdadm
[root@centos7 md5]$ mdadm /dev/md5 -f /dev/sdc1                                                 # -f 设定指定设备故障, 将/dev/sdc1 这个盘标记失败, 看是否数据能访问,我这里使用-f标记失败,工作中可以根据硬盘指示灯判断磁盘状态
mdadm: set /dev/sdc1 faulty in /dev/md5            
[root@centos7 md5]$ mdadm -D /dev/md5                                                           #在次查看信息,发现工作的是2个, 一个失败的设备 
/dev/md5:
           Version : 1.2
     Creation Time : Wed Dec  6 19:28:22 2017
        Raid Level : raid5
        Array Size : 2095104 (2046.00 MiB 2145.39 MB)
     Used Dev Size : 1047552 (1023.00 MiB 1072.69 MB)
      Raid Devices : 3
     Total Devices : 3
       Persistence : Superblock is persistent

       Update Time : Wed Dec  6 19:41:08 2017
             State : clean, degraded                                                             # 这里注意了。 我们的一个盘坏掉了。 raid5状态为降级使用了。
    Active Devices : 2
   Working Devices : 2
    Failed Devices : 1
     Spare Devices : 0

            Layout : left-symmetric
        Chunk Size : 256K

Consistency Policy : resync

              Name : centos7.magedu.com:5  (local to host centos7.magedu.com)
              UUID : 2c8ae60d:a799fcb7:9008a046:ae6ea430
            Events : 20

    Number   Major   Minor   RaidDevice State
       0       8       17        0      active sync   /dev/sdb1
       -       0        0        1      removed
       3       8       49        2      active sync   /dev/sdd1

       1       8       33        -      faulty   /dev/sdc1
[root@centos7 md5]$ cat a.txt                                          # 发现我们的数据还是能访问的。没有问题。

5.1.5 替换设备

我这里是磁盘坏掉后的执行替换的, 完全可以多一个备用盘, 坏掉自动替换的。

[root@centos7 md5]$ mdadm /dev/md5 -a /dev/sde1                        # 上面我们的sdc1数据损坏,我们需要更换新的磁盘来顶替他的位置。这里添加一个sde1的磁盘, fdisk操作这里省去了。
mdadm: added /dev/sde1
[root@centos7 md5]$ mdadm -Ds                                          # 查看详细信息
ARRAY /dev/md5 metadata=1.2 name=centos7.magedu.com:5 UUID=2c8ae60d:a799fcb7:9008a046:ae6ea430
[root@centos7 md5]$ mdadm -D /dev/md5                                  # 查看详细信息
/dev/md5:
           Version : 1.2
     Creation Time : Wed Dec  6 19:28:22 2017
        Raid Level : raid5
        Array Size : 2095104 (2046.00 MiB 2145.39 MB)
     Used Dev Size : 1047552 (1023.00 MiB 1072.69 MB)
      Raid Devices : 3
     Total Devices : 4
       Persistence : Superblock is persistent

       Update Time : Wed Dec  6 19:50:01 2017
             State : clean                                                  # 状态恢复正常了。没有问题
    Active Devices : 3
   Working Devices : 3
    Failed Devices : 1
     Spare Devices : 0

            Layout : left-symmetric
        Chunk Size : 256K

Consistency Policy : resync

              Name : centos7.magedu.com:5  (local to host centos7.magedu.com)
              UUID : 2c8ae60d:a799fcb7:9008a046:ae6ea430
            Events : 43

    Number   Major   Minor   RaidDevice State
       0       8       17        0      active sync   /dev/sdb1
       4       8       65        1      active sync   /dev/sde1
       3       8       49        2      active sync   /dev/sdd1

       1       8       33        -      faulty   /dev/sdc1             # 这个盘是坏掉的,我们已经加入了新的磁盘, 这个盘可以干掉了
[root@centos7 md5]$ man mdadm
[root@centos7 md5]$ mdadm /dev/md5 --remove /dev/sdc1                  # 这个盘我们从raid5中移除去。        
mdadm: hot removed /dev/sdc1 from /dev/md5

5.1.6 扩展raid

我们上面使用的是2+1构成的raid5,磁盘利用率为66%,如果我们想改成3+1 可以执行类似如下命令

[root@centos7 mnt]$ mkadm -G -r  /dev/md5 -n 4 -a /dev/sdxx                  # 这里我就不测试了。使用/dev/sdxx代替一个设备。-G 是Grown增长的意思,-r 是resizefs的意思,

5.1.7 清空raid信息

[root@centos7 mnt]$ umount /dev/md5                                   # 卸载设备
[root@centos7 mnt]$ mdadm -S /dev/md5                                 # 停止raid5 
mdadm: stopped /dev/md5
[root@centos7 mnt]$ sed -i '$d' /etc/fstab                            # 删除fstab中关于raid5挂载的行
[root@centos7 mnt]$ cat /etc/fstab                                    # 确保fstab没有大问题

#
# /etc/fstab
# Created by anaconda on Tue Nov  7 16:07:01 2017
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#

UUID=59ccea87-3c4e-4bbc-9e2f-3fadb1dcf2e6 /                       ext4    defaults        1 1
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime,usrquota,grpquota        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
#UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0
#UUID=a0516c4f-40e6-4919-905a-8b44db12ff7b swap               swap    defaults,pri=0        0 0 
#/dev/sdb2 /test ext4 rw,seclabel,relatime,data=ordered 0 0
#/dev/sdb1 /home xfs rw,seclabel,relatime,attr2,inode64,usrquota,grpquota  0 0
[root@centos7 mnt]$ rm -rf /etc/mdadm.conf                                   # 删除raid默认配置文件
[root@centos7 mnt]$ mdadm --zero-superblock /dev/sd{b1,e1,d1,c1}             # 清空设置上的超级块信息

5.2 RAID10的实现

raid10 ,6个分区,2个一组raid1,3组raid0

5.2.1 案例分析

分析下,我们创建一个raid10设置,2个设备组成一个raid1,6个设备2个一组可以组成3个raid1, 然后把3个raid1组成一个raid0即可

5.2.2 先创建6个设备

[root@centos7 mnt]$ lsblk                                # 就是使用fdisk 创建的设备, 具体这里就不写了。 最终使用lsblk显示,我们可以看到sdb1,sdb2,sdd1,sde1一共6个磁盘
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0  200G  0 disk 
├─sda1   8:1    0    1G  0 part /boot
├─sda2   8:2    0  128G  0 part 
├─sda3   8:3    0 48.8G  0 part /
├─sda4   8:4    0  512B  0 part 
└─sda5   8:5    0 19.5G  0 part /app
sdb      8:16   0  100G  0 disk 
├─sdb1   8:17   0    1G  0 part 
└─sdb2   8:18   0    1G  0 part 
sdc      8:32   0   20G  0 disk 
├─sdc1   8:33   0    1G  0 part 
└─sdc2   8:34   0    1G  0 part 
sdd      8:48   0   20G  0 disk 
└─sdd1   8:49   0    1G  0 part 
sde      8:64   0   20G  0 disk 
└─sde1   8:65   0    1G  0 part 
sdf      8:80   0   20G  0 disk 
sr0     11:0    1  8.1G  0 rom  /run/media/root/CentOS 7 x86_64

5.2.3 创建raid

[root@centos7 mnt]$ mdadm -C /dev/md11 -a yes -l 1 -n 2 /dev/sd{b1,c1}                               # 创建第一个raid1
mdadm: /dev/sdb1 appears to be part of a raid array:
       level=raid5 devices=3 ctime=Wed Dec  6 19:28:22 2017
mdadm: Note: this array has metadata at the start and
    may not be suitable as a boot device.  If you plan to
    store '/boot' on this device please ensure that
    your boot-loader understands md/v1.x metadata, or use
    --metadata=0.90
mdadm: /dev/sdc1 appears to be part of a raid array:
       level=raid5 devices=3 ctime=Wed Dec  6 19:28:22 2017
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md11 started.
[root@centos7 mnt]$ mdadm -C /dev/md12 -a yes -l 1 -n 2 /dev/sd{b2,c2}                                #创建第二个raid1
mdadm: Note: this array has metadata at the start and
    may not be suitable as a boot device.  If you plan to
    store '/boot' on this device please ensure that
    your boot-loader understands md/v1.x metadata, or use
    --metadata=0.90
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md12 started.
[root@centos7 mnt]$ mdadm -C /dev/md13 -a yes -l 1 -n 2 /dev/sd{d1,e1}                                 # 创建第三个raid1
mdadm: /dev/sdd1 appears to be part of a raid array:
       level=raid5 devices=3 ctime=Wed Dec  6 19:28:22 2017
mdadm: Note: this array has metadata at the start and
    may not be suitable as a boot device.  If you plan to
    store '/boot' on this device please ensure that
    your boot-loader understands md/v1.x metadata, or use
    --metadata=0.90
mdadm: /dev/sde1 appears to be part of a raid array:
       level=raid5 devices=3 ctime=Wed Dec  6 19:28:22 2017
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md13 started.
[root@centos7 mnt]$ mdadm -C /dev/md10 -a yes -l 0 -n 3 /dev/md{11,12,13}                             # 将3个raid1 合并为一个raid0 
mdadm: /dev/md11 appears to contain an ext2fs file system
       size=2095104K  mtime=Wed Dec  6 19:29:45 2017
mdadm: /dev/md13 appears to contain an ext2fs file system
       size=2095104K  mtime=Wed Dec  6 19:29:45 2017
Continue creating array? y
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md10 started.
[root@centos7 mnt]$ mkfs.ext
mkfs.ext2  mkfs.ext3  mkfs.ext4            
[root@centos7 mnt]$ mkfs.ext4 /dev/md10                                                                 # 创建文件系统                                                                                         
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=128 blocks, Stripe width=384 blocks
196224 inodes, 784896 blocks
39244 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=805306368
24 block groups
32768 blocks per group, 32768 fragments per group
8176 inodes per group
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done 

[root@centos7 mnt]$ mdadm -Ds                                                                             # 查看配置信息
ARRAY /dev/md11 metadata=1.2 name=centos7.magedu.com:11 UUID=0ce2cd6c:cd21fab6:3e65cfb5:64bd86f3
ARRAY /dev/md12 metadata=1.2 name=centos7.magedu.com:12 UUID=8af31dff:efab06ed:48e2613b:a599c774
ARRAY /dev/md13 metadata=1.2 name=centos7.magedu.com:13 UUID=a8c99d60:2d0c61e7:97a76809:9396c020
ARRAY /dev/md10 metadata=1.2 name=centos7.magedu.com:10 UUID=50b2fa58:4ce65d67:8c50c853:fa175a28
[root@centos7 mnt]$ mdadm -Ds  >> /etc/mdadm.conf                                                         # 写配置文件到mdadm的配置文件中
[root@centos7 mnt]$ mkdir /mnt/md10                                                                       # 创建挂载目录
[root@centos7 mnt]$ mount /dev/md10 /mnt/md10                                                             # 挂载文件系统
[root@centos7 mnt]$ tail -n 1 /etc/mtab                                                                   # 查看mtab文件中的最后一行, 也就是我们的md10挂载信息
/dev/md10 /mnt/md10 ext4 rw,seclabel,relatime,stripe=384,data=ordered 0 0
[root@centos7 mnt]$ tail -n 1 /etc/mtab >> /etc/fstab                                                     #添加到开机启动

5.2.4 raid 清除工作

[root@centos7 mnt]$ umount /dev/md10                                                                      # 取消挂载
[root@centos7 mnt]$ rm -rf /etc/mdadm.conf                                                                # 删除mdadm的默认配置
[root@centos7 mnt]$ mdadm -S /dev/md10                                                                    # 停止raid0设置
mdadm: stopped /dev/md10
[root@centos7 mnt]$ mdadm -S /dev/md11                                                                    # 停止raid1设置
mdadm: stopped /dev/md11
[root@centos7 mnt]$ mdadm -S /dev/md12                                                                    # 停止radi1 设置
mdadm: stopped /dev/md12 
[root@centos7 mnt]$ mdadm -S /dev/md13                                                                    # 停止raid 1 设置
mdadm: stopped /dev/md13
[root@centos7 mnt]$ sed -i '$d' /etc/fstab                                                                # 删除fstab的挂载  
[root@centos7 mnt]$ cat /etc/fstab                                                                        # 确保正确

#
# /etc/fstab
# Created by anaconda on Tue Nov  7 16:07:01 2017
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#

UUID=59ccea87-3c4e-4bbc-9e2f-3fadb1dcf2e6 /                       ext4    defaults        1 1
UUID=f4e867e8-bcde-43a2-adc7-c80b0948e85f /app                    ext4    noatime,usrquota,grpquota        1 2
UUID=1d6cbe88-ffb4-4adf-bacf-76be1fa75708 /boot                   ext4    defaults        1 2
#UUID=b2c064f5-1ee5-4b5c-9e75-ed41cb99c5aa swap                    swap    defaults        0 0
#UUID=a0516c4f-40e6-4919-905a-8b44db12ff7b swap               swap    defaults,pri=0        0 0 
#/dev/sdb2 /test ext4 rw,seclabel,relatime,data=ordered 0 0
#/dev/sdb1 /home xfs rw,seclabel,relatime,attr2,inode64,usrquota,grpquota  0 0
[root@centos7 mnt]$ mdadm -D                                                                                  # 再次查看下mdadm信息,确保没有了
mdadm: No devices given.
[root@centos7 mnt]$ mdadm --zero-superblock /dev/sd{b1,b2,c1,c2,d1,e1}                                        # 请求md的元数据信息

linux磁盘管理系列一:磁盘配额管理

一、前言

在linux系统中,由于是多用户、多任务的环境,如果有少数几个用户大量使用磁盘空间,导致其他用户的正常使用,因此需要对各个用户的磁盘空间进行管理和限定。

二、quota的用途

限制某一个用户的最大磁盘配额

三、quota的使用限制

  • 仅能针对整个文件系统
  • 内核必须支持
  • 只对一般用户生效
  • 这里提供一个样例,针对样例对quota的配置管理做个描述

四、案例讲解

4.1 案例描述

  • 创建5个用户user1,user2,user3,user4,user5,密码和用户名相同,初始组为usergrp组。
  • 5个用户都可以取得300M的磁盘使用空间,文件数量不限。超过250M,给于提示。
  • usergrp这个组内成员最大使用空间1GB。
  • 如果有用户超过soft限制,给14天的宽限时间。

4.2 准备磁盘

[root@mail ~]# fdisk -l      #查看磁盘情况

Disk /dev/sda: 42.9 GB, 42949672960 bytes, 83886080 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x000bd275

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2099199     1048576   83  Linux
/dev/sda2         2099200    83886079    40893440   8e  Linux LVM

Disk /dev/sdb: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/cl-root: 39.7 GB, 39720058880 bytes, 77578240 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes


Disk /dev/mapper/cl-swap: 2147 MB, 2147483648 bytes, 4194304 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

[root@mail ~]# fdisk /dev/sdb     #对sdb这个盘进行分区,这里就分一个区
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0xbcd17d69.

Command (m for help): n
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p): p
Partition number (1-4, default 1): 1
First sector (2048-20971519, default 2048): 
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-20971519, default 20971519): 
Using default value 20971519
Partition 1 of type Linux and of size 10 GiB is set

Command (m for help): p

Disk /dev/sdb: 10.7 GB, 10737418240 bytes, 20971520 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0xbcd17d69

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    20971519    10484736   83  Linux

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
[root@mail ~]# mkfs.ext4 /dev/sdb1
mke2fs 1.42.9 (28-Dec-2013)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
655360 inodes, 2621184 blocks
131059 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=2151677952
80 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks: 
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done 

[root@mail ~]# mkdir /mnt/home          #创建一个目录
[root@mail ~]# mount /dev/sdb1 /mnt/home   #测试挂载下

4.4 创建用户

[root@mail ~]# vim adduserbat.sh  #创建一个添加用户的脚本
[root@mail ~]# cat adduserbat.sh  #确认下脚本
#!/bin/bash

groupadd usergrp
for user in user1 user2 user3 user4 user5
do 
    useradd -g usergrp -b /mnt/home $user
    echo $user |passwd --stdin $user
done
[root@mail ~]# sh adduserbat.sh    #运行脚本去创建用户
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
Changing password for user user1.
passwd: all authentication tokens updated successfully.
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
Changing password for user user2.
passwd: all authentication tokens updated successfully.
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
Changing password for user user3.
passwd: all authentication tokens updated successfully.
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
Changing password for user user4.
passwd: all authentication tokens updated successfully.
useradd: warning: the home directory already exists.
Not copying any file from skel directory into it.
Creating mailbox file: File exists
Changing password for user user5.
passwd: all authentication tokens updated successfully.
[root@mail ~]# finger user1             #查看用户信息,确保家目录在/dev/sdb1的挂载目录上。
Login: user1                      Name: 
Directory: /mnt/home/user1              Shell: /bin/bash
Never logged in.
No mail.
No Plan.
[root@mail ~]# id user1              #查看用户信息
uid=2531(user1) gid=2532(usergrp) groups=2532(usergrp)

4.5 检查操作系统支持

前面提到了quota仅仅针对整个文件系统来进行规划的。需要确认我们为各个用户提供存储的位置是独立的文件系统。

[root@mail ~]# df -h /mnt/home      #查看我们的挂载点是否是独立文件系统
Filesystem      Size  Used Avail Use% Mounted on
/dev/sdb1       9.8G   37M  9.2G   1% /mnt/home
[root@mail ~]# mount |grep /mnt/home     #查看我们的文件系统
/dev/sdb1 on /mnt/home type ext4 (rw,relatime,data=ordered)

4.6 让文件系统支持quota设置

[root@mail ~]# mount -o remount,usrquota,grpquota /mnt/home   #重新挂载/mnt/home 支持usrquota,grpquota
[root@mail ~]# mount |grep /mnt/home                           #确认下
/dev/sdb1 on /mnt/home type ext4 (rw,relatime,quota,usrquota,grpquota,data=ordered)
[root@mail ~]# tail -n 1 /etc/mtab >> /etc/fstab         #追加到/etc/fstab中去,确保开机启用quota
[root@mail ~]# cat /etc/fstab                            #确保fstab文件正确性

#
# /etc/fstab
# Created by anaconda on Fri Feb 10 03:56:55 2017
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/cl-root     /                       xfs     defaults        0 0
UUID=dd4c6743-bdf5-4899-a43b-814cbe75c618 /boot                   xfs     defaults        0 0
/dev/mapper/cl-swap     swap                    swap    defaults        0 0
/dev/sr0 /mnt/cdrom iso9660 ro,relatime,uid=0,gid=0,iocharset=utf8,mode=0400,dmode=0500 0 0
/dev/sdb1 /mnt/home ext4 rw,relatime,quota,usrquota,grpquota,data=ordered 0 0

4.7 扫描文件系统并新建quota的配置文件

[root@mail ~]# quotacheck -avug
quotacheck: Your kernel probably supports journaled quota but you are not using it. Consider switching to journaled quota to avoid running quotacheck after an unclean shutdown.
quotacheck: Scanning /dev/sdb1 [/mnt/home] done
quotacheck: Cannot stat old user quota file /mnt/home/aquota.user: No such file or directory. Usage will not be subtracted.
quotacheck: Cannot stat old group quota file /mnt/home/aquota.group: No such file or directory. Usage will not be subtracted.
quotacheck: Cannot stat old user quota file /mnt/home/aquota.user: No such file or directory. Usage will not be subtracted.
quotacheck: Cannot stat old group quota file /mnt/home/aquota.group: No such file or directory. Usage will not be subtracted.
quotacheck: Checked 30 directories and 20 files
quotacheck: Old file not found.
quotacheck: Old file not found.

主要参数

  • -a:  扫描所有在/etc/mtab内含有quota参数的文件系统
  • -u:  针对用户扫描文件与目录的使用情况,会新建一个aquota.user文件
  • -g:  针对用户组扫描文件与目录的使用情况,会新增一个aquota.group文件
  • -v:  显示扫描过程的信息

4.8 启用quota

[root@mail ~]# quotaon  -avug    #启用quota
/dev/sdb1 [/mnt/home]: group quotas turned on
/dev/sdb1 [/mnt/home]: user quotas turned on

这个命令(quotaon) 几乎只需要在第一次启动quota时才需要进行,因为下次等你重新启动时,系统的/etc/rc.d/rc.sysinit这个初始化脚本就会自动执行这个命令。

如果想关闭可以使用quotaoff -avug

4.9 编辑账户的的限值

[root@mail ~]# edquota -u user1

会打开一个vi编辑器,修改我们的设置如下图。

未分类

  • 软限制: 这个值超过了基本上没事,还是可以创建文件继续使用文件,但是在指定grace天过后就不能在创建文件了。
  • 硬限值: 这个值不能超过。

执行如下命令将user1的设置应用到其他用户上

[root@mail ~]# edquota -p user1 -u user2    #-p 指定参考用户,这句话的意思就是将user1的quota信息赋值给user2
[root@mail ~]# edquota -p user1 -u user3
[root@mail ~]# edquota -p user1 -u user4
[root@mail ~]# edquota -p user1 -u user5

4.10 编辑组的设置

[root@mail ~]# edquota -g usergrp

4.11 修改宽限时间

[root@mail ~]# edquota -t

4.12 对用户和组合quota限制查看

[root@mail ~]# quota -uvs user1       #查看user1的限制信息
Disk quotas for user user1 (uid 2531): 
     Filesystem   space   quota   limit   grace   files   quota   limit   grace
      /dev/sdb1     28K    245M    293M               7       0       0        
[root@mail ~]# quota -gvs usergrp
Disk quotas for group usergrp (gid 2532): #查看usergrp的限制信息
     Filesystem   space   quota   limit   grace   files   quota   limit   grace
      /dev/sdb1      0K    879M    977M               0       0       0        

参数说明

  • -u:  指定用户
  • -g:  指定用户组
  • -s:  以1024为倍数来指定单位,显示M之类的单位
  • -v:  显示用户在文件系统的quota值

4.13 对文件系统quota限制查看

[root@mail ~]# repquota -as
*** Report for user quotas on device /dev/sdb1                   #这里看到是针对/dev/sdb1的文件系统的
Block grace time: 14days; Inode grace time: 7days
                        Space limits                File limits
User            used    soft    hard  grace    used  soft  hard  grace
----------------------------------------------------------------------
root      --     20K      0K      0K              2     0     0       
zhao      --     52K      0K      0K             13     0     0       
user1     --     28K    245M    293M              7     0     0       
user2     --     28K    245M    293M              7     0     0       
user3     --     28K    245M    293M              7     0     0       
user4     --     28K    245M    293M              7     0     0       
user5     --     28K    245M    293M              7     0     0       

4.14 quota测试

[user1@mail ~]$ dd if=/dev/zero of=bigfile bs=1M count=270  #先创建一个270M的文件看看 
sdb1: warning, user block quota exceeded.                   #这里提示警告了。 也就是我们超过了软限制的值250了。
270+0 records in
270+0 records out
283115520 bytes (283 MB) copied, 0.715086 s, 396 MB/s
[user1@mail ~]$ dd if=/dev/zero of=bigfile2 bs=1M count=40  #这里我们创建一个40M的文件
sdb1: write failed, user block limit reached.               #提示错误了。超出限制了。
dd: error writing ‘bigfile2’: Disk quota exceeded
23+0 records in
22+0 records out
24035328 bytes (24 MB) copied, 0.1165 s, 206 MB/s
[user1@mail ~]$ du -sk                                      #查看两个文件占用情况
300000    .

4.15 脚本设置quota信息

上面我们对用户和组的设置,它会启动一个vi编辑器,修改保存才生效。需要交互。如果我们想使用script方式快速设置,那就需要使用setquota命令了。

命令使用 setquota [ -u | -g ] 用户名或者组名 块大小软限制 块大小硬限制 文件数量软限制 文件数量大小硬限制 文件系统

[root@mail ~]# quota -usv user1     #查看user1的quota信息
Disk quotas for user user1 (uid 2531): 
     Filesystem   space   quota   limit   grace   files   quota   limit   grace
      /dev/sdb1    293M*   245M    293M  13days      14       0       0        
[root@mail ~]# setquota -u user1 400000 500000 100 200 /dev/sdb1    #使用setquota修改
[root@mail ~]# quota -usv user1                                     #再次查看quota信息
Disk quotas for user user1 (uid 2531): 
     Filesystem   space   quota   limit   grace   files   quota   limit   grace
      /dev/sdb1    293M    391M    489M              14     100     200        

Linux服务器使用Crontab控制定时任务

Crontab,可以将任何脚本、程序或文档安排在某个最方便的时间运行。通俗的讲就是定时执行某个脚本、程序。

常见用途:

定时关机
定时检查更新
定时对系统配置、数据库、日志进行备份
定时清理垃圾文件

检测是否已安装

crontab
-bash: crontab: command not found

执行 crontab 命令如果报 command not found,就表明没有安装.

开始安装

#yum -y install vixie-cron crontabs -y

crontab 并不支持-h或–help之类的选项,不过还是可以通过它查看命令帮助

# crontab -h

也可以使用 info crontab 命令查看详细的帮助信息。

cron服务提供crontab命令来设定cron服务的,以下是这个命令的一些参数与说明:

crontab -u //设定某个用户的cron服务,一般root用户在执行这个命令的时候需要此参数
crontab -l //列出某个用户cron服务的详细内容
crontab -r //删除没个用户的cron服务
crontab -e //编辑某个用户的cron服务

比如说root查看自己的cron设置:

crontab -u root -l

再例如,root想删除fred的cron设置:

crontab -u fred -r

在编辑cron服务时,编辑的内容有一些格式和约定,输入:

crontab -u root -e

进入vi编辑模式,编辑的内容一定要符合下面的格式:/1 * * * ls >> /tmp/ls.txt


Crontab配置方法:

重点来了:

每个用户可以直接修改文件 /var/spool/cron/user来控制/etc/crontab文件,root的话就是

/var/spool/cron/root

直接编辑此文件即可自动化运行,示例:

echo  "0 1 * * * /sbin/reboot > /dev/null 2>&1"  >> /var/spool/cron/root

这个脚本每天1点自动重启服务器
添加之后使用

crontab -l

可以看到已经添加了Crontab任务。

方法二:

echo "0 1 * * * /sbin/reboot > /dev/null 2>&1" >1.sh
crontab 1.sh

意思也就是先把定时任务存为文件,在使用Crontab来调用,也可以添加成功。
添加之后使用

crontab -l

也可以看到已经添加了Crontab任务。
这样就能使得Crontab添加脚本自动化运行相关程序。
Crontab比init.d运行级别大一些,用Crontab来控制程序运行更加完美。


Crontab状态控制

/sbin/service crond start //启动服务
/sbin/service crond stop //关闭服务
/sbin/service crond restart //重启服务
/sbin/service crond reload //重新载入配置
/sbin/service crond status //查看状态

或者使用

# service crond start
# service crond stop
# service crond restart
# service crond reload
# service crond status

想记录下来的也就是—之间部分。。。
附上一个Crontab定时重启服务器脚本:

#!/bin/bash
#  .-------------------------------------------------------------
#  | Bash Name: 服务器定时重启脚本
#  | Version: 1.0
#  | This Is a Shell Script ,Easy To Use
#  | Web Site: https://4ker.cc/crontab.html
#  |--------------------------------------------------------------
#  | Author: 刺猬 <[email protected]>
#  | Copyright (c) 2017, https://4ker.cc All Rights Reserved.
#  .--------------------------------------------------------------
echo "欢迎使用服务器定时重启脚本"
echo '请输入重启服务器的时间:(示例:数字1-9,表示1-9点):'
read time
yum install vixie-cron crontabs -y
chkconfig crond on
systemctl enable crond.service
service crond start
/bin/systemctl start crond.service
echo  "0 $time * * * /sbin/reboot > /dev/null 2>&1"  >> /var/spool/cron/root
echo "添加成功,服务器在每天$time自动重启!"
sleep 1
echo "服务器将重启使脚本生效!"
reboot
echo ;

HAProxy系列—Linux下的安装

HAProxy是一个使用C语言编写的自由及开放源代码软件,其提供高可用性、负载均衡,以及基于TCP和HTTP的应用程序代理。
  
HAProxy特别适用于那些负载特大的web站点,这些站点通常又需要会话保持或七层处理。HAProxy运行在当前的硬件上,完全可以支持数以万计的并发连接。并且它的运行模式使得它可以很简单安全的整合进您当前的架构中, 同时可以保护你的web服务器不被暴露到网络上。
  
HAProxy实现了一种事件驱动, 单一进程模型,此模型支持非常大的并发连接数。多进程或多线程模型受内存限制 、系统调度器限制以及无处不在的锁限制,很少能处理数千并发连接。事件驱动模型因为在有更好的资源和时间管理的用户空间(User-Space) 实现所有这些任务,所以没有这些问题。此模型的弊端是,在多核系统上,这些程序通常扩展性较差。这就是为什么他们必须进行优化以 使每个CPU时间片(Cycle)做更多的工作。

一、下载并解压

下载地址:http://pkgs.fedoraproject.org/repo/pkgs/haproxy/

[root@haproxy-server-master ~]# cd /usr/local/src/
[root@haproxy-server-master src]# wget http://pkgs.fedoraproject.org/repo/pkgs/haproxy/haproxy-1.7.9.tar.gz/sha512/d1ed791bc9607dbeabcfc6a1853cf258e28b3a079923b63d3bf97504dd59e64a5f5f44f9da968c23c12b4279e8d45ff3bd39418942ca6f00d9d548c9a0ccfd73/haproxy-1.7.9.tar.gz
[root@haproxy-server-master src]# tar zxvf haproxy-1.7.9.tar.gz

二、安装

[root@haproxy-server-master src]# cd haproxy-1.7.9
[root@haproxy-server-master haproxy-1.7.9]# uname -r
3.10.0-514.el7.x86_64
[root@haproxy-server-master haproxy-1.7.9]# make TARGET=linux310 ARCH=x86_64 PREFIX=/usr/local/haproxy
[root@haproxy-server-master haproxy-1.7.9]# make install PREFIX=/usr/local/haproxy

参数说明:

  • TARGET=linux310,内核版本,使用uname -r查看内核,如:3.10.0-514.el7,此时该参数就为linux310;kernel 大于2.6.28的可以用:TARGET=linux2628;
  • ARCH=x86_64,系统位数;
  • PREFIX=/usr/local/haprpxy #/usr/local/haprpxy,为haprpxy安装路径。

三、添加配置文件

1.79及以后的版本解压后文件内就没有haproxy.cfg文件,所以需要我们自己找个模板写一下。

由于没有配置其他的服务器,这里就简单的添加一个可以让Haproxy启动的配置。

[root@haproxy-server-master haproxy]# mkdir conf
[root@haproxy-server-master haproxy]# ls
conf  doc  sbin  share
[root@haproxy-server-master haproxy]# cd conf/
[root@haproxy-server-master conf]# vim haproxy.cfg

global
        log 127.0.0.1   local0
        maxconn 1000
        daemon

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        timeout connect 5000
        timeout client  50000
        timeout server 50000

listen admin_stats
        bind 0.0.0.0:1080
        mode http
        option httplog
        maxconn 10
        stats refresh 30s
        stats uri /stats
        stats realm XingCloud Haproxy
        stats auth admin:admin
        stats auth  Frank:Frank
        stats hide-version
        stats  admin if TRUE

四、启动haproxy

[root@haproxy-server-master conf]# /usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/conf/haproxy.cfg

验证一下是否启动成功:

[root@haproxy-server-master conf]# lsof -i :1080
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
haproxy 2221 root    3u  IPv4  20285      0t0  TCP *:socks (LISTEN)

五、访问统计页面

地址:http://10.73.150.4:1080/stats

未分类

附:其他问题

六、haproxy记录日志

在配置前,我们先来了解一下日志的level:local0~local7 16~23保留为本地使用:

  • emerg 0 系统不可用;
  • alert 1 必须马上采取行动的事件;
  • crit 2 关键的事件;
  • err 3 错误事件;
  • warning 4 警告事件;
  • notice 5 普通但重要的事件;
  • info 6 有用的信息;
  • debug 7 调试信息。

默认 haproxy 是不记录日志的,为了记录日志还需要配置 syslog 模块,在 linux 下是 rsyslogd 服务。

1、先安装 rsyslog(系统应该都安装了,先查看一下)

[root@haproxy-server-master /]# yum -y install rsyslog

2、添加haproxy的日志配置

[root@haproxy-server-master /]# vim /etc/rsyslog.d/haproxy.conf

$ModLoad imudp
$UDPServerRun 514
local0.* /var/log/haproxy.log

[root@haproxy-server-master /]# ls /etc/rsyslog.d/
haproxy.conf  listen.conf

3、修改 /etc/rsyslog.conf 文件

在#### RULES ####上面一行的地方加入以下内容(文件里应该默认有这个配置,可以看一下):

[root@haproxy-server-master /]# vim /etc/rsyslog.conf

# Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf

4、修改 /etc/sysconfig/rsyslog 文件

把SYSLOGD_OPTIONS=”-m 0”改成 SYSLOGD_OPTIONS=”-r -m 0 -c 2”

[root@haproxy-server-master /]# vim /etc/sysconfig/rsyslog

SYSLOGD_OPTIONS="-r -m 0 -c 2"

相关解释说明:

  • -r:打开接受外来日志消息的功能,其监控514 UDP端口;
  • -x:关闭自动解析对方日志服务器的FQDN信息,这能避免DNS不完整所带来的麻烦;
  • -m:修改syslog的内部mark消息写入间隔时间(0为关闭),例如240为每隔240分钟写入一次”–MARK–”信息;
  • -h:默认情况下,syslog不会发送从远端接受过来的消息到其他主机,而使用该选项,则把该开关打开,所有 接受到的信息都可根据syslog.conf中定义的@主机转发过去。

3、保存,重启 rsyslog 服务

[root@haproxy-server-master /]# systemctl restart rsyslog.service
[root@haproxy-server-master /]# systemctl status rsyslog.service
● rsyslog.service - System Logging Service
   Loaded: loaded (/usr/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: active (running) since 一 2017-11-27 10:51:26 CST; 11s ago
     Docs: man:rsyslogd(8)
           www.rsyslog.com/doc/
 Main PID: 3855 (rsyslogd)
   CGroup: /system.slice/rsyslog.service
           └─3855 /usr/sbin/rsyslogd -n

11月 27 10:51:26 haproxy-server-master systemd[1]: Starting System Logging Service...
11月 27 10:51:26 haproxy-server-master rsyslogd[3855]:  [origin software="rsyslogd" swVersion="8.24.0" x-pid="38...tart
11月 27 10:51:26 haproxy-server-master systemd[1]: Started System Logging Service.
Hint: Some lines were ellipsized, use -l to show in full.

现在你就可以看到日志(/var/log/haproxy.log)了(如果没有,重启一下Haproxy)。

Linux下php-fpm进程过多导致内存耗尽问题解决

当个人博客数据库服务经常突然挂断,造成无法访问时我们能做什么?本篇主题就是记录博主针对这一现象时发现问题,分析问题,最后解决问题的过程。

发现问题

最近,发现个人博客的Linux服务器,数据库服务经常挂掉,导致需要重启,才能正常访问,极其恶心,于是决心开始解决问题,解放我的时间和精力(我可不想经常出问题,然后人工重启,费力费时)。

分析问题

发现问题以后,首先使用free -m指令查看当前服务器执行状况:
未分类
可以看到我的服务器内存是2G的,但是目前可用内存只剩下70M,内存使用率高达92%,很有可能是内存使用率过高导致数据库服务挂断。

继续看详细情况,使用top指令:
未分类
然后再看指令输出结果中详细列出的进程情况,重点关注第10列内存使用占比:
未分类
发现CPU使用率不算高,也排除了CPU的问题,另外可以看到数据库服务占用15.2%的内存,内存使用过高时将会挤掉数据库进程(占用内存最高的进程),导致服务挂断,所以我们需要查看详细内存使用情况,是哪些进程耗费了这么多的内存呢?

使用指令:

ps auxw|head -1;ps auxw|sort -rn -k4|head -40

查看消耗内存最多的前40个进程:
未分类
查看第四列内存使用占比,发现除了mysql数据库服务之外,php-fpm服务池开启了太多子进程,占用超过大半内存,问题找到了,我们开始解决问题:设置控制php-fpm进程池进程数量。

解决问题

通过各种搜索手段,发现可以通过配置pm.max_children属性,控制php-fpm子进程数量,首先,打开php-fpm配置文件,执行指令:

vi /etc/php-fpm.d/www.conf

找到pm.max_children字段,发现其值过大:
未分类
如图,pm.max_children值为50,每一个进程占用1%-2.5%的内存,加起来就耗费大半内存了,所以我们需要将其值调小,博主这里将其设置为25,同时,检查以下两个属性:

  1. pm.max_spare_servers: 该值表示保证空闲进程数最大值,如果空闲进程大于此值,此进行清理
  2. pm.min_spare_servers: 保证空闲进程数最小值,如果空闲进程小于此值,则创建新的子进程;
    这两个值均不能不能大于pm.max_children值,通常设置pm.max_spare_servers值为pm.max_children值的60%-80%。

最后,重启php-fpm

systemctl restart php-fpm

再次查看内存使用情况, 使用内存降低很多:
未分类
之后经过多次观察内存使用情况,发现此次改进后,服务器内存资源消耗得到很大缓解。

linux 下安装 lua 及 lua-cjson

安装 lua

yum -y install libtermcap-devel ncurses-devel libevent-devel readline-devel
wget -c https://www.lua.org/ftp/lua-5.1.4.tar.gz
tar xvzf lua-5.1.4.tar.gz
cd lua-5.1.4
make linux install

安装 lua-cjson

wget -c https://www.kyne.com.au/~mark/software/download/lua-cjson-2.1.0.tar.gz
tar zxvf lua-cjson-2.1.0.tar.gz
cd lua-cjson-2.1.0/
make 
make install

Linux系统 Crontab命令 安装配置使用详细说明

Crontab命令常见于Unix和Linux的操作系统之中,用于设置周期性被执行的指令。该命令从标准输入设备读取指令,并将其存放于“crontab”文件中,以供之后读取和执行。通常,crontab储存的指令被守护进程激活。crond 常常在后台运行,每一分钟检查是否有预定的作业需要执行。这类作业一般称为cron jobs。
未分类

一、安装

yum -y install vixie-cron
yum -y install crontabs

说明:
vixie-cron 软件包是 cron 的主程序;
crontabs 软件包是用来安装、卸装、或列举用来驱动 cron 守护进程的表格的程序。

二、配置

cron 是 linux 的内置服务,但它不自动起来,可以用以下的方法启动、关闭这个服务:

service crond start //启动服务
service crond stop //关闭服务
service crond restart //重启服务
service crond reload //重新载入配置
service crond status //查看crontab服务状态

在CentOS系统中加入开机自动启动:

chkconfig –level 345 crond on

列子:

01 * * * * root run-parts /etc/cron.hourly
02 4 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly

三、Crontab文件的格式:

minute:分,值为0-59
hour:小时,值为1-23
day:天,值为1-31
month:月,值为1-12
weekday:星期,值为0-6(0代表星期天,1代表星期一,以此类推)
username:要执行程序的用户,一般设置为root
command:要执行的程序路径(设置为绝对路径)例如:/home/cunlz.org/cunlz.sh

root身份登录到命令行

输入crontab -e

按下a键进入到编辑模式

输入 执行代码,例如:

0 3 */7 * * /bin/certbot renew –renew-hook “/etc/init.d/nginx reload”

同时按下ctrl+c退出编辑模式

按下shift+: 输入wq 退出 crontab

附:crontab规则详细实例

1、每天6:00执行

0 6 * * * root /home/cunlz.org/cunlz.sh

2、每周六凌晨4:00执行

0 4 * * 6 root /home/cunlz.org/cunlz.sh

3、每周六凌晨4:25执行

25 4 * * 6 root /home/cunlz.org/cunlz.sh

4、每周一到周五的11:41开始,每隔10分钟执行一次

41,51 11 * * 1-5   root /home/cunlz.org/cunlz.sh
1-59/10 12-23 * * 1-5   root /cunlz.org/cunlz.sh

5、在每天的10:31开始,每隔2小时重复一次

31 10-23/2 * * * root   /cunlz.org/cunlz.sh

6、每天15:00执行

0 15 * * *  root /home/cunlz.org/cunlz.sh

linux 防御SYN攻击

一、默认syn配置

sysctl -a | grep _syn
net.ipv4.tcp_max_syn_backlog = 1024
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_synack_retries = 5
net.ipv4.tcp_syn_retries = 5

tcp_max_syn_backlog 是SYN队列的长度,加大SYN队列长度可以容纳更多等待连接的网络连接数。 tcp_syncookies是一个开关,是否打开SYN Cookie 功能,该功能可以防止部分SYN攻击。 tcp_synack_retries和tcp_syn_retries定义SYN 的重试连接次数,将默认的参数减小来控制SYN连接次数的尽量少。

二、修改syn配置

ulimit -HSn 65535
sysctl -w net.ipv4.tcp_max_syn_backlog=2048
sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_synack_retries=2
sysctl -w net.ipv4.tcp_syn_retries=2

三、添加防火墙规则

#Syn 洪水攻击(--limit 1/s 限制syn并发数每秒1次)
iptables -A INPUT -p tcp --syn -m limit --limit 1/s -j ACCEPT
#防端口扫描
iptables -A FORWARD -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s -j ACCEPT
#防洪水ping
iptables -A FORWARD -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPT

四、添加开机启动

最后别忘记将二、三、里面的命令写到/etc/rc.d/rc.local

Linux传输超大文件

linux下的文件传输,大家首先会想到rsync、scp之类的工具,但这类工具有一个特点——慢,因为这类工具都是加密传输,发送端加密,接收端解密,当我们传输一些非敏感文件的时候,完全可以不加密,直接在网络上传输。
直接上实例,传输一个2077M的ISO文件。

nc发送接收数据

接收端:

nc -l 45.55.0.86 9999 > jieshou.iso

➤ -l :监听一个端口来接收数据
➤ -u : 不使用 TCP 而是使用 UDP 来进行数据连接(应该速度更快,没试)
整条命令的意思:本地开启9999端口来接收数据,把接收到的数据存到“jieshou.iso”文件里面。

发送端:

time nc  45.55.0.86 9999 < CentOS-6.9-x86_64-bin-DVD2.iso

命令最前面的time是用来检测该命令运行耗时的。
未分类
24秒就在公网上传完了一个2077M的文件,平均速度高达87M/s,传输完毕后在两端校验MD5,发现文件完全一致。
用nc传输有两个特点:
➤速度快
➤传输简单,不需要登录对方服务器,不需要验证信息。

nc进度显示

若你文件实在太大,想看到传输进度,用PV

yum install epel-release -y
yum install pv -y
cat CentOS-6.9-x86_64-bin-DVD2.iso |pv -b | nc  45.55.0.86 9999

传输目录

接收端:

nc -l 45.55.0.86 9999 | pv -b > home.tar.gz

发送端:

tar -czf - /home/ | nc  45.55.0.86 9999

中转文件

A、B、C三台主机,A美国,C昌南,C只能访问到B,不能直接访问A,B和AC互通。C要怎么才能拿到A上的文件呢?
C上执行:

nc -l 9999 > google_file.txt

B上执行:

nc -l 9999 | nc (C的外网IP) 9999

A上执行:

nc (B的外网IP) 9999 < google_file.txt

Linux下通过受限bash创建指定权限的账号

在日常业务运维中,有时为了配合解决问题,需要给非运维人员开通系统账号,用于查询日志或代码。通常为了系统安全或避免不必要的误操作等目的,会将账号权限降至最低。下面介绍下在Linux下通过受限bash创建指定权限账号的操作记录:

[root@mq-server ~]# ln -s /bin/bash  /bin/rbash
[root@mq-server ~]# useradd -s /bin/rbash wangshibo
[root@mq-server ~]# passwd wangshibo
[root@mq-server ~]# mkdir /home/wangshibo/bin
[root@mq-server ~]# chown root. /home/wangshibo/.bash_profile
[root@mq-server ~]# chmod 755 /home/wangshibo/.bash_profile
[root@mq-server ~]# vim /home/wangshibo/.bash_profile       //复制下面的内容覆盖原内容
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$HOME/bin

export PATH<br data-filtered="filtered">
[root@mq-server ~]# ln -s /bin/cat /home/wangshibo/bin/cat
[root@mq-server ~]# ll /home/wangshibo/
total 4
drwxr-xr-x 2 root root 4096 Nov 25 23:38 bin
[root@mq-server ~]# ll /home/wangshibo/bin/
total 0
lrwxrwxrwx 1 root root 8 Nov 25 23:12 cat -> /bin/cat

如上设置后,可以发现创建的wangshibo用户家目录下的文件权限是root.root,上面只设置了wangshibo用户的cat权限,并且只能cat查看wangshibo用户家目录/home/wangshibo下的文件。除了cat命令外。不能执行其他命令!

[wangshibo@mq-server ~]$ cat /var/log/messages
cat: /var/log/messages: Permission denied
[wangshibo@mq-server ~]$ ls
-rbash: /home/wangshibo/bin/ls: No such file or directory
[wangshibo@mq-server ~]$ touch test
-rbash: /home/wangshibo/bin/touch: No such file or directory

如果要想在其家目录下有其他命令的执行权,那么需要添加这些命令的软链接到/home/wangshibo/bin目录下(可以通过which命令查看二进制命令的全路径)

[root@mq-server ~]# ln -s /bin/ls /home/wangshibo/bin
[root@mq-server ~]# ln -s /bin/touch /home/wangshibo/bin
[root@mq-server ~]# ln -s /bin/mkdir /home/wangshibo/bin
[root@mq-server ~]# ln -s /usr/bin/vim /home/wangshibo/bin/
[root@mq-server ~]# ll /home/wangshibo/bin/
total 0
lrwxrwxrwx 1 root root  8 Nov 25 23:12 cat -> /bin/cat
lrwxrwxrwx 1 root root  7 Nov 25 23:44 ls -> /bin/ls
lrwxrwxrwx 1 root root 10 Nov 25 23:45 mkdir -> /bin/mkdir
lrwxrwxrwx 1 root root 10 Nov 25 23:44 touch -> /bin/touch
lrwxrwxrwx 1 root root 12 Nov 25 23:45 vim -> /usr/bin/vim

这样,wangshibo用户就拥有了上面加入的命令的执行权

[root@mq-server ~]# su - wangshibo
[wangshibo@mq-server ~]$ ls
bin
[wangshibo@mq-server ~]$ touch test
[wangshibo@mq-server ~]$ mkdir ops
[wangshibo@mq-server ~]$ vim test
[wangshibo@mq-server ~]$ cat test
dsfdsafsadf
[wangshibo@mq-server ~]$ rm -f test
-rbash: rm: command not found
[wangshibo@mq-server ~]$ ls /usr/
bin  etc  games  include  lib  lib64  libexec  local  sbin  share  src  tmp
[wangshibo@mq-server ~]$ cat /var/log/messages
cat: /var/log/messages: Permission denied