def main():
"""
?????
"""
redis_client.delete(REDIS_VISITED_URLS)
start_user_url = gen_user_page_url(START_USER)
gevent.signal(signal.SIGQUIT, gevent.kill)
request_api([start_user_url], async_get, parse_user)
python类signal()的实例源码
def handler_signal_ctrl_c():
pid = os.getpid()
os.killpg(os.getpgid(pid), signal.SIGKILL)
os.kill(pid, signal.SIGKILL)
return #
def shut_down(etcd_api):
_log.info("Shutting down due to signal")
try:
with gevent.Timeout(10):
etcd_api.kill(async=False)
except:
_log.exception("Exception during shutdown")
raise
finally:
os._exit(1)
def stop(self, *args, **kwargs):
"""
Stop the daemon
"""
if self.verbose >= 1:
self.log("Stopping...")
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError as err:
if err.errno == errno.ESRCH:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print(str(err))
sys.exit(1)
self.log("Stopped")
def install_signal_handlers():
signal.signal(signal.SIGINT, signal.default_int_handler)
signal.signal(signal.SIGTERM, signal.default_int_handler)
def disable_interrupts():
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
def kill(pid, signum=signal.SIGKILL):
"""
Safe version of `os.kill(pid, signum)` that catches OSError in case of an
already-dead pid.
"""
try:
os.kill(pid, signum)
except OSError as e:
if e.errno != errno.ESRCH:
# Allow "No such process", since that means process is
# already gone---no need to kill what's already dead
raise
def install_signal_handlers(self):
# Enabling the following line to explicitly set SIGINT yields very
# weird behaviour: can anybody explain?
# gevent.signal(signal.SIGINT, signal.default_int_handler)
gevent.signal(signal.SIGTERM, signal.default_int_handler)
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print "Stopping..."
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
if self.verbose >= 1:
print "Stopped"
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print "wyproxy daemon stopping..."
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
if self.verbose >= 1:
print "wyproxy daemon stopped successfully"
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print "Stopping..."
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
if self.verbose >= 1:
print "Stopped"
def start(self):
"""start method is where we decide to :
* catch term signal
* run as daemon
* start the http server
* connect to Freeswitch via our Inbound Socket interface
* wait even if it takes forever, ever, ever, evveeerrr...
"""
self.log.info("RESTServer starting ...")
# catch SIG_TERM
gevent.signal(signal.SIGTERM, self.sig_term)
gevent.signal(signal.SIGHUP, self.sig_hup)
# run
self._run = True
if self._daemon:
self.do_daemon()
# connection counter
retries = 1
# start http server
self.http_proc = gevent.spawn(self.http_server.serve_forever)
if self._ssl:
self.log.info("RESTServer started at: 'https://%s'" % self.http_address)
else:
self.log.info("RESTServer started at: 'http://%s'" % self.http_address)
# Start inbound socket
try:
while self._run:
try:
self.log.info("Trying to connect to FreeSWITCH at: %s" \
% self.fs_inbound_address)
self._rest_inbound_socket.connect()
# reset retries when connection is a success
retries = 1
self.log.info("Connected to FreeSWITCH")
# serve forever
self._rest_inbound_socket.serve_forever()
except ConnectError, e:
if self._run is False:
break
self.log.error("Connect failed: %s" % str(e))
# sleep after connection failure
sleep_for = retries * 10
self.log.error("Reconnecting in %d seconds" % sleep_for)
gevent.sleep(sleep_for)
# don't sleep more than 30 secs
if retries < 3:
retries += 1
except (SystemExit, KeyboardInterrupt):
pass
# kill http server
self.http_proc.kill()
# finish here
self.log.info("RESTServer Exited")
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print("Stopping...")
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError:
err = str(sys.exc_info()[1])
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print(err)
sys.exit(1)
if self.verbose >= 1:
print("Stopped")
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print "wyproxy daemon stopping..."
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
if self.verbose >= 1:
print "wyproxy daemon stopped successfully"
def init_sender(config):
gevent.signal(signal.SIGINT, sender_shutdown)
gevent.signal(signal.SIGTERM, sender_shutdown)
gevent.signal(signal.SIGQUIT, sender_shutdown)
process_title = config['sender'].get('process_title')
if process_title and isinstance(process_title, basestring):
setproctitle.setproctitle(process_title)
logger.info('Changing process name to %s', process_title)
api_host = config['sender'].get('api_host', 'http://localhost:16649')
db.init(config)
cache.init(api_host, config)
metrics.init(config, 'iris-sender', default_sender_metrics)
api_cache.cache_priorities()
api_cache.cache_applications()
api_cache.cache_modes()
global should_mock_gwatch_renewer, send_message
if config['sender'].get('debug'):
logger.info('DEBUG MODE')
should_mock_gwatch_renewer = True
should_skip_send = True
else:
should_skip_send = False
should_mock_gwatch_renewer = should_mock_gwatch_renewer or config.get('skipgmailwatch', False)
should_skip_send = should_skip_send or config.get('skipsend', False)
if should_skip_send:
config['vendors'] = [{
'type': 'iris_dummy',
'name': 'iris dummy vendor'
}]
global quota
quota = ApplicationQuota(db, cache.targets_for_role, message_send_enqueue, config['sender'].get('sender_app'))
global coordinator
zk_hosts = config['sender'].get('zookeeper_cluster', False)
if zk_hosts:
logger.info('Initializing coordinator with ZK: %s', zk_hosts)
from iris.coordinator.kazoo import Coordinator
coordinator = Coordinator(zk_hosts=zk_hosts,
hostname=socket.gethostname(),
port=config['sender'].get('port', 2321),
join_cluster=True)
else:
logger.info('ZK cluster info not specified. Using master status from config')
from iris.coordinator.noncluster import Coordinator
coordinator = Coordinator(is_master=config['sender'].get('is_master', True),
slaves=config['sender'].get('slaves', []))
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print "Stopping..."
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = "pidfile %s does not exist. Not running?\n"
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i = i + 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
if self.verbose >= 1:
print "Stopped"
def stop(self):
"""
Stop the daemon
"""
if self.verbose >= 1:
print('Stopping...')
# Get the pid from the pidfile
pid = self.get_pid()
if not pid:
message = 'pidfile %s does not exist. Not running?\n'
sys.stderr.write(message % self.pidfile)
# Just to be sure. A ValueError might occur if the PID file is
# empty but does actually exist
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
return # Not an error in a restart
# Try killing the daemon process
try:
i = 0
while True:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
i += 1
if i % 10 == 0:
os.kill(pid, signal.SIGHUP)
except OSError as err:
err = str(err)
if err.find('No such process') > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print(str(err))
sys.exit(1)
if self.verbose >= 1:
print('Stopped')