File: first_stage_test.py

package info (click to toggle)
python-mitogen 0.3.37-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,728 kB
  • sloc: python: 24,644; sh: 198; makefile: 74; perl: 19; ansic: 18
file content (367 lines) | stat: -rw-r--r-- 13,845 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import errno
import operator
import os

import mitogen.core
import mitogen.parent
from mitogen.core import b

import testlib


def create_child_using_pipes(args, blocking, preexec_fn=None):
    """
    Create a child process whose stdin/stdout/stderr is connected to a pipe.

    :param list args:
        Program argument vector.
    :param bool blocking:
        If :data:`True`, the sockets use blocking IO, otherwise non-blocking.
    :param function preexec_fn:
        If not :data:`None`, a function to run within the post-fork child
        before executing the target program.
    :returns:
        :class:`PopenProcess` instance.
    """

    parent_rfp, child_wfp = mitogen.core.pipe(blocking)
    child_rfp, parent_wfp = mitogen.core.pipe(blocking)
    stderr_r, stderr = mitogen.core.pipe(blocking=blocking)
    mitogen.core.set_cloexec(stderr_r.fileno())
    try:
        proc = testlib.subprocess.Popen(
            args=args,
            stdin=child_rfp,
            stdout=child_wfp,
            stderr=stderr,
            close_fds=True,
            preexec_fn=preexec_fn,
        )
    except Exception:
        parent_rfp.close()
        parent_wfp.close()
        stderr_r.close()
        raise
    finally:
        child_rfp.close()
        child_wfp.close()
        stderr.close()

    return mitogen.parent.PopenProcess(
        proc=proc,
        stdin=parent_wfp,
        stdout=parent_rfp,
        stderr=stderr_r,
    )


def create_child_using_sockets(args, blocking, size=None, preexec_fn=None):
    """
    Create a child process whose stdin/stdout is connected to a socket and stderr to a pipe.

    :param list args:
        Program argument vector.
    :param bool blocking:
        If :data:`True`, the sockets use blocking IO, otherwise non-blocking.
    :param int size:
        If not :data:`None`, use the value as the socket buffer size.
    :param function preexec_fn:
        If not :data:`None`, a function to run within the post-fork child
        before executing the target program.
    :returns:
        :class:`PopenProcess` instance.
    """

    parent_rw_fp, child_rw_fp = mitogen.parent.create_socketpair(size=size, blocking=blocking)
    stderr_r, stderr = mitogen.core.pipe(blocking=blocking)
    mitogen.core.set_cloexec(stderr_r.fileno())
    try:
        proc = testlib.subprocess.Popen(
            args=args,
            stdin=child_rw_fp,
            stdout=child_rw_fp,
            stderr=stderr,
            close_fds=True,
            preexec_fn=preexec_fn,
        )
    except Exception:
        parent_rw_fp.close()
        stderr_r.close()
        raise
    finally:
        child_rw_fp.close()
        stderr.close()

    return mitogen.parent.PopenProcess(
        proc=proc,
        stdin=parent_rw_fp,
        stdout=parent_rw_fp,
        stderr=stderr_r,
    )


class DummyConnectionBlocking(mitogen.parent.Connection):
    """Dummy blocking IO connection"""

    create_child = staticmethod(create_child_using_sockets)
    name_prefix = "dummy_blocking"

    #: Dictionary of extra kwargs passed to :attr:`create_child`.
    #: Use a size smaller than the conn.get_preamble() size so multiple
    #: read-calls are needed in the first stage.
    create_child_args = {"blocking": True, "size": 4096}


class DummyConnectionNonBlocking(mitogen.parent.Connection):
    """Dummy non-blocking IO connection"""

    create_child = staticmethod(create_child_using_sockets)
    name_prefix = "dummy_non_blocking"

    #: Dictionary of extra kwargs passed to :attr:`create_child`.
    #: Use a size smaller than the conn.get_preamble() size so multiple
    #: read-calls are needed in the first stage.
    create_child_args = {"blocking": False, "size": 4096}


class DummyConnectionEOFRead(mitogen.parent.Connection):
    """Dummy connection that triggers an EOF-read(STDIN) in the first_stage"""

    name_prefix = "dummy_eof_read"

    #: Dictionary of extra kwargs passed to :attr:`create_child`.
    create_child_args = {"blocking": True}

    @staticmethod
    def create_child(*a, **kw):
        proc = create_child_using_pipes(*a, **kw)
        # Close the pipe -> results in an EOF-read(STDIN) in the first_stage
        proc.stdin.close()
        # Whatever the parent writes to the child, drop it.
        proc.stdin = open("/dev/null", "wb")
        return proc


class DummyConnectionEndlessBlockingRead(mitogen.parent.Connection):
    """Dummy connection that triggers a non-returning read(STDIN) call in the
    first_stage.

    """

    name_prefix = "dummy_endless_blocking_read"

    #: Dictionary of extra kwargs passed to :attr:`create_child`.
    create_child_args = {"blocking": True}

    @staticmethod
    def create_child(*a, **kw):
        proc = create_child_using_pipes(*a, **kw)
        # Keep the pipe open by having a reference to it, otherwise it would be
        # automatically closed by the garbage collector.
        proc._mitogen_test_orig_stdin = proc.stdin
        # Whatever the parent writes to the child, drop it -> read from STDOUT
        # blocks forever in the fork child as no data could be read.
        proc.stdin = open("/dev/null", "wb")
        return proc


class ConnectionTest(testlib.RouterMixin, testlib.TestCase):
    def test_non_blocking_stdin(self):
        """Test that first stage works with non-blocking STDIN

        The boot command should read the preamble from STDIN, write all ECO
        markers to STDOUT, and then execute the preamble.

        This test writes the complete preamble to non-blocking STDIN.

        1. Fork child reads from non-blocking STDIN
        2. Fork child writes all data as expected by the protocol.
        3. A context call works as expected.

        """
        with testlib.LogCapturer() as _:
            ctx = self.router._connect(DummyConnectionNonBlocking, connect_timeout=0.5)
            self.assertEqual(3, ctx.call(operator.add, 1, 2))

    def test_blocking_stdin(self):
        """Test that first stage works with blocking STDIN

        The boot command should read the preamble from STDIN, write all ECO
        markers to STDOUT, and then execute the preamble.

        This test writes the complete preamble to blocking STDIN.

        1. Fork child reads from blocking STDIN
        2. Fork child writes all data as expected by the protocol.
        3. A context call works as expected.

        """
        with testlib.LogCapturer() as _:
            ctx = self.router._connect(DummyConnectionBlocking, connect_timeout=0.5)
            self.assertEqual(3, ctx.call(operator.add, 1, 2))

    def test_broker_connect_eof_error(self):
        """Test that broker takes care about EOF errors in the first stage

        The boot command should write an ECO marker to stdout, try to read the
        preamble from STDIN. This read returns with an EOF and the process exits.

        This test writes closes the pipe for STDIN of the fork child to enforce an EOF read call.
        1. Fork child reads from STDIN and reads an EOF and breaks the read-loop
        2. Decompressing the received data results in an error
        3. The child process exits
        4. The streams get disconnected -> mitogen.parent.EofError is raised

        """

        with testlib.LogCapturer() as _:
            e = self.assertRaises(mitogen.parent.EofError,
                              self.router._connect, DummyConnectionEOFRead, connect_timeout=0.5)
            self.assertIn("Error -5 while decompressing data", str(e))

            # Test that a TimeoutError is raised by the broker and all resources
            # are cleaned up.
            options = mitogen.parent.Options(
                old_router=self.router,
                max_message_size=self.router.max_message_size,
                connect_timeout=0.5,
            )
            conn = DummyConnectionEOFRead(options, router=self.router)
            e = self.assertRaises(mitogen.parent.EofError,
                                  conn.connect, context=mitogen.core.Context(None, 1234))
            self.assertIn("Error -5 while decompressing data", str(e))
            # Ensure the child process is reaped if the connection times out.
            testlib.wait_for_child(conn.proc.pid)
            e = self.assertRaises(OSError,
                                  os.kill, conn.proc.pid, 0)
            self.assertEqual(e.args[0], errno.ESRCH)

    def test_broker_connect_timeout_because_endless_blocking_read(self):
        """Test that broker takes care about connection timeouts

        The boot command should write an ECO marker to stdout, try to read the
        preamble from STDIN. This read blocks forever as the parent does write
        all the data to /dev/null instead of the pipe. The broker should then
        raise a TimeoutError as the child needs too much time.

        This test writes no data to STDIN of the fork child to enforce a blocking read call.
        1. Fork child tries to read from STDIN, but blocks forever.
        2. Parent connection timeout timer pops up and the parent cleans up
           everything from the child (e.g. kills the child process).
        3. TimeoutError is raised in the connect call

        """
        with testlib.LogCapturer() as _:
            # Ensure the child process is reaped if the connection times out.
            options = mitogen.parent.Options(
                old_router=self.router,
                max_message_size=self.router.max_message_size,
                connect_timeout=0.5,
            )

            conn = DummyConnectionEndlessBlockingRead(options, router=self.router)
            try:
                self.assertRaises(mitogen.core.TimeoutError,
                                  lambda: conn.connect(context=mitogen.core.Context(None, 1234))
                                  )
                testlib.wait_for_child(conn.proc.pid)
                e = self.assertRaises(OSError,
                                      os.kill, conn.proc.pid, 0)
                self.assertEqual(e.args[0], errno.ESRCH)
            finally:
                conn.proc._mitogen_test_orig_stdin.close()


class CommandLineTest(testlib.RouterMixin, testlib.TestCase):
    # Ensure this version of Python produces a command line that is sufficient
    # to bootstrap this version of Python.
    #
    # TODO:
    #   * 2.7 starting 2.4
    #   * 2.7 starting 3.x
    #   * 3.x starting 2.7

    def test_valid_syntax(self):
        """Test valid syntax

        The boot command should write an ECO marker to stdout, read the
        preamble from stdin, then execute it.

        This test attaches /dev/zero to stdin to create a specific failure

        1. Fork child reads <compressed preamble size> bytes of NUL (`b'\0'`)
        2. Fork child crashes (trying to decompress the junk data)
        3. Fork child's file descriptors (write pipes) are closed by the OS
        4. Fork parent does `dup(<read pipe>, <stdin>)` and `exec(<python>)`
        5. Python reads `b''` (i.e. EOF) from stdin (a closed pipe)
        6. Python runs `''` (a valid script) and exits with success

        """

        options = mitogen.parent.Options(max_message_size=123)
        conn = mitogen.parent.Connection(options, self.router)
        conn.context = mitogen.core.Context(None, 123)
        fp = open("/dev/zero", "rb")
        try:
            proc = testlib.subprocess.Popen(
                args=conn.get_boot_command(),
                stdin=fp,
                stdout=testlib.subprocess.PIPE,
                stderr=testlib.subprocess.PIPE,
            )
            stdout, stderr = proc.communicate()
            self.assertEqual(0, proc.returncode)
            self.assertEqual(stdout,
                mitogen.parent.BootstrapProtocol.EC0_MARKER+b('\n'))
            self.assertIn(
                b("Error -3 while decompressing data"),  # Unknown compression method
                stderr,
            )
        finally:
            fp.close()

    def test_premature_eof(self):
        """The boot command should write an ECO marker to stdout, read the
        preamble from stdin, then execute it.

        This test writes some data to STDIN and closes it then to create an
        EOF situation.
        1. Fork child tries to read from STDIN, but stops as EOF is received.
        2. Fork child crashes (trying to decompress the junk data)
        3. Fork child's file descriptors (write pipes) are closed by the OS
        4. Fork parent does `dup(<read pipe>, <stdin>)` and `exec(<python>)`
        5. Python reads `b''` (i.e. EOF) from stdin (a closed pipe)
        6. Python runs `''` (a valid script) and exits with success"""

        options = mitogen.parent.Options(max_message_size=123)
        conn = mitogen.parent.Connection(options, self.router)
        conn.context = mitogen.core.Context(None, 123)
        proc = testlib.subprocess.Popen(
            args=conn.get_boot_command(),
            stdout=testlib.subprocess.PIPE,
            stderr=testlib.subprocess.PIPE,
            stdin=testlib.subprocess.PIPE,
        )

        # Do not send all of the data from the preamble
        proc.stdin.write(conn.get_preamble()[:-128])
        proc.stdin.close()
        try:
            returncode = proc.wait(timeout=1)
        except testlib.subprocess.TimeoutExpired:
            proc.kill()
            proc.wait(timeout=3)
            self.fail("First stage did not handle EOF on STDIN")
        try:
            self.assertEqual(0, returncode)
            self.assertEqual(
                proc.stdout.read(),
                mitogen.parent.BootstrapProtocol.EC0_MARKER + b("\n"),
            )
            self.assertIn(
                b("Error -5 while decompressing data"),
                proc.stderr.read(),
            )
        finally:
            proc.stdout.close()
            proc.stderr.close()