convergence_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "fmt"
  16. "strings"
  17. "testing"
  18. "github.com/compose-spec/compose-go/v2/types"
  19. "github.com/docker/cli/cli/config/configfile"
  20. moby "github.com/docker/docker/api/types"
  21. "github.com/docker/docker/api/types/container"
  22. "github.com/docker/docker/api/types/filters"
  23. "github.com/docker/docker/api/types/image"
  24. "github.com/docker/docker/api/types/network"
  25. "github.com/docker/go-connections/nat"
  26. "go.uber.org/mock/gomock"
  27. "gotest.tools/v3/assert"
  28. "github.com/docker/compose/v5/pkg/api"
  29. "github.com/docker/compose/v5/pkg/mocks"
  30. )
  31. func TestContainerName(t *testing.T) {
  32. s := types.ServiceConfig{
  33. Name: "testservicename",
  34. ContainerName: "testcontainername",
  35. Scale: intPtr(1),
  36. Deploy: &types.DeployConfig{},
  37. }
  38. ret, err := getScale(s)
  39. assert.NilError(t, err)
  40. assert.Equal(t, ret, *s.Scale)
  41. s.Scale = intPtr(0)
  42. ret, err = getScale(s)
  43. assert.NilError(t, err)
  44. assert.Equal(t, ret, *s.Scale)
  45. s.Scale = intPtr(2)
  46. _, err = getScale(s)
  47. assert.Error(t, err, fmt.Sprintf(doubledContainerNameWarning, s.Name, s.ContainerName))
  48. }
  49. func intPtr(i int) *int {
  50. return &i
  51. }
  52. func TestServiceLinks(t *testing.T) {
  53. const dbContainerName = "/" + testProject + "-db-1"
  54. const webContainerName = "/" + testProject + "-web-1"
  55. s := types.ServiceConfig{
  56. Name: "web",
  57. Scale: intPtr(1),
  58. }
  59. containerListOptions := container.ListOptions{
  60. Filters: filters.NewArgs(
  61. projectFilter(testProject),
  62. serviceFilter("db"),
  63. oneOffFilter(false),
  64. hasConfigHashLabel(),
  65. ),
  66. All: true,
  67. }
  68. t.Run("service links default", func(t *testing.T) {
  69. mockCtrl := gomock.NewController(t)
  70. defer mockCtrl.Finish()
  71. apiClient := mocks.NewMockAPIClient(mockCtrl)
  72. cli := mocks.NewMockCli(mockCtrl)
  73. tested, err := NewComposeService(cli)
  74. assert.NilError(t, err)
  75. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  76. s.Links = []string{"db"}
  77. c := testContainer("db", dbContainerName, false)
  78. apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil)
  79. links, err := tested.(*composeService).getLinks(t.Context(), testProject, s, 1)
  80. assert.NilError(t, err)
  81. assert.Equal(t, len(links), 3)
  82. assert.Equal(t, links[0], "testProject-db-1:db")
  83. assert.Equal(t, links[1], "testProject-db-1:db-1")
  84. assert.Equal(t, links[2], "testProject-db-1:testProject-db-1")
  85. })
  86. t.Run("service links", func(t *testing.T) {
  87. mockCtrl := gomock.NewController(t)
  88. defer mockCtrl.Finish()
  89. apiClient := mocks.NewMockAPIClient(mockCtrl)
  90. cli := mocks.NewMockCli(mockCtrl)
  91. tested, err := NewComposeService(cli)
  92. assert.NilError(t, err)
  93. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  94. s.Links = []string{"db:db"}
  95. c := testContainer("db", dbContainerName, false)
  96. apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil)
  97. links, err := tested.(*composeService).getLinks(t.Context(), testProject, s, 1)
  98. assert.NilError(t, err)
  99. assert.Equal(t, len(links), 3)
  100. assert.Equal(t, links[0], "testProject-db-1:db")
  101. assert.Equal(t, links[1], "testProject-db-1:db-1")
  102. assert.Equal(t, links[2], "testProject-db-1:testProject-db-1")
  103. })
  104. t.Run("service links name", func(t *testing.T) {
  105. mockCtrl := gomock.NewController(t)
  106. defer mockCtrl.Finish()
  107. apiClient := mocks.NewMockAPIClient(mockCtrl)
  108. cli := mocks.NewMockCli(mockCtrl)
  109. tested, err := NewComposeService(cli)
  110. assert.NilError(t, err)
  111. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  112. s.Links = []string{"db:dbname"}
  113. c := testContainer("db", dbContainerName, false)
  114. apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil)
  115. links, err := tested.(*composeService).getLinks(t.Context(), testProject, s, 1)
  116. assert.NilError(t, err)
  117. assert.Equal(t, len(links), 3)
  118. assert.Equal(t, links[0], "testProject-db-1:dbname")
  119. assert.Equal(t, links[1], "testProject-db-1:db-1")
  120. assert.Equal(t, links[2], "testProject-db-1:testProject-db-1")
  121. })
  122. t.Run("service links external links", func(t *testing.T) {
  123. mockCtrl := gomock.NewController(t)
  124. defer mockCtrl.Finish()
  125. apiClient := mocks.NewMockAPIClient(mockCtrl)
  126. cli := mocks.NewMockCli(mockCtrl)
  127. tested, err := NewComposeService(cli)
  128. assert.NilError(t, err)
  129. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  130. s.Links = []string{"db:dbname"}
  131. s.ExternalLinks = []string{"db1:db2"}
  132. c := testContainer("db", dbContainerName, false)
  133. apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptions).Return([]container.Summary{c}, nil)
  134. links, err := tested.(*composeService).getLinks(t.Context(), testProject, s, 1)
  135. assert.NilError(t, err)
  136. assert.Equal(t, len(links), 4)
  137. assert.Equal(t, links[0], "testProject-db-1:dbname")
  138. assert.Equal(t, links[1], "testProject-db-1:db-1")
  139. assert.Equal(t, links[2], "testProject-db-1:testProject-db-1")
  140. // ExternalLink
  141. assert.Equal(t, links[3], "db1:db2")
  142. })
  143. t.Run("service links itself oneoff", func(t *testing.T) {
  144. mockCtrl := gomock.NewController(t)
  145. defer mockCtrl.Finish()
  146. apiClient := mocks.NewMockAPIClient(mockCtrl)
  147. cli := mocks.NewMockCli(mockCtrl)
  148. tested, err := NewComposeService(cli)
  149. assert.NilError(t, err)
  150. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  151. s.Links = []string{}
  152. s.ExternalLinks = []string{}
  153. s.Labels = s.Labels.Add(api.OneoffLabel, "True")
  154. c := testContainer("web", webContainerName, true)
  155. containerListOptionsOneOff := container.ListOptions{
  156. Filters: filters.NewArgs(
  157. projectFilter(testProject),
  158. serviceFilter("web"),
  159. oneOffFilter(false),
  160. hasConfigHashLabel(),
  161. ),
  162. All: true,
  163. }
  164. apiClient.EXPECT().ContainerList(gomock.Any(), containerListOptionsOneOff).Return([]container.Summary{c}, nil)
  165. links, err := tested.(*composeService).getLinks(t.Context(), testProject, s, 1)
  166. assert.NilError(t, err)
  167. assert.Equal(t, len(links), 3)
  168. assert.Equal(t, links[0], "testProject-web-1:web")
  169. assert.Equal(t, links[1], "testProject-web-1:web-1")
  170. assert.Equal(t, links[2], "testProject-web-1:testProject-web-1")
  171. })
  172. }
  173. func TestWaitDependencies(t *testing.T) {
  174. mockCtrl := gomock.NewController(t)
  175. defer mockCtrl.Finish()
  176. apiClient := mocks.NewMockAPIClient(mockCtrl)
  177. cli := mocks.NewMockCli(mockCtrl)
  178. tested, err := NewComposeService(cli)
  179. assert.NilError(t, err)
  180. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  181. t.Run("should skip dependencies with scale 0", func(t *testing.T) {
  182. dbService := types.ServiceConfig{Name: "db", Scale: intPtr(0)}
  183. redisService := types.ServiceConfig{Name: "redis", Scale: intPtr(0)}
  184. project := types.Project{Name: strings.ToLower(testProject), Services: types.Services{
  185. "db": dbService,
  186. "redis": redisService,
  187. }}
  188. dependencies := types.DependsOnConfig{
  189. "db": {Condition: ServiceConditionRunningOrHealthy},
  190. "redis": {Condition: ServiceConditionRunningOrHealthy},
  191. }
  192. assert.NilError(t, tested.(*composeService).waitDependencies(t.Context(), &project, "", dependencies, nil, 0))
  193. })
  194. t.Run("should skip dependencies with condition service_started", func(t *testing.T) {
  195. dbService := types.ServiceConfig{Name: "db", Scale: intPtr(1)}
  196. redisService := types.ServiceConfig{Name: "redis", Scale: intPtr(1)}
  197. project := types.Project{Name: strings.ToLower(testProject), Services: types.Services{
  198. "db": dbService,
  199. "redis": redisService,
  200. }}
  201. dependencies := types.DependsOnConfig{
  202. "db": {Condition: types.ServiceConditionStarted, Required: true},
  203. "redis": {Condition: types.ServiceConditionStarted, Required: true},
  204. }
  205. assert.NilError(t, tested.(*composeService).waitDependencies(t.Context(), &project, "", dependencies, nil, 0))
  206. })
  207. }
  208. func TestIsServiceHealthy(t *testing.T) {
  209. mockCtrl := gomock.NewController(t)
  210. defer mockCtrl.Finish()
  211. apiClient := mocks.NewMockAPIClient(mockCtrl)
  212. cli := mocks.NewMockCli(mockCtrl)
  213. tested, err := NewComposeService(cli)
  214. assert.NilError(t, err)
  215. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  216. ctx := t.Context()
  217. t.Run("disabled healthcheck with fallback to running", func(t *testing.T) {
  218. containerID := "test-container-id"
  219. containers := Containers{
  220. {ID: containerID},
  221. }
  222. // Container with disabled healthcheck (Test: ["NONE"])
  223. apiClient.EXPECT().ContainerInspect(ctx, containerID).Return(container.InspectResponse{
  224. ContainerJSONBase: &container.ContainerJSONBase{
  225. ID: containerID,
  226. Name: "test-container",
  227. State: &container.State{Status: "running"},
  228. },
  229. Config: &container.Config{
  230. Healthcheck: &container.HealthConfig{
  231. Test: []string{"NONE"},
  232. },
  233. },
  234. }, nil)
  235. isHealthy, err := tested.(*composeService).isServiceHealthy(ctx, containers, true)
  236. assert.NilError(t, err)
  237. assert.Equal(t, true, isHealthy, "Container with disabled healthcheck should be considered healthy when running with fallbackRunning=true")
  238. })
  239. t.Run("disabled healthcheck without fallback", func(t *testing.T) {
  240. containerID := "test-container-id"
  241. containers := Containers{
  242. {ID: containerID},
  243. }
  244. // Container with disabled healthcheck (Test: ["NONE"]) but fallbackRunning=false
  245. apiClient.EXPECT().ContainerInspect(ctx, containerID).Return(container.InspectResponse{
  246. ContainerJSONBase: &container.ContainerJSONBase{
  247. ID: containerID,
  248. Name: "test-container",
  249. State: &container.State{Status: "running"},
  250. },
  251. Config: &container.Config{
  252. Healthcheck: &container.HealthConfig{
  253. Test: []string{"NONE"},
  254. },
  255. },
  256. }, nil)
  257. _, err := tested.(*composeService).isServiceHealthy(ctx, containers, false)
  258. assert.ErrorContains(t, err, "has no healthcheck configured")
  259. })
  260. t.Run("no healthcheck with fallback to running", func(t *testing.T) {
  261. containerID := "test-container-id"
  262. containers := Containers{
  263. {ID: containerID},
  264. }
  265. // Container with no healthcheck at all
  266. apiClient.EXPECT().ContainerInspect(ctx, containerID).Return(container.InspectResponse{
  267. ContainerJSONBase: &container.ContainerJSONBase{
  268. ID: containerID,
  269. Name: "test-container",
  270. State: &container.State{Status: "running"},
  271. },
  272. Config: &container.Config{
  273. Healthcheck: nil,
  274. },
  275. }, nil)
  276. isHealthy, err := tested.(*composeService).isServiceHealthy(ctx, containers, true)
  277. assert.NilError(t, err)
  278. assert.Equal(t, true, isHealthy, "Container with no healthcheck should be considered healthy when running with fallbackRunning=true")
  279. })
  280. t.Run("exited container with disabled healthcheck", func(t *testing.T) {
  281. containerID := "test-container-id"
  282. containers := Containers{
  283. {ID: containerID},
  284. }
  285. // Container with disabled healthcheck but exited
  286. apiClient.EXPECT().ContainerInspect(ctx, containerID).Return(container.InspectResponse{
  287. ContainerJSONBase: &container.ContainerJSONBase{
  288. ID: containerID,
  289. Name: "test-container",
  290. State: &container.State{
  291. Status: "exited",
  292. ExitCode: 1,
  293. },
  294. },
  295. Config: &container.Config{
  296. Healthcheck: &container.HealthConfig{
  297. Test: []string{"NONE"},
  298. },
  299. },
  300. }, nil)
  301. _, err := tested.(*composeService).isServiceHealthy(ctx, containers, true)
  302. assert.ErrorContains(t, err, "exited")
  303. })
  304. t.Run("healthy container with healthcheck", func(t *testing.T) {
  305. containerID := "test-container-id"
  306. containers := Containers{
  307. {ID: containerID},
  308. }
  309. // Container with actual healthcheck that is healthy
  310. apiClient.EXPECT().ContainerInspect(ctx, containerID).Return(container.InspectResponse{
  311. ContainerJSONBase: &container.ContainerJSONBase{
  312. ID: containerID,
  313. Name: "test-container",
  314. State: &container.State{
  315. Status: "running",
  316. Health: &container.Health{
  317. Status: container.Healthy,
  318. },
  319. },
  320. },
  321. Config: &container.Config{
  322. Healthcheck: &container.HealthConfig{
  323. Test: []string{"CMD", "curl", "-f", "http://localhost"},
  324. },
  325. },
  326. }, nil)
  327. isHealthy, err := tested.(*composeService).isServiceHealthy(ctx, containers, false)
  328. assert.NilError(t, err)
  329. assert.Equal(t, true, isHealthy, "Container with healthy status should be healthy")
  330. })
  331. }
  332. func TestCreateMobyContainer(t *testing.T) {
  333. t.Run("connects container networks one by one if API <1.44", func(t *testing.T) {
  334. mockCtrl := gomock.NewController(t)
  335. defer mockCtrl.Finish()
  336. apiClient := mocks.NewMockAPIClient(mockCtrl)
  337. cli := mocks.NewMockCli(mockCtrl)
  338. tested, err := NewComposeService(cli)
  339. assert.NilError(t, err)
  340. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  341. cli.EXPECT().ConfigFile().Return(&configfile.ConfigFile{}).AnyTimes()
  342. apiClient.EXPECT().DaemonHost().Return("").AnyTimes()
  343. apiClient.EXPECT().ImageInspect(gomock.Any(), gomock.Any()).Return(image.InspectResponse{}, nil).AnyTimes()
  344. // force `RuntimeVersion` to fetch again
  345. runtimeVersion = runtimeVersionCache{}
  346. apiClient.EXPECT().ServerVersion(gomock.Any()).Return(moby.Version{
  347. APIVersion: "1.43",
  348. }, nil).AnyTimes()
  349. service := types.ServiceConfig{
  350. Name: "test",
  351. Networks: map[string]*types.ServiceNetworkConfig{
  352. "a": {
  353. Priority: 10,
  354. },
  355. "b": {
  356. Priority: 100,
  357. },
  358. },
  359. }
  360. project := types.Project{
  361. Name: "bork",
  362. Services: types.Services{
  363. "test": service,
  364. },
  365. Networks: types.Networks{
  366. "a": types.NetworkConfig{
  367. Name: "a-moby-name",
  368. },
  369. "b": types.NetworkConfig{
  370. Name: "b-moby-name",
  371. },
  372. },
  373. }
  374. var falseBool bool
  375. apiClient.EXPECT().ContainerCreate(gomock.Any(), gomock.Any(), gomock.Eq(
  376. &container.HostConfig{
  377. PortBindings: nat.PortMap{},
  378. ExtraHosts: []string{},
  379. Tmpfs: map[string]string{},
  380. Resources: container.Resources{
  381. OomKillDisable: &falseBool,
  382. },
  383. NetworkMode: "b-moby-name",
  384. }), gomock.Eq(
  385. &network.NetworkingConfig{
  386. EndpointsConfig: map[string]*network.EndpointSettings{
  387. "b-moby-name": {
  388. IPAMConfig: &network.EndpointIPAMConfig{},
  389. Aliases: []string{"bork-test-0"},
  390. },
  391. },
  392. }), gomock.Any(), gomock.Any()).Times(1).Return(
  393. container.CreateResponse{
  394. ID: "an-id",
  395. }, nil)
  396. apiClient.EXPECT().ContainerInspect(gomock.Any(), gomock.Eq("an-id")).Times(1).Return(
  397. container.InspectResponse{
  398. ContainerJSONBase: &container.ContainerJSONBase{
  399. ID: "an-id",
  400. Name: "a-name",
  401. },
  402. Config: &container.Config{},
  403. NetworkSettings: &container.NetworkSettings{},
  404. }, nil)
  405. apiClient.EXPECT().NetworkConnect(gomock.Any(), "a-moby-name", "an-id", gomock.Eq(
  406. &network.EndpointSettings{
  407. IPAMConfig: &network.EndpointIPAMConfig{},
  408. Aliases: []string{"bork-test-0"},
  409. }))
  410. _, err = tested.(*composeService).createMobyContainer(t.Context(), &project, service, "test", 0, nil, createOptions{
  411. Labels: make(types.Labels),
  412. })
  413. assert.NilError(t, err)
  414. })
  415. t.Run("includes all container networks in ContainerCreate call if API >=1.44", func(t *testing.T) {
  416. mockCtrl := gomock.NewController(t)
  417. defer mockCtrl.Finish()
  418. apiClient := mocks.NewMockAPIClient(mockCtrl)
  419. cli := mocks.NewMockCli(mockCtrl)
  420. tested, err := NewComposeService(cli)
  421. assert.NilError(t, err)
  422. cli.EXPECT().Client().Return(apiClient).AnyTimes()
  423. cli.EXPECT().ConfigFile().Return(&configfile.ConfigFile{}).AnyTimes()
  424. apiClient.EXPECT().DaemonHost().Return("").AnyTimes()
  425. apiClient.EXPECT().ImageInspect(gomock.Any(), gomock.Any()).Return(image.InspectResponse{}, nil).AnyTimes()
  426. // force `RuntimeVersion` to fetch fresh version
  427. runtimeVersion = runtimeVersionCache{}
  428. apiClient.EXPECT().ServerVersion(gomock.Any()).Return(moby.Version{
  429. APIVersion: APIVersion144,
  430. }, nil).AnyTimes()
  431. service := types.ServiceConfig{
  432. Name: "test",
  433. Networks: map[string]*types.ServiceNetworkConfig{
  434. "a": {
  435. Priority: 10,
  436. },
  437. "b": {
  438. Priority: 100,
  439. },
  440. },
  441. }
  442. project := types.Project{
  443. Name: "bork",
  444. Services: types.Services{
  445. "test": service,
  446. },
  447. Networks: types.Networks{
  448. "a": types.NetworkConfig{
  449. Name: "a-moby-name",
  450. },
  451. "b": types.NetworkConfig{
  452. Name: "b-moby-name",
  453. },
  454. },
  455. }
  456. var falseBool bool
  457. apiClient.EXPECT().ContainerCreate(gomock.Any(), gomock.Any(), gomock.Eq(
  458. &container.HostConfig{
  459. PortBindings: nat.PortMap{},
  460. ExtraHosts: []string{},
  461. Tmpfs: map[string]string{},
  462. Resources: container.Resources{
  463. OomKillDisable: &falseBool,
  464. },
  465. NetworkMode: "b-moby-name",
  466. }), gomock.Eq(
  467. &network.NetworkingConfig{
  468. EndpointsConfig: map[string]*network.EndpointSettings{
  469. "a-moby-name": {
  470. IPAMConfig: &network.EndpointIPAMConfig{},
  471. Aliases: []string{"bork-test-0"},
  472. },
  473. "b-moby-name": {
  474. IPAMConfig: &network.EndpointIPAMConfig{},
  475. Aliases: []string{"bork-test-0"},
  476. },
  477. },
  478. }), gomock.Any(), gomock.Any()).Times(1).Return(
  479. container.CreateResponse{
  480. ID: "an-id",
  481. }, nil)
  482. apiClient.EXPECT().ContainerInspect(gomock.Any(), gomock.Eq("an-id")).Times(1).Return(
  483. container.InspectResponse{
  484. ContainerJSONBase: &container.ContainerJSONBase{
  485. ID: "an-id",
  486. Name: "a-name",
  487. },
  488. Config: &container.Config{},
  489. NetworkSettings: &container.NetworkSettings{},
  490. }, nil)
  491. _, err = tested.(*composeService).createMobyContainer(t.Context(), &project, service, "test", 0, nil, createOptions{
  492. Labels: make(types.Labels),
  493. })
  494. assert.NilError(t, err)
  495. })
  496. }