Debian Codegraph @

src/python/grpcio_tests/tests/csds/test_csds.py

raw
1 # Copyright 2021 The gRPC Authors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """A simple test to ensure that the Python wrapper can get xDS config."""
15
16 from concurrent.futures import ThreadPoolExecutor
17 import logging
18 import os
19 import queue
20 import sys
21 import time
22 import unittest
23
24 from envoy.service.status.v3 import csds_pb2
25 from envoy.service.status.v3 import csds_pb2_grpc
26 from google.protobuf import json_format
27 import grpc
28 import grpc_csds
29
30 _DUMMY_XDS_ADDRESS = 'xds:///foo.bar'
31 _DUMMY_BOOTSTRAP_FILE = """
32 {
33 \"xds_servers\": [
34 {
35 \"server_uri\": \"fake:///xds_server\",
36 \"channel_creds\": [
37 {
38 \"type\": \"fake\"
39 }
40 ],
41 \"server_features\": [\"xds_v3\"]
42 }
43 ],
44 \"node\": {
45 \"id\": \"python_test_csds\",
46 \"cluster\": \"test\",
47 \"metadata\": {
48 \"foo\": \"bar\"
49 },
50 \"locality\": {
51 \"region\": \"corp\",
52 \"zone\": \"svl\",
53 \"sub_zone\": \"mp3\"
54 }
55 }
56 }\
57 """
58
59
60 @unittest.skipIf(sys.version_info[0] < 3,
61 'ProtoBuf descriptor has moved on from Python2')
62 class TestCsds(unittest.TestCase):
63
64 def setUp(self):
65 os.environ['GRPC_XDS_BOOTSTRAP_CONFIG'] = _DUMMY_BOOTSTRAP_FILE
66 self._server = grpc.server(ThreadPoolExecutor())
67 port = self._server.add_insecure_port('localhost:0')
68 grpc_csds.add_csds_servicer(self._server)
69 self._server.start()
70
71 self._channel = grpc.insecure_channel('localhost:%s' % port)
72 self._stub = csds_pb2_grpc.ClientStatusDiscoveryServiceStub(
73 self._channel)
74
75 def tearDown(self):
76 self._channel.close()
77 self._server.stop(0)
78 os.environ.pop('GRPC_XDS_BOOTSTRAP_CONFIG', None)
79
80 def get_xds_config_dump(self):
81 return self._stub.FetchClientStatus(csds_pb2.ClientStatusRequest())
82
83 def test_has_node(self):
84 resp = self.get_xds_config_dump()
85 self.assertEqual(1, len(resp.config))
86 self.assertEqual('python_test_csds', resp.config[0].node.id)
87 self.assertEqual('test', resp.config[0].node.cluster)
88
89 def test_no_lds_found(self):
90 dummy_channel = grpc.insecure_channel(_DUMMY_XDS_ADDRESS)
91
92 # Force the XdsClient to initialize and request a resource
93 with self.assertRaises(grpc.RpcError) as rpc_error:
94 dummy_channel.unary_unary('')(b'', wait_for_ready=False, timeout=1)
95 self.assertEqual(grpc.StatusCode.DEADLINE_EXCEEDED,
96 rpc_error.exception.code())
97
98 # The resource request will fail with DOES_NOT_EXIST (after 15s)
99 while True:
100 resp = self.get_xds_config_dump()
101 config = json_format.MessageToDict(resp)
102 ok = False
103 try:
104 for xds_config in config["config"][0].get("xdsConfig", []):
105 if "listenerConfig" in xds_config:
106 listener = xds_config["listenerConfig"][
107 "dynamicListeners"][0]
108 if listener['clientStatus'] == 'REQUESTED':
109 ok = True
110 break
111 for generic_xds_config in config["config"][0].get(
112 "genericXdsConfigs", []):
113 if "Listener" in generic_xds_config["typeUrl"]:
114 if generic_xds_config['clientStatus'] == 'REQUESTED':
115 ok = True
116 break
117 except KeyError as e:
118 logging.debug("Invalid config: %s\n%s: %s", config, type(e), e)
119 pass
120 if ok:
121 break
122 time.sleep(1)
123 dummy_channel.close()
124
125
126 @unittest.skipIf(sys.version_info[0] < 3,
127 'ProtoBuf descriptor has moved on from Python2')
128 class TestCsdsStream(TestCsds):
129
130 def get_xds_config_dump(self):
131 if not hasattr(self, 'request_queue'):
132 request_queue = queue.Queue()
133 response_iterator = self._stub.StreamClientStatus(
134 iter(request_queue.get, None))
135 request_queue.put(csds_pb2.ClientStatusRequest())
136 return next(response_iterator)
137
138
139 if __name__ == "__main__":
140 logging.basicConfig(level=logging.DEBUG)
141 unittest.main(verbosity=2)