forked from flynn-archive/flynn-host
/
rpc.go
69 lines (60 loc) · 1.23 KB
/
rpc.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
package main
import (
"errors"
"net/http"
"github.com/flynn/lorne/types"
"github.com/flynn/rpcplus"
)
func rpcServer() {
rpcplus.Register(&Host{})
rpcplus.HandleHTTP()
http.ListenAndServe(":1113", nil)
}
type Host struct{}
const stopTimeout = 1
func (h *Host) JobList(arg struct{}, res *map[string]lorne.Job) error {
*res = state.Get()
return nil
}
func (h *Host) GetJob(id string, res *lorne.Job) error {
job := state.GetJob(id)
if job != nil {
*res = *job
}
return nil
}
func (h *Host) StopJob(id string, res *struct{}) error {
job := state.GetJob(id)
if job == nil {
return errors.New("lorne: unknown job")
}
if job.Status != lorne.StatusRunning {
return errors.New("lorne: job is not running")
}
return Docker.StopContainer(job.ContainerID, stopTimeout)
}
func (h *Host) Stream(id string, stream rpcplus.Stream) error {
ch := make(chan lorne.Event)
state.AddListener(id, ch)
defer func() {
go func() {
// drain to prevent deadlock while removing the listener
for _ = range ch {
}
}()
state.RemoveListener(id, ch)
close(ch)
}()
for {
select {
case event := <-ch:
select {
case stream.Send <- event:
case <-stream.Error:
return nil
}
case <-stream.Error:
return nil
}
}
}