__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import os
  2. import random
  3. import re
  4. import subprocess
  5. import six
  6. import yaml
  7. import logging
  8. import argparse
  9. import yatest.common
  10. from six.moves import input
  11. import build.plugins.lib.test_const as const
  12. import library.python.fs as fs
  13. import library.python.testing.recipe
  14. logger = logging.getLogger(__name__)
  15. class DockerComposeRecipeException(Exception):
  16. def __init__(self, msg):
  17. super(DockerComposeRecipeException, self).__init__("[[bad]]{}[[rst]]".format(msg))
  18. def start(argv):
  19. args = _parse_args(argv)
  20. yml_file, cwd = get_compose_file_and_cwd(argv)
  21. _verify_compose_file(yml_file)
  22. env = _setup_env()
  23. docker_compose = get_docker_compose()
  24. recipe_config = _get_recipe_config(args)
  25. deprecated_context = _get_docker_deprecated_context(args)
  26. docker_context = recipe_config.get('context', deprecated_context)
  27. if docker_context:
  28. context_map = _create_context(docker_context, os.path.dirname(yml_file), yatest.common.work_path("docker_context_root"))
  29. env.update(context_map)
  30. test_host_name = _get_test_host(args, recipe_config)
  31. if test_host_name:
  32. yml_file = _setup_test_host(test_host_name, yml_file, env)
  33. library.python.testing.recipe.set_env("DONT_CREATE_TEST_PROCESS_GROUP", "1") # XXX find out why docker-compose hangs in other case
  34. library.python.testing.recipe.set_env(
  35. "TEST_COMMAND_WRAPPER", " ".join([docker_compose, "-f", yml_file, "exec", "-T", test_host_name])
  36. )
  37. library.python.testing.recipe.set_env("DOCKER_COMPOSE_FILE", yml_file)
  38. networks = _get_networks(recipe_config)
  39. if networks:
  40. subnets = set()
  41. for net_name, net_config in six.iteritems(networks):
  42. while True:
  43. subnet = "fc00:420:%04x::/32" % random.randrange(16**4)
  44. if subnet not in subnets:
  45. break
  46. subnets.add(subnet)
  47. net_args = ["docker", "network", "create", "--subnet", subnet]
  48. if net_config and net_config.get("ipv6", False):
  49. net_args.append("--ipv6")
  50. net_args.append(net_name)
  51. yatest.common.execute(net_args, cwd=cwd)
  52. yatest.common.execute([docker_compose, "-f", yml_file, "--log-level", "DEBUG", "--no-ansi", "up", "-d", "--build",
  53. "--force-recreate"],
  54. cwd=cwd, env=env)
  55. def stop(argv):
  56. if yatest.common.get_param("docker-pause"):
  57. library.python.testing.recipe.tty()
  58. try:
  59. input("\ndocker_compose will stop, press <Enter> to continue")
  60. except KeyboardInterrupt:
  61. pass
  62. docker_compose = get_docker_compose()
  63. yaml, cwd = get_compose_file_and_cwd(argv)
  64. args = _parse_args(argv)
  65. recipe_config = _get_recipe_config(args)
  66. failed_containers = []
  67. containers = _get_containers(yaml)
  68. try:
  69. containers_ids_res = yatest.common.execute([docker_compose, "-f", yaml, "--log-level", "DEBUG", "--no-ansi", "ps", "-q"], cwd=cwd, stdout=subprocess.PIPE, text=True)
  70. if containers_ids_res.exit_code != 0:
  71. raise DockerComposeRecipeException("'docker-compose ps' returned {}'".format(containers_ids_res.exit_code))
  72. containers_ids = str.splitlines(containers_ids_res.std_out)
  73. if len(containers_ids) == 0:
  74. raise DockerComposeRecipeException("'docker-compose ps' output is empty '{}'".format(containers_ids_res.std_out))
  75. for container_id in containers_ids:
  76. container_id_status_res = yatest.common.execute(["docker", "ps", "-a", "--filter", "id=" + container_id, "--format", "{{.Status}}\t{{.Names}}"], cwd=cwd)
  77. if container_id_status_res.exit_code != 0:
  78. raise DockerComposeRecipeException("'docker ps' returned {}'".format(container_id_status_res.exit_code))
  79. status_line, container_name = six.ensure_str(container_id_status_res.std_out).split('\t')
  80. if "Up" in status_line or "Exited (0)" in status_line:
  81. continue
  82. failed_containers.append(container_name)
  83. yatest.common.execute([docker_compose, "-f", yaml, "--log-level", "DEBUG", "--no-ansi", "stop"], cwd=cwd)
  84. _dump_container_logs(containers, _get_requested_paths(yaml, recipe_config))
  85. finally:
  86. if not yatest.common.context.test_debug:
  87. yatest.common.execute([get_docker_compose(), "-f", yaml, "--log-level", "DEBUG", "--no-ansi", "down", "--rmi", "local"], cwd=cwd)
  88. networks = _get_networks(recipe_config)
  89. if networks:
  90. for net_name in six.iterkeys(networks):
  91. yatest.common.execute(["docker", "network", "rm", net_name], cwd=cwd)
  92. if len(failed_containers) > 0:
  93. raise DockerComposeRecipeException("Has failed containers: {}".format(", ".join(failed_containers)))
  94. def get_compose_file_and_cwd(args):
  95. if "DOCKER_COMPOSE_FILE" in os.environ:
  96. yaml_file = os.environ["DOCKER_COMPOSE_FILE"]
  97. else:
  98. args = _parse_args(args)
  99. if args.compose_file and args.compose_file != "$DOCKER_COMPOSE_FILE":
  100. yaml_file = yatest.common.source_path(args.compose_file)
  101. else:
  102. yaml_file = yatest.common.test_source_path("docker-compose.yml")
  103. return yaml_file, os.path.dirname(yaml_file)
  104. def get_docker_compose():
  105. docker_compose = yatest.common.build_path("library/recipes/docker_compose/bin/docker-compose")
  106. if not os.path.exists(docker_compose):
  107. raise DockerComposeRecipeException("cannot find docker_compose by build_path '{}'".format(docker_compose))
  108. os.chmod(docker_compose, 0o755)
  109. return docker_compose
  110. def _parse_args(argv):
  111. parser = argparse.ArgumentParser()
  112. parser.add_argument("--recipe-config-file", help="Path recipe config yml file (Arcadia related)")
  113. parser.add_argument("--compose-file", help="Path to docker-compose.yml file (Arcadia related)")
  114. parser.add_argument("--context-file", help="Path to docker-context.yml file (Arcadia related)")
  115. parser.add_argument("--test-host", help="Name of service in docker-compose file that will host test execution")
  116. return parser.parse_args(argv)
  117. def _get_recipe_config(args):
  118. if args.recipe_config_file and args.recipe_config_file != "$RECIPE_CONFIG_FILE":
  119. config_path = yatest.common.source_path(args.recipe_config_file)
  120. if not os.path.exists(config_path):
  121. raise DockerComposeRecipeException("Cannot find specified recipe config file '{}'".format(args.recipe_config_file))
  122. with open(config_path) as f:
  123. return yaml.load(f, Loader=yaml.FullLoader)
  124. return {}
  125. def _get_docker_deprecated_context(args):
  126. # XXX: to be removed when all recipes use new config file
  127. if args.context_file and args.context_file != "$DOCKER_CONTEXT_FILE":
  128. context_file = yatest.common.source_path(args.context_file)
  129. if not os.path.exists(context_file):
  130. raise DockerComposeRecipeException("Cannot find context file by {}".format(context_file))
  131. with open(context_file) as f:
  132. return yaml.load(f, Loader=yaml.FullLoader)
  133. return None
  134. def _setup_env():
  135. env = os.environ.copy()
  136. env["CURRENT_USER"] = "{}:{}".format(os.getuid(), os.getgid())
  137. # Setup extra env.vars. to be able to pass coverage dir to the docker
  138. for name in const.COVERAGE_ENV_VARS:
  139. if name in env:
  140. env["{}_DIRNAME".format(name.rsplit('_', 1)[0])] = os.path.dirname(env[name])
  141. return env
  142. def _create_context(context, init_dir, context_root):
  143. def copy_files(src, dst):
  144. if os.path.isfile(src):
  145. fs.copy_file(src, dst)
  146. else:
  147. if not os.path.exists(dst):
  148. os.makedirs(dst)
  149. for name in os.listdir(src):
  150. copy_files(os.path.join(src, name), os.path.join(dst, name))
  151. context_map = {}
  152. fs.ensure_dir(context_root)
  153. for context_name in context:
  154. _verify_context_name(context_name)
  155. context_dir = os.path.join(context_root, context_name)
  156. copy_files(init_dir, context_dir)
  157. for item in context[context_name]:
  158. if len(item.keys()) != 1 or len(item.values()) != 1:
  159. raise DockerComposeRecipeException("Context item should be in form of <source>:<destination> item")
  160. source_path, target_path = next(iter(six.iteritems(item)))
  161. if source_path.startswith("build://"):
  162. source_path = yatest.common.build_path(source_path[len("build://"):])
  163. elif source_path.startswith("arcadia://"):
  164. source_path = yatest.common.source_path(source_path[len("arcadia://"):])
  165. else:
  166. raise DockerComposeRecipeException("Source path should start with 'build://' or 'arcadia://'")
  167. target_path = os.path.join(context_dir, target_path.lstrip("/"))
  168. fs.ensure_dir(os.path.dirname(target_path))
  169. copy_files(source_path, target_path)
  170. context_map[context_name] = context_dir
  171. return context_map
  172. def _verify_context_name(name):
  173. assert re.match("^[a-zA-Z0-9]+$", name), "Context name '{}' has incorrect symbols".format(name)
  174. def _verify_compose_file(file_path):
  175. with open(file_path) as f:
  176. data = yaml.safe_load(f)
  177. known_images = set()
  178. for service, settings in six.iteritems(data["services"]):
  179. if "image" in settings:
  180. image = settings["image"]
  181. if "build" not in settings and "@sha256" not in image and image not in known_images:
  182. message = "Using image without specified sha256 (e.g. redis:alpine@sha256:66ccc75f079ab9059c900e9545bbd271bff78a66f94b45827e6901f57fb973f1) and build section is not supported"
  183. logger.error(message)
  184. raise DockerComposeRecipeException(message)
  185. known_images.add(image)
  186. def _get_networks(config):
  187. return config.get("networks")
  188. def _get_test_host(args, config):
  189. def get_from_args():
  190. if args.test_host and args.test_host != "$DOCKER_TEST_HOST":
  191. return args.test_host
  192. return None
  193. return config.get('test-host', get_from_args())
  194. def _setup_test_host(test_host_name, yml_path, env):
  195. with open(yml_path) as f:
  196. data = yaml.load(f, Loader=yaml.FullLoader)
  197. for service, settings in six.iteritems(data["services"]):
  198. if service == test_host_name:
  199. overwritten_yml_path = yatest.common.work_path("docker_compose_for_test.yml")
  200. if "env" not in settings:
  201. settings["environment"] = []
  202. for env_key, env_value in six.iteritems(env):
  203. settings["environment"].append("{}={}".format(env_key, env_value))
  204. if "volumes" not in settings:
  205. settings["volumes"] = []
  206. if "command" in settings:
  207. raise DockerComposeRecipeException("Test hosting service '{}' has `command` section which is not supported by testing framework".format(test_host_name))
  208. settings["command"] = "sleep 3600"
  209. settings["tty"] = False
  210. if "user" in settings:
  211. raise DockerComposeRecipeException("Test hosting service '{}' has `user` section which is not supported by testing framework".format(test_host_name))
  212. settings["user"] = "$CURRENT_USER"
  213. if "build" in settings:
  214. conext = settings["build"].get("context")
  215. if conext == ".":
  216. settings["build"]["context"] = os.path.dirname(yml_path)
  217. bind_paths = [
  218. yatest.common.build_path(),
  219. os.environ.get("ORIGINAL_SOURCE_ROOT", yatest.common.source_path()),
  220. ]
  221. if yatest.common.runtime.context.test_tool_path:
  222. bind_paths.append(yatest.common.runtime.context.test_tool_path)
  223. for k in [
  224. "PORT_SYNC_PATH",
  225. "OS_SDK_ROOT_RESOURCE_GLOBAL",
  226. "LLD_ROOT_RESOURCE_GLOBAL",
  227. "ASAN_SYMBOLIZER_PATH",
  228. "LSAN_SYMBOLIZER_PATH",
  229. "MSAN_SYMBOLIZER_PATH",
  230. "UBSAN_SYMBOLIZER_PATH",
  231. "TMPDIR",
  232. ]:
  233. if k in os.environ:
  234. p = os.environ[k]
  235. if p not in bind_paths and os.path.exists(p):
  236. bind_paths.append(p)
  237. for bind_path in bind_paths:
  238. settings["volumes"].append({
  239. "type": "bind",
  240. "source": bind_path,
  241. "target": bind_path,
  242. })
  243. real_bind_path = os.path.realpath(bind_path)
  244. if real_bind_path != bind_path:
  245. settings["volumes"].append({
  246. "type": "bind",
  247. "source": real_bind_path,
  248. "target": real_bind_path,
  249. })
  250. with open(overwritten_yml_path, "w") as f:
  251. yaml.dump(data, f)
  252. return overwritten_yml_path
  253. raise DockerComposeRecipeException("Service with name '{}' was not found to be setup as a host for running test".format(test_host_name))
  254. def _dump_container_logs(containers, requested_paths):
  255. # add links to container logs
  256. container_logs = yatest.common.output_path("containers")
  257. if not os.path.exists(container_logs):
  258. os.makedirs(container_logs)
  259. for container_id, container_name in six.iteritems(containers):
  260. try:
  261. output_path = os.path.join(container_logs, container_name)
  262. os.makedirs(output_path)
  263. for output_type in ['std_out', 'std_err']:
  264. output_log_path = os.path.join(output_path, "container_{}.log".format(output_type))
  265. res = yatest.common.execute(["docker", "logs", container_id])
  266. with open(output_log_path, "w") as f:
  267. f.write(six.ensure_str(getattr(res, output_type)))
  268. for path in requested_paths.get(container_id, []):
  269. try:
  270. yatest.common.execute(["docker", "cp", "-L", "{}:{}".format(container_id, path), output_path])
  271. except yatest.common.ExecutionError:
  272. logging.exception("Error while copying %s from %s", path, container_name)
  273. except Exception:
  274. logger.exception("Error collecting container's log with name {} and id {}".format(container_name, container_id))
  275. def _get_requested_paths(yaml_path, config):
  276. requested_logs = {}
  277. if config:
  278. for service_name, logs in six.iteritems(config.get("save", {})):
  279. try:
  280. res = yatest.common.execute([get_docker_compose(), "-f", yaml_path, "ps", "-q", service_name])
  281. requested_logs[six.ensure_str(res.std_out).strip()] = logs
  282. except yatest.common.ExecutionError:
  283. logging.exception("Error while trying to find docker compose service by name: %s", service_name)
  284. return requested_logs
  285. def _get_containers(yaml_path):
  286. res = yatest.common.execute([get_docker_compose(), "-f", yaml_path, "ps", "-q"])
  287. return {container_id: _get_container_name(container_id) for container_id in filter(None, six.ensure_str(res.std_out).split("\n"))}
  288. def _get_container_name(container_id):
  289. res = yatest.common.execute(["docker", "inspect", "--format={{.Name}}", container_id])
  290. container_name = six.ensure_str(res.std_out).strip("/").strip()
  291. return container_name