/
box.go
209 lines (175 loc) · 4.3 KB
/
box.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
package process
import (
"expvar"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sync"
"syscall"
"golang.org/x/net/context"
"github.com/noxiouz/stout/isolate"
"github.com/apex/log"
)
const (
defaultSpoolPath = "/var/spool/cocaine"
)
var (
// can be overwritten for tests
createCodeStorage = func(locator []string) codeStorage {
return &cocaineCodeStorage{
locator: locator,
}
}
)
var (
boxStat = expvar.NewMap("process.box")
)
type codeStorage interface {
Spool(ctx context.Context, appname string) ([]byte, error)
}
type Box struct {
spoolPath string
storage codeStorage
mu sync.Mutex
children map[int]*exec.Cmd
wg sync.WaitGroup
onClose chan struct{}
}
func NewBox(cfg isolate.BoxConfig) (isolate.Box, error) {
spoolPath, ok := cfg["spool"].(string)
if !ok {
spoolPath = defaultSpoolPath
}
var locator []string
if endpoint, ok := cfg["locator"].(string); ok {
locator = append(locator, endpoint)
}
box := &Box{
spoolPath: spoolPath,
storage: createCodeStorage(locator),
children: make(map[int]*exec.Cmd),
onClose: make(chan struct{}),
}
box.wg.Add(1)
go func() {
defer box.wg.Done()
box.sigchldHandler()
}()
boxStat.Set("processes", expvar.Func(func() interface{} {
box.mu.Lock()
defer box.mu.Unlock()
pids := make([]int, 0, len(box.children))
for k := range box.children {
pids = append(pids, k)
}
return pids
}))
return box, nil
}
func (b *Box) Close() error {
close(b.onClose)
b.wg.Wait()
return nil
}
func (b *Box) sigchldHandler() {
sigchld := make(chan os.Signal, 1)
signal.Notify(sigchld, syscall.SIGCHLD)
defer signal.Stop(sigchld)
for {
select {
case <-sigchld:
// NOTE: due to possible signal merging
// Box.wait tries to call Wait unless ECHILD occures
b.wait()
case <-b.onClose:
return
}
}
}
func (b *Box) wait() {
var (
ws syscall.WaitStatus
pid int
err error
)
for {
switch pid, err = syscall.Wait4(-1, &ws, syscall.WNOHANG, nil); err {
case syscall.EINTR:
// pass to retry again
case syscall.ECHILD:
return
case nil:
// NOTE: I fully understand that handling signals from library is a bad idea,
// but there's nothing better in this case
b.mu.Lock()
// If `pid` is not in the map, it means that it's not our worker
pr, ok := b.children[pid]
if ok {
delete(b.children, pid)
}
b.mu.Unlock()
if ok {
// There is no point to check error here,
// as it always returns "Wait error", because Wait4 has been already called.
// But we have to call Wait to close all associated fds and to release other resources
pr.Wait()
boxStat.Add("waited", 1)
}
default:
fmt.Printf("Wait4 error: %v\n", err)
return
}
}
}
// Spawn spawns a new process
func (b *Box) Spawn(ctx context.Context, opts isolate.Profile, name, executable string, args, env map[string]string) (isolate.Process, error) {
spoolPath := b.spoolPath
if val, ok := opts["spool"]; ok {
spoolPath = fmt.Sprintf("%s", val)
}
workDir := filepath.Join(spoolPath, name)
var execPath = executable
if !filepath.IsAbs(executable) {
execPath = filepath.Join(workDir, executable)
}
var (
err error
pr *process
)
defer isolate.GetLogger(ctx).WithFields(
log.Fields{"name": name, "executable": executable,
"workDir": workDir, "execPath": execPath}).Trace("processBox.Spawn").Stop(&err)
// NOTE: once process was put to the map
// its waiter responsibility to Wait for it.
boxStat.Add("spawned", 1)
b.mu.Lock()
defer b.mu.Unlock()
pr, err = newProcess(ctx, execPath, args, env, workDir)
if err != nil {
boxStat.Add("crashed", 1)
return nil, err
}
b.children[pr.cmd.Process.Pid] = pr.cmd
return pr, err
}
// Spool spools code of an app from Cocaine Storage service
func (b *Box) Spool(ctx context.Context, name string, opts isolate.Profile) (err error) {
spoolPath := b.spoolPath
if val, ok := opts["spool"]; ok {
spoolPath = fmt.Sprintf("%s", val)
}
defer isolate.GetLogger(ctx).WithField("name", name).WithField("spoolpath", spoolPath).Trace("processBox.Spool").Stop(&err)
data, err := b.fetch(ctx, name)
if err != nil {
return err
}
if isolate.IsCancelled(ctx) {
return nil
}
return unpackArchive(ctx, data, filepath.Join(spoolPath, name))
}
func (b *Box) fetch(ctx context.Context, appname string) ([]byte, error) {
return b.storage.Spool(ctx, appname)
}