-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
104 lines (87 loc) · 2.07 KB
/
worker.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
package scheduler
import (
"context"
"io"
"io/ioutil"
"log"
"os"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
)
type Worker struct {
name string
reporter Reporter
taskCh chan Task
stopCh chan struct{}
}
func (w *Worker) Run() {
for {
select {
case task := <-w.taskCh:
ctx := context.Background()
result, err := task.Do(ctx)
if err != nil {
w.reporter.Fail(ctx, task.Name(), []byte(err.Error()))
continue
}
if err := w.reporter.Success(ctx, task.Name(), result); err != nil {
log.Printf("reporter success failed: %s\n", err)
continue
}
case <-w.stopCh:
return
}
}
}
func (w *Worker) Stop() {
close(w.stopCh)
close(w.taskCh)
}
func (w *Worker) RecvTask(ctx context.Context, task Task) error {
w.taskCh <- task
return nil
}
type Task interface {
Name() string
Resource() *Resource
Do(context.Context) ([]byte, error)
}
type containerTask struct {
name string
config *container.Config
hostConfig *container.HostConfig
networkingConfig *network.NetworkingConfig
}
func (t *containerTask) Do(ctx context.Context) ([]byte, error) {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return nil, err
}
reader, err := cli.ImagePull(ctx, t.config.Image, types.ImagePullOptions{})
if err != nil {
return nil, err
}
io.Copy(os.Stdout, reader)
resp, err := cli.ContainerCreate(ctx, t.config, t.hostConfig, t.networkingConfig, nil, t.name)
if err != nil {
return nil, err
}
if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {
return nil, err
}
statusCh, errCh := cli.ContainerWait(ctx, resp.ID, container.WaitConditionNotRunning)
select {
case err := <-errCh:
if err != nil {
return nil, err
}
case <-statusCh:
}
out, err := cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})
if err != nil {
return nil, err
}
return ioutil.ReadAll(out)
}