dependencies.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // +build local
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package local
  15. import (
  16. "context"
  17. "github.com/compose-spec/compose-go/types"
  18. "golang.org/x/sync/errgroup"
  19. )
  20. func inDependencyOrder(ctx context.Context, project *types.Project, fn func(types.ServiceConfig) error) error {
  21. eg, ctx := errgroup.WithContext(ctx)
  22. var (
  23. scheduled []string
  24. ready []string
  25. )
  26. results := make(chan string)
  27. for len(ready) < len(project.Services) {
  28. for _, service := range project.Services {
  29. if contains(scheduled, service.Name) {
  30. continue
  31. }
  32. if containsAll(ready, service.GetDependencies()) {
  33. service := service
  34. scheduled = append(scheduled, service.Name)
  35. eg.Go(func() error {
  36. err := fn(service)
  37. if err != nil {
  38. close(results)
  39. return err
  40. }
  41. results <- service.Name
  42. return nil
  43. })
  44. }
  45. }
  46. result, ok := <-results
  47. if !ok {
  48. break
  49. }
  50. ready = append(ready, result)
  51. }
  52. return eg.Wait()
  53. }