service_test.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  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 == 'composetest_foo_1'
  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 'composetest_bar_1' in names
  68. assert 'composetest_bar_2' 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 == 'composetest_web_1'
  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 == 'composetest_db_run_1'
  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 == 'composetest_db_run_1'
  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_duplicate_volume_trailing_slash(self):
  373. """
  374. When an image specifies a volume, and the Compose file specifies a host path
  375. but adds a trailing slash, make sure that we don't create duplicate binds.
  376. """
  377. host_path = '/tmp/data'
  378. container_path = '/data'
  379. volumes = [VolumeSpec.parse('{}:{}/'.format(host_path, container_path))]
  380. tmp_container = self.client.create_container(
  381. 'busybox', 'true',
  382. volumes={container_path: {}},
  383. labels={'com.docker.compose.test_image': 'true'},
  384. host_config={}
  385. )
  386. image = self.client.commit(tmp_container)['Id']
  387. service = self.create_service('db', image=image, volumes=volumes)
  388. old_container = create_and_start_container(service)
  389. assert old_container.get('Config.Volumes') == {container_path: {}}
  390. service = self.create_service('db', image=image, volumes=volumes)
  391. new_container = service.recreate_container(old_container)
  392. assert new_container.get('Config.Volumes') == {container_path: {}}
  393. assert service.containers(stopped=False) == [new_container]
  394. def test_create_container_with_volumes_from(self):
  395. volume_service = self.create_service('data')
  396. volume_container_1 = volume_service.create_container()
  397. volume_container_2 = Container.create(
  398. self.client,
  399. image='busybox:latest',
  400. command=["top"],
  401. labels={LABEL_PROJECT: 'composetest'},
  402. host_config={},
  403. environment=['affinity:container=={}'.format(volume_container_1.id)],
  404. )
  405. host_service = self.create_service(
  406. 'host',
  407. volumes_from=[
  408. VolumeFromSpec(volume_service, 'rw', 'service'),
  409. VolumeFromSpec(volume_container_2, 'rw', 'container')
  410. ],
  411. environment=['affinity:container=={}'.format(volume_container_1.id)],
  412. )
  413. host_container = host_service.create_container()
  414. host_service.start_container(host_container)
  415. assert volume_container_1.id + ':rw' in host_container.get('HostConfig.VolumesFrom')
  416. assert volume_container_2.id + ':rw' in host_container.get('HostConfig.VolumesFrom')
  417. def test_execute_convergence_plan_recreate(self):
  418. service = self.create_service(
  419. 'db',
  420. environment={'FOO': '1'},
  421. volumes=[VolumeSpec.parse('/etc')],
  422. entrypoint=['top'],
  423. command=['-d', '1']
  424. )
  425. old_container = service.create_container()
  426. assert old_container.get('Config.Entrypoint') == ['top']
  427. assert old_container.get('Config.Cmd') == ['-d', '1']
  428. assert 'FOO=1' in old_container.get('Config.Env')
  429. assert old_container.name == 'composetest_db_1'
  430. service.start_container(old_container)
  431. old_container.inspect() # reload volume data
  432. volume_path = old_container.get_mount('/etc')['Source']
  433. num_containers_before = len(self.client.containers(all=True))
  434. service.options['environment']['FOO'] = '2'
  435. new_container, = service.execute_convergence_plan(
  436. ConvergencePlan('recreate', [old_container]))
  437. assert new_container.get('Config.Entrypoint') == ['top']
  438. assert new_container.get('Config.Cmd') == ['-d', '1']
  439. assert 'FOO=2' in new_container.get('Config.Env')
  440. assert new_container.name == 'composetest_db_1'
  441. assert new_container.get_mount('/etc')['Source'] == volume_path
  442. if not is_cluster(self.client):
  443. assert (
  444. 'affinity:container==%s' % old_container.id in
  445. new_container.get('Config.Env')
  446. )
  447. else:
  448. # In Swarm, the env marker is consumed and the container should be deployed
  449. # on the same node.
  450. assert old_container.get('Node.Name') == new_container.get('Node.Name')
  451. assert len(self.client.containers(all=True)) == num_containers_before
  452. assert old_container.id != new_container.id
  453. with pytest.raises(APIError):
  454. self.client.inspect_container(old_container.id)
  455. def test_execute_convergence_plan_recreate_change_mount_target(self):
  456. service = self.create_service(
  457. 'db',
  458. volumes=[MountSpec(target='/app1', type='volume')],
  459. entrypoint=['top'], command=['-d', '1']
  460. )
  461. old_container = create_and_start_container(service)
  462. assert (
  463. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  464. ['/app1']
  465. )
  466. service.options['volumes'] = [MountSpec(target='/app2', type='volume')]
  467. new_container, = service.execute_convergence_plan(
  468. ConvergencePlan('recreate', [old_container])
  469. )
  470. assert (
  471. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  472. ['/app2']
  473. )
  474. def test_execute_convergence_plan_recreate_twice(self):
  475. service = self.create_service(
  476. 'db',
  477. volumes=[VolumeSpec.parse('/etc')],
  478. entrypoint=['top'],
  479. command=['-d', '1'])
  480. orig_container = service.create_container()
  481. service.start_container(orig_container)
  482. orig_container.inspect() # reload volume data
  483. volume_path = orig_container.get_mount('/etc')['Source']
  484. # Do this twice to reproduce the bug
  485. for _ in range(2):
  486. new_container, = service.execute_convergence_plan(
  487. ConvergencePlan('recreate', [orig_container]))
  488. assert new_container.get_mount('/etc')['Source'] == volume_path
  489. if not is_cluster(self.client):
  490. assert ('affinity:container==%s' % orig_container.id in
  491. new_container.get('Config.Env'))
  492. else:
  493. # In Swarm, the env marker is consumed and the container should be deployed
  494. # on the same node.
  495. assert orig_container.get('Node.Name') == new_container.get('Node.Name')
  496. orig_container = new_container
  497. @v2_3_only()
  498. def test_execute_convergence_plan_recreate_twice_with_mount(self):
  499. service = self.create_service(
  500. 'db',
  501. volumes=[MountSpec(target='/etc', type='volume')],
  502. entrypoint=['top'],
  503. command=['-d', '1']
  504. )
  505. orig_container = service.create_container()
  506. service.start_container(orig_container)
  507. orig_container.inspect() # reload volume data
  508. volume_path = orig_container.get_mount('/etc')['Source']
  509. # Do this twice to reproduce the bug
  510. for _ in range(2):
  511. new_container, = service.execute_convergence_plan(
  512. ConvergencePlan('recreate', [orig_container])
  513. )
  514. assert new_container.get_mount('/etc')['Source'] == volume_path
  515. if not is_cluster(self.client):
  516. assert ('affinity:container==%s' % orig_container.id in
  517. new_container.get('Config.Env'))
  518. else:
  519. # In Swarm, the env marker is consumed and the container should be deployed
  520. # on the same node.
  521. assert orig_container.get('Node.Name') == new_container.get('Node.Name')
  522. orig_container = new_container
  523. def test_execute_convergence_plan_when_containers_are_stopped(self):
  524. service = self.create_service(
  525. 'db',
  526. environment={'FOO': '1'},
  527. volumes=[VolumeSpec.parse('/var/db')],
  528. entrypoint=['top'],
  529. command=['-d', '1']
  530. )
  531. service.create_container()
  532. containers = service.containers(stopped=True)
  533. assert len(containers) == 1
  534. container, = containers
  535. assert not container.is_running
  536. service.execute_convergence_plan(ConvergencePlan('start', [container]))
  537. containers = service.containers()
  538. assert len(containers) == 1
  539. container.inspect()
  540. assert container == containers[0]
  541. assert container.is_running
  542. def test_execute_convergence_plan_with_image_declared_volume(self):
  543. service = Service(
  544. project='composetest',
  545. name='db',
  546. client=self.client,
  547. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  548. )
  549. old_container = create_and_start_container(service)
  550. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  551. volume_path = old_container.get_mount('/data')['Source']
  552. new_container, = service.execute_convergence_plan(
  553. ConvergencePlan('recreate', [old_container]))
  554. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  555. assert new_container.get_mount('/data')['Source'] == volume_path
  556. def test_execute_convergence_plan_with_image_declared_volume_renew(self):
  557. service = Service(
  558. project='composetest',
  559. name='db',
  560. client=self.client,
  561. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  562. )
  563. old_container = create_and_start_container(service)
  564. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  565. volume_path = old_container.get_mount('/data')['Source']
  566. new_container, = service.execute_convergence_plan(
  567. ConvergencePlan('recreate', [old_container]), renew_anonymous_volumes=True
  568. )
  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_when_image_volume_masks_config(self):
  572. service = self.create_service(
  573. 'db',
  574. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  575. )
  576. old_container = create_and_start_container(service)
  577. assert [mount['Destination'] for mount in old_container.get('Mounts')] == ['/data']
  578. volume_path = old_container.get_mount('/data')['Source']
  579. service.options['volumes'] = [VolumeSpec.parse('/tmp:/data')]
  580. with mock.patch('compose.service.log') as mock_log:
  581. new_container, = service.execute_convergence_plan(
  582. ConvergencePlan('recreate', [old_container]))
  583. mock_log.warn.assert_called_once_with(mock.ANY)
  584. _, args, kwargs = mock_log.warn.mock_calls[0]
  585. assert "Service \"db\" is using volume \"/data\" from the previous container" in args[0]
  586. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  587. assert new_container.get_mount('/data')['Source'] == volume_path
  588. def test_execute_convergence_plan_when_host_volume_is_removed(self):
  589. host_path = '/tmp/host-path'
  590. service = self.create_service(
  591. 'db',
  592. build={'context': 'tests/fixtures/dockerfile-with-volume'},
  593. volumes=[VolumeSpec(host_path, '/data', 'rw')])
  594. old_container = create_and_start_container(service)
  595. assert (
  596. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  597. ['/data']
  598. )
  599. service.options['volumes'] = []
  600. with mock.patch('compose.service.log', autospec=True) as mock_log:
  601. new_container, = service.execute_convergence_plan(
  602. ConvergencePlan('recreate', [old_container]))
  603. assert not mock_log.warn.called
  604. assert (
  605. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  606. ['/data']
  607. )
  608. assert new_container.get_mount('/data')['Source'] != host_path
  609. def test_execute_convergence_plan_anonymous_volume_renew(self):
  610. service = self.create_service(
  611. 'db',
  612. image='busybox',
  613. volumes=[VolumeSpec(None, '/data', 'rw')])
  614. old_container = create_and_start_container(service)
  615. assert (
  616. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  617. ['/data']
  618. )
  619. volume_path = old_container.get_mount('/data')['Source']
  620. new_container, = service.execute_convergence_plan(
  621. ConvergencePlan('recreate', [old_container]),
  622. renew_anonymous_volumes=True
  623. )
  624. assert (
  625. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  626. ['/data']
  627. )
  628. assert new_container.get_mount('/data')['Source'] != volume_path
  629. def test_execute_convergence_plan_anonymous_volume_recreate_then_renew(self):
  630. service = self.create_service(
  631. 'db',
  632. image='busybox',
  633. volumes=[VolumeSpec(None, '/data', 'rw')])
  634. old_container = create_and_start_container(service)
  635. assert (
  636. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  637. ['/data']
  638. )
  639. volume_path = old_container.get_mount('/data')['Source']
  640. mid_container, = service.execute_convergence_plan(
  641. ConvergencePlan('recreate', [old_container]),
  642. )
  643. assert (
  644. [mount['Destination'] for mount in mid_container.get('Mounts')] ==
  645. ['/data']
  646. )
  647. assert mid_container.get_mount('/data')['Source'] == volume_path
  648. new_container, = service.execute_convergence_plan(
  649. ConvergencePlan('recreate', [mid_container]),
  650. renew_anonymous_volumes=True
  651. )
  652. assert (
  653. [mount['Destination'] for mount in new_container.get('Mounts')] ==
  654. ['/data']
  655. )
  656. assert new_container.get_mount('/data')['Source'] != volume_path
  657. def test_execute_convergence_plan_without_start(self):
  658. service = self.create_service(
  659. 'db',
  660. build={'context': 'tests/fixtures/dockerfile-with-volume'}
  661. )
  662. containers = service.execute_convergence_plan(ConvergencePlan('create', []), start=False)
  663. service_containers = service.containers(stopped=True)
  664. assert len(service_containers) == 1
  665. assert not service_containers[0].is_running
  666. containers = service.execute_convergence_plan(
  667. ConvergencePlan('recreate', containers),
  668. start=False)
  669. service_containers = service.containers(stopped=True)
  670. assert len(service_containers) == 1
  671. assert not service_containers[0].is_running
  672. service.execute_convergence_plan(ConvergencePlan('start', containers), start=False)
  673. service_containers = service.containers(stopped=True)
  674. assert len(service_containers) == 1
  675. assert not service_containers[0].is_running
  676. def test_execute_convergence_plan_image_with_volume_is_removed(self):
  677. service = self.create_service(
  678. 'db', build={'context': 'tests/fixtures/dockerfile-with-volume'}
  679. )
  680. old_container = create_and_start_container(service)
  681. assert (
  682. [mount['Destination'] for mount in old_container.get('Mounts')] ==
  683. ['/data']
  684. )
  685. volume_path = old_container.get_mount('/data')['Source']
  686. old_container.stop()
  687. self.client.remove_image(service.image(), force=True)
  688. service.ensure_image_exists()
  689. with pytest.raises(ImageNotFound):
  690. service.execute_convergence_plan(
  691. ConvergencePlan('recreate', [old_container])
  692. )
  693. old_container.inspect() # retrieve new name from server
  694. new_container, = service.execute_convergence_plan(
  695. ConvergencePlan('recreate', [old_container]),
  696. reset_container_image=True
  697. )
  698. assert [mount['Destination'] for mount in new_container.get('Mounts')] == ['/data']
  699. assert new_container.get_mount('/data')['Source'] == volume_path
  700. def test_start_container_passes_through_options(self):
  701. db = self.create_service('db')
  702. create_and_start_container(db, environment={'FOO': 'BAR'})
  703. assert db.containers()[0].environment['FOO'] == 'BAR'
  704. def test_start_container_inherits_options_from_constructor(self):
  705. db = self.create_service('db', environment={'FOO': 'BAR'})
  706. create_and_start_container(db)
  707. assert db.containers()[0].environment['FOO'] == 'BAR'
  708. @no_cluster('No legacy links support in Swarm')
  709. def test_start_container_creates_links(self):
  710. db = self.create_service('db')
  711. web = self.create_service('web', links=[(db, None)])
  712. create_and_start_container(db)
  713. create_and_start_container(db)
  714. create_and_start_container(web)
  715. assert set(get_links(web.containers()[0])) == set([
  716. 'composetest_db_1', 'db_1',
  717. 'composetest_db_2', 'db_2',
  718. 'db'
  719. ])
  720. @no_cluster('No legacy links support in Swarm')
  721. def test_start_container_creates_links_with_names(self):
  722. db = self.create_service('db')
  723. web = self.create_service('web', links=[(db, 'custom_link_name')])
  724. create_and_start_container(db)
  725. create_and_start_container(db)
  726. create_and_start_container(web)
  727. assert set(get_links(web.containers()[0])) == set([
  728. 'composetest_db_1', 'db_1',
  729. 'composetest_db_2', 'db_2',
  730. 'custom_link_name'
  731. ])
  732. @no_cluster('No legacy links support in Swarm')
  733. def test_start_container_with_external_links(self):
  734. db = self.create_service('db')
  735. web = self.create_service('web', external_links=['composetest_db_1',
  736. 'composetest_db_2',
  737. 'composetest_db_3:db_3'])
  738. for _ in range(3):
  739. create_and_start_container(db)
  740. create_and_start_container(web)
  741. assert set(get_links(web.containers()[0])) == set([
  742. 'composetest_db_1',
  743. 'composetest_db_2',
  744. 'db_3'
  745. ])
  746. @no_cluster('No legacy links support in Swarm')
  747. def test_start_normal_container_does_not_create_links_to_its_own_service(self):
  748. db = self.create_service('db')
  749. create_and_start_container(db)
  750. create_and_start_container(db)
  751. c = create_and_start_container(db)
  752. assert set(get_links(c)) == set([])
  753. @no_cluster('No legacy links support in Swarm')
  754. def test_start_one_off_container_creates_links_to_its_own_service(self):
  755. db = self.create_service('db')
  756. create_and_start_container(db)
  757. create_and_start_container(db)
  758. c = create_and_start_container(db, one_off=OneOffFilter.only)
  759. assert set(get_links(c)) == set([
  760. 'composetest_db_1', 'db_1',
  761. 'composetest_db_2', 'db_2',
  762. 'db'
  763. ])
  764. def test_start_container_builds_images(self):
  765. service = Service(
  766. name='test',
  767. client=self.client,
  768. build={'context': 'tests/fixtures/simple-dockerfile'},
  769. project='composetest',
  770. )
  771. container = create_and_start_container(service)
  772. container.wait()
  773. assert b'success' in container.logs()
  774. assert len(self.client.images(name='composetest_test')) >= 1
  775. def test_start_container_uses_tagged_image_if_it_exists(self):
  776. self.check_build('tests/fixtures/simple-dockerfile', tag='composetest_test')
  777. service = Service(
  778. name='test',
  779. client=self.client,
  780. build={'context': 'this/does/not/exist/and/will/throw/error'},
  781. project='composetest',
  782. )
  783. container = create_and_start_container(service)
  784. container.wait()
  785. assert b'success' in container.logs()
  786. def test_start_container_creates_ports(self):
  787. service = self.create_service('web', ports=[8000])
  788. container = create_and_start_container(service).inspect()
  789. assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/tcp']
  790. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] != '8000'
  791. def test_build(self):
  792. base_dir = tempfile.mkdtemp()
  793. self.addCleanup(shutil.rmtree, base_dir)
  794. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  795. f.write("FROM busybox\n")
  796. service = self.create_service('web', build={'context': base_dir})
  797. service.build()
  798. self.addCleanup(self.client.remove_image, service.image_name)
  799. assert self.client.inspect_image('composetest_web')
  800. def test_build_non_ascii_filename(self):
  801. base_dir = tempfile.mkdtemp()
  802. self.addCleanup(shutil.rmtree, base_dir)
  803. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  804. f.write("FROM busybox\n")
  805. with open(os.path.join(base_dir.encode('utf8'), b'foo\xE2bar'), 'w') as f:
  806. f.write("hello world\n")
  807. service = self.create_service('web', build={'context': text_type(base_dir)})
  808. service.build()
  809. self.addCleanup(self.client.remove_image, service.image_name)
  810. assert self.client.inspect_image('composetest_web')
  811. def test_build_with_image_name(self):
  812. base_dir = tempfile.mkdtemp()
  813. self.addCleanup(shutil.rmtree, base_dir)
  814. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  815. f.write("FROM busybox\n")
  816. image_name = 'examples/composetest:latest'
  817. self.addCleanup(self.client.remove_image, image_name)
  818. self.create_service('web', build={'context': base_dir}, image=image_name).build()
  819. assert self.client.inspect_image(image_name)
  820. def test_build_with_git_url(self):
  821. build_url = "https://github.com/dnephin/docker-build-from-url.git"
  822. service = self.create_service('buildwithurl', build={'context': build_url})
  823. self.addCleanup(self.client.remove_image, service.image_name)
  824. service.build()
  825. assert service.image()
  826. def test_build_with_build_args(self):
  827. base_dir = tempfile.mkdtemp()
  828. self.addCleanup(shutil.rmtree, base_dir)
  829. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  830. f.write("FROM busybox\n")
  831. f.write("ARG build_version\n")
  832. f.write("RUN echo ${build_version}\n")
  833. service = self.create_service('buildwithargs',
  834. build={'context': text_type(base_dir),
  835. 'args': {"build_version": "1"}})
  836. service.build()
  837. self.addCleanup(self.client.remove_image, service.image_name)
  838. assert service.image()
  839. assert "build_version=1" in service.image()['ContainerConfig']['Cmd']
  840. def test_build_with_build_args_override(self):
  841. base_dir = tempfile.mkdtemp()
  842. self.addCleanup(shutil.rmtree, base_dir)
  843. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  844. f.write("FROM busybox\n")
  845. f.write("ARG build_version\n")
  846. f.write("RUN echo ${build_version}\n")
  847. service = self.create_service('buildwithargs',
  848. build={'context': text_type(base_dir),
  849. 'args': {"build_version": "1"}})
  850. service.build(build_args_override={'build_version': '2'})
  851. self.addCleanup(self.client.remove_image, service.image_name)
  852. assert service.image()
  853. assert "build_version=2" in service.image()['ContainerConfig']['Cmd']
  854. def test_build_with_build_labels(self):
  855. base_dir = tempfile.mkdtemp()
  856. self.addCleanup(shutil.rmtree, base_dir)
  857. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  858. f.write('FROM busybox\n')
  859. service = self.create_service('buildlabels', build={
  860. 'context': text_type(base_dir),
  861. 'labels': {'com.docker.compose.test': 'true'}
  862. })
  863. service.build()
  864. self.addCleanup(self.client.remove_image, service.image_name)
  865. assert service.image()
  866. assert service.image()['Config']['Labels']['com.docker.compose.test'] == 'true'
  867. @no_cluster('Container networks not on Swarm')
  868. def test_build_with_network(self):
  869. base_dir = tempfile.mkdtemp()
  870. self.addCleanup(shutil.rmtree, base_dir)
  871. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  872. f.write('FROM busybox\n')
  873. f.write('RUN ping -c1 google.local\n')
  874. net_container = self.client.create_container(
  875. 'busybox', 'top', host_config=self.client.create_host_config(
  876. extra_hosts={'google.local': '127.0.0.1'}
  877. ), name='composetest_build_network'
  878. )
  879. self.addCleanup(self.client.remove_container, net_container, force=True)
  880. self.client.start(net_container)
  881. service = self.create_service('buildwithnet', build={
  882. 'context': text_type(base_dir),
  883. 'network': 'container:{}'.format(net_container['Id'])
  884. })
  885. service.build()
  886. self.addCleanup(self.client.remove_image, service.image_name)
  887. assert service.image()
  888. @v2_3_only()
  889. @no_cluster('Not supported on UCP 2.2.0-beta1') # FIXME: remove once support is added
  890. def test_build_with_target(self):
  891. self.require_api_version('1.30')
  892. base_dir = tempfile.mkdtemp()
  893. self.addCleanup(shutil.rmtree, base_dir)
  894. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  895. f.write('FROM busybox as one\n')
  896. f.write('LABEL com.docker.compose.test=true\n')
  897. f.write('LABEL com.docker.compose.test.target=one\n')
  898. f.write('FROM busybox as two\n')
  899. f.write('LABEL com.docker.compose.test.target=two\n')
  900. service = self.create_service('buildtarget', build={
  901. 'context': text_type(base_dir),
  902. 'target': 'one'
  903. })
  904. service.build()
  905. assert service.image()
  906. assert service.image()['Config']['Labels']['com.docker.compose.test.target'] == 'one'
  907. @v2_3_only()
  908. def test_build_with_extra_hosts(self):
  909. self.require_api_version('1.27')
  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('\n'.join([
  914. 'FROM busybox',
  915. 'RUN ping -c1 foobar',
  916. 'RUN ping -c1 baz',
  917. ]))
  918. service = self.create_service('build_extra_hosts', build={
  919. 'context': text_type(base_dir),
  920. 'extra_hosts': {
  921. 'foobar': '127.0.0.1',
  922. 'baz': '127.0.0.1'
  923. }
  924. })
  925. service.build()
  926. assert service.image()
  927. def test_start_container_stays_unprivileged(self):
  928. service = self.create_service('web')
  929. container = create_and_start_container(service).inspect()
  930. assert container['HostConfig']['Privileged'] is False
  931. def test_start_container_becomes_privileged(self):
  932. service = self.create_service('web', privileged=True)
  933. container = create_and_start_container(service).inspect()
  934. assert container['HostConfig']['Privileged'] is True
  935. def test_expose_does_not_publish_ports(self):
  936. service = self.create_service('web', expose=["8000"])
  937. container = create_and_start_container(service).inspect()
  938. assert container['NetworkSettings']['Ports'] == {'8000/tcp': None}
  939. def test_start_container_creates_port_with_explicit_protocol(self):
  940. service = self.create_service('web', ports=['8000/udp'])
  941. container = create_and_start_container(service).inspect()
  942. assert list(container['NetworkSettings']['Ports'].keys()) == ['8000/udp']
  943. def test_start_container_creates_fixed_external_ports(self):
  944. service = self.create_service('web', ports=['8000:8000'])
  945. container = create_and_start_container(service).inspect()
  946. assert '8000/tcp' in container['NetworkSettings']['Ports']
  947. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8000'
  948. def test_start_container_creates_fixed_external_ports_when_it_is_different_to_internal_port(self):
  949. service = self.create_service('web', ports=['8001:8000'])
  950. container = create_and_start_container(service).inspect()
  951. assert '8000/tcp' in container['NetworkSettings']['Ports']
  952. assert container['NetworkSettings']['Ports']['8000/tcp'][0]['HostPort'] == '8001'
  953. def test_port_with_explicit_interface(self):
  954. service = self.create_service('web', ports=[
  955. '127.0.0.1:8001:8000',
  956. '0.0.0.0:9001:9000/udp',
  957. ])
  958. container = create_and_start_container(service).inspect()
  959. assert container['NetworkSettings']['Ports']['8000/tcp'] == [{
  960. 'HostIp': '127.0.0.1',
  961. 'HostPort': '8001',
  962. }]
  963. assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostPort'] == '9001'
  964. if not is_cluster(self.client):
  965. assert container['NetworkSettings']['Ports']['9000/udp'][0]['HostIp'] == '0.0.0.0'
  966. # self.assertEqual(container['NetworkSettings']['Ports'], {
  967. # '8000/tcp': [
  968. # {
  969. # 'HostIp': '127.0.0.1',
  970. # 'HostPort': '8001',
  971. # },
  972. # ],
  973. # '9000/udp': [
  974. # {
  975. # 'HostIp': '0.0.0.0',
  976. # 'HostPort': '9001',
  977. # },
  978. # ],
  979. # })
  980. def test_create_with_image_id(self):
  981. # Get image id for the current busybox:latest
  982. pull_busybox(self.client)
  983. image_id = self.client.inspect_image('busybox:latest')['Id'][:12]
  984. service = self.create_service('foo', image=image_id)
  985. service.create_container()
  986. def test_scale(self):
  987. service = self.create_service('web')
  988. service.scale(1)
  989. assert len(service.containers()) == 1
  990. # Ensure containers don't have stdout or stdin connected
  991. container = service.containers()[0]
  992. config = container.inspect()['Config']
  993. assert not config['AttachStderr']
  994. assert not config['AttachStdout']
  995. assert not config['AttachStdin']
  996. service.scale(3)
  997. assert len(service.containers()) == 3
  998. service.scale(1)
  999. assert len(service.containers()) == 1
  1000. service.scale(0)
  1001. assert len(service.containers()) == 0
  1002. @pytest.mark.skipif(
  1003. SWARM_SKIP_CONTAINERS_ALL,
  1004. reason='Swarm /containers/json bug'
  1005. )
  1006. def test_scale_with_stopped_containers(self):
  1007. """
  1008. Given there are some stopped containers and scale is called with a
  1009. desired number that is the same as the number of stopped containers,
  1010. test that those containers are restarted and not removed/recreated.
  1011. """
  1012. service = self.create_service('web')
  1013. next_number = service._next_container_number()
  1014. valid_numbers = [next_number, next_number + 1]
  1015. service.create_container(number=next_number)
  1016. service.create_container(number=next_number + 1)
  1017. ParallelStreamWriter.instance = None
  1018. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1019. service.scale(2)
  1020. for container in service.containers():
  1021. assert container.is_running
  1022. assert container.number in valid_numbers
  1023. captured_output = mock_stderr.getvalue()
  1024. assert 'Creating' not in captured_output
  1025. assert 'Starting' in captured_output
  1026. def test_scale_with_stopped_containers_and_needing_creation(self):
  1027. """
  1028. Given there are some stopped containers and scale is called with a
  1029. desired number that is greater than the number of stopped containers,
  1030. test that those containers are restarted and required number are created.
  1031. """
  1032. service = self.create_service('web')
  1033. next_number = service._next_container_number()
  1034. service.create_container(number=next_number, quiet=True)
  1035. for container in service.containers():
  1036. assert not container.is_running
  1037. ParallelStreamWriter.instance = None
  1038. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1039. service.scale(2)
  1040. assert len(service.containers()) == 2
  1041. for container in service.containers():
  1042. assert container.is_running
  1043. captured_output = mock_stderr.getvalue()
  1044. assert 'Creating' in captured_output
  1045. assert 'Starting' in captured_output
  1046. def test_scale_with_api_error(self):
  1047. """Test that when scaling if the API returns an error, that error is handled
  1048. and the remaining threads continue.
  1049. """
  1050. service = self.create_service('web')
  1051. next_number = service._next_container_number()
  1052. service.create_container(number=next_number, quiet=True)
  1053. with mock.patch(
  1054. 'compose.container.Container.create',
  1055. side_effect=APIError(
  1056. message="testing",
  1057. response={},
  1058. explanation="Boom")):
  1059. with mock.patch('sys.stderr', new_callable=StringIO) as mock_stderr:
  1060. with pytest.raises(OperationFailedError):
  1061. service.scale(3)
  1062. assert len(service.containers()) == 1
  1063. assert service.containers()[0].is_running
  1064. assert (
  1065. "ERROR: for composetest_web_2 Cannot create container for service"
  1066. " web: Boom" in mock_stderr.getvalue()
  1067. )
  1068. def test_scale_with_unexpected_exception(self):
  1069. """Test that when scaling if the API returns an error, that is not of type
  1070. APIError, that error is re-raised.
  1071. """
  1072. service = self.create_service('web')
  1073. next_number = service._next_container_number()
  1074. service.create_container(number=next_number, quiet=True)
  1075. with mock.patch(
  1076. 'compose.container.Container.create',
  1077. side_effect=ValueError("BOOM")
  1078. ):
  1079. with pytest.raises(ValueError):
  1080. service.scale(3)
  1081. assert len(service.containers()) == 1
  1082. assert service.containers()[0].is_running
  1083. @mock.patch('compose.service.log')
  1084. def test_scale_with_desired_number_already_achieved(self, mock_log):
  1085. """
  1086. Test that calling scale with a desired number that is equal to the
  1087. number of containers already running results in no change.
  1088. """
  1089. service = self.create_service('web')
  1090. next_number = service._next_container_number()
  1091. container = service.create_container(number=next_number, quiet=True)
  1092. container.start()
  1093. container.inspect()
  1094. assert container.is_running
  1095. assert len(service.containers()) == 1
  1096. service.scale(1)
  1097. assert len(service.containers()) == 1
  1098. container.inspect()
  1099. assert container.is_running
  1100. captured_output = mock_log.info.call_args[0]
  1101. assert 'Desired container number already achieved' in captured_output
  1102. @mock.patch('compose.service.log')
  1103. def test_scale_with_custom_container_name_outputs_warning(self, mock_log):
  1104. """Test that calling scale on a service that has a custom container name
  1105. results in warning output.
  1106. """
  1107. service = self.create_service('app', container_name='custom-container')
  1108. assert service.custom_container_name == 'custom-container'
  1109. with pytest.raises(OperationFailedError):
  1110. service.scale(3)
  1111. captured_output = mock_log.warn.call_args[0][0]
  1112. assert len(service.containers()) == 1
  1113. assert "Remove the custom name to scale the service." in captured_output
  1114. def test_scale_sets_ports(self):
  1115. service = self.create_service('web', ports=['8000'])
  1116. service.scale(2)
  1117. containers = service.containers()
  1118. assert len(containers) == 2
  1119. for container in containers:
  1120. assert list(container.get('HostConfig.PortBindings')) == ['8000/tcp']
  1121. def test_scale_with_immediate_exit(self):
  1122. service = self.create_service('web', image='busybox', command='true')
  1123. service.scale(2)
  1124. assert len(service.containers(stopped=True)) == 2
  1125. def test_network_mode_none(self):
  1126. service = self.create_service('web', network_mode=NetworkMode('none'))
  1127. container = create_and_start_container(service)
  1128. assert container.get('HostConfig.NetworkMode') == 'none'
  1129. def test_network_mode_bridged(self):
  1130. service = self.create_service('web', network_mode=NetworkMode('bridge'))
  1131. container = create_and_start_container(service)
  1132. assert container.get('HostConfig.NetworkMode') == 'bridge'
  1133. def test_network_mode_host(self):
  1134. service = self.create_service('web', network_mode=NetworkMode('host'))
  1135. container = create_and_start_container(service)
  1136. assert container.get('HostConfig.NetworkMode') == 'host'
  1137. def test_pid_mode_none_defined(self):
  1138. service = self.create_service('web', pid_mode=None)
  1139. container = create_and_start_container(service)
  1140. assert container.get('HostConfig.PidMode') == ''
  1141. def test_pid_mode_host(self):
  1142. service = self.create_service('web', pid_mode=PidMode('host'))
  1143. container = create_and_start_container(service)
  1144. assert container.get('HostConfig.PidMode') == 'host'
  1145. @v2_1_only()
  1146. def test_userns_mode_none_defined(self):
  1147. service = self.create_service('web', userns_mode=None)
  1148. container = create_and_start_container(service)
  1149. assert container.get('HostConfig.UsernsMode') == ''
  1150. @v2_1_only()
  1151. def test_userns_mode_host(self):
  1152. service = self.create_service('web', userns_mode='host')
  1153. container = create_and_start_container(service)
  1154. assert container.get('HostConfig.UsernsMode') == 'host'
  1155. def test_dns_no_value(self):
  1156. service = self.create_service('web')
  1157. container = create_and_start_container(service)
  1158. assert container.get('HostConfig.Dns') is None
  1159. def test_dns_list(self):
  1160. service = self.create_service('web', dns=['8.8.8.8', '9.9.9.9'])
  1161. container = create_and_start_container(service)
  1162. assert container.get('HostConfig.Dns') == ['8.8.8.8', '9.9.9.9']
  1163. def test_mem_swappiness(self):
  1164. service = self.create_service('web', mem_swappiness=11)
  1165. container = create_and_start_container(service)
  1166. assert container.get('HostConfig.MemorySwappiness') == 11
  1167. def test_mem_reservation(self):
  1168. service = self.create_service('web', mem_reservation='20m')
  1169. container = create_and_start_container(service)
  1170. assert container.get('HostConfig.MemoryReservation') == 20 * 1024 * 1024
  1171. def test_restart_always_value(self):
  1172. service = self.create_service('web', restart={'Name': 'always'})
  1173. container = create_and_start_container(service)
  1174. assert container.get('HostConfig.RestartPolicy.Name') == 'always'
  1175. def test_oom_score_adj_value(self):
  1176. service = self.create_service('web', oom_score_adj=500)
  1177. container = create_and_start_container(service)
  1178. assert container.get('HostConfig.OomScoreAdj') == 500
  1179. def test_group_add_value(self):
  1180. service = self.create_service('web', group_add=["root", "1"])
  1181. container = create_and_start_container(service)
  1182. host_container_groupadd = container.get('HostConfig.GroupAdd')
  1183. assert "root" in host_container_groupadd
  1184. assert "1" in host_container_groupadd
  1185. def test_dns_opt_value(self):
  1186. service = self.create_service('web', dns_opt=["use-vc", "no-tld-query"])
  1187. container = create_and_start_container(service)
  1188. dns_opt = container.get('HostConfig.DnsOptions')
  1189. assert 'use-vc' in dns_opt
  1190. assert 'no-tld-query' in dns_opt
  1191. def test_restart_on_failure_value(self):
  1192. service = self.create_service('web', restart={
  1193. 'Name': 'on-failure',
  1194. 'MaximumRetryCount': 5
  1195. })
  1196. container = create_and_start_container(service)
  1197. assert container.get('HostConfig.RestartPolicy.Name') == 'on-failure'
  1198. assert container.get('HostConfig.RestartPolicy.MaximumRetryCount') == 5
  1199. def test_cap_add_list(self):
  1200. service = self.create_service('web', cap_add=['SYS_ADMIN', 'NET_ADMIN'])
  1201. container = create_and_start_container(service)
  1202. assert container.get('HostConfig.CapAdd') == ['SYS_ADMIN', 'NET_ADMIN']
  1203. def test_cap_drop_list(self):
  1204. service = self.create_service('web', cap_drop=['SYS_ADMIN', 'NET_ADMIN'])
  1205. container = create_and_start_container(service)
  1206. assert container.get('HostConfig.CapDrop') == ['SYS_ADMIN', 'NET_ADMIN']
  1207. def test_dns_search(self):
  1208. service = self.create_service('web', dns_search=['dc1.example.com', 'dc2.example.com'])
  1209. container = create_and_start_container(service)
  1210. assert container.get('HostConfig.DnsSearch') == ['dc1.example.com', 'dc2.example.com']
  1211. @v2_only()
  1212. def test_tmpfs(self):
  1213. service = self.create_service('web', tmpfs=['/run'])
  1214. container = create_and_start_container(service)
  1215. assert container.get('HostConfig.Tmpfs') == {'/run': ''}
  1216. def test_working_dir_param(self):
  1217. service = self.create_service('container', working_dir='/working/dir/sample')
  1218. container = service.create_container()
  1219. assert container.get('Config.WorkingDir') == '/working/dir/sample'
  1220. def test_split_env(self):
  1221. service = self.create_service(
  1222. 'web',
  1223. environment=['NORMAL=F1', 'CONTAINS_EQUALS=F=2', 'TRAILING_EQUALS='])
  1224. env = create_and_start_container(service).environment
  1225. for k, v in {'NORMAL': 'F1', 'CONTAINS_EQUALS': 'F=2', 'TRAILING_EQUALS': ''}.items():
  1226. assert env[k] == v
  1227. def test_env_from_file_combined_with_env(self):
  1228. service = self.create_service(
  1229. 'web',
  1230. environment=['ONE=1', 'TWO=2', 'THREE=3'],
  1231. env_file=['tests/fixtures/env/one.env', 'tests/fixtures/env/two.env'])
  1232. env = create_and_start_container(service).environment
  1233. for k, v in {
  1234. 'ONE': '1',
  1235. 'TWO': '2',
  1236. 'THREE': '3',
  1237. 'FOO': 'baz',
  1238. 'DOO': 'dah'
  1239. }.items():
  1240. assert env[k] == v
  1241. @v3_only()
  1242. def test_build_with_cachefrom(self):
  1243. base_dir = tempfile.mkdtemp()
  1244. self.addCleanup(shutil.rmtree, base_dir)
  1245. with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
  1246. f.write("FROM busybox\n")
  1247. service = self.create_service('cache_from',
  1248. build={'context': base_dir,
  1249. 'cache_from': ['build1']})
  1250. service.build()
  1251. self.addCleanup(self.client.remove_image, service.image_name)
  1252. assert service.image()
  1253. @mock.patch.dict(os.environ)
  1254. def test_resolve_env(self):
  1255. os.environ['FILE_DEF'] = 'E1'
  1256. os.environ['FILE_DEF_EMPTY'] = 'E2'
  1257. os.environ['ENV_DEF'] = 'E3'
  1258. service = self.create_service(
  1259. 'web',
  1260. environment={
  1261. 'FILE_DEF': 'F1',
  1262. 'FILE_DEF_EMPTY': '',
  1263. 'ENV_DEF': None,
  1264. 'NO_DEF': None
  1265. }
  1266. )
  1267. env = create_and_start_container(service).environment
  1268. for k, v in {
  1269. 'FILE_DEF': 'F1',
  1270. 'FILE_DEF_EMPTY': '',
  1271. 'ENV_DEF': 'E3',
  1272. 'NO_DEF': None
  1273. }.items():
  1274. assert env[k] == v
  1275. def test_with_high_enough_api_version_we_get_default_network_mode(self):
  1276. # TODO: remove this test once minimum docker version is 1.8.x
  1277. with mock.patch.object(self.client, '_version', '1.20'):
  1278. service = self.create_service('web')
  1279. service_config = service._get_container_host_config({})
  1280. assert service_config['NetworkMode'] == 'default'
  1281. def test_labels(self):
  1282. labels_dict = {
  1283. 'com.example.description': "Accounting webapp",
  1284. 'com.example.department': "Finance",
  1285. 'com.example.label-with-empty-value': "",
  1286. }
  1287. compose_labels = {
  1288. LABEL_CONTAINER_NUMBER: '1',
  1289. LABEL_ONE_OFF: 'False',
  1290. LABEL_PROJECT: 'composetest',
  1291. LABEL_SERVICE: 'web',
  1292. LABEL_VERSION: __version__,
  1293. }
  1294. expected = dict(labels_dict, **compose_labels)
  1295. service = self.create_service('web', labels=labels_dict)
  1296. labels = create_and_start_container(service).labels.items()
  1297. for pair in expected.items():
  1298. assert pair in labels
  1299. def test_empty_labels(self):
  1300. labels_dict = {'foo': '', 'bar': ''}
  1301. service = self.create_service('web', labels=labels_dict)
  1302. labels = create_and_start_container(service).labels.items()
  1303. for name in labels_dict:
  1304. assert (name, '') in labels
  1305. def test_stop_signal(self):
  1306. stop_signal = 'SIGINT'
  1307. service = self.create_service('web', stop_signal=stop_signal)
  1308. container = create_and_start_container(service)
  1309. assert container.stop_signal == stop_signal
  1310. def test_custom_container_name(self):
  1311. service = self.create_service('web', container_name='my-web-container')
  1312. assert service.custom_container_name == 'my-web-container'
  1313. container = create_and_start_container(service)
  1314. assert container.name == 'my-web-container'
  1315. one_off_container = service.create_container(one_off=True)
  1316. assert one_off_container.name != 'my-web-container'
  1317. @pytest.mark.skipif(True, reason="Broken on 1.11.0 - 17.03.0")
  1318. def test_log_drive_invalid(self):
  1319. service = self.create_service('web', logging={'driver': 'xxx'})
  1320. expected_error_msg = "logger: no log driver named 'xxx' is registered"
  1321. with pytest.raises(APIError) as excinfo:
  1322. create_and_start_container(service)
  1323. assert re.search(expected_error_msg, excinfo.value)
  1324. def test_log_drive_empty_default_jsonfile(self):
  1325. service = self.create_service('web')
  1326. log_config = create_and_start_container(service).log_config
  1327. assert 'json-file' == log_config['Type']
  1328. assert not log_config['Config']
  1329. def test_log_drive_none(self):
  1330. service = self.create_service('web', logging={'driver': 'none'})
  1331. log_config = create_and_start_container(service).log_config
  1332. assert 'none' == log_config['Type']
  1333. assert not log_config['Config']
  1334. def test_devices(self):
  1335. service = self.create_service('web', devices=["/dev/random:/dev/mapped-random"])
  1336. device_config = create_and_start_container(service).get('HostConfig.Devices')
  1337. device_dict = {
  1338. 'PathOnHost': '/dev/random',
  1339. 'CgroupPermissions': 'rwm',
  1340. 'PathInContainer': '/dev/mapped-random'
  1341. }
  1342. assert 1 == len(device_config)
  1343. assert device_dict == device_config[0]
  1344. def test_duplicate_containers(self):
  1345. service = self.create_service('web')
  1346. options = service._get_container_create_options({}, 1)
  1347. original = Container.create(service.client, **options)
  1348. assert set(service.containers(stopped=True)) == set([original])
  1349. assert set(service.duplicate_containers()) == set()
  1350. options['name'] = 'temporary_container_name'
  1351. duplicate = Container.create(service.client, **options)
  1352. assert set(service.containers(stopped=True)) == set([original, duplicate])
  1353. assert set(service.duplicate_containers()) == set([duplicate])
  1354. def converge(service, strategy=ConvergenceStrategy.changed):
  1355. """Create a converge plan from a strategy and execute the plan."""
  1356. plan = service.convergence_plan(strategy)
  1357. return service.execute_convergence_plan(plan, timeout=1)
  1358. class ConfigHashTest(DockerClientTestCase):
  1359. def test_no_config_hash_when_one_off(self):
  1360. web = self.create_service('web')
  1361. container = web.create_container(one_off=True)
  1362. assert LABEL_CONFIG_HASH not in container.labels
  1363. def test_no_config_hash_when_overriding_options(self):
  1364. web = self.create_service('web')
  1365. container = web.create_container(environment={'FOO': '1'})
  1366. assert LABEL_CONFIG_HASH not in container.labels
  1367. def test_config_hash_with_custom_labels(self):
  1368. web = self.create_service('web', labels={'foo': '1'})
  1369. container = converge(web)[0]
  1370. assert LABEL_CONFIG_HASH in container.labels
  1371. assert 'foo' in container.labels
  1372. def test_config_hash_sticks_around(self):
  1373. web = self.create_service('web', command=["top"])
  1374. container = converge(web)[0]
  1375. assert LABEL_CONFIG_HASH in container.labels
  1376. web = self.create_service('web', command=["top", "-d", "1"])
  1377. container = converge(web)[0]
  1378. assert LABEL_CONFIG_HASH in container.labels