summaryrefslogtreecommitdiff
path: root/plugin/executor/containerd/containerd.go
blob: 2d3b99fe4cfc07eec6d9f7e062b5c944f91e971a (plain)
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
package containerd // import "github.com/docker/docker/plugin/executor/containerd"

import (
	"context"
	"fmt"
	"io"
	"sync"
	"syscall"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/cio"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/errdefs"
	"github.com/docker/docker/libcontainerd"
	libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
	specs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

// ExitHandler represents an object that is called when the exit event is received from containerd
type ExitHandler interface {
	HandleExitEvent(id string) error
}

// New creates a new containerd plugin executor
func New(ctx context.Context, rootDir string, cli *containerd.Client, ns string, exitHandler ExitHandler, runtime types.Runtime) (*Executor, error) {
	e := &Executor{
		rootDir:     rootDir,
		exitHandler: exitHandler,
		runtime:     runtime,
		plugins:     make(map[string]*c8dPlugin),
	}

	client, err := libcontainerd.NewClient(ctx, cli, rootDir, ns, e)
	if err != nil {
		return nil, errors.Wrap(err, "error creating containerd exec client")
	}
	e.client = client
	return e, nil
}

// Executor is the containerd client implementation of a plugin executor
type Executor struct {
	rootDir     string
	client      libcontainerdtypes.Client
	exitHandler ExitHandler
	runtime     types.Runtime

	mu      sync.Mutex // Guards plugins map
	plugins map[string]*c8dPlugin
}

type c8dPlugin struct {
	log *logrus.Entry
	ctr libcontainerdtypes.Container
	tsk libcontainerdtypes.Task
}

// deleteTaskAndContainer deletes plugin task and then plugin container from containerd
func (p c8dPlugin) deleteTaskAndContainer(ctx context.Context) {
	if p.tsk != nil {
		if _, err := p.tsk.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
			p.log.WithError(err).Error("failed to delete plugin task from containerd")
		}
	}
	if p.ctr != nil {
		if err := p.ctr.Delete(ctx); err != nil && !errdefs.IsNotFound(err) {
			p.log.WithError(err).Error("failed to delete plugin container from containerd")
		}
	}
}

// Create creates a new container
func (e *Executor) Create(id string, spec specs.Spec, stdout, stderr io.WriteCloser) error {
	ctx := context.Background()
	log := logrus.WithField("plugin", id)
	ctr, err := e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
	if err != nil {
		ctr2, err2 := e.client.LoadContainer(ctx, id)
		if err2 != nil {
			if !errdefs.IsNotFound(err2) {
				log.WithError(err2).Warn("Received an error while attempting to load containerd container for plugin")
			}
		} else {
			status := containerd.Unknown
			t, err2 := ctr2.Task(ctx)
			if err2 != nil {
				if !errdefs.IsNotFound(err2) {
					log.WithError(err2).Warn("Received an error while attempting to load containerd task for plugin")
				}
			} else {
				s, err2 := t.Status(ctx)
				if err2 != nil {
					log.WithError(err2).Warn("Received an error while attempting to read plugin status")
				} else {
					status = s.Status
				}
			}
			if status != containerd.Running && status != containerd.Unknown {
				if err2 := ctr2.Delete(ctx); err2 != nil && !errdefs.IsNotFound(err2) {
					log.WithError(err2).Error("Error cleaning up containerd container")
				}
				ctr, err = e.client.NewContainer(ctx, id, &spec, e.runtime.Shim.Binary, e.runtime.Shim.Opts)
			}
		}

		if err != nil {
			return errors.Wrap(err, "error creating containerd container")
		}
	}

	p := c8dPlugin{log: log, ctr: ctr}
	p.tsk, err = ctr.Start(ctx, "", false, attachStreamsFunc(stdout, stderr))
	if err != nil {
		p.deleteTaskAndContainer(ctx)
		return err
	}
	e.mu.Lock()
	defer e.mu.Unlock()
	e.plugins[id] = &p
	return nil
}

// Restore restores a container
func (e *Executor) Restore(id string, stdout, stderr io.WriteCloser) (bool, error) {
	ctx := context.Background()
	p := c8dPlugin{log: logrus.WithField("plugin", id)}
	ctr, err := e.client.LoadContainer(ctx, id)
	if err != nil {
		if errdefs.IsNotFound(err) {
			return false, nil
		}
		return false, err
	}
	p.tsk, err = ctr.AttachTask(ctx, attachStreamsFunc(stdout, stderr))
	if err != nil {
		if errdefs.IsNotFound(err) {
			p.deleteTaskAndContainer(ctx)
			return false, nil
		}
		return false, err
	}
	s, err := p.tsk.Status(ctx)
	if err != nil {
		if errdefs.IsNotFound(err) {
			// Task vanished after attaching?
			p.tsk = nil
			p.deleteTaskAndContainer(ctx)
			return false, nil
		}
		return false, err
	}
	if s.Status == containerd.Stopped {
		p.deleteTaskAndContainer(ctx)
		return false, nil
	}
	e.mu.Lock()
	defer e.mu.Unlock()
	e.plugins[id] = &p
	return true, nil
}

// IsRunning returns if the container with the given id is running
func (e *Executor) IsRunning(id string) (bool, error) {
	e.mu.Lock()
	p := e.plugins[id]
	e.mu.Unlock()
	if p == nil {
		return false, errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
	}
	status, err := p.tsk.Status(context.Background())
	return status.Status == containerd.Running, err
}

// Signal sends the specified signal to the container
func (e *Executor) Signal(id string, signal syscall.Signal) error {
	e.mu.Lock()
	p := e.plugins[id]
	e.mu.Unlock()
	if p == nil {
		return errdefs.NotFound(fmt.Errorf("unknown plugin %q", id))
	}
	return p.tsk.Kill(context.Background(), signal)
}

// ProcessEvent handles events from containerd
// All events are ignored except the exit event, which is sent of to the stored handler
func (e *Executor) ProcessEvent(id string, et libcontainerdtypes.EventType, ei libcontainerdtypes.EventInfo) error {
	switch et {
	case libcontainerdtypes.EventExit:
		e.mu.Lock()
		p := e.plugins[id]
		e.mu.Unlock()
		if p == nil {
			logrus.WithField("id", id).Warn("Received exit event for an unknown plugin")
		} else {
			p.deleteTaskAndContainer(context.Background())
		}
		return e.exitHandler.HandleExitEvent(ei.ContainerID)
	}
	return nil
}

type rio struct {
	cio.IO

	wg sync.WaitGroup
}

func (c *rio) Wait() {
	c.wg.Wait()
	c.IO.Wait()
}

func attachStreamsFunc(stdout, stderr io.WriteCloser) libcontainerdtypes.StdioCallback {
	return func(iop *cio.DirectIO) (cio.IO, error) {
		if iop.Stdin != nil {
			iop.Stdin.Close()
			// closing stdin shouldn't be needed here, it should never be open
			panic("plugin stdin shouldn't have been created!")
		}

		rio := &rio{IO: iop}
		rio.wg.Add(2)
		go func() {
			io.Copy(stdout, iop.Stdout)
			stdout.Close()
			rio.wg.Done()
		}()
		go func() {
			io.Copy(stderr, iop.Stderr)
			stderr.Close()
			rio.wg.Done()
		}()
		return rio, nil
	}
}