This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
run_job_action.go
100 lines (84 loc) · 1.89 KB
/
run_job_action.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
package bootstrap
import (
"fmt"
"github.com/flynn/flynn-host/types"
"github.com/flynn/go-flynn/cluster"
)
type RunJobAction struct {
ID string `json:"id"`
Job *host.Job `json:"job"`
}
func init() {
Register("run-job", &RunJobAction{})
}
type RunJobState struct {
*Job
}
func (a *RunJobAction) Run(s *State) (err error) {
js := &RunJobState{}
s.StepData[a.ID] = js
js.Job, err = startJob(s, "", a.Job)
return
}
func startJob(s *State, hostID string, job *host.Job) (*Job, error) {
cc, err := s.ClusterClient()
if err != nil {
return nil, err
}
if hostID == "" {
hostID, err = randomHost(cc)
if err != nil {
return nil, err
}
}
// TODO: filter by tags
job.ID = cluster.RandomJobID("")
data := &Job{HostID: hostID, JobID: job.ID}
hc, err := cc.DialHost(hostID)
if err != nil {
return nil, err
}
defer hc.Close()
jobStatus := make(chan error)
events := make(chan *host.Event)
stream := hc.StreamEvents(data.JobID, events)
go func() {
defer stream.Close()
for e := range events {
switch e.Event {
case "start", "stop":
jobStatus <- nil
return
case "error":
job, err := hc.GetJob(data.JobID)
if err != nil {
jobStatus <- err
return
}
if job.Error == nil {
jobStatus <- fmt.Errorf("bootstrap: unknown error from host")
return
}
jobStatus <- fmt.Errorf("bootstrap: host error while launching job: %q", *job.Error)
return
default:
}
}
jobStatus <- fmt.Errorf("bootstrap: host job stream disconnected unexpectedly: %q", stream.Err())
}()
_, err = cc.AddJobs(&host.AddJobsReq{HostJobs: map[string][]*host.Job{hostID: {job}}})
if err != nil {
return nil, err
}
return data, <-jobStatus
}
func randomHost(cc *cluster.Client) (string, error) {
hosts, err := cc.ListHosts()
if err != nil {
return "", err
}
for _, host := range hosts {
return host.ID, nil
}
return "", cluster.ErrNoServers
}