Created
August 13, 2010 14:38
-
-
Save schmir/522980 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
import sys, os, signal, getopt, time | |
base_cgroup = "/cgroup" | |
def get_pids(name): | |
pids = open(os.path.join(base_cgroup, name, "tasks")).read().split() | |
return pids | |
def find_init(name): | |
pids = get_pids(name) | |
inits = [] | |
for p in pids: | |
try: | |
exe = os.readlink("/proc/%s/exe" % p) | |
except OSError: | |
continue | |
if exe=="/sbin/init": | |
inits.append(p) | |
if not inits: | |
raise RuntimeError("could not find '/sbin/init'") | |
if len(inits)>1: | |
raise RuntimeError("more than one '/sbin/init' found") | |
return int(inits[0]), "/sbin/init" | |
def shutdown(name): | |
init, exe = find_init(name) | |
print "sending SIGINT (ctrl-alt-del) to %s (%s) in container %s" % (exe, init, name) | |
os.kill(init, signal.SIGINT) | |
try: | |
print "processes running in %s:" % name, | |
for x in range(60): | |
num = len(get_pids(name)) | |
print num, | |
sys.stdout.flush() | |
if num==1: | |
break | |
time.sleep(1) | |
finally: | |
os.system("lxc-stop -n %s" % (name, )) | |
def usage(): | |
print "lxc-shutdown -n NAME" | |
print " send SIGINT to /sbin/init in container NAME and wait for all processes besides init to finish" | |
sys.exit(0) | |
def main(): | |
try: | |
opts, args = getopt.getopt(sys.argv[1:], "n:", ["name="]) | |
except getopt.GetoptError, err: | |
print str(err) | |
sys.exit(10) | |
name = None | |
for o, a in opts: | |
if o in ("-n", "--name"): | |
name = a | |
if not name: | |
usage() | |
shutdown(name) | |
if __name__=="__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment