python运维实战--LVM创建和在线扩容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python运维实战--LVM创建和在线扩容相关的知识,希望对你有一定的参考价值。

python运维实战--LVM创建和在线扩容

LVM有关概念和操作

说明??:有关LVM详细概念,请各位大佬自行百度,谷歌。。这里不做重点介绍。

这个python脚本能做什么

创建LVM

  • 指定具体磁盘进行分区,这里定义分区号1
  • 刷新分区,不需要reboot系统
  • 创建pv
  • 创建vg
  • 创建lv
  • 格式化,ext4/xfs
  • 创建挂载目录
  • 将文件系统信息写到 /etc/fstab
  • 使用 mount -a 自动挂载

在线扩容vg/lv

  • 磁盘分区
  • 刷新分区信息
  • 创建pv
  • 在线扩容vg
  • 在线扩容lv
  • 扩容后容量刷新

python 脚本信息

#!/usr/bin/env python
# coding=utf-8

__author__ = "wutengfei"
__email__ = "[email protected]"
__status__ = "Production"
__version__ = "1.0"

from optparse import OptionParser
from subprocess import Popen, call, PIPE
from shlex import split
from commands import getstatusoutput
from os import mkdir
from os.path import basename , normpath
import time

parser = OptionParser()
parser.add_option(‘-d‘, ‘--drive‘, dest=‘drive‘, help=‘this is the name of the drive like sda, hdd etc..‘)
parser.add_option(‘-f‘, ‘--folder‘, dest=‘folder‘, help=‘this is the name of the directory like /data or /var/log‘)
parser.add_option(‘-t‘, ‘--fstype‘, dest=‘fstype‘, help=‘this is the type of filesystem you need like ext4 or xfs‘)
(opts,args) = parser.parse_args()

class FormatDriver(object):
    """
    This is a class that does end to end create partition, deal with lvm, make filesystem, extend filesystem, write to fstab and resize filesystem
    """
    def __init__(self,drive,folder,fstype):
        self.drive = str(drive)
        self.folder = str(folder)
        self.fstype = str(fstype)

    def fdisk(self):
        """
        this is a definition to perform fdisk the drive in the argument
        """
        before_pipe_cmd = ‘echo -e "n
p
1


t\n8e
w"‘
        before_pipe_args = split(before_pipe_cmd)
        after_pipe_cmd = "fdisk /dev/%s" % self.drive
        after_pipe_args = split(after_pipe_cmd)
        p1 = Popen(before_pipe_args, stdout=PIPE)
        p2 = call(after_pipe_args, stdin=p1.stdout)

    def partprobe(self):
        """
        this function performs the partprobe
        """
        pprobe = "partprobe"
        pprobe1 = split(pprobe)
        part = call(pprobe1)

    def pvcreate(self):
        """
        This function creates the physical volume
        """
        pvcreate = call(["pvcreate", "/dev/%s1" %self.drive])

    def volgroup(self):
        """
        This function creates the physical volume and also created the volume group
        """
        vgcreate = ‘vgcreate -v vg_%s /dev/%s1‘ % (basename(normpath(self.folder)), self.drive)
        status, output = getstatusoutput(vgcreate)

    def lvm(self):
        """
        This function creates the logical volume
        """
        lvcreate = ‘lvcreate -v -l "100%FREE" -n lv_{0} vg_{1}‘.format(basename(normpath(self.folder)),
                                                                       basename(normpath(self.folder)))
        status, output = getstatusoutput(lvcreate)
        print status
        print output

    def makefs(self):
        ‘‘‘This functions creates the filesystem on the /dev/mapper LVM device‘‘‘
        if self.fstype == ‘ext4‘:
            mkfs = call(["mkfs.ext4", "/dev/mapper/vg_%s-lv_%s" % (
            basename(normpath(self.folder)), basename(normpath(self.folder)))])
        elif self.fstype == ‘xfs‘:
            mkfs = call(["mkfs.xfs", "/dev/mapper/vg_%s-lv_%s" % (
            basename(normpath(self.folder)), basename(normpath(self.folder)))])

    def makedir(self):
        ‘‘‘This function makes directory inthe /root level‘‘‘
        path = "%s" % self.folder
        mkdir(path, 0755)
        print ‘%s is created‘ % path

    def write_to_fstab(self):
        ‘‘‘This function appends the filesystem info to the /etc/fstab‘‘‘
        if self.fstype == ‘ext4‘:
            string = ‘/dev/mapper/vg_%s-lv_%s     %s           ext4    defaults        1 1‘ % (
            basename(normpath(self.folder)), basename(normpath(self.folder)), self.folder)
            f = open("/etc/fstab", ‘a‘)
            f.write(string + "
")
            f.close()
        elif self.fstype == ‘xfs‘:
            string = ‘/dev/mapper/vg_%s-lv_%s     %s           xfs    defaults        1 1‘ % (
            basename(normpath(self.folder)), basename(normpath(self.folder)), self.folder)
            f = open("/etc/fstab", ‘a‘)
            f.write(string + "
")
            f.close()

    def filesystem_mount(self):
        ‘‘‘This is a simple function to mount all the drive‘‘‘
        fsmount = ‘mount -a‘
        status, output = getstatusoutput(fsmount)

    def resizefs(self):
        ‘‘‘ This method is to resize an existing filesystem‘‘‘
        if self.fstype == ‘ext4‘:
            rs = ‘resize2fs /dev/vg_%s/lv_%s‘ % (basename(normpath(self.folder)), basename(normpath(self.folder)))
            status, output = getstatusoutput(rs)
        elif self.fstype == ‘xfs‘:
            rs = ‘xfs_growfs /dev/vg_%s/lv_%s‘ % (basename(normpath(self.folder)), basename(normpath(self.folder)))
            status, output = getstatusoutput(rs)

    def extend_vg(self):
        ‘‘‘Extending volume group‘‘‘
        vgextend = ‘vgextend vg_%s /dev/%s1‘ % (basename(normpath(self.folder)), self.drive)
        status, output = getstatusoutput(vgextend)

    def extend_lv(self):
        ‘‘‘Extending logical volume‘‘‘
        lvextend = call(["lvextend", "-l", "+100%FREE",
                         "/dev/vg_%s/lv_%s" % (basename(normpath(self.folder)), basename(normpath(self.folder)))])

def main():
    x = FormatDriver(opts.drive, opts.folder, opts.fstype)
    intake = raw_input("Do you want to extend of create a new filesystem ? please enter ‘extend‘ or ‘create‘:")
    if intake == ‘create‘:
        print "a new drive has been created"
        x.fdisk()
        x.partprobe()
        x.pvcreate()
        time.sleep(5)
        x.volgroup()
        time.sleep(5)
        x.lvm()
        x.makefs()
        x.makedir()
        x.write_to_fstab()
        x.filesystem_mount()
    elif intake == ‘extend‘:
        print "a drive has been extended"
        x.fdisk()
        x.partprobe()
        x.pvcreate()
        x.extend_vg()
        x.extend_lv()
        x.resizefs()

if __name__ == ‘__main__‘:
    if opts.drive == None or opts.folder == None or opts.fstype == None:
        parser.print_help()
        exit(-1)

main()
print ‘The root folder is %s‘ % opts.folder
print ‘the drive is %s‘ % opts.drive
print ‘The fstype is %s‘ % opts.fstype

脚本执行情况

实战创建LVM

# python test.py -d sdb -f /data1 -t ext4
Do you want to extend of create a new filesystem ? please enter ‘extend‘ or ‘create‘:create
a new drive has been created
欢迎使用 fdisk (util-linux 2.23.2)。
....
/data1 is created
The root folder is /data1
the drive is sdb
The fstype is ext4

说明??:如果执行脚本时不使用任何参数,则会提示帮助信息,如:

# python test.py 
Usage: test.py [options]

Options:
  -h, --help            show this help message and exit
  -d DRIVE, --drive=DRIVE
                        this is the name of the drive like sda, hdd etc..
  -f FOLDER, --folder=FOLDER
                        this is the name of the directory like /data or
                        /var/log
  -t FSTYPE, --fstype=FSTYPE
                        this is the type of filesystem you need like ext4 or
                        xfs

以上是关于python运维实战--LVM创建和在线扩容的主要内容,如果未能解决你的问题,请参考以下文章

RedHat 6 创建和扩容LVM卷

CentOS7下的lvm(逻辑卷)在线扩容

CentOS 7.6在线扩容xfs文件系统(创建大于2T的磁盘分区并使用LVM管理)

CentOS 7.6在线扩容xfs文件系统(创建大于2T的磁盘分区并使用LVM管理)

LVM逻辑卷管理--在线扩容逻辑卷与卷组容量缩减逻辑卷快照

centos7在线扩容根分区LVM