/
daemon.go
432 lines (356 loc) · 10.6 KB
/
daemon.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package daemon
import (
"context"
"fmt"
"path"
"path/filepath"
"reflect"
"github.com/alibaba/pouch/apis/server"
criservice "github.com/alibaba/pouch/cri"
"github.com/alibaba/pouch/cri/stream"
"github.com/alibaba/pouch/ctrd"
"github.com/alibaba/pouch/ctrd/supervisord"
"github.com/alibaba/pouch/daemon/config"
"github.com/alibaba/pouch/daemon/events"
"github.com/alibaba/pouch/daemon/mgr"
"github.com/alibaba/pouch/hookplugins"
"github.com/alibaba/pouch/internal"
"github.com/alibaba/pouch/network/mode"
"github.com/alibaba/pouch/pkg/log"
"github.com/alibaba/pouch/pkg/meta"
"github.com/alibaba/pouch/pkg/system"
systemddaemon "github.com/coreos/go-systemd/daemon"
systemdutil "github.com/coreos/go-systemd/util"
)
// Daemon refers to a daemon.
type Daemon struct {
config *config.Config
containerStore *meta.Store
// ctrdDaemon controls containerd process
ctrdDaemon *supervisord.Daemon
// ctrdClient is grpc client connecting to the containerd
ctrdClient ctrd.APIClient
containerMgr mgr.ContainerMgr
systemMgr mgr.SystemMgr
imageMgr mgr.ImageMgr
volumeMgr mgr.VolumeMgr
networkMgr mgr.NetworkMgr
server server.Server
containerPlugin hookplugins.ContainerPlugin
imagePlugin hookplugins.ImagePlugin
daemonPlugin hookplugins.DaemonPlugin
volumePlugin hookplugins.VolumePlugin
criPlugin hookplugins.CriPlugin
apiPlugin hookplugins.APIPlugin
eventsService *events.Events
}
// NewDaemon constructs a brand new server.
func NewDaemon(cfg *config.Config) *Daemon {
containerStore, err := meta.NewStore(meta.Config{
Driver: "local",
BaseDir: path.Join(cfg.HomeDir, "containers"),
Buckets: []meta.Bucket{
{
Name: meta.MetaJSONFile,
Type: reflect.TypeOf(mgr.Container{}),
},
},
})
if err != nil {
log.With(nil).Errorf("failed to create container meta store: %v", err)
return nil
}
// start containerd
ctrdDaemonOpts := []supervisord.Opt{
supervisord.WithOOMScore(cfg.OOMScoreAdjust),
supervisord.WithGRPCAddress(cfg.ContainerdAddr),
}
if cfg.ContainerdPath != "" {
ctrdDaemonOpts = append(ctrdDaemonOpts, supervisord.WithContainerdBinary(cfg.ContainerdPath))
}
if cfg.Debug {
ctrdDaemonOpts = append(ctrdDaemonOpts, supervisord.WithLogLevel("debug"))
}
ctrdDaemonOpts = append(ctrdDaemonOpts, supervisord.WithV1RuntimeShimDebug())
ctrdDaemon, err := supervisord.Start(context.TODO(),
filepath.Join(cfg.HomeDir, "containerd/root"),
filepath.Join(cfg.HomeDir, "containerd/state"),
ctrdDaemonOpts...,
)
if err != nil {
log.With(nil).Errorf("failed to start containerd: %v", err)
return nil
}
// create containerd client
ctrdClient, err := ctrd.NewClient(
ctrd.WithRPCAddr(cfg.ContainerdAddr),
ctrd.WithDefaultNamespace(cfg.DefaultNamespace),
ctrd.WithInsecureRegistries(cfg.InsecureRegistries),
)
if err != nil {
log.With(nil).Errorf("failed to new containerd's client: %v", err)
return nil
}
if cfg.Snapshotter != "" {
ctrd.SetSnapshotterName(cfg.Snapshotter)
}
if err = ctrdClient.CheckSnapshotterValid(ctrd.CurrentSnapshotterName(context.TODO()), cfg.AllowMultiSnapshotter); err != nil {
log.With(nil).Errorf("failed to check snapshotter driver: %v", err)
return nil
}
log.With(nil).Infof("Snapshotter is set to be %s", ctrd.CurrentSnapshotterName(context.TODO()))
return &Daemon{
config: cfg,
ctrdClient: ctrdClient,
ctrdDaemon: ctrdDaemon,
containerStore: containerStore,
}
}
func (d *Daemon) loadPlugin() error {
var err error
// load daemon plugin if exist
if daemonPlugin := hookplugins.GetDaemonPlugin(); daemonPlugin != nil {
d.daemonPlugin = daemonPlugin
}
// load container plugin if exist
if containerPlugin := hookplugins.GetContainerPlugin(); containerPlugin != nil {
d.containerPlugin = containerPlugin
}
// load image plugin if exist
if imagePlugin := hookplugins.GetImagePlugin(); imagePlugin != nil {
d.imagePlugin = imagePlugin
}
// load volume plugin if exist
if volumePlugin := hookplugins.GetVolumePlugin(); volumePlugin != nil {
d.volumePlugin = volumePlugin
}
// load cri plugin if exist
if criPlugin := hookplugins.GetCriPlugin(); criPlugin != nil {
d.criPlugin = criPlugin
}
// load api plugin if exist
if apiPlugin := hookplugins.GetAPIPlugin(); apiPlugin != nil {
d.apiPlugin = apiPlugin
}
if d.daemonPlugin != nil {
log.With(nil).Infof("invoke pre-start hook in plugin")
if err = d.daemonPlugin.PreStartHook(); err != nil {
return err
}
}
return nil
}
// Run starts daemon.
func (d *Daemon) Run() error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if err := d.loadPlugin(); err != nil {
return err
}
// initializes runtimes real path.
if err := initialRuntime(d.config.HomeDir, d.config.Runtimes); err != nil {
return err
}
d.eventsService = events.NewEvents()
imageMgr, err := internal.GenImageMgr(d.config, d)
if err != nil {
return err
}
d.imageMgr = imageMgr
systemMgr, err := internal.GenSystemMgr(d.config, d)
if err != nil {
return err
}
d.systemMgr = systemMgr
volumeMgr, err := internal.GenVolumeMgr(d.config, d)
if err != nil {
return err
}
d.volumeMgr = volumeMgr
containerMgr, err := internal.GenContainerMgr(ctx, d)
if err != nil {
return err
}
d.containerMgr = containerMgr
// just register containers information here to let
// networkMgr to use.
if err := containerMgr.Load(ctx); err != nil {
return err
}
networkMgr, err := internal.GenNetworkMgr(d.config, d)
if err != nil {
return err
}
d.networkMgr = networkMgr
containerMgr.(*mgr.ContainerManager).NetworkMgr = networkMgr
// after initialize network manager, try to recover all
// running containers
if err := containerMgr.Restore(context.Background()); err != nil {
return err
}
if err := d.addSystemLabels(); err != nil {
return err
}
// init base network
err = d.networkInit(ctx)
if err != nil {
return err
}
// set image proxy
ctrd.SetImageProxy(d.config.ImageProxy)
criStreamRouterCh := make(chan stream.Router)
criReadyCh := make(chan bool)
criStopCh := make(chan error)
go criservice.RunCriService(d.config, d.containerMgr, d.imageMgr, d.volumeMgr, d.criPlugin, criStreamRouterCh, criStopCh, criReadyCh)
streamRouter := <-criStreamRouterCh
d.server = server.Server{
Config: d.config,
ContainerMgr: containerMgr,
SystemMgr: systemMgr,
ImageMgr: imageMgr,
VolumeMgr: volumeMgr,
NetworkMgr: networkMgr,
StreamRouter: streamRouter,
ContainerPlugin: d.containerPlugin,
APIPlugin: d.apiPlugin,
}
httpReadyCh := make(chan bool)
httpCloseCh := make(chan struct{})
go func() {
if err := d.server.Start(httpReadyCh); err != nil {
log.With(nil).Errorf("failed to start http server: %v", err)
}
close(httpCloseCh)
}()
httpReady := <-httpReadyCh
criReady := <-criReadyCh
if httpReady && criReady {
notifySystemd()
}
// close the ready channel
close(httpReadyCh)
close(criReadyCh)
// init buildkit if enable builder functionality
//
// FIXME(fuweid): builder functionality is experimental version, which
// do not impact existing http server and cri grpc server. After it
// is stable, we will check the status of builder and shutdown whole
// daemon if the builder server is down.
if d.config.EnableBuilder {
go func() {
log.With(nil).Info("serving builder server...")
if err := d.runBuilderServer(); err != nil {
log.With(nil).Errorf("failed to serve builder server: %v", err)
}
}()
}
err = <-criStopCh
if err != nil {
return err
}
// Stop pouchd if the server stopped
<-httpCloseCh
log.With(nil).Infof("HTTP server stopped")
return nil
}
// Shutdown stops daemon.
func (d *Daemon) Shutdown() error {
var errMsg string
if err := d.server.Stop(); err != nil {
errMsg = fmt.Sprintf("%s\n", err.Error())
}
log.With(nil).Debugf("Start cleanup containerd...")
if err := d.ctrdClient.Cleanup(); err != nil {
errMsg = fmt.Sprintf("%s\n", err.Error())
}
if err := d.ctrdDaemon.Stop(); err != nil {
errMsg = fmt.Sprintf("%s\n", err.Error())
}
if errMsg != "" {
return fmt.Errorf("failed to shutdown pouchd: %s", errMsg)
}
return nil
}
// Config gets config of daemon.
func (d *Daemon) Config() *config.Config {
return d.config
}
// CtrMgr gets manager of container.
func (d *Daemon) CtrMgr() mgr.ContainerMgr {
return d.containerMgr
}
// ImgMgr gets manager of image.
func (d *Daemon) ImgMgr() mgr.ImageMgr {
return d.imageMgr
}
// VolMgr gets manager of volume.
func (d *Daemon) VolMgr() mgr.VolumeMgr {
return d.volumeMgr
}
// NetMgr gets manager of network.
func (d *Daemon) NetMgr() mgr.NetworkMgr {
return d.networkMgr
}
// Containerd gets containerd client.
func (d *Daemon) Containerd() ctrd.APIClient {
return d.ctrdClient
}
// MetaStore gets store of meta.
func (d *Daemon) MetaStore() *meta.Store {
return d.containerStore
}
func (d *Daemon) networkInit(ctx context.Context) error {
return mode.NetworkModeInit(ctx, d.config.NetworkConfig, d.networkMgr)
}
// ContainerPlugin returns the container plugin fetched from shared file
func (d *Daemon) ContainerPlugin() hookplugins.ContainerPlugin {
return d.containerPlugin
}
// ImagePlugin returns the container plugin fetched from shared file
func (d *Daemon) ImagePlugin() hookplugins.ImagePlugin {
return d.imagePlugin
}
// ShutdownPlugin invoke pre-stop method in daemon plugin if exist
func (d *Daemon) ShutdownPlugin() error {
if d.daemonPlugin != nil {
log.With(nil).Infof("invoke pre-stop hook in plugin")
if err := d.daemonPlugin.PreStopHook(); err != nil {
log.With(nil).Errorf("stop prehook execute error %v", err)
}
}
return nil
}
// EventsService gets Events instance
func (d *Daemon) EventsService() *events.Events {
return d.eventsService
}
// addSystemLabels adds some system labels to daemon's config.
// Currently, pouchd add node ip and serial number to pouchd with the format:
// node_ip=192.168.0.1
// SN=xxxxx
func (d *Daemon) addSystemLabels() error {
d.config.Lock()
defer d.config.Unlock()
if d.config.Labels == nil {
d.config.Labels = make([]string, 0)
}
// get node IP
nodeIP := system.GetNodeIP()
d.config.Labels = append(d.config.Labels, fmt.Sprintf("node_ip=%s", nodeIP))
// get serial number
serialNo := system.GetSerialNumber()
d.config.Labels = append(d.config.Labels, fmt.Sprintf("SN=%s", serialNo))
return nil
}
func notifySystemd() {
if !systemdutil.IsRunningSystemd() {
return
}
sent, err := systemddaemon.SdNotify(false, "READY=1")
if err != nil {
log.With(nil).Errorf("failed to notify systemd for readiness: %v", err)
}
if !sent {
log.With(nil).Errorf("forgot to set Type=notify in systemd service file?")
}
}