Source

Cheesecake service / util.py


import math
import os
import resource
import signal
import sys
import time

from subprocess import call, Popen, PIPE, STDOUT


if 'set' not in dir(__builtins__):
    from sets import Set as set


def create_empty_file(file_path):
    fd = file(file_path, "w")
    fd.close()

def create_empty_files_in_directory(files, directory):
    for filename in files:
        create_empty_file(os.path.join(directory, filename))

def obj2dict(obj):
    d = {}
    for attr in dir(obj):
        d[attr] = getattr(obj, attr)
    return d

def one_of_in(L, obj):
    for x in L:
        if x in obj:
            return True
    return False

def touch_file(filename):
    """Update file's last modification time.

    Create file if it didn't exist.
    """
    file(filename, 'a').close()
    os.utime(filename, None)

def get_last_modification_time(filename):
    """Get file's last modification time.
    """
    return os.stat(filename).st_mtime

def daemonize(workdir='/', umask=0):
    """Detach from the terminal and run in the background.

    Based on recipe:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731
    """
    pid = os.fork()
    if pid != 0:
        os._exit(0)

    os.setsid()

    pid = os.fork()
    if pid != 0:
        os._exit(0)

    os.chdir(workdir)
    os.umask(umask)

    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if maxfd == resource.RLIM_INFINITY:
        maxfd = 1024
  
    for fd in range(maxfd):
        try:
            os.close(fd)
        except OSError:
            pass

    os.open('/dev/null', os.O_RDONLY)
    os.dup2(0, 1)
    os.dup2(0, 2)

def fraction(number):
    return number - math.floor(number)

def run_command(cmd, env=None, max_timeout=None):
    """Run command and return its return code and its output.

    >>> run_command('/bin/true')
    (0, '')

    >>> run_command('/bin/cat', max_timeout=0.2)
    (1, 'Time exceeded')
    """
    if isinstance(cmd, str):
        arglist = cmd.split()
    else:
        arglist = cmd

    output = os.tmpfile()
    try:
        p = Popen(arglist, stdout=output, stderr=STDOUT, env=env)
    except Exception, e:
        return 1, e

    # Wait only max_timeout seconds.
    if max_timeout:
        start = time.time()
        while p.poll() is None:
            time.sleep(0.1)
            if time.time() - start > max_timeout:
                os.kill(p.pid, signal.SIGINT)
                p.wait()
                return 1, "Time exceeded"

    p.wait()
    output.seek(0)
    return p.returncode, output.read()

def fill_file_with(filename, string):
    """Trim file and write `string` to it.

    File is created if it didn't existed before.
    """
    fd = file(filename, 'w')
    fd.write(string)
    fd.close()