docker_helper.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import os
  2. import socket
  3. import fnmatch
  4. import subprocess
  5. import multiprocessing
  6. import json
  7. import docker
  8. import time
  9. import traceback
  10. from threading import Thread
  11. from toolset.utils.output_helper import log, log_error, FNULL
  12. from toolset.utils.metadata_helper import gather_tests
  13. from toolset.utils.ordered_set import OrderedSet
  14. from toolset.utils.database_helper import test_database
  15. def clean(config):
  16. '''
  17. Cleans all the docker images from the system
  18. '''
  19. # Clean the app server images
  20. subprocess.check_call(["docker", "image", "prune", "-f"])
  21. docker_ids = subprocess.check_output(["docker", "images",
  22. "-q"]).splitlines()
  23. for docker_id in docker_ids:
  24. subprocess.check_call(["docker", "image", "rmi", "-f", docker_id])
  25. subprocess.check_call(["docker", "system", "prune", "-a", "-f"])
  26. # Clean the database server images
  27. command = list(config.database_ssh_command)
  28. command.extend(["docker", "image", "prune", "-f"])
  29. subprocess.check_call(command)
  30. command = list(config.database_ssh_command)
  31. command.extend(["docker", "images", "-q"])
  32. docker_ids = subprocess.check_output(command).splitlines()
  33. for docker_id in docker_ids:
  34. command = list(config.database_ssh_command)
  35. command.extend(["docker", "image", "rmi", "-f", docker_id])
  36. subprocess.check_call(command)
  37. command = list(config.database_ssh_command)
  38. command.extend(["docker", "system", "prune", "-a", "-f"])
  39. subprocess.check_call(command)
  40. def build(benchmarker_config, test_names, build_log_dir=os.devnull):
  41. '''
  42. Builds the dependency chain as well as the test implementation docker images
  43. for the given tests.
  44. '''
  45. tests = gather_tests(test_names)
  46. for test in tests:
  47. log_prefix = "%s: " % test.name
  48. docker_buildargs = {
  49. 'CPU_COUNT': str(multiprocessing.cpu_count()),
  50. 'MAX_CONCURRENCY': str(max(benchmarker_config.concurrency_levels)),
  51. 'TFB_DATABASE': str(benchmarker_config.database_host)
  52. }
  53. test_docker_files = ["%s.dockerfile" % test.name]
  54. if test.docker_files is not None:
  55. if type(test.docker_files) is list:
  56. test_docker_files.extend(test.docker_files)
  57. else:
  58. raise Exception(
  59. "docker_files in benchmark_config.json must be an array")
  60. for test_docker_file in test_docker_files:
  61. deps = OrderedSet(
  62. list(
  63. reversed(
  64. __gather_dependencies(
  65. os.path.join(test.directory, test_docker_file)))))
  66. docker_dir = os.path.join(
  67. os.getenv('FWROOT'), "toolset", "setup", "docker")
  68. for dependency in deps:
  69. build_log_file = build_log_dir
  70. if build_log_dir is not os.devnull:
  71. build_log_file = os.path.join(
  72. build_log_dir, "%s.log" % dependency.lower())
  73. with open(build_log_file, 'w') as build_log:
  74. docker_file = os.path.join(test.directory,
  75. dependency + ".dockerfile")
  76. if not docker_file or not os.path.exists(docker_file):
  77. docker_file = find(docker_dir,
  78. dependency + ".dockerfile")
  79. if not docker_file:
  80. log("Docker build failed; %s could not be found; terminating"
  81. % (dependency + ".dockerfile"), log_prefix,
  82. build_log)
  83. return 1
  84. # Build the dependency image
  85. try:
  86. for line in docker.APIClient(
  87. base_url='unix://var/run/docker.sock').build(
  88. path=os.path.dirname(docker_file),
  89. dockerfile="%s.dockerfile" % dependency,
  90. tag="tfb/%s" % dependency,
  91. buildargs=docker_buildargs,
  92. forcerm=True):
  93. if line.startswith('{"stream":'):
  94. line = json.loads(line)
  95. line = line[line.keys()[0]].encode('utf-8')
  96. log(line, log_prefix, build_log)
  97. except Exception:
  98. tb = traceback.format_exc()
  99. log("Docker dependency build failed; terminating",
  100. log_prefix, build_log)
  101. log_error(tb, log_prefix, build_log)
  102. return 1
  103. # Build the test images
  104. for test_docker_file in test_docker_files:
  105. build_log_file = build_log_dir
  106. if build_log_dir is not os.devnull:
  107. build_log_file = os.path.join(
  108. build_log_dir, "%s.log" % test_docker_file.replace(
  109. ".dockerfile", "").lower())
  110. with open(build_log_file, 'w') as build_log:
  111. try:
  112. for line in docker.APIClient(
  113. base_url='unix://var/run/docker.sock').build(
  114. path=test.directory,
  115. dockerfile=test_docker_file,
  116. tag="tfb/test/%s" % test_docker_file.replace(
  117. ".dockerfile", ""),
  118. buildargs=docker_buildargs,
  119. forcerm=True):
  120. if line.startswith('{"stream":'):
  121. line = json.loads(line)
  122. line = line[line.keys()[0]].encode('utf-8')
  123. log(line, log_prefix, build_log)
  124. except Exception:
  125. tb = traceback.format_exc()
  126. log("Docker build failed; terminating", log_prefix,
  127. build_log)
  128. log_error(tb, log_prefix, build_log)
  129. return 1
  130. return 0
  131. def run(benchmarker_config, docker_files, run_log_dir):
  132. '''
  133. Run the given Docker container(s)
  134. '''
  135. client = docker.from_env()
  136. for docker_file in docker_files:
  137. log_prefix = "%s: " % docker_file.replace(".dockerfile", "")
  138. try:
  139. def watch_container(container, docker_file):
  140. with open(
  141. os.path.join(
  142. run_log_dir, "%s.log" % docker_file.replace(
  143. ".dockerfile", "").lower()), 'w') as run_log:
  144. for line in container.logs(stream=True):
  145. log(line, log_prefix, run_log)
  146. extra_hosts = {
  147. socket.gethostname(): str(benchmarker_config.server_host),
  148. 'TFB-SERVER': str(benchmarker_config.server_host),
  149. 'TFB-DATABASE': str(benchmarker_config.database_host),
  150. 'TFB-CLIENT': str(benchmarker_config.client_host)
  151. }
  152. container = client.containers.run(
  153. "tfb/test/%s" % docker_file.replace(".dockerfile", ""),
  154. network_mode="host",
  155. privileged=True,
  156. stderr=True,
  157. detach=True,
  158. init=True,
  159. extra_hosts=extra_hosts)
  160. watch_thread = Thread(
  161. target=watch_container, args=(
  162. container,
  163. docker_file,
  164. ))
  165. watch_thread.daemon = True
  166. watch_thread.start()
  167. except Exception:
  168. with open(
  169. os.path.join(run_log_dir, "%s.log" % docker_file.replace(
  170. ".dockerfile", "").lower()), 'w') as run_log:
  171. tb = traceback.format_exc()
  172. log("Running docker cointainer: %s failed" % docker_file,
  173. log_prefix, run_log)
  174. log_error(tb, log_prefix, run_log)
  175. return 1
  176. return 0
  177. def successfully_running_containers(docker_files, out):
  178. '''
  179. Returns whether all the expected containers for the given docker_files are
  180. running.
  181. '''
  182. client = docker.from_env()
  183. expected_running_container_images = []
  184. for docker_file in docker_files:
  185. # 'gemini.dockerfile' -> 'gemini'
  186. image_tag = docker_file.split('.')[0]
  187. expected_running_container_images.append(image_tag)
  188. running_container_images = []
  189. for container in client.containers.list():
  190. # 'tfb/test/gemini:latest' -> 'gemini'
  191. image_tag = container.image.tags[0].split(':')[0][9:]
  192. running_container_images.append(image_tag)
  193. for image_name in expected_running_container_images:
  194. if image_name not in running_container_images:
  195. log_prefix = "%s: " % image_name
  196. log("ERROR: Expected tfb/test/%s to be running container" %
  197. image_name, log_prefix, out)
  198. return False
  199. return True
  200. def stop(config=None, database_container_id=None, test=None):
  201. '''
  202. Attempts to stop the running test container.
  203. '''
  204. client = docker.from_env()
  205. # Stop all the containers
  206. for container in client.containers.list():
  207. if container.status == "running" and container.id != database_container_id:
  208. container.stop()
  209. # Remove only the tfb/test image for this test
  210. try:
  211. client.images.remove("tfb/test/%s" % test.name, force=True)
  212. except:
  213. # This can be okay if the user hit ctrl+c before the image built/ran
  214. pass
  215. # Stop the database container
  216. if database_container_id:
  217. command = list(config.database_ssh_command)
  218. command.extend(['docker', 'stop', database_container_id])
  219. subprocess.check_call(command, stdout=FNULL, stderr=subprocess.STDOUT)
  220. client.images.prune()
  221. client.containers.prune()
  222. client.networks.prune()
  223. client.volumes.prune()
  224. def find(path, pattern):
  225. '''
  226. Finds and returns all the the files matching the given pattern recursively in
  227. the given path.
  228. '''
  229. for root, dirs, files in os.walk(path):
  230. for name in files:
  231. if fnmatch.fnmatch(name, pattern):
  232. return os.path.join(root, name)
  233. def start_database(config, database):
  234. '''
  235. Sets up a container for the given database and port, and starts said docker
  236. container.
  237. '''
  238. def __is_hex(s):
  239. try:
  240. int(s, 16)
  241. except ValueError:
  242. return False
  243. return len(s) % 2 == 0
  244. command = list(config.database_ssh_command)
  245. command.extend(['docker', 'images', '-q', database])
  246. out = subprocess.check_output(command)
  247. dbid = ''
  248. if len(out.splitlines()) > 0:
  249. dbid = out.splitlines()[len(out.splitlines()) - 1]
  250. # If the database image exists, then dbid will look like
  251. # fe12ca519b47, and we do not want to rebuild if it exists
  252. if len(dbid) != 12 and not __is_hex(dbid):
  253. def __scp_command(files):
  254. scpstr = ["scp", "-i", config.database_identity_file]
  255. for file in files:
  256. scpstr.append(file)
  257. scpstr.append("%s@%s:~/%s/" % (config.database_user,
  258. config.database_host, database))
  259. return scpstr
  260. command = list(config.database_ssh_command)
  261. command.extend(['mkdir', '-p', database])
  262. subprocess.check_call(command)
  263. dbpath = os.path.join(config.fwroot, "toolset", "setup", "docker",
  264. "databases", database)
  265. dbfiles = ""
  266. for dbfile in os.listdir(dbpath):
  267. dbfiles += "%s " % os.path.join(dbpath, dbfile)
  268. subprocess.check_call(__scp_command(dbfiles.split()))
  269. command = list(config.database_ssh_command)
  270. command.extend([
  271. 'docker', 'build', '-f',
  272. '~/%s/%s.dockerfile' % (database, database), '-t', database,
  273. '~/%s' % database
  274. ])
  275. subprocess.check_call(command)
  276. command = list(config.database_ssh_command)
  277. command.extend(
  278. ['docker', 'run', '-d', '--rm', '--init', '--network=host', database])
  279. docker_id = subprocess.check_output(command).strip()
  280. # Sleep until the database accepts connections
  281. slept = 0
  282. max_sleep = 60
  283. while not test_database(config, database) and slept < max_sleep:
  284. time.sleep(1)
  285. slept += 1
  286. return docker_id
  287. def __gather_dependencies(docker_file):
  288. '''
  289. Gathers all the known docker dependencies for the given docker image.
  290. '''
  291. deps = []
  292. docker_dir = os.path.join(
  293. os.getenv('FWROOT'), "toolset", "setup", "docker")
  294. if os.path.exists(docker_file):
  295. with open(docker_file) as fp:
  296. for line in fp.readlines():
  297. tokens = line.strip().split(' ')
  298. if tokens[0] == "FROM":
  299. # This is magic that our base image points to
  300. if tokens[1] != "ubuntu:16.04":
  301. dep_ref = tokens[1].strip().split(':')[0].strip()
  302. if '/' not in dep_ref:
  303. raise AttributeError(
  304. "Could not find docker FROM dependency: %s" %
  305. dep_ref)
  306. depToken = dep_ref.split('/')[1]
  307. deps.append(depToken)
  308. dep_docker_file = os.path.join(
  309. os.path.dirname(docker_file),
  310. depToken + ".dockerfile")
  311. if not os.path.exists(dep_docker_file):
  312. dep_docker_file = find(docker_dir,
  313. depToken + ".dockerfile")
  314. deps.extend(__gather_dependencies(dep_docker_file))
  315. return deps