Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bot: signal handler now checks if the bot is connected #1893

Merged
merged 1 commit into from
Jun 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions sopel/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import itertools
import logging
import re
import signal
import sys
import threading
import time
Expand All @@ -30,6 +31,18 @@
__all__ = ['Sopel', 'SopelWrapper']

LOGGER = logging.getLogger(__name__)
QUIT_SIGNALS = [
getattr(signal, name)
for name in ['SIGUSR1', 'SIGTERM', 'SIGINT']
if hasattr(signal, name)
]
RESTART_SIGNALS = [
getattr(signal, name)
for name in ['SIGUSR2', 'SIGILL']
if hasattr(signal, name)
]
SIGNALS = QUIT_SIGNALS + RESTART_SIGNALS


if sys.version_info.major >= 3:
unicode = str
Expand Down Expand Up @@ -183,6 +196,49 @@ def hostmask(self):

return self.users.get(self.nick).hostmask

# signal handlers

def set_signal_handlers(self):
"""Set signal handlers for the bot.

Before running the bot, this method can be called from the main thread
to setup signals. If the bot is connected, upon receiving a signal it
will send a ``QUIT`` message. Otherwise, it raises a
:exc:`KeyboardInterrupt` error.

.. note::

Per the Python documentation of :func:`signal.signal`:

When threads are enabled, this function can only be called from
the main thread; attempting to call it from other threads will
cause a :exc:`ValueError` exception to be raised.

"""
for obj in SIGNALS:
signal.signal(obj, self._signal_handler)

def _signal_handler(self, sig, frame):
if sig in QUIT_SIGNALS:
if self.backend.is_connected():
LOGGER.warning('Got quit signal, sending QUIT to server.')
self.quit('Closing')
else:
self.hasquit = True # mark the bot as "want to quit"
LOGGER.warning('Got quit signal.')
raise KeyboardInterrupt
elif sig in RESTART_SIGNALS:
if self.backend.is_connected():
LOGGER.warning('Got restart signal, sending QUIT to server.')
self.restart('Restarting')
else:
LOGGER.warning('Got restart signal.')
self.wantsrestart = True # mark the bot as "want to restart"
self.hasquit = True # mark the bot as "want to quit"
raise KeyboardInterrupt

# setup

def setup(self):
"""Set up Sopel bot before it can run.

Expand Down
20 changes: 2 additions & 18 deletions sopel/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,33 +60,17 @@ def run(settings, pid_file, daemon=False):
tools.stderr(
'Could not open CA certificates file. SSL will not work properly!')

def signal_handler(sig, frame):
if sig == signal.SIGUSR1 or sig == signal.SIGTERM or sig == signal.SIGINT:
LOGGER.warning('Got quit signal, shutting down.')
p.quit('Closing')
elif sig == signal.SIGUSR2 or sig == signal.SIGILL:
LOGGER.warning('Got restart signal, shutting down and restarting.')
p.restart('Restarting')

# Define empty variable `p` for bot
p = None
while True:
if p and p.hasquit: # Check if `hasquit` was set for bot during disconnected phase
break
try:
p = bot.Sopel(settings, daemon=daemon)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, signal_handler)
if hasattr(signal, 'SIGTERM'):
signal.signal(signal.SIGTERM, signal_handler)
if hasattr(signal, 'SIGINT'):
signal.signal(signal.SIGINT, signal_handler)
if hasattr(signal, 'SIGUSR2'):
signal.signal(signal.SIGUSR2, signal_handler)
if hasattr(signal, 'SIGILL'):
signal.signal(signal.SIGILL, signal_handler)
p.setup()
p.set_signal_handlers()
except KeyboardInterrupt:
tools.stderr('Bot setup interrupted')
break
except Exception:
# In that case, there is nothing we can do.
Expand Down
14 changes: 9 additions & 5 deletions sopel/irc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,29 +179,33 @@ def run(self, host, port=6667):
try:
self.backend.run_forever()
except KeyboardInterrupt:
# raised only when the bot is not connected
LOGGER.warning('Keyboard Interrupt')
self.quit('KeyboardInterrupt')

# Connection Events
raise

def on_connect(self):
"""Handle successful establishment of IRC connection."""
LOGGER.info('Connected, initiating setup sequence')

# Request list of server capabilities. IRCv3 servers will respond with
# CAP * LS (which we handle in coretasks). v2 servers will respond with
# 421 Unknown command, which we'll ignore
LOGGER.debug('Sending CAP request')
self.backend.send_command('CAP', 'LS', '302')

# authenticate account if needed
if self.settings.core.auth_method == 'server':
LOGGER.debug('Sending server auth')
self.backend.send_pass(self.settings.core.auth_password)
elif self.settings.core.server_auth_method == 'server':
LOGGER.debug('Sending server auth')
self.backend.send_pass(self.settings.core.server_auth_password)

LOGGER.debug('Sending nick "%s"', self.nick)
self.backend.send_nick(self.nick)
LOGGER.debug('Sending user "%s" (name: "%s")', self.user, self.name)
self.backend.send_user(self.user, '+iw', self.nick, self.name)

LOGGER.info('Connected.')

def on_message(self, message):
"""Handle an incoming IRC message.

Expand Down
2 changes: 1 addition & 1 deletion sopel/irc/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def irc_send(self, data):

:param bytes data: raw line to send

This uses :meth:`asynchat.async_chat.send` method to send ``data``
This uses :meth:`asyncore.dispatcher.send` method to send ``data``
directly. This method is thread-safe.
"""
with self.writing_lock:
Expand Down