service.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. package docker
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "golang.org/x/net/context"
  7. "github.com/Sirupsen/logrus"
  8. "github.com/docker/engine-api/client"
  9. "github.com/docker/go-connections/nat"
  10. "github.com/docker/libcompose/config"
  11. "github.com/docker/libcompose/docker/builder"
  12. "github.com/docker/libcompose/labels"
  13. "github.com/docker/libcompose/project"
  14. "github.com/docker/libcompose/project/options"
  15. "github.com/docker/libcompose/utils"
  16. )
  17. // Service is a project.Service implementations.
  18. type Service struct {
  19. name string
  20. serviceConfig *config.ServiceConfig
  21. context *Context
  22. }
  23. // NewService creates a service
  24. func NewService(name string, serviceConfig *config.ServiceConfig, context *Context) *Service {
  25. return &Service{
  26. name: name,
  27. serviceConfig: serviceConfig,
  28. context: context,
  29. }
  30. }
  31. // Name returns the service name.
  32. func (s *Service) Name() string {
  33. return s.name
  34. }
  35. // Config returns the configuration of the service (config.ServiceConfig).
  36. func (s *Service) Config() *config.ServiceConfig {
  37. return s.serviceConfig
  38. }
  39. // DependentServices returns the dependent services (as an array of ServiceRelationship) of the service.
  40. func (s *Service) DependentServices() []project.ServiceRelationship {
  41. return project.DefaultDependentServices(s.context.Project, s)
  42. }
  43. // Create implements Service.Create. It ensures the image exists or build it
  44. // if it can and then create a container.
  45. func (s *Service) Create(ctx context.Context, options options.Create) error {
  46. containers, err := s.collectContainers(ctx)
  47. if err != nil {
  48. return err
  49. }
  50. imageName, err := s.ensureImageExists(ctx, options.NoBuild)
  51. if err != nil {
  52. return err
  53. }
  54. if len(containers) != 0 {
  55. return s.eachContainer(ctx, func(c *Container) error {
  56. return s.recreateIfNeeded(ctx, imageName, c, options.NoRecreate, options.ForceRecreate)
  57. })
  58. }
  59. _, err = s.createOne(ctx, imageName)
  60. return err
  61. }
  62. func (s *Service) collectContainers(ctx context.Context) ([]*Container, error) {
  63. client := s.context.ClientFactory.Create(s)
  64. containers, err := GetContainersByFilter(ctx, client, labels.SERVICE.Eq(s.name), labels.PROJECT.Eq(s.context.Project.Name))
  65. if err != nil {
  66. return nil, err
  67. }
  68. legacyContainers, err := GetContainersByFilter(ctx, client, labels.SERVICE_LEGACY.Eq(s.name), labels.PROJECT_LEGACY.Eq(s.context.Project.Name))
  69. if err != nil {
  70. return nil, err
  71. }
  72. if len(containers) == 0 && len(legacyContainers) > 0 {
  73. containers = legacyContainers
  74. }
  75. result := []*Container{}
  76. for _, container := range containers {
  77. numberLabel := container.Labels[labels.NUMBER.Str()]
  78. name := strings.SplitAfter(container.Names[0], "/")
  79. if numberLabel == "" {
  80. result = append(result, NewContainer(client, name[1], 1, s))
  81. return result, nil
  82. }
  83. containerNumber, err := strconv.Atoi(numberLabel)
  84. if err != nil {
  85. return nil, err
  86. }
  87. // Compose add "/" before name, so Name[1] will store actaul name.
  88. result = append(result, NewContainer(client, name[1], containerNumber, s))
  89. }
  90. return result, nil
  91. }
  92. func (s *Service) createOne(ctx context.Context, imageName string) (*Container, error) {
  93. containers, err := s.constructContainers(ctx, imageName, 1)
  94. if err != nil {
  95. return nil, err
  96. }
  97. return containers[0], err
  98. }
  99. func (s *Service) ensureImageExists(ctx context.Context, noBuild bool) (string, error) {
  100. err := s.imageExists()
  101. if err == nil {
  102. return s.imageName(), nil
  103. }
  104. if err != nil && !client.IsErrImageNotFound(err) {
  105. return "", err
  106. }
  107. if s.Config().Build.Context != "" {
  108. if noBuild {
  109. return "", fmt.Errorf("Service %q needs to be built, but no-build was specified", s.name)
  110. }
  111. return s.imageName(), s.build(ctx, options.Build{})
  112. }
  113. return s.imageName(), s.Pull(ctx)
  114. }
  115. func (s *Service) imageExists() error {
  116. client := s.context.ClientFactory.Create(s)
  117. _, _, err := client.ImageInspectWithRaw(context.Background(), s.imageName(), false)
  118. return err
  119. }
  120. func (s *Service) imageName() string {
  121. if s.Config().Image != "" {
  122. return s.Config().Image
  123. }
  124. return fmt.Sprintf("%s_%s", s.context.ProjectName, s.Name())
  125. }
  126. // Build implements Service.Build. If an imageName is specified or if the context has
  127. // no build to work with it will do nothing. Otherwise it will try to build
  128. // the image and returns an error if any.
  129. func (s *Service) Build(ctx context.Context, buildOptions options.Build) error {
  130. if s.Config().Image != "" {
  131. return nil
  132. }
  133. return s.build(ctx, buildOptions)
  134. }
  135. func (s *Service) build(ctx context.Context, buildOptions options.Build) error {
  136. if s.Config().Build.Context == "" {
  137. return fmt.Errorf("Specified service does not have a build section")
  138. }
  139. builder := &builder.DaemonBuilder{
  140. Client: s.context.ClientFactory.Create(s),
  141. ContextDirectory: s.Config().Build.Context,
  142. Dockerfile: s.Config().Build.Dockerfile,
  143. AuthConfigs: s.context.AuthLookup.All(),
  144. NoCache: buildOptions.NoCache,
  145. ForceRemove: buildOptions.ForceRemove,
  146. Pull: buildOptions.Pull,
  147. }
  148. return builder.Build(ctx, s.imageName())
  149. }
  150. func (s *Service) constructContainers(ctx context.Context, imageName string, count int) ([]*Container, error) {
  151. result, err := s.collectContainers(ctx)
  152. if err != nil {
  153. return nil, err
  154. }
  155. client := s.context.ClientFactory.Create(s)
  156. var namer Namer
  157. if s.serviceConfig.ContainerName != "" {
  158. if count > 1 {
  159. logrus.Warnf(`The "%s" service is using the custom container name "%s". Docker requires each container to have a unique name. Remove the custom name to scale the service.`, s.name, s.serviceConfig.ContainerName)
  160. }
  161. namer = NewSingleNamer(s.serviceConfig.ContainerName)
  162. } else {
  163. namer, err = NewNamer(ctx, client, s.context.Project.Name, s.name, false)
  164. if err != nil {
  165. return nil, err
  166. }
  167. }
  168. for i := len(result); i < count; i++ {
  169. containerName, containerNumber := namer.Next()
  170. c := NewContainer(client, containerName, containerNumber, s)
  171. dockerContainer, err := c.Create(ctx, imageName)
  172. if err != nil {
  173. return nil, err
  174. }
  175. logrus.Debugf("Created container %s: %v", dockerContainer.ID, dockerContainer.Name)
  176. result = append(result, NewContainer(client, containerName, containerNumber, s))
  177. }
  178. return result, nil
  179. }
  180. // Up implements Service.Up. It builds the image if needed, creates a container
  181. // and start it.
  182. func (s *Service) Up(ctx context.Context, options options.Up) error {
  183. containers, err := s.collectContainers(ctx)
  184. if err != nil {
  185. return err
  186. }
  187. var imageName = s.imageName()
  188. if len(containers) == 0 || !options.NoRecreate {
  189. imageName, err = s.ensureImageExists(ctx, options.NoBuild)
  190. if err != nil {
  191. return err
  192. }
  193. }
  194. return s.up(ctx, imageName, true, options)
  195. }
  196. // Run implements Service.Run. It runs a one of command within the service container.
  197. func (s *Service) Run(ctx context.Context, commandParts []string) (int, error) {
  198. imageName, err := s.ensureImageExists(ctx, false)
  199. if err != nil {
  200. return -1, err
  201. }
  202. client := s.context.ClientFactory.Create(s)
  203. namer, err := NewNamer(ctx, client, s.context.Project.Name, s.name, true)
  204. if err != nil {
  205. return -1, err
  206. }
  207. containerName, containerNumber := namer.Next()
  208. c := NewOneOffContainer(client, containerName, containerNumber, s)
  209. return c.Run(ctx, imageName, &config.ServiceConfig{Command: commandParts, Tty: true, StdinOpen: true})
  210. }
  211. // Info implements Service.Info. It returns an project.InfoSet with the containers
  212. // related to this service (can be multiple if using the scale command).
  213. func (s *Service) Info(ctx context.Context, qFlag bool) (project.InfoSet, error) {
  214. result := project.InfoSet{}
  215. containers, err := s.collectContainers(ctx)
  216. if err != nil {
  217. return nil, err
  218. }
  219. for _, c := range containers {
  220. info, err := c.Info(ctx, qFlag)
  221. if err != nil {
  222. return nil, err
  223. }
  224. result = append(result, info)
  225. }
  226. return result, nil
  227. }
  228. // Start implements Service.Start. It tries to start a container without creating it.
  229. func (s *Service) Start(ctx context.Context) error {
  230. return s.up(ctx, "", false, options.Up{})
  231. }
  232. func (s *Service) up(ctx context.Context, imageName string, create bool, options options.Up) error {
  233. containers, err := s.collectContainers(ctx)
  234. if err != nil {
  235. return err
  236. }
  237. logrus.Debugf("Found %d existing containers for service %s", len(containers), s.name)
  238. if len(containers) == 0 && create {
  239. c, err := s.createOne(ctx, imageName)
  240. if err != nil {
  241. return err
  242. }
  243. containers = []*Container{c}
  244. }
  245. return s.eachContainer(ctx, func(c *Container) error {
  246. if create {
  247. if err := s.recreateIfNeeded(ctx, imageName, c, options.NoRecreate, options.ForceRecreate); err != nil {
  248. return err
  249. }
  250. }
  251. if options.Log {
  252. go c.Log(ctx, true)
  253. }
  254. return c.Up(ctx, imageName)
  255. })
  256. }
  257. func (s *Service) recreateIfNeeded(ctx context.Context, imageName string, c *Container, noRecreate, forceRecreate bool) error {
  258. if noRecreate {
  259. return nil
  260. }
  261. outOfSync, err := c.OutOfSync(ctx, imageName)
  262. if err != nil {
  263. return err
  264. }
  265. logrus.WithFields(logrus.Fields{
  266. "outOfSync": outOfSync,
  267. "ForceRecreate": forceRecreate,
  268. "NoRecreate": noRecreate}).Debug("Going to decide if recreate is needed")
  269. if forceRecreate || outOfSync {
  270. logrus.Infof("Recreating %s", s.name)
  271. if _, err := c.Recreate(ctx, imageName); err != nil {
  272. return err
  273. }
  274. }
  275. return nil
  276. }
  277. func (s *Service) eachContainer(ctx context.Context, action func(*Container) error) error {
  278. containers, err := s.collectContainers(ctx)
  279. if err != nil {
  280. return err
  281. }
  282. tasks := utils.InParallel{}
  283. for _, container := range containers {
  284. task := func(container *Container) func() error {
  285. return func() error {
  286. return action(container)
  287. }
  288. }(container)
  289. tasks.Add(task)
  290. }
  291. return tasks.Wait()
  292. }
  293. // Stop implements Service.Stop. It stops any containers related to the service.
  294. func (s *Service) Stop(ctx context.Context, timeout int) error {
  295. return s.eachContainer(ctx, func(c *Container) error {
  296. return c.Stop(ctx, timeout)
  297. })
  298. }
  299. // Restart implements Service.Restart. It restarts any containers related to the service.
  300. func (s *Service) Restart(ctx context.Context, timeout int) error {
  301. return s.eachContainer(ctx, func(c *Container) error {
  302. return c.Restart(ctx, timeout)
  303. })
  304. }
  305. // Kill implements Service.Kill. It kills any containers related to the service.
  306. func (s *Service) Kill(ctx context.Context, signal string) error {
  307. return s.eachContainer(ctx, func(c *Container) error {
  308. return c.Kill(ctx, signal)
  309. })
  310. }
  311. // Delete implements Service.Delete. It removes any containers related to the service.
  312. func (s *Service) Delete(ctx context.Context, options options.Delete) error {
  313. return s.eachContainer(ctx, func(c *Container) error {
  314. return c.Delete(ctx, options.RemoveVolume)
  315. })
  316. }
  317. // Log implements Service.Log. It returns the docker logs for each container related to the service.
  318. func (s *Service) Log(ctx context.Context, follow bool) error {
  319. return s.eachContainer(ctx, func(c *Container) error {
  320. return c.Log(ctx, follow)
  321. })
  322. }
  323. // Scale implements Service.Scale. It creates or removes containers to have the specified number
  324. // of related container to the service to run.
  325. func (s *Service) Scale(ctx context.Context, scale int, timeout int) error {
  326. if s.specificiesHostPort() {
  327. logrus.Warnf("The \"%s\" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.", s.Name())
  328. }
  329. foundCount := 0
  330. err := s.eachContainer(ctx, func(c *Container) error {
  331. foundCount++
  332. if foundCount > scale {
  333. err := c.Stop(ctx, timeout)
  334. if err != nil {
  335. return err
  336. }
  337. // FIXME(vdemeester) remove volume in scale by default ?
  338. return c.Delete(ctx, false)
  339. }
  340. return nil
  341. })
  342. if err != nil {
  343. return err
  344. }
  345. if foundCount != scale {
  346. imageName, err := s.ensureImageExists(ctx, false)
  347. if err != nil {
  348. return err
  349. }
  350. if _, err = s.constructContainers(ctx, imageName, scale); err != nil {
  351. return err
  352. }
  353. }
  354. return s.up(ctx, "", false, options.Up{})
  355. }
  356. // Pull implements Service.Pull. It pulls the image of the service and skip the service that
  357. // would need to be built.
  358. func (s *Service) Pull(ctx context.Context) error {
  359. if s.Config().Image == "" {
  360. return nil
  361. }
  362. return pullImage(ctx, s.context.ClientFactory.Create(s), s, s.Config().Image)
  363. }
  364. // Pause implements Service.Pause. It puts into pause the container(s) related
  365. // to the service.
  366. func (s *Service) Pause(ctx context.Context) error {
  367. return s.eachContainer(ctx, func(c *Container) error {
  368. return c.Pause(ctx)
  369. })
  370. }
  371. // Unpause implements Service.Pause. It brings back from pause the container(s)
  372. // related to the service.
  373. func (s *Service) Unpause(ctx context.Context) error {
  374. return s.eachContainer(ctx, func(c *Container) error {
  375. return c.Unpause(ctx)
  376. })
  377. }
  378. // RemoveImage implements Service.RemoveImage. It removes images used for the service
  379. // depending on the specified type.
  380. func (s *Service) RemoveImage(ctx context.Context, imageType options.ImageType) error {
  381. switch imageType {
  382. case "local":
  383. if s.Config().Image != "" {
  384. return nil
  385. }
  386. return removeImage(ctx, s.context.ClientFactory.Create(s), s.imageName())
  387. case "all":
  388. return removeImage(ctx, s.context.ClientFactory.Create(s), s.imageName())
  389. default:
  390. // Don't do a thing, should be validated up-front
  391. return nil
  392. }
  393. }
  394. // Containers implements Service.Containers. It returns the list of containers
  395. // that are related to the service.
  396. func (s *Service) Containers(ctx context.Context) ([]project.Container, error) {
  397. result := []project.Container{}
  398. containers, err := s.collectContainers(ctx)
  399. if err != nil {
  400. return nil, err
  401. }
  402. for _, c := range containers {
  403. result = append(result, c)
  404. }
  405. return result, nil
  406. }
  407. func (s *Service) specificiesHostPort() bool {
  408. _, bindings, err := nat.ParsePortSpecs(s.Config().Ports)
  409. if err != nil {
  410. fmt.Println(err)
  411. }
  412. for _, portBindings := range bindings {
  413. for _, portBinding := range portBindings {
  414. if portBinding.HostPort != "" {
  415. return true
  416. }
  417. }
  418. }
  419. return false
  420. }