xref: /curl/tests/http/test_19_shutdown.py (revision b42eb27c)
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#***************************************************************************
4#                                  _   _ ____  _
5#  Project                     ___| | | |  _ \| |
6#                             / __| | | | |_) | |
7#                            | (__| |_| |  _ <| |___
8#                             \___|\___/|_| \_\_____|
9#
10# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
11#
12# This software is licensed as described in the file COPYING, which
13# you should have received as part of this distribution. The terms
14# are also available at https://curl.se/docs/copyright.html.
15#
16# You may opt to use, copy, modify, merge, publish, distribute and/or sell
17# copies of the Software, and permit persons to whom the Software is
18# furnished to do so, under the terms of the COPYING file.
19#
20# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21# KIND, either express or implied.
22#
23# SPDX-License-Identifier: curl
24#
25###########################################################################
26#
27import logging
28import re
29import pytest
30
31from testenv import Env, CurlClient, LocalClient
32
33
34log = logging.getLogger(__name__)
35
36
37class TestShutdown:
38
39    @pytest.fixture(autouse=True, scope='class')
40    def _class_scope(self, env, httpd, nghttpx):
41        if env.have_h3():
42            nghttpx.start_if_needed()
43        httpd.clear_extra_configs()
44        httpd.reload()
45
46    @pytest.fixture(autouse=True, scope='class')
47    def _class_scope(self, env, httpd):
48        indir = httpd.docs_dir
49        env.make_data_file(indir=indir, fname="data-10k", fsize=10*1024)
50        env.make_data_file(indir=indir, fname="data-100k", fsize=100*1024)
51        env.make_data_file(indir=indir, fname="data-1m", fsize=1024*1024)
52
53    # check with `tcpdump` that we see curl TCP RST packets
54    @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available")
55    @pytest.mark.parametrize("proto", ['http/1.1'])
56    def test_19_01_check_tcp_rst(self, env: Env, httpd, repeat, proto):
57        if env.ci_run:
58            pytest.skip("seems not to work in CI")
59        curl = CurlClient(env=env)
60        url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]'
61        r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[
62            '--parallel'
63        ])
64        r.check_response(http_status=200, count=2)
65        assert r.tcpdump
66        assert len(r.tcpdump.stats) != 0, f'Expected TCP RSTs packets: {r.tcpdump.stderr}'
67
68    # check with `tcpdump` that we do NOT see TCP RST when CURL_GRACEFUL_SHUTDOWN set
69    @pytest.mark.skipif(condition=not Env.tcpdump(), reason="tcpdump not available")
70    @pytest.mark.parametrize("proto", ['http/1.1', 'h2'])
71    def test_19_02_check_shutdown(self, env: Env, httpd, repeat, proto):
72        if not env.curl_is_debug():
73            pytest.skip('only works for curl debug builds')
74        curl = CurlClient(env=env, run_env={
75            'CURL_GRACEFUL_SHUTDOWN': '2000',
76            'CURL_DEBUG': 'ssl,tcp'
77        })
78        url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]'
79        r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[
80            '--parallel'
81        ])
82        r.check_response(http_status=200, count=2)
83        assert r.tcpdump
84        assert len(r.tcpdump.stats) == 0, 'Unexpected TCP RSTs packets'
85
86    # run downloads where the server closes the connection after each request
87    @pytest.mark.parametrize("proto", ['http/1.1'])
88    def test_19_03_shutdown_by_server(self, env: Env, httpd, repeat, proto):
89        if not env.curl_is_debug():
90            pytest.skip('only works for curl debug builds')
91        count = 10
92        curl = CurlClient(env=env, run_env={
93            'CURL_GRACEFUL_SHUTDOWN': '2000',
94            'CURL_DEBUG': 'ssl'
95        })
96        url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak/?'\
97            f'id=[0-{count-1}]&with_cl&close'
98        r = curl.http_download(urls=[url], alpn_proto=proto)
99        r.check_response(http_status=200, count=count)
100        shutdowns = [line for line in r.trace_lines
101                     if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)]
102        assert len(shutdowns) == count, f'{shutdowns}'
103
104    # run downloads with CURLOPT_FORBID_REUSE set, meaning *we* close
105    # the connection after each request
106    @pytest.mark.parametrize("proto", ['http/1.1'])
107    def test_19_04_shutdown_by_curl(self, env: Env, httpd, proto, repeat):
108        if not env.curl_is_debug():
109            pytest.skip('only works for curl debug builds')
110        count = 10
111        docname = 'data.json'
112        url = f'https://localhost:{env.https_port}/{docname}'
113        client = LocalClient(name='hx-download', env=env, run_env={
114            'CURL_GRACEFUL_SHUTDOWN': '2000',
115            'CURL_DEBUG': 'ssl'
116        })
117        if not client.exists():
118            pytest.skip(f'example client not built: {client.name}')
119        r = client.run(args=[
120             '-n', f'{count}', '-f', '-V', proto, url
121        ])
122        r.check_exit_code(0)
123        shutdowns = [line for line in r.trace_lines
124                     if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)]
125        assert len(shutdowns) == count, f'{shutdowns}'
126
127    # run event-based downloads with CURLOPT_FORBID_REUSE set, meaning *we* close
128    # the connection after each request
129    @pytest.mark.parametrize("proto", ['http/1.1'])
130    def test_19_05_event_shutdown_by_server(self, env: Env, httpd, proto, repeat):
131        if not env.curl_is_debug():
132            pytest.skip('only works for curl debug builds')
133        count = 10
134        curl = CurlClient(env=env, run_env={
135            # forbid connection reuse to trigger shutdowns after transfer
136            'CURL_FORBID_REUSE': '1',
137            # make socket receives block 50% of the time to delay shutdown
138            'CURL_DBG_SOCK_RBLOCK': '50',
139            'CURL_DEBUG': 'ssl'
140        })
141        url = f'https://{env.authority_for(env.domain1, proto)}/curltest/tweak/?'\
142            f'id=[0-{count-1}]&with_cl&'
143        r = curl.http_download(urls=[url], alpn_proto=proto, extra_args=[
144            '--test-event'
145        ])
146        r.check_response(http_status=200, count=count)
147        # check that we closed all connections
148        closings = [line for line in r.trace_lines
149                    if re.match(r'.*CCACHE\] closing #\d+', line)]
150        assert len(closings) == count, f'{closings}'
151        # check that all connection sockets were removed from event
152        removes = [line for line in r.trace_lines
153                   if re.match(r'.*socket cb: socket \d+ REMOVED', line)]
154        assert len(removes) == count, f'{removes}'
155
156    # check graceful shutdown on multiplexed http
157    @pytest.mark.parametrize("proto", ['h2', 'h3'])
158    def test_19_06_check_shutdown(self, env: Env, httpd, nghttpx, repeat, proto):
159        if proto == 'h3' and not env.have_h3():
160            pytest.skip("h3 not supported")
161        if not env.curl_is_debug():
162            pytest.skip('only works for curl debug builds')
163        curl = CurlClient(env=env, run_env={
164            'CURL_GRACEFUL_SHUTDOWN': '2000',
165            'CURL_DEBUG': 'all'
166        })
167        url = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-1]'
168        r = curl.http_download(urls=[url], alpn_proto=proto, with_tcpdump=True, extra_args=[
169            '--parallel'
170        ])
171        r.check_response(http_status=200, count=2)
172        # check connection cache closings
173        shutdowns = [line for line in r.trace_lines
174                     if re.match(r'.*CCACHE\] shutdown #\d+, done=1', line)]
175        assert len(shutdowns) == 1, f'{shutdowns}'
176