create_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. package service // import "github.com/docker/docker/integration/service"
  2. import (
  3. "context"
  4. "io"
  5. "strings"
  6. "testing"
  7. "time"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/container"
  10. "github.com/docker/docker/api/types/filters"
  11. "github.com/docker/docker/api/types/strslice"
  12. swarmtypes "github.com/docker/docker/api/types/swarm"
  13. "github.com/docker/docker/client"
  14. "github.com/docker/docker/errdefs"
  15. "github.com/docker/docker/integration/internal/network"
  16. "github.com/docker/docker/integration/internal/swarm"
  17. "github.com/docker/docker/testutil"
  18. "github.com/docker/docker/testutil/daemon"
  19. "gotest.tools/v3/assert"
  20. is "gotest.tools/v3/assert/cmp"
  21. "gotest.tools/v3/poll"
  22. "gotest.tools/v3/skip"
  23. )
  24. func TestServiceCreateInit(t *testing.T) {
  25. ctx := setupTest(t)
  26. t.Run("daemonInitDisabled", testServiceCreateInit(ctx, false))
  27. t.Run("daemonInitEnabled", testServiceCreateInit(ctx, true))
  28. }
  29. func testServiceCreateInit(ctx context.Context, daemonEnabled bool) func(t *testing.T) {
  30. return func(t *testing.T) {
  31. _ = testutil.StartSpan(ctx, t)
  32. ops := []daemon.Option{}
  33. if daemonEnabled {
  34. ops = append(ops, daemon.WithInit())
  35. }
  36. d := swarm.NewSwarm(ctx, t, testEnv, ops...)
  37. defer d.Stop(t)
  38. client := d.NewClientT(t)
  39. defer client.Close()
  40. booleanTrue := true
  41. booleanFalse := false
  42. serviceID := swarm.CreateService(ctx, t, d)
  43. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, 1), swarm.ServicePoll)
  44. i := inspectServiceContainer(ctx, t, client, serviceID)
  45. // HostConfig.Init == nil means that it delegates to daemon configuration
  46. assert.Check(t, i.HostConfig.Init == nil)
  47. serviceID = swarm.CreateService(ctx, t, d, swarm.ServiceWithInit(&booleanTrue))
  48. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, 1), swarm.ServicePoll)
  49. i = inspectServiceContainer(ctx, t, client, serviceID)
  50. assert.Check(t, is.Equal(true, *i.HostConfig.Init))
  51. serviceID = swarm.CreateService(ctx, t, d, swarm.ServiceWithInit(&booleanFalse))
  52. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, 1), swarm.ServicePoll)
  53. i = inspectServiceContainer(ctx, t, client, serviceID)
  54. assert.Check(t, is.Equal(false, *i.HostConfig.Init))
  55. }
  56. }
  57. func inspectServiceContainer(ctx context.Context, t *testing.T, client client.APIClient, serviceID string) types.ContainerJSON {
  58. t.Helper()
  59. containers, err := client.ContainerList(ctx, container.ListOptions{
  60. Filters: filters.NewArgs(filters.Arg("label", "com.docker.swarm.service.id="+serviceID)),
  61. })
  62. assert.NilError(t, err)
  63. assert.Check(t, is.Len(containers, 1))
  64. i, err := client.ContainerInspect(ctx, containers[0].ID)
  65. assert.NilError(t, err)
  66. return i
  67. }
  68. func TestCreateServiceMultipleTimes(t *testing.T) {
  69. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  70. ctx := setupTest(t)
  71. d := swarm.NewSwarm(ctx, t, testEnv)
  72. defer d.Stop(t)
  73. client := d.NewClientT(t)
  74. defer client.Close()
  75. overlayName := "overlay1_" + t.Name()
  76. overlayID := network.CreateNoError(ctx, t, client, overlayName,
  77. network.WithDriver("overlay"),
  78. )
  79. var instances uint64 = 4
  80. serviceName := "TestService_" + t.Name()
  81. serviceSpec := []swarm.ServiceSpecOpt{
  82. swarm.ServiceWithReplicas(instances),
  83. swarm.ServiceWithName(serviceName),
  84. swarm.ServiceWithNetwork(overlayName),
  85. }
  86. serviceID := swarm.CreateService(ctx, t, d, serviceSpec...)
  87. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, instances), swarm.ServicePoll)
  88. _, _, err := client.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
  89. assert.NilError(t, err)
  90. err = client.ServiceRemove(ctx, serviceID)
  91. assert.NilError(t, err)
  92. poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID), swarm.ServicePoll)
  93. serviceID2 := swarm.CreateService(ctx, t, d, serviceSpec...)
  94. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID2, instances), swarm.ServicePoll)
  95. err = client.ServiceRemove(ctx, serviceID2)
  96. assert.NilError(t, err)
  97. // we can't just wait on no tasks for the service, counter-intuitively.
  98. // Tasks may briefly exist but not show up, if they are are in the process
  99. // of being deallocated. To avoid this case, we should retry network remove
  100. // a few times, to give tasks time to be deallcoated
  101. poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID2), swarm.ServicePoll)
  102. for retry := 0; retry < 5; retry++ {
  103. err = client.NetworkRemove(ctx, overlayID)
  104. // TODO(dperny): using strings.Contains for error checking is awful,
  105. // but so is the fact that swarm functions don't return errdefs errors.
  106. // I don't have time at this moment to fix the latter, so I guess I'll
  107. // go with the former.
  108. //
  109. // The full error we're looking for is something like this:
  110. //
  111. // Error response from daemon: rpc error: code = FailedPrecondition desc = network %v is in use by task %v
  112. //
  113. // The safest way to catch this, I think, will be to match on "is in
  114. // use by", as this is an uninterrupted string that best identifies
  115. // this error.
  116. if err == nil || !strings.Contains(err.Error(), "is in use by") {
  117. // if there is no error, or the error isn't this kind of error,
  118. // then we'll break the loop body, and either fail the test or
  119. // continue.
  120. break
  121. }
  122. }
  123. assert.NilError(t, err)
  124. poll.WaitOn(t, network.IsRemoved(ctx, client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second))
  125. }
  126. func TestCreateServiceConflict(t *testing.T) {
  127. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  128. ctx := setupTest(t)
  129. d := swarm.NewSwarm(ctx, t, testEnv)
  130. defer d.Stop(t)
  131. c := d.NewClientT(t)
  132. defer c.Close()
  133. serviceName := "TestService_" + t.Name()
  134. serviceSpec := []swarm.ServiceSpecOpt{
  135. swarm.ServiceWithName(serviceName),
  136. }
  137. swarm.CreateService(ctx, t, d, serviceSpec...)
  138. spec := swarm.CreateServiceSpec(t, serviceSpec...)
  139. _, err := c.ServiceCreate(ctx, spec, types.ServiceCreateOptions{})
  140. assert.Check(t, errdefs.IsConflict(err))
  141. assert.ErrorContains(t, err, "service "+serviceName+" already exists")
  142. }
  143. func TestCreateServiceMaxReplicas(t *testing.T) {
  144. ctx := setupTest(t)
  145. d := swarm.NewSwarm(ctx, t, testEnv)
  146. defer d.Stop(t)
  147. client := d.NewClientT(t)
  148. defer client.Close()
  149. var maxReplicas uint64 = 2
  150. serviceSpec := []swarm.ServiceSpecOpt{
  151. swarm.ServiceWithReplicas(maxReplicas),
  152. swarm.ServiceWithMaxReplicas(maxReplicas),
  153. }
  154. serviceID := swarm.CreateService(ctx, t, d, serviceSpec...)
  155. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, maxReplicas), swarm.ServicePoll)
  156. _, _, err := client.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
  157. assert.NilError(t, err)
  158. }
  159. func TestCreateServiceSecretFileMode(t *testing.T) {
  160. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  161. ctx := setupTest(t)
  162. d := swarm.NewSwarm(ctx, t, testEnv)
  163. defer d.Stop(t)
  164. client := d.NewClientT(t)
  165. defer client.Close()
  166. secretName := "TestSecret_" + t.Name()
  167. secretResp, err := client.SecretCreate(ctx, swarmtypes.SecretSpec{
  168. Annotations: swarmtypes.Annotations{
  169. Name: secretName,
  170. },
  171. Data: []byte("TESTSECRET"),
  172. })
  173. assert.NilError(t, err)
  174. var instances uint64 = 1
  175. serviceName := "TestService_" + t.Name()
  176. serviceID := swarm.CreateService(ctx, t, d,
  177. swarm.ServiceWithReplicas(instances),
  178. swarm.ServiceWithName(serviceName),
  179. swarm.ServiceWithCommand([]string{"/bin/sh", "-c", "ls -l /etc/secret && sleep inf"}),
  180. swarm.ServiceWithSecret(&swarmtypes.SecretReference{
  181. File: &swarmtypes.SecretReferenceFileTarget{
  182. Name: "/etc/secret",
  183. UID: "0",
  184. GID: "0",
  185. Mode: 0o777,
  186. },
  187. SecretID: secretResp.ID,
  188. SecretName: secretName,
  189. }),
  190. )
  191. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, instances), swarm.ServicePoll)
  192. body, err := client.ServiceLogs(ctx, serviceID, container.LogsOptions{
  193. Tail: "1",
  194. ShowStdout: true,
  195. })
  196. assert.NilError(t, err)
  197. defer body.Close()
  198. content, err := io.ReadAll(body)
  199. assert.NilError(t, err)
  200. assert.Check(t, is.Contains(string(content), "-rwxrwxrwx"))
  201. err = client.ServiceRemove(ctx, serviceID)
  202. assert.NilError(t, err)
  203. poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID), swarm.ServicePoll)
  204. err = client.SecretRemove(ctx, secretName)
  205. assert.NilError(t, err)
  206. }
  207. func TestCreateServiceConfigFileMode(t *testing.T) {
  208. skip.If(t, testEnv.DaemonInfo.OSType == "windows")
  209. ctx := setupTest(t)
  210. d := swarm.NewSwarm(ctx, t, testEnv)
  211. defer d.Stop(t)
  212. client := d.NewClientT(t)
  213. defer client.Close()
  214. configName := "TestConfig_" + t.Name()
  215. configResp, err := client.ConfigCreate(ctx, swarmtypes.ConfigSpec{
  216. Annotations: swarmtypes.Annotations{
  217. Name: configName,
  218. },
  219. Data: []byte("TESTCONFIG"),
  220. })
  221. assert.NilError(t, err)
  222. var instances uint64 = 1
  223. serviceName := "TestService_" + t.Name()
  224. serviceID := swarm.CreateService(ctx, t, d,
  225. swarm.ServiceWithName(serviceName),
  226. swarm.ServiceWithCommand([]string{"/bin/sh", "-c", "ls -l /etc/config && sleep inf"}),
  227. swarm.ServiceWithReplicas(instances),
  228. swarm.ServiceWithConfig(&swarmtypes.ConfigReference{
  229. File: &swarmtypes.ConfigReferenceFileTarget{
  230. Name: "/etc/config",
  231. UID: "0",
  232. GID: "0",
  233. Mode: 0o777,
  234. },
  235. ConfigID: configResp.ID,
  236. ConfigName: configName,
  237. }),
  238. )
  239. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, instances))
  240. body, err := client.ServiceLogs(ctx, serviceID, container.LogsOptions{
  241. Tail: "1",
  242. ShowStdout: true,
  243. })
  244. assert.NilError(t, err)
  245. defer body.Close()
  246. content, err := io.ReadAll(body)
  247. assert.NilError(t, err)
  248. assert.Check(t, is.Contains(string(content), "-rwxrwxrwx"))
  249. err = client.ServiceRemove(ctx, serviceID)
  250. assert.NilError(t, err)
  251. poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID))
  252. err = client.ConfigRemove(ctx, configName)
  253. assert.NilError(t, err)
  254. }
  255. // TestServiceCreateSysctls tests that a service created with sysctl options in
  256. // the ContainerSpec correctly applies those options.
  257. //
  258. // To test this, we're going to create a service with the sysctl option
  259. //
  260. // {"net.ipv4.ip_nonlocal_bind": "0"}
  261. //
  262. // We'll get the service's tasks to get the container ID, and then we'll
  263. // inspect the container. If the output of the container inspect contains the
  264. // sysctl option with the correct value, we can assume that the sysctl has been
  265. // plumbed correctly.
  266. //
  267. // Next, we'll remove that service and create a new service with that option
  268. // set to 1. This means that no matter what the default is, we can be confident
  269. // that the sysctl option is applying as intended.
  270. //
  271. // Additionally, we'll do service and task inspects to verify that the inspect
  272. // output includes the desired sysctl option.
  273. //
  274. // We're using net.ipv4.ip_nonlocal_bind because it's something that I'm fairly
  275. // confident won't be modified by the container runtime, and won't blow
  276. // anything up in the test environment
  277. func TestCreateServiceSysctls(t *testing.T) {
  278. ctx := setupTest(t)
  279. d := swarm.NewSwarm(ctx, t, testEnv)
  280. defer d.Stop(t)
  281. client := d.NewClientT(t)
  282. defer client.Close()
  283. // run thie block twice, so that no matter what the default value of
  284. // net.ipv4.ip_nonlocal_bind is, we can verify that setting the sysctl
  285. // options works
  286. for _, expected := range []string{"0", "1"} {
  287. // store the map we're going to be using everywhere.
  288. expectedSysctls := map[string]string{"net.ipv4.ip_nonlocal_bind": expected}
  289. // Create the service with the sysctl options
  290. var instances uint64 = 1
  291. serviceID := swarm.CreateService(ctx, t, d,
  292. swarm.ServiceWithSysctls(expectedSysctls),
  293. )
  294. // wait for the service to converge to 1 running task as expected
  295. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, instances))
  296. // we're going to check 3 things:
  297. //
  298. // 1. Does the container, when inspected, have the sysctl option set?
  299. // 2. Does the task have the sysctl in the spec?
  300. // 3. Does the service have the sysctl in the spec?
  301. //
  302. // if all 3 of these things are true, we know that the sysctl has been
  303. // plumbed correctly through the engine.
  304. //
  305. // We don't actually have to get inside the container and check its
  306. // logs or anything. If we see the sysctl set on the container inspect,
  307. // we know that the sysctl is plumbed correctly. everything below that
  308. // level has been tested elsewhere. (thanks @thaJeztah, because an
  309. // earlier version of this test had to get container logs and was much
  310. // more complex)
  311. // get all tasks of the service, so we can get the container
  312. tasks, err := client.TaskList(ctx, types.TaskListOptions{
  313. Filters: filters.NewArgs(filters.Arg("service", serviceID)),
  314. })
  315. assert.NilError(t, err)
  316. assert.Check(t, is.Equal(len(tasks), 1))
  317. // verify that the container has the sysctl option set
  318. ctnr, err := client.ContainerInspect(ctx, tasks[0].Status.ContainerStatus.ContainerID)
  319. assert.NilError(t, err)
  320. assert.DeepEqual(t, ctnr.HostConfig.Sysctls, expectedSysctls)
  321. // verify that the task has the sysctl option set in the task object
  322. assert.DeepEqual(t, tasks[0].Spec.ContainerSpec.Sysctls, expectedSysctls)
  323. // verify that the service also has the sysctl set in the spec.
  324. service, _, err := client.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
  325. assert.NilError(t, err)
  326. assert.DeepEqual(t,
  327. service.Spec.TaskTemplate.ContainerSpec.Sysctls, expectedSysctls,
  328. )
  329. }
  330. }
  331. // TestServiceCreateCapabilities tests that a service created with capabilities options in
  332. // the ContainerSpec correctly applies those options.
  333. //
  334. // To test this, we're going to create a service with the capabilities option
  335. //
  336. // []string{"CAP_NET_RAW", "CAP_SYS_CHROOT"}
  337. //
  338. // We'll get the service's tasks to get the container ID, and then we'll
  339. // inspect the container. If the output of the container inspect contains the
  340. // capabilities option with the correct value, we can assume that the capabilities has been
  341. // plumbed correctly.
  342. func TestCreateServiceCapabilities(t *testing.T) {
  343. ctx := setupTest(t)
  344. d := swarm.NewSwarm(ctx, t, testEnv)
  345. defer d.Stop(t)
  346. client := d.NewClientT(t)
  347. defer client.Close()
  348. // store the map we're going to be using everywhere.
  349. capAdd := []string{"CAP_SYS_CHROOT"}
  350. capDrop := []string{"CAP_NET_RAW"}
  351. // Create the service with the capabilities options
  352. var instances uint64 = 1
  353. serviceID := swarm.CreateService(ctx, t, d,
  354. swarm.ServiceWithCapabilities(capAdd, capDrop),
  355. )
  356. // wait for the service to converge to 1 running task as expected
  357. poll.WaitOn(t, swarm.RunningTasksCount(ctx, client, serviceID, instances))
  358. // we're going to check 3 things:
  359. //
  360. // 1. Does the container, when inspected, have the capabilities option set?
  361. // 2. Does the task have the capabilities in the spec?
  362. // 3. Does the service have the capabilities in the spec?
  363. //
  364. // if all 3 of these things are true, we know that the capabilities has been
  365. // plumbed correctly through the engine.
  366. //
  367. // We don't actually have to get inside the container and check its
  368. // logs or anything. If we see the capabilities set on the container inspect,
  369. // we know that the capabilities is plumbed correctly. everything below that
  370. // level has been tested elsewhere.
  371. // get all tasks of the service, so we can get the container
  372. tasks, err := client.TaskList(ctx, types.TaskListOptions{
  373. Filters: filters.NewArgs(filters.Arg("service", serviceID)),
  374. })
  375. assert.NilError(t, err)
  376. assert.Check(t, is.Equal(len(tasks), 1))
  377. // verify that the container has the capabilities option set
  378. ctnr, err := client.ContainerInspect(ctx, tasks[0].Status.ContainerStatus.ContainerID)
  379. assert.NilError(t, err)
  380. assert.DeepEqual(t, ctnr.HostConfig.CapAdd, strslice.StrSlice(capAdd))
  381. assert.DeepEqual(t, ctnr.HostConfig.CapDrop, strslice.StrSlice(capDrop))
  382. // verify that the task has the capabilities option set in the task object
  383. assert.DeepEqual(t, tasks[0].Spec.ContainerSpec.CapabilityAdd, capAdd)
  384. assert.DeepEqual(t, tasks[0].Spec.ContainerSpec.CapabilityDrop, capDrop)
  385. // verify that the service also has the capabilities set in the spec.
  386. service, _, err := client.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
  387. assert.NilError(t, err)
  388. assert.DeepEqual(t, service.Spec.TaskTemplate.ContainerSpec.CapabilityAdd, capAdd)
  389. assert.DeepEqual(t, service.Spec.TaskTemplate.ContainerSpec.CapabilityDrop, capDrop)
  390. }