# vi: encoding=utf-8 ts=8 sts=4 sw=4 et import os import re import random import util import shutil import subprocess from config import config def quote(cmd): return re.sub("([\"\\\\$`])", r"\\\1", cmd) def command(cmd, user = None, nostdin=""): if user == None: user = config.builder_user if nostdin: nostdin = "exec < /dev/null; " return "%s sudo chroot %s su - %s -c \"export LC_ALL=C; %s %s\"" \ % (config.sudo_chroot_wrapper, config.chroot, user, nostdin, quote(cmd)) def command_sh(cmd): return "%s sudo chroot %s /bin/sh -c \"export LC_ALL=C; exec < /dev/null; %s\"" \ % (config.sudo_chroot_wrapper, config.chroot, quote(cmd)) def popen(cmd, user = "builder", mode = "r", encoding = None): if mode == "r": p = subprocess.Popen(command(cmd, user), shell=True, stdout=subprocess.PIPE, close_fds=True, encoding=encoding) f = p.stdout else: p = subprocess.Popen(command(cmd, user), shell=True, stdin=subprocess.PIPE, close_fds=True, encoding=encoding) f = p.stdin return f def run(cmd, user = "builder", logfile = None, logstdout = None): c = command(cmd, user, nostdin=True) if logfile != None: if logstdout != None: c = "%s 2>&1 | /usr/bin/tee -a %s" % (c, logfile) else: c = "%s >> %s 2>&1" % (c, logfile) f = os.popen(c) if logstdout != None: for l in f: logstdout.write(l) r = f.close() if r == None: return 0 else: return r def cp(file, outfile, user="builder", rm=False): f_out = open(outfile, 'wb') cmd = "cat %s" % file if rm: cmd += "; rm %s" % file p = subprocess.Popen(command(cmd, user), shell=True, stdout=subprocess.PIPE, close_fds=True) f_in = p.stdout shutil.copyfileobj(f_in, f_out) f_out.close() r = f_in.close() if r == None: return 0 else: return r