forked from containerd/cri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fake_execution_client.go
392 lines (350 loc) · 11.1 KB
/
fake_execution_client.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
/*
Copyright 2017 The Kubernetes Authors.
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 testing
import (
"fmt"
"math/rand"
"sync"
"time"
"github.com/containerd/containerd/api/services/execution"
"github.com/containerd/containerd/api/types/task"
googleprotobuf "github.com/golang/protobuf/ptypes/empty"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
// TaskNotExistError is the fake error returned when task does not exist.
var TaskNotExistError = grpc.Errorf(codes.NotFound, "task does not exist")
// CalledDetail is the struct contains called function name and arguments.
type CalledDetail struct {
// Name of the function called.
Name string
// Argument of the function called.
Argument interface{}
}
var _ execution.Tasks_EventsClient = &EventClient{}
// EventClient is a test implementation of execution.Tasks_EventsClient
type EventClient struct {
Events chan *task.Event
grpc.ClientStream
}
// Recv is a test implementation of Recv
func (cli *EventClient) Recv() (*task.Event, error) {
event, ok := <-cli.Events
if !ok {
return nil, fmt.Errorf("event channel closed")
}
return event, nil
}
// FakeExecutionClient is a simple fake execution client, so that cri-containerd
// can be run for testing without requiring a real containerd setup.
type FakeExecutionClient struct {
sync.Mutex
called []CalledDetail
errors map[string]error
TaskList map[string]task.Task
eventsQueue chan *task.Event
eventClients []*EventClient
}
var _ execution.TasksClient = &FakeExecutionClient{}
// NewFakeExecutionClient creates a FakeExecutionClient
func NewFakeExecutionClient() *FakeExecutionClient {
return &FakeExecutionClient{
errors: make(map[string]error),
TaskList: make(map[string]task.Task),
}
}
// Stop the fake execution service. Needed when event is enabled.
func (f *FakeExecutionClient) Stop() {
if f.eventsQueue != nil {
close(f.eventsQueue)
}
f.Lock()
defer f.Unlock()
for _, client := range f.eventClients {
close(client.Events)
}
f.eventClients = nil
}
// WithEvents setup events publisher for FakeExecutionClient
func (f *FakeExecutionClient) WithEvents() *FakeExecutionClient {
f.eventsQueue = make(chan *task.Event, 1024)
go func() {
for e := range f.eventsQueue {
f.Lock()
for _, client := range f.eventClients {
client.Events <- e
}
f.Unlock()
}
}()
return f
}
func (f *FakeExecutionClient) getError(op string) error {
err, ok := f.errors[op]
if ok {
delete(f.errors, op)
return err
}
return nil
}
// InjectError inject error for call
func (f *FakeExecutionClient) InjectError(fn string, err error) {
f.Lock()
defer f.Unlock()
f.errors[fn] = err
}
// InjectErrors inject errors for calls
func (f *FakeExecutionClient) InjectErrors(errs map[string]error) {
f.Lock()
defer f.Unlock()
for fn, err := range errs {
f.errors[fn] = err
}
}
// ClearErrors clear errors for call
func (f *FakeExecutionClient) ClearErrors() {
f.Lock()
defer f.Unlock()
f.errors = make(map[string]error)
}
func generatePid() uint32 {
rand.Seed(time.Now().Unix())
randPid := uint32(rand.Intn(1000))
return randPid
}
func (f *FakeExecutionClient) sendEvent(event *task.Event) {
if f.eventsQueue != nil {
f.eventsQueue <- event
}
}
func (f *FakeExecutionClient) appendCalled(name string, argument interface{}) {
call := CalledDetail{Name: name, Argument: argument}
f.called = append(f.called, call)
}
// GetCalledNames get names of call
func (f *FakeExecutionClient) GetCalledNames() []string {
f.Lock()
defer f.Unlock()
names := []string{}
for _, detail := range f.called {
names = append(names, detail.Name)
}
return names
}
// ClearCalls clear all call detail.
func (f *FakeExecutionClient) ClearCalls() {
f.Lock()
defer f.Unlock()
f.called = []CalledDetail{}
}
// GetCalledDetails get detail of each call.
func (f *FakeExecutionClient) GetCalledDetails() []CalledDetail {
f.Lock()
defer f.Unlock()
// Copy the list and return.
return append([]CalledDetail{}, f.called...)
}
// SetFakeTasks injects fake tasks.
func (f *FakeExecutionClient) SetFakeTasks(tasks []task.Task) {
f.Lock()
defer f.Unlock()
for _, t := range tasks {
f.TaskList[t.ID] = t
}
}
// Create is a test implementation of execution.Create.
func (f *FakeExecutionClient) Create(ctx context.Context, createOpts *execution.CreateRequest, opts ...grpc.CallOption) (*execution.CreateResponse, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("create", createOpts)
if err := f.getError("create"); err != nil {
return nil, err
}
_, ok := f.TaskList[createOpts.ContainerID]
if ok {
return nil, fmt.Errorf("task already exists")
}
pid := generatePid()
f.TaskList[createOpts.ContainerID] = task.Task{
ContainerID: createOpts.ContainerID,
Pid: pid,
Status: task.StatusCreated,
}
f.sendEvent(&task.Event{
ID: createOpts.ContainerID,
Type: task.Event_CREATE,
Pid: pid,
})
return &execution.CreateResponse{
ContainerID: createOpts.ContainerID,
Pid: pid,
}, nil
}
// Start is a test implementation of execution.Start
func (f *FakeExecutionClient) Start(ctx context.Context, startOpts *execution.StartRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("start", startOpts)
if err := f.getError("start"); err != nil {
return nil, err
}
c, ok := f.TaskList[startOpts.ContainerID]
if !ok {
return nil, TaskNotExistError
}
f.sendEvent(&task.Event{
ID: c.ID,
Type: task.Event_START,
Pid: c.Pid,
})
switch c.Status {
case task.StatusCreated:
c.Status = task.StatusRunning
f.TaskList[startOpts.ContainerID] = c
return &googleprotobuf.Empty{}, nil
case task.StatusStopped:
return &googleprotobuf.Empty{}, fmt.Errorf("cannot start a container that has stopped")
case task.StatusRunning:
return &googleprotobuf.Empty{}, fmt.Errorf("cannot start an already running container")
default:
return &googleprotobuf.Empty{}, fmt.Errorf("cannot start a container in the %s state", c.Status)
}
}
// Delete is a test implementation of execution.Delete
func (f *FakeExecutionClient) Delete(ctx context.Context, deleteOpts *execution.DeleteRequest, opts ...grpc.CallOption) (*execution.DeleteResponse, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("delete", deleteOpts)
if err := f.getError("delete"); err != nil {
return nil, err
}
c, ok := f.TaskList[deleteOpts.ContainerID]
if !ok {
return nil, TaskNotExistError
}
delete(f.TaskList, deleteOpts.ContainerID)
f.sendEvent(&task.Event{
ID: c.ID,
Type: task.Event_EXIT,
Pid: c.Pid,
})
return nil, nil
}
// Info is a test implementation of execution.Info
func (f *FakeExecutionClient) Info(ctx context.Context, infoOpts *execution.InfoRequest, opts ...grpc.CallOption) (*execution.InfoResponse, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("info", infoOpts)
if err := f.getError("info"); err != nil {
return nil, err
}
c, ok := f.TaskList[infoOpts.ContainerID]
if !ok {
return nil, TaskNotExistError
}
return &execution.InfoResponse{Task: &c}, nil
}
// List is a test implementation of execution.List
func (f *FakeExecutionClient) List(ctx context.Context, listOpts *execution.ListRequest, opts ...grpc.CallOption) (*execution.ListResponse, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("list", listOpts)
if err := f.getError("list"); err != nil {
return nil, err
}
resp := &execution.ListResponse{}
for _, c := range f.TaskList {
resp.Tasks = append(resp.Tasks, &task.Task{
ID: c.ID,
Pid: c.Pid,
Status: c.Status,
})
}
return resp, nil
}
// Kill is a test implementation of execution.Kill
func (f *FakeExecutionClient) Kill(ctx context.Context, killOpts *execution.KillRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("kill", killOpts)
if err := f.getError("kill"); err != nil {
return nil, err
}
c, ok := f.TaskList[killOpts.ContainerID]
if !ok {
return nil, TaskNotExistError
}
c.Status = task.StatusStopped
f.TaskList[killOpts.ContainerID] = c
f.sendEvent(&task.Event{
ID: c.ID,
Type: task.Event_EXIT,
Pid: c.Pid,
})
return &googleprotobuf.Empty{}, nil
}
// Events is a test implementation of execution.Events
func (f *FakeExecutionClient) Events(ctx context.Context, eventsOpts *execution.EventsRequest, opts ...grpc.CallOption) (execution.Tasks_EventsClient, error) {
f.Lock()
defer f.Unlock()
f.appendCalled("events", eventsOpts)
if err := f.getError("events"); err != nil {
return nil, err
}
var client = &EventClient{
Events: make(chan *task.Event, 100),
}
f.eventClients = append(f.eventClients, client)
return client, nil
}
// Exec is a test implementation of execution.Exec
func (f *FakeExecutionClient) Exec(ctx context.Context, execOpts *execution.ExecRequest, opts ...grpc.CallOption) (*execution.ExecResponse, error) {
// TODO: implement Exec()
return nil, nil
}
// Pty is a test implementation of execution.Pty
func (f *FakeExecutionClient) Pty(ctx context.Context, ptyOpts *execution.PtyRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
// TODO: implement Pty()
return nil, nil
}
// CloseStdin is a test implementation of execution.CloseStdin
func (f *FakeExecutionClient) CloseStdin(ctx context.Context, closeStdinOpts *execution.CloseStdinRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
// TODO: implement CloseStdin()
return nil, nil
}
// Pause is a test implementation of execution.Pause
func (f *FakeExecutionClient) Pause(ctx context.Context, in *execution.PauseRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
// TODO: implement Pause()
return nil, nil
}
// Resume is a test implementation of execution.Resume
func (f *FakeExecutionClient) Resume(ctx context.Context, in *execution.ResumeRequest, opts ...grpc.CallOption) (*googleprotobuf.Empty, error) {
// TODO: implement Resume()
return nil, nil
}
// Checkpoint is a test implementation of execution.Checkpoint
func (f *FakeExecutionClient) Checkpoint(ctx context.Context, in *execution.CheckpointRequest, opts ...grpc.CallOption) (*execution.CheckpointResponse, error) {
// TODO: implement Checkpoint()
return nil, nil
}
// Processes is a test implementation of execution.Processes
func (f *FakeExecutionClient) Processes(ctx context.Context, in *execution.ProcessesRequest, opts ...grpc.CallOption) (*execution.ProcessesResponse, error) {
// TODO: implement Processes()
return nil, nil
}
// DeleteProcess is a test implementation of execution.DeleteProcess
func (f *FakeExecutionClient) DeleteProcess(ctx context.Context, in *execution.DeleteProcessRequest, opts ...grpc.CallOption) (*execution.DeleteResponse, error) {
// TODO: implement DeleteProcess()
return nil, nil
}