-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun_xds_tests.py
executable file
·4343 lines (4084 loc) · 156 KB
/
run_xds_tests.py
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2020 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run xDS integration tests on GCP using Traffic Director."""
import argparse
import datetime
import json
import logging
import os
import random
import re
import shlex
import socket
import subprocess
import sys
import tempfile
import time
import uuid
from google.protobuf import json_format
import googleapiclient.discovery
import grpc
from oauth2client.client import GoogleCredentials
import python_utils.jobset as jobset
import python_utils.report_utils as report_utils
from src.proto.grpc.health.v1 import health_pb2
from src.proto.grpc.health.v1 import health_pb2_grpc
from src.proto.grpc.testing import empty_pb2
from src.proto.grpc.testing import messages_pb2
from src.proto.grpc.testing import test_pb2_grpc
# Envoy protos provided by PyPI package xds-protos
# Needs to import the generated Python file to load descriptors
try:
from envoy.extensions.filters.common.fault.v3 import fault_pb2
from envoy.extensions.filters.http.fault.v3 import fault_pb2
from envoy.extensions.filters.http.router.v3 import router_pb2
from envoy.extensions.filters.network.http_connection_manager.v3 import (
http_connection_manager_pb2,
)
from envoy.service.status.v3 import csds_pb2
from envoy.service.status.v3 import csds_pb2_grpc
except ImportError:
# These protos are required by CSDS test. We should not fail the entire
# script for one test case.
pass
logger = logging.getLogger()
console_handler = logging.StreamHandler()
formatter = logging.Formatter(fmt="%(asctime)s: %(levelname)-8s %(message)s")
console_handler.setFormatter(formatter)
logger.handlers = []
logger.addHandler(console_handler)
logger.setLevel(logging.WARNING)
# Suppress excessive logs for gRPC Python
original_grpc_trace = os.environ.pop("GRPC_TRACE", None)
original_grpc_verbosity = os.environ.pop("GRPC_VERBOSITY", None)
# Suppress not-essential logs for GCP clients
logging.getLogger("google_auth_httplib2").setLevel(logging.WARNING)
logging.getLogger("googleapiclient.discovery").setLevel(logging.WARNING)
_TEST_CASES = [
"backends_restart",
"change_backend_service",
"gentle_failover",
"load_report_based_failover",
"ping_pong",
"remove_instance_group",
"round_robin",
"secondary_locality_gets_no_requests_on_partial_primary_failure",
"secondary_locality_gets_requests_on_primary_failure",
"traffic_splitting",
"path_matching",
"header_matching",
"api_listener",
"forwarding_rule_port_match",
"forwarding_rule_default_port",
"metadata_filter",
]
# Valid test cases, but not in all. So the tests can only run manually, and
# aren't enabled automatically for all languages.
#
# TODO: Move them into _TEST_CASES when support is ready in all languages.
_ADDITIONAL_TEST_CASES = [
"circuit_breaking",
"timeout",
"fault_injection",
"csds",
]
# Test cases that require the V3 API. Skipped in older runs.
_V3_TEST_CASES = frozenset(["timeout", "fault_injection", "csds"])
# Test cases that require the alpha API. Skipped for stable API runs.
_ALPHA_TEST_CASES = frozenset(["timeout"])
def parse_test_cases(arg):
if arg == "":
return []
arg_split = arg.split(",")
test_cases = set()
all_test_cases = _TEST_CASES + _ADDITIONAL_TEST_CASES
for arg in arg_split:
if arg == "all":
test_cases = test_cases.union(_TEST_CASES)
else:
test_cases = test_cases.union([arg])
if not all([test_case in all_test_cases for test_case in test_cases]):
raise Exception("Failed to parse test cases %s" % arg)
# Preserve order.
return [x for x in all_test_cases if x in test_cases]
def parse_port_range(port_arg):
try:
port = int(port_arg)
return list(range(port, port + 1))
except:
port_min, port_max = port_arg.split(":")
return list(range(int(port_min), int(port_max) + 1))
argp = argparse.ArgumentParser(description="Run xDS interop tests on GCP")
# TODO(zdapeng): remove default value of project_id and project_num
argp.add_argument("--project_id", default="grpc-testing", help="GCP project id")
argp.add_argument(
"--project_num", default="830293263384", help="GCP project number"
)
argp.add_argument(
"--gcp_suffix",
default="",
help=(
"Optional suffix for all generated GCP resource names. Useful to "
"ensure distinct names across test runs."
),
)
argp.add_argument(
"--test_case",
default="ping_pong",
type=parse_test_cases,
help=(
"Comma-separated list of test cases to run. Available tests: %s, "
"(or 'all' to run every test). "
"Alternative tests not included in 'all': %s"
)
% (",".join(_TEST_CASES), ",".join(_ADDITIONAL_TEST_CASES)),
)
argp.add_argument(
"--bootstrap_file",
default="",
help=(
"File to reference via GRPC_XDS_BOOTSTRAP. Disables built-in "
"bootstrap generation"
),
)
argp.add_argument(
"--xds_v3_support",
default=False,
action="store_true",
help=(
"Support xDS v3 via GRPC_XDS_EXPERIMENTAL_V3_SUPPORT. "
"If a pre-created bootstrap file is provided via the --bootstrap_file "
"parameter, it should include xds_v3 in its server_features field."
),
)
argp.add_argument(
"--client_cmd",
default=None,
help=(
"Command to launch xDS test client. {server_uri}, {stats_port} and"
" {qps} references will be replaced using str.format()."
" GRPC_XDS_BOOTSTRAP will be set for the command"
),
)
argp.add_argument(
"--client_hosts",
default=None,
help=(
"Comma-separated list of hosts running client processes. If set,"
" --client_cmd is ignored and client processes are assumed to be"
" running on the specified hosts."
),
)
argp.add_argument("--zone", default="us-central1-a")
argp.add_argument(
"--secondary_zone",
default="us-west1-b",
help="Zone to use for secondary TD locality tests",
)
argp.add_argument("--qps", default=100, type=int, help="Client QPS")
argp.add_argument(
"--wait_for_backend_sec",
default=1200,
type=int,
help=(
"Time limit for waiting for created backend services to report "
"healthy when launching or updated GCP resources"
),
)
argp.add_argument(
"--use_existing_gcp_resources",
default=False,
action="store_true",
help=(
"If set, find and use already created GCP resources instead of creating"
" new ones."
),
)
argp.add_argument(
"--keep_gcp_resources",
default=False,
action="store_true",
help=(
"Leave GCP VMs and configuration running after test. Default behavior"
" is to delete when tests complete."
),
)
argp.add_argument(
"--halt_after_fail",
action="store_true",
help="Halt and save the resources when test failed.",
)
argp.add_argument(
"--compute_discovery_document",
default=None,
type=str,
help=(
"If provided, uses this file instead of retrieving via the GCP"
" discovery API"
),
)
argp.add_argument(
"--alpha_compute_discovery_document",
default=None,
type=str,
help=(
"If provided, uses this file instead of retrieving via the alpha GCP "
"discovery API"
),
)
argp.add_argument(
"--network", default="global/networks/default", help="GCP network to use"
)
_DEFAULT_PORT_RANGE = "8080:8280"
argp.add_argument(
"--service_port_range",
default=_DEFAULT_PORT_RANGE,
type=parse_port_range,
help=(
"Listening port for created gRPC backends. Specified as "
"either a single int or as a range in the format min:max, in "
"which case an available port p will be chosen s.t. min <= p "
"<= max"
),
)
argp.add_argument(
"--stats_port",
default=8079,
type=int,
help="Local port for the client process to expose the LB stats service",
)
argp.add_argument(
"--xds_server",
default="trafficdirector.googleapis.com:443",
help="xDS server",
)
argp.add_argument(
"--source_image",
default="projects/debian-cloud/global/images/family/debian-9",
help="Source image for VMs created during the test",
)
argp.add_argument(
"--path_to_server_binary",
default=None,
type=str,
help=(
"If set, the server binary must already be pre-built on "
"the specified source image"
),
)
argp.add_argument(
"--machine_type",
default="e2-standard-2",
help="Machine type for VMs created during the test",
)
argp.add_argument(
"--instance_group_size",
default=2,
type=int,
help=(
"Number of VMs to create per instance group. Certain test cases (e.g.,"
" round_robin) may not give meaningful results if this is set to a"
" value less than 2."
),
)
argp.add_argument(
"--verbose", help="verbose log output", default=False, action="store_true"
)
# TODO(ericgribkoff) Remove this param once the sponge-formatted log files are
# visible in all test environments.
argp.add_argument(
"--log_client_output",
help="Log captured client output",
default=False,
action="store_true",
)
# TODO(ericgribkoff) Remove this flag once all test environments are verified to
# have access to the alpha compute APIs.
argp.add_argument(
"--only_stable_gcp_apis",
help=(
"Do not use alpha compute APIs. Some tests may be "
"incompatible with this option (gRPC health checks are "
"currently alpha and required for simulating server failure"
),
default=False,
action="store_true",
)
args = argp.parse_args()
if args.verbose:
logger.setLevel(logging.DEBUG)
# In grpc-testing, use non-legacy network.
if (
args.project_id == "grpc-testing"
and args.network
and args.network == argp.get_default("network")
):
args.network += "-vpc"
CLIENT_HOSTS = []
if args.client_hosts:
CLIENT_HOSTS = args.client_hosts.split(",")
# Each of the config propagation in the control plane should finish within 600s.
# Otherwise, it indicates a bug in the control plane. The config propagation
# includes all kinds of traffic config update, like updating urlMap, creating
# the resources for the first time, updating BackendService, and changing the
# status of endpoints in BackendService.
_WAIT_FOR_URL_MAP_PATCH_SEC = 600
# In general, fetching load balancing stats only takes ~10s. However, slow
# config update could lead to empty EDS or similar symptoms causing the
# connection to hang for a long period of time. So, we want to extend the stats
# wait time to be the same as urlMap patch time.
_WAIT_FOR_STATS_SEC = _WAIT_FOR_URL_MAP_PATCH_SEC
_DEFAULT_SERVICE_PORT = 80
_WAIT_FOR_BACKEND_SEC = args.wait_for_backend_sec
_WAIT_FOR_OPERATION_SEC = 1200
_INSTANCE_GROUP_SIZE = args.instance_group_size
_NUM_TEST_RPCS = 10 * args.qps
_CONNECTION_TIMEOUT_SEC = 60
_GCP_API_RETRIES = 5
_BOOTSTRAP_TEMPLATE = """
{{
"node": {{
"id": "{node_id}",
"metadata": {{
"TRAFFICDIRECTOR_NETWORK_NAME": "%s",
"com.googleapis.trafficdirector.config_time_trace": "TRUE"
}},
"locality": {{
"zone": "%s"
}}
}},
"xds_servers": [{{
"server_uri": "%s",
"channel_creds": [
{{
"type": "google_default",
"config": {{}}
}}
],
"server_features": {server_features}
}}]
}}""" % (
args.network.split("/")[-1],
args.zone,
args.xds_server,
)
# TODO(ericgribkoff) Add change_backend_service to this list once TD no longer
# sends an update with no localities when adding the MIG to the backend service
# can race with the URL map patch.
_TESTS_TO_FAIL_ON_RPC_FAILURE = ["ping_pong", "round_robin"]
# Tests that run UnaryCall and EmptyCall.
_TESTS_TO_RUN_MULTIPLE_RPCS = ["path_matching", "header_matching"]
# Tests that make UnaryCall with test metadata.
_TESTS_TO_SEND_METADATA = ["header_matching"]
_TEST_METADATA_KEY = "xds_md"
_TEST_METADATA_VALUE_UNARY = "unary_yranu"
_TEST_METADATA_VALUE_EMPTY = "empty_ytpme"
# Extra RPC metadata whose value is a number, sent with UnaryCall only.
_TEST_METADATA_NUMERIC_KEY = "xds_md_numeric"
_TEST_METADATA_NUMERIC_VALUE = "159"
_PATH_MATCHER_NAME = "path-matcher"
_BASE_TEMPLATE_NAME = "test-template"
_BASE_INSTANCE_GROUP_NAME = "test-ig"
_BASE_HEALTH_CHECK_NAME = "test-hc"
_BASE_FIREWALL_RULE_NAME = "test-fw-rule"
_BASE_BACKEND_SERVICE_NAME = "test-backend-service"
_BASE_URL_MAP_NAME = "test-map"
_BASE_SERVICE_HOST = "grpc-test"
_BASE_TARGET_PROXY_NAME = "test-target-proxy"
_BASE_FORWARDING_RULE_NAME = "test-forwarding-rule"
_TEST_LOG_BASE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "../../reports"
)
_SPONGE_LOG_NAME = "sponge_log.log"
_SPONGE_XML_NAME = "sponge_log.xml"
def get_client_stats(num_rpcs, timeout_sec):
if CLIENT_HOSTS:
hosts = CLIENT_HOSTS
else:
hosts = ["localhost"]
for host in hosts:
with grpc.insecure_channel(
"%s:%d" % (host, args.stats_port)
) as channel:
stub = test_pb2_grpc.LoadBalancerStatsServiceStub(channel)
request = messages_pb2.LoadBalancerStatsRequest()
request.num_rpcs = num_rpcs
request.timeout_sec = timeout_sec
rpc_timeout = timeout_sec + _CONNECTION_TIMEOUT_SEC
logger.debug(
"Invoking GetClientStats RPC to %s:%d:", host, args.stats_port
)
response = stub.GetClientStats(
request, wait_for_ready=True, timeout=rpc_timeout
)
logger.debug(
"Invoked GetClientStats RPC to %s: %s",
host,
json_format.MessageToJson(response),
)
return response
def get_client_accumulated_stats():
if CLIENT_HOSTS:
hosts = CLIENT_HOSTS
else:
hosts = ["localhost"]
for host in hosts:
with grpc.insecure_channel(
"%s:%d" % (host, args.stats_port)
) as channel:
stub = test_pb2_grpc.LoadBalancerStatsServiceStub(channel)
request = messages_pb2.LoadBalancerAccumulatedStatsRequest()
logger.debug(
"Invoking GetClientAccumulatedStats RPC to %s:%d:",
host,
args.stats_port,
)
response = stub.GetClientAccumulatedStats(
request, wait_for_ready=True, timeout=_CONNECTION_TIMEOUT_SEC
)
logger.debug(
"Invoked GetClientAccumulatedStats RPC to %s: %s",
host,
response,
)
return response
def get_client_xds_config_dump():
if CLIENT_HOSTS:
hosts = CLIENT_HOSTS
else:
hosts = ["localhost"]
for host in hosts:
server_address = "%s:%d" % (host, args.stats_port)
with grpc.insecure_channel(server_address) as channel:
stub = csds_pb2_grpc.ClientStatusDiscoveryServiceStub(channel)
logger.debug("Fetching xDS config dump from %s", server_address)
response = stub.FetchClientStatus(
csds_pb2.ClientStatusRequest(),
wait_for_ready=True,
timeout=_CONNECTION_TIMEOUT_SEC,
)
logger.debug("Fetched xDS config dump from %s", server_address)
if len(response.config) != 1:
logger.error(
"Unexpected number of ClientConfigs %d: %s",
len(response.config),
response,
)
return None
else:
# Converting the ClientStatusResponse into JSON, because many
# fields are packed in google.protobuf.Any. It will require many
# duplicated code to unpack proto message and inspect values.
return json_format.MessageToDict(
response.config[0], preserving_proto_field_name=True
)
def configure_client(rpc_types, metadata=[], timeout_sec=None):
if CLIENT_HOSTS:
hosts = CLIENT_HOSTS
else:
hosts = ["localhost"]
for host in hosts:
with grpc.insecure_channel(
"%s:%d" % (host, args.stats_port)
) as channel:
stub = test_pb2_grpc.XdsUpdateClientConfigureServiceStub(channel)
request = messages_pb2.ClientConfigureRequest()
request.types.extend(rpc_types)
for rpc_type, md_key, md_value in metadata:
md = request.metadata.add()
md.type = rpc_type
md.key = md_key
md.value = md_value
if timeout_sec:
request.timeout_sec = timeout_sec
logger.debug(
"Invoking XdsUpdateClientConfigureService RPC to %s:%d: %s",
host,
args.stats_port,
request,
)
stub.Configure(
request, wait_for_ready=True, timeout=_CONNECTION_TIMEOUT_SEC
)
logger.debug(
"Invoked XdsUpdateClientConfigureService RPC to %s", host
)
class RpcDistributionError(Exception):
pass
def _verify_rpcs_to_given_backends(
backends, timeout_sec, num_rpcs, allow_failures
):
start_time = time.time()
error_msg = None
logger.debug(
"Waiting for %d sec until backends %s receive load"
% (timeout_sec, backends)
)
while time.time() - start_time <= timeout_sec:
error_msg = None
stats = get_client_stats(num_rpcs, timeout_sec)
rpcs_by_peer = stats.rpcs_by_peer
for backend in backends:
if backend not in rpcs_by_peer:
error_msg = "Backend %s did not receive load" % backend
break
if not error_msg and len(rpcs_by_peer) > len(backends):
error_msg = "Unexpected backend received load: %s" % rpcs_by_peer
if not allow_failures and stats.num_failures > 0:
error_msg = "%d RPCs failed" % stats.num_failures
if not error_msg:
return
raise RpcDistributionError(error_msg)
def wait_until_all_rpcs_go_to_given_backends_or_fail(
backends, timeout_sec, num_rpcs=_NUM_TEST_RPCS
):
_verify_rpcs_to_given_backends(
backends, timeout_sec, num_rpcs, allow_failures=True
)
def wait_until_all_rpcs_go_to_given_backends(
backends, timeout_sec, num_rpcs=_NUM_TEST_RPCS
):
_verify_rpcs_to_given_backends(
backends, timeout_sec, num_rpcs, allow_failures=False
)
def wait_until_no_rpcs_go_to_given_backends(backends, timeout_sec):
start_time = time.time()
while time.time() - start_time <= timeout_sec:
stats = get_client_stats(_NUM_TEST_RPCS, timeout_sec)
error_msg = None
rpcs_by_peer = stats.rpcs_by_peer
for backend in backends:
if backend in rpcs_by_peer:
error_msg = "Unexpected backend %s receives load" % backend
break
if not error_msg:
return
raise Exception("Unexpected RPCs going to given backends")
def wait_until_rpcs_in_flight(rpc_type, timeout_sec, num_rpcs, threshold):
"""Block until the test client reaches the state with the given number
of RPCs being outstanding stably.
Args:
rpc_type: A string indicating the RPC method to check for. Either
'UnaryCall' or 'EmptyCall'.
timeout_sec: Maximum number of seconds to wait until the desired state
is reached.
num_rpcs: Expected number of RPCs to be in-flight.
threshold: Number within [0,100], the tolerable percentage by which
the actual number of RPCs in-flight can differ from the expected number.
"""
if threshold < 0 or threshold > 100:
raise ValueError("Value error: Threshold should be between 0 to 100")
threshold_fraction = threshold / 100.0
start_time = time.time()
error_msg = None
logger.debug(
"Waiting for %d sec until %d %s RPCs (with %d%% tolerance) in-flight"
% (timeout_sec, num_rpcs, rpc_type, threshold)
)
while time.time() - start_time <= timeout_sec:
error_msg = _check_rpcs_in_flight(
rpc_type, num_rpcs, threshold, threshold_fraction
)
if error_msg:
logger.debug("Progress: %s", error_msg)
time.sleep(2)
else:
break
# Ensure the number of outstanding RPCs is stable.
if not error_msg:
time.sleep(5)
error_msg = _check_rpcs_in_flight(
rpc_type, num_rpcs, threshold, threshold_fraction
)
if error_msg:
raise Exception(
"Wrong number of %s RPCs in-flight: %s" % (rpc_type, error_msg)
)
def _check_rpcs_in_flight(rpc_type, num_rpcs, threshold, threshold_fraction):
error_msg = None
stats = get_client_accumulated_stats()
rpcs_started = stats.num_rpcs_started_by_method[rpc_type]
rpcs_succeeded = stats.num_rpcs_succeeded_by_method[rpc_type]
rpcs_failed = stats.num_rpcs_failed_by_method[rpc_type]
rpcs_in_flight = rpcs_started - rpcs_succeeded - rpcs_failed
if rpcs_in_flight < (num_rpcs * (1 - threshold_fraction)):
error_msg = "actual(%d) < expected(%d - %d%%)" % (
rpcs_in_flight,
num_rpcs,
threshold,
)
elif rpcs_in_flight > (num_rpcs * (1 + threshold_fraction)):
error_msg = "actual(%d) > expected(%d + %d%%)" % (
rpcs_in_flight,
num_rpcs,
threshold,
)
return error_msg
def compare_distributions(
actual_distribution, expected_distribution, threshold
):
"""Compare if two distributions are similar.
Args:
actual_distribution: A list of floats, contains the actual distribution.
expected_distribution: A list of floats, contains the expected distribution.
threshold: Number within [0,100], the threshold percentage by which the
actual distribution can differ from the expected distribution.
Returns:
The similarity between the distributions as a boolean. Returns true if the
actual distribution lies within the threshold of the expected
distribution, false otherwise.
Raises:
ValueError: if threshold is not with in [0,100].
Exception: containing detailed error messages.
"""
if len(expected_distribution) != len(actual_distribution):
raise Exception(
"Error: expected and actual distributions have different size (%d"
" vs %d)" % (len(expected_distribution), len(actual_distribution))
)
if threshold < 0 or threshold > 100:
raise ValueError("Value error: Threshold should be between 0 to 100")
threshold_fraction = threshold / 100.0
for expected, actual in zip(expected_distribution, actual_distribution):
if actual < (expected * (1 - threshold_fraction)):
raise Exception(
"actual(%f) < expected(%f-%d%%)" % (actual, expected, threshold)
)
if actual > (expected * (1 + threshold_fraction)):
raise Exception(
"actual(%f) > expected(%f+%d%%)" % (actual, expected, threshold)
)
return True
def compare_expected_instances(stats, expected_instances):
"""Compare if stats have expected instances for each type of RPC.
Args:
stats: LoadBalancerStatsResponse reported by interop client.
expected_instances: a dict with key as the RPC type (string), value as
the expected backend instances (list of strings).
Returns:
Returns true if the instances are expected. False if not.
"""
for rpc_type, expected_peers in list(expected_instances.items()):
rpcs_by_peer_for_type = stats.rpcs_by_method[rpc_type]
rpcs_by_peer = (
rpcs_by_peer_for_type.rpcs_by_peer
if rpcs_by_peer_for_type
else None
)
logger.debug("rpc: %s, by_peer: %s", rpc_type, rpcs_by_peer)
peers = list(rpcs_by_peer.keys())
if set(peers) != set(expected_peers):
logger.info(
"unexpected peers for %s, got %s, want %s",
rpc_type,
peers,
expected_peers,
)
return False
return True
def test_backends_restart(gcp, backend_service, instance_group):
logger.info("Running test_backends_restart")
instance_names = get_instance_names(gcp, instance_group)
num_instances = len(instance_names)
start_time = time.time()
wait_until_all_rpcs_go_to_given_backends(
instance_names, _WAIT_FOR_STATS_SEC
)
try:
resize_instance_group(gcp, instance_group, 0)
wait_until_all_rpcs_go_to_given_backends_or_fail(
[], _WAIT_FOR_BACKEND_SEC
)
finally:
resize_instance_group(gcp, instance_group, num_instances)
wait_for_healthy_backends(gcp, backend_service, instance_group)
new_instance_names = get_instance_names(gcp, instance_group)
wait_until_all_rpcs_go_to_given_backends(
new_instance_names, _WAIT_FOR_BACKEND_SEC
)
def test_change_backend_service(
gcp,
original_backend_service,
instance_group,
alternate_backend_service,
same_zone_instance_group,
):
logger.info("Running test_change_backend_service")
original_backend_instances = get_instance_names(gcp, instance_group)
alternate_backend_instances = get_instance_names(
gcp, same_zone_instance_group
)
patch_backend_service(
gcp, alternate_backend_service, [same_zone_instance_group]
)
wait_for_healthy_backends(gcp, original_backend_service, instance_group)
wait_for_healthy_backends(
gcp, alternate_backend_service, same_zone_instance_group
)
wait_until_all_rpcs_go_to_given_backends(
original_backend_instances, _WAIT_FOR_STATS_SEC
)
passed = True
try:
patch_url_map_backend_service(gcp, alternate_backend_service)
wait_until_all_rpcs_go_to_given_backends(
alternate_backend_instances, _WAIT_FOR_URL_MAP_PATCH_SEC
)
except Exception:
passed = False
raise
finally:
if passed or not args.halt_after_fail:
patch_url_map_backend_service(gcp, original_backend_service)
patch_backend_service(gcp, alternate_backend_service, [])
def test_gentle_failover(
gcp,
backend_service,
primary_instance_group,
secondary_instance_group,
swapped_primary_and_secondary=False,
):
logger.info("Running test_gentle_failover")
num_primary_instances = len(get_instance_names(gcp, primary_instance_group))
min_instances_for_gentle_failover = 3 # Need >50% failure to start failover
passed = True
try:
if num_primary_instances < min_instances_for_gentle_failover:
resize_instance_group(
gcp, primary_instance_group, min_instances_for_gentle_failover
)
patch_backend_service(
gcp,
backend_service,
[primary_instance_group, secondary_instance_group],
)
primary_instance_names = get_instance_names(gcp, primary_instance_group)
secondary_instance_names = get_instance_names(
gcp, secondary_instance_group
)
wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
wait_for_healthy_backends(
gcp, backend_service, secondary_instance_group
)
wait_until_all_rpcs_go_to_given_backends(
primary_instance_names, _WAIT_FOR_STATS_SEC
)
instances_to_stop = primary_instance_names[:-1]
remaining_instances = primary_instance_names[-1:]
try:
set_serving_status(
instances_to_stop, gcp.service_port, serving=False
)
wait_until_all_rpcs_go_to_given_backends(
remaining_instances + secondary_instance_names,
_WAIT_FOR_BACKEND_SEC,
)
finally:
set_serving_status(
primary_instance_names, gcp.service_port, serving=True
)
except RpcDistributionError as e:
if not swapped_primary_and_secondary and is_primary_instance_group(
gcp, secondary_instance_group
):
# Swap expectation of primary and secondary instance groups.
test_gentle_failover(
gcp,
backend_service,
secondary_instance_group,
primary_instance_group,
swapped_primary_and_secondary=True,
)
else:
passed = False
raise e
except Exception:
passed = False
raise
finally:
if passed or not args.halt_after_fail:
patch_backend_service(
gcp, backend_service, [primary_instance_group]
)
resize_instance_group(
gcp, primary_instance_group, num_primary_instances
)
instance_names = get_instance_names(gcp, primary_instance_group)
wait_until_all_rpcs_go_to_given_backends(
instance_names, _WAIT_FOR_BACKEND_SEC
)
def test_load_report_based_failover(
gcp, backend_service, primary_instance_group, secondary_instance_group
):
logger.info("Running test_load_report_based_failover")
passed = True
try:
patch_backend_service(
gcp,
backend_service,
[primary_instance_group, secondary_instance_group],
)
primary_instance_names = get_instance_names(gcp, primary_instance_group)
secondary_instance_names = get_instance_names(
gcp, secondary_instance_group
)
wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
wait_for_healthy_backends(
gcp, backend_service, secondary_instance_group
)
wait_until_all_rpcs_go_to_given_backends(
primary_instance_names, _WAIT_FOR_STATS_SEC
)
# Set primary locality's balance mode to RATE, and RPS to 20% of the
# client's QPS. The secondary locality will be used.
max_rate = int(args.qps * 1 / 5)
logger.info(
"Patching backend service to RATE with %d max_rate", max_rate
)
patch_backend_service(
gcp,
backend_service,
[primary_instance_group, secondary_instance_group],
balancing_mode="RATE",
max_rate=max_rate,
)
wait_until_all_rpcs_go_to_given_backends(
primary_instance_names + secondary_instance_names,
_WAIT_FOR_BACKEND_SEC,
)
# Set primary locality's balance mode to RATE, and RPS to 120% of the
# client's QPS. Only the primary locality will be used.
max_rate = int(args.qps * 6 / 5)
logger.info(
"Patching backend service to RATE with %d max_rate", max_rate
)
patch_backend_service(
gcp,
backend_service,
[primary_instance_group, secondary_instance_group],
balancing_mode="RATE",
max_rate=max_rate,
)
wait_until_all_rpcs_go_to_given_backends(
primary_instance_names, _WAIT_FOR_BACKEND_SEC
)
logger.info("success")
except Exception:
passed = False
raise
finally:
if passed or not args.halt_after_fail:
patch_backend_service(
gcp, backend_service, [primary_instance_group]
)
instance_names = get_instance_names(gcp, primary_instance_group)
wait_until_all_rpcs_go_to_given_backends(
instance_names, _WAIT_FOR_BACKEND_SEC
)
def test_ping_pong(gcp, backend_service, instance_group):
logger.info("Running test_ping_pong")
wait_for_healthy_backends(gcp, backend_service, instance_group)
instance_names = get_instance_names(gcp, instance_group)
wait_until_all_rpcs_go_to_given_backends(
instance_names, _WAIT_FOR_STATS_SEC
)
def test_remove_instance_group(
gcp, backend_service, instance_group, same_zone_instance_group
):
logger.info("Running test_remove_instance_group")
passed = True
try:
patch_backend_service(
gcp,
backend_service,
[instance_group, same_zone_instance_group],
balancing_mode="RATE",
)
wait_for_healthy_backends(gcp, backend_service, instance_group)
wait_for_healthy_backends(
gcp, backend_service, same_zone_instance_group
)
instance_names = get_instance_names(gcp, instance_group)
same_zone_instance_names = get_instance_names(
gcp, same_zone_instance_group
)
try:
wait_until_all_rpcs_go_to_given_backends(
instance_names + same_zone_instance_names,
_WAIT_FOR_OPERATION_SEC,
)
remaining_instance_group = same_zone_instance_group
remaining_instance_names = same_zone_instance_names
except RpcDistributionError as e:
# If connected to TD in a different zone, we may route traffic to
# only one instance group. Determine which group that is to continue
# with the remainder of the test case.
try:
wait_until_all_rpcs_go_to_given_backends(
instance_names, _WAIT_FOR_STATS_SEC
)
remaining_instance_group = same_zone_instance_group
remaining_instance_names = same_zone_instance_names