This repository has been archived by the owner on Apr 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdiff.go
290 lines (250 loc) · 7.75 KB
/
diff.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*-
* Copyright 2015 Grammarly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package compose
import (
"fmt"
"github.com/grammarly/rocker-compose/src/compose/config"
)
// Diff describes a comparison functionality of two container sets: expected and actual
// 'expected' is a list of containers from a spec (compose.yml)
// 'actual' is a list of existing containers in a docker daemon
//
// The Diff function should return the action list that is needed to transition form
// the 'actual' state to the 'expected' one.
type Diff interface {
Diff(expected []*Container, actual []*Container) ([]Action, error)
}
// graph with container dependencies
type graph struct {
ns string
dependencies map[*Container][]*dependency
}
// single dependency (external - means not in our namespace)
type dependency struct {
container *Container
external bool
waitForIt bool
}
// NewDiff returns an implementation of Diff object
func NewDiff(ns string) Diff {
return &graph{
ns: ns,
dependencies: make(map[*Container][]*dependency),
}
}
// Diff compares 'expected' and 'actual' state by detecting changes and building
// a gependency graph, and returns an action list that is needed to transition
// from 'actual' state to 'expected' one.
func (g *graph) Diff(expected []*Container, actual []*Container) (res []Action, err error) {
//filling dependency graph
err = g.buildDependencyGraph(expected, actual)
if err != nil {
res = []Action{}
return
}
//check for cycles in configuration
if g.hasCycles() {
err = fmt.Errorf("Dependencies have cycles, check links and volumes-from")
return
}
res = listContainersToRemove(g.ns, expected, actual)
res = append(res, g.buildExecutionPlan(actual)...)
return
}
func (g *graph) buildDependencyGraph(expected []*Container, actual []*Container) error {
for _, c := range expected {
g.dependencies[c] = []*dependency{}
dependencies, err := resolveDependencies(g.ns, expected, actual, c)
if err != nil {
return err
}
g.dependencies[c] = append(g.dependencies[c], dependencies...)
}
return nil
}
func resolveDependencies(ns string, expected []*Container, actual []*Container, target *Container) (resolved []*dependency, err error) {
resolved = []*dependency{}
toResolve := map[config.ContainerName]*dependency{}
//VolumesFrom
for _, cn := range target.Config.VolumesFrom {
if _, found := toResolve[cn]; !found {
toResolve[cn] = &dependency{external: cn.Namespace != ns}
}
}
//WaitFor
for _, cn := range target.Config.WaitFor {
if d, found := toResolve[cn]; !found {
toResolve[cn] = &dependency{
waitForIt: true,
external: cn.Namespace != ns,
}
} else {
d.waitForIt = true
}
}
//Links
for _, link := range target.Config.Links {
cn := link.ContainerName
if _, found := toResolve[cn]; !found {
toResolve[cn] = &dependency{external: cn.Namespace != ns}
}
}
//Net
if target.Config.Net != nil && target.Config.Net.Type == "container" {
cn := target.Config.Net.Container
if _, found := toResolve[cn]; !found {
toResolve[cn] = &dependency{external: cn.Namespace != ns}
}
}
for name, dep := range toResolve {
// in case of the same namespace, we should find dependency
// in given configuration
var scope = expected
if dep.external {
scope = actual
}
if container := find(scope, &name); container != nil {
dep.container = container
resolved = append(resolved, dep)
continue
}
err = fmt.Errorf("Cannot resolve dependency %s for %s", name, target)
return
}
return
}
func listContainersToRemove(ns string, expected []*Container, actual []*Container) (res []Action) {
for _, a := range actual {
if a.Name.Namespace == ns {
var found bool
for _, e := range expected {
found = found || e.IsSameKind(a)
}
if !found {
res = append(res, NewRemoveContainerAction(a))
}
}
}
return
}
func (g *graph) buildExecutionPlan(actual []*Container) (res []Action) {
visited := map[*Container]bool{}
restarted := map[*Container]struct{}{}
// while number of visited deps less than number of
// dependencies which should be visited - loop
for len(visited) < len(g.dependencies) {
var step = []Action{}
nextDependency:
for container, deps := range g.dependencies {
// if dependency is already visited - skip it
if _, contains := visited[container]; contains {
continue
}
var depActions = []Action{}
var restart bool
// check transitive dependencies of current dependency
for _, dependency := range deps {
if finalized, contains := visited[dependency.container]; !dependency.external && (!contains || !finalized) {
continue nextDependency
}
// for all external dependencies (in other namespace), ensure that it exists
if dependency.waitForIt {
depActions = append(depActions, NewWaitContainerAction(dependency.container))
} else if dependency.external {
depActions = append(depActions, NewEnsureContainerExistAction(dependency.container))
} else {
// if dependency should be restarted - we should restart current one
_, contains := restarted[dependency.container]
restart = restart || contains
}
}
// predefine flag / set false to prevent getting into the same operation
visited[container] = false
// comparing dependency with current state
for _, actualContainer := range actual {
if container.IsSameKind(actualContainer) {
//in configuration was changed or restart forced by dependency - recreate container
if !container.IsEqualTo(actualContainer) || restart {
restartActions := []Action{
NewStepAction(true, depActions...),
NewRemoveContainerAction(actualContainer),
NewRunContainerAction(container),
}
// in recovery mode we have to ensure containers are started
if container.Name.Namespace != g.ns {
restartActions = []Action{
NewStepAction(true, depActions...),
NewEnsureContainerStateAction(container),
}
}
step = append(step, NewStepAction(false, restartActions...))
// mark container as recreated
restarted[container] = struct{}{}
continue nextDependency
}
// adding ensure action if applicable
step = append(step, NewStepAction(true, depActions...))
continue nextDependency
}
}
// container is not exists
step = append(step, NewStepAction(false,
NewStepAction(true, depActions...),
NewRunContainerAction(container),
))
}
//finalize step
for container, visit := range visited {
if !visit {
visited[container] = true
}
}
// adding step to result (step actions will be run concurrently)
res = append(res, NewStepAction(true, step...))
}
return
}
func find(containers []*Container, name *config.ContainerName) *Container {
for _, c := range containers {
if c.Name.IsEqualTo(name) {
return c
}
}
return nil
}
func (g *graph) hasCycles() bool {
for k := range g.dependencies {
if g.hasCycles0([]*Container{k}, k) {
return true
}
}
return false
}
func (g *graph) hasCycles0(path []*Container, curr *Container) bool {
for _, c := range path[:len(path)-1] {
if c.IsSameKind(curr) {
return true
}
}
if deps := g.dependencies[curr]; deps != nil {
for _, d := range deps {
if g.hasCycles0(append(path, d.container), d.container) {
return true
}
}
}
return false
}