service-wrapper.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package project
  2. import (
  3. "sync"
  4. log "github.com/Sirupsen/logrus"
  5. "github.com/docker/libcompose/project/events"
  6. )
  7. type serviceWrapper struct {
  8. name string
  9. service Service
  10. done sync.WaitGroup
  11. state ServiceState
  12. err error
  13. project *Project
  14. noWait bool
  15. ignored map[string]bool
  16. }
  17. func newServiceWrapper(name string, p *Project) (*serviceWrapper, error) {
  18. wrapper := &serviceWrapper{
  19. name: name,
  20. state: StateUnknown,
  21. project: p,
  22. ignored: map[string]bool{},
  23. }
  24. return wrapper, wrapper.Reset()
  25. }
  26. func (s *serviceWrapper) IgnoreDep(name string) {
  27. s.ignored[name] = true
  28. }
  29. func (s *serviceWrapper) Reset() error {
  30. if s.state != StateExecuted {
  31. service, err := s.project.CreateService(s.name)
  32. if err != nil {
  33. log.Errorf("Failed to create service for %s : %v", s.name, err)
  34. return err
  35. }
  36. s.service = service
  37. }
  38. if s.err == ErrRestart {
  39. s.err = nil
  40. }
  41. s.done.Add(1)
  42. return nil
  43. }
  44. func (s *serviceWrapper) Ignore() {
  45. defer s.done.Done()
  46. s.state = StateExecuted
  47. s.project.Notify(events.ServiceUpIgnored, s.service.Name(), nil)
  48. }
  49. func (s *serviceWrapper) waitForDeps(wrappers map[string]*serviceWrapper) bool {
  50. if s.noWait {
  51. return true
  52. }
  53. for _, dep := range s.service.DependentServices() {
  54. if s.ignored[dep.Target] {
  55. continue
  56. }
  57. if wrapper, ok := wrappers[dep.Target]; ok {
  58. if wrapper.Wait() == ErrRestart {
  59. s.project.Notify(events.ProjectReload, wrapper.service.Name(), nil)
  60. s.err = ErrRestart
  61. return false
  62. }
  63. } else {
  64. log.Errorf("Failed to find %s", dep.Target)
  65. }
  66. }
  67. return true
  68. }
  69. func (s *serviceWrapper) Do(wrappers map[string]*serviceWrapper, start, done events.EventType, action func(service Service) error) {
  70. defer s.done.Done()
  71. if s.state == StateExecuted {
  72. return
  73. }
  74. if wrappers != nil && !s.waitForDeps(wrappers) {
  75. return
  76. }
  77. s.state = StateExecuted
  78. s.project.Notify(start, s.service.Name(), nil)
  79. s.err = action(s.service)
  80. if s.err == ErrRestart {
  81. s.project.Notify(done, s.service.Name(), nil)
  82. s.project.Notify(events.ProjectReloadTrigger, s.service.Name(), nil)
  83. } else if s.err != nil {
  84. log.Errorf("Failed %s %s : %v", start, s.name, s.err)
  85. } else {
  86. s.project.Notify(done, s.service.Name(), nil)
  87. }
  88. }
  89. func (s *serviceWrapper) Wait() error {
  90. s.done.Wait()
  91. return s.err
  92. }