dependencies.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. "context"
  16. "fmt"
  17. "slices"
  18. "strings"
  19. "sync"
  20. "github.com/compose-spec/compose-go/v2/types"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "golang.org/x/sync/errgroup"
  23. )
  24. // ServiceStatus indicates the status of a service
  25. type ServiceStatus int
  26. // Services status flags
  27. const (
  28. ServiceStopped ServiceStatus = iota
  29. ServiceStarted
  30. )
  31. type graphTraversal struct {
  32. mu sync.Mutex
  33. seen map[string]struct{}
  34. ignored map[string]struct{}
  35. extremityNodesFn func(*Graph) []*Vertex // leaves or roots
  36. adjacentNodesFn func(*Vertex) []*Vertex // getParents or getChildren
  37. filterAdjacentByStatusFn func(*Graph, string, ServiceStatus) []*Vertex // filterChildren or filterParents
  38. targetServiceStatus ServiceStatus
  39. adjacentServiceStatusToSkip ServiceStatus
  40. visitorFn func(context.Context, string) error
  41. maxConcurrency int
  42. }
  43. func upDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal {
  44. return &graphTraversal{
  45. extremityNodesFn: leaves,
  46. adjacentNodesFn: getParents,
  47. filterAdjacentByStatusFn: filterChildren,
  48. adjacentServiceStatusToSkip: ServiceStopped,
  49. targetServiceStatus: ServiceStarted,
  50. visitorFn: visitorFn,
  51. }
  52. }
  53. func downDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal {
  54. return &graphTraversal{
  55. extremityNodesFn: roots,
  56. adjacentNodesFn: getChildren,
  57. filterAdjacentByStatusFn: filterParents,
  58. adjacentServiceStatusToSkip: ServiceStarted,
  59. targetServiceStatus: ServiceStopped,
  60. visitorFn: visitorFn,
  61. }
  62. }
  63. // InDependencyOrder applies the function to the services of the project taking in account the dependency order
  64. func InDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error {
  65. graph, err := NewGraph(project, ServiceStopped)
  66. if err != nil {
  67. return err
  68. }
  69. t := upDirectionTraversal(fn)
  70. for _, option := range options {
  71. option(t)
  72. }
  73. return t.visit(ctx, graph)
  74. }
  75. // InReverseDependencyOrder applies the function to the services of the project in reverse order of dependencies
  76. func InReverseDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error {
  77. graph, err := NewGraph(project, ServiceStarted)
  78. if err != nil {
  79. return err
  80. }
  81. t := downDirectionTraversal(fn)
  82. for _, option := range options {
  83. option(t)
  84. }
  85. return t.visit(ctx, graph)
  86. }
  87. func WithRootNodesAndDown(nodes []string) func(*graphTraversal) {
  88. return func(t *graphTraversal) {
  89. if len(nodes) == 0 {
  90. return
  91. }
  92. originalFn := t.extremityNodesFn
  93. t.extremityNodesFn = func(graph *Graph) []*Vertex {
  94. var want []string
  95. for _, node := range nodes {
  96. vertex := graph.Vertices[node]
  97. want = append(want, vertex.Service)
  98. for _, v := range getAncestors(vertex) {
  99. want = append(want, v.Service)
  100. }
  101. }
  102. t.ignored = map[string]struct{}{}
  103. for k := range graph.Vertices {
  104. if !slices.Contains(want, k) {
  105. t.ignored[k] = struct{}{}
  106. }
  107. }
  108. return originalFn(graph)
  109. }
  110. }
  111. }
  112. func (t *graphTraversal) visit(ctx context.Context, g *Graph) error {
  113. expect := len(g.Vertices)
  114. if expect == 0 {
  115. return nil
  116. }
  117. eg, ctx := errgroup.WithContext(ctx)
  118. if t.maxConcurrency > 0 {
  119. eg.SetLimit(t.maxConcurrency + 1)
  120. }
  121. nodeCh := make(chan *Vertex, expect)
  122. defer close(nodeCh)
  123. // nodeCh need to allow n=expect writers while reader goroutine could have returner after ctx.Done
  124. eg.Go(func() error {
  125. for {
  126. select {
  127. case <-ctx.Done():
  128. return nil
  129. case node := <-nodeCh:
  130. expect--
  131. if expect == 0 {
  132. return nil
  133. }
  134. t.run(ctx, g, eg, t.adjacentNodesFn(node), nodeCh)
  135. }
  136. }
  137. })
  138. nodes := t.extremityNodesFn(g)
  139. t.run(ctx, g, eg, nodes, nodeCh)
  140. return eg.Wait()
  141. }
  142. // Note: this could be `graph.walk` or whatever
  143. func (t *graphTraversal) run(ctx context.Context, graph *Graph, eg *errgroup.Group, nodes []*Vertex, nodeCh chan *Vertex) {
  144. for _, node := range nodes {
  145. // Don't start this service yet if all of its children have
  146. // not been started yet.
  147. if len(t.filterAdjacentByStatusFn(graph, node.Key, t.adjacentServiceStatusToSkip)) != 0 {
  148. continue
  149. }
  150. if !t.consume(node.Key) {
  151. // another worker already visited this node
  152. continue
  153. }
  154. eg.Go(func() error {
  155. var err error
  156. if _, ignore := t.ignored[node.Service]; !ignore {
  157. err = t.visitorFn(ctx, node.Service)
  158. }
  159. if err == nil {
  160. graph.UpdateStatus(node.Key, t.targetServiceStatus)
  161. }
  162. nodeCh <- node
  163. return err
  164. })
  165. }
  166. }
  167. func (t *graphTraversal) consume(nodeKey string) bool {
  168. t.mu.Lock()
  169. defer t.mu.Unlock()
  170. if t.seen == nil {
  171. t.seen = make(map[string]struct{})
  172. }
  173. if _, ok := t.seen[nodeKey]; ok {
  174. return false
  175. }
  176. t.seen[nodeKey] = struct{}{}
  177. return true
  178. }
  179. // Graph represents project as service dependencies
  180. type Graph struct {
  181. Vertices map[string]*Vertex
  182. lock sync.RWMutex
  183. }
  184. // Vertex represents a service in the dependencies structure
  185. type Vertex struct {
  186. Key string
  187. Service string
  188. Status ServiceStatus
  189. Children map[string]*Vertex
  190. Parents map[string]*Vertex
  191. }
  192. func getParents(v *Vertex) []*Vertex {
  193. return v.GetParents()
  194. }
  195. // GetParents returns a slice with the parent vertices of the Vertex
  196. func (v *Vertex) GetParents() []*Vertex {
  197. var res []*Vertex
  198. for _, p := range v.Parents {
  199. res = append(res, p)
  200. }
  201. return res
  202. }
  203. func getChildren(v *Vertex) []*Vertex {
  204. return v.GetChildren()
  205. }
  206. // getAncestors return all descendents for a vertex, might contain duplicates
  207. func getAncestors(v *Vertex) []*Vertex {
  208. var descendents []*Vertex
  209. for _, parent := range v.GetParents() {
  210. descendents = append(descendents, parent)
  211. descendents = append(descendents, getAncestors(parent)...)
  212. }
  213. return descendents
  214. }
  215. // GetChildren returns a slice with the child vertices of the Vertex
  216. func (v *Vertex) GetChildren() []*Vertex {
  217. var res []*Vertex
  218. for _, p := range v.Children {
  219. res = append(res, p)
  220. }
  221. return res
  222. }
  223. // NewGraph returns the dependency graph of the services
  224. func NewGraph(project *types.Project, initialStatus ServiceStatus) (*Graph, error) {
  225. graph := &Graph{
  226. lock: sync.RWMutex{},
  227. Vertices: map[string]*Vertex{},
  228. }
  229. for _, s := range project.Services {
  230. graph.AddVertex(s.Name, s.Name, initialStatus)
  231. }
  232. for index, s := range project.Services {
  233. for _, name := range s.GetDependencies() {
  234. err := graph.AddEdge(s.Name, name)
  235. if err != nil {
  236. if !s.DependsOn[name].Required {
  237. delete(s.DependsOn, name)
  238. project.Services[index] = s
  239. continue
  240. }
  241. if api.IsNotFoundError(err) {
  242. ds, err := project.GetDisabledService(name)
  243. if err == nil {
  244. return nil, fmt.Errorf("service %s is required by %s but is disabled. Can be enabled by profiles %s", name, s.Name, ds.Profiles)
  245. }
  246. }
  247. return nil, err
  248. }
  249. }
  250. }
  251. if b, err := graph.HasCycles(); b {
  252. return nil, err
  253. }
  254. return graph, nil
  255. }
  256. // NewVertex is the constructor function for the Vertex
  257. func NewVertex(key string, service string, initialStatus ServiceStatus) *Vertex {
  258. return &Vertex{
  259. Key: key,
  260. Service: service,
  261. Status: initialStatus,
  262. Parents: map[string]*Vertex{},
  263. Children: map[string]*Vertex{},
  264. }
  265. }
  266. // AddVertex adds a vertex to the Graph
  267. func (g *Graph) AddVertex(key string, service string, initialStatus ServiceStatus) {
  268. g.lock.Lock()
  269. defer g.lock.Unlock()
  270. v := NewVertex(key, service, initialStatus)
  271. g.Vertices[key] = v
  272. }
  273. // AddEdge adds a relationship of dependency between vertices `source` and `destination`
  274. func (g *Graph) AddEdge(source string, destination string) error {
  275. g.lock.Lock()
  276. defer g.lock.Unlock()
  277. sourceVertex := g.Vertices[source]
  278. destinationVertex := g.Vertices[destination]
  279. if sourceVertex == nil {
  280. return fmt.Errorf("could not find %s: %w", source, api.ErrNotFound)
  281. }
  282. if destinationVertex == nil {
  283. return fmt.Errorf("could not find %s: %w", destination, api.ErrNotFound)
  284. }
  285. // If they are already connected
  286. if _, ok := sourceVertex.Children[destination]; ok {
  287. return nil
  288. }
  289. sourceVertex.Children[destination] = destinationVertex
  290. destinationVertex.Parents[source] = sourceVertex
  291. return nil
  292. }
  293. func leaves(g *Graph) []*Vertex {
  294. return g.Leaves()
  295. }
  296. // Leaves returns the slice of leaves of the graph
  297. func (g *Graph) Leaves() []*Vertex {
  298. g.lock.Lock()
  299. defer g.lock.Unlock()
  300. var res []*Vertex
  301. for _, v := range g.Vertices {
  302. if len(v.Children) == 0 {
  303. res = append(res, v)
  304. }
  305. }
  306. return res
  307. }
  308. func roots(g *Graph) []*Vertex {
  309. return g.Roots()
  310. }
  311. // Roots returns the slice of "Roots" of the graph
  312. func (g *Graph) Roots() []*Vertex {
  313. g.lock.Lock()
  314. defer g.lock.Unlock()
  315. var res []*Vertex
  316. for _, v := range g.Vertices {
  317. if len(v.Parents) == 0 {
  318. res = append(res, v)
  319. }
  320. }
  321. return res
  322. }
  323. // UpdateStatus updates the status of a certain vertex
  324. func (g *Graph) UpdateStatus(key string, status ServiceStatus) {
  325. g.lock.Lock()
  326. defer g.lock.Unlock()
  327. g.Vertices[key].Status = status
  328. }
  329. func filterChildren(g *Graph, k string, s ServiceStatus) []*Vertex {
  330. return g.FilterChildren(k, s)
  331. }
  332. // FilterChildren returns children of a certain vertex that are in a certain status
  333. func (g *Graph) FilterChildren(key string, status ServiceStatus) []*Vertex {
  334. g.lock.Lock()
  335. defer g.lock.Unlock()
  336. var res []*Vertex
  337. vertex := g.Vertices[key]
  338. for _, child := range vertex.Children {
  339. if child.Status == status {
  340. res = append(res, child)
  341. }
  342. }
  343. return res
  344. }
  345. func filterParents(g *Graph, k string, s ServiceStatus) []*Vertex {
  346. return g.FilterParents(k, s)
  347. }
  348. // FilterParents returns the parents of a certain vertex that are in a certain status
  349. func (g *Graph) FilterParents(key string, status ServiceStatus) []*Vertex {
  350. g.lock.Lock()
  351. defer g.lock.Unlock()
  352. var res []*Vertex
  353. vertex := g.Vertices[key]
  354. for _, parent := range vertex.Parents {
  355. if parent.Status == status {
  356. res = append(res, parent)
  357. }
  358. }
  359. return res
  360. }
  361. // HasCycles detects cycles in the graph
  362. func (g *Graph) HasCycles() (bool, error) {
  363. discovered := []string{}
  364. finished := []string{}
  365. for _, vertex := range g.Vertices {
  366. path := []string{
  367. vertex.Key,
  368. }
  369. if !slices.Contains(discovered, vertex.Key) && !slices.Contains(finished, vertex.Key) {
  370. var err error
  371. discovered, finished, err = g.visit(vertex.Key, path, discovered, finished)
  372. if err != nil {
  373. return true, err
  374. }
  375. }
  376. }
  377. return false, nil
  378. }
  379. func (g *Graph) visit(key string, path []string, discovered []string, finished []string) ([]string, []string, error) {
  380. discovered = append(discovered, key)
  381. for _, v := range g.Vertices[key].Children {
  382. path := append(path, v.Key)
  383. if slices.Contains(discovered, v.Key) {
  384. return nil, nil, fmt.Errorf("cycle found: %s", strings.Join(path, " -> "))
  385. }
  386. if !slices.Contains(finished, v.Key) {
  387. if _, _, err := g.visit(v.Key, path, discovered, finished); err != nil {
  388. return nil, nil, err
  389. }
  390. }
  391. }
  392. discovered = remove(discovered, key)
  393. finished = append(finished, key)
  394. return discovered, finished, nil
  395. }
  396. func remove(slice []string, item string) []string {
  397. var s []string
  398. for _, i := range slice {
  399. if i != item {
  400. s = append(s, i)
  401. }
  402. }
  403. return s
  404. }