tolvmxfs/activate.rb

87 lines
2.0 KiB
Ruby
Executable File

#!/usr/bin/env ruby
require 'pathname'
$: << Pathname.new($0).expand_path.dirname+'lib'
require 'base'
require 'active_support/all'
require 'json'
class Tivate < Base
def initialize
super
sh.alias_command :lsblk_json, *%w[lsblk --json --fs], return: :string
end
def listing *devices, reverse: nil, only_fs: nil, &exe
return to_enum( __method__, *devices, reverse: reverse, only_fs: only_fs) unless block_given?
return nil if devices.empty?
reverse = false if reverse.nil?
only_fs = false if only_fs.nil?
l =
lambda do |e|
case e['fstype']
when 'LVM2_member'
e[:isfs] = false
yield e if not only_fs and not reverse
(e['children']||[]).each &l
yield e if not only_fs and reverse
when *%w[ext2 ext3 ext4 xfs]
e[:isfs] = true
yield e
end
end
devices.each do |dev|
if dev.exist?
data = JSON.parse sh.lsblk_json( dev)
data['blockdevices'].each &l
end
end
end
end
cmd = Pathname.new $0
case ARGV[0]
when '-h', '--help'
puts <<EOF
Usage: activate.rb -h | image # provides all filesystem of an image as devices
deactivate.rb -h | image # umounts and deprovitions devices
EOF
end
image = Pathname.new ARGV[0]
case cmd.basename( '.rb').to_s.downcase.to_sym
when :activate
Tivate.run do
raise "Image «#{image}» does not exist" unless image.exist?
devs = kpartx image
listing *devs do |dev|
if 'LVM2_member' == dev['fstype']
vgname = get_vgname_of_pv( "/dev/mapper/#{dev['name']}").to_a[0]
sh.vgchange -:ay, vgname, return: :string
end
end
listing *devs do |dev|
if dev[:isfs]
puts "/dev/mapper/#{dev['name']}"
end
end
end
when :deactivate
Tivate.run do
raise "Image «#{image}» does not exist" unless image.exist?
devs = lpartx image
listing *devs, reverse: true do |dev|
sh.umount dev['mountpoint'] if dev['mountpoint']
if 'LVM2_member' == dev['fstype']
vgname = get_vgname_of_pv( "/dev/mapper/#{dev['name']}").to_a[0]
sh.vgchange -:an, vgname
end
end
departx image
end
else
raise "activate or deactivate?"
end