run_xds_tests.py 85 KB

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