run_xds_tests.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. #!/usr/bin/env python
  2. # Copyright 2020 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. """Run xDS integration tests on GCP using Traffic Director."""
  16. import argparse
  17. import googleapiclient.discovery
  18. import grpc
  19. import logging
  20. import os
  21. import random
  22. import shlex
  23. import socket
  24. import subprocess
  25. import sys
  26. import tempfile
  27. import time
  28. from oauth2client.client import GoogleCredentials
  29. import python_utils.jobset as jobset
  30. import python_utils.report_utils as report_utils
  31. from src.proto.grpc.health.v1 import health_pb2
  32. from src.proto.grpc.health.v1 import health_pb2_grpc
  33. from src.proto.grpc.testing import empty_pb2
  34. from src.proto.grpc.testing import messages_pb2
  35. from src.proto.grpc.testing import test_pb2_grpc
  36. logger = logging.getLogger()
  37. console_handler = logging.StreamHandler()
  38. formatter = logging.Formatter(fmt='%(asctime)s: %(levelname)-8s %(message)s')
  39. console_handler.setFormatter(formatter)
  40. logger.handlers = []
  41. logger.addHandler(console_handler)
  42. logger.setLevel(logging.WARNING)
  43. _TEST_CASES = [
  44. 'backends_restart',
  45. 'change_backend_service',
  46. 'gentle_failover',
  47. 'load_report_based_failover',
  48. 'ping_pong',
  49. 'remove_instance_group',
  50. 'round_robin',
  51. 'secondary_locality_gets_no_requests_on_partial_primary_failure',
  52. 'secondary_locality_gets_requests_on_primary_failure',
  53. 'traffic_splitting',
  54. ]
  55. # Valid test cases, but not in all. So the tests can only run manually, and
  56. # aren't enabled automatically for all languages.
  57. #
  58. # TODO: Move them into _TEST_CASES when support is ready in all languages.
  59. _ADDITIONAL_TEST_CASES = ['path_matching', 'header_matching']
  60. def parse_test_cases(arg):
  61. if arg == '':
  62. return []
  63. arg_split = arg.split(',')
  64. test_cases = set()
  65. all_test_cases = _TEST_CASES + _ADDITIONAL_TEST_CASES
  66. for arg in arg_split:
  67. if arg == "all":
  68. test_cases = test_cases.union(_TEST_CASES)
  69. else:
  70. test_cases = test_cases.union([arg])
  71. if not all([test_case in all_test_cases for test_case in test_cases]):
  72. raise Exception('Failed to parse test cases %s' % arg)
  73. # Perserve order.
  74. return [x for x in all_test_cases if x in test_cases]
  75. def parse_port_range(port_arg):
  76. try:
  77. port = int(port_arg)
  78. return range(port, port + 1)
  79. except:
  80. port_min, port_max = port_arg.split(':')
  81. return range(int(port_min), int(port_max) + 1)
  82. argp = argparse.ArgumentParser(description='Run xDS interop tests on GCP')
  83. argp.add_argument('--project_id', help='GCP project id')
  84. argp.add_argument(
  85. '--gcp_suffix',
  86. default='',
  87. help='Optional suffix for all generated GCP resource names. Useful to '
  88. 'ensure distinct names across test runs.')
  89. argp.add_argument(
  90. '--test_case',
  91. default='ping_pong',
  92. type=parse_test_cases,
  93. help='Comma-separated list of test cases to run. Available tests: %s, '
  94. '(or \'all\' to run every test). '
  95. 'Alternative tests not included in \'all\': %s' %
  96. (','.join(_TEST_CASES), ','.join(_ADDITIONAL_TEST_CASES)))
  97. argp.add_argument(
  98. '--bootstrap_file',
  99. default='',
  100. help='File to reference via GRPC_XDS_BOOTSTRAP. Disables built-in '
  101. 'bootstrap generation')
  102. argp.add_argument(
  103. '--client_cmd',
  104. default=None,
  105. help='Command to launch xDS test client. {server_uri}, {stats_port} and '
  106. '{qps} references will be replaced using str.format(). GRPC_XDS_BOOTSTRAP '
  107. 'will be set for the command')
  108. argp.add_argument('--zone', default='us-central1-a')
  109. argp.add_argument('--secondary_zone',
  110. default='us-west1-b',
  111. help='Zone to use for secondary TD locality tests')
  112. argp.add_argument('--qps', default=100, type=int, help='Client QPS')
  113. argp.add_argument(
  114. '--wait_for_backend_sec',
  115. default=1200,
  116. type=int,
  117. help='Time limit for waiting for created backend services to report '
  118. 'healthy when launching or updated GCP resources')
  119. argp.add_argument(
  120. '--use_existing_gcp_resources',
  121. default=False,
  122. action='store_true',
  123. help=
  124. 'If set, find and use already created GCP resources instead of creating new'
  125. ' ones.')
  126. argp.add_argument(
  127. '--keep_gcp_resources',
  128. default=False,
  129. action='store_true',
  130. help=
  131. 'Leave GCP VMs and configuration running after test. Default behavior is '
  132. 'to delete when tests complete.')
  133. argp.add_argument(
  134. '--compute_discovery_document',
  135. default=None,
  136. type=str,
  137. help=
  138. 'If provided, uses this file instead of retrieving via the GCP discovery '
  139. 'API')
  140. argp.add_argument(
  141. '--alpha_compute_discovery_document',
  142. default=None,
  143. type=str,
  144. help='If provided, uses this file instead of retrieving via the alpha GCP '
  145. 'discovery API')
  146. argp.add_argument('--network',
  147. default='global/networks/default',
  148. help='GCP network to use')
  149. argp.add_argument('--service_port_range',
  150. default='8080:8110',
  151. type=parse_port_range,
  152. help='Listening port for created gRPC backends. Specified as '
  153. 'either a single int or as a range in the format min:max, in '
  154. 'which case an available port p will be chosen s.t. min <= p '
  155. '<= max')
  156. argp.add_argument(
  157. '--stats_port',
  158. default=8079,
  159. type=int,
  160. help='Local port for the client process to expose the LB stats service')
  161. argp.add_argument('--xds_server',
  162. default='trafficdirector.googleapis.com:443',
  163. help='xDS server')
  164. argp.add_argument('--source_image',
  165. default='projects/debian-cloud/global/images/family/debian-9',
  166. help='Source image for VMs created during the test')
  167. argp.add_argument('--path_to_server_binary',
  168. default=None,
  169. type=str,
  170. help='If set, the server binary must already be pre-built on '
  171. 'the specified source image')
  172. argp.add_argument('--machine_type',
  173. default='e2-standard-2',
  174. help='Machine type for VMs created during the test')
  175. argp.add_argument(
  176. '--instance_group_size',
  177. default=2,
  178. type=int,
  179. help='Number of VMs to create per instance group. Certain test cases (e.g., '
  180. 'round_robin) may not give meaningful results if this is set to a value '
  181. 'less than 2.')
  182. argp.add_argument('--verbose',
  183. help='verbose log output',
  184. default=False,
  185. action='store_true')
  186. # TODO(ericgribkoff) Remove this param once the sponge-formatted log files are
  187. # visible in all test environments.
  188. argp.add_argument('--log_client_output',
  189. help='Log captured client output',
  190. default=False,
  191. action='store_true')
  192. # TODO(ericgribkoff) Remove this flag once all test environments are verified to
  193. # have access to the alpha compute APIs.
  194. argp.add_argument('--only_stable_gcp_apis',
  195. help='Do not use alpha compute APIs. Some tests may be '
  196. 'incompatible with this option (gRPC health checks are '
  197. 'currently alpha and required for simulating server failure',
  198. default=False,
  199. action='store_true')
  200. args = argp.parse_args()
  201. if args.verbose:
  202. logger.setLevel(logging.DEBUG)
  203. _DEFAULT_SERVICE_PORT = 80
  204. _WAIT_FOR_BACKEND_SEC = args.wait_for_backend_sec
  205. _WAIT_FOR_OPERATION_SEC = 1200
  206. _INSTANCE_GROUP_SIZE = args.instance_group_size
  207. _NUM_TEST_RPCS = 10 * args.qps
  208. _WAIT_FOR_STATS_SEC = 360
  209. _WAIT_FOR_VALID_CONFIG_SEC = 60
  210. _WAIT_FOR_URL_MAP_PATCH_SEC = 300
  211. _CONNECTION_TIMEOUT_SEC = 60
  212. _GCP_API_RETRIES = 5
  213. _BOOTSTRAP_TEMPLATE = """
  214. {{
  215. "node": {{
  216. "id": "{node_id}",
  217. "metadata": {{
  218. "TRAFFICDIRECTOR_NETWORK_NAME": "%s"
  219. }},
  220. "locality": {{
  221. "zone": "%s"
  222. }}
  223. }},
  224. "xds_servers": [{{
  225. "server_uri": "%s",
  226. "channel_creds": [
  227. {{
  228. "type": "google_default",
  229. "config": {{}}
  230. }}
  231. ]
  232. }}]
  233. }}""" % (args.network.split('/')[-1], args.zone, args.xds_server)
  234. # TODO(ericgribkoff) Add change_backend_service to this list once TD no longer
  235. # sends an update with no localities when adding the MIG to the backend service
  236. # can race with the URL map patch.
  237. _TESTS_TO_FAIL_ON_RPC_FAILURE = ['ping_pong', 'round_robin']
  238. # Tests that run UnaryCall and EmptyCall.
  239. _TESTS_TO_RUN_MULTIPLE_RPCS = ['path_matching', 'header_matching']
  240. # Tests that make UnaryCall with test metadata.
  241. _TESTS_TO_SEND_METADATA = ['header_matching']
  242. _TEST_METADATA_KEY = 'xds_md'
  243. _TEST_METADATA_VALUE_UNARY = 'unary_yranu'
  244. _TEST_METADATA_VALUE_EMPTY = 'empty_ytpme'
  245. # Extra RPC metadata whose value is a number, sent with UnaryCall only.
  246. _TEST_METADATA_NUMERIC_KEY = 'xds_md_numeric'
  247. _TEST_METADATA_NUMERIC_VALUE = '159'
  248. _PATH_MATCHER_NAME = 'path-matcher'
  249. _BASE_TEMPLATE_NAME = 'test-template'
  250. _BASE_INSTANCE_GROUP_NAME = 'test-ig'
  251. _BASE_HEALTH_CHECK_NAME = 'test-hc'
  252. _BASE_FIREWALL_RULE_NAME = 'test-fw-rule'
  253. _BASE_BACKEND_SERVICE_NAME = 'test-backend-service'
  254. _BASE_URL_MAP_NAME = 'test-map'
  255. _BASE_SERVICE_HOST = 'grpc-test'
  256. _BASE_TARGET_PROXY_NAME = 'test-target-proxy'
  257. _BASE_FORWARDING_RULE_NAME = 'test-forwarding-rule'
  258. _TEST_LOG_BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  259. '../../reports')
  260. _SPONGE_LOG_NAME = 'sponge_log.log'
  261. _SPONGE_XML_NAME = 'sponge_log.xml'
  262. def get_client_stats(num_rpcs, timeout_sec):
  263. with grpc.insecure_channel('localhost:%d' % args.stats_port) as channel:
  264. stub = test_pb2_grpc.LoadBalancerStatsServiceStub(channel)
  265. request = messages_pb2.LoadBalancerStatsRequest()
  266. request.num_rpcs = num_rpcs
  267. request.timeout_sec = timeout_sec
  268. rpc_timeout = timeout_sec + _CONNECTION_TIMEOUT_SEC
  269. response = stub.GetClientStats(request,
  270. wait_for_ready=True,
  271. timeout=rpc_timeout)
  272. logger.debug('Invoked GetClientStats RPC: %s', response)
  273. return response
  274. class RpcDistributionError(Exception):
  275. pass
  276. def _verify_rpcs_to_given_backends(backends, timeout_sec, num_rpcs,
  277. allow_failures):
  278. start_time = time.time()
  279. error_msg = None
  280. logger.debug('Waiting for %d sec until backends %s receive load' %
  281. (timeout_sec, backends))
  282. while time.time() - start_time <= timeout_sec:
  283. error_msg = None
  284. stats = get_client_stats(num_rpcs, timeout_sec)
  285. rpcs_by_peer = stats.rpcs_by_peer
  286. for backend in backends:
  287. if backend not in rpcs_by_peer:
  288. error_msg = 'Backend %s did not receive load' % backend
  289. break
  290. if not error_msg and len(rpcs_by_peer) > len(backends):
  291. error_msg = 'Unexpected backend received load: %s' % rpcs_by_peer
  292. if not allow_failures and stats.num_failures > 0:
  293. error_msg = '%d RPCs failed' % stats.num_failures
  294. if not error_msg:
  295. return
  296. raise RpcDistributionError(error_msg)
  297. def wait_until_all_rpcs_go_to_given_backends_or_fail(backends,
  298. timeout_sec,
  299. num_rpcs=_NUM_TEST_RPCS):
  300. _verify_rpcs_to_given_backends(backends,
  301. timeout_sec,
  302. num_rpcs,
  303. allow_failures=True)
  304. def wait_until_all_rpcs_go_to_given_backends(backends,
  305. timeout_sec,
  306. num_rpcs=_NUM_TEST_RPCS):
  307. _verify_rpcs_to_given_backends(backends,
  308. timeout_sec,
  309. num_rpcs,
  310. allow_failures=False)
  311. def compare_distributions(actual_distribution, expected_distribution,
  312. threshold):
  313. """Compare if two distributions are similar.
  314. Args:
  315. actual_distribution: A list of floats, contains the actual distribution.
  316. expected_distribution: A list of floats, contains the expected distribution.
  317. threshold: Number within [0,100], the threshold percentage by which the
  318. actual distribution can differ from the expected distribution.
  319. Returns:
  320. The similarity between the distributions as a boolean. Returns true if the
  321. actual distribution lies within the threshold of the expected
  322. distribution, false otherwise.
  323. Raises:
  324. ValueError: if threshold is not with in [0,100].
  325. Exception: containing detailed error messages.
  326. """
  327. if len(expected_distribution) != len(actual_distribution):
  328. raise Exception(
  329. 'Error: expected and actual distributions have different size (%d vs %d)'
  330. % (len(expected_distribution), len(actual_distribution)))
  331. if threshold < 0 or threshold > 100:
  332. raise ValueError('Value error: Threshold should be between 0 to 100')
  333. threshold_fraction = threshold / 100.0
  334. for expected, actual in zip(expected_distribution, actual_distribution):
  335. if actual < (expected * (1 - threshold_fraction)):
  336. raise Exception("actual(%f) < expected(%f-%d%%)" %
  337. (actual, expected, threshold))
  338. if actual > (expected * (1 + threshold_fraction)):
  339. raise Exception("actual(%f) > expected(%f+%d%%)" %
  340. (actual, expected, threshold))
  341. return True
  342. def compare_expected_instances(stats, expected_instances):
  343. """Compare if stats have expected instances for each type of RPC.
  344. Args:
  345. stats: LoadBalancerStatsResponse reported by interop client.
  346. expected_instances: a dict with key as the RPC type (string), value as
  347. the expected backend instances (list of strings).
  348. Returns:
  349. Returns true if the instances are expected. False if not.
  350. """
  351. for rpc_type, expected_peers in expected_instances.items():
  352. rpcs_by_peer_for_type = stats.rpcs_by_method[rpc_type]
  353. rpcs_by_peer = rpcs_by_peer_for_type.rpcs_by_peer if rpcs_by_peer_for_type else None
  354. logger.debug('rpc: %s, by_peer: %s', rpc_type, rpcs_by_peer)
  355. peers = list(rpcs_by_peer.keys())
  356. if set(peers) != set(expected_peers):
  357. logger.info('unexpected peers for %s, got %s, want %s', rpc_type,
  358. peers, expected_peers)
  359. return False
  360. return True
  361. def test_backends_restart(gcp, backend_service, instance_group):
  362. logger.info('Running test_backends_restart')
  363. instance_names = get_instance_names(gcp, instance_group)
  364. num_instances = len(instance_names)
  365. start_time = time.time()
  366. wait_until_all_rpcs_go_to_given_backends(instance_names,
  367. _WAIT_FOR_STATS_SEC)
  368. try:
  369. resize_instance_group(gcp, instance_group, 0)
  370. wait_until_all_rpcs_go_to_given_backends_or_fail([],
  371. _WAIT_FOR_BACKEND_SEC)
  372. finally:
  373. resize_instance_group(gcp, instance_group, num_instances)
  374. wait_for_healthy_backends(gcp, backend_service, instance_group)
  375. new_instance_names = get_instance_names(gcp, instance_group)
  376. wait_until_all_rpcs_go_to_given_backends(new_instance_names,
  377. _WAIT_FOR_BACKEND_SEC)
  378. def test_change_backend_service(gcp, original_backend_service, instance_group,
  379. alternate_backend_service,
  380. same_zone_instance_group):
  381. logger.info('Running test_change_backend_service')
  382. original_backend_instances = get_instance_names(gcp, instance_group)
  383. alternate_backend_instances = get_instance_names(gcp,
  384. same_zone_instance_group)
  385. patch_backend_instances(gcp, alternate_backend_service,
  386. [same_zone_instance_group])
  387. wait_for_healthy_backends(gcp, original_backend_service, instance_group)
  388. wait_for_healthy_backends(gcp, alternate_backend_service,
  389. same_zone_instance_group)
  390. wait_until_all_rpcs_go_to_given_backends(original_backend_instances,
  391. _WAIT_FOR_STATS_SEC)
  392. try:
  393. patch_url_map_backend_service(gcp, alternate_backend_service)
  394. wait_until_all_rpcs_go_to_given_backends(alternate_backend_instances,
  395. _WAIT_FOR_URL_MAP_PATCH_SEC)
  396. finally:
  397. patch_url_map_backend_service(gcp, original_backend_service)
  398. patch_backend_instances(gcp, alternate_backend_service, [])
  399. def test_gentle_failover(gcp,
  400. backend_service,
  401. primary_instance_group,
  402. secondary_instance_group,
  403. swapped_primary_and_secondary=False):
  404. logger.info('Running test_gentle_failover')
  405. num_primary_instances = len(get_instance_names(gcp, primary_instance_group))
  406. min_instances_for_gentle_failover = 3 # Need >50% failure to start failover
  407. try:
  408. if num_primary_instances < min_instances_for_gentle_failover:
  409. resize_instance_group(gcp, primary_instance_group,
  410. min_instances_for_gentle_failover)
  411. patch_backend_instances(
  412. gcp, backend_service,
  413. [primary_instance_group, secondary_instance_group])
  414. primary_instance_names = get_instance_names(gcp, primary_instance_group)
  415. secondary_instance_names = get_instance_names(gcp,
  416. secondary_instance_group)
  417. wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
  418. wait_for_healthy_backends(gcp, backend_service,
  419. secondary_instance_group)
  420. wait_until_all_rpcs_go_to_given_backends(primary_instance_names,
  421. _WAIT_FOR_STATS_SEC)
  422. instances_to_stop = primary_instance_names[:-1]
  423. remaining_instances = primary_instance_names[-1:]
  424. try:
  425. set_serving_status(instances_to_stop,
  426. gcp.service_port,
  427. serving=False)
  428. wait_until_all_rpcs_go_to_given_backends(
  429. remaining_instances + secondary_instance_names,
  430. _WAIT_FOR_BACKEND_SEC)
  431. finally:
  432. set_serving_status(primary_instance_names,
  433. gcp.service_port,
  434. serving=True)
  435. except RpcDistributionError as e:
  436. if not swapped_primary_and_secondary and is_primary_instance_group(
  437. gcp, secondary_instance_group):
  438. # Swap expectation of primary and secondary instance groups.
  439. test_gentle_failover(gcp,
  440. backend_service,
  441. secondary_instance_group,
  442. primary_instance_group,
  443. swapped_primary_and_secondary=True)
  444. else:
  445. raise e
  446. finally:
  447. patch_backend_instances(gcp, backend_service, [primary_instance_group])
  448. resize_instance_group(gcp, primary_instance_group,
  449. num_primary_instances)
  450. instance_names = get_instance_names(gcp, primary_instance_group)
  451. wait_until_all_rpcs_go_to_given_backends(instance_names,
  452. _WAIT_FOR_BACKEND_SEC)
  453. def test_load_report_based_failover(gcp, backend_service,
  454. primary_instance_group,
  455. secondary_instance_group):
  456. logger.info('Running test_load_report_based_failover')
  457. try:
  458. patch_backend_instances(
  459. gcp, backend_service,
  460. [primary_instance_group, secondary_instance_group])
  461. primary_instance_names = get_instance_names(gcp, primary_instance_group)
  462. secondary_instance_names = get_instance_names(gcp,
  463. secondary_instance_group)
  464. wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
  465. wait_for_healthy_backends(gcp, backend_service,
  466. secondary_instance_group)
  467. wait_until_all_rpcs_go_to_given_backends(primary_instance_names,
  468. _WAIT_FOR_STATS_SEC)
  469. # Set primary locality's balance mode to RATE, and RPS to 20% of the
  470. # client's QPS. The secondary locality will be used.
  471. max_rate = int(args.qps * 1 / 5)
  472. logger.info('Patching backend service to RATE with %d max_rate',
  473. max_rate)
  474. patch_backend_instances(
  475. gcp,
  476. backend_service, [primary_instance_group, secondary_instance_group],
  477. balancing_mode='RATE',
  478. max_rate=max_rate)
  479. wait_until_all_rpcs_go_to_given_backends(
  480. primary_instance_names + secondary_instance_names,
  481. _WAIT_FOR_BACKEND_SEC)
  482. # Set primary locality's balance mode to RATE, and RPS to 120% of the
  483. # client's QPS. Only the primary locality will be used.
  484. max_rate = int(args.qps * 6 / 5)
  485. logger.info('Patching backend service to RATE with %d max_rate',
  486. max_rate)
  487. patch_backend_instances(
  488. gcp,
  489. backend_service, [primary_instance_group, secondary_instance_group],
  490. balancing_mode='RATE',
  491. max_rate=max_rate)
  492. wait_until_all_rpcs_go_to_given_backends(primary_instance_names,
  493. _WAIT_FOR_BACKEND_SEC)
  494. logger.info("success")
  495. finally:
  496. patch_backend_instances(gcp, backend_service, [primary_instance_group])
  497. instance_names = get_instance_names(gcp, primary_instance_group)
  498. wait_until_all_rpcs_go_to_given_backends(instance_names,
  499. _WAIT_FOR_BACKEND_SEC)
  500. def test_ping_pong(gcp, backend_service, instance_group):
  501. logger.info('Running test_ping_pong')
  502. wait_for_healthy_backends(gcp, backend_service, instance_group)
  503. instance_names = get_instance_names(gcp, instance_group)
  504. wait_until_all_rpcs_go_to_given_backends(instance_names,
  505. _WAIT_FOR_STATS_SEC)
  506. def test_remove_instance_group(gcp, backend_service, instance_group,
  507. same_zone_instance_group):
  508. logger.info('Running test_remove_instance_group')
  509. try:
  510. patch_backend_instances(gcp,
  511. backend_service,
  512. [instance_group, same_zone_instance_group],
  513. balancing_mode='RATE')
  514. wait_for_healthy_backends(gcp, backend_service, instance_group)
  515. wait_for_healthy_backends(gcp, backend_service,
  516. same_zone_instance_group)
  517. instance_names = get_instance_names(gcp, instance_group)
  518. same_zone_instance_names = get_instance_names(gcp,
  519. same_zone_instance_group)
  520. try:
  521. wait_until_all_rpcs_go_to_given_backends(
  522. instance_names + same_zone_instance_names,
  523. _WAIT_FOR_OPERATION_SEC)
  524. remaining_instance_group = same_zone_instance_group
  525. remaining_instance_names = same_zone_instance_names
  526. except RpcDistributionError as e:
  527. # If connected to TD in a different zone, we may route traffic to
  528. # only one instance group. Determine which group that is to continue
  529. # with the remainder of the test case.
  530. try:
  531. wait_until_all_rpcs_go_to_given_backends(
  532. instance_names, _WAIT_FOR_STATS_SEC)
  533. remaining_instance_group = same_zone_instance_group
  534. remaining_instance_names = same_zone_instance_names
  535. except RpcDistributionError as e:
  536. wait_until_all_rpcs_go_to_given_backends(
  537. same_zone_instance_names, _WAIT_FOR_STATS_SEC)
  538. remaining_instance_group = instance_group
  539. remaining_instance_names = instance_names
  540. patch_backend_instances(gcp,
  541. backend_service, [remaining_instance_group],
  542. balancing_mode='RATE')
  543. wait_until_all_rpcs_go_to_given_backends(remaining_instance_names,
  544. _WAIT_FOR_BACKEND_SEC)
  545. finally:
  546. patch_backend_instances(gcp, backend_service, [instance_group])
  547. wait_until_all_rpcs_go_to_given_backends(instance_names,
  548. _WAIT_FOR_BACKEND_SEC)
  549. def test_round_robin(gcp, backend_service, instance_group):
  550. logger.info('Running test_round_robin')
  551. wait_for_healthy_backends(gcp, backend_service, instance_group)
  552. instance_names = get_instance_names(gcp, instance_group)
  553. threshold = 1
  554. wait_until_all_rpcs_go_to_given_backends(instance_names,
  555. _WAIT_FOR_STATS_SEC)
  556. # TODO(ericgribkoff) Delayed config propagation from earlier tests
  557. # may result in briefly receiving an empty EDS update, resulting in failed
  558. # RPCs. Retry distribution validation if this occurs; long-term fix is
  559. # creating new backend resources for each individual test case.
  560. # Each attempt takes 10 seconds. Config propagation can take several
  561. # minutes.
  562. max_attempts = 40
  563. for i in range(max_attempts):
  564. stats = get_client_stats(_NUM_TEST_RPCS, _WAIT_FOR_STATS_SEC)
  565. requests_received = [stats.rpcs_by_peer[x] for x in stats.rpcs_by_peer]
  566. total_requests_received = sum(requests_received)
  567. if total_requests_received != _NUM_TEST_RPCS:
  568. logger.info('Unexpected RPC failures, retrying: %s', stats)
  569. continue
  570. expected_requests = total_requests_received / len(instance_names)
  571. for instance in instance_names:
  572. if abs(stats.rpcs_by_peer[instance] -
  573. expected_requests) > threshold:
  574. raise Exception(
  575. 'RPC peer distribution differs from expected by more than %d '
  576. 'for instance %s (%s)' % (threshold, instance, stats))
  577. return
  578. raise Exception('RPC failures persisted through %d retries' % max_attempts)
  579. def test_secondary_locality_gets_no_requests_on_partial_primary_failure(
  580. gcp,
  581. backend_service,
  582. primary_instance_group,
  583. secondary_instance_group,
  584. swapped_primary_and_secondary=False):
  585. logger.info(
  586. 'Running secondary_locality_gets_no_requests_on_partial_primary_failure'
  587. )
  588. try:
  589. patch_backend_instances(
  590. gcp, backend_service,
  591. [primary_instance_group, secondary_instance_group])
  592. wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
  593. wait_for_healthy_backends(gcp, backend_service,
  594. secondary_instance_group)
  595. primary_instance_names = get_instance_names(gcp, primary_instance_group)
  596. wait_until_all_rpcs_go_to_given_backends(primary_instance_names,
  597. _WAIT_FOR_STATS_SEC)
  598. instances_to_stop = primary_instance_names[:1]
  599. remaining_instances = primary_instance_names[1:]
  600. try:
  601. set_serving_status(instances_to_stop,
  602. gcp.service_port,
  603. serving=False)
  604. wait_until_all_rpcs_go_to_given_backends(remaining_instances,
  605. _WAIT_FOR_BACKEND_SEC)
  606. finally:
  607. set_serving_status(primary_instance_names,
  608. gcp.service_port,
  609. serving=True)
  610. except RpcDistributionError as e:
  611. if not swapped_primary_and_secondary and is_primary_instance_group(
  612. gcp, secondary_instance_group):
  613. # Swap expectation of primary and secondary instance groups.
  614. test_secondary_locality_gets_no_requests_on_partial_primary_failure(
  615. gcp,
  616. backend_service,
  617. secondary_instance_group,
  618. primary_instance_group,
  619. swapped_primary_and_secondary=True)
  620. else:
  621. raise e
  622. finally:
  623. patch_backend_instances(gcp, backend_service, [primary_instance_group])
  624. def test_secondary_locality_gets_requests_on_primary_failure(
  625. gcp,
  626. backend_service,
  627. primary_instance_group,
  628. secondary_instance_group,
  629. swapped_primary_and_secondary=False):
  630. logger.info('Running secondary_locality_gets_requests_on_primary_failure')
  631. try:
  632. patch_backend_instances(
  633. gcp, backend_service,
  634. [primary_instance_group, secondary_instance_group])
  635. wait_for_healthy_backends(gcp, backend_service, primary_instance_group)
  636. wait_for_healthy_backends(gcp, backend_service,
  637. secondary_instance_group)
  638. primary_instance_names = get_instance_names(gcp, primary_instance_group)
  639. secondary_instance_names = get_instance_names(gcp,
  640. secondary_instance_group)
  641. wait_until_all_rpcs_go_to_given_backends(primary_instance_names,
  642. _WAIT_FOR_STATS_SEC)
  643. try:
  644. set_serving_status(primary_instance_names,
  645. gcp.service_port,
  646. serving=False)
  647. wait_until_all_rpcs_go_to_given_backends(secondary_instance_names,
  648. _WAIT_FOR_BACKEND_SEC)
  649. finally:
  650. set_serving_status(primary_instance_names,
  651. gcp.service_port,
  652. serving=True)
  653. except RpcDistributionError as e:
  654. if not swapped_primary_and_secondary and is_primary_instance_group(
  655. gcp, secondary_instance_group):
  656. # Swap expectation of primary and secondary instance groups.
  657. test_secondary_locality_gets_requests_on_primary_failure(
  658. gcp,
  659. backend_service,
  660. secondary_instance_group,
  661. primary_instance_group,
  662. swapped_primary_and_secondary=True)
  663. else:
  664. raise e
  665. finally:
  666. patch_backend_instances(gcp, backend_service, [primary_instance_group])
  667. def prepare_services_for_urlmap_tests(gcp, original_backend_service,
  668. instance_group, alternate_backend_service,
  669. same_zone_instance_group):
  670. '''
  671. This function prepares the services to be ready for tests that modifies
  672. urlmaps.
  673. Returns:
  674. Returns original and alternate backend names as lists of strings.
  675. '''
  676. logger.info('waiting for original backends to become healthy')
  677. wait_for_healthy_backends(gcp, original_backend_service, instance_group)
  678. patch_backend_instances(gcp, alternate_backend_service,
  679. [same_zone_instance_group])
  680. logger.info('waiting for alternate to become healthy')
  681. wait_for_healthy_backends(gcp, alternate_backend_service,
  682. same_zone_instance_group)
  683. original_backend_instances = get_instance_names(gcp, instance_group)
  684. logger.info('original backends instances: %s', original_backend_instances)
  685. alternate_backend_instances = get_instance_names(gcp,
  686. same_zone_instance_group)
  687. logger.info('alternate backends instances: %s', alternate_backend_instances)
  688. # Start with all traffic going to original_backend_service.
  689. logger.info('waiting for traffic to all go to original backends')
  690. wait_until_all_rpcs_go_to_given_backends(original_backend_instances,
  691. _WAIT_FOR_STATS_SEC)
  692. return original_backend_instances, alternate_backend_instances
  693. def test_traffic_splitting(gcp, original_backend_service, instance_group,
  694. alternate_backend_service, same_zone_instance_group):
  695. # This test start with all traffic going to original_backend_service. Then
  696. # it updates URL-map to set default action to traffic splitting between
  697. # original and alternate. It waits for all backends in both services to
  698. # receive traffic, then verifies that weights are expected.
  699. logger.info('Running test_traffic_splitting')
  700. original_backend_instances, alternate_backend_instances = prepare_services_for_urlmap_tests(
  701. gcp, original_backend_service, instance_group,
  702. alternate_backend_service, same_zone_instance_group)
  703. try:
  704. # Patch urlmap, change route action to traffic splitting between
  705. # original and alternate.
  706. logger.info('patching url map with traffic splitting')
  707. original_service_percentage, alternate_service_percentage = 20, 80
  708. patch_url_map_backend_service(
  709. gcp,
  710. services_with_weights={
  711. original_backend_service: original_service_percentage,
  712. alternate_backend_service: alternate_service_percentage,
  713. })
  714. # Split percentage between instances: [20,80] -> [10,10,40,40].
  715. expected_instance_percentage = [
  716. original_service_percentage * 1.0 / len(original_backend_instances)
  717. ] * len(original_backend_instances) + [
  718. alternate_service_percentage * 1.0 /
  719. len(alternate_backend_instances)
  720. ] * len(alternate_backend_instances)
  721. # Wait for traffic to go to both services.
  722. logger.info(
  723. 'waiting for traffic to go to all backends (including alternate)')
  724. wait_until_all_rpcs_go_to_given_backends(
  725. original_backend_instances + alternate_backend_instances,
  726. _WAIT_FOR_STATS_SEC)
  727. # Verify that weights between two services are expected.
  728. retry_count = 10
  729. # Each attempt takes about 10 seconds, 10 retries is equivalent to 100
  730. # seconds timeout.
  731. for i in range(retry_count):
  732. stats = get_client_stats(_NUM_TEST_RPCS, _WAIT_FOR_STATS_SEC)
  733. got_instance_count = [
  734. stats.rpcs_by_peer[i] for i in original_backend_instances
  735. ] + [stats.rpcs_by_peer[i] for i in alternate_backend_instances]
  736. total_count = sum(got_instance_count)
  737. got_instance_percentage = [
  738. x * 100.0 / total_count for x in got_instance_count
  739. ]
  740. try:
  741. compare_distributions(got_instance_percentage,
  742. expected_instance_percentage, 5)
  743. except Exception as e:
  744. logger.info('attempt %d', i)
  745. logger.info('got percentage: %s', got_instance_percentage)
  746. logger.info('expected percentage: %s',
  747. expected_instance_percentage)
  748. logger.info(e)
  749. if i == retry_count - 1:
  750. raise Exception(
  751. 'RPC distribution (%s) differs from expected (%s)',
  752. got_instance_percentage, expected_instance_percentage)
  753. else:
  754. logger.info("success")
  755. break
  756. finally:
  757. patch_url_map_backend_service(gcp, original_backend_service)
  758. patch_backend_instances(gcp, alternate_backend_service, [])
  759. def test_path_matching(gcp, original_backend_service, instance_group,
  760. alternate_backend_service, same_zone_instance_group):
  761. # This test start with all traffic (UnaryCall and EmptyCall) going to
  762. # original_backend_service.
  763. #
  764. # Then it updates URL-map to add routes, to make UnaryCall and EmptyCall to
  765. # go different backends. It waits for all backends in both services to
  766. # receive traffic, then verifies that traffic goes to the expected
  767. # backends.
  768. logger.info('Running test_path_matching')
  769. original_backend_instances, alternate_backend_instances = prepare_services_for_urlmap_tests(
  770. gcp, original_backend_service, instance_group,
  771. alternate_backend_service, same_zone_instance_group)
  772. try:
  773. # A list of tuples (route_rules, expected_instances).
  774. test_cases = [
  775. (
  776. [{
  777. 'priority': 0,
  778. # FullPath EmptyCall -> alternate_backend_service.
  779. 'matchRules': [{
  780. 'fullPathMatch': '/grpc.testing.TestService/EmptyCall'
  781. }],
  782. 'service': alternate_backend_service.url
  783. }],
  784. {
  785. "EmptyCall": alternate_backend_instances,
  786. "UnaryCall": original_backend_instances
  787. }),
  788. (
  789. [{
  790. 'priority': 0,
  791. # Prefix UnaryCall -> alternate_backend_service.
  792. 'matchRules': [{
  793. 'prefixMatch': '/grpc.testing.TestService/Unary'
  794. }],
  795. 'service': alternate_backend_service.url
  796. }],
  797. {
  798. "UnaryCall": alternate_backend_instances,
  799. "EmptyCall": original_backend_instances
  800. }),
  801. (
  802. # This test case is similar to the one above (but with route
  803. # services swapped). This test has two routes (full_path and
  804. # the default) to match EmptyCall, and both routes set
  805. # alternative_backend_service as the action. This forces the
  806. # client to handle duplicate Clusters in the RDS response.
  807. [
  808. {
  809. 'priority': 0,
  810. # Prefix UnaryCall -> original_backend_service.
  811. 'matchRules': [{
  812. 'prefixMatch': '/grpc.testing.TestService/Unary'
  813. }],
  814. 'service': original_backend_service.url
  815. },
  816. {
  817. 'priority': 1,
  818. # FullPath EmptyCall -> alternate_backend_service.
  819. 'matchRules': [{
  820. 'fullPathMatch':
  821. '/grpc.testing.TestService/EmptyCall'
  822. }],
  823. 'service': alternate_backend_service.url
  824. }
  825. ],
  826. {
  827. "UnaryCall": original_backend_instances,
  828. "EmptyCall": alternate_backend_instances
  829. }),
  830. (
  831. [{
  832. 'priority': 0,
  833. # Regex UnaryCall -> alternate_backend_service.
  834. 'matchRules': [{
  835. 'regexMatch':
  836. '^\/.*\/UnaryCall$' # Unary methods with any services.
  837. }],
  838. 'service': alternate_backend_service.url
  839. }],
  840. {
  841. "UnaryCall": alternate_backend_instances,
  842. "EmptyCall": original_backend_instances
  843. }),
  844. ]
  845. for (route_rules, expected_instances) in test_cases:
  846. logger.info('patching url map with %s', route_rules)
  847. patch_url_map_backend_service(gcp,
  848. original_backend_service,
  849. route_rules=route_rules)
  850. # Wait for traffic to go to both services.
  851. logger.info(
  852. 'waiting for traffic to go to all backends (including alternate)'
  853. )
  854. wait_until_all_rpcs_go_to_given_backends(
  855. original_backend_instances + alternate_backend_instances,
  856. _WAIT_FOR_STATS_SEC)
  857. retry_count = 40
  858. # Each attempt takes about 10 seconds, 40 retries is equivalent to 400
  859. # seconds timeout.
  860. for i in range(retry_count):
  861. stats = get_client_stats(_NUM_TEST_RPCS, _WAIT_FOR_STATS_SEC)
  862. if not stats.rpcs_by_method:
  863. raise ValueError(
  864. 'stats.rpcs_by_method is None, the interop client stats service does not support this test case'
  865. )
  866. logger.info('attempt %d', i)
  867. if compare_expected_instances(stats, expected_instances):
  868. logger.info("success")
  869. break
  870. elif i == retry_count - 1:
  871. raise Exception(
  872. 'timeout waiting for RPCs to the expected instances: %s'
  873. % expected_instances)
  874. finally:
  875. patch_url_map_backend_service(gcp, original_backend_service)
  876. patch_backend_instances(gcp, alternate_backend_service, [])
  877. def test_header_matching(gcp, original_backend_service, instance_group,
  878. alternate_backend_service, same_zone_instance_group):
  879. # This test start with all traffic (UnaryCall and EmptyCall) going to
  880. # original_backend_service.
  881. #
  882. # Then it updates URL-map to add routes, to make RPCs with test headers to
  883. # go to different backends. It waits for all backends in both services to
  884. # receive traffic, then verifies that traffic goes to the expected
  885. # backends.
  886. logger.info('Running test_header_matching')
  887. original_backend_instances, alternate_backend_instances = prepare_services_for_urlmap_tests(
  888. gcp, original_backend_service, instance_group,
  889. alternate_backend_service, same_zone_instance_group)
  890. try:
  891. # A list of tuples (route_rules, expected_instances).
  892. test_cases = [
  893. (
  894. [{
  895. 'priority': 0,
  896. # Header ExactMatch -> alternate_backend_service.
  897. # EmptyCall is sent with the metadata.
  898. 'matchRules': [{
  899. 'prefixMatch':
  900. '/',
  901. 'headerMatches': [{
  902. 'headerName': _TEST_METADATA_KEY,
  903. 'exactMatch': _TEST_METADATA_VALUE_EMPTY
  904. }]
  905. }],
  906. 'service': alternate_backend_service.url
  907. }],
  908. {
  909. "EmptyCall": alternate_backend_instances,
  910. "UnaryCall": original_backend_instances
  911. }),
  912. (
  913. [{
  914. 'priority': 0,
  915. # Header PrefixMatch -> alternate_backend_service.
  916. # UnaryCall is sent with the metadata.
  917. 'matchRules': [{
  918. 'prefixMatch':
  919. '/',
  920. 'headerMatches': [{
  921. 'headerName': _TEST_METADATA_KEY,
  922. 'prefixMatch': _TEST_METADATA_VALUE_UNARY[:2]
  923. }]
  924. }],
  925. 'service': alternate_backend_service.url
  926. }],
  927. {
  928. "EmptyCall": original_backend_instances,
  929. "UnaryCall": alternate_backend_instances
  930. }),
  931. (
  932. [{
  933. 'priority': 0,
  934. # Header SuffixMatch -> alternate_backend_service.
  935. # EmptyCall is sent with the metadata.
  936. 'matchRules': [{
  937. 'prefixMatch':
  938. '/',
  939. 'headerMatches': [{
  940. 'headerName': _TEST_METADATA_KEY,
  941. 'suffixMatch': _TEST_METADATA_VALUE_EMPTY[-2:]
  942. }]
  943. }],
  944. 'service': alternate_backend_service.url
  945. }],
  946. {
  947. "EmptyCall": alternate_backend_instances,
  948. "UnaryCall": original_backend_instances
  949. }),
  950. (
  951. [{
  952. 'priority': 0,
  953. # Header 'xds_md_numeric' present -> alternate_backend_service.
  954. # UnaryCall is sent with the metadata, so will be sent to alternative.
  955. 'matchRules': [{
  956. 'prefixMatch':
  957. '/',
  958. 'headerMatches': [{
  959. 'headerName': _TEST_METADATA_NUMERIC_KEY,
  960. 'presentMatch': True
  961. }]
  962. }],
  963. 'service': alternate_backend_service.url
  964. }],
  965. {
  966. "EmptyCall": original_backend_instances,
  967. "UnaryCall": alternate_backend_instances
  968. }),
  969. (
  970. [{
  971. 'priority': 0,
  972. # Header invert ExactMatch -> alternate_backend_service.
  973. # UnaryCall is sent with the metadata, so will be sent to
  974. # original. EmptyCall will be sent to alternative.
  975. 'matchRules': [{
  976. 'prefixMatch':
  977. '/',
  978. 'headerMatches': [{
  979. 'headerName': _TEST_METADATA_KEY,
  980. 'exactMatch': _TEST_METADATA_VALUE_UNARY,
  981. 'invertMatch': True
  982. }]
  983. }],
  984. 'service': alternate_backend_service.url
  985. }],
  986. {
  987. "EmptyCall": alternate_backend_instances,
  988. "UnaryCall": original_backend_instances
  989. }),
  990. (
  991. [{
  992. 'priority': 0,
  993. # Header 'xds_md_numeric' range [100,200] -> alternate_backend_service.
  994. # UnaryCall is sent with the metadata in range.
  995. 'matchRules': [{
  996. 'prefixMatch':
  997. '/',
  998. 'headerMatches': [{
  999. 'headerName': _TEST_METADATA_NUMERIC_KEY,
  1000. 'rangeMatch': {
  1001. 'rangeStart': '100',
  1002. 'rangeEnd': '200'
  1003. }
  1004. }]
  1005. }],
  1006. 'service': alternate_backend_service.url
  1007. }],
  1008. {
  1009. "EmptyCall": original_backend_instances,
  1010. "UnaryCall": alternate_backend_instances
  1011. }),
  1012. ]
  1013. for (route_rules, expected_instances) in test_cases:
  1014. logger.info('patching url map with %s -> alternative',
  1015. route_rules[0]['matchRules'])
  1016. patch_url_map_backend_service(gcp,
  1017. original_backend_service,
  1018. route_rules=route_rules)
  1019. # Wait for traffic to go to both services.
  1020. logger.info(
  1021. 'waiting for traffic to go to all backends (including alternate)'
  1022. )
  1023. wait_until_all_rpcs_go_to_given_backends(
  1024. original_backend_instances + alternate_backend_instances,
  1025. _WAIT_FOR_STATS_SEC)
  1026. retry_count = 40
  1027. # Each attempt takes about 10 seconds, 40 retries is equivalent to 400
  1028. # seconds timeout.
  1029. for i in range(retry_count):
  1030. stats = get_client_stats(_NUM_TEST_RPCS, _WAIT_FOR_STATS_SEC)
  1031. if not stats.rpcs_by_method:
  1032. raise ValueError(
  1033. 'stats.rpcs_by_method is None, the interop client stats service does not support this test case'
  1034. )
  1035. logger.info('attempt %d', i)
  1036. if compare_expected_instances(stats, expected_instances):
  1037. logger.info("success")
  1038. break
  1039. elif i == retry_count - 1:
  1040. raise Exception(
  1041. 'timeout waiting for RPCs to the expected instances: %s'
  1042. % expected_instances)
  1043. finally:
  1044. patch_url_map_backend_service(gcp, original_backend_service)
  1045. patch_backend_instances(gcp, alternate_backend_service, [])
  1046. def get_serving_status(instance, service_port):
  1047. with grpc.insecure_channel('%s:%d' % (instance, service_port)) as channel:
  1048. health_stub = health_pb2_grpc.HealthStub(channel)
  1049. return health_stub.Check(health_pb2.HealthCheckRequest())
  1050. def set_serving_status(instances, service_port, serving):
  1051. logger.info('setting %s serving status to %s', instances, serving)
  1052. for instance in instances:
  1053. with grpc.insecure_channel('%s:%d' %
  1054. (instance, service_port)) as channel:
  1055. logger.info('setting %s serving status to %s', instance, serving)
  1056. stub = test_pb2_grpc.XdsUpdateHealthServiceStub(channel)
  1057. retry_count = 5
  1058. for i in range(5):
  1059. if serving:
  1060. stub.SetServing(empty_pb2.Empty())
  1061. else:
  1062. stub.SetNotServing(empty_pb2.Empty())
  1063. serving_status = get_serving_status(instance, service_port)
  1064. logger.info('got instance service status %s', serving_status)
  1065. want_status = health_pb2.HealthCheckResponse.SERVING if serving else health_pb2.HealthCheckResponse.NOT_SERVING
  1066. if serving_status.status == want_status:
  1067. break
  1068. if i == retry_count - 1:
  1069. raise Exception(
  1070. 'failed to set instance service status after %d retries'
  1071. % retry_count)
  1072. def is_primary_instance_group(gcp, instance_group):
  1073. # Clients may connect to a TD instance in a different region than the
  1074. # client, in which case primary/secondary assignments may not be based on
  1075. # the client's actual locality.
  1076. instance_names = get_instance_names(gcp, instance_group)
  1077. stats = get_client_stats(_NUM_TEST_RPCS, _WAIT_FOR_STATS_SEC)
  1078. return all(peer in instance_names for peer in stats.rpcs_by_peer.keys())
  1079. def get_startup_script(path_to_server_binary, service_port):
  1080. if path_to_server_binary:
  1081. return "nohup %s --port=%d 1>/dev/null &" % (path_to_server_binary,
  1082. service_port)
  1083. else:
  1084. return """#!/bin/bash
  1085. sudo apt update
  1086. sudo apt install -y git default-jdk
  1087. mkdir java_server
  1088. pushd java_server
  1089. git clone https://github.com/grpc/grpc-java.git
  1090. pushd grpc-java
  1091. pushd interop-testing
  1092. ../gradlew installDist -x test -PskipCodegen=true -PskipAndroid=true
  1093. nohup build/install/grpc-interop-testing/bin/xds-test-server \
  1094. --port=%d 1>/dev/null &""" % service_port
  1095. def create_instance_template(gcp, name, network, source_image, machine_type,
  1096. startup_script):
  1097. config = {
  1098. 'name': name,
  1099. 'properties': {
  1100. 'tags': {
  1101. 'items': ['allow-health-checks']
  1102. },
  1103. 'machineType': machine_type,
  1104. 'serviceAccounts': [{
  1105. 'email': 'default',
  1106. 'scopes': ['https://www.googleapis.com/auth/cloud-platform',]
  1107. }],
  1108. 'networkInterfaces': [{
  1109. 'accessConfigs': [{
  1110. 'type': 'ONE_TO_ONE_NAT'
  1111. }],
  1112. 'network': network
  1113. }],
  1114. 'disks': [{
  1115. 'boot': True,
  1116. 'initializeParams': {
  1117. 'sourceImage': source_image
  1118. }
  1119. }],
  1120. 'metadata': {
  1121. 'items': [{
  1122. 'key': 'startup-script',
  1123. 'value': startup_script
  1124. }]
  1125. }
  1126. }
  1127. }
  1128. logger.debug('Sending GCP request with body=%s', config)
  1129. result = gcp.compute.instanceTemplates().insert(
  1130. project=gcp.project, body=config).execute(num_retries=_GCP_API_RETRIES)
  1131. wait_for_global_operation(gcp, result['name'])
  1132. gcp.instance_template = GcpResource(config['name'], result['targetLink'])
  1133. def add_instance_group(gcp, zone, name, size):
  1134. config = {
  1135. 'name': name,
  1136. 'instanceTemplate': gcp.instance_template.url,
  1137. 'targetSize': size,
  1138. 'namedPorts': [{
  1139. 'name': 'grpc',
  1140. 'port': gcp.service_port
  1141. }]
  1142. }
  1143. logger.debug('Sending GCP request with body=%s', config)
  1144. result = gcp.compute.instanceGroupManagers().insert(
  1145. project=gcp.project, zone=zone,
  1146. body=config).execute(num_retries=_GCP_API_RETRIES)
  1147. wait_for_zone_operation(gcp, zone, result['name'])
  1148. result = gcp.compute.instanceGroupManagers().get(
  1149. project=gcp.project, zone=zone,
  1150. instanceGroupManager=config['name']).execute(
  1151. num_retries=_GCP_API_RETRIES)
  1152. instance_group = InstanceGroup(config['name'], result['instanceGroup'],
  1153. zone)
  1154. gcp.instance_groups.append(instance_group)
  1155. wait_for_instance_group_to_reach_expected_size(gcp, instance_group, size,
  1156. _WAIT_FOR_OPERATION_SEC)
  1157. return instance_group
  1158. def create_health_check(gcp, name):
  1159. if gcp.alpha_compute:
  1160. config = {
  1161. 'name': name,
  1162. 'type': 'GRPC',
  1163. 'grpcHealthCheck': {
  1164. 'portSpecification': 'USE_SERVING_PORT'
  1165. }
  1166. }
  1167. compute_to_use = gcp.alpha_compute
  1168. else:
  1169. config = {
  1170. 'name': name,
  1171. 'type': 'TCP',
  1172. 'tcpHealthCheck': {
  1173. 'portName': 'grpc'
  1174. }
  1175. }
  1176. compute_to_use = gcp.compute
  1177. logger.debug('Sending GCP request with body=%s', config)
  1178. result = compute_to_use.healthChecks().insert(
  1179. project=gcp.project, body=config).execute(num_retries=_GCP_API_RETRIES)
  1180. wait_for_global_operation(gcp, result['name'])
  1181. gcp.health_check = GcpResource(config['name'], result['targetLink'])
  1182. def create_health_check_firewall_rule(gcp, name):
  1183. config = {
  1184. 'name': name,
  1185. 'direction': 'INGRESS',
  1186. 'allowed': [{
  1187. 'IPProtocol': 'tcp'
  1188. }],
  1189. 'sourceRanges': ['35.191.0.0/16', '130.211.0.0/22'],
  1190. 'targetTags': ['allow-health-checks'],
  1191. }
  1192. logger.debug('Sending GCP request with body=%s', config)
  1193. result = gcp.compute.firewalls().insert(
  1194. project=gcp.project, body=config).execute(num_retries=_GCP_API_RETRIES)
  1195. wait_for_global_operation(gcp, result['name'])
  1196. gcp.health_check_firewall_rule = GcpResource(config['name'],
  1197. result['targetLink'])
  1198. def add_backend_service(gcp, name):
  1199. if gcp.alpha_compute:
  1200. protocol = 'GRPC'
  1201. compute_to_use = gcp.alpha_compute
  1202. else:
  1203. protocol = 'HTTP2'
  1204. compute_to_use = gcp.compute
  1205. config = {
  1206. 'name': name,
  1207. 'loadBalancingScheme': 'INTERNAL_SELF_MANAGED',
  1208. 'healthChecks': [gcp.health_check.url],
  1209. 'portName': 'grpc',
  1210. 'protocol': protocol
  1211. }
  1212. logger.debug('Sending GCP request with body=%s', config)
  1213. result = compute_to_use.backendServices().insert(
  1214. project=gcp.project, body=config).execute(num_retries=_GCP_API_RETRIES)
  1215. wait_for_global_operation(gcp, result['name'])
  1216. backend_service = GcpResource(config['name'], result['targetLink'])
  1217. gcp.backend_services.append(backend_service)
  1218. return backend_service
  1219. def create_url_map(gcp, name, backend_service, host_name):
  1220. config = {
  1221. 'name': name,
  1222. 'defaultService': backend_service.url,
  1223. 'pathMatchers': [{
  1224. 'name': _PATH_MATCHER_NAME,
  1225. 'defaultService': backend_service.url,
  1226. }],
  1227. 'hostRules': [{
  1228. 'hosts': [host_name],
  1229. 'pathMatcher': _PATH_MATCHER_NAME
  1230. }]
  1231. }
  1232. logger.debug('Sending GCP request with body=%s', config)
  1233. result = gcp.compute.urlMaps().insert(
  1234. project=gcp.project, body=config).execute(num_retries=_GCP_API_RETRIES)
  1235. wait_for_global_operation(gcp, result['name'])
  1236. gcp.url_map = GcpResource(config['name'], result['targetLink'])
  1237. def patch_url_map_host_rule_with_port(gcp, name, backend_service, host_name):
  1238. config = {
  1239. 'hostRules': [{
  1240. 'hosts': ['%s:%d' % (host_name, gcp.service_port)],
  1241. 'pathMatcher': _PATH_MATCHER_NAME
  1242. }]
  1243. }
  1244. logger.debug('Sending GCP request with body=%s', config)
  1245. result = gcp.compute.urlMaps().patch(
  1246. project=gcp.project, urlMap=name,
  1247. body=config).execute(num_retries=_GCP_API_RETRIES)
  1248. wait_for_global_operation(gcp, result['name'])
  1249. def create_target_proxy(gcp, name):
  1250. if gcp.alpha_compute:
  1251. config = {
  1252. 'name': name,
  1253. 'url_map': gcp.url_map.url,
  1254. 'validate_for_proxyless': True,
  1255. }
  1256. logger.debug('Sending GCP request with body=%s', config)
  1257. result = gcp.alpha_compute.targetGrpcProxies().insert(
  1258. project=gcp.project,
  1259. body=config).execute(num_retries=_GCP_API_RETRIES)
  1260. else:
  1261. config = {
  1262. 'name': name,
  1263. 'url_map': gcp.url_map.url,
  1264. }
  1265. logger.debug('Sending GCP request with body=%s', config)
  1266. result = gcp.compute.targetHttpProxies().insert(
  1267. project=gcp.project,
  1268. body=config).execute(num_retries=_GCP_API_RETRIES)
  1269. wait_for_global_operation(gcp, result['name'])
  1270. gcp.target_proxy = GcpResource(config['name'], result['targetLink'])
  1271. def create_global_forwarding_rule(gcp, name, potential_ports):
  1272. if gcp.alpha_compute:
  1273. compute_to_use = gcp.alpha_compute
  1274. else:
  1275. compute_to_use = gcp.compute
  1276. for port in potential_ports:
  1277. try:
  1278. config = {
  1279. 'name': name,
  1280. 'loadBalancingScheme': 'INTERNAL_SELF_MANAGED',
  1281. 'portRange': str(port),
  1282. 'IPAddress': '0.0.0.0',
  1283. 'network': args.network,
  1284. 'target': gcp.target_proxy.url,
  1285. }
  1286. logger.debug('Sending GCP request with body=%s', config)
  1287. result = compute_to_use.globalForwardingRules().insert(
  1288. project=gcp.project,
  1289. body=config).execute(num_retries=_GCP_API_RETRIES)
  1290. wait_for_global_operation(gcp, result['name'])
  1291. gcp.global_forwarding_rule = GcpResource(config['name'],
  1292. result['targetLink'])
  1293. gcp.service_port = port
  1294. return
  1295. except googleapiclient.errors.HttpError as http_error:
  1296. logger.warning(
  1297. 'Got error %s when attempting to create forwarding rule to '
  1298. '0.0.0.0:%d. Retrying with another port.' % (http_error, port))
  1299. def get_health_check(gcp, health_check_name):
  1300. result = gcp.compute.healthChecks().get(
  1301. project=gcp.project, healthCheck=health_check_name).execute()
  1302. gcp.health_check = GcpResource(health_check_name, result['selfLink'])
  1303. def get_health_check_firewall_rule(gcp, firewall_name):
  1304. result = gcp.compute.firewalls().get(project=gcp.project,
  1305. firewall=firewall_name).execute()
  1306. gcp.health_check_firewall_rule = GcpResource(firewall_name,
  1307. result['selfLink'])
  1308. def get_backend_service(gcp, backend_service_name):
  1309. result = gcp.compute.backendServices().get(
  1310. project=gcp.project, backendService=backend_service_name).execute()
  1311. backend_service = GcpResource(backend_service_name, result['selfLink'])
  1312. gcp.backend_services.append(backend_service)
  1313. return backend_service
  1314. def get_url_map(gcp, url_map_name):
  1315. result = gcp.compute.urlMaps().get(project=gcp.project,
  1316. urlMap=url_map_name).execute()
  1317. gcp.url_map = GcpResource(url_map_name, result['selfLink'])
  1318. def get_target_proxy(gcp, target_proxy_name):
  1319. if gcp.alpha_compute:
  1320. result = gcp.alpha_compute.targetGrpcProxies().get(
  1321. project=gcp.project, targetGrpcProxy=target_proxy_name).execute()
  1322. else:
  1323. result = gcp.compute.targetHttpProxies().get(
  1324. project=gcp.project, targetHttpProxy=target_proxy_name).execute()
  1325. gcp.target_proxy = GcpResource(target_proxy_name, result['selfLink'])
  1326. def get_global_forwarding_rule(gcp, forwarding_rule_name):
  1327. result = gcp.compute.globalForwardingRules().get(
  1328. project=gcp.project, forwardingRule=forwarding_rule_name).execute()
  1329. gcp.global_forwarding_rule = GcpResource(forwarding_rule_name,
  1330. result['selfLink'])
  1331. def get_instance_template(gcp, template_name):
  1332. result = gcp.compute.instanceTemplates().get(
  1333. project=gcp.project, instanceTemplate=template_name).execute()
  1334. gcp.instance_template = GcpResource(template_name, result['selfLink'])
  1335. def get_instance_group(gcp, zone, instance_group_name):
  1336. result = gcp.compute.instanceGroups().get(
  1337. project=gcp.project, zone=zone,
  1338. instanceGroup=instance_group_name).execute()
  1339. gcp.service_port = result['namedPorts'][0]['port']
  1340. instance_group = InstanceGroup(instance_group_name, result['selfLink'],
  1341. zone)
  1342. gcp.instance_groups.append(instance_group)
  1343. return instance_group
  1344. def delete_global_forwarding_rule(gcp):
  1345. try:
  1346. result = gcp.compute.globalForwardingRules().delete(
  1347. project=gcp.project,
  1348. forwardingRule=gcp.global_forwarding_rule.name).execute(
  1349. num_retries=_GCP_API_RETRIES)
  1350. wait_for_global_operation(gcp, result['name'])
  1351. except googleapiclient.errors.HttpError as http_error:
  1352. logger.info('Delete failed: %s', http_error)
  1353. def delete_target_proxy(gcp):
  1354. try:
  1355. if gcp.alpha_compute:
  1356. result = gcp.alpha_compute.targetGrpcProxies().delete(
  1357. project=gcp.project,
  1358. targetGrpcProxy=gcp.target_proxy.name).execute(
  1359. num_retries=_GCP_API_RETRIES)
  1360. else:
  1361. result = gcp.compute.targetHttpProxies().delete(
  1362. project=gcp.project,
  1363. targetHttpProxy=gcp.target_proxy.name).execute(
  1364. num_retries=_GCP_API_RETRIES)
  1365. wait_for_global_operation(gcp, result['name'])
  1366. except googleapiclient.errors.HttpError as http_error:
  1367. logger.info('Delete failed: %s', http_error)
  1368. def delete_url_map(gcp):
  1369. try:
  1370. result = gcp.compute.urlMaps().delete(
  1371. project=gcp.project,
  1372. urlMap=gcp.url_map.name).execute(num_retries=_GCP_API_RETRIES)
  1373. wait_for_global_operation(gcp, result['name'])
  1374. except googleapiclient.errors.HttpError as http_error:
  1375. logger.info('Delete failed: %s', http_error)
  1376. def delete_backend_services(gcp):
  1377. for backend_service in gcp.backend_services:
  1378. try:
  1379. result = gcp.compute.backendServices().delete(
  1380. project=gcp.project,
  1381. backendService=backend_service.name).execute(
  1382. num_retries=_GCP_API_RETRIES)
  1383. wait_for_global_operation(gcp, result['name'])
  1384. except googleapiclient.errors.HttpError as http_error:
  1385. logger.info('Delete failed: %s', http_error)
  1386. def delete_firewall(gcp):
  1387. try:
  1388. result = gcp.compute.firewalls().delete(
  1389. project=gcp.project,
  1390. firewall=gcp.health_check_firewall_rule.name).execute(
  1391. num_retries=_GCP_API_RETRIES)
  1392. wait_for_global_operation(gcp, result['name'])
  1393. except googleapiclient.errors.HttpError as http_error:
  1394. logger.info('Delete failed: %s', http_error)
  1395. def delete_health_check(gcp):
  1396. try:
  1397. result = gcp.compute.healthChecks().delete(
  1398. project=gcp.project, healthCheck=gcp.health_check.name).execute(
  1399. num_retries=_GCP_API_RETRIES)
  1400. wait_for_global_operation(gcp, result['name'])
  1401. except googleapiclient.errors.HttpError as http_error:
  1402. logger.info('Delete failed: %s', http_error)
  1403. def delete_instance_groups(gcp):
  1404. for instance_group in gcp.instance_groups:
  1405. try:
  1406. result = gcp.compute.instanceGroupManagers().delete(
  1407. project=gcp.project,
  1408. zone=instance_group.zone,
  1409. instanceGroupManager=instance_group.name).execute(
  1410. num_retries=_GCP_API_RETRIES)
  1411. wait_for_zone_operation(gcp,
  1412. instance_group.zone,
  1413. result['name'],
  1414. timeout_sec=_WAIT_FOR_BACKEND_SEC)
  1415. except googleapiclient.errors.HttpError as http_error:
  1416. logger.info('Delete failed: %s', http_error)
  1417. def delete_instance_template(gcp):
  1418. try:
  1419. result = gcp.compute.instanceTemplates().delete(
  1420. project=gcp.project,
  1421. instanceTemplate=gcp.instance_template.name).execute(
  1422. num_retries=_GCP_API_RETRIES)
  1423. wait_for_global_operation(gcp, result['name'])
  1424. except googleapiclient.errors.HttpError as http_error:
  1425. logger.info('Delete failed: %s', http_error)
  1426. def patch_backend_instances(gcp,
  1427. backend_service,
  1428. instance_groups,
  1429. balancing_mode='UTILIZATION',
  1430. max_rate=1):
  1431. if gcp.alpha_compute:
  1432. compute_to_use = gcp.alpha_compute
  1433. else:
  1434. compute_to_use = gcp.compute
  1435. config = {
  1436. 'backends': [{
  1437. 'group': instance_group.url,
  1438. 'balancingMode': balancing_mode,
  1439. 'maxRate': max_rate if balancing_mode == 'RATE' else None
  1440. } for instance_group in instance_groups],
  1441. }
  1442. logger.debug('Sending GCP request with body=%s', config)
  1443. result = compute_to_use.backendServices().patch(
  1444. project=gcp.project, backendService=backend_service.name,
  1445. body=config).execute(num_retries=_GCP_API_RETRIES)
  1446. wait_for_global_operation(gcp,
  1447. result['name'],
  1448. timeout_sec=_WAIT_FOR_BACKEND_SEC)
  1449. def resize_instance_group(gcp,
  1450. instance_group,
  1451. new_size,
  1452. timeout_sec=_WAIT_FOR_OPERATION_SEC):
  1453. result = gcp.compute.instanceGroupManagers().resize(
  1454. project=gcp.project,
  1455. zone=instance_group.zone,
  1456. instanceGroupManager=instance_group.name,
  1457. size=new_size).execute(num_retries=_GCP_API_RETRIES)
  1458. wait_for_zone_operation(gcp,
  1459. instance_group.zone,
  1460. result['name'],
  1461. timeout_sec=360)
  1462. wait_for_instance_group_to_reach_expected_size(gcp, instance_group,
  1463. new_size, timeout_sec)
  1464. def patch_url_map_backend_service(gcp,
  1465. backend_service=None,
  1466. services_with_weights=None,
  1467. route_rules=None):
  1468. '''change url_map's backend service
  1469. Only one of backend_service and service_with_weights can be not None.
  1470. '''
  1471. if backend_service and services_with_weights:
  1472. raise ValueError(
  1473. 'both backend_service and service_with_weights are not None.')
  1474. default_service = backend_service.url if backend_service else None
  1475. default_route_action = {
  1476. 'weightedBackendServices': [{
  1477. 'backendService': service.url,
  1478. 'weight': w,
  1479. } for service, w in services_with_weights.items()]
  1480. } if services_with_weights else None
  1481. config = {
  1482. 'pathMatchers': [{
  1483. 'name': _PATH_MATCHER_NAME,
  1484. 'defaultService': default_service,
  1485. 'defaultRouteAction': default_route_action,
  1486. 'routeRules': route_rules,
  1487. }]
  1488. }
  1489. logger.debug('Sending GCP request with body=%s', config)
  1490. result = gcp.compute.urlMaps().patch(
  1491. project=gcp.project, urlMap=gcp.url_map.name,
  1492. body=config).execute(num_retries=_GCP_API_RETRIES)
  1493. wait_for_global_operation(gcp, result['name'])
  1494. def wait_for_instance_group_to_reach_expected_size(gcp, instance_group,
  1495. expected_size, timeout_sec):
  1496. start_time = time.time()
  1497. while True:
  1498. current_size = len(get_instance_names(gcp, instance_group))
  1499. if current_size == expected_size:
  1500. break
  1501. if time.time() - start_time > timeout_sec:
  1502. raise Exception(
  1503. 'Instance group had expected size %d but actual size %d' %
  1504. (expected_size, current_size))
  1505. time.sleep(2)
  1506. def wait_for_global_operation(gcp,
  1507. operation,
  1508. timeout_sec=_WAIT_FOR_OPERATION_SEC):
  1509. start_time = time.time()
  1510. while time.time() - start_time <= timeout_sec:
  1511. result = gcp.compute.globalOperations().get(
  1512. project=gcp.project,
  1513. operation=operation).execute(num_retries=_GCP_API_RETRIES)
  1514. if result['status'] == 'DONE':
  1515. if 'error' in result:
  1516. raise Exception(result['error'])
  1517. return
  1518. time.sleep(2)
  1519. raise Exception('Operation %s did not complete within %d', operation,
  1520. timeout_sec)
  1521. def wait_for_zone_operation(gcp,
  1522. zone,
  1523. operation,
  1524. timeout_sec=_WAIT_FOR_OPERATION_SEC):
  1525. start_time = time.time()
  1526. while time.time() - start_time <= timeout_sec:
  1527. result = gcp.compute.zoneOperations().get(
  1528. project=gcp.project, zone=zone,
  1529. operation=operation).execute(num_retries=_GCP_API_RETRIES)
  1530. if result['status'] == 'DONE':
  1531. if 'error' in result:
  1532. raise Exception(result['error'])
  1533. return
  1534. time.sleep(2)
  1535. raise Exception('Operation %s did not complete within %d', operation,
  1536. timeout_sec)
  1537. def wait_for_healthy_backends(gcp,
  1538. backend_service,
  1539. instance_group,
  1540. timeout_sec=_WAIT_FOR_BACKEND_SEC):
  1541. start_time = time.time()
  1542. config = {'group': instance_group.url}
  1543. instance_names = get_instance_names(gcp, instance_group)
  1544. expected_size = len(instance_names)
  1545. while time.time() - start_time <= timeout_sec:
  1546. for instance_name in instance_names:
  1547. try:
  1548. status = get_serving_status(instance_name, gcp.service_port)
  1549. logger.info('serving status response from %s: %s',
  1550. instance_name, status)
  1551. except grpc.RpcError as rpc_error:
  1552. logger.info('checking serving status of %s failed: %s',
  1553. instance_name, rpc_error)
  1554. result = gcp.compute.backendServices().getHealth(
  1555. project=gcp.project,
  1556. backendService=backend_service.name,
  1557. body=config).execute(num_retries=_GCP_API_RETRIES)
  1558. if 'healthStatus' in result:
  1559. logger.info('received GCP healthStatus: %s', result['healthStatus'])
  1560. healthy = True
  1561. for instance in result['healthStatus']:
  1562. if instance['healthState'] != 'HEALTHY':
  1563. healthy = False
  1564. break
  1565. if healthy and expected_size == len(result['healthStatus']):
  1566. return
  1567. else:
  1568. logger.info('no healthStatus received from GCP')
  1569. time.sleep(5)
  1570. raise Exception('Not all backends became healthy within %d seconds: %s' %
  1571. (timeout_sec, result))
  1572. def get_instance_names(gcp, instance_group):
  1573. instance_names = []
  1574. result = gcp.compute.instanceGroups().listInstances(
  1575. project=gcp.project,
  1576. zone=instance_group.zone,
  1577. instanceGroup=instance_group.name,
  1578. body={
  1579. 'instanceState': 'ALL'
  1580. }).execute(num_retries=_GCP_API_RETRIES)
  1581. if 'items' not in result:
  1582. return []
  1583. for item in result['items']:
  1584. # listInstances() returns the full URL of the instance, which ends with
  1585. # the instance name. compute.instances().get() requires using the
  1586. # instance name (not the full URL) to look up instance details, so we
  1587. # just extract the name manually.
  1588. instance_name = item['instance'].split('/')[-1]
  1589. instance_names.append(instance_name)
  1590. logger.info('retrieved instance names: %s', instance_names)
  1591. return instance_names
  1592. def clean_up(gcp):
  1593. if gcp.global_forwarding_rule:
  1594. delete_global_forwarding_rule(gcp)
  1595. if gcp.target_proxy:
  1596. delete_target_proxy(gcp)
  1597. if gcp.url_map:
  1598. delete_url_map(gcp)
  1599. delete_backend_services(gcp)
  1600. if gcp.health_check_firewall_rule:
  1601. delete_firewall(gcp)
  1602. if gcp.health_check:
  1603. delete_health_check(gcp)
  1604. delete_instance_groups(gcp)
  1605. if gcp.instance_template:
  1606. delete_instance_template(gcp)
  1607. class InstanceGroup(object):
  1608. def __init__(self, name, url, zone):
  1609. self.name = name
  1610. self.url = url
  1611. self.zone = zone
  1612. class GcpResource(object):
  1613. def __init__(self, name, url):
  1614. self.name = name
  1615. self.url = url
  1616. class GcpState(object):
  1617. def __init__(self, compute, alpha_compute, project):
  1618. self.compute = compute
  1619. self.alpha_compute = alpha_compute
  1620. self.project = project
  1621. self.health_check = None
  1622. self.health_check_firewall_rule = None
  1623. self.backend_services = []
  1624. self.url_map = None
  1625. self.target_proxy = None
  1626. self.global_forwarding_rule = None
  1627. self.service_port = None
  1628. self.instance_template = None
  1629. self.instance_groups = []
  1630. alpha_compute = None
  1631. if args.compute_discovery_document:
  1632. with open(args.compute_discovery_document, 'r') as discovery_doc:
  1633. compute = googleapiclient.discovery.build_from_document(
  1634. discovery_doc.read())
  1635. if not args.only_stable_gcp_apis and args.alpha_compute_discovery_document:
  1636. with open(args.alpha_compute_discovery_document, 'r') as discovery_doc:
  1637. alpha_compute = googleapiclient.discovery.build_from_document(
  1638. discovery_doc.read())
  1639. else:
  1640. compute = googleapiclient.discovery.build('compute', 'v1')
  1641. if not args.only_stable_gcp_apis:
  1642. alpha_compute = googleapiclient.discovery.build('compute', 'alpha')
  1643. try:
  1644. gcp = GcpState(compute, alpha_compute, args.project_id)
  1645. gcp_suffix = args.gcp_suffix
  1646. health_check_name = _BASE_HEALTH_CHECK_NAME + gcp_suffix
  1647. if not args.use_existing_gcp_resources:
  1648. num_attempts = 5
  1649. for i in range(num_attempts):
  1650. try:
  1651. logger.info('Using GCP suffix %s', gcp_suffix)
  1652. create_health_check(gcp, health_check_name)
  1653. break
  1654. except googleapiclient.errors.HttpError as http_error:
  1655. gcp_suffix = '%s-%04d' % (gcp_suffix, random.randint(0, 9999))
  1656. health_check_name = _BASE_HEALTH_CHECK_NAME + gcp_suffix
  1657. logger.exception('HttpError when creating health check')
  1658. if gcp.health_check is None:
  1659. raise Exception('Failed to create health check name after %d '
  1660. 'attempts' % num_attempts)
  1661. firewall_name = _BASE_FIREWALL_RULE_NAME + gcp_suffix
  1662. backend_service_name = _BASE_BACKEND_SERVICE_NAME + gcp_suffix
  1663. alternate_backend_service_name = _BASE_BACKEND_SERVICE_NAME + '-alternate' + gcp_suffix
  1664. url_map_name = _BASE_URL_MAP_NAME + gcp_suffix
  1665. service_host_name = _BASE_SERVICE_HOST + gcp_suffix
  1666. target_proxy_name = _BASE_TARGET_PROXY_NAME + gcp_suffix
  1667. forwarding_rule_name = _BASE_FORWARDING_RULE_NAME + gcp_suffix
  1668. template_name = _BASE_TEMPLATE_NAME + gcp_suffix
  1669. instance_group_name = _BASE_INSTANCE_GROUP_NAME + gcp_suffix
  1670. same_zone_instance_group_name = _BASE_INSTANCE_GROUP_NAME + '-same-zone' + gcp_suffix
  1671. secondary_zone_instance_group_name = _BASE_INSTANCE_GROUP_NAME + '-secondary-zone' + gcp_suffix
  1672. if args.use_existing_gcp_resources:
  1673. logger.info('Reusing existing GCP resources')
  1674. get_health_check(gcp, health_check_name)
  1675. try:
  1676. get_health_check_firewall_rule(gcp, firewall_name)
  1677. except googleapiclient.errors.HttpError as http_error:
  1678. # Firewall rule may be auto-deleted periodically depending on GCP
  1679. # project settings.
  1680. logger.exception('Failed to find firewall rule, recreating')
  1681. create_health_check_firewall_rule(gcp, firewall_name)
  1682. backend_service = get_backend_service(gcp, backend_service_name)
  1683. alternate_backend_service = get_backend_service(
  1684. gcp, alternate_backend_service_name)
  1685. get_url_map(gcp, url_map_name)
  1686. get_target_proxy(gcp, target_proxy_name)
  1687. get_global_forwarding_rule(gcp, forwarding_rule_name)
  1688. get_instance_template(gcp, template_name)
  1689. instance_group = get_instance_group(gcp, args.zone, instance_group_name)
  1690. same_zone_instance_group = get_instance_group(
  1691. gcp, args.zone, same_zone_instance_group_name)
  1692. secondary_zone_instance_group = get_instance_group(
  1693. gcp, args.secondary_zone, secondary_zone_instance_group_name)
  1694. else:
  1695. create_health_check_firewall_rule(gcp, firewall_name)
  1696. backend_service = add_backend_service(gcp, backend_service_name)
  1697. alternate_backend_service = add_backend_service(
  1698. gcp, alternate_backend_service_name)
  1699. create_url_map(gcp, url_map_name, backend_service, service_host_name)
  1700. create_target_proxy(gcp, target_proxy_name)
  1701. potential_service_ports = list(args.service_port_range)
  1702. random.shuffle(potential_service_ports)
  1703. create_global_forwarding_rule(gcp, forwarding_rule_name,
  1704. potential_service_ports)
  1705. if not gcp.service_port:
  1706. raise Exception(
  1707. 'Failed to find a valid ip:port for the forwarding rule')
  1708. if gcp.service_port != _DEFAULT_SERVICE_PORT:
  1709. patch_url_map_host_rule_with_port(gcp, url_map_name,
  1710. backend_service,
  1711. service_host_name)
  1712. startup_script = get_startup_script(args.path_to_server_binary,
  1713. gcp.service_port)
  1714. create_instance_template(gcp, template_name, args.network,
  1715. args.source_image, args.machine_type,
  1716. startup_script)
  1717. instance_group = add_instance_group(gcp, args.zone, instance_group_name,
  1718. _INSTANCE_GROUP_SIZE)
  1719. patch_backend_instances(gcp, backend_service, [instance_group])
  1720. same_zone_instance_group = add_instance_group(
  1721. gcp, args.zone, same_zone_instance_group_name, _INSTANCE_GROUP_SIZE)
  1722. secondary_zone_instance_group = add_instance_group(
  1723. gcp, args.secondary_zone, secondary_zone_instance_group_name,
  1724. _INSTANCE_GROUP_SIZE)
  1725. wait_for_healthy_backends(gcp, backend_service, instance_group)
  1726. if args.test_case:
  1727. if gcp.service_port == _DEFAULT_SERVICE_PORT:
  1728. server_uri = service_host_name
  1729. else:
  1730. server_uri = service_host_name + ':' + str(gcp.service_port)
  1731. if args.bootstrap_file:
  1732. bootstrap_path = os.path.abspath(args.bootstrap_file)
  1733. else:
  1734. with tempfile.NamedTemporaryFile(delete=False) as bootstrap_file:
  1735. bootstrap_file.write(
  1736. _BOOTSTRAP_TEMPLATE.format(
  1737. node_id=socket.gethostname()).encode('utf-8'))
  1738. bootstrap_path = bootstrap_file.name
  1739. client_env = dict(os.environ, GRPC_XDS_BOOTSTRAP=bootstrap_path)
  1740. test_results = {}
  1741. failed_tests = []
  1742. for test_case in args.test_case:
  1743. result = jobset.JobResult()
  1744. log_dir = os.path.join(_TEST_LOG_BASE_DIR, test_case)
  1745. if not os.path.exists(log_dir):
  1746. os.makedirs(log_dir)
  1747. test_log_filename = os.path.join(log_dir, _SPONGE_LOG_NAME)
  1748. test_log_file = open(test_log_filename, 'w+')
  1749. client_process = None
  1750. if test_case in _TESTS_TO_RUN_MULTIPLE_RPCS:
  1751. rpcs_to_send = '--rpc="UnaryCall,EmptyCall"'
  1752. else:
  1753. rpcs_to_send = '--rpc="UnaryCall"'
  1754. if test_case in _TESTS_TO_SEND_METADATA:
  1755. metadata_to_send = '--metadata="EmptyCall:{keyE}:{valueE},UnaryCall:{keyU}:{valueU},UnaryCall:{keyNU}:{valueNU}"'.format(
  1756. keyE=_TEST_METADATA_KEY,
  1757. valueE=_TEST_METADATA_VALUE_EMPTY,
  1758. keyU=_TEST_METADATA_KEY,
  1759. valueU=_TEST_METADATA_VALUE_UNARY,
  1760. keyNU=_TEST_METADATA_NUMERIC_KEY,
  1761. valueNU=_TEST_METADATA_NUMERIC_VALUE)
  1762. else:
  1763. # Setting the arg explicitly to empty with '--metadata=""'
  1764. # makes C# client fail
  1765. # (see https://github.com/commandlineparser/commandline/issues/412),
  1766. # so instead we just rely on clients using the default when
  1767. # metadata arg is not specified.
  1768. metadata_to_send = ''
  1769. # TODO(ericgribkoff) Temporarily disable fail_on_failed_rpc checks
  1770. # in the client. This means we will ignore intermittent RPC
  1771. # failures (but this framework still checks that the final result
  1772. # is as expected).
  1773. #
  1774. # Reason for disabling this is, the resources are shared by
  1775. # multiple tests, and a change in previous test could be delayed
  1776. # until the second test starts. The second test may see
  1777. # intermittent failures because of that.
  1778. #
  1779. # A fix is to not share resources between tests (though that does
  1780. # mean the tests will be significantly slower due to creating new
  1781. # resources).
  1782. fail_on_failed_rpc = ''
  1783. client_cmd_formatted = args.client_cmd.format(
  1784. server_uri=server_uri,
  1785. stats_port=args.stats_port,
  1786. qps=args.qps,
  1787. fail_on_failed_rpc=fail_on_failed_rpc,
  1788. rpcs_to_send=rpcs_to_send,
  1789. metadata_to_send=metadata_to_send)
  1790. logger.debug('running client: %s', client_cmd_formatted)
  1791. client_cmd = shlex.split(client_cmd_formatted)
  1792. try:
  1793. client_process = subprocess.Popen(client_cmd,
  1794. env=client_env,
  1795. stderr=subprocess.STDOUT,
  1796. stdout=test_log_file)
  1797. if test_case == 'backends_restart':
  1798. test_backends_restart(gcp, backend_service, instance_group)
  1799. elif test_case == 'change_backend_service':
  1800. test_change_backend_service(gcp, backend_service,
  1801. instance_group,
  1802. alternate_backend_service,
  1803. same_zone_instance_group)
  1804. elif test_case == 'gentle_failover':
  1805. test_gentle_failover(gcp, backend_service, instance_group,
  1806. secondary_zone_instance_group)
  1807. elif test_case == 'load_report_based_failover':
  1808. test_load_report_based_failover(
  1809. gcp, backend_service, instance_group,
  1810. secondary_zone_instance_group)
  1811. elif test_case == 'ping_pong':
  1812. test_ping_pong(gcp, backend_service, instance_group)
  1813. elif test_case == 'remove_instance_group':
  1814. test_remove_instance_group(gcp, backend_service,
  1815. instance_group,
  1816. same_zone_instance_group)
  1817. elif test_case == 'round_robin':
  1818. test_round_robin(gcp, backend_service, instance_group)
  1819. elif test_case == 'secondary_locality_gets_no_requests_on_partial_primary_failure':
  1820. test_secondary_locality_gets_no_requests_on_partial_primary_failure(
  1821. gcp, backend_service, instance_group,
  1822. secondary_zone_instance_group)
  1823. elif test_case == 'secondary_locality_gets_requests_on_primary_failure':
  1824. test_secondary_locality_gets_requests_on_primary_failure(
  1825. gcp, backend_service, instance_group,
  1826. secondary_zone_instance_group)
  1827. elif test_case == 'traffic_splitting':
  1828. test_traffic_splitting(gcp, backend_service, instance_group,
  1829. alternate_backend_service,
  1830. same_zone_instance_group)
  1831. elif test_case == 'path_matching':
  1832. test_path_matching(gcp, backend_service, instance_group,
  1833. alternate_backend_service,
  1834. same_zone_instance_group)
  1835. elif test_case == 'header_matching':
  1836. test_header_matching(gcp, backend_service, instance_group,
  1837. alternate_backend_service,
  1838. same_zone_instance_group)
  1839. else:
  1840. logger.error('Unknown test case: %s', test_case)
  1841. sys.exit(1)
  1842. if client_process.poll() is not None:
  1843. raise Exception(
  1844. 'Client process exited prematurely with exit code %d' %
  1845. client_process.returncode)
  1846. result.state = 'PASSED'
  1847. result.returncode = 0
  1848. except Exception as e:
  1849. logger.exception('Test case %s failed', test_case)
  1850. failed_tests.append(test_case)
  1851. result.state = 'FAILED'
  1852. result.message = str(e)
  1853. finally:
  1854. if client_process and not client_process.returncode:
  1855. client_process.terminate()
  1856. test_log_file.close()
  1857. # Workaround for Python 3, as report_utils will invoke decode() on
  1858. # result.message, which has a default value of ''.
  1859. result.message = result.message.encode('UTF-8')
  1860. test_results[test_case] = [result]
  1861. if args.log_client_output:
  1862. logger.info('Client output:')
  1863. with open(test_log_filename, 'r') as client_output:
  1864. logger.info(client_output.read())
  1865. if not os.path.exists(_TEST_LOG_BASE_DIR):
  1866. os.makedirs(_TEST_LOG_BASE_DIR)
  1867. report_utils.render_junit_xml_report(test_results,
  1868. os.path.join(
  1869. _TEST_LOG_BASE_DIR,
  1870. _SPONGE_XML_NAME),
  1871. suite_name='xds_tests',
  1872. multi_target=True)
  1873. if failed_tests:
  1874. logger.error('Test case(s) %s failed', failed_tests)
  1875. sys.exit(1)
  1876. finally:
  1877. if not args.keep_gcp_resources:
  1878. logger.info('Cleaning up GCP resources. This may take some time.')
  1879. clean_up(gcp)