Skip to content

Commit

Permalink
Merge pull request #1893 from Exirel/signals-on-connect
Browse files Browse the repository at this point in the history
bot: signal handler now checks if the bot is connected
  • Loading branch information
dgw authored Jun 23, 2020
2 parents 9c87a35 + 40eb807 commit b5ef93d
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 24 deletions.
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

1 comment on commit b5ef93d

@dgw
Copy link
Member Author

@dgw dgw commented on b5ef93d Jun 23, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CI failure from CoinGecko API being down. When it comes back up, I'll try to get a VCR cassette recorded for the currency plugin.

Update: Re-ran failed CI job (passed) and added cassettes in 41620d0

Please sign in to comment.