run_xds_tests.py 89 KB

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