1
0

service_test.py 68 KB

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