loadtest_config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #!/usr/bin/env python3
  2. # Copyright 2021 The 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. # Script to generate test configurations for the OSS benchmarks framework.
  16. #
  17. # This script filters test scenarios and generates uniquely named configurations
  18. # for each test. Configurations are dumped in multipart YAML format.
  19. #
  20. # See documentation below:
  21. # https://github.com/grpc/grpc/blob/master/tools/run_tests/performance/README.md#grpc-oss-benchmarks
  22. import argparse
  23. import collections
  24. import copy
  25. import datetime
  26. import itertools
  27. import json
  28. import os
  29. import string
  30. import sys
  31. from typing import Any, Dict, Iterable, Mapping, Optional, Type
  32. import yaml
  33. sys.path.append(os.path.dirname(os.path.abspath(__file__)))
  34. import scenario_config
  35. import scenario_config_exporter
  36. CONFIGURATION_FILE_HEADER_COMMENT = """
  37. # Load test configurations generated from a template by loadtest_config.py.
  38. # See documentation below:
  39. # https://github.com/grpc/grpc/blob/master/tools/run_tests/performance/README.md#grpc-oss-benchmarks
  40. """
  41. def safe_name(language: str) -> str:
  42. """Returns a name that is safe to use in labels and file names."""
  43. return scenario_config.LANGUAGES[language].safename
  44. def default_prefix() -> str:
  45. """Constructs and returns a default prefix for LoadTest names."""
  46. return os.environ.get('USER', 'loadtest')
  47. def now_string() -> str:
  48. """Returns the current date and time in string format."""
  49. return datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  50. def validate_loadtest_name(name: str) -> None:
  51. """Validates that a LoadTest name is in the expected format."""
  52. if len(name) > 253:
  53. raise ValueError(
  54. 'LoadTest name must be less than 253 characters long: %s' % name)
  55. if not all(c.isalnum() and not c.isupper() for c in name if c != '-'):
  56. raise ValueError('Invalid characters in LoadTest name: %s' % name)
  57. if not name or not name[0].isalpha() or name[-1] == '-':
  58. raise ValueError('Invalid format for LoadTest name: %s' % name)
  59. def loadtest_base_name(scenario_name: str,
  60. uniquifier_elements: Iterable[str]) -> str:
  61. """Constructs and returns the base name for a LoadTest resource."""
  62. name_elements = scenario_name.split('_')
  63. name_elements.extend(uniquifier_elements)
  64. return '-'.join(element.lower() for element in name_elements)
  65. def loadtest_name(prefix: str, scenario_name: str,
  66. uniquifier_elements: Iterable[str]) -> str:
  67. """Constructs and returns a valid name for a LoadTest resource."""
  68. base_name = loadtest_base_name(scenario_name, uniquifier_elements)
  69. name_elements = []
  70. if prefix:
  71. name_elements.append(prefix)
  72. name_elements.append(base_name)
  73. name = '-'.join(name_elements)
  74. validate_loadtest_name(name)
  75. return name
  76. def component_name(elements: Iterable[str]) -> str:
  77. """Constructs a component name from possibly empty elements."""
  78. return '-'.join((e for e in elements if e))
  79. def validate_annotations(annotations: Dict[str, str]) -> None:
  80. """Validates that annotations do not contain reserved names.
  81. These names are automatically added by the config generator.
  82. """
  83. names = set(('scenario', 'uniquifier')).intersection(annotations)
  84. if names:
  85. raise ValueError('Annotations contain reserved names: %s' % names)
  86. def gen_run_indices(runs_per_test: int) -> Iterable[str]:
  87. """Generates run indices for multiple runs, as formatted strings."""
  88. if runs_per_test < 2:
  89. yield ''
  90. return
  91. index_length = len('{:d}'.format(runs_per_test - 1))
  92. index_fmt = '{{:0{:d}d}}'.format(index_length)
  93. for i in range(runs_per_test):
  94. yield index_fmt.format(i)
  95. def gen_loadtest_configs(
  96. base_config: Mapping[str, Any],
  97. base_config_clients: Iterable[Mapping[str, Any]],
  98. base_config_servers: Iterable[Mapping[str, Any]],
  99. scenario_name_regex: str,
  100. language_config: scenario_config_exporter.LanguageConfig,
  101. loadtest_name_prefix: str,
  102. uniquifier_elements: Iterable[str],
  103. annotations: Mapping[str, str],
  104. instances_per_client: int = 1,
  105. runs_per_test: int = 1) -> Iterable[Dict[str, Any]]:
  106. """Generates LoadTest configurations for a given language config.
  107. The LoadTest configurations are generated as YAML objects.
  108. """
  109. validate_annotations(annotations)
  110. prefix = loadtest_name_prefix or default_prefix()
  111. cl = safe_name(language_config.client_language or language_config.language)
  112. sl = safe_name(language_config.server_language or language_config.language)
  113. scenario_filter = scenario_config_exporter.scenario_filter(
  114. scenario_name_regex=scenario_name_regex,
  115. category=language_config.category,
  116. client_language=language_config.client_language,
  117. server_language=language_config.server_language)
  118. scenarios = scenario_config_exporter.gen_scenarios(language_config.language,
  119. scenario_filter)
  120. for scenario in scenarios:
  121. for run_index in gen_run_indices(runs_per_test):
  122. uniq = (uniquifier_elements +
  123. [run_index] if run_index else uniquifier_elements)
  124. name = loadtest_name(prefix, scenario['name'], uniq)
  125. scenario_str = json.dumps({'scenarios': scenario},
  126. indent=' ') + '\n'
  127. config = copy.deepcopy(base_config)
  128. metadata = config['metadata']
  129. metadata['name'] = name
  130. if 'labels' not in metadata:
  131. metadata['labels'] = dict()
  132. metadata['labels']['language'] = safe_name(language_config.language)
  133. metadata['labels']['prefix'] = prefix
  134. if 'annotations' not in metadata:
  135. metadata['annotations'] = dict()
  136. metadata['annotations'].update(annotations)
  137. metadata['annotations'].update({
  138. 'scenario': scenario['name'],
  139. 'uniquifier': '-'.join(uniq),
  140. })
  141. spec = config['spec']
  142. # Select clients with the required language.
  143. clients = [
  144. client for client in base_config_clients
  145. if client['language'] == cl
  146. ]
  147. if not clients:
  148. raise IndexError('Client language not found in template: %s' %
  149. cl)
  150. # Validate config for additional client instances.
  151. if instances_per_client > 1:
  152. c = collections.Counter(
  153. (client.get('name', '') for client in clients))
  154. if max(c.values()) > 1:
  155. raise ValueError(
  156. ('Multiple instances of multiple clients requires '
  157. 'unique names, name counts for language %s: %s') %
  158. (cl, c.most_common()))
  159. # Name client instances with an index starting from zero.
  160. client_instances = []
  161. for i in range(instances_per_client):
  162. client_instances.extend(copy.deepcopy(clients))
  163. for client in client_instances[-len(clients):]:
  164. client['name'] = component_name((client.get('name',
  165. ''), str(i)))
  166. # Set clients to named instances.
  167. spec['clients'] = client_instances
  168. # Select servers with the required language.
  169. servers = copy.deepcopy([
  170. server for server in base_config_servers
  171. if server['language'] == sl
  172. ])
  173. if not servers:
  174. raise IndexError('Server language not found in template: %s' %
  175. sl)
  176. # Name servers with an index for consistency with clients.
  177. for i, server in enumerate(servers):
  178. server['name'] = component_name((server.get('name',
  179. ''), str(i)))
  180. # Set servers to named instances.
  181. spec['servers'] = servers
  182. # Add driver, if needed.
  183. if 'driver' not in spec:
  184. spec['driver'] = dict()
  185. # Ensure driver has language and run fields.
  186. driver = spec['driver']
  187. if 'language' not in driver:
  188. driver['language'] = safe_name('c++')
  189. if 'run' not in driver:
  190. driver['run'] = dict()
  191. # Name the driver with an index for consistency with workers.
  192. # There is only one driver, so the index is zero.
  193. if 'name' not in driver or not driver['name']:
  194. driver['name'] = '0'
  195. spec['scenariosJSON'] = scenario_str
  196. yield config
  197. def parse_key_value_args(args: Optional[Iterable[str]]) -> Dict[str, str]:
  198. """Parses arguments in the form key=value into a dictionary."""
  199. d = dict()
  200. if args is None:
  201. return d
  202. for arg in args:
  203. key, equals, value = arg.partition('=')
  204. if equals != '=':
  205. raise ValueError('Expected key=value: ' + value)
  206. d[key] = value
  207. return d
  208. def clear_empty_fields(config: Dict[str, Any]) -> None:
  209. """Clears fields set to empty values by string substitution."""
  210. spec = config['spec']
  211. if 'clients' in spec:
  212. for client in spec['clients']:
  213. if 'pool' in client and not client['pool']:
  214. del client['pool']
  215. if 'servers' in spec:
  216. for server in spec['servers']:
  217. if 'pool' in server and not server['pool']:
  218. del server['pool']
  219. if 'driver' in spec:
  220. driver = spec['driver']
  221. if 'pool' in driver and not driver['pool']:
  222. del driver['pool']
  223. if ('run' in driver and 'image' in driver['run'] and
  224. not driver['run']['image']):
  225. del driver['run']['image']
  226. if 'results' in spec and not ('bigQueryTable' in spec['results'] and
  227. spec['results']['bigQueryTable']):
  228. del spec['results']
  229. def config_dumper(header_comment: str) -> Type[yaml.SafeDumper]:
  230. """Returns a custom dumper to dump configurations in the expected format."""
  231. class ConfigDumper(yaml.SafeDumper):
  232. def expect_stream_start(self):
  233. super().expect_stream_start()
  234. if isinstance(self.event, yaml.StreamStartEvent):
  235. self.write_indent()
  236. self.write_indicator(header_comment, need_whitespace=False)
  237. def str_presenter(dumper, data):
  238. if '\n' in data:
  239. return dumper.represent_scalar('tag:yaml.org,2002:str',
  240. data,
  241. style='|')
  242. return dumper.represent_scalar('tag:yaml.org,2002:str', data)
  243. ConfigDumper.add_representer(str, str_presenter)
  244. return ConfigDumper
  245. def main() -> None:
  246. language_choices = sorted(scenario_config.LANGUAGES.keys())
  247. argp = argparse.ArgumentParser(
  248. description='Generates load test configs from a template.',
  249. fromfile_prefix_chars='@')
  250. argp.add_argument('-l',
  251. '--language',
  252. action='append',
  253. choices=language_choices,
  254. required=True,
  255. help='Language(s) to benchmark.',
  256. dest='languages')
  257. argp.add_argument('-t',
  258. '--template',
  259. type=str,
  260. required=True,
  261. help='LoadTest configuration yaml file template.')
  262. argp.add_argument('-s',
  263. '--substitution',
  264. action='append',
  265. default=[],
  266. help='Template substitution(s), in the form key=value.',
  267. dest='substitutions')
  268. argp.add_argument('-p',
  269. '--prefix',
  270. default='',
  271. type=str,
  272. help='Test name prefix.')
  273. argp.add_argument('-u',
  274. '--uniquifier_element',
  275. action='append',
  276. default=[],
  277. help='String element(s) to make the test name unique.',
  278. dest='uniquifier_elements')
  279. argp.add_argument(
  280. '-d',
  281. action='store_true',
  282. help='Use creation date and time as an additional uniquifier element.')
  283. argp.add_argument('-a',
  284. '--annotation',
  285. action='append',
  286. default=[],
  287. help='metadata.annotation(s), in the form key=value.',
  288. dest='annotations')
  289. argp.add_argument('-r',
  290. '--regex',
  291. default='.*',
  292. type=str,
  293. help='Regex to select scenarios to run.')
  294. argp.add_argument(
  295. '--category',
  296. choices=['all', 'inproc', 'scalable', 'smoketest', 'sweep'],
  297. default='all',
  298. help='Select a category of tests to run.')
  299. argp.add_argument(
  300. '--allow_client_language',
  301. action='append',
  302. choices=language_choices,
  303. default=[],
  304. help='Allow cross-language scenarios with this client language.',
  305. dest='allow_client_languages')
  306. argp.add_argument(
  307. '--allow_server_language',
  308. action='append',
  309. choices=language_choices,
  310. default=[],
  311. help='Allow cross-language scenarios with this server language.',
  312. dest='allow_server_languages')
  313. argp.add_argument('--instances_per_client',
  314. default=1,
  315. type=int,
  316. help="Number of instances to generate for each client.")
  317. argp.add_argument('--runs_per_test',
  318. default=1,
  319. type=int,
  320. help='Number of copies to generate for each test.')
  321. argp.add_argument('-o',
  322. '--output',
  323. type=str,
  324. help='Output file name. Output to stdout if not set.')
  325. args = argp.parse_args()
  326. if args.instances_per_client < 1:
  327. argp.error('instances_per_client must be greater than zero.')
  328. if args.runs_per_test < 1:
  329. argp.error('runs_per_test must be greater than zero.')
  330. # Config generation ignores environment variables that are passed by the
  331. # controller at runtime.
  332. substitutions = {
  333. 'DRIVER_PORT': '${DRIVER_PORT}',
  334. 'KILL_AFTER': '${KILL_AFTER}',
  335. 'POD_TIMEOUT': '${POD_TIMEOUT}',
  336. }
  337. # The user can override the ignored variables above by passing them in as
  338. # substitution keys.
  339. substitutions.update(parse_key_value_args(args.substitutions))
  340. uniquifier_elements = args.uniquifier_elements
  341. if args.d:
  342. uniquifier_elements.append(now_string())
  343. annotations = parse_key_value_args(args.annotations)
  344. with open(args.template) as f:
  345. base_config = yaml.safe_load(
  346. string.Template(f.read()).substitute(substitutions))
  347. clear_empty_fields(base_config)
  348. spec = base_config['spec']
  349. base_config_clients = spec['clients']
  350. del spec['clients']
  351. base_config_servers = spec['servers']
  352. del spec['servers']
  353. client_languages = [''] + args.allow_client_languages
  354. server_languages = [''] + args.allow_server_languages
  355. config_generators = []
  356. for l, cl, sl in itertools.product(args.languages, client_languages,
  357. server_languages):
  358. language_config = scenario_config_exporter.LanguageConfig(
  359. category=args.category,
  360. language=l,
  361. client_language=cl,
  362. server_language=sl)
  363. config_generators.append(
  364. gen_loadtest_configs(base_config,
  365. base_config_clients,
  366. base_config_servers,
  367. args.regex,
  368. language_config,
  369. loadtest_name_prefix=args.prefix,
  370. uniquifier_elements=uniquifier_elements,
  371. annotations=annotations,
  372. instances_per_client=args.instances_per_client,
  373. runs_per_test=args.runs_per_test))
  374. configs = (config for config in itertools.chain(*config_generators))
  375. with open(args.output, 'w') if args.output else sys.stdout as f:
  376. yaml.dump_all(configs,
  377. stream=f,
  378. Dumper=config_dumper(
  379. CONFIGURATION_FILE_HEADER_COMMENT.strip()),
  380. default_flow_style=False)
  381. if __name__ == '__main__':
  382. main()