Saturday, September 16, 2017

Resize Physical Partition on LVM




Resizing physical LVM partition is a bit painful and requires few steps:
1) Resize the physical partition
2) Resize the physical volume
3) Resize the logical volume
4) Resize the filesystem (e.g. ext4 filesystem)

Take this example: assuming the primary partitions have been filled up to 4, if the total HD capacity is expanded from 100 GB to 150 GB, there will be no way to attach more partition to the LVM group: 

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1026047      512000   83  Linux      (488 MiB)
/dev/sda2         1026048    41943039    20458496   8e  Linux LVM  (19.5 GiB)
/dev/sda3        41943040    83886079    20971520   8e  Linux LVM  (20 GiB)
/dev/sda4        83886080   209715199    62914560   8e  Linux LVM  (60 GiB) 

If we want to resize /dev/sda4 from 60 GB to 100 GB or max available new space, usually we can perform it with standard "parted" utility.

But on LVM, this throws error "Could not detect file system"

# parted /dev/sda
GNU Parted 2.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print free                                                      
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 150GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End       Size    Type     File system  Flags
        32.3kB  1049kB    1016kB           Free Space
 1      1049kB  525MB     524MB   primary  ext4         boot
 2      525MB   21.5GB    20.9GB  primary               lvm
 3      21.5GB  42.9GB    21.5GB  primary               lvm
 4      42.9GB  107.37GB  64.4GB  primary               lvm

(parted)                                                  
(parted) resize 4 42.9GB 100GB
WARNING: you are attempting to use parted to operate on (resize) a file system.
parted's file system manipulation code is not as robust as what you'll find in
dedicated, file-system-specific packages like e2fsprogs.  We recommend
you use parted only to manipulate partition tables, whenever possible.
Support for performing most operations on most types of file systems
will be removed in an upcoming release.
Error: Could not detect file system.
(parted) check 4                                                         
WARNING: you are attempting to use parted to operate on (check) a file system.
parted's file system manipulation code is not as robust as what you'll find in
dedicated, file-system-specific packages like e2fsprogs.  We recommend
you use parted only to manipulate partition tables, whenever possible.
Support for performing most operations on most types of file systems
will be removed in an upcoming release.
Error: Could not detect file system.   
(parted) quit                                                            
#

So, here is the tricky part where we need to use fdisk to delete and re-create back the partition.

It may sounds scary when performing deletion, but if we do it "right" by re-creating it with exactly the same parameters on the "start sector" and "partition type", we should not lose any data when doing the "delete and create"

Follow the below steps to perform the resize.

If you execute the commands thru ssh, it is strongly recommended that you use "screen" session to prevent your active process from getting terminated by the disconnected shell during network interruption. Or else unrecoverable corruption may occur when the ssh session gets disconnected by network issues.

For more info about "screen", you can search some tutorials on internet with keywords like "linux screen session"

- http://aperiodic.net/screen/quick_reference
- https://www.howtoforge.com/linux_screen
- https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/
- https://www.linode.com/docs/networking/ssh/using-gnu-screen-to-manage-persistent-terminal-sessions


Step 1: Resize the physical partition


Before start doing any modification on the partition, ensure the existing filesystem to be resized has been unmounted first.

Start fdisk and use command 'u' to switch to sector mode.

IMPORTANT:

- Don't forget use command 'u' to switch to sector mode
- Don't perform write or commit ('w') during deletion and creation of the partition
- Only perform write or commit ('w') after the partition has been re-created correctly on the "start sector" and "partition type (8e)"
- If you feel that you do something wrong in the middle and want to redo from beginning, press ctrl-C and rerun "fdisk" (as long as you do not perform write or commit "w", there should be nothing change against your harddisk partitions)

(i) Start fdisk and use command 'u' to switch to sector mode.


# fdisk /dev/sda

WARNING: DOS-compatible mode is deprecated. It's strongly recommended to
         switch off the mode (command 'c') and change display units to
         sectors (command 'u').

Command (m for help): u
Changing display/entry units to sectors

(ii) Write down the start sector and partition id on /dev/sda4 (or better copy the whole line to somewhere on notepad before start deleting it)


Command (m for help): p

Disk /dev/sda: 150.3 GB, 150323855360 bytes
64 heads, 32 sectors/track, 143360 cylinders, total 293601280 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 identifier: 0x00076ede

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1026047      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2         1026048    41943039    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.
/dev/sda3        41943040    83886079    20971520   8e  Linux LVM
/dev/sda4        83886080   209715199    62914560   8e  Linux LVM

Command (m for help):


After this, keep in mind that the partition layout before and after must look like this:

Before:
/dev/sda4        83886080   209715199    62914560   8e  Linux LVM

After:
/dev/sda4        83886080   [new value]  [new value] 8e  Linux LVM

(iii) Now, here we go: delete and recreate the partition with the start sector that we had noted it down previously

Delete the /dev/sda4:

Command (m for help): d
Partition number (1-4): 4
Command (m for help): 

Once it is deleted, the /dev/sda4 should be gone now:

Command (m for help): p

Disk /dev/sda: 150.3 GB, 150323855360 bytes
64 heads, 32 sectors/track, 143360 cylinders, total 293601280 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 identifier: 0x00076ede

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1026047      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2         1026048    41943039    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.
/dev/sda3        41943040    83886079    20971520   8e  Linux LVM

Command (m for help):

Create back the /dev/sda4:

Command (m for help): n
Command action
   e   extended
   p   primary partition (1-4)
p
Selected partition 4
First sector (32-293601279, default 32): 83886080
Last sector, +sectors or +size{K,M,G} (83886080-293601279, default 293601279):
Using default value 293601279

Command (m for help):


Once it is created back, the /dev/sda4 would be visible again with the new parameter on the "End", "Blocks", and "Id":

Command (m for help): p

Disk /dev/sda: 150.3 GB, 150323855360 bytes
64 heads, 32 sectors/track, 143360 cylinders, total 293601280 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 identifier: 0x00076ede

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1026047      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2         1026048    41943039    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.
/dev/sda3        41943040    83886079    20971520   8e  Linux LVM
/dev/sda4        83886080   293601279   104857600   83  Linux

Command (m for help):


Change back the partition id from 83 to 8e

Command (m for help): t
Partition number (1-4): 4
Hex code (type L to list codes): 8e

Command (m for help):

(iv) Double-check the "recreated" new partition and ensure all are the same except the size that has changed on the "End" sector and "Block" sector


Command (m for help): p

Disk /dev/sda: 150.3 GB, 150323855360 bytes
64 heads, 32 sectors/track, 143360 cylinders, total 293601280 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 identifier: 0x00076ede

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     1026047      512000   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2         1026048    41943039    20458496   8e  Linux LVM
Partition 2 does not end on cylinder boundary.
/dev/sda3        41943040    83886079    20971520   8e  Linux LVM
/dev/sda4        83886080   293601279   104857600   8e  Linux

Command (m for help):

Verify all are correct with respect to the previous partition layout, except the "End" and "Blocks" column:

Before:
/dev/sda4        83886080   209715199    62914560   8e  Linux LVM

After:
/dev/sda4        83886080   293601279    104857600  8e  Linux LVM

(v) Once it looks ok, then commit

Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.
#

(vi) Perform "partprobe" or reboot to refresh the partition table

# partprobe
# init 6


Step 2: Resize the physical volume


If all sub-steps on step #1 have been done successfully, the following and next step will be very simple.

To resize the LVM's physical volume, run "pvresize". This will automatically resize the physical volume to the maximum allocated physical partition

# pvresize /dev/sda4
  Physical volume "/dev/sda4" changed
  1 physical volume(s) resized / 0 physical volume(s) not resized


Step 3: Resize the logical volume


Use this simple command to resize the logical volume:

# lvresize -l +100%FREE /dev/vg00/lvol4


Step 4: Resize the filesystem


For ext4 filesystem, use this command:

# resize2fs -p /dev/mapper/vg00-lvol4

If it complains to run e2fsck, then execute this command:

# e2fsck -ff /dev/mapper/vg00-lvol4


Done, remount and verify the newly resized filesystem


What a nice solution. If you are a programmer savvy, you can also make a script or app to perform string parsing to those text outputs and provide interaction thru UI or CLI.

Linux and open source give freedom to everyone who possesses knowledge and capabilities to leverage their skills and competencies in solving problem and delivering solutions.

Unlike proprietary software like Microsoft or Apple who rely on trade secret to disclose its limitation, in open source world everything is transparent and customizable. The only things can limit the freedom of software is the hardware and infrastructure. Free software, means freedom of software. Open source, means open society :)


Wednesday, July 15, 2015

Windows Scripting with Ruby


Windows world is full of clicks. For some people, this is a nightmare.

While others may try to use batch file to automate, batch itself is too awkward and ancient with very limited capabilities.

There is Windows Powershell to allow more scripting, but for some people, powershell is still "not good enough" (or read: syntaces are too dirty and messy) compared to other popular script languages like Python, Ruby or Groovy.

Below is an example install script written with Ruby to perform simple file copies and eliminate the needs of writing Powershell:
  1. Delete or backup files if previous installation is detected
  2. Copy files from source to destination
  3. Perform Windows registry setup
  4. Perform auto-reboot if certain files cannot be copied due to file locking by other Windows process

install_program.rb
require 'fileutils'

$REBOOT_ON_ERROR = true #Change to false if we don't want to auto-reboot upon exception error (e.g. during debugging)
$INSTALL_RETRY_BAT = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup\installretry.bat' #Startup location on Windows 7
$IS_RESUMING = File.exist?( $INSTALL_RETRY_BAT )

def copy_files
    _TARGET_FOLDER = 'C:\MyApp\RubyApp'
    FileUtils.mv(_TARGET_FOLDER, "#{_TARGET_FOLDER}_#{Time.now.strftime "%Y-%m-%d_%H-%M-%S"}") if (Dir.exist? _TARGET_FOLDER) #Make backup instead of overwriting it
    FileUtils::mkdir_p(_TARGET_FOLDER)
    FileUtils.cp_r(".\\RubyAppSource\\", "#{_TARGET_FOLDER}")
end

def configure_windows
    system( "net stop \"Windows Time\" /y 2>&1" )
    2.times do #Handle Windows bug (https://whiskykilo.com/w32tm-or-w32time-or-whatever-ms-wants-to-call-it/)
        system( "w32tm /unregister >nul 2>&1" ) 
        system( "w32tm /unregister >nul 2>&1" ) 
        system( "w32tm /register >nul 2>&1" )
    end
    system( "reg add \"HKLM\\SYSTEM\\CurrentControlSet\\services\\W32Time\\TimeProviders\\NtpServer\" /v Enabled /t REG_DWORD /d 1 /f 2>&1" )
    system( "reg add \"HKLM\\SYSTEM\\CurrentControlSet\\services\\W32Time\\Config\" /v AnnounceFlags /t REG_DWORD /d 5 /f 2>&1" )
    system( "net start \"Windows Time\" /y 2>&1" )
    system( "w32tm /config /update 2>&1" )
end

def show_retry_if_it_is_executed_from_installretry_bat
    if $IS_RESUMING
        puts "*** Retrying installation after previous error and reboot ***" 
        sleep 10
    end
end

def do_auto_reboot_and_retry
    if $REBOOT_ON_ERROR == true and !$IS_RESUMING
        puts "Script engine is trying to perform reboot on error now..."
        File.open( $INSTALL_RETRY_BAT, "w" ) { |file| file.write( File.expand_path($0).gsub('/', '\\') ) }
        system "shutdown /f /r /t 1 2>&1" 
    else
        ( puts "Fatal error, still unable to complete installation after the reboot" ) if $IS_RESUMING
    end
end

if (__FILE__ == $0)
    begin
        show_retry_if_it_is_executed_from_installretry_bat()
        copy_files()
        configure_windows()
        puts "Installation done"
    rescue => e
        do_auto_reboot_and_retry() #in case some files or folders are locked and require reboot during copy_files()
    ensure
        ( FileUtils.rm( $INSTALL_RETRY_BAT ) rescue nil ) if $IS_RESUMING #Ensure we resume only ONCE, not repeatedly
        puts "Press ENTER to exit"
        $stdin.gets
    end
end

That's it.
We don't need fancy tool like WiX or InstallShield. Just fire the text editor and then run it.

And if we want to call WinAPI, we can use FFI or Win32API for it

This is an example on how to fire Visual Studio COM automation using WIN32OLE:
require 'win32ole'

_MY_SOLUTION_SLN='D:/myvisualstudio_projects/project1/solution1.sln'
_dte = WIN32OLE.new('VisualStudio.DTE.12.0') rescue WIN32OLE.new('VisualStudio.DTE.10.0') rescue raise "Cannot find Visual Studio 2010 nor 2013"
_vs_version = _dte.RegistryRoot[-4..-1] rescue ""
puts "\r\nDetected Visual Studio version: #{_vs_version}"

_dte.SuppressUI = false
_mainWindow = _dte.MainWindow
_mainWindow.Visible = true
_mainWindow.WindowState = 2 #maximize
#_mainWindow.WindowState = 0 #restore
#_mainWindow.WindowState = 1 #minimize

_sln = _dte.Solution
_sln.Open("#{_MY_SOLUTION_SLN}") 

Happy scripting with Ruby :)

Friday, November 7, 2014

Ruby Language as alternative to Powershell for Windows Scripting


Powershell is an enhanced version of DOS batch scripting.

It is much much more "powerful" than DOS batch, but "not powerful enough" in compared to the Unix/Linux scripting world (e.g. Bash, Python, Ruby, Perl, etc)

But because Powershell is installed by default in every Windows platform, people normally will opt to it, compared to using other better ones.

For people who have already been used to Linux scripting, Powershell syntax may look more dirty and messy, at the expense of getting "small improvement" compared to those other scripting languages (I know people who stand at Microsoft side will shout me on my rant about "small improvement" :-P)

On the other hands, getting scripts like Perl, Bash, or Python to work on Windows, need certain efforts on the installation steps and make us "inconvenience" to deploy it.

To minimize this kind of "inconvenience", we can make use of batch script to allow "one-time-click" process on deploying the scripts.

I use Ruby as an example below because it has been my favorite scripting language over the past seven years.


install.bat

@echo off
cls
NET FILE 1>NUL 2>NUL
IF NOT '%errorlevel%' == '0' (
    echo.
    echo ERROR: This script needs be run as admin
    echo Please rerun by doing right click and choose "Run as administrator"
    echo.
    pause
    exit
)
pushd "%~dp0"
 
echo Ruby engine installer
set args="[%*]"
IF "%args:silent=%" == "%args%" (pause)
start /wait taskkill /F /im ruby.exe >nul 2>&1
 
IF EXIST "C:\ruby\bin\ruby.exe" (
    powershell.exe "gem list | %%{$_.split(' ')[0]} | ? {$_ -notmatch 'test-unit|rdoc|psych|minitest|io-console|rake|bigdecimal|json'} | %%{gem uninstall -Iax $_ }" 2>&1 1>nul
)
.\rubygem\rubyinstaller-2.1.4.exe /silent /dir="C:\ruby" /tasks="addtk,assocfiles,modpath"
call C:\ruby\bin\setrbvars.bat
 
echo Performing the rest of installation from Ruby script... (in case you do hate Powershell)
call ruby .\post_install.rb %*
 
call gem install --local .\rubygem\ffi-1.9.6-x86-mingw32.gem 2>&1 1>nul
call gem install --local .\rubygem\win32-service-0.8.6.gem
call gem install --local .\rubygem\tins-1.3.3.gem 2>&1 1>nul
call gem install --local .\rubygem\term-ansicolor-1.3.0.gem 2>&1 1>nul
call gem install --local .\rubygem\ocra-1.3.3.gem 2>&1 1>nul
call gem install --local .\rubygem\rubyzip-1.1.6.gem 2>&1 1>nul
 
call gem install --local .\rubygem\win32-api-1.5.2-universal-mingw32.gem 2>&1 1>nul
call gem install --local .\rubygem\windows-api-0.4.3.gem 2>&1 1>nul
call gem install --local .\rubygem\windows-pr-1.2.4.gem 2>&1 1>nul
call gem install --local .\rubygem\serialport-1.3.1-x86-mingw32.gem 2>&1 1>nul
 
popd
echo.
echo Done.
IF "%args:silent=%" == "%args%" (pause)

That's it.

In the above script, you will notice powershell command that is used to remove the existing gem. If you are a Linux fanatics and hate to include even a single piece of powershell syntax, you can move that line to the post_install.rb script and perform system("gem uninstall -Iax #{gemname}") from there.