Skip to content

Commit c6d3403

Browse files
committed
task-runner
1 parent b1d4ebc commit c6d3403

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

internal/task-runner/runner.go

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package taskrunner
2+
3+
import (
4+
"context"
5+
"fmt"
6+
7+
"github.com/docker/docker/client"
8+
cm "github.com/dockersamples/gopher-task-system/internal/container-manager"
9+
"github.com/dockersamples/gopher-task-system/internal/types"
10+
)
11+
12+
type Runner interface {
13+
Run(ctx context.Context, doneCh chan<- bool)
14+
}
15+
16+
type runner struct {
17+
def types.TaskDefinition
18+
containerManager cm.ContainerManager
19+
}
20+
21+
func NewRunner(def types.TaskDefinition) (Runner, error) {
22+
client, err := initDockerClient()
23+
if err != nil {
24+
return nil, err
25+
}
26+
27+
return &runner{
28+
def: def,
29+
containerManager: cm.NewContainerManager(client),
30+
}, nil
31+
}
32+
33+
func initDockerClient() (cm.DockerClient, error) {
34+
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
35+
if err != nil {
36+
return nil, err
37+
}
38+
39+
return cli, nil
40+
}
41+
42+
func (r *runner) Run(ctx context.Context, doneCh chan<- bool) {
43+
taskDoneCh := make(chan bool)
44+
for _, task := range r.def.Tasks {
45+
go r.run(ctx, task, taskDoneCh)
46+
}
47+
48+
taskCompleted := 0
49+
for {
50+
if <-taskDoneCh {
51+
taskCompleted++
52+
}
53+
54+
if taskCompleted == len(r.def.Tasks) {
55+
doneCh <- true
56+
return
57+
}
58+
}
59+
}
60+
61+
func (r *runner) run(ctx context.Context, task types.Task, taskDoneCh chan<- bool) {
62+
defer func() {
63+
taskDoneCh <- true
64+
}()
65+
66+
fmt.Println("preparing task - ", task.Name)
67+
if err := r.containerManager.PullImage(ctx, task.Runner); err != nil {
68+
fmt.Println(err)
69+
return
70+
}
71+
72+
id, err := r.containerManager.CreateContainer(ctx, task)
73+
if err != nil {
74+
fmt.Println(err)
75+
return
76+
}
77+
78+
fmt.Println("starting task - ", task.Name)
79+
err = r.containerManager.StartContainer(ctx, id)
80+
if err != nil {
81+
fmt.Println(err)
82+
return
83+
}
84+
85+
statusSuccess, err := r.containerManager.WaitForContainer(ctx, id)
86+
if err != nil {
87+
fmt.Println(err)
88+
return
89+
}
90+
91+
if statusSuccess {
92+
fmt.Println("completed task - ", task.Name)
93+
94+
// cleanup by removing the task container
95+
if task.Cleanup {
96+
fmt.Println("cleanup task - ", task.Name)
97+
err = r.containerManager.RemoveContainer(ctx, id)
98+
if err != nil {
99+
fmt.Println(err)
100+
}
101+
}
102+
} else {
103+
fmt.Println("failed task - ", task.Name)
104+
}
105+
}

0 commit comments

Comments
 (0)