m0e-vinstall / vinstall / backend / utils.py

#!/bin/env python

"""Collection of small utilities."""


__version__ = "0.0.1a"
__date__ = "08/20/09"
__author__ = "rbistolfi"
__credits__ = "M0E-lnx, Uelsk8s, Kidd"


import os
import re
from vinstall.backend import sp
from vinstall.core import log

LOG = log.get_logger("vinstall_utils")


def get_mem_size():
    """Get the amount of RAM availablein the system in mB.

    """
    meminfo = "/proc/meminfo"
    fo = open(meminfo)
    line = fo.readline()
    fo.close()
    label, size, unit = line.split()
    return int(size) / 1024.0


def format_partition(path, filesystem):
    """Create a filesystem in a partition using mkfs.

    """
    commands = {
        "swap": "mkswap %s",
        "reiserfs": "mkfs.reiserfs -f -f %s",
        "xfs": "mkfs.xfs -f %s",
        "jfs": "mkfs.jfs -f %s",
        "ext2": "mkfs.ext2 -F %s",
        "ext3": "mkfs.ext3 -F %s",
        "ext4": "mkfs.ext4 -F %s"
    }
    command = commands[filesystem] % path
    sp.call(command.split())


def activate_swap(path=None):
    if path is None:
        #Activate all swap space
        command = 'swapon -a'
    else:
        command = 'swapon %s'% path
    sp.call(command.split())


def mount(src, mountpoint, filesystem='auto'):
    """Mount a filesystem.

    Arguments:

        src: the filesystem or device to be mounted.
        filesystem: filesystem type passed to the mount command, for example:
                    "ext3". Default is auto.

    """
    command = 'mount -t %s %s %s' % (filesystem, src, mountpoint)
    sp.call(command.split())
    return mountpoint


def mountiso(src, mountpoint):
    """Mount a filesystem.

    Arguments:

        src: the filesystem or device to be mounted.
        extra: extra options to be passed to the mount command, for example:
               "-o loop". Default is None.
        filesystem: filesystem type passed to the mount command, for example:
                    "ext3". Default is auto.

    """
    command = 'mount -o loop %s %s' % (src, mountpoint)
    sp.call(command.split())
    return mountpoint


def bind_mount(src, mountpoint):
    """Mount a filesystem with --bind

    """
    command = 'mount --bind %s %s' % (src, mountpoint)
    sp.call(command.split())
    return mountpoint


def umount(mounted):
    """Unmount a filesystem.

    Arguments:

        A mounted filesystem or device.

    >>> umount('/mnt/loop')
    0

    """
    command = 'umount %s' % (mounted)
    return sp.call(command.split())


def exec_chroot(root, command):
    """Change the root dir for current shell  and run the given command.

    Arguments:

        dir: The directory to for chrooting to.
        command: The command to be executed under the new root.

    >>> exec_chroot('/', 'pwd')
    0

    """
    command = 'chroot %s %s' % (root, command)
    sp.call(command.split())


def is_mounted(device):
    """Returns true if device is mounted.

    """
    with open("/proc/mounts") as mounted:
        if device in mounted.read():
            return True
        else:
            return False


def get_mounted(mountpoint):
    """Return device for a mountpoint

    """
    for line in open("/etc/mtab"):
        device, mpoint, _ = line.split(" ", 2)
        if mountpoint == mpoint:
            return device


def supported_filesystems():
    """Returns a list of filesystems supported by the system."""

    fo = open('/proc/filesystems')
    data = fo.read()
    fo.close()
    kernel_fs = re.findall(r'^\s+(\w+)', data, re.M)
    path = os.environ['PATH'].split(':')
    for p in path:
        for k in kernel_fs:
            if os.path.isfile(os.path.join(p, 'mkfs.' + k)):
                yield k


def depmod():
    """Run depmod"""

    command = "depmod -a"
    return sp.call(command.split())


def mkinitrd(root, fs):
    """Create an initrd"""

    command = ("mkinitrd -c -u -r %s -f %s -m "
               "i810:i915:intel:nouveau:radeon:vmwgfx" % (root, fs))
    sp.call(command.split())


class Chroot(object):
    """Execute block in a chrooted context

        >>> with Chroot("/mnt"):
        ...     dostuff()

    If chdir kwarg is True, os.chdir to "/" before entering

    """
    def __init__(self, new_root, chdir=True):
        self.new_root = new_root
        self.chdir = chdir

    def __enter__(self):
        """Save current root for restoring later

        """
        LOG.debug("Entering chroot")
        try:
            self.real_root = os.open("/", os.O_RDONLY)
            self.old_cwd = os.getcwd()
            os.chroot(self.new_root)
            if self.chdir:
                os.chdir("/")
        except:
            LOG.error("Error occurred while running commands in chroot %s"% self.new_root)

    def __exit__(self, *_):
        """Go back to previous root

        """
        os.fchdir(self.real_root)
        os.chroot(".")
        os.close(self.real_root)
        os.chdir(self.old_cwd)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.