File: helper.py

package info (click to toggle)
manhole 1.8.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 444 kB
  • sloc: python: 1,661; makefile: 3
file content (290 lines) | stat: -rw-r--r-- 10,369 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import atexit
import errno
import logging
import os
import signal
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'
OUTPUT = sys.__stdout__


def handle_sigterm(signo, _frame):
    # Simulate real termination
    print('Terminated', file=OUTPUT)
    sys.exit(128 + signo)


# Handling sigterm ensure that atexit functions are called, and we do not leave
# leftover /tmp/manhole-pid sockets.
signal.signal(signal.SIGTERM, handle_sigterm)


@atexit.register
def log_exit():
    print('In atexit handler.', file=OUTPUT)


def setup_greenthreads(patch_threads=False):
    try:
        from gevent import monkey

        monkey.patch_all(thread=False)
    except (ImportError, SyntaxError):
        pass

    try:
        import eventlet

        eventlet.hubs.get_hub()  # workaround for circular import issue in eventlet,
        # see https://github.com/eventlet/eventlet/issues/401
        eventlet.monkey_patch(thread=False)
    except (ImportError, SyntaxError):
        pass


def do_fork():
    pid = os.fork()
    if pid:

        @atexit.register
        def cleanup():
            try:
                os.kill(pid, signal.SIGINT)
                time.sleep(0.2)
                os.kill(pid, signal.SIGTERM)
            except OSError as e:
                if e.errno != errno.ESRCH:
                    raise

        os.waitpid(pid, 0)
    else:
        time.sleep(TIMEOUT * 10)


if __name__ == '__main__':
    logging.basicConfig(
        level=logging.DEBUG,
        format='[pid=%(process)d - %(asctime)s]: %(name)s - %(levelname)s - %(message)s',
    )
    test_name = sys.argv[1]
    try:
        if os.getenv('PATCH_THREAD', False):
            import manhole

            setup_greenthreads(True)
        else:
            setup_greenthreads(True)
            import manhole

        if test_name == 'test_environ_variable_activation':
            print(f'Sleeping {TIMEOUT} seconds...')
            time.sleep(TIMEOUT)
        elif test_name == 'test_install_twice_not_strict':
            manhole.install(oneshot_on='USR2')
            manhole.install(strict=False)
            time.sleep(TIMEOUT)
        elif test_name == 'test_unbuffered':
            manhole.install(verbose=True)
            print(os.getpid())
            for i in range(5):
                time.sleep(1)
                print(f'line{i}')
                sys.stdout.flush()
        elif test_name == 'test_log_fd':
            manhole.install(verbose=True, verbose_destination=2)
            manhole._LOG('whatever-1')
            manhole._LOG('whatever-2')
        elif test_name == 'test_log_fh':

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

            manhole.install(verbose=True, verbose_destination=Output)
            manhole._LOG('whatever')
            if Output.data and ']: whatever' in Output.data[-1]:
                print('SUCCESS')
        elif test_name == 'test_activate_on_usr2':
            manhole.install(activate_on='USR2')
            for _ in range(TIMEOUT * 100):
                time.sleep(0.1)
        elif test_name == 'test_install_once':
            manhole.install()
            try:
                manhole.install()
            except manhole.AlreadyInstalled:
                print('ALREADY_INSTALLED')
            else:
                raise AssertionError('Did not raise AlreadyInstalled')
        elif test_name == 'test_stderr_doesnt_deadlock':
            import subprocess

            manhole.install()

            for i in range(50):
                print('running iteration', i)
                p = subprocess.Popen(['true'])
                print('waiting for process', p.pid)
                p.wait()
                print('process ended')
                path = '/tmp/manhole-%d' % p.pid
                if os.path.exists(path):
                    os.unlink(path)
                    raise AssertionError(path + ' exists !')
            print('SUCCESS')
        elif test_name == 'test_fork_exec':
            manhole.install(reinstall_delay=5)
            print('Installed.')
            time.sleep(0.2)
            pid = os.fork()
            print('Forked, pid =', pid)
            if pid:
                os.waitpid(pid, 0)
                path = '/tmp/manhole-%d' % pid
                if os.path.exists(path):
                    os.unlink(path)
                    raise AssertionError(path + ' exists !')
            else:
                try:
                    time.sleep(1)
                    print('Exec-ing `true`')
                    os.execvp('true', ['true'])
                finally:
                    os._exit(1)
            print('SUCCESS')
        elif test_name == 'test_activate_on_with_oneshot_on':
            manhole.install(activate_on='USR2', oneshot_on='USR2')
            for _ in range(TIMEOUT * 100):
                time.sleep(0.1)
        elif test_name == 'test_interrupt_on_accept':

            def handle_usr2(_sig, _frame):
                print('Got USR2')

            signal.signal(signal.SIGUSR2, handle_usr2)

            import ctypes
            import ctypes.util

            libpthread_path = ctypes.util.find_library('pthread')
            if not libpthread_path:
                raise ImportError('ctypes.util.find_library("pthread") failed')
            libpthread = ctypes.CDLL(libpthread_path)
            if not hasattr(libpthread, 'pthread_setname_np'):
                raise ImportError('libpthread.pthread_setname_np missing')
            pthread_kill = libpthread.pthread_kill
            pthread_kill.argtypes = [ctypes.c_void_p, ctypes.c_int]
            pthread_kill.restype = ctypes.c_int
            manhole.install(sigmask=None)
            for _ in range(15):
                time.sleep(0.1)
            print('Sending signal to manhole thread ...')
            pthread_kill(manhole._MANHOLE.thread.ident, signal.SIGUSR2)
            for _ in range(TIMEOUT * 100):
                time.sleep(0.1)
        elif test_name == 'test_oneshot_on_usr2':
            manhole.install(oneshot_on='USR2')
            for _ in range(TIMEOUT * 100):
                time.sleep(0.1)
        elif test_name.startswith('test_signalfd_weirdness'):
            signalled = False

            @partial(signal.signal, signal.SIGUSR1)
            def signal_handler(sig, _):
                print(f'Received signal {sig}')
                global signalled
                signalled = True

            if 'negative' in test_name:
                manhole.install(sigmask=None)
            else:
                manhole.install(sigmask=[signal.SIGUSR1])

            time.sleep(0.3)  # give the manhole a bit enough time to start
            print('Starting ...')
            import signalfd

            signalfd.sigprocmask(signalfd.SIG_BLOCK, [signal.SIGUSR1])
            sys.setcheckinterval(1)
            for _ in range(100000):
                os.kill(os.getpid(), signal.SIGUSR1)
            print(f'signalled={signalled}')
            time.sleep(TIMEOUT * 10)
        elif test_name == 'test_auth_fail':
            manhole.get_peercred = lambda _: (-1, -1, -1)
            manhole.install()
            time.sleep(TIMEOUT * 10)
        elif test_name == 'test_socket_path':
            manhole.install(socket_path=SOCKET_PATH)
            time.sleep(TIMEOUT * 10)
        elif test_name == 'test_daemon_connection':
            manhole.install(daemon_connection=True)
            time.sleep(TIMEOUT)
        elif test_name == 'test_socket_path_with_fork':
            manhole.install(socket_path=SOCKET_PATH)
            time.sleep(TIMEOUT)
            do_fork()
        elif test_name == 'test_locals':
            manhole.install(socket_path=SOCKET_PATH, locals={'k1': 'v1', 'k2': 'v2'})
            time.sleep(TIMEOUT)
        elif test_name == 'test_locals_after_fork':
            manhole.install(locals={'k1': 'v1', 'k2': 'v2'})
            do_fork()
        elif test_name == 'test_redirect_stderr_default':
            manhole.install(socket_path=SOCKET_PATH)
            time.sleep(TIMEOUT)
        elif test_name == 'test_redirect_stderr_disabled':
            manhole.install(socket_path=SOCKET_PATH, redirect_stderr=False)
            time.sleep(TIMEOUT)
        elif test_name == 'test_sigmask':
            manhole.install(socket_path=SOCKET_PATH, sigmask=[signal.SIGUSR1])
            time.sleep(TIMEOUT)
        elif test_name == 'test_connection_handler_exec_func':
            manhole.install(connection_handler=manhole.handle_connection_exec, locals={'tete': lambda: print('TETE')})
            time.sleep(TIMEOUT * 10)
        elif test_name == 'test_connection_handler_exec_str':
            manhole.install(connection_handler='exec', locals={'tete': lambda: print('TETE')})
            time.sleep(TIMEOUT * 10)
        else:
            manhole.install()
            time.sleep(0.3)  # give the manhole a bit enough time to start
            if test_name == 'test_simple':
                time.sleep(TIMEOUT * 10)
            elif test_name == 'test_with_forkpty':
                time.sleep(1)
                pid, masterfd = os.forkpty()
                if pid:

                    @atexit.register
                    def cleanup():
                        try:
                            os.kill(pid, signal.SIGINT)
                            time.sleep(0.2)
                            os.kill(pid, signal.SIGTERM)
                        except OSError as e:
                            if e.errno != errno.ESRCH:
                                raise

                    while not os.waitpid(pid, os.WNOHANG)[0]:
                        try:
                            os.write(2, os.read(masterfd, 1024))
                        except OSError as e:
                            print('Error while reading from masterfd:', e)
                else:
                    time.sleep(TIMEOUT * 10)
            elif test_name == 'test_with_fork':
                time.sleep(1)
                do_fork()
            else:
                raise RuntimeError('Invalid test spec.')
    except:  # noqa
        print(f'Died with {sys.exc_info()[0].__name__}.', file=OUTPUT)
        import traceback

        traceback.print_exc(file=OUTPUT)
    print('DIED.', file=OUTPUT)