1
0

service_test.py 68 KB

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