-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathcommands.go
More file actions
344 lines (304 loc) · 9.33 KB
/
Copy pathcommands.go
File metadata and controls
344 lines (304 loc) · 9.33 KB
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
339
340
341
342
343
344
package worker
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/open-lambda/open-lambda/go/common"
"github.com/open-lambda/open-lambda/go/worker/event"
"github.com/open-lambda/open-lambda/go/worker/sandbox/cgroups"
"github.com/urfave/cli/v2"
)
// performs an HTTP GET request to the worker over its UDS
func udsGet(requestPath string) (*http.Response, error) {
sockPath := filepath.Join(common.Conf.Worker_dir, "ol.sock")
// create a transport that dials the socket
tr := &http.Transport{}
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "unix", sockPath)
}
client := &http.Client{Transport: tr, Timeout: 2 * time.Second}
// perform HTTP GET request with custom client
url := "http://unix" + requestPath
return client.Get(url)
}
// initCmd corresponds to the "init" command of the admin tool.
func initCmd(ctx *cli.Context) error {
if os.Getuid() != 0 {
return fmt.Errorf("'ol worker init' must be run with sudo")
}
olPath, err := common.GetOlPath(ctx)
if err != nil {
return fmt.Errorf("init failed to get OL path: %w", err)
}
if err := common.LoadDefaults(olPath); err != nil {
return fmt.Errorf("init failed to load config defaults: %w", err)
}
if err := initOLDir(olPath, ctx.String("image"), ctx.Bool("newbase")); err != nil {
return fmt.Errorf("init failed to create OL directory: %w", err)
}
if err := cgroups.InitPoolRoot(common.CgroupPoolPath(olPath)); err != nil {
return fmt.Errorf("init failed to create cgroup pool: %w", err)
}
fmt.Printf("\nYou may optionally modify the defaults here: %s\n\n",
filepath.Join(olPath, "config.json"))
fmt.Printf("Next start a worker using the \"ol worker up\" command.\n")
return nil
}
// upCmd corresponds to the "up" command of the admin tool.
// If it returns a non-nil error at any point, `urfave/cli` will
// automatically catch it, print the error message to stderr.
// Then we exit the program and return to main, where we call os.Exit(1)
func upCmd(ctx *cli.Context) error {
// get path of worker files
olPath, err := common.GetOlPath(ctx)
if err != nil {
return err
}
// PREP STEP 1: make sure we have a worker directory
if _, err := os.Stat(olPath); os.IsNotExist(err) {
// need to init worker dir first
fmt.Printf("Did not find OL directory at %s\n", olPath)
if err := common.LoadDefaults(olPath); err != nil {
return err
}
if err := initOLDir(olPath, ctx.String("image"), false); err != nil {
return err
}
}
// PREP STEP 2: load config file and apply any command-line overrides
confPath := filepath.Join(olPath, "config.json")
overrides := ctx.String("options")
if overrides != "" {
overridesPath := confPath + ".overrides"
err = overrideOpts(confPath, overridesPath, overrides)
if err != nil {
return err
}
confPath = overridesPath
}
if err := common.LoadGlobalConfig(confPath); err != nil {
return err
}
// PREP STEP 3: ensure Open Lambda is in the StoppedClean state
if err := bringToStoppedClean(olPath); err != nil {
return err
}
// should we run as a background process?
detach := ctx.Bool("detach")
if detach {
// stdout+stderr both go to log
logPath := filepath.Join(olPath, "worker.out")
// creates a worker.out file
f, err := os.Create(logPath)
if err != nil {
return err
}
// holds attributes that will be used when os.StartProcess.
// we use CLONE_NEWNS because ol creates many mount points.
// we don't want them to show up in /proc/self/mountinfo
// for systemd because systemd creates a service for each
// mount point, which is a major overhead.
attr := os.ProcAttr{
Files: []*os.File{nil, f, f},
Sys: &syscall.SysProcAttr{
Unshareflags: syscall.CLONE_NEWNS,
},
}
cmd := []string{}
for _, arg := range os.Args {
if arg != "-d" && arg != "--detach" {
cmd = append(cmd, arg)
}
}
// looks for ./ol path
binPath, err := exec.LookPath(os.Args[0])
if err != nil {
return err
}
// start the worker process
fmt.Printf("Starting worker in %s and waiting until it's ready.\n", olPath)
proc, err := os.StartProcess(binPath, cmd, &attr)
if err != nil {
return err
}
// died is error message
died := make(chan error)
go func() {
_, err := proc.Wait()
died <- err
}()
fmt.Printf("\tPID: %d\n\tPort: %s\n\tLog File: %s\n", proc.Pid, common.Conf.Worker_port, logPath)
var pingErr error
for i := 0; i < 300; i++ {
// check if it has died
select {
case err := <-died:
if err != nil {
return err
}
return fmt.Errorf("worker process %d does not appear to be running; check worker.out", proc.Pid)
default:
}
// is the worker still alive?
err := proc.Signal(syscall.Signal(0))
if err != nil {
}
// is it reachable?
response, err := udsGet("/pid")
if err != nil {
pingErr = err
time.Sleep(100 * time.Millisecond)
continue
}
defer response.Body.Close()
// are we talking with the expected PID?
body, err := ioutil.ReadAll(response.Body)
pid, err := strconv.Atoi(strings.TrimSpace(string(body)))
if err != nil {
return fmt.Errorf("/pid did not return an int: %s", err)
}
if pid == proc.Pid {
fmt.Printf("Ready!\n")
return nil // server is started and ready for requests
}
return fmt.Errorf("pid mismatch: expected %v but found %v (another worker running?)", proc.Pid, pid)
}
return fmt.Errorf("worker still not reachable after 30 seconds: %w", pingErr)
}
// server had clean shutdown
return event.Main()
}
// statusCmd corresponds to the "status" command of the admin tool.
func statusCmd(ctx *cli.Context) error {
olPath, err := common.GetOlPath(ctx)
if err != nil {
return err
}
err = common.LoadGlobalConfig(filepath.Join(olPath, "config.json"))
if err != nil {
return err
}
fmt.Printf("Worker Ping:\n")
url := fmt.Sprintf("http://localhost:%s/status", common.Conf.Worker_port)
response, err := http.Get(url)
if err != nil {
return fmt.Errorf("could not send GET to %s", url)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("failed to read body from GET to %s", url)
}
fmt.Printf(" %s => %s [%s]\n", url, body, response.Status)
fmt.Printf("\n")
return nil
}
// downCmd corresponds to the "down" command of the admin tool.
func downCmd(ctx *cli.Context) error {
olPath, err := common.GetOlPath(ctx)
if err != nil {
return err
}
err = common.LoadGlobalConfig(filepath.Join(olPath, "config.json"))
if err != nil {
return err
}
return bringToStoppedClean(olPath)
}
// cleanupCmd corresponds to the "force-cleanup" command of the admin tool.
func cleanupCmd(ctx *cli.Context) error {
olPath, err := common.GetOlPath(ctx)
if err != nil {
return err
}
err = common.LoadGlobalConfig(filepath.Join(olPath, "config.json"))
if err != nil {
return fmt.Errorf("failed to load OL config: %s", err)
}
return bringToStoppedClean(olPath)
}
// WorkerCommands returns a list of CLI commands for the worker.
func WorkerCommands() []*cli.Command {
pathFlag := cli.StringFlag{
Name: "path",
Aliases: []string{"p"},
Usage: "Path location for OL environment",
}
dockerImgFlag := cli.StringFlag{
Name: "image",
Aliases: []string{"i"},
Usage: "Name of Docker image to use for base",
}
cmds := []*cli.Command{
&cli.Command{
Name: "init",
Usage: "Create an OL worker environment, including default config and dump of base image",
UsageText: "ol init [OPTIONS...]",
Description: "A cluster directory of the given name will be created with internal structure initialized.",
Flags: []cli.Flag{
&pathFlag,
&dockerImgFlag,
&cli.BoolFlag{
Name: "newbase",
Aliases: []string{"b"},
Usage: "Overwrite base directory if it already exists",
},
},
Action: initCmd,
},
&cli.Command{
Name: "up",
Usage: "Start an OL worker process (automatically calls 'init' and uses default if that wasn't already done)",
UsageText: "ol up [OPTIONS...] [--detach]",
Description: "Start an OL worker.",
Flags: []cli.Flag{
&pathFlag,
&dockerImgFlag,
&cli.StringFlag{
Name: "options",
Aliases: []string{"o"},
Usage: "Override options with: -o opt1=val1,opt2=val2/opt3.subopt31=val3",
},
&cli.BoolFlag{
Name: "detach",
Aliases: []string{"d"},
Usage: "Run worker in background",
},
},
Action: upCmd,
},
&cli.Command{
Name: "down",
Usage: "Kill containers and processes of the worker",
UsageText: "ol down [OPTIONS...]",
Flags: []cli.Flag{&pathFlag},
Action: downCmd,
},
&cli.Command{
Name: "status",
Usage: "check status of an OL worker process",
UsageText: "ol status [OPTIONS...]",
Description: "If no cluster name is specified, number of containers of each cluster is printed; otherwise the connection information for all containers in the given cluster will be displayed.",
Flags: []cli.Flag{&pathFlag},
Action: statusCmd,
},
&cli.Command{
Name: "force-cleanup",
Usage: "Developer use only. Cleanup cgroups and mount points (only needed when OL halted unexpectedly or there's a bug)",
UsageText: "ol force-cleanup [OPTIONS...]",
Flags: []cli.Flag{&pathFlag},
Action: cleanupCmd,
},
}
return cmds
}