xref: /aosp_15_r20/external/grpc-grpc/test/cpp/naming/utils/dns_server.py (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1#!/usr/bin/env python3
2# Copyright 2015 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Starts a local DNS server for use in tests"""
16
17import argparse
18import os
19import platform
20import signal
21import sys
22import threading
23import time
24
25import twisted
26import twisted.internet
27import twisted.internet.defer
28import twisted.internet.protocol
29import twisted.internet.reactor
30import twisted.internet.threads
31import twisted.names
32from twisted.names import authority
33from twisted.names import client
34from twisted.names import common
35from twisted.names import dns
36from twisted.names import server
37import twisted.names.client
38import twisted.names.dns
39import twisted.names.server
40import yaml
41
42_SERVER_HEALTH_CHECK_RECORD_NAME = (  # missing end '.' for twisted syntax
43    "health-check-local-dns-server-is-alive.resolver-tests.grpctestingexp"
44)
45_SERVER_HEALTH_CHECK_RECORD_DATA = "123.123.123.123"
46
47
48class NoFileAuthority(authority.FileAuthority):
49    def __init__(self, soa, records):
50        # skip FileAuthority
51        common.ResolverBase.__init__(self)
52        self.soa = soa
53        self.records = records
54
55
56def start_local_dns_server(args):
57    all_records = {}
58
59    def _push_record(name, r):
60        name = name.encode("ascii")
61        print("pushing record: |%s|" % name)
62        if all_records.get(name) is not None:
63            all_records[name].append(r)
64            return
65        all_records[name] = [r]
66
67    def _maybe_split_up_txt_data(name, txt_data, r_ttl):
68        txt_data = txt_data.encode("ascii")
69        start = 0
70        txt_data_list = []
71        while len(txt_data[start:]) > 0:
72            next_read = len(txt_data[start:])
73            if next_read > 255:
74                next_read = 255
75            txt_data_list.append(txt_data[start : start + next_read])
76            start += next_read
77        _push_record(name, dns.Record_TXT(*txt_data_list, ttl=r_ttl))
78
79    with open(args.records_config_path) as config:
80        test_records_config = yaml.safe_load(config)
81    common_zone_name = test_records_config["resolver_tests_common_zone_name"]
82    for group in test_records_config["resolver_component_tests"]:
83        for name in group["records"].keys():
84            for record in group["records"][name]:
85                r_type = record["type"]
86                r_data = record["data"]
87                r_ttl = int(record["TTL"])
88                record_full_name = "%s.%s" % (name, common_zone_name)
89                assert record_full_name[-1] == "."
90                record_full_name = record_full_name[:-1]
91                if r_type == "A":
92                    _push_record(
93                        record_full_name, dns.Record_A(r_data, ttl=r_ttl)
94                    )
95                if r_type == "AAAA":
96                    _push_record(
97                        record_full_name, dns.Record_AAAA(r_data, ttl=r_ttl)
98                    )
99                if r_type == "SRV":
100                    p, w, port, target = r_data.split(" ")
101                    p = int(p)
102                    w = int(w)
103                    port = int(port)
104                    target_full_name = (
105                        "%s.%s" % (target, common_zone_name)
106                    ).encode("ascii")
107                    _push_record(
108                        record_full_name,
109                        dns.Record_SRV(p, w, port, target_full_name, ttl=r_ttl),
110                    )
111                if r_type == "TXT":
112                    _maybe_split_up_txt_data(record_full_name, r_data, r_ttl)
113    # Add an optional IPv4 record is specified
114    if args.add_a_record:
115        extra_host, extra_host_ipv4 = args.add_a_record.split(":")
116        _push_record(extra_host, dns.Record_A(extra_host_ipv4, ttl=0))
117    # Server health check record
118    _push_record(
119        _SERVER_HEALTH_CHECK_RECORD_NAME,
120        dns.Record_A(_SERVER_HEALTH_CHECK_RECORD_DATA, ttl=0),
121    )
122    soa_record = dns.Record_SOA(mname=common_zone_name.encode("ascii"))
123    test_domain_com = NoFileAuthority(
124        soa=(common_zone_name.encode("ascii"), soa_record),
125        records=all_records,
126    )
127    server = twisted.names.server.DNSServerFactory(
128        authorities=[test_domain_com], verbose=2
129    )
130    server.noisy = 2
131    twisted.internet.reactor.listenTCP(args.port, server)
132    dns_proto = twisted.names.dns.DNSDatagramProtocol(server)
133    dns_proto.noisy = 2
134    twisted.internet.reactor.listenUDP(args.port, dns_proto)
135    print("starting local dns server on 127.0.0.1:%s" % args.port)
136    print("starting twisted.internet.reactor")
137    twisted.internet.reactor.suggestThreadPoolSize(1)
138    twisted.internet.reactor.run()
139
140
141def _quit_on_signal(signum, _frame):
142    print("Received SIGNAL %d. Quitting with exit code 0" % signum)
143    twisted.internet.reactor.stop()
144    sys.stdout.flush()
145    sys.exit(0)
146
147
148def flush_stdout_loop():
149    num_timeouts_so_far = 0
150    sleep_time = 1
151    # Prevent zombies. Tests that use this server are short-lived.
152    max_timeouts = 60 * 10
153    while num_timeouts_so_far < max_timeouts:
154        sys.stdout.flush()
155        time.sleep(sleep_time)
156        num_timeouts_so_far += 1
157    print("Process timeout reached, or cancelled. Exitting 0.")
158    os.kill(os.getpid(), signal.SIGTERM)
159
160
161def main():
162    argp = argparse.ArgumentParser(
163        description="Local DNS Server for resolver tests"
164    )
165    argp.add_argument(
166        "-p",
167        "--port",
168        default=None,
169        type=int,
170        help="Port for DNS server to listen on for TCP and UDP.",
171    )
172    argp.add_argument(
173        "-r",
174        "--records_config_path",
175        default=None,
176        type=str,
177        help=(
178            "Directory of resolver_test_record_groups.yaml file. "
179            "Defaults to path needed when the test is invoked as part "
180            "of run_tests.py."
181        ),
182    )
183    argp.add_argument(
184        "--add_a_record",
185        default=None,
186        type=str,
187        help=(
188            "Add an A record via the command line. Useful for when we "
189            "need to serve a one-off A record that is under a "
190            "different domain then the rest the records configured in "
191            "--records_config_path (which all need to be under the "
192            "same domain). Format: <name>:<ipv4 address>"
193        ),
194    )
195    args = argp.parse_args()
196    signal.signal(signal.SIGTERM, _quit_on_signal)
197    signal.signal(signal.SIGINT, _quit_on_signal)
198    output_flush_thread = threading.Thread(target=flush_stdout_loop)
199    output_flush_thread.setDaemon(True)
200    output_flush_thread.start()
201    start_local_dns_server(args)
202
203
204if __name__ == "__main__":
205    main()
206