def set_zombie_refresh_to_fail(self, refresh_job):
current_pid = refresh_job.pid
if current_pid is None:
return
p = psutil.Process(current_pid)
if p.status() != psutil.STATUS_ZOMBIE:
return
refresh = self.schematizer.get_refresh_by_id(
refresh_job.refresh_id
)
if refresh.status == RefreshStatus.IN_PROGRESS:
# Must update manually (not relying on the signal),
# as the process may not properly handle the signal
# if it's a zombie
self.schematizer.update_refresh(
refresh_id=refresh_job.refresh_id,
status=RefreshStatus.FAILED,
offset=0
)
source = refresh_job.source
del self.active_refresh_jobs[source]
os.kill(current_pid, signal.SIGINT)
python类kill()的实例源码
def test_transform_service_heartbeat(self, coordinator):
# mock coordinator
fake_kazoo_driver = MagicMock(name="MagicKazooDriver",
spec=KazooDriver)
coordinator.return_value = fake_kazoo_driver
# option1
serv_thread = transform_service.TransformService()
serv_thread.daemon = True
serv_thread.start()
time.sleep(2)
# option2
# mocks dont seem to work when spawning a service
# pid = _spawn_transform_service()
# time.sleep()
# os.kill(pid, signal.SIGNAL_SIGTERM)
fake_kazoo_driver.heartbeat.assert_called_with()
def stop(self):
self._log.debug("stop()")
if self.get_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def get_commandAlive(self):
if self._pid != None:
try:
os.kill(self._pid, 0)
if os.waitpid(self._pid, os.WNOHANG) == (0,0):
return True
else:
return False
except OSError:
pass
return False
def stop(self):
self._log.debug("stop()")
if self.get_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def stop(self):
self._log.debug("%s.stop()", self.naming_service_name)
if self.query_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
def stop(self):
self._log.debug("stop()")
if self.query_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def stop(self):
self._log.debug("stop()")
if self.get_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def stop(self):
self._log.debug("stop()")
try:
if self.get_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
finally:
Resource.stop(self)
# CF::LifeCycle
def stop(self):
self._log.debug("stop()")
if self.get_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def stop(self):
self._log.debug("stop()")
if self.query_prop_commandAlive() == True:
for sig, timeout in self.STOP_SIGNALS:
try:
os.kill(self._pid, sig)
except OSError:
self._pid = None
return
if timeout != None:
giveup_time = time.time() + timeout
while os.waitpid(self._pid, os.WNOHANG) == (0,0):
time.sleep(0.1)
if time.time() > giveup_time:
break
else:
# Wait until there is a response
os.waitpid(self._pid, 0)
self._pid = None
######################################
# Implement specific property setters/getters
def _test_ShutdownParent(self, node):
self._setupDevices(node)
# test aggregate device releaseObject functionality
pids = getChildren(self._devBooter.pid)
self._parentDevice.releaseObject()
for pid in pids:
number_attempts = 0
while True:
try:
os.kill(pid, 0) # check to see if the process is still alive
time.sleep(0.5)
number_attempts+=1
except:
break
if number_attempts == 5:
break
pids = getChildren(self._devBooter.pid)
self.assertEqual(len(self._devMgr._get_registeredDevices()), 0)
# make sure the child device was also released
self.assertEqual(len(pids), 0)
self._devMgr.shutdown()
self.assert_(self.waitTermination(self._devBooter))
self.assertEqual(len(self._domMgr._get_deviceManagers()), 0)
def test_NSCleanup(self):
domain_name = self._domMgr._get_name()
ns_domMgr = URI.stringToName("%s/%s" % (domain_name, domain_name))
ns_domMgrCtx = URI.stringToName("%s" % (domain_name))
ns_ODM = URI.stringToName("%s/%s" % (domain_name, "ODM_Channel"))
ns_IDM = URI.stringToName("%s/%s" % (domain_name, "IDM_Channel"))
domCtx_ref = self._root.resolve(ns_domMgrCtx)
domMgr_ref = self._root.resolve(ns_domMgr)
ODM_ref = self._root.resolve(ns_ODM)
IDM_ref = self._root.resolve(ns_IDM)
self.assertNotEqual(domCtx_ref, None)
self.assertNotEqual(domMgr_ref, None)
self.assertNotEqual(ODM_ref, None)
self.assertNotEqual(IDM_ref, None)
os.kill(self._domainBooter.pid, signal.SIGINT)
self.waitTermination(self._domainBooter)
self.assertRaises(CosNaming.NamingContext.NotFound, self._root.resolve, ns_domMgrCtx)
def test_CatatrophicUnregister(self):
# Test that if a device manager dies unexpectedly and then re-registers there are no problems
devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_SelfTerminatingDevice_node/DeviceManager.dcd.xml")
self.assertNotEqual(devMgr, None)
# NOTE These assert check must be kept in-line with the DeviceManager.dcd.xml
self.assertEqual(len(devMgr._get_registeredDevices()), 1)
devs = devMgr._get_registeredDevices()
pids = getChildren(devmgr_nb.pid)
for devpid in pids:
os.kill(devpid, signal.SIGKILL)
os.kill(devmgr_nb.pid, signal.SIGKILL)
self.waitTermination(devmgr_nb)
devmgr_nb, devMgr = self.launchDeviceManager("/nodes/test_SelfTerminatingDevice_node/DeviceManager.dcd.xml")
self.assertNotEqual(devMgr, None)
self.assertEqual(len(devMgr._get_registeredDevices()), 1)
# Test that the DCD file componentproperties get pushed to configure()
# as per DeviceManager requirement SR:482
devMgr.shutdown()
self.assert_(self.waitTermination(devmgr_nb), "Nodebooter did not die after shutdown")
def test_DeviceManagerSurprise(self):
self._nb_domMgr, self._domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self.assertEqual(len(self._domMgr._get_deviceManagers()), 0)
# Kill the domainMgr
os.kill(self._nb_domMgr.pid, signal.SIGKILL)
if not self.waitTermination(self._nb_domMgr):
self.fail("Domain Manager Failed to Die")
self._nb_devMgr, devMgr = self.launchDeviceManager("/nodes/test_BasicTestDevice_node/DeviceManager.dcd.xml", wait=False)
# this sleep is needed to allow the Device Manager to figure out that the Domain Manager is not available
time.sleep(1)
# Start the domainMgr again
self._nb_domMgr, newDomMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
time.sleep(1) # sleep needed to make sure that the Device Manager has registered with the Domain Manager
node_name = 'BasicTestDevice_node'
domainName = scatest.getTestDomainName()
devMgrURI = URI.stringToName("%s/%s/BasicTestDevice1" % (domainName, node_name))
dev = self._root.resolve(devMgrURI)
self.assertNotEqual(dev, None)
self.assertEqual(len(self._domMgr._get_deviceManagers()), 1)
def test_DeviceManagerRegisterWhileDomainManagerCrashed(self):
domBooter, domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self.assertNotEqual(domMgr, None)
# Forcibly terminate the domain manager to simulate a crash
os.kill(domBooter.pid, signal.SIGKILL)
if not self.waitTermination(domBooter):
self.fail("DomainManager failed to die")
time.sleep(2)
# Start the node; we cannot get the object reference because the
# DomainManager is down, so waiting is pointless right now.
dcdFile = "/nodes/test_PortTestDevice_node/DeviceManager.dcd.xml"
devBooter, unused = self.launchDeviceManager(dcdFile, wait=False)
time.sleep(2)
# Restart the DomainManager
domBooter, domMgr = self.launchDomainManager(endpoint="giop:tcp::5679", dbURI=self._dbfile)
self.assertNotEqual(domMgr, None)
# Wait for the DeviceManager and make sure it registers.
devMgr = self.waitDeviceManager(devBooter, dcdFile)
self.assertNotEqual(devMgr, None)
def terminateChild(self, child, signals=(signal.SIGINT, signal.SIGTERM)):
if child.poll() != None:
return
try:
#self.waitTermination(child)
for sig in signals:
#print "sending signal " + str(sig) + " to pid:" + str(child.pid)
os.kill(child.pid, sig)
if self.waitTermination(child):
break
child.wait()
except OSError, e:
#print "terminateChild: pid:" + str(child.pid) + " OS ERROR:" + str(e)
pass
finally:
pass
def register_signal(signal_number, handler_func, once = False):
prev_handler = None
def _handler(signum, frame):
skip_prev = handler_func(signum, frame)
if not skip_prev:
if callable(prev_handler):
if once:
signal.signal(signum, prev_handler)
prev_handler(signum, frame)
elif prev_handler == signal.SIG_DFL and once:
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum)
prev_handler = signal.signal(signal_number, _handler)
def test_register_signal(self):
if runtime_info.OS_WIN:
return
result = {'handler': 0}
def _handler(signum, frame):
result['handler'] += 1
register_signal(signal.SIGUSR1, _handler)
os.kill(os.getpid(), signal.SIGUSR1)
os.kill(os.getpid(), signal.SIGUSR1)
signal.signal(signal.SIGUSR1, signal.SIG_DFL)
self.assertEqual(result['handler'], 2)
def kill(self):
if not self.qemu:
return
try:
self.qemu = None
os.kill(self.current_qemu_pid, signal.SIGKILL)
os.waitpid(self.current_qemu_pid, 0)
self.current_qemu_pid = -1
except OSError: # process may be finished by kill already
pass
LOG.debug('let gdb notice process was killed')
try:
execute_gdb_command('detach')
raise RuntimeError('gdb should have disconnected and raise gdb.error')
except gdb.error as e:
LOG.debug('catch expected exception: ' + str(e))
def test_log(self):
"""Logging tests"""
# Not much to test here but exercise the code nonetheless
# for regression/coverage.
log = Log(verbose=False, prefix='test')
log.debug("Invisible debug.")
try:
raise ValueError("Test exception")
except ValueError:
log.exception("Test exception with message")
for num in range(1, 5):
log.debug("Debug")
log.info("Info")
log.warning("Warning")
log.error("Error")
log.critical("Crtitical")
os.kill(os.getpid(),
signal.SIGUSR1 if (num % 2) != 0 else signal.SIGUSR2)
def stop(sel, domain_name):
LOG.debug('Stopping Virtual BMC for domain %s', domain_name)
domain_path = os.path.join(utils.CONFIG_PATH, domain_name)
if not os.path.exists(domain_path):
raise exception.DomainNotFound(domain=domain_name)
pidfile_path = os.path.join(domain_path, 'pid')
pid = None
try:
with open(pidfile_path, 'r') as f:
pid = int(f.read())
except IOError:
raise exception.VirtualBMCError(
'Error stopping the domain %s: PID file not '
'found' % domain_name)
else:
os.remove(pidfile_path)
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
def terminationHandler(cls, signal=None, frame=None, terminate=True):
"""Signal termination handler
signal - raised signal
frame - origin stack frame
terminate - whether to terminate the application
"""
#if signal == signal.SIGABRT:
# os.killpg(os.getpgrp(), signal)
# os.kill(os.getpid(), signal)
if cls._execpool:
del cls._execpool # Destructors are caled later
# Define _execpool to avoid unnessary trash in the error log, which might
# be caused by the attempt of subsequent deletion on destruction
cls._execpool = None # Note: otherwise _execpool becomes undefined
if terminate:
sys.exit() # exit(0), 0 is the default exit code.
def test_all_exit_sigs_with_sig(self):
# Same as above but the process is terminated by a signal
# instead of exiting cleanly.
for sig in TEST_SIGNALS:
ret = pyrun(textwrap.dedent(
"""
import functools, os, signal, imp
mod = imp.load_source("mod", r"{modname}")
def foo(s):
with open(r"{testfn}", "ab") as f:
f.write(s)
signal.signal({sig}, functools.partial(foo, b'0'))
mod.register_exit_fun(functools.partial(foo, b'1'))
mod.register_exit_fun(functools.partial(foo, b'2'))
os.kill(os.getpid(), {sig})
""".format(modname=os.path.abspath(__file__),
testfn=TESTFN, sig=sig)
))
self.assertEqual(ret, sig)
with open(TESTFN, "rb") as f:
self.assertEqual(f.read(), b"210")
safe_remove(TESTFN)
def input(s, stdout = True, timeout = 2,
prompt = rgx2nd(('(.+)', 'py3to2 server: \\1'), ),
subprompt = rgx2nd(('>>> ', '', None), ),
fndexc = re.compile('\WTraceback '),
):
self = _server
if not s: return
SERVER.stdin.write(s)
try:
buf = ''
SERVER.stdin.write("\n\nimport os, signal; os.kill(CLIENTPID, signal.SIGINT)\n")
time.sleep(timeout)
raise IOError('py3to2 server not responding to input: %s'%repr(s))
except KeyboardInterrupt:
buf = os.read(SERVERIO[0], self.bufsize)
buf = subprompt.sub(buf)
if prompt: buf = prompt.sub(buf)
if fndexc.search(buf): raise IOError('py3to2 server input: %s\n%s'%(s, buf))
if stdout: sys.stdout.write(buf)
else: return buf
def input(s, stdout = True, timeout = 2,
prompt = rgx2nd(('(.+)', 'py3to2 server: \\1'), ),
subprompt = rgx2nd(('>>> ', '', None), ),
fndexc = re.compile('\WTraceback '),
):
self = _server
if not s: return
SERVER.stdin.write(s)
try:
buf = ''
SERVER.stdin.write("\n\nimport os, signal; os.kill(CLIENTPID, signal.SIGINT)\n")
time.sleep(timeout)
raise IOError('py3to2 server not responding to input: %s'%repr(s))
except KeyboardInterrupt:
buf = os.read(SERVERIO[0], self.bufsize)
buf = subprompt.sub(buf)
if prompt: buf = prompt.sub(buf)
if fndexc.search(buf): raise IOError('py3to2 server input: %s\n%s'%(s, buf))
if stdout: sys.stdout.write(buf)
else: return buf
def stop(self):
"""
Stop the shell
"""
if self.is_running():
try:
os.kill(self._shell_pid, signal.SIGTERM)
except OSError:
pass
start = time.time()
while self.is_running() and (time.time() < (start + 0.2)):
time.sleep(0.05)
if self.is_running():
utils.ConsoleLogger.log("Failed to stop shell process")
else:
utils.ConsoleLogger.log("Shell process stopped")
def cleanup(self):
print
if (self.webserver is not None):
if (self.config["daemon_web"]):
self.display.alert("Webserver is still running as requested.")
else:
# send SIGTERM to the web process
self.display.output("stopping the webserver")
self.webserver.send_signal(signal.SIGINT)
# delete the pid file
os.remove(self.pid_path + "spfwebsrv.pid")
# as a double check, manually kill the process
self.killProcess(self.webserverpid)
# call report generation
self.generateReport()
# exit
sys.exit(0)
#----------------------------
# Kill specified process
#----------------------------
def kill_invalid_connection():
unfinished_logs = Log.objects.filter(is_finished=False)
now = datetime.datetime.now()
now_timestamp = int(time.mktime(now.timetuple()))
for log in unfinished_logs:
try:
log_file_mtime = int(os.stat('%s.log' % log.log_path).st_mtime)
except OSError:
log_file_mtime = 0
if (now_timestamp - log_file_mtime) > 3600:
if log.login_type == 'ssh':
try:
os.kill(int(log.pid), 9)
except OSError:
pass
elif (now - log.start_time).days < 1:
continue
log.is_finished = True
log.end_time = now
log.save()
logger.warn('kill log %s' % log.log_path)
def stop(self):
pid = None
if not os.path.exists(self.pidfile):
logger.debug('pidfile not exist:' + self.pidfile)
return
try:
pid = _read_file(self.pidfile)
pid = int(pid)
os.kill(pid, signal.SIGTERM)
return
except Exception as e:
logger.warn('{e} while get and kill pid={pid}'.format(
e=repr(e), pid=pid))