Skip to content

Commit

Permalink
Apply more cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
ionelmc committed Dec 18, 2023
1 parent 602f540 commit 0fb66e6
Show file tree
Hide file tree
Showing 7 changed files with 33 additions and 25 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ repos:
rev: v0.1.8
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix, --show-fixes]
args: [--fix, --exit-non-zero-on-fix, --show-fixes, --unsafe-fixes]
- repo: https://github.com/psf/black
rev: 23.12.0
hooks:
Expand Down
9 changes: 8 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ ignore = [
"S101", # flake8-bandit assert
"S308", # flake8-bandit suspicious-mark-safe-usage
"E501", # pycodestyle line-too-long
"B008",
"S108",
"S110",
"S307",
"S603",
"S606",
"S607",
]
line-length = 140
select = [
Expand All @@ -28,7 +35,7 @@ select = [
"PLC", # pylint convention
"PLE", # pylint errors
"PT", # flake8-pytest-style
"PTH", # flake8-use-pathlib
# "PTH", # flake8-use-pathlib
"Q", # flake8-quotes
"RSE", # flake8-raise
"RUF", # ruff-specific rules
Expand Down
18 changes: 9 additions & 9 deletions src/manhole/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ class ManholeThread(_ORIGINAL_THREAD):
"""

def __init__(self, get_socket, sigmask, start_timeout, connection_handler, bind_delay=None, daemon_connection=False):
super(ManholeThread, self).__init__()
super().__init__()
self.daemon = True
self.daemon_connection = daemon_connection
self.name = 'Manhole'
Expand Down Expand Up @@ -184,7 +184,7 @@ def clone(self, **kwargs):

def start(self):
self.should_run = True
super(ManholeThread, self).start()
super().start()
if not self.serious.wait(self.start_timeout):
_LOG("WARNING: Waited %s seconds but Manhole thread didn't start yet :(" % self.start_timeout)

Expand Down Expand Up @@ -228,7 +228,7 @@ class ManholeConnectionThread(_ORIGINAL_THREAD):
"""

def __init__(self, client, connection_handler, daemon=False):
super(ManholeConnectionThread, self).__init__()
super().__init__()
self.daemon = daemon
self.client = force_original_socket(client)
self.connection_handler = connection_handler
Expand All @@ -253,11 +253,11 @@ def check_credentials(client):
pid, uid, gid = get_peercred(client)

euid = os.geteuid()
client_name = 'PID:%s UID:%s GID:%s' % (pid, uid, gid)
client_name = f'PID:{pid} UID:{uid} GID:{gid}'
if uid not in (0, euid):
raise SuspiciousClient("Can't accept client with %s. It doesn't match the current EUID:%s or ROOT." % (client_name, euid))
raise SuspiciousClient(f"Can't accept client with {client_name}. It doesn't match the current EUID:{euid} or ROOT.")

_LOG('Accepted connection on fd:%s from %s' % (client.fileno(), client_name))
_LOG(f'Accepted connection on fd:{client.fileno()} from {client_name}')
return pid, uid, gid


Expand Down Expand Up @@ -403,7 +403,7 @@ def __call__(self, message):
if self.destination is None:
raise NotInstalled('Manhole is not installed!')
try:
full_message = 'Manhole[%s:%.4f]: %s\n' % (os.getpid(), self.time(), message)
full_message = f'Manhole[{os.getpid()}:{self.time():.4f}]: {message}\n'

if isinstance(self.destination, int):
os.write(self.destination, full_message.encode('ascii', 'ignore'))
Expand Down Expand Up @@ -571,7 +571,7 @@ def patched_forkpty(self):
def patch_os_fork_functions(self):
self.original_os_fork, os.fork = os.fork, self.patched_fork
self.original_os_forkpty, os.forkpty = os.forkpty, self.patched_forkpty
_LOG('Patched %s and %s.' % (self.original_os_fork, self.original_os_forkpty))
_LOG(f'Patched {self.original_os_fork} and {self.original_os_forkpty}.')

def restore_os_fork_functions(self):
if self.original_os_fork:
Expand Down Expand Up @@ -643,7 +643,7 @@ def dump_stacktraces():
"""
lines = []
for thread_id, stack in sys._current_frames().items(): # pylint: disable=W0212
lines.append('\n######### ProcessID=%s, ThreadID=%s #########' % (os.getpid(), thread_id))
lines.append(f'\n######### ProcessID={os.getpid()}, ThreadID={thread_id} #########')
for filename, lineno, name, line in traceback.extract_stack(stack):
lines.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
Expand Down
6 changes: 3 additions & 3 deletions src/manhole/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def parse_signal(value):
return value
else:
raise argparse.ArgumentTypeError(
'Invalid signal number %s. Expected one of: %s' % (value, ', '.join(str(i) for i in SIG_NUMBERS))
'Invalid signal number {}. Expected one of: {}'.format(value, ', '.join(str(i) for i in SIG_NUMBERS))
)
value = value.upper()
if value in SIG_NAMES:
Expand Down Expand Up @@ -81,7 +81,7 @@ def parse_signal(value):

class ConnectionHandler(threading.Thread):
def __init__(self, sock, is_closing):
super(ConnectionHandler, self).__init__()
super().__init__()
self.sock = sock
self.is_closing = is_closing

Expand Down Expand Up @@ -127,7 +127,7 @@ def main():
sock.connect(uds_path)
except Exception as exc:
if exc.errno not in (errno.ENOENT, errno.ECONNREFUSED):
print('Failed to connect to %r: %r' % (uds_path, exc), file=sys.stderr)
print(f'Failed to connect to {uds_path!r}: {exc!r}', file=sys.stderr)
else:
break
else:
Expand Down
15 changes: 8 additions & 7 deletions tests/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import sys
import time
from functools import partial
from typing import ClassVar

TIMEOUT = int(os.getenv('MANHOLE_TEST_TIMEOUT', 10))
SOCKET_PATH = '/tmp/manhole-socket'
Expand Down Expand Up @@ -93,7 +94,7 @@ def cleanup():
elif test_name == 'test_log_fh':

class Output:
data = []
data: ClassVar = []
write = data.append

manhole.install(verbose=True, verbose_destination=Output)
Expand All @@ -102,7 +103,7 @@ class Output:
print('SUCCESS')
elif test_name == 'test_activate_on_usr2':
manhole.install(activate_on='USR2')
for i in range(TIMEOUT * 100):
for _ in range(TIMEOUT * 100):
time.sleep(0.1)
elif test_name == 'test_install_once':
manhole.install()
Expand Down Expand Up @@ -150,7 +151,7 @@ class Output:
print('SUCCESS')
elif test_name == 'test_activate_on_with_oneshot_on':
manhole.install(activate_on='USR2', oneshot_on='USR2')
for i in range(TIMEOUT * 100):
for _ in range(TIMEOUT * 100):
time.sleep(0.1)
elif test_name == 'test_interrupt_on_accept':

Expand All @@ -172,15 +173,15 @@ def handle_usr2(_sig, _frame):
pthread_kill.argtypes = [ctypes.c_void_p, ctypes.c_int]
pthread_kill.restype = ctypes.c_int
manhole.install(sigmask=None)
for i in range(15):
for _ in range(15):
time.sleep(0.1)
print('Sending signal to manhole thread ...')
pthread_kill(manhole._MANHOLE.thread.ident, signal.SIGUSR2)
for i in range(TIMEOUT * 100):
for _ in range(TIMEOUT * 100):
time.sleep(0.1)
elif test_name == 'test_oneshot_on_usr2':
manhole.install(oneshot_on='USR2')
for i in range(TIMEOUT * 100):
for _ in range(TIMEOUT * 100):
time.sleep(0.1)
elif test_name.startswith('test_signalfd_weirdness'):
signalled = False
Expand All @@ -202,7 +203,7 @@ def signal_handler(sig, _):

signalfd.sigprocmask(signalfd.SIG_BLOCK, [signal.SIGUSR1])
sys.setcheckinterval(1)
for i in range(100000):
for _ in range(100000):
os.kill(os.getpid(), signal.SIGUSR1)
print('signalled=%s' % signalled)
time.sleep(TIMEOUT * 10)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_manhole.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def connect_to_manhole(uds_path):
sock.connect(uds_path)
return sock
except Exception as exc:
print('Failed to connect to %s: %s' % (uds_path, exc))
print(f'Failed to connect to {uds_path}: {exc}')
if i + 1 == TIMEOUT:
sock.close()
raise
Expand Down Expand Up @@ -551,7 +551,7 @@ def test_uwsgi():
with dump_on_error(proc.read):
wait_for_strings(proc.read, TIMEOUT, 'uWSGI http bound')
port = re.findall(r'uWSGI http bound on :(\d+) fd', proc.read())[0]
assert requests.get('http://127.0.0.1:%s/' % port).text == 'OK'
assert requests.get('http://127.0.0.1:%s/' % port, timeout=TIMEOUT).text == 'OK'

wait_for_strings(proc.read, TIMEOUT, 'spawned uWSGI worker 1')
pid = re.findall(r'spawned uWSGI worker 1 \(pid: (\d+), ', proc.read())[0]
Expand Down
4 changes: 2 additions & 2 deletions tests/wsgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ def open_manhole(dummy_signum):
uwsgi.register_signal(uwsgi_signal_number, 'workers', open_manhole)
uwsgi.add_file_monitor(uwsgi_signal_number, stack_dump_file)

print('Listening for stack manhole requests via %r' % (stack_dump_file,), file=sys.stderr)
print(f'Listening for stack manhole requests via {stack_dump_file!r}', file=sys.stderr)
except ImportError:
print('Not running under uwsgi; unable to configure manhole trigger', file=sys.stderr)
except OSError:
print('IOError creating manhole trigger %r' % (stack_dump_file,), file=sys.stderr)
print(f'IOError creating manhole trigger {stack_dump_file!r}', file=sys.stderr)


def application(env, sr):
Expand Down

0 comments on commit 0fb66e6

Please sign in to comment.