| 1 | """Launch one rsync daemon session over a local socketpair.""" |
| 2 | |
| 3 | import socket |
| 4 | import subprocess |
| 5 | |
| 6 | import rsync_proto as rp |
| 7 | |
| 8 | from rsyncfns import rsync_argv |
| 9 | |
| 10 | |
| 11 | def _client_for_socket(sock, timeout=10): |
| 12 | client = object.__new__(rp.DaemonClient) |
| 13 | client.sock = sock |
| 14 | client.sock.settimeout(timeout) |
| 15 | client.protocol = rp.DEFAULT_PROTOCOL |
| 16 | client.compat_flags = None |
| 17 | client.seed = None |
| 18 | client.xfer_sum_len = 16 |
| 19 | client._rbuf = b'' |
| 20 | client._ndx_prev_positive = -1 |
| 21 | client._ndx_prev_negative = 1 |
| 22 | client._mux_in = b'' |
| 23 | client._r_ndx_prev_positive = -1 |
| 24 | client._r_ndx_prev_negative = 1 |
| 25 | client.messages = [] |
| 26 | return client |
| 27 | |
| 28 | |
| 29 | def start_stdio_daemon(conf, timeout=10, env=None): |
| 30 | """Return ``(DaemonClient, Popen)`` for one daemon connection.""" |
| 31 | parent, child = socket.socketpair() |
| 32 | try: |
| 33 | proc = subprocess.Popen( |
| 34 | rsync_argv('--daemon', '--no-detach', f'--config={conf}'), |
| 35 | stdin=child.fileno(), stdout=child.fileno(), |
| 36 | stderr=subprocess.PIPE, close_fds=True, env=env, |
| 37 | ) |
| 38 | except Exception: |
| 39 | parent.close() |
| 40 | child.close() |
| 41 | raise |
| 42 | child.close() |
| 43 | return _client_for_socket(parent, timeout), proc |
| 44 | |
| 45 | |
| 46 | def finish_stdio_daemon(client, proc, timeout=5): |
| 47 | """Close a test session and return the daemon's stderr text.""" |
| 48 | try: |
| 49 | client.drain(timeout=0.25) |
| 50 | except OSError: |
| 51 | pass |
| 52 | client.close() |
| 53 | try: |
| 54 | proc.wait(timeout=timeout) |
| 55 | except subprocess.TimeoutExpired: |
| 56 | proc.terminate() |
| 57 | try: |
| 58 | proc.wait(timeout=timeout) |
| 59 | except subprocess.TimeoutExpired: |
| 60 | proc.kill() |
| 61 | proc.wait(timeout=timeout) |
| 62 | return proc.stderr.read().decode('utf-8', 'replace') if proc.stderr else '' |
| 63 |