This repository has been archived by the owner on Feb 8, 2021. It is now read-only.
/
container.go
338 lines (299 loc) · 8.64 KB
/
container.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/golang/glog"
"github.com/hyperhq/runv/api"
"github.com/hyperhq/runv/hypervisor"
"github.com/hyperhq/runv/lib/linuxsignal"
"github.com/opencontainers/runc/libcontainer/system"
"github.com/opencontainers/runtime-spec/specs-go"
)
func startContainer(vm *hypervisor.Vm, root, container string, spec *specs.Spec, state *State) error {
err := vm.StartContainer(container)
if err != nil {
glog.V(1).Infof("Start Container fail: fail to start container with err: %#v", err)
return err
}
err = syscall.Kill(state.Pid, syscall.SIGUSR1)
if err != nil {
glog.V(1).Infof("failed to notify the shim to work", err.Error())
return err
}
glog.V(3).Infof("change the status of container %s to `running`", container)
state.Status = "running"
state.ContainerCreateTime = time.Now().UTC().Unix()
if err = saveStateFile(root, container, state); err != nil {
return err
}
var pl *ProcessList
if pl, err = NewProcessList(root, container); err != nil {
return err
}
defer pl.Release()
// No need to load, container init process must be the first
var p []Process
cmd := strings.Join(spec.Process.Args, " ")
p = append(p, Process{Id: "init", Pid: state.Pid, CMD: cmd, CreateTime: state.ShimCreateTime})
if err = pl.Save(p); err != nil {
return err
}
err = execPoststartHooks(spec, state)
if err != nil {
glog.V(1).Infof("execute Poststart hooks failed %s", err.Error())
}
return err
}
func createContainer(options runvOptions, vm *hypervisor.Vm, container, bundle, stateRoot string, spec *specs.Spec) (shim *os.Process, err error) {
if err = setupContainerFs(vm, bundle, container, spec); err != nil {
return nil, err
}
defer func() {
if err != nil {
removeContainerFs(sandboxPath(vm), container)
}
}()
glog.V(3).Infof("vm.AddContainer()")
config := api.ContainerDescriptionFromOCF(container, spec)
r := vm.AddContainer(config)
if !r.IsSuccess() {
return nil, fmt.Errorf("add container %s failed: %s", container, r.Message())
}
defer func() {
if err != nil {
vm.RemoveContainer(container)
}
}()
// Prepare container state directory
stateDir := filepath.Join(stateRoot, container)
_, err = os.Stat(stateDir)
if err == nil {
glog.Errorf("Container %s exists", container)
return nil, fmt.Errorf("Container %s exists", container)
}
err = os.MkdirAll(stateDir, 0644)
if err != nil {
glog.V(1).Infof("%s", err.Error())
return nil, err
}
defer func() {
if err != nil {
os.RemoveAll(stateDir)
}
}()
// Create sandbox dir symbol link in container root dir
vmRootLinkPath := filepath.Join(stateDir, "sandbox")
vmRootPath := sandboxPath(vm)
if err = os.Symlink(vmRootPath, vmRootLinkPath); err != nil {
return nil, fmt.Errorf("failed to create symbol link %q: %v", vmRootLinkPath, err)
}
// create shim and save the state
shim, err = createShim(options, container, "init", spec.Process)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
shim.Kill()
}
}()
var stat system.Stat_t
stat, err = system.Stat(shim.Pid)
if err != nil {
return nil, err
}
state := &State{
State: specs.State{
Version: spec.Version,
ID: container,
Status: "created",
Pid: shim.Pid,
Bundle: bundle,
},
ShimCreateTime: stat.StartTime,
}
glog.V(3).Infof("save state id %s, boundle %s", container, bundle)
if err = saveStateFile(stateRoot, container, state); err != nil {
return nil, err
}
err = execPrestartHooks(spec, state)
if err != nil {
glog.V(1).Infof("execute Prestart hooks failed, %s", err.Error())
return nil, err
}
// If runv is launched via docker/containerd, we start netlistener to watch/collect network changes.
// TODO: if runv is launched by cni compatible tools, the cni script can use `runv cni` cmdline to update the network.
// Create the listener process which will enters into the netns of the shim
options.withContainer = state
if err = startNsListener(options, vm); err != nil {
glog.Errorf("start ns listener fail: %v", err)
return nil, err
}
return shim, nil
}
func deleteContainer(vm *hypervisor.Vm, root, container string, force bool, spec *specs.Spec, state *State) error {
// non-force killing can only be performed when at least one of the realProcess and shimProcess exited
exitedVM := true
for _, c := range vm.ContainerList() {
if c == container {
exitedVM = vm.SignalProcess(container, "init", syscall.Signal(0)) != nil // todo: is this check reliable?
break
}
}
exitedHost := !shimProcessAlive(state.Pid, state.ShimCreateTime)
if !exitedVM && !exitedHost && !force {
// don't perform deleting
return fmt.Errorf("the container %s is still alive, use -f to force kill it?", container)
}
if !exitedVM { // force kill the real init process inside the vm
for i := 0; i < 100; i++ {
vm.SignalProcess(container, "init", linuxsignal.SIGKILL)
time.Sleep(100 * time.Millisecond)
if vm.SignalProcess(container, "init", syscall.Signal(0)) != nil {
break
}
}
}
vm.RemoveContainer(container)
return deleteContainerHost(root, container, spec, state)
}
func deleteContainerHost(root, container string, spec *specs.Spec, state *State) error {
if shimProcessAlive(state.Pid, state.ShimCreateTime) { // force kill the shim process in the host
time.Sleep(200 * time.Millisecond) // the shim might be going to exit, wait it
for i := 0; i < 100; i++ {
syscall.Kill(state.Pid, syscall.SIGKILL)
time.Sleep(100 * time.Millisecond)
if !shimProcessAlive(state.Pid, state.ShimCreateTime) {
break
}
}
}
err := execPoststopHooks(spec, state)
if err != nil {
glog.V(1).Infof("execute Poststop hooks failed %s", err.Error())
removeContainerFs(filepath.Join(root, container, "sandbox"), container)
os.RemoveAll(filepath.Join(root, container))
return err // return err of the hooks
}
removeContainerFs(filepath.Join(root, container, "sandbox"), container)
return os.RemoveAll(filepath.Join(root, container))
}
func addProcess(options runvOptions, vm *hypervisor.Vm, container, process string, spec *specs.Process) (shim *os.Process, err error) {
p := &api.Process{
Container: container,
Id: process,
Terminal: spec.Terminal,
Args: spec.Args,
Envs: spec.Env,
Workdir: spec.Cwd,
}
if spec.User.UID != 0 {
p.User = strconv.FormatUint(uint64(spec.User.UID), 10)
}
if spec.User.GID != 0 {
p.Group = strconv.FormatUint(uint64(spec.User.GID), 10)
}
if len(spec.User.AdditionalGids) > 0 {
ag := []string{}
for _, g := range spec.User.AdditionalGids {
ag = append(ag, strconv.FormatUint(uint64(g), 10))
}
p.AdditionalGroup = ag
}
err = vm.AddProcess(p, nil)
if err != nil {
glog.V(1).Infof("add process to container failed: %v", err)
return nil, err
}
defer func() {
if err != nil {
vm.SignalProcess(container, process, linuxsignal.SIGKILL)
}
}()
shim, err = createShim(options, container, process, spec)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
shim.Kill()
}
}()
var stat system.Stat_t
stat, err = system.Stat(shim.Pid)
if err != nil {
return nil, err
}
var pl *ProcessList
if pl, err = NewProcessList(options.GlobalString("root"), container); err != nil {
return nil, err
}
defer pl.Release()
cmd := strings.Join(spec.Args, " ")
err = pl.Add(Process{Id: process, Pid: shim.Pid, CMD: cmd, CreateTime: stat.StartTime})
if err != nil {
return nil, err
}
return shim, nil
}
func execHook(hook specs.Hook, state *State) error {
b, err := json.Marshal(state)
if err != nil {
return err
}
cmd := exec.Cmd{
Path: hook.Path,
Args: hook.Args,
Env: hook.Env,
Stdin: bytes.NewReader(b),
}
return cmd.Run()
}
func execPrestartHooks(rt *specs.Spec, state *State) error {
if rt.Hooks == nil {
return nil
}
for _, hook := range rt.Hooks.Prestart {
err := execHook(hook, state)
if err != nil {
return err
}
}
return nil
}
func execPoststartHooks(rt *specs.Spec, state *State) error {
if rt.Hooks == nil {
return nil
}
for _, hook := range rt.Hooks.Poststart {
err := execHook(hook, state)
if err != nil {
glog.V(1).Infof("exec Poststart hook %s failed %s", hook.Path, err.Error())
}
}
return nil
}
func execPoststopHooks(rt *specs.Spec, state *State) error {
if rt.Hooks == nil {
return nil
}
for _, hook := range rt.Hooks.Poststop {
err := execHook(hook, state)
if err != nil {
glog.V(1).Infof("exec Poststop hook %s failed %s", hook.Path, err.Error())
}
}
return nil
}
func shimProcessAlive(pid int, createTime uint64) bool {
stat, err := system.Stat(pid)
return err == nil && stat.StartTime == createTime && stat.State != system.Zombie && stat.State != system.Dead
}