Skip to content

Instantly share code, notes, and snippets.

@0xa
Created October 11, 2016 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xa/43603b0edd79e93fbe170a5eb9b2b3f8 to your computer and use it in GitHub Desktop.
Save 0xa/43603b0edd79e93fbe170a5eb9b2b3f8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
mostly-hot-resize a swap device from a Xen VM.
(Py 2/3)
usage:
vm # swapoff -a
host# ./reswap.py /etc/xen/vmname.cfg xvda1 1g
vm # swapon -a
"""
import os
import sys
import imp
import subprocess
if sys.version_info[:2] <= (2, 7):
input = raw_input
if len(sys.argv) != 4:
print("usage: reswap.py <config path> <device name> <new_size>")
exit(1)
vm_cfg = imp.load_source('cfg', sys.argv[1])
device = sys.argv[2]
new_size = sys.argv[3]
name = vm_cfg.name
print("vm name: %s" % name)
swap_config = ''
swap_file = ''
for d in vm_cfg.disk:
parts = d.split(',')
if parts[1] == device:
assert parts[0].startswith('file:')
swap_config = d
swap_file = parts[0][5:] # skip file:
break
else:
print("swap device not found.")
exit(1)
print("swap: %s (%s)" % (swap_file, swap_config))
blklist = subprocess.check_output(['xl', 'block-list', name])
blklist = blklist.split('\n')
blklist = [l.split() for l in blklist]
blklist = [(p[0], p[6]) for p in blklist[1:] if p]
for blkn, blkpath in blklist:
blkdev = subprocess.check_output(['xenstore-read', blkpath + '/dev']).strip()
if blkdev == device:
break
else:
print("block device not found")
exit(1)
print("blk: %s (%s) -> %s" % (blkn, blkdev, blkpath))
print(subprocess.check_output(['xenstore-ls', blkpath]))
print(" ---- ")
print("okay? [y] (SWAPOFF FIRST!)")
if input() != 'y':
print("aborted")
exit(1)
def run_print(args):
print(">" + " ".join(args))
print(subprocess.check_output(args))
run_print(['xl', 'block-detach', name, blkn])
run_print(['truncate', '-s', new_size, swap_file])
run_print(['mkswap', swap_file])
run_print(['xl', 'block-attach', name, swap_config])
print(" ---- ")
print("done, you can swapon -a")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment