forked from aws/aws-lambda-runtime-interface-emulator
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlocal_supervisor.go
More file actions
303 lines (257 loc) · 7.28 KB
/
local_supervisor.go
File metadata and controls
303 lines (257 loc) · 7.28 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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package supervisor
import (
"context"
"errors"
"fmt"
"os/exec"
"runtime"
"sync"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"go.amzn.com/lambda/supervisor/model"
)
// typecheck interface compliance
var _ model.SupervisorClient = (*LocalSupervisor)(nil)
type process struct {
// pid of the running process
pid int
// channel that can be use to block
// while waiting on process termination.
termination chan struct{}
}
type LocalSupervisor struct {
events chan model.Event
processMapLock sync.Mutex
processMap map[string]process
freezeThawCycleStart time.Time
RootPath string
}
func NewLocalSupervisor() *LocalSupervisor {
return &LocalSupervisor{
events: make(chan model.Event),
processMap: make(map[string]process),
RootPath: "/",
}
}
func (*LocalSupervisor) Start(ctx context.Context, req *model.StartRequest) error {
return nil
}
func (*LocalSupervisor) Configure(ctx context.Context, req *model.ConfigureRequest) error {
return nil
}
func (*LocalSupervisor) Exit(ctx context.Context) {}
func (s *LocalSupervisor) Exec(ctx context.Context, req *model.ExecRequest) error {
if req.Domain != "runtime" {
log.Debug("Exec is a no op if domain != runtime")
return nil
}
command := exec.Command(req.Path, req.Args...)
if req.Env != nil {
envStrings := make([]string, 0, len(*req.Env))
for key, value := range *req.Env {
envStrings = append(envStrings, key+"="+value)
}
command.Env = envStrings
}
if req.Cwd != nil && *req.Cwd != "" {
command.Dir = *req.Cwd
}
if req.ExtraFiles != nil {
command.ExtraFiles = *req.ExtraFiles
}
command.Stdout = req.StdoutWriter
command.Stderr = req.StderrWriter
command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err := command.Start()
if err != nil {
return err
// TODO Use supevisor specific error
}
pid := command.Process.Pid
termination := make(chan struct{})
s.processMapLock.Lock()
s.processMap[req.Name] = process{
pid: pid,
termination: termination,
}
s.processMapLock.Unlock()
// The first freeze thaw cycle starts on Exec() at init time
s.freezeThawCycleStart = time.Now()
go func() {
err = command.Wait()
// close the termination channel to unblock whoever's blocked on
// it (used to implement kill's blocking behaviour)
close(termination)
var cell int32
var exitStatus *int32
var signo *int32
var exitErr *exec.ExitError
if err == nil {
exitStatus = &cell
} else if errors.As(err, &exitErr) {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
if code := status.ExitStatus(); code >= 0 {
cell = int32(code)
exitStatus = &cell
} else {
cell = int32(status.Signal())
signo = &cell
}
}
}
if signo == nil && exitStatus == nil {
log.Error("Cannot convert process exit status to unix WaitStatus. This is unexpected. Assuming ExitStatus 1")
cell = 1
exitStatus = &cell
}
s.events <- model.Event{
Time: uint64(time.Now().UnixMilli()),
Event: model.EventData{
Domain: &req.Domain,
Name: &req.Name,
Signo: signo,
ExitStatus: exitStatus,
},
}
}()
return nil
}
func kill(p process, name string, deadline time.Time) error {
// kill should report success if the process terminated by the time
//supervisor receives the request.
select {
// if this case is selected, the channel is closed,
// which means the process is terminated
case <-p.termination:
log.Debugf("Process %s already terminated.", name)
return nil
default:
log.Infof("Sending SIGKILL to %s(%d).", name, p.pid)
}
if (time.Since(deadline)) > 0 {
return fmt.Errorf("invalid timeout while killing %s", name)
}
pgid, err := syscall.Getpgid(p.pid)
if err == nil {
// Negative pid sends signal to all in process group
syscall.Kill(-pgid, syscall.SIGKILL)
} else {
syscall.Kill(p.pid, syscall.SIGKILL)
}
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
// block until the (main) process exits
// or the timeout fires
select {
case <-p.termination:
return nil
case <-ctx.Done():
return fmt.Errorf("timed out while trying to SIGKILL %s", name)
}
}
func (s *LocalSupervisor) Kill(ctx context.Context, req *model.KillRequest) error {
if req.Domain != "runtime" {
log.Debug("Kill is a no op if domain != runtime")
return nil
}
s.processMapLock.Lock()
process, ok := s.processMap[req.Name]
s.processMapLock.Unlock()
if !ok {
msg := "Unknown process"
return &model.SupervisorError{
Kind: model.NoSuchEntity,
Message: &msg,
}
}
return kill(process, req.Name, req.Deadline)
}
func (s *LocalSupervisor) Terminate(ctx context.Context, req *model.TerminateRequest) error {
if req.Domain != "runtime" {
log.Debug("Terminate is no op if domain != runtime")
return nil
}
s.processMapLock.Lock()
process, ok := s.processMap[req.Name]
pid := process.pid
s.processMapLock.Unlock()
if !ok {
msg := "Unknown process"
err := &model.SupervisorError{
Kind: model.NoSuchEntity,
Message: &msg,
}
log.WithError(err).Errorf("Process %s not found in local supervisor map", req.Name)
return err
}
pgid, err := syscall.Getpgid(pid)
if err == nil {
// Negative pid sends signal to all in process group
// best effort, ignore errors
_ = syscall.Kill(-pgid, syscall.SIGTERM)
} else {
_ = syscall.Kill(pid, syscall.SIGTERM)
}
return nil
}
func (s *LocalSupervisor) Stop(ctx context.Context, req *model.StopRequest) (*model.StopResponse, error) {
if req.Domain != "runtime" {
log.Debug("Shutdown is no op if domain != runtime")
return &model.StopResponse{}, nil
}
// shut down kills all the processes in the map
s.processMapLock.Lock()
defer s.processMapLock.Unlock()
nprocs := len(s.processMap)
successes := make(chan struct{})
errors := make(chan error)
for name, proc := range s.processMap {
go func(n string, p process) {
log.Debugf("Killing %s", n)
err := kill(p, n, req.Deadline)
if err != nil {
errors <- err
} else {
successes <- struct{}{}
}
}(name, proc)
}
var err error
for i := 0; i < nprocs; i++ {
select {
case <-successes:
case e := <-errors:
if err == nil {
err = fmt.Errorf("shutdown failed: %s", e.Error())
}
}
}
s.processMap = make(map[string]process)
return nil, err
}
func (s *LocalSupervisor) Freeze(ctx context.Context, req *model.FreezeRequest) (*model.FreezeResponse, error) {
// We return mocked freeze/thaw cycle metrics to mimic usage metrics in standalone mode
var m runtime.MemStats
runtime.ReadMemStats(&m)
return &model.FreezeResponse{
CycleDeltaMetrics: model.CycleDeltaMetrics{
DomainCPURunNs: uint64(time.Since(s.freezeThawCycleStart).Nanoseconds()),
DomainRunNs: uint64(time.Since(s.freezeThawCycleStart).Nanoseconds()),
DomainMaxMemoryUsageBytes: m.Alloc,
MicrovmCPURunNs: uint64(time.Since(s.freezeThawCycleStart).Nanoseconds()),
},
}, nil
}
func (s *LocalSupervisor) Thaw(ctx context.Context, req *model.ThawRequest) error {
s.freezeThawCycleStart = time.Now()
return nil
}
func (s *LocalSupervisor) Ping(ctx context.Context) error {
return nil
}
func (s *LocalSupervisor) Events(ctx context.Context, req *model.EventsRequest) (<-chan model.Event, error) {
return s.events, nil
}