service_test.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import os
  4. import re
  5. import shutil
  6. import tempfile
  7. from distutils.spawn import find_executable
  8. from os import path
  9. import pytest
  10. from docker.errors import APIError
  11. from docker.errors import ImageNotFound
  12. from six import StringIO
  13. from six import text_type
  14. from .. import mock
  15. from ..helpers import BUSYBOX_IMAGE_WITH_TAG
  16. from .testcases import docker_client
  17. from .testcases import DockerClientTestCase
  18. from .testcases import get_links
  19. from .testcases import pull_busybox
  20. from .testcases import SWARM_SKIP_CONTAINERS_ALL
  21. from .testcases import SWARM_SKIP_CPU_SHARES
  22. from compose import __version__
  23. from compose.config.types import MountSpec
  24. from compose.config.types import SecurityOpt
  25. from compose.config.types import VolumeFromSpec
  26. from compose.config.types import VolumeSpec
  27. from compose.const import IS_WINDOWS_PLATFORM
  28. from compose.const import LABEL_CONFIG_HASH
  29. from compose.const import LABEL_CONTAINER_NUMBER
  30. from compose.const import LABEL_ONE_OFF
  31. from compose.const import LABEL_PROJECT
  32. from compose.const import LABEL_SERVICE
  33. from compose.const import LABEL_VERSION
  34. from compose.container import Container
  35. from compose.errors import OperationFailedError
  36. from compose.parallel import ParallelStreamWriter
  37. from compose.project import OneOffFilter
  38. from compose.project import Project
  39. from compose.service import BuildAction
  40. from compose.service import ConvergencePlan
  41. from compose.service import ConvergenceStrategy
  42. from compose.service import NetworkMode
  43. from compose.service import PidMode
  44. from compose.service import Service
  45. from compose.utils import parse_nanoseconds_int
  46. from tests.helpers import create_custom_host_file
  47. from tests.integration.testcases import is_cluster
  48. from tests.integration.testcases import no_cluster
  49. from tests.integration.testcases import v2_1_only
  50. from tests.integration.testcases import v2_2_only
  51. from tests.integration.testcases import v2_3_only
  52. from tests.integration.testcases import v2_only
  53. from tests.integration.testcases import v3_only
  54. def create_and_start_container(service, **override_options):
  55. container = service.create_container(**override_options)
  56. return service.start_container(container)
  57. class ServiceTest(DockerClientTestCase):
  58. def test_containers(self):
  59. foo = self.create_service('foo')
  60. bar = self.create_service('bar')
  61. create_and_start_container(foo)
  62. assert len(foo.containers()) == 1
  63. assert foo.containers()[0].name.startswith('composetest_foo_')
  64. assert len(bar.containers()) == 0
  65. create_and_start_container(bar)
  66. create_and_start_container(bar)
  67. assert len(foo.containers()) == 1
  68. assert len(bar.containers()) == 2
  69. names = [c.name for c in bar.containers()]
  70. assert len(names) == 2
  71. assert all(name.startswith('composetest_bar_') for name in names)
  72. def test_containers_one_off(self):
  73. db = self.create_service('db')
  74. container = db.create_container(one_off=True)
  75. assert db.containers(stopped=True) == []
  76. assert db.containers(one_off=OneOffFilter.only, stopped=True) == [container]
  77. def test_project_is_added_to_container_name(self):
  78. service = self.create_service('web')
  79. create_and_start_container(service)
  80. assert service.containers()[0].name.startswith('composetest_web_')
  81. def test_create_container_with_one_off(self):
  82. db = self.create_service('db')
  83. container = db.create_container(one_off=True)
  84. assert container.name.startswith('composetest_db_run_')
  85. def test_create_container_with_one_off_when_existing_container_is_running(self):
  86. db = self.create_service('db')
  87. db.start()
  88. container = db.create_container(one_off=True)
  89. assert container.name.startswith('composetest_db_run_')
  90. def test_create_container_with_unspecified_volume(self):
  91. service = self.create_service('db', volumes=[VolumeSpec.parse('/var/db')])
  92. container = service.create_container()
  93. service.start_container(container)
  94. assert container.get_mount('/var/db')
  95. def test_create_container_with_volume_driver(self):
  96. service = self.create_service('db', volume_driver='foodriver')
  97. container = service.create_container()
  98. service.start_container(container)
  99. assert 'foodriver' == container.get('HostConfig.VolumeDriver')
  100. @pytest.mark.skipif(SWARM_SKIP_CPU_SHARES, reason='Swarm --cpu-shares bug')
  101. def test_create_container_with_cpu_shares(self):
  102. service = self.create_service('db', cpu_shares=73)
  103. container = service.create_container()
  104. service.start_container(container)
  105. assert container.get('HostConfig.CpuShares') == 73
  106. def test_create_container_with_cpu_quota(self):
  107. service = self.create_service('db', cpu_quota=40000, cpu_period=150000)
  108. container = service.create_container()
  109. container.start()
  110. assert container.get('HostConfig.CpuQuota') == 40000
  111. assert container.get('HostConfig.CpuPeriod') == 150000
  112. @pytest.mark.xfail(raises=OperationFailedError, reason='not supported by kernel')
  113. def test_create_container_with_cpu_rt(self):
  114. service = self.create_service('db', cpu_rt_runtime=40000, cpu_rt_period=150000)
  115. container = service.create_container()
  116. container.start()
  117. assert container.get('HostConfig.CpuRealtimeRuntime') == 40000
  118. assert container.get('HostConfig.CpuRealtimePeriod') == 150000
  119. @v2_2_only()
  120. def test_create_container_with_cpu_count(self):
  121. self.require_api_version('1.25')
  122. service = self.create_service('db', cpu_count=2)
  123. container = service.create_container()
  124. service.start_container(container)
  125. assert container.get('HostConfig.CpuCount') == 2
  126. @v2_2_only()
  127. @pytest.mark.skipif(not IS_WINDOWS_PLATFORM, reason='cpu_percent is not supported for Linux')
  128. def test_create_container_with_cpu_percent(self):
  129. self.require_api_version('1.25')
  130. service = self.create_service('db', cpu_percent=12)
  131. container = service.create_container()
  132. service.start_container(container)
  133. assert container.get('HostConfig.CpuPercent') == 12
  134. @v2_2_only()
  135. def test_create_container_with_cpus(self):
  136. self.require_api_version('1.25')
  137. service = self.create_service('db', cpus=1)
  138. container = service.create_container()
  139. service.start_container(container)
  140. assert container.get('HostConfig.NanoCpus') == 1000000000
  141. def test_create_container_with_shm_size(self):
  142. self.require_api_version('1.22')
  143. service = self.create_service('db', shm_size=67108864)
  144. container = service.create_container()
  145. service.start_container(container)
  146. assert container.get('HostConfig.ShmSize') == 67108864
  147. def test_create_container_with_init_bool(self):
  148. self.require_api_version('1.25')
  149. service = self.create_service('db', init=True)
  150. container = service.create_container()
  151. service.start_container(container)
  152. assert container.get('HostConfig.Init') is True
  153. @pytest.mark.xfail(True, reason='Option has been removed in Engine 17.06.0')
  154. def test_create_container_with_init_path(self):
  155. self.require_api_version('1.25')
  156. docker_init_path = find_executable('docker-init')
  157. service = self.create_service('db', init=docker_init_path)
  158. container = service.create_container()
  159. service.start_container(container)
  160. assert container.get('HostConfig.InitPath') == docker_init_path
  161. @pytest.mark.xfail(True, reason='Some kernels/configs do not support pids_limit')
  162. def test_create_container_with_pids_limit(self):
  163. self.require_api_version('1.23')
  164. service = self.create_service('db', pids_limit=10)
  165. container = service.create_container()
  166. service.start_container(container)
  167. assert container.get('HostConfig.PidsLimit') == 10
  168. def test_create_container_with_extra_hosts_list(self):
  169. extra_hosts = ['somehost:162.242.195.82', 'otherhost:50.31.209.229']
  170. service = self.create_service('db', extra_hosts=extra_hosts)
  171. container = service.create_container()
  172. service.start_container(container)
  173. assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts)
  174. def test_create_container_with_extra_hosts_dicts(self):
  175. extra_hosts = {'somehost': '162.242.195.82', 'otherhost': '50.31.209.229'}
  176. extra_hosts_list = ['somehost:162.242.195.82', 'otherhost:50.31.209.229']
  177. service = self.create_service('db', extra_hosts=extra_hosts)
  178. container = service.create_container()
  179. service.start_container(container)
  180. assert set(container.get('HostConfig.ExtraHosts')) == set(extra_hosts_list)
  181. def test_create_container_with_cpu_set(self):
  182. service = self.create_service('db', cpuset='0')
  183. container = service.create_container()
  184. service.start_container(container)
  185. assert container.get('HostConfig.CpusetCpus') == '0'
  186. def test_create_container_with_read_only_root_fs(self):
  187. read_only = True
  188. service = self.create_service('db', read_only=read_only)
  189. container = service.create_container()
  190. service.start_container(container)
  191. assert container.get('HostConfig.ReadonlyRootfs') == read_only
  192. def test_create_container_with_blkio_config(self):
  193. blkio_config = {
  194. 'weight': 300,
  195. 'weight_device': [{'path': '/dev/sda', 'weight': 200}],
  196. 'device_read_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024 * 100}],
  197. 'device_read_iops': [{'path': '/dev/sda', 'rate': 1000}],
  198. 'device_write_bps': [{'path': '/dev/sda', 'rate': 1024 * 1024}],
  199. 'device_write_iops': [{'path': '/dev/sda', 'rate': 800}]
  200. }
  201. service = self.create_service('web', blkio_config=blkio_config)
  202. container = service.create_container()
  203. assert container.get('HostConfig.BlkioWeight') == 300
  204. assert container.get('HostConfig.BlkioWeightDevice') == [{
  205. 'Path': '/dev/sda', 'Weight': 200
  206. }]
  207. assert container.get('HostConfig.BlkioDeviceReadBps') == [{
  208. 'Path': '/dev/sda', 'Rate': 1024 * 1024 * 100
  209. }]
  210. assert container.get('HostConfig.BlkioDeviceWriteBps') == [{
  211. 'Path': '/dev/sda', 'Rate': 1024 * 1024
  212. }]
  213. assert container.get('HostConfig.BlkioDeviceReadIOps') == [{
  214. 'Path': '/dev/sda', 'Rate': 1000
  215. }]
  216. assert container.get('HostConfig.BlkioDeviceWriteIOps') == [{
  217. 'Path': '/dev/sda', 'Rate': 800
  218. }]
  219. def test_create_container_with_security_opt(self):
  220. security_opt = [SecurityOpt.parse('label:disable')]
  221. service = self.create_service('db', security_opt=security_opt)
  222. container = service.create_container()
  223. service.start_container(container)
  224. assert set(container.get('HostConfig.SecurityOpt')) == set([o.repr() for o in security_opt])
  225. @pytest.mark.xfail(True, reason='Not supported on most drivers')
  226. def test_create_container_with_storage_opt(self):
  227. storage_opt = {'size': '1G'}
  228. service = self.create_service('db', storage_opt=storage_opt)
  229. container = service.create_container()
  230. service.start_container(container)
  231. assert container.get('HostConfig.StorageOpt') == storage_opt
  232. def test_create_container_with_oom_kill_disable(self):
  233. self.require_api_version('1.20')
  234. service = self.create_service('db', oom_kill_disable=True)
  235. container = service.create_container()
  236. assert container.get('HostConfig.OomKillDisable') is True
  237. def test_create_container_with_mac_address(self):
  238. service = self.create_service('db', mac_address='02:42:ac:11:65:43')
  239. container = service.create_container()
  240. service.start_container(container)
  241. assert container.inspect()['Config']['MacAddress'] == '02:42:ac:11:65:43'
  242. def test_create_container_with_device_cgroup_rules(self):
  243. service = self.create_service('db', device_cgroup_rules=['c 7:128 rwm'])
  244. container = service.create_container()
  245. assert container.get('HostConfig.DeviceCgroupRules') == ['c 7:128 rwm']
  246. def test_create_container_with_specified_volume(self):
  247. host_path = '/tmp/host-path'
  248. container_path = '/container-path'
  249. service = self.create_service(
  250. 'db',
  251. volumes=[VolumeSpec(host_path, container_path, 'rw')])
  252. container = service.create_container()
  253. service.start_container(container)
  254. assert container.get_mount(container_path)
  255. # Match the last component ("host-path"), because boot2docker symlinks /tmp
  256. actual_host_path = container.get_mount(container_path)['Source']
  257. assert path.basename(actual_host_path) == path.basename(host_path), (
  258. "Last component differs: %s, %s" % (actual_host_path, host_path)
  259. )
  260. @v2_3_only()
  261. def test_create_container_with_host_mount(self):
  262. host_path = '/tmp/host-path'
  263. container_path = '/container-path'
  264. create_custom_host_file(self.client, path.join(host_path, 'a.txt'), 'test')
  265. service = self.create_service(
  266. 'db',
  267. volumes=[
  268. MountSpec(type='bind', source=host_path, target=container_path, read_only=True)
  269. ]
  270. )
  271. container = service.create_container()
  272. service.start_container(container)
  273. mount = container.get_mount(container_path)
  274. assert mount
  275. assert path.basename(mount['Source']) == path.basename(host_path)
  276. assert mount['RW'] is False
  277. @v2_3_only()
  278. def test_create_container_with_tmpfs_mount(self):
  279. container_path = '/container-tmpfs'
  280. service = self.create_service(
  281. 'db',
  282. volumes=[MountSpec(type='tmpfs', target=container_path)]
  283. )
  284. container = service.create_container()
  285. service.start_container(container)
  286. mount = container.get_mount(container_path)
  287. assert mount
  288. assert mount['Type'] == 'tmpfs'
  289. @v2_3_only()
  290. def test_create_container_with_tmpfs_mount_tmpfs_size(self):
  291. container_path = '/container-tmpfs'
  292. service = self.create_service(
  293. 'db',
  294. volumes=[MountSpec(type='tmpfs', target=container_path, tmpfs={'size': 5368709})]
  295. )
  296. container = service.create_container()
  297. service.start_container(container)
  298. mount = container.get_mount(container_path)
  299. assert mount
  300. print(container.dictionary)
  301. assert mount['Type'] == 'tmpfs'
  302. assert container.get('HostConfig.Mounts')[0]['TmpfsOptions'] == {
  303. 'SizeBytes': 5368709
  304. }
  305. @v2_3_only()
  306. def test_create_container_with_volume_mount(self):
  307. container_path = '/container-volume'
  308. volume_name = 'composetest_abcde'
  309. self.client.create_volume(volume_name)
  310. service = self.create_service(
  311. 'db',
  312. volumes=[MountSpec(type='volume', source=volume_name, target=container_path)]
  313. )
  314. container = service.create_container()
  315. service.start_container(container)
  316. mount = container.get_mount(container_path)
  317. assert mount
  318. assert mount['Name'] == volume_name
  319. @v3_only()
  320. def test_create_container_with_legacy_mount(self):
  321. # Ensure mounts are converted to volumes if API version < 1.30
  322. # Needed to support long syntax in the 3.2 format
  323. client = docker_client({}, version='1.25')
  324. container_path = '/container-volume'
  325. volume_name = 'composetest_abcde'
  326. self.client.create_volume(volume_name)
  327. service = Service('db', client=client, volumes=[
  328. MountSpec(type='volume', source=volume_name, target=container_path)
  329. ], image=BUSYBOX_IMAGE_WITH_TAG, command=['top'], project='composetest')
  330. container = service.create_container()
  331. service.start_container(container)
  332. mount = container.get_mount(container_path)
  333. assert mount
  334. assert mount['Name'] == volume_name
  335. @v3_only()
  336. def test_create_container_with_legacy_tmpfs_mount(self):
  337. # Ensure tmpfs mounts are converted to tmpfs entries if API version < 1.30
  338. # Needed to support long syntax in the 3.2 format
  339. client = docker_client({}, version='1.25')
  340. container_path = '/container-tmpfs'
  341. service = Service('db', client=client, volumes=[
  342. MountSpec(type='tmpfs', target=container_path)
  343. ], image=BUSYBOX_IMAGE_WITH_TAG, command=['top'], project='composetest')
  344. container = service.create_container()
  345. service.start_container(container)
  346. mount = container.get_mount(container_path)
  347. assert mount is None
  348. assert container_path in container.get('HostConfig.Tmpfs')
  349. def test_create_container_with_healthcheck_config(self):
  350. one_second = parse_nanoseconds_int('1s')
  351. healthcheck = {
  352. 'test': ['true'],
  353. 'interval': 2 * one_second,
  354. 'timeout': 5 * one_second,
  355. 'retries': 5,
  356. 'start_period': 2 * one_second
  357. }
  358. service = self.create_service('db', healthcheck=healthcheck)
  359. container = service.create_container()
  360. remote_healthcheck = container.get('Config.Healthcheck')
  361. assert remote_healthcheck['Test'] == healthcheck['test']
  362. assert remote_healthcheck['Interval'] == healthcheck['interval']
  363. assert remote_healthcheck['Timeout'] == healthcheck['timeout']
  364. assert remote_healthcheck['Retries'] == healthcheck['retries']
  365. assert remote_healthcheck['StartPeriod'] == healthcheck['start_period']
  366. def test_recreate_preserves_volume_with_trailing_slash(self):
  367. """When the Compose file specifies a trailing slash in the container path, make
  368. sure we copy the volume over when recreating.
  369. """
  370. service = self.create_service('data', volumes=[VolumeSpec.parse('/data/')])
  371. old_container = create_and_start_container(service)
  372. volume_path = old_container.get_mount('/data')['Source']
  373. new_container = service.recreate_container(old_container)
  374. assert new_container.get_mount('/data')['Source'] == volume_path
  375. def test_recreate_volume_to_mount(self):
  376. # https://github.com/docker/compose/issues/6280
  377. service = Service(
  378. project='composetest',
  379. name='db',
  380. client=self.client,
  381. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  382. volumes=[MountSpec.parse({
  383. 'type': 'volume',
  384. 'target': '/data',
  385. })]
  386. )
  387. old_container = create_and_start_container(service)
  388. new_container = service.recreate_container(old_container)
  389. assert new_container.get_mount('/data')['Source']
  390. def test_duplicate_volume_trailing_slash(self):
  391. """
  392. When an image specifies a volume, and the Compose file specifies a host path
  393. but adds a trailing slash, make sure that we don't create duplicate binds.
  394. """
  395. host_path = '/tmp/data'
  396. container_path = '/data'
  397. volumes = [VolumeSpec.parse('{}:{}/'.format(host_path, container_path))]
  398. tmp_container = self.client.create_container(
  399. 'busybox', 'true',
  400. volumes={container_path: {}},
  401. labels={'com.docker.compose.test_image': 'true'},
  402. host_config={}
  403. )
  404. image = self.client.commit(tmp_container)['Id']
  405. service = self.create_service('db', image=image, volumes=volumes)
  406. old_container = create_and_start_container(service)
  407. assert old_container.get('Config.Volumes') == {container_path: {}}
  408. service = self.create_service('db', image=image, volumes=volumes)
  409. new_container = service.recreate_container(old_container)
  410. assert new_container.get('Config.Volumes') == {container_path: {}}
  411. assert service.containers(stopped=False) == [new_container]
  412. def test_create_container_with_volumes_from(self):
  413. volume_service = self.create_service('data')
  414. volume_container_1 = volume_service.create_container()
  415. volume_container_2 = Container.create(
  416. self.client,
  417. image=BUSYBOX_IMAGE_WITH_TAG,
  418. command=["top"],
  419. labels={LABEL_PROJECT: 'composetest'},
  420. host_config={},
  421. environment=['affinity:container=={}'.format(volume_container_1.id)],
  422. )
  423. host_service = self.create_service(
  424. 'host',
  425. volumes_from=[
  426. VolumeFromSpec(volume_service, 'rw', 'service'),
  427. VolumeFromSpec(volume_container_2, 'rw', 'container')
  428. ],
  429. environment=['affinity:container=={}'.format(volume_container_1.id)],
  430. )
  431. host_container = host_service.create_container()
  432. host_service.start_container(host_container)
  433. assert volume_container_1.id + ':rw' in host_container.get('HostConfig.VolumesFrom')
  434. assert volume_container_2.id + ':rw' in host_container.get('HostConfig.VolumesFrom')
  435. def test_execute_convergence_plan_recreate(self):
  436. service = self.create_service(
  437. 'db',
  438. environment={'FOO': '1'},
  439. volumes=[VolumeSpec.parse('/etc')],
  440. entrypoint=['top'],
  441. command=['-d', '1']
  442. )
  443. old_container = service.create_container()
  444. assert old_container.get('Config.Entrypoint') == ['top']
  445. assert old_container.get('Config.Cmd') == ['-d', '1']
  446. assert 'FOO=1' in old_container.get('Config.Env')
  447. assert old_container.name.startswith('composetest_db_')
  448. service.start_container(old_container)
  449. old_container.inspect() # reload volume data
  450. volume_path = old_container.get_mount('/etc')['Source']
  451. num_containers_before = len(self.client.containers(all=True))
  452. service.options['environment']['FOO'] = '2'
  453. new_container, = service.execute_convergence_plan(
  454. ConvergencePlan('recreate', [old_container]))
  455. assert new_container.get('Config.Entrypoint') == ['top']
  456. assert new_container.get('Config.Cmd') == ['-d', '1']
  457. assert 'FOO=2' in new_container.get('Config.Env')
  458. assert new_container.name.startswith('composetest_db_')
  459. assert new_container.get_mount('/etc')['Source'] == volume_path
  460. if not is_cluster(self.client):
  461. assert (
  462. 'affinity:container==%s' % old_container.id in
  463. new_container.get('Config.Env')
  464. )
  465. else:
  466. # In Swarm, the env marker is consumed and the container should be deployed
  467. # on the same node.
  468. assert old_container.get('Node.Name') == new_container.get('Node.Name')
  469. assert len(self.client.containers(all=True)) == num_containers_before
  470. assert old_container.id != new_container.id
  471. with pytest.raises(APIError):
  472. self.client.inspect_container(old_container.id)
  473. def test_execute_convergence_plan_recreate_change_mount_target(self):
  474. service = self.create_service(
  475. 'db',
  476. volumes=[MountSpec(target='/app1', type='volume')],
  477. entrypoint=['top'], command=['-d', '1']
  478. )
  479. old_container = create_and_start_container(service)
  480. assert (
  481. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  482. ['/app1']
  483. )
  484. service.options['volumes'] = [MountSpec(target='/app2', type='volume')]
  485. new_container, = service.execute_convergence_plan(
  486. ConvergencePlan('recreate', [old_container])
  487. )
  488. assert (
  489. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  490. ['/app2']
  491. )
  492. def test_execute_convergence_plan_recreate_twice(self):
  493. service = self.create_service(
  494. 'db',
  495. volumes=[VolumeSpec.parse('/etc')],
  496. entrypoint=['top'],
  497. command=['-d', '1'])
  498. orig_container = service.create_container()
  499. service.start_container(orig_container)
  500. orig_container.inspect() # reload volume data
  501. volume_path = orig_container.get_mount('/etc')['Source']
  502. # Do this twice to reproduce the bug
  503. for _ in range(2):
  504. new_container, = service.execute_convergence_plan(
  505. ConvergencePlan('recreate', [orig_container]))
  506. assert new_container.get_mount('/etc')['Source'] == volume_path
  507. if not is_cluster(self.client):
  508. assert ('affinity:container==%s' % orig_container.id in
  509. new_container.get('Config.Env'))
  510. else:
  511. # In Swarm, the env marker is consumed and the container should be deployed
  512. # on the same node.
  513. assert orig_container.get('Node.Name') == new_container.get('Node.Name')
  514. orig_container = new_container
  515. @v2_3_only()
  516. def test_execute_convergence_plan_recreate_twice_with_mount(self):
  517. service = self.create_service(
  518. 'db',
  519. volumes=[MountSpec(target='/etc', type='volume')],
  520. entrypoint=['top'],
  521. command=['-d', '1']
  522. )
  523. orig_container = service.create_container()
  524. service.start_container(orig_container)
  525. orig_container.inspect() # reload volume data
  526. volume_path = orig_container.get_mount('/etc')['Source']
  527. # Do this twice to reproduce the bug
  528. for _ in range(2):
  529. new_container, = service.execute_convergence_plan(
  530. ConvergencePlan('recreate', [orig_container])
  531. )
  532. assert new_container.get_mount('/etc')['Source'] == volume_path
  533. if not is_cluster(self.client):
  534. assert ('affinity:container==%s' % orig_container.id in
  535. new_container.get('Config.Env'))
  536. else:
  537. # In Swarm, the env marker is consumed and the container should be deployed
  538. # on the same node.
  539. assert orig_container.get('Node.Name') == new_container.get('Node.Name')
  540. orig_container = new_container
  541. def test_execute_convergence_plan_when_containers_are_stopped(self):
  542. service = self.create_service(
  543. 'db',
  544. environment={'FOO': '1'},
  545. volumes=[VolumeSpec.parse('/var/db')],
  546. entrypoint=['top'],
  547. command=['-d', '1']
  548. )
  549. service.create_container()
  550. containers = service.containers(stopped=True)
  551. assert len(containers) == 1
  552. container, = containers
  553. assert not container.is_running
  554. service.execute_convergence_plan(ConvergencePlan('start', [container]))
  555. containers = service.containers()
  556. assert len(containers) == 1
  557. container.inspect()
  558. assert container == containers[0]
  559. assert container.is_running
  560. def test_execute_convergence_plan_with_image_declared_volume(self):
  561. service = Service(
  562. project='composetest',
  563. name='db',
  564. client=self.client,
  565. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  566. )
  567. old_container = create_and_start_container(service)
  568. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  569. volume_path = old_container.get_mount('/data')['Source']
  570. new_container, = service.execute_convergence_plan(
  571. ConvergencePlan('recreate', [old_container]))
  572. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  573. assert new_container.get_mount('/data')['Source'] == volume_path
  574. def test_execute_convergence_plan_with_image_declared_volume_renew(self):
  575. service = Service(
  576. project='composetest',
  577. name='db',
  578. client=self.client,
  579. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  580. )
  581. old_container = create_and_start_container(service)
  582. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  583. volume_path = old_container.get_mount('/data')['Source']
  584. new_container, = service.execute_convergence_plan(
  585. ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True
  586. )
  587. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  588. assert new_container.get_mount('/data')['Source'] != volume_path
  589. def test_execute_convergence_plan_when_image_volume_masks_config(self):
  590. service = self.create_service(
  591. 'db',
  592. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  593. )
  594. old_container = create_and_start_container(service)
  595. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  596. volume_path = old_container.get_mount('/data')['Source']
  597. service.options['volumes'] = [VolumeSpec.parse('/tmp:/data')]
  598. with mock.patch('compose.service.log') as mock_log:
  599. new_container, = service.execute_convergence_plan(
  600. ConvergencePlan('recreate', [old_container]))
  601. mock_log.warning.assert_called_once_with(mock.ANY)
  602. _, args, kwargs = mock_log.warning.mock_calls[0]
  603. assert "Service \"db\" is using volume \"/data\" from the previous container" in args[0]
  604. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  605. assert new_container.get_mount('/data')['Source'] == volume_path
  606. def test_execute_convergence_plan_when_host_volume_is_removed(self):
  607. host_path = '/tmp/host-path'
  608. service = self.create_service(
  609. 'db',
  610. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  611. volumes=[VolumeSpec(host_path, '/data', 'rw')])
  612. old_container = create_and_start_container(service)
  613. assert (
  614. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  615. ['/data']
  616. )
  617. service.options['volumes'] = []
  618. with mock.patch('compose.service.log', autospec=True) as mock_log:
  619. new_container, = service.execute_convergence_plan(
  620. ConvergencePlan('recreate', [old_container]))
  621. assert not mock_log.warn.called
  622. assert (
  623. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  624. ['/data']
  625. )
  626. assert new_container.get_mount('/data')['Source'] != host_path
  627. def test_execute_convergence_plan_anonymous_volume_renew(self):
  628. service = self.create_service(
  629. 'db',
  630. image='busybox',
  631. volumes=[VolumeSpec(None, '/data', 'rw')])
  632. old_container = create_and_start_container(service)
  633. assert (
  634. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  635. ['/data']
  636. )
  637. volume_path = old_container.get_mount('/data')['Source']
  638. new_container, = service.execute_convergence_plan(
  639. ConvergencePlan('recreate', [old_container]),
  640. renew_anonymous_volumes=True
  641. )
  642. assert (
  643. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  644. ['/data']
  645. )
  646. assert new_container.get_mount('/data')['Source'] != volume_path
  647. def test_execute_convergence_plan_anonymous_volume_recreate_then_renew(self):
  648. service = self.create_service(
  649. 'db',
  650. image='busybox',
  651. volumes=[VolumeSpec(None, '/data', 'rw')])
  652. old_container = create_and_start_container(service)
  653. assert (
  654. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  655. ['/data']
  656. )
  657. volume_path = old_container.get_mount('/data')['Source']
  658. mid_container, = service.execute_convergence_plan(
  659. ConvergencePlan('recreate', [old_container]),
  660. )
  661. assert (
  662. [mount['Destination'] for mount in mid_container.get('Mounts')] ==
  663. ['/data']
  664. )
  665. assert mid_container.get_mount('/data')['Source'] == volume_path
  666. new_container, = service.execute_convergence_plan(
  667. ConvergencePlan('recreate', [mid_container]),
  668. renew_anonymous_volumes=True
  669. )
  670. assert (
  671. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  672. ['/data']
  673. )
  674. assert new_container.get_mount('/data')['Source'] != volume_path
  675. def test_execute_convergence_plan_without_start(self):
  676. service = self.create_service(
  677. 'db',
  678. build={'context': 'tests/fixtures/dockerfile-with-volume'}
  679. )
  680. containers = service.execute_convergence_plan(ConvergencePlan('create', []), start=False)
  681. service_containers = service.containers(stopped=True)
  682. assert len(service_containers) == 1
  683. assert not service_containers[0].is_running
  684. containers = service.execute_convergence_plan(
  685. ConvergencePlan('recreate', containers),
  686. start=False)
  687. service_containers = service.containers(stopped=True)
  688. assert len(service_containers) == 1
  689. assert not service_containers[0].is_running
  690. service.execute_convergence_plan(ConvergencePlan('start', containers), start=False)
  691. service_containers = service.containers(stopped=True)
  692. assert len(service_containers) == 1
  693. assert not service_containers[0].is_running
  694. def test_execute_convergence_plan_image_with_volume_is_removed(self):
  695. service = self.create_service(
  696. 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}
  697. )
  698. old_container = create_and_start_container(service)
  699. assert (
  700. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  701. ['/data']
  702. )
  703. volume_path = old_container.get_mount('/data')['Source']
  704. old_container.stop()
  705. self.client.remove_image(service.image(), force=True)
  706. service.ensure_image_exists()
  707. with pytest.raises(ImageNotFound):
  708. service.execute_convergence_plan(
  709. ConvergencePlan('recreate', [old_container])
  710. )
  711. old_container.inspect() # retrieve new name from server
  712. new_container, = service.execute_convergence_plan(
  713. ConvergencePlan('recreate', [old_container]),
  714. reset_container_image=True
  715. )
  716. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  717. assert new_container.get_mount('/data')['Source'] == volume_path
  718. def test_start_container_passes_through_options(self):
  719. db = self.create_service('db')
  720. create_and_start_container(db, environment={'FOO': 'BAR'})
  721. assert db.containers()[0].environment['FOO'] == 'BAR'
  722. def test_start_container_inherits_options_from_constructor(self):
  723. db = self.create_service('db', environment={'FOO': 'BAR'})
  724. create_and_start_container(db)
  725. assert db.containers()[0].environment['FOO'] == 'BAR'
  726. @no_cluster('No legacy links support in Swarm')
  727. def test_start_container_creates_links(self):
  728. db = self.create_service('db')
  729. web = self.create_service('web', links=[(db, None)])
  730. db1 = create_and_start_container(db)
  731. db2 = create_and_start_container(db)
  732. create_and_start_container(web)
  733. assert set(get_links(web.containers()[0])) == set([
  734. db1.name, db1.name_without_project,
  735. db2.name, db2.name_without_project,
  736. 'db'
  737. ])
  738. @no_cluster('No legacy links support in Swarm')
  739. def test_start_container_creates_links_with_names(self):
  740. db = self.create_service('db')
  741. web = self.create_service('web', links=[(db, 'custom_link_name')])
  742. db1 = create_and_start_container(db)
  743. db2 = create_and_start_container(db)
  744. create_and_start_container(web)
  745. assert set(get_links(web.containers()[0])) == set([
  746. db1.name, db1.name_without_project,
  747. db2.name, db2.name_without_project,
  748. 'custom_link_name'
  749. ])
  750. @no_cluster('No legacy links support in Swarm')
  751. def test_start_container_with_external_links(self):
  752. db = self.create_service('db')
  753. db_ctnrs = [create_and_start_container(db) for _ in range(3)]
  754. web = self.create_service(
  755. 'web', external_links=[
  756. db_ctnrs[0].name,
  757. db_ctnrs[1].name,
  758. '{}:db_3'.format(db_ctnrs[2].name)
  759. ]
  760. )
  761. create_and_start_container(web)
  762. assert set(get_links(web.containers()[0])) == set([
  763. db_ctnrs[0].name,
  764. db_ctnrs[1].name,
  765. 'db_3'
  766. ])
  767. @no_cluster('No legacy links support in Swarm')
  768. def test_start_normal_container_does_not_create_links_to_its_own_service(self):
  769. db = self.create_service('db')
  770. create_and_start_container(db)
  771. create_and_start_container(db)
  772. c = create_and_start_container(db)
  773. assert set(get_links(c)) == set([])
  774. @no_cluster('No legacy links support in Swarm')
  775. def test_start_one_off_container_creates_links_to_its_own_service(self):
  776. db = self.create_service('db')
  777. db1 = create_and_start_container(db)
  778. db2 = create_and_start_container(db)
  779. c = create_and_start_container(db, one_off=OneOffFilter.only)
  780. assert set(get_links(c)) == set([
  781. db1.name, db1.name_without_project,
  782. db2.name, db2.name_without_project,
  783. 'db'
  784. ])
  785. def test_start_container_builds_images(self):
  786. service = Service(
  787. name='test',
  788. client=self.client,
  789. build={'context': 'tests/fixtures/simple-dockerfile'},
  790. project='composetest',
  791. )
  792. container = create_and_start_container(service)
  793. container.wait()
  794. assert b'success' in container.logs()
  795. assert len(self.client.images(name='composetest_test')) >= 1
  796. def test_start_container_uses_tagged_image_if_it_exists(self):
  797. self.check_build('tests/fixtures/simple-dockerfile', tag='composetest_test')
  798. service = Service(
  799. name='test',
  800. client=self.client,
  801. build={'context': 'this/does/not/exist/and/will/throw/error'},
  802. project='composetest',
  803. )
  804. container = create_and_start_container(service)
  805. container.wait()
  806. assert b'success' in container.logs()
  807. def test_start_container_creates_ports(self):
  808. service = self.create_service('web', ports=[8000])
  809. container = create_and_start_container(service).inspect()
  810. assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/tcp']
  811. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] != '8000'
  812. def test_build(self):
  813. base_dir = tempfile.mkdtemp()
  814. self.addCleanup(shutil.rmtree, base_dir)
  815. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  816. f.write("FROM busybox\n")
  817. service = self.create_service('web', build={'context': base_dir})
  818. service.build()
  819. self.addCleanup(self.client.remove_image, service.image_name)
  820. assert self.client.inspect_image('composetest_web')
  821. def test_build_cli(self):
  822. base_dir = tempfile.mkdtemp()
  823. self.addCleanup(shutil.rmtree, base_dir)
  824. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  825. f.write("FROM busybox\n")
  826. service = self.create_service('web',
  827. build={'context': base_dir},
  828. environment={
  829. 'COMPOSE_DOCKER_CLI_BUILD': '1',
  830. 'DOCKER_BUILDKIT': '1',
  831. })
  832. service.build(cli=True)
  833. self.addCleanup(self.client.remove_image, service.image_name)
  834. assert self.client.inspect_image('composetest_web')
  835. def test_up_build_cli(self):
  836. base_dir = tempfile.mkdtemp()
  837. self.addCleanup(shutil.rmtree, base_dir)
  838. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  839. f.write("FROM busybox\n")
  840. web = self.create_service('web',
  841. build={'context': base_dir},
  842. environment={
  843. 'COMPOSE_DOCKER_CLI_BUILD': '1',
  844. 'DOCKER_BUILDKIT': '1',
  845. })
  846. project = Project('composetest', [web], self.client)
  847. project.up(do_build=BuildAction.force)
  848. containers = project.containers(['web'])
  849. assert len(containers) == 1
  850. assert containers[0].name.startswith('composetest_web_')
  851. def test_build_non_ascii_filename(self):
  852. base_dir = tempfile.mkdtemp()
  853. self.addCleanup(shutil.rmtree, base_dir)
  854. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  855. f.write("FROM busybox\n")
  856. with open(os.path.join(base_dir.encode('utf8'), b'foo\xE2bar'), 'w') as f:
  857. f.write("hello world\n")
  858. service = self.create_service('web', build={'context': text_type(base_dir)})
  859. service.build()
  860. self.addCleanup(self.client.remove_image, service.image_name)
  861. assert self.client.inspect_image('composetest_web')
  862. def test_build_with_image_name(self):
  863. base_dir = tempfile.mkdtemp()
  864. self.addCleanup(shutil.rmtree, base_dir)
  865. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  866. f.write("FROM busybox\n")
  867. image_name = 'examples/composetest:latest'
  868. self.addCleanup(self.client.remove_image, image_name)
  869. self.create_service('web', build={'context': base_dir}, image=image_name).build()
  870. assert self.client.inspect_image(image_name)
  871. def test_build_with_git_url(self):
  872. build_url = "https://github.com/dnephin/docker-build-from-url.git"
  873. service = self.create_service('buildwithurl', build={'context': build_url})
  874. self.addCleanup(self.client.remove_image, service.image_name)
  875. service.build()
  876. assert service.image()
  877. def test_build_with_build_args(self):
  878. base_dir = tempfile.mkdtemp()
  879. self.addCleanup(shutil.rmtree, base_dir)
  880. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  881. f.write("FROM busybox\n")
  882. f.write("ARG build_version\n")
  883. f.write("RUN echo ${build_version}\n")
  884. service = self.create_service('buildwithargs',
  885. build={'context': text_type(base_dir),
  886. 'args': {"build_version": "1"}})
  887. service.build()
  888. self.addCleanup(self.client.remove_image, service.image_name)
  889. assert service.image()
  890. assert "build_version=1" in service.image()['ContainerConfig']['Cmd']
  891. def test_build_with_build_args_override(self):
  892. base_dir = tempfile.mkdtemp()
  893. self.addCleanup(shutil.rmtree, base_dir)
  894. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  895. f.write("FROM busybox\n")
  896. f.write("ARG build_version\n")
  897. f.write("RUN echo ${build_version}\n")
  898. service = self.create_service('buildwithargs',
  899. build={'context': text_type(base_dir),
  900. 'args': {"build_version": "1"}})
  901. service.build(build_args_override={'build_version': '2'})
  902. self.addCleanup(self.client.remove_image, service.image_name)
  903. assert service.image()
  904. assert "build_version=2" in service.image()['ContainerConfig']['Cmd']
  905. def test_build_with_build_labels(self):
  906. base_dir = tempfile.mkdtemp()
  907. self.addCleanup(shutil.rmtree, base_dir)
  908. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  909. f.write('FROM busybox\n')
  910. service = self.create_service('buildlabels', build={
  911. 'context': text_type(base_dir),
  912. 'labels': {'com.docker.compose.test': 'true'}
  913. })
  914. service.build()
  915. self.addCleanup(self.client.remove_image, service.image_name)
  916. assert service.image()
  917. assert service.image()['Config']['Labels']['com.docker.compose.test'] == 'true'
  918. @no_cluster('Container networks not on Swarm')
  919. def test_build_with_network(self):
  920. base_dir = tempfile.mkdtemp()
  921. self.addCleanup(shutil.rmtree, base_dir)
  922. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  923. f.write('FROM busybox\n')
  924. f.write('RUN ping -c1 google.local\n')
  925. net_container = self.client.create_container(
  926. 'busybox', 'top', host_config=self.client.create_host_config(
  927. extra_hosts={'google.local': '127.0.0.1'}
  928. ), name='composetest_build_network'
  929. )
  930. self.addCleanup(self.client.remove_container, net_container, force=True)
  931. self.client.start(net_container)
  932. service = self.create_service('buildwithnet', build={
  933. 'context': text_type(base_dir),
  934. 'network': 'container:{}'.format(net_container['Id'])
  935. })
  936. service.build()
  937. self.addCleanup(self.client.remove_image, service.image_name)
  938. assert service.image()
  939. @v2_3_only()
  940. @no_cluster('Not supported on UCP 2.2.0-beta1') # FIXME: remove once support is added
  941. def test_build_with_target(self):
  942. self.require_api_version('1.30')
  943. base_dir = tempfile.mkdtemp()
  944. self.addCleanup(shutil.rmtree, base_dir)
  945. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  946. f.write('FROM busybox as one\n')
  947. f.write('LABEL com.docker.compose.test=true\n')
  948. f.write('LABEL com.docker.compose.test.target=one\n')
  949. f.write('FROM busybox as two\n')
  950. f.write('LABEL com.docker.compose.test.target=two\n')
  951. service = self.create_service('buildtarget', build={
  952. 'context': text_type(base_dir),
  953. 'target': 'one'
  954. })
  955. service.build()
  956. assert service.image()
  957. assert service.image()['Config']['Labels']['com.docker.compose.test.target'] == 'one'
  958. @v2_3_only()
  959. def test_build_with_extra_hosts(self):
  960. self.require_api_version('1.27')
  961. base_dir = tempfile.mkdtemp()
  962. self.addCleanup(shutil.rmtree, base_dir)
  963. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  964. f.write('\n'.join([
  965. 'FROM busybox',
  966. 'RUN ping -c1 foobar',
  967. 'RUN ping -c1 baz',
  968. ]))
  969. service = self.create_service('build_extra_hosts', build={
  970. 'context': text_type(base_dir),
  971. 'extra_hosts': {
  972. 'foobar': '127.0.0.1',
  973. 'baz': '127.0.0.1'
  974. }
  975. })
  976. service.build()
  977. assert service.image()
  978. def test_build_with_gzip(self):
  979. base_dir = tempfile.mkdtemp()
  980. self.addCleanup(shutil.rmtree, base_dir)
  981. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  982. f.write('\n'.join([
  983. 'FROM busybox',
  984. 'COPY . /src',
  985. 'RUN cat /src/hello.txt'
  986. ]))
  987. with open(os.path.join(base_dir, 'hello.txt'), 'w') as f:
  988. f.write('hello world\n')
  989. service = self.create_service('build_gzip', build={
  990. 'context': text_type(base_dir),
  991. })
  992. service.build(gzip=True)
  993. assert service.image()
  994. @v2_1_only()
  995. def test_build_with_isolation(self):
  996. base_dir = tempfile.mkdtemp()
  997. self.addCleanup(shutil.rmtree, base_dir)
  998. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  999. f.write('FROM busybox\n')
  1000. service = self.create_service('build_isolation', build={
  1001. 'context': text_type(base_dir),
  1002. 'isolation': 'default',
  1003. })
  1004. service.build()
  1005. assert service.image()
  1006. def test_build_with_illegal_leading_chars(self):
  1007. base_dir = tempfile.mkdtemp()
  1008. self.addCleanup(shutil.rmtree, base_dir)
  1009. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  1010. f.write('FROM busybox\nRUN echo "Embodiment of Scarlet Devil"\n')
  1011. service = Service(
  1012. 'build_leading_slug', client=self.client,
  1013. project='___-composetest', build={
  1014. 'context': text_type(base_dir)
  1015. }
  1016. )
  1017. assert service.image_name == 'composetest_build_leading_slug'
  1018. service.build()
  1019. assert service.image()
  1020. def test_start_container_stays_unprivileged(self):
  1021. service = self.create_service('web')
  1022. container = create_and_start_container(service).inspect()
  1023. assert container['HostConfig']['Privileged'] is False
  1024. def test_start_container_becomes_privileged(self):
  1025. service = self.create_service('web', privileged=True)
  1026. container = create_and_start_container(service).inspect()
  1027. assert container['HostConfig']['Privileged'] is True
  1028. def test_expose_does_not_publish_ports(self):
  1029. service = self.create_service('web', expose=["8000"])
  1030. container = create_and_start_container(service).inspect()
  1031. assert container['NetworkSettings']['Ports'] == {'8000/tcp': None}
  1032. def test_start_container_creates_port_with_explicit_protocol(self):
  1033. service = self.create_service('web', ports=['8000/udp'])
  1034. container = create_and_start_container(service).inspect()
  1035. assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/udp']
  1036. def test_start_container_creates_fixed_external_ports(self):
  1037. service = self.create_service('web', ports=['8000:8000'])
  1038. container = create_and_start_container(service).inspect()
  1039. assert '8000/tcp' in container['NetworkSettings']['Ports']
  1040. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8000'
  1041. def test_start_container_creates_fixed_external_ports_when_it_is_different_to_internal_port(self):
  1042. service = self.create_service('web', ports=['8001:8000'])
  1043. container = create_and_start_container(service).inspect()
  1044. assert '8000/tcp' in container['NetworkSettings']['Ports']
  1045. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8001'
  1046. def test_port_with_explicit_interface(self):
  1047. service = self.create_service('web', ports=[
  1048. '127.0.0.1:8001:8000',
  1049. '0.0.0.0:9001:9000/udp',
  1050. ])
  1051. container = create_and_start_container(service).inspect()
  1052. assert container['NetworkSettings']['Ports']['8000/tcp'] == [{
  1053. 'HostIp': '127.0.0.1',
  1054. 'HostPort': '8001',
  1055. }]
  1056. assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostPort'] == '9001'
  1057. if not is_cluster(self.client):
  1058. assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostIp'] == '0.0.0.0'
  1059. # self.assertEqual(container['NetworkSettings']['Ports'], {
  1060. # '8000/tcp': [
  1061. # {
  1062. # 'HostIp': '127.0.0.1',
  1063. # 'HostPort': '8001',
  1064. # },
  1065. # ],
  1066. # '9000/udp': [
  1067. # {
  1068. # 'HostIp': '0.0.0.0',
  1069. # 'HostPort': '9001',
  1070. # },
  1071. # ],
  1072. # })
  1073. def test_create_with_image_id(self):
  1074. pull_busybox(self.client)
  1075. image_id = self.client.inspect_image(BUSYBOX_IMAGE_WITH_TAG)['Id'][:12]
  1076. service = self.create_service('foo', image=image_id)
  1077. service.create_container()
  1078. def test_scale(self):
  1079. service = self.create_service('web')
  1080. service.scale(1)
  1081. assert len(service.containers()) == 1
  1082. # Ensure containers don't have stdout or stdin connected
  1083. container = service.containers()[0]
  1084. config = container.inspect()['Config']
  1085. assert not config['AttachStderr']
  1086. assert not config['AttachStdout']
  1087. assert not config['AttachStdin']
  1088. service.scale(3)
  1089. assert len(service.containers()) == 3
  1090. service.scale(1)
  1091. assert len(service.containers()) == 1
  1092. service.scale(0)
  1093. assert len(service.containers()) == 0
  1094. @pytest.mark.skipif(
  1095. SWARM_SKIP_CONTAINERS_ALL,
  1096. reason='Swarm /containers/json bug'
  1097. )
  1098. def test_scale_with_stopped_containers(self):
  1099. """
  1100. Given there are some stopped containers and scale is called with a
  1101. desired number that is the same as the number of stopped containers,
  1102. test that those containers are restarted and not removed/recreated.
  1103. """
  1104. service = self.create_service('web')
  1105. service.create_container(number=1)
  1106. service.create_container(number=2)
  1107. ParallelStreamWriter.instance = None
  1108. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1109. service.scale(2)
  1110. for container in service.containers():
  1111. assert container.is_running
  1112. assert container.number in [1, 2]
  1113. captured_output = mock_stderr.getvalue()
  1114. assert 'Creating' not in captured_output
  1115. assert 'Starting' in captured_output
  1116. def test_scale_with_stopped_containers_and_needing_creation(self):
  1117. """
  1118. Given there are some stopped containers and scale is called with a
  1119. desired number that is greater than the number of stopped containers,
  1120. test that those containers are restarted and required number are created.
  1121. """
  1122. service = self.create_service('web')
  1123. next_number = service._next_container_number()
  1124. service.create_container(number=next_number, quiet=True)
  1125. for container in service.containers():
  1126. assert not container.is_running
  1127. ParallelStreamWriter.instance = None
  1128. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1129. service.scale(2)
  1130. assert len(service.containers()) == 2
  1131. for container in service.containers():
  1132. assert container.is_running
  1133. captured_output = mock_stderr.getvalue()
  1134. assert 'Creating' in captured_output
  1135. assert 'Starting' in captured_output
  1136. def test_scale_with_api_error(self):
  1137. """Test that when scaling if the API returns an error, that error is handled
  1138. and the remaining threads continue.
  1139. """
  1140. service = self.create_service('web')
  1141. next_number = service._next_container_number()
  1142. service.create_container(number=next_number, quiet=True)
  1143. with mock.patch(
  1144. 'compose.container.Container.create',
  1145. side_effect=APIError(
  1146. message="testing",
  1147. response={},
  1148. explanation="Boom")):
  1149. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1150. with pytest.raises(OperationFailedError):
  1151. service.scale(3)
  1152. assert len(service.containers()) == 1
  1153. assert service.containers()[0].is_running
  1154. assert "ERROR: for composetest_web_" in mock_stderr.getvalue()
  1155. assert "Cannot create container for service web: Boom" in mock_stderr.getvalue()
  1156. def test_scale_with_unexpected_exception(self):
  1157. """Test that when scaling if the API returns an error, that is not of type
  1158. APIError, that error is re-raised.
  1159. """
  1160. service = self.create_service('web')
  1161. next_number = service._next_container_number()
  1162. service.create_container(number=next_number, quiet=True)
  1163. with mock.patch(
  1164. 'compose.container.Container.create',
  1165. side_effect=ValueError("BOOM")
  1166. ):
  1167. with pytest.raises(ValueError):
  1168. service.scale(3)
  1169. assert len(service.containers()) == 1
  1170. assert service.containers()[0].is_running
  1171. @mock.patch('compose.service.log')
  1172. def test_scale_with_desired_number_already_achieved(self, mock_log):
  1173. """
  1174. Test that calling scale with a desired number that is equal to the
  1175. number of containers already running results in no change.
  1176. """
  1177. service = self.create_service('web')
  1178. next_number = service._next_container_number()
  1179. container = service.create_container(number=next_number, quiet=True)
  1180. container.start()
  1181. container.inspect()
  1182. assert container.is_running
  1183. assert len(service.containers()) == 1
  1184. service.scale(1)
  1185. assert len(service.containers()) == 1
  1186. container.inspect()
  1187. assert container.is_running
  1188. captured_output = mock_log.info.call_args[0]
  1189. assert 'Desired container number already achieved' in captured_output
  1190. @mock.patch('compose.service.log')
  1191. def test_scale_with_custom_container_name_outputs_warning(self, mock_log):
  1192. """Test that calling scale on a service that has a custom container name
  1193. results in warning output.
  1194. """
  1195. service = self.create_service('app', container_name='custom-container')
  1196. assert service.custom_container_name == 'custom-container'
  1197. with pytest.raises(OperationFailedError):
  1198. service.scale(3)
  1199. captured_output = mock_log.warning.call_args[0][0]
  1200. assert len(service.containers()) == 1
  1201. assert "Remove the custom name to scale the service." in captured_output
  1202. def test_scale_sets_ports(self):
  1203. service = self.create_service('web', ports=['8000'])
  1204. service.scale(2)
  1205. containers = service.containers()
  1206. assert len(containers) == 2
  1207. for container in containers:
  1208. assert list(container.get('HostConfig.PortBindings')) == ['8000/tcp']
  1209. def test_scale_with_immediate_exit(self):
  1210. service = self.create_service('web', image='busybox', command='true')
  1211. service.scale(2)
  1212. assert len(service.containers(stopped=True)) == 2
  1213. def test_network_mode_none(self):
  1214. service = self.create_service('web', network_mode=NetworkMode('none'))
  1215. container = create_and_start_container(service)
  1216. assert container.get('HostConfig.NetworkMode') == 'none'
  1217. def test_network_mode_bridged(self):
  1218. service = self.create_service('web', network_mode=NetworkMode('bridge'))
  1219. container = create_and_start_container(service)
  1220. assert container.get('HostConfig.NetworkMode') == 'bridge'
  1221. def test_network_mode_host(self):
  1222. service = self.create_service('web', network_mode=NetworkMode('host'))
  1223. container = create_and_start_container(service)
  1224. assert container.get('HostConfig.NetworkMode') == 'host'
  1225. def test_pid_mode_none_defined(self):
  1226. service = self.create_service('web', pid_mode=None)
  1227. container = create_and_start_container(service)
  1228. assert container.get('HostConfig.PidMode') == ''
  1229. def test_pid_mode_host(self):
  1230. service = self.create_service('web', pid_mode=PidMode('host'))
  1231. container = create_and_start_container(service)
  1232. assert container.get('HostConfig.PidMode') == 'host'
  1233. @v2_1_only()
  1234. def test_userns_mode_none_defined(self):
  1235. service = self.create_service('web', userns_mode=None)
  1236. container = create_and_start_container(service)
  1237. assert container.get('HostConfig.UsernsMode') == ''
  1238. @v2_1_only()
  1239. def test_userns_mode_host(self):
  1240. service = self.create_service('web', userns_mode='host')
  1241. container = create_and_start_container(service)
  1242. assert container.get('HostConfig.UsernsMode') == 'host'
  1243. def test_dns_no_value(self):
  1244. service = self.create_service('web')
  1245. container = create_and_start_container(service)
  1246. assert container.get('HostConfig.Dns') is None
  1247. def test_dns_list(self):
  1248. service = self.create_service('web', dns=['8.8.8.8', '9.9.9.9'])
  1249. container = create_and_start_container(service)
  1250. assert container.get('HostConfig.Dns') == ['8.8.8.8', '9.9.9.9']
  1251. def test_mem_swappiness(self):
  1252. service = self.create_service('web', mem_swappiness=11)
  1253. container = create_and_start_container(service)
  1254. assert container.get('HostConfig.MemorySwappiness') == 11
  1255. def test_mem_reservation(self):
  1256. service = self.create_service('web', mem_reservation='20m')
  1257. container = create_and_start_container(service)
  1258. assert container.get('HostConfig.MemoryReservation') == 20 * 1024 * 1024
  1259. def test_restart_always_value(self):
  1260. service = self.create_service('web', restart={'Name': 'always'})
  1261. container = create_and_start_container(service)
  1262. assert container.get('HostConfig.RestartPolicy.Name') == 'always'
  1263. def test_oom_score_adj_value(self):
  1264. service = self.create_service('web', oom_score_adj=500)
  1265. container = create_and_start_container(service)
  1266. assert container.get('HostConfig.OomScoreAdj') == 500
  1267. def test_group_add_value(self):
  1268. service = self.create_service('web', group_add=["root", "1"])
  1269. container = create_and_start_container(service)
  1270. host_container_groupadd = container.get('HostConfig.GroupAdd')
  1271. assert "root" in host_container_groupadd
  1272. assert "1" in host_container_groupadd
  1273. def test_dns_opt_value(self):
  1274. service = self.create_service('web', dns_opt=["use-vc", "no-tld-query"])
  1275. container = create_and_start_container(service)
  1276. dns_opt = container.get('HostConfig.DnsOptions')
  1277. assert 'use-vc' in dns_opt
  1278. assert 'no-tld-query' in dns_opt
  1279. def test_restart_on_failure_value(self):
  1280. service = self.create_service('web', restart={
  1281. 'Name': 'on-failure',
  1282. 'MaximumRetryCount': 5
  1283. })
  1284. container = create_and_start_container(service)
  1285. assert container.get('HostConfig.RestartPolicy.Name') == 'on-failure'
  1286. assert container.get('HostConfig.RestartPolicy.MaximumRetryCount') == 5
  1287. def test_cap_add_list(self):
  1288. service = self.create_service('web', cap_add=['SYS_ADMIN', 'NET_ADMIN'])
  1289. container = create_and_start_container(service)
  1290. assert container.get('HostConfig.CapAdd') == ['SYS_ADMIN', 'NET_ADMIN']
  1291. def test_cap_drop_list(self):
  1292. service = self.create_service('web', cap_drop=['SYS_ADMIN', 'NET_ADMIN'])
  1293. container = create_and_start_container(service)
  1294. assert container.get('HostConfig.CapDrop') == ['SYS_ADMIN', 'NET_ADMIN']
  1295. def test_dns_search(self):
  1296. service = self.create_service('web', dns_search=['dc1.example.com', 'dc2.example.com'])
  1297. container = create_and_start_container(service)
  1298. assert container.get('HostConfig.DnsSearch') == ['dc1.example.com', 'dc2.example.com']
  1299. @v2_only()
  1300. def test_tmpfs(self):
  1301. service = self.create_service('web', tmpfs=['/run'])
  1302. container = create_and_start_container(service)
  1303. assert container.get('HostConfig.Tmpfs') == {'/run': ''}
  1304. def test_working_dir_param(self):
  1305. service = self.create_service('container', working_dir='/working/dir/sample')
  1306. container = service.create_container()
  1307. assert container.get('Config.WorkingDir') == '/working/dir/sample'
  1308. def test_split_env(self):
  1309. service = self.create_service(
  1310. 'web',
  1311. environment=['NORMAL=F1', 'CONTAINS_EQUALS=F=2', 'TRAILING_EQUALS='])
  1312. env = create_and_start_container(service).environment
  1313. for k, v in {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''}.items():
  1314. assert env[k] == v
  1315. def test_env_from_file_combined_with_env(self):
  1316. service = self.create_service(
  1317. 'web',
  1318. environment=['ONE=1', 'TWO=2', 'THREE=3'],
  1319. env_file=['tests/fixtures/env/one.env', 'tests/fixtures/env/two.env'])
  1320. env = create_and_start_container(service).environment
  1321. for k, v in {
  1322. 'ONE': '1',
  1323. 'TWO': '2',
  1324. 'THREE': '3',
  1325. 'FOO': 'baz',
  1326. 'DOO': 'dah'
  1327. }.items():
  1328. assert env[k] == v
  1329. @v3_only()
  1330. def test_build_with_cachefrom(self):
  1331. base_dir = tempfile.mkdtemp()
  1332. self.addCleanup(shutil.rmtree, base_dir)
  1333. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  1334. f.write("FROM busybox\n")
  1335. service = self.create_service('cache_from',
  1336. build={'context': base_dir,
  1337. 'cache_from': ['build1']})
  1338. service.build()
  1339. self.addCleanup(self.client.remove_image, service.image_name)
  1340. assert service.image()
  1341. @mock.patch.dict(os.environ)
  1342. def test_resolve_env(self):
  1343. os.environ['FILE_DEF'] = 'E1'
  1344. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1345. os.environ['ENV_DEF'] = 'E3'
  1346. service = self.create_service(
  1347. 'web',
  1348. environment={
  1349. 'FILE_DEF': 'F1',
  1350. 'FILE_DEF_EMPTY': '',
  1351. 'ENV_DEF': None,
  1352. 'NO_DEF': None
  1353. }
  1354. )
  1355. env = create_and_start_container(service).environment
  1356. for k, v in {
  1357. 'FILE_DEF': 'F1',
  1358. 'FILE_DEF_EMPTY': '',
  1359. 'ENV_DEF': 'E3',
  1360. 'NO_DEF': None
  1361. }.items():
  1362. assert env[k] == v
  1363. def test_with_high_enough_api_version_we_get_default_network_mode(self):
  1364. # TODO: remove this test once minimum docker version is 1.8.x
  1365. with mock.patch.object(self.client, '_version', '1.20'):
  1366. service = self.create_service('web')
  1367. service_config = service._get_container_host_config({})
  1368. assert service_config['NetworkMode'] == 'default'
  1369. def test_labels(self):
  1370. labels_dict = {
  1371. 'com.example.description': "Accounting webapp",
  1372. 'com.example.department': "Finance",
  1373. 'com.example.label-with-empty-value': "",
  1374. }
  1375. compose_labels = {
  1376. LABEL_ONE_OFF: 'False',
  1377. LABEL_PROJECT: 'composetest',
  1378. LABEL_SERVICE: 'web',
  1379. LABEL_VERSION: __version__,
  1380. LABEL_CONTAINER_NUMBER: '1'
  1381. }
  1382. expected = dict(labels_dict, **compose_labels)
  1383. service = self.create_service('web', labels=labels_dict)
  1384. ctnr = create_and_start_container(service)
  1385. labels = ctnr.labels.items()
  1386. for pair in expected.items():
  1387. assert pair in labels
  1388. def test_empty_labels(self):
  1389. labels_dict = {'foo': '', 'bar': ''}
  1390. service = self.create_service('web', labels=labels_dict)
  1391. labels = create_and_start_container(service).labels.items()
  1392. for name in labels_dict:
  1393. assert (name, '') in labels
  1394. def test_stop_signal(self):
  1395. stop_signal = 'SIGINT'
  1396. service = self.create_service('web', stop_signal=stop_signal)
  1397. container = create_and_start_container(service)
  1398. assert container.stop_signal == stop_signal
  1399. def test_custom_container_name(self):
  1400. service = self.create_service('web', container_name='my-web-container')
  1401. assert service.custom_container_name == 'my-web-container'
  1402. container = create_and_start_container(service)
  1403. assert container.name == 'my-web-container'
  1404. one_off_container = service.create_container(one_off=True)
  1405. assert one_off_container.name != 'my-web-container'
  1406. @pytest.mark.skipif(True, reason="Broken on 1.11.0 - 17.03.0")
  1407. def test_log_drive_invalid(self):
  1408. service = self.create_service('web', logging={'driver': 'xxx'})
  1409. expected_error_msg = "logger: no log driver named 'xxx' is registered"
  1410. with pytest.raises(APIError) as excinfo:
  1411. create_and_start_container(service)
  1412. assert re.search(expected_error_msg, excinfo.value)
  1413. def test_log_drive_empty_default_jsonfile(self):
  1414. service = self.create_service('web')
  1415. log_config = create_and_start_container(service).log_config
  1416. assert 'json-file' == log_config['Type']
  1417. assert not log_config['Config']
  1418. def test_log_drive_none(self):
  1419. service = self.create_service('web', logging={'driver': 'none'})
  1420. log_config = create_and_start_container(service).log_config
  1421. assert 'none' == log_config['Type']
  1422. assert not log_config['Config']
  1423. def test_devices(self):
  1424. service = self.create_service('web', devices=["/dev/random:/dev/mapped-random"])
  1425. device_config = create_and_start_container(service).get('HostConfig.Devices')
  1426. device_dict = {
  1427. 'PathOnHost': '/dev/random',
  1428. 'CgroupPermissions': 'rwm',
  1429. 'PathInContainer': '/dev/mapped-random'
  1430. }
  1431. assert 1 == len(device_config)
  1432. assert device_dict == device_config[0]
  1433. def test_duplicate_containers(self):
  1434. service = self.create_service('web')
  1435. options = service._get_container_create_options({}, service._next_container_number())
  1436. original = Container.create(service.client, **options)
  1437. assert set(service.containers(stopped=True)) == set([original])
  1438. assert set(service.duplicate_containers()) == set()
  1439. options['name'] = 'temporary_container_name'
  1440. duplicate = Container.create(service.client, **options)
  1441. assert set(service.containers(stopped=True)) == set([original, duplicate])
  1442. assert set(service.duplicate_containers()) == set([duplicate])
  1443. def converge(service, strategy=ConvergenceStrategy.changed):
  1444. """Create a converge plan from a strategy and execute the plan."""
  1445. plan = service.convergence_plan(strategy)
  1446. return service.execute_convergence_plan(plan, timeout=1)
  1447. class ConfigHashTest(DockerClientTestCase):
  1448. def test_no_config_hash_when_one_off(self):
  1449. web = self.create_service('web')
  1450. container = web.create_container(one_off=True)
  1451. assert LABEL_CONFIG_HASH not in container.labels
  1452. def test_no_config_hash_when_overriding_options(self):
  1453. web = self.create_service('web')
  1454. container = web.create_container(environment={'FOO': '1'})
  1455. assert LABEL_CONFIG_HASH not in container.labels
  1456. def test_config_hash_with_custom_labels(self):
  1457. web = self.create_service('web', labels={'foo': '1'})
  1458. container = converge(web)[0]
  1459. assert LABEL_CONFIG_HASH in container.labels
  1460. assert 'foo' in container.labels
  1461. def test_config_hash_sticks_around(self):
  1462. web = self.create_service('web', command=["top"])
  1463. container = converge(web)[0]
  1464. assert LABEL_CONFIG_HASH in container.labels
  1465. web = self.create_service('web', command=["top", "-d", "1"])
  1466. container = converge(web)[0]
  1467. assert LABEL_CONFIG_HASH in container.labels