dependencies.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. "strings"
  18. "sync"
  19. "github.com/compose-spec/compose-go/types"
  20. "golang.org/x/sync/errgroup"
  21. "github.com/docker/compose/v2/pkg/utils"
  22. )
  23. // ServiceStatus indicates the status of a service
  24. type ServiceStatus int
  25. // Services status flags
  26. const (
  27. ServiceStopped ServiceStatus = iota
  28. ServiceStarted
  29. )
  30. type graphTraversal struct {
  31. mu sync.Mutex
  32. seen map[string]struct{}
  33. extremityNodesFn func(*Graph) []*Vertex // leaves or roots
  34. adjacentNodesFn func(*Vertex) []*Vertex // getParents or getChildren
  35. filterAdjacentByStatusFn func(*Graph, string, ServiceStatus) []*Vertex // filterChildren or filterParents
  36. targetServiceStatus ServiceStatus
  37. adjacentServiceStatusToSkip ServiceStatus
  38. visitorFn func(context.Context, string) error
  39. }
  40. func upDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal {
  41. return &graphTraversal{
  42. extremityNodesFn: leaves,
  43. adjacentNodesFn: getParents,
  44. filterAdjacentByStatusFn: filterChildren,
  45. adjacentServiceStatusToSkip: ServiceStopped,
  46. targetServiceStatus: ServiceStarted,
  47. visitorFn: visitorFn,
  48. }
  49. }
  50. func downDirectionTraversal(visitorFn func(context.Context, string) error) *graphTraversal {
  51. return &graphTraversal{
  52. extremityNodesFn: roots,
  53. adjacentNodesFn: getChildren,
  54. filterAdjacentByStatusFn: filterParents,
  55. adjacentServiceStatusToSkip: ServiceStarted,
  56. targetServiceStatus: ServiceStopped,
  57. visitorFn: visitorFn,
  58. }
  59. }
  60. // InDependencyOrder applies the function to the services of the project taking in account the dependency order
  61. func InDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error, options ...func(*graphTraversal)) error {
  62. graph, err := NewGraph(project.Services, ServiceStopped)
  63. if err != nil {
  64. return err
  65. }
  66. t := upDirectionTraversal(fn)
  67. return t.visit(ctx, graph)
  68. }
  69. // InReverseDependencyOrder applies the function to the services of the project in reverse order of dependencies
  70. func InReverseDependencyOrder(ctx context.Context, project *types.Project, fn func(context.Context, string) error) error {
  71. graph, err := NewGraph(project.Services, ServiceStarted)
  72. if err != nil {
  73. return err
  74. }
  75. t := downDirectionTraversal(fn)
  76. return t.visit(ctx, graph)
  77. }
  78. func (t *graphTraversal) visit(ctx context.Context, g *Graph) error {
  79. nodes := t.extremityNodesFn(g)
  80. eg, ctx := errgroup.WithContext(ctx)
  81. t.run(ctx, g, eg, nodes)
  82. return eg.Wait()
  83. }
  84. // Note: this could be `graph.walk` or whatever
  85. func (t *graphTraversal) run(ctx context.Context, graph *Graph, eg *errgroup.Group, nodes []*Vertex) {
  86. for _, node := range nodes {
  87. // Don't start this service yet if all of its children have
  88. // not been started yet.
  89. if len(t.filterAdjacentByStatusFn(graph, node.Key, t.adjacentServiceStatusToSkip)) != 0 {
  90. continue
  91. }
  92. node := node
  93. if !t.consume(node.Key) {
  94. // another worker already visited this node
  95. continue
  96. }
  97. eg.Go(func() error {
  98. err := t.visitorFn(ctx, node.Service)
  99. if err != nil {
  100. return err
  101. }
  102. graph.UpdateStatus(node.Key, t.targetServiceStatus)
  103. t.run(ctx, graph, eg, t.adjacentNodesFn(node))
  104. return nil
  105. })
  106. }
  107. }
  108. func (t *graphTraversal) consume(nodeKey string) bool {
  109. t.mu.Lock()
  110. defer t.mu.Unlock()
  111. if t.seen == nil {
  112. t.seen = make(map[string]struct{})
  113. }
  114. if _, ok := t.seen[nodeKey]; ok {
  115. return false
  116. }
  117. t.seen[nodeKey] = struct{}{}
  118. return true
  119. }
  120. // Graph represents project as service dependencies
  121. type Graph struct {
  122. Vertices map[string]*Vertex
  123. lock sync.RWMutex
  124. }
  125. // Vertex represents a service in the dependencies structure
  126. type Vertex struct {
  127. Key string
  128. Service string
  129. Status ServiceStatus
  130. Children map[string]*Vertex
  131. Parents map[string]*Vertex
  132. }
  133. func getParents(v *Vertex) []*Vertex {
  134. return v.GetParents()
  135. }
  136. // GetParents returns a slice with the parent vertices of the a Vertex
  137. func (v *Vertex) GetParents() []*Vertex {
  138. var res []*Vertex
  139. for _, p := range v.Parents {
  140. res = append(res, p)
  141. }
  142. return res
  143. }
  144. func getChildren(v *Vertex) []*Vertex {
  145. return v.GetChildren()
  146. }
  147. // GetChildren returns a slice with the child vertices of the a Vertex
  148. func (v *Vertex) GetChildren() []*Vertex {
  149. var res []*Vertex
  150. for _, p := range v.Children {
  151. res = append(res, p)
  152. }
  153. return res
  154. }
  155. // NewGraph returns the dependency graph of the services
  156. func NewGraph(services types.Services, initialStatus ServiceStatus) (*Graph, error) {
  157. graph := &Graph{
  158. lock: sync.RWMutex{},
  159. Vertices: map[string]*Vertex{},
  160. }
  161. for _, s := range services {
  162. graph.AddVertex(s.Name, s.Name, initialStatus)
  163. }
  164. for _, s := range services {
  165. for _, name := range s.GetDependencies() {
  166. _ = graph.AddEdge(s.Name, name)
  167. }
  168. }
  169. if b, err := graph.HasCycles(); b {
  170. return nil, err
  171. }
  172. return graph, nil
  173. }
  174. // NewVertex is the constructor function for the Vertex
  175. func NewVertex(key string, service string, initialStatus ServiceStatus) *Vertex {
  176. return &Vertex{
  177. Key: key,
  178. Service: service,
  179. Status: initialStatus,
  180. Parents: map[string]*Vertex{},
  181. Children: map[string]*Vertex{},
  182. }
  183. }
  184. // AddVertex adds a vertex to the Graph
  185. func (g *Graph) AddVertex(key string, service string, initialStatus ServiceStatus) {
  186. g.lock.Lock()
  187. defer g.lock.Unlock()
  188. v := NewVertex(key, service, initialStatus)
  189. g.Vertices[key] = v
  190. }
  191. // AddEdge adds a relationship of dependency between vertices `source` and `destination`
  192. func (g *Graph) AddEdge(source string, destination string) error {
  193. g.lock.Lock()
  194. defer g.lock.Unlock()
  195. sourceVertex := g.Vertices[source]
  196. destinationVertex := g.Vertices[destination]
  197. if sourceVertex == nil {
  198. return fmt.Errorf("could not find %s", source)
  199. }
  200. if destinationVertex == nil {
  201. return fmt.Errorf("could not find %s", destination)
  202. }
  203. // If they are already connected
  204. if _, ok := sourceVertex.Children[destination]; ok {
  205. return nil
  206. }
  207. sourceVertex.Children[destination] = destinationVertex
  208. destinationVertex.Parents[source] = sourceVertex
  209. return nil
  210. }
  211. func leaves(g *Graph) []*Vertex {
  212. return g.Leaves()
  213. }
  214. // Leaves returns the slice of leaves of the graph
  215. func (g *Graph) Leaves() []*Vertex {
  216. g.lock.Lock()
  217. defer g.lock.Unlock()
  218. var res []*Vertex
  219. for _, v := range g.Vertices {
  220. if len(v.Children) == 0 {
  221. res = append(res, v)
  222. }
  223. }
  224. return res
  225. }
  226. func roots(g *Graph) []*Vertex {
  227. return g.Roots()
  228. }
  229. // Roots returns the slice of "Roots" of the graph
  230. func (g *Graph) Roots() []*Vertex {
  231. g.lock.Lock()
  232. defer g.lock.Unlock()
  233. var res []*Vertex
  234. for _, v := range g.Vertices {
  235. if len(v.Parents) == 0 {
  236. res = append(res, v)
  237. }
  238. }
  239. return res
  240. }
  241. // UpdateStatus updates the status of a certain vertex
  242. func (g *Graph) UpdateStatus(key string, status ServiceStatus) {
  243. g.lock.Lock()
  244. defer g.lock.Unlock()
  245. g.Vertices[key].Status = status
  246. }
  247. func filterChildren(g *Graph, k string, s ServiceStatus) []*Vertex {
  248. return g.FilterChildren(k, s)
  249. }
  250. // FilterChildren returns children of a certain vertex that are in a certain status
  251. func (g *Graph) FilterChildren(key string, status ServiceStatus) []*Vertex {
  252. g.lock.Lock()
  253. defer g.lock.Unlock()
  254. var res []*Vertex
  255. vertex := g.Vertices[key]
  256. for _, child := range vertex.Children {
  257. if child.Status == status {
  258. res = append(res, child)
  259. }
  260. }
  261. return res
  262. }
  263. func filterParents(g *Graph, k string, s ServiceStatus) []*Vertex {
  264. return g.FilterParents(k, s)
  265. }
  266. // FilterParents returns the parents of a certain vertex that are in a certain status
  267. func (g *Graph) FilterParents(key string, status ServiceStatus) []*Vertex {
  268. g.lock.Lock()
  269. defer g.lock.Unlock()
  270. var res []*Vertex
  271. vertex := g.Vertices[key]
  272. for _, parent := range vertex.Parents {
  273. if parent.Status == status {
  274. res = append(res, parent)
  275. }
  276. }
  277. return res
  278. }
  279. // HasCycles detects cycles in the graph
  280. func (g *Graph) HasCycles() (bool, error) {
  281. discovered := []string{}
  282. finished := []string{}
  283. for _, vertex := range g.Vertices {
  284. path := []string{
  285. vertex.Key,
  286. }
  287. if !utils.StringContains(discovered, vertex.Key) && !utils.StringContains(finished, vertex.Key) {
  288. var err error
  289. discovered, finished, err = g.visit(vertex.Key, path, discovered, finished)
  290. if err != nil {
  291. return true, err
  292. }
  293. }
  294. }
  295. return false, nil
  296. }
  297. func (g *Graph) visit(key string, path []string, discovered []string, finished []string) ([]string, []string, error) {
  298. discovered = append(discovered, key)
  299. for _, v := range g.Vertices[key].Children {
  300. path := append(path, v.Key)
  301. if utils.StringContains(discovered, v.Key) {
  302. return nil, nil, fmt.Errorf("cycle found: %s", strings.Join(path, " -> "))
  303. }
  304. if !utils.StringContains(finished, v.Key) {
  305. if _, _, err := g.visit(v.Key, path, discovered, finished); err != nil {
  306. return nil, nil, err
  307. }
  308. }
  309. }
  310. discovered = remove(discovered, key)
  311. finished = append(finished, key)
  312. return discovered, finished, nil
  313. }
  314. func remove(slice []string, item string) []string {
  315. var s []string
  316. for _, i := range slice {
  317. if i != item {
  318. s = append(s, i)
  319. }
  320. }
  321. return s
  322. }