-
Notifications
You must be signed in to change notification settings - Fork 1k
/
cmd.go
244 lines (191 loc) · 5.57 KB
/
cmd.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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"github.com/containerd/containerd"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/runtime/restart"
specs "github.com/opencontainers/runtime-spec/specs-go"
log "github.com/sirupsen/logrus"
)
func parseCmd(ctx context.Context, command string, args []string) (*log.Entry, string, string, string, string) {
invoked := filepath.Base(os.Args[0])
flags := flag.NewFlagSet(command, flag.ExitOnError)
flags.Usage = func() {
fmt.Printf("USAGE: %s %s [service]\n\n", invoked, command)
fmt.Printf("Options:\n")
flags.PrintDefaults()
}
sock := flags.String("sock", defaultSocket, "Path to containerd socket")
path := flags.String("path", defaultPath, "Path to service configs")
dumpSpec := flags.String("dump-spec", "", "Dump container spec to file before start")
if err := flags.Parse(args); err != nil {
log.Fatal("Unable to parse args")
}
args = flags.Args()
if len(args) != 1 {
fmt.Println("Please specify the service")
flags.Usage()
os.Exit(1)
}
service := args[0]
log := log.WithFields(log.Fields{
"service": service,
})
return log, service, *sock, *path, *dumpSpec
}
func stopCmd(ctx context.Context, args []string) {
log, service, sock, path, _ := parseCmd(ctx, "stop", args)
log.Infof("Stopping service: %q", service)
id, pid, msg, err := stop(ctx, service, sock, path)
if err != nil {
log.WithError(err).Fatal(msg)
}
log.Debugf("Stopped %s pid %d", id, pid)
}
func startCmd(ctx context.Context, args []string) {
log, service, sock, path, dumpSpec := parseCmd(ctx, "start", args)
log.Infof("Starting service: %q", service)
id, pid, msg, err := start(ctx, service, sock, path, dumpSpec)
if err != nil {
log.WithError(err).Fatal(msg)
}
log.Debugf("Started %s pid %d", id, pid)
}
func restartCmd(ctx context.Context, args []string) {
// validate arguments with the command as "restart"
parseCmd(ctx, "restart", args)
stopCmd(ctx, args)
startCmd(ctx, args)
}
type logio struct {
config cio.Config
}
func (c *logio) Config() cio.Config {
return c.config
}
func (c *logio) Cancel() {
}
func (c *logio) Wait() {
}
func (c *logio) Close() error {
return nil
}
func stop(ctx context.Context, service, sock, basePath string) (string, uint32, string, error) {
path := filepath.Join(basePath, service)
runtimeConfig := getRuntimeConfig(path)
client, err := containerd.New(sock)
if err != nil {
return "", 0, "creating containerd client", err
}
if runtimeConfig.Namespace != "" {
ctx = namespaces.WithNamespace(ctx, runtimeConfig.Namespace)
}
ctr, err := client.LoadContainer(ctx, service)
if err != nil {
return "", 0, "loading container", err
}
err = ctr.Update(ctx, restart.WithNoRestarts)
if err != nil {
return "", 0, "failed to clear restart monitor", err
}
task, err := ctr.Task(ctx, nil)
if err != nil {
return "", 0, "fetching task", err
}
id := ctr.ID()
pid := task.Pid()
err = task.Kill(ctx, 9)
if err != nil {
return "", 0, "killing task", err
}
_, err = task.Wait(ctx)
if err != nil {
return "", 0, "waiting for task to exit", err
}
_, err = task.Delete(ctx)
if err != nil {
return "", 0, "deleting task", err
}
err = ctr.Delete(ctx)
if err != nil {
return "", 0, "deleting container", err
}
return id, pid, "", nil
}
func start(ctx context.Context, service, sock, basePath, dumpSpec string) (string, uint32, string, error) {
path := filepath.Join(basePath, service)
runtimeConfig := getRuntimeConfig(path)
rootfs := filepath.Join(path, "rootfs")
if err := prepareFilesystem(path, runtimeConfig); err != nil {
return "", 0, "preparing filesystem", err
}
client, err := containerd.New(sock)
if err != nil {
return "", 0, "creating containerd client", err
}
var spec *specs.Spec
specf, err := os.Open(filepath.Join(path, "config.json"))
if err != nil {
return "", 0, "failed to read service spec", err
}
if err := json.NewDecoder(specf).Decode(&spec); err != nil {
return "", 0, "failed to parse service spec", err
}
spec.Root.Path = rootfs
if dumpSpec != "" {
d, err := os.Create(dumpSpec)
if err != nil {
return "", 0, "failed to open file for spec dump", err
}
enc := json.NewEncoder(d)
enc.SetIndent("", " ")
if err := enc.Encode(&spec); err != nil {
return "", 0, "failed to write spec dump", err
}
}
if runtimeConfig.Namespace != "" {
ctx = namespaces.WithNamespace(ctx, runtimeConfig.Namespace)
}
ctr, err := client.NewContainer(ctx, service, containerd.WithSpec(spec))
if err != nil {
return "", 0, "failed to create container", err
}
logger := GetLog(varLogDir)
io := func(id string) (cio.IO, error) {
stdoutFile := logger.Path(service + ".out")
stderrFile := logger.Path(service)
return &logio{
cio.Config{
Stdin: "/dev/null",
Stdout: stdoutFile,
Stderr: stderrFile,
Terminal: false,
},
}, nil
}
task, err := ctr.NewTask(ctx, io)
if err != nil {
// Don't bother to destroy the container here.
return "", 0, "failed to create task", err
}
if err := prepareProcess(int(task.Pid()), runtimeConfig); err != nil {
return "", 0, "preparing process", err
}
if err := task.Start(ctx); err != nil {
// Don't destroy the container here so it can be inspected for debugging.
return "", 0, "failed to start task", err
}
if runtimeConfig.NoRestart == nil || *runtimeConfig.NoRestart == false {
err = ctr.Update(ctx, restart.WithStatus(containerd.Running))
if err != nil {
return "", 0, "failed to add restart monitor", err
}
}
return ctr.ID(), task.Pid(), "", nil
}