forked from cilium/cilium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
275 lines (242 loc) · 7.25 KB
/
state.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
// Copyright 2016-2017 Authors of Cilium
//
// 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 main
import (
"fmt"
"io/ioutil"
"path/filepath"
"reflect"
"github.com/cilium/cilium/common"
"github.com/cilium/cilium/pkg/endpoint"
"github.com/cilium/cilium/pkg/endpointmanager"
"github.com/cilium/cilium/pkg/events"
log "github.com/Sirupsen/logrus"
dockerAPI "github.com/docker/engine-api/client"
ctx "golang.org/x/net/context"
)
// SyncState syncs cilium state against the containers running in the host. dir is the
// cilium's running directory. If clean is set, the endpoints that don't have its
// container in running state are deleted.
func (d *Daemon) SyncState(dir string, clean bool) error {
restored := 0
log.Info("Recovering old running endpoints...")
dirFiles, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
eptsID := endpoint.FilterEPDir(dirFiles)
possibleEPs := readEPsFromDirNames(dir, eptsID)
if len(possibleEPs) == 0 {
log.Debug("No old endpoints found.")
return nil
}
for _, ep := range possibleEPs {
log.Debugf("Restoring endpoint ID %d", ep.ID)
if err := d.syncLabels(ep); err != nil {
log.Warningf("Unable to restore endpoint %+v: %s", ep, err)
continue
}
if d.conf.KeepConfig {
ep.SetDefaultOpts(nil)
} else {
ep.SetDefaultOpts(d.conf.Opts)
}
if buildSuccess := <-ep.Regenerate(d); !buildSuccess {
continue
}
endpointmanager.Insert(ep)
restored++
log.Infof("Restored endpoint: %d", ep.ID)
}
log.Infof("Restored %d endpoints", restored)
if clean {
d.cleanUpDockerDandlingEndpoints()
}
endpointmanager.Mutex.Lock()
for k := range endpointmanager.Endpoints {
ep := endpointmanager.Endpoints[k]
if err := d.allocateIPs(ep); err != nil {
log.Errorf("Failed while reallocating ep %d's IP addresses: %s. Endpoint won't be restored", ep.ID, err)
d.deleteEndpoint(ep)
continue
}
log.Infof("EP %d's IP addresses successfully reallocated", ep.ID)
if buildSuccess := <-ep.Regenerate(d); !buildSuccess {
log.Warningf("Failed while regenerating endpoint %d: %s", ep.ID, err)
continue
}
ep.Mutex.RLock()
epID := ep.ID
if ep.SecLabel != nil {
epLabels := ep.SecLabel.DeepCopy()
ep.Mutex.RUnlock()
d.events <- *events.NewEvent(events.IdentityAdd, epLabels)
} else {
ep.Mutex.RUnlock()
}
log.Infof("Restored endpoint %d", epID)
}
endpointmanager.Mutex.Unlock()
return nil
}
func (d *Daemon) allocateIPs(ep *endpoint.Endpoint) error {
ep.Mutex.RLock()
defer ep.Mutex.RUnlock()
err := d.AllocateIP(ep.IPv6.IP())
if err != nil {
// TODO if allocation failed reallocate a new IP address and setup veth
// pair accordingly
return fmt.Errorf("unable to reallocate IPv6 address: %s", err)
}
defer func(ep *endpoint.Endpoint) {
if err != nil {
d.ReleaseIP(ep.IPv6.IP())
}
}(ep)
if !d.conf.IPv4Disabled {
if ep.IPv4 != nil {
if err = d.AllocateIP(ep.IPv4.IP()); err != nil {
return fmt.Errorf("unable to reallocate IPv4 address: %s", err)
}
}
}
return nil
}
// readEPsFromDirNames returns a list of endpoints from a list of directory names that
// possible contain an endpoint.
func readEPsFromDirNames(basePath string, eptsDirNames []string) []*endpoint.Endpoint {
possibleEPs := []*endpoint.Endpoint{}
for _, epID := range eptsDirNames {
epDir := filepath.Join(basePath, epID)
readDir := func() string {
log.Debugf("Reading directory %s\n", epDir)
epFiles, err := ioutil.ReadDir(epDir)
if err != nil {
log.Warningf("Error while reading directory %q. Ignoring it...", epDir)
return ""
}
cHeaderFile := common.FindEPConfigCHeader(epDir, epFiles)
if cHeaderFile == "" {
log.Infof("File %q not found in %q. Ignoring endpoint %s.",
common.CHeaderFileName, epDir, epID)
return ""
}
return cHeaderFile
}
// There's an odd issue where the first read dir doesn't work.
cHeaderFile := readDir()
if cHeaderFile == "" {
cHeaderFile = readDir()
}
log.Debugf("Found endpoint C header file %q\n", cHeaderFile)
strEp, err := common.GetCiliumVersionString(cHeaderFile)
if err != nil {
log.Warningf("Unable to read the C header file %q: %s\n", cHeaderFile, err)
continue
}
ep, err := endpoint.ParseEndpoint(strEp)
if err != nil {
log.Warningf("Unable to read the C header file %q: %s\n", cHeaderFile, err)
continue
}
possibleEPs = append(possibleEPs, ep)
}
return possibleEPs
}
// syncLabels syncs the labels from the labels' database for the given endpoint. To be
// used with endpoint.Mutex locked.
func (d *Daemon) syncLabels(ep *endpoint.Endpoint) error {
if ep.SecLabel == nil {
return fmt.Errorf("Endpoint doesn't have a security label.")
}
sha256sum := ep.SecLabel.Labels.SHA256Sum()
labels, err := LookupIdentityBySHA256(sha256sum)
if err != nil {
return fmt.Errorf("Unable to get labels of sha256sum:%s: %+v\n", sha256sum, err)
}
if ep.DockerID == "" {
return nil
}
if labels == nil {
l, _, err := d.CreateOrUpdateIdentity(ep.SecLabel.Labels, ep.StringID())
if err != nil {
return fmt.Errorf("Unable to put labels %+v: %s\n", ep.SecLabel.Labels, err)
}
labels = l
}
if !reflect.DeepEqual(labels.Labels, ep.SecLabel.Labels) {
return fmt.Errorf("The set of labels should be the same for " +
"the endpoint being restored and the labels stored")
}
if labels.ID != ep.SecLabel.ID {
log.Infof("Security label ID for endpoint %d is different "+
"that the one stored, updating from %d to %d\n",
ep.ID, ep.SecLabel.ID, labels.ID)
}
ep.SetIdentity(d, labels)
return nil
}
// cleanUpDockerDandlingEndpoints cleans all endpoints that are dandling by checking out
// if a particular endpoint has its container running.
func (d *Daemon) cleanUpDockerDandlingEndpoints() {
cleanUp := func(ep *endpoint.Endpoint) {
log.Infof("Endpoint %d not found in docker, cleaning up...", ep.ID)
ep.Mutex.RUnlock()
d.deleteEndpoint(ep)
}
for k := range endpointmanager.Endpoints {
ep := endpointmanager.Endpoints[k]
ep.Mutex.RLock()
log.Debugf("Checking if endpoint is running in docker %d", ep.ID)
if ep.DockerNetworkID != "" {
nls, err := d.dockerClient.NetworkInspect(ctx.Background(), ep.DockerNetworkID)
if dockerAPI.IsErrNetworkNotFound(err) {
cleanUp(ep)
continue
}
if err != nil {
ep.Mutex.RUnlock()
continue
}
found := false
for _, v := range nls.Containers {
if v.EndpointID == ep.DockerEndpointID {
found = true
break
}
}
if !found {
cleanUp(ep)
continue
}
} else if ep.DockerID != "" {
cont, err := d.dockerClient.ContainerInspect(ctx.Background(), ep.DockerID)
if dockerAPI.IsErrContainerNotFound(err) {
cleanUp(ep)
continue
}
if err != nil {
ep.Mutex.RUnlock()
continue
}
if !cont.State.Running {
cleanUp(ep)
continue
}
} else {
cleanUp(ep)
continue
}
}
}