-
Notifications
You must be signed in to change notification settings - Fork 0
/
services_graph.go
82 lines (62 loc) · 1.52 KB
/
services_graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
const (
NotVisited = 0
Visited = 1
CurrentlyVisiting = 2
)
type Graph map[string][]string
type State map[string]int
// helper for topologicalSort function
func topologicalSortHelper(node string, state State, sortedDependency *[]string, graph Graph) {
if state[node] == Visited {
return
}
state[node] = Visited
for _, child := range graph[node] {
topologicalSortHelper(child, state, sortedDependency, graph)
}
*sortedDependency = append(*sortedDependency, node)
}
// simple dfs function
func dfs(node string, state State, graph Graph) bool {
can := true
if state[node] == Visited {
return can
}
if state[node] == CurrentlyVisiting {
can = false
return can
}
state[node] = CurrentlyVisiting
for _, child := range graph[node] {
can = can && dfs(child, state, graph)
}
state[node] = Visited
return can
}
// building dependency graph for processes
func (f *Foreman) buildDependencyGraph() Graph {
graph := make(Graph)
for _, service := range f.services {
graph[service.serviceName] = service.deps
}
return graph
}
// check if there is a cycle in the dependency graph
func (g Graph) isCycleFree() bool {
state := make(State)
cycleFree := true
for node := range g {
cycleFree = cycleFree && dfs(node, state, g)
}
return cycleFree
}
// sort dependency graph
func (g Graph) topologicalSort() []string {
sortedDependency := make([]string, 0)
state := make(State)
for node := range g {
topologicalSortHelper(node, state, &sortedDependency, g)
}
return sortedDependency
}