Skip to content

Instantly share code, notes, and snippets.

@vgerak
Last active January 4, 2016 00:29
Show Gist options
  • Save vgerak/8542354 to your computer and use it in GitHub Desktop.
Save vgerak/8542354 to your computer and use it in GitHub Desktop.
VM Disk size
from bundle_volume import *
def _read_fstable(f):
"""Use this generator to iterate over the lines of and fstab file"""
if not os.path.isfile(f):
raise FatalError("Unable to open: `%s'. File is missing." % f)
FileSystemTableEntry = namedtuple('FileSystemTableEntry',
'dev mpoint fs opts freq passno')
with open(f) as table:
for line in iter(table):
entry = line.split('#')[0].strip().split()
if len(entry) != 6:
continue
yield FileSystemTableEntry(*entry)
for entry in _read_fstable('/etc/fstab'):
if entry.mpoint =='/':
root = entry.dev #root = "UUID=53966d11-b4b3-480b-aeb5-3a121308d25b"
Partition = namedtuple('Partition', 'num start end type fs')
partitions = []
for p in disk.partitions:
num = p.number
start = p.geometry.start
end = p.geometry.end
ptype = p.type
fs = p.fileSystem.type if p.fileSystem is not None else ''
partitions.append(Partition(num, start, end, ptype, fs))
print partitions # [Partition(num=1, start=2048L, end=41940991L, type=0L, fs='ext4')]
root = findfs(root).stdout.strip() #root = '/dev/vda1'
disk_file = re.split('[0-9]', root)[0]
device = parted.Device(disk_file)
the_disk = parted.Disk(device)
size = the_disk.device.length * the_disk.device.sectorSize
print size, type(size) # 21474836480L
print free_space("/"), type(free_space("/")) # 11291127808
print free_space("/") < size # True
stat = os.statvfs("/")
# Shrink the last partition. The new size should be the size of the
# occupied blocks
blcks = stat.f_blocks - stat.f_bavail
new_size = (blcks * stat.f_frsize) // 512 # self.disk.device.sectorSize
# Add 10% just to be on the safe side
part_end = last.start + (new_size * 11) // 10
# Align to 2048
part_end = ((part_end + 2047) // 2048) * 2048
size = (part_end + 1) * 512
print size, type(size) # 10830742016L
print free_space("/"), type(free_space("/")) # 11291127808
print free_space("/") < size # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment