def test_ApplicationUsesDevice(self):
self._nb_domMgr, self._domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_SADUsesDevice/DeviceManager.dcd.xml")
self._domMgr.installApplication("/waveforms/SADUsesDeviceWave/SADUsesDeviceWaveExternalSimple.sad.xml")
appFact = self._domMgr._get_applicationFactories()[0]
app = appFact.create(appFact._get_name(), [], [])
# Make sure that the allocation was made to the device
prop = CF.DataType(id='simple_alloc', value=any.to_any(None))
for dev in devMgr._get_registeredDevices():
if dev._get_label() == 'SADUsesDevice_1':
allocRes = dev.query([prop])
self.assertEquals(allocRes[0].value.value(), 8)
# Kill the domainMgr
os.kill(self._nb_domMgr.pid, signal.SIGTERM)
# TODO if SIGKILL is used (simulating a nodeBooter unexpected abort,
# the IOR and the newly spawned domain manager do not work
if not self.waitTermination(self._nb_domMgr):
self.fail("Domain Manager Failed to Die")
# Start the domainMgr again
self._nb_domMgr, newDomMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
# Capacity still allocated to device
prop = CF.DataType(id='simple_alloc', value=any.to_any(None))
for dev in devMgr._get_registeredDevices():
if dev._get_label() == 'SADUsesDevice_1':
allocRes = dev.query([prop])
self.assertEquals(allocRes[0].value.value(), 8)
# Release app to free up device capacity to make sure usesdevicecapacties was properly restored
newApp = newDomMgr._get_applications()[0]
newApp.releaseObject()
prop = CF.DataType(id='simple_alloc', value=any.to_any(None))
for dev in devMgr._get_registeredDevices():
if dev._get_label() == 'SADUsesDevice_1':
allocRes = dev.query([prop])
self.assertEquals(allocRes[0].value.value(), 10)
python类SIGTERM的实例源码
def test_ApplicationStartOrder(self):
self._nb_domMgr, self._domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml")
self._domMgr.installApplication("/waveforms/CommandWrapperStartOrderTests/CommandWrapperWithOrder.sad.xml")
appFact = self._domMgr._get_applicationFactories()[0]
app = appFact.create(appFact._get_name(), [], [])
app.start()
comps = app._get_registeredComponents()
for c in comps:
self.assertEquals(c.componentObject._get_started(), True)
# Kill the domainMgr
os.kill(self._nb_domMgr.pid, signal.SIGTERM)
# TODO if SIGKILL is used (simulating a nodeBooter unexpected abort,
# the IOR and the newly spawned domain manager do not work
if not self.waitTermination(self._nb_domMgr):
self.fail("Domain Manager Failed to Die")
# Start the domainMgr again
self._nb_domMgr, newDomMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
# Components should all still be started
for c in comps:
self.assertEquals(c.componentObject._get_started(), True)
# Stop application to make sure that start order Resource variables were recovered properly
app = newDomMgr._get_applications()[0]
app.stop()
for c in comps:
self.assertEquals(c.componentObject._get_started(), False)
# Start components to make sure that start also works
app.start()
for c in comps:
self.assertEquals(c.componentObject._get_started(), True)
def test_RegisteredDomains(self):
nb, domMgr = self.launchDomainManager(endpoint='giop:tcp::5679', dbURI=self._dbfile)
testMgr1 = TestDomainManager('test1')
domMgr.registerRemoteDomainManager(testMgr1._this())
testMgr2 = TestDomainManager('test2')
domMgr.registerRemoteDomainManager(testMgr2._this())
remotes = [r._get_identifier() for r in domMgr._get_remoteDomainManagers()]
self.assertEqual(len(remotes), 2)
self.assert_(testMgr1._get_identifier() in remotes)
self.assert_(testMgr2._get_identifier() in remotes)
# Kill the DomainManager
os.kill(nb.pid, signal.SIGTERM)
if not self.waitTermination(nb):
self.fail("Domain Manager Failed to Die")
# Deactivate the second domain manager to check that its connection is
# not restored
poa = testMgr2._default_POA()
oid = poa.servant_to_id(testMgr2)
poa.deactivate_object(oid)
# Re-launch and check that the remote domain is restored
nb, domMgr = self.launchDomainManager(endpoint='giop:tcp::5679', dbURI=self._dbfile)
remotes = domMgr._get_remoteDomainManagers()
self.assertEqual(len(remotes), 1)
self.assertEqual(remotes[0]._get_identifier(), testMgr1._get_identifier())
def test_Allocations(self):
nb, domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml")
# Make a couple of different allocations
allocMgr = domMgr._get_allocationMgr()
memCapacityId = 'DCE:8dcef419-b440-4bcf-b893-cab79b6024fb'
bogoMipsId = 'DCE:5636c210-0346-4df7-a5a3-8fd34c5540a8'
nicCapacityId = 'DCE:4f9a57fc-8fb3-47f6-b779-3c2692f52cf9'
allocations = { 'test1': {memCapacityId:2048, nicCapacityId:0.125},
'test2': {bogoMipsId:10000}}
requests = [CF.AllocationManager.AllocationRequestType(k, properties.props_from_dict(v), [], [], 'test_Allocations') for k,v in allocations.iteritems()]
results = allocMgr.allocate(requests)
self.assertEqual(len(results), len(requests))
# Save the allocation state prior to termination
pre = dict((al.allocationID, al) for al in allocMgr.allocations([]))
self.assertEqual(len(pre), len(results))
# Kill the DomainManager
os.kill(nb.pid, signal.SIGTERM)
if not self.waitTermination(nb):
self.fail("Domain Manager Failed to Die")
# Re-launch and check that the allocation state remains the same;
# implicitly tests that the AllocationManager reference is persistent
self.launchDomainManager(endpoint='giop:tcp::5679', dbURI=self._dbfile)
post = dict((al.allocationID, al) for al in allocMgr.allocations([]))
self.assertEqual(len(pre), len(post))
self.assertEqual(pre.keys(), post.keys())
for allocId, status in pre.iteritems():
self._compareAllocation(status, post[allocId])
def test_AllocationPersistence(self):
self.launchDeviceManager("/nodes/test_multiDomain_exec/DeviceManager.dcd.xml", domainManager=self._domainManager_1)
self.launchDeviceManager("/nodes/test_multiDomain_uses/DeviceManager.dcd.xml", domainManager=self._domainManager_2)
self._domainManager_1.registerRemoteDomainManager(self._domainManager_2)
allocMgr_1 = self._domainManager_1._get_allocationMgr()
# Make a couple of allocation requests that we know will have to be
# split across the two domains
execcap = {'DCE:8dcef419-b440-4bcf-b893-cab79b6024fb':1000,
'DCE:4f9a57fc-8fb3-47f6-b779-3c2692f52cf9':50.0}
usescap = {'DCE:8cad8ca5-c155-4d1d-ae40-e194aa1d855f':1}
requests = [allocMgrHelpers.createRequest('exec', properties.props_from_dict(execcap)),
allocMgrHelpers.createRequest('uses', properties.props_from_dict(usescap))]
results = dict((r.requestID, r) for r in allocMgr_1.allocate(requests))
self.assertEqual(len(requests), len(results))
usesId = results['uses'].allocationID
execId = results['exec'].allocationID
# Save the current allocation state
pre = dict((al.allocationID, al) for al in allocMgr_1.allocations([]))
# Kill the DomainManager
os.kill(self._domainBooter_1.pid, signal.SIGTERM)
if not self.waitTermination(self._domainBooter_1):
self.fail("Domain Manager Failed to Die")
# Re-launch and check that the allocation state remains the same
self.launchDomainManager(endpoint='giop:tcp::5679', dbURI=self._dbfile)
post = dict((al.allocationID, al) for al in allocMgr_1.allocations([]))
self.assertEqual(len(pre), len(post))
self.assertEqual(pre.keys(), post.keys())
for allocId, status in pre.iteritems():
self.assert_(allocMgrHelpers.compareAllocationStatus(status, post[allocId]))
def terminateChildrenPidOnly(self, pid, signals=(signal.SIGINT, signal.SIGTERM)):
ls = commands.getoutput('ls /proc')
entries = ls.split('\n')
for entry in entries:
filename = '/proc/'+entry+'/status'
try:
fp = open(filename,'r')
stuff = fp.readlines()
fp.close()
except:
continue
ret = ''
for line in stuff:
if 'PPid' in line:
ret=line
break
if ret != '':
parentPid = ret.split('\t')[-1][:-1]
if parentPid == pid:
self.terminateChildrenPidOnly(entry, signals)
filename = '/proc/'+pid+'/status'
for sig in signals:
try:
os.kill(int(pid), sig)
except:
continue
done = False
attemptCount = 0
while not done:
try:
fp = open(filename,'r')
fp.close()
attemptCount += 1
if attemptCount == 10:
break
time.sleep(0.1)
except:
done = True
if not done:
continue
def terminateChildren(self, child, signals=(signal.SIGINT, signal.SIGTERM)):
ls = commands.getoutput('ls /proc')
entries = ls.split('\n')
for entry in entries:
filename = '/proc/'+entry+'/status'
try:
fp = open(filename,'r')
stuff = fp.readlines()
except:
continue
for line in stuff:
if 'PPid' in line:
ret=line
break
if ret != '':
parentPid = int(ret.split('\t')[-1][:-1])
if parentPid == child.pid:
self.terminateChildrenPidOnly(entry, signals)
if child.poll() != None:
return
try:
for sig in signals:
os.kill(child.pid, sig)
if self.waitTermination(child):
break
child.wait()
except OSError:
pass
def __terminate_process( process, signals=(_signal.SIGINT, _signal.SIGTERM, _signal.SIGKILL) ):
if process and process.poll() != None:
return
try:
for sig in signals:
_os.kill(process.pid, sig)
if __waitTermination(process):
break
process.wait()
except OSError, e:
pass
finally:
pass
def setUp(self):
"""
Starts the component whose id matches the one stored in the IMPL_ID
"""
signal.signal(signal.SIGINT, self.tearDown)
signal.signal(signal.SIGTERM, self.tearDown)
signal.signal(signal.SIGQUIT, self.tearDown)
global SOFT_PKG
global IMPL_ID
self.comp_obj = None
self.comp = None
# Use the globals by default
self.impl = IMPL_ID
self.spd_file = SOFT_PKG
self.spd = SPDParser.parse(SOFT_PKG)
try:
self.prf_file = self.spd.get_propertyfile().get_localfile().get_name()
if (self.prf_file[0] != '/'):
self.prf_file = os.path.join(os.path.dirname(self.spd_file), self.prf_file)
self.prf = PRFParser.parse(self.prf_file)
except:
self.prf_file = None
self.prf = None
self.scd_file = self.spd.get_descriptor().get_localfile().get_name()
if (self.scd_file[0] != '/'):
self.scd_file = os.path.join(os.path.dirname(self.spd_file), self.scd_file)
self.scd = SCDParser.parse(self.scd_file)
# create a map between prop ids and names
if self.prf:
self._props = prop_helpers.getPropNameDict(self.prf)
def __init__(self):
helperBase.__init__(self)
self.usesPortIORString = None
self._providesPortDict = {}
self._processes = {}
self._STOP_SIGNALS = ((_signal.SIGINT, 1),
(_signal.SIGTERM, 5),
(_signal.SIGKILL, None))
def pause_job(self, job):
# This signal will cause the refresh runner to update
# the job to paused
os.kill(job.pid, signal.SIGTERM)
job.pid = None
def test_server_signals(self):
server = spoon.server.TCPSpoon(("0.0.0.0", 30783))
calls = [
call(signal.SIGUSR1, server.reload_handler),
call(signal.SIGTERM, server.shutdown_handler)
]
self.mock_signal.assert_has_calls(calls)
def test_master_shutdown(self):
shutdown = patch("spoon.server.TCPSpoon.shutdown").start()
server = spoon.server.TCPSpork(("0.0.0.0", 30783))
server.prefork = 2
server.pids = [100, 101]
server.shutdown()
calls = [
call(100, signal.SIGTERM),
call(101, signal.SIGTERM),
]
self.mock_kill.assert_has_calls(calls)
def send_action(action, pidfile, logger=None):
"""Send a signal to an existing running daemon."""
if logger is None:
logger = logging
if not os.path.exists(pidfile):
logger.critical("No pid file available: %s", pidfile)
return
with open(pidfile) as pidf:
pid = int(pidf.read())
if action == "reload":
os.kill(pid, signal.SIGUSR1)
elif action == "stop":
os.kill(pid, signal.SIGTERM)
def shutdown_handler(self, *args, **kwargs):
"""Handler for the SIGTERM signal. This should be used to kill the
daemon and ensure proper clean-up.
"""
self.log.info("SIGTERM received. Shutting down.")
t = threading.Thread(target=self.shutdown)
t.start()
def send_signal(self, sig):
"""Send a signal to the process
"""
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
def terminate(self):
"""Terminate the process with SIGTERM
"""
self.send_signal(signal.SIGTERM)
def terminate(self):
if self.returncode is None:
try:
os.kill(self.pid, signal.SIGTERM)
except OSError, e:
if self.wait(timeout=0.1) is None:
raise
def wait(self, timeout=None):
if self.returncode is None:
if timeout is None:
msecs = _subprocess.INFINITE
else:
msecs = max(0, int(timeout * 1000 + 0.5))
res = _subprocess.WaitForSingleObject(int(self._handle), msecs)
if res == _subprocess.WAIT_OBJECT_0:
code = _subprocess.GetExitCodeProcess(self._handle)
if code == TERMINATE:
code = -signal.SIGTERM
self.returncode = code
return self.returncode
def setup_docker_sigterm_handler(): # type: () -> None
'''
'manage.py runserver' is not set up to deal with a SIGTERM signal,
and instead expects a Ctrl-C to come to its child process. So we'll
add a SIGTERM handler here that finds all our children and gracefully
shuts them down, which provides a quick graceful exit from Docker.
'''
def get_children(): # type: () -> Iterator[int]
output = subprocess.check_output(
"ps --ppid=%d -o pid | awk 'NR>1' | xargs echo" % os.getpid(),
shell=True
)
return map(int, output.split())
def handler(signum, frame): # type: (int, Any) -> None
for child_pid in get_children():
try:
os.kill(child_pid, signal.SIGTERM)
os.waitpid(child_pid, 0)
except OSError:
pass
sys.exit(0)
info("Setting up Docker SIGTERM handler for quick, graceful exit.")
signal.signal(signal.SIGTERM, handler)