forked from kata-containers/shim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
317 lines (257 loc) · 7.91 KB
/
main.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
// Copyright 2017 HyperHQ Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"bufio"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log/syslog"
"net"
"net/url"
"os"
"os/signal"
"runtime"
"sync"
"time"
opentracing "github.com/opentracing/opentracing-go"
"github.com/sirupsen/logrus"
lSyslog "github.com/sirupsen/logrus/hooks/syslog"
context "golang.org/x/net/context"
)
const (
shimName = "kata-shim"
exitFailure = 1
exitSuccess = 0
// Max number of threads the shim should consume.
// We choose 6 as we want a couple of threads for the runtime (gc etc.)
// and couple of threads for our parallel user code, such as the copy
// code in shim.go
maxThreads = 6
)
// version is the shim version. This variable is populated at build time.
var version = "unknown"
var debug bool
// if true, coredump when an internal error occurs or a fatal signal is received
var crashOnError = false
// if true, enable opentracing support.
var tracing = false
var shimLog *logrus.Entry
func logger() *logrus.Entry {
if shimLog != nil {
return shimLog
}
return logrus.NewEntry(logrus.StandardLogger())
}
func initLogger(logLevel, container, execID string, announceFields logrus.Fields, loggerOutput io.Writer) error {
shimLog = logrus.WithFields(logrus.Fields{
"name": shimName,
"pid": os.Getpid(),
"source": "shim",
"container": container,
"exec-id": execID,
})
shimLog.Logger.Formatter = &logrus.TextFormatter{TimestampFormat: time.RFC3339Nano}
level, err := logrus.ParseLevel(logLevel)
if err != nil {
return err
}
shimLog.Logger.SetLevel(level)
shimLog.Logger.Out = loggerOutput
hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_INFO|syslog.LOG_USER, shimName)
if err == nil {
shimLog.Logger.AddHook(hook)
}
logger().WithFields(announceFields).Info("announce")
return nil
}
func setThreads() {
// If GOMAXPROCS has not been set, restrict our thread usage
// so we don't grow many idle threads on large core count systems,
// which un-necessarily consume host PID space (and thus set an
// artificial max limit on the number of concurrent containers we can
// run)
if os.Getenv("GOMAXPROCS") == "" {
if runtime.NumCPU() > maxThreads {
runtime.GOMAXPROCS(maxThreads)
}
}
}
func unixAddr(uri string) (string, error) {
if uri == "" {
return "", errors.New("empty uri")
}
addr, err := url.Parse(uri)
if err != nil {
return "", err
}
if addr.Scheme != "" && addr.Scheme != "unix" {
return "", errors.New("invalid address scheme")
}
return addr.Host + addr.Path, nil
}
func printAgentLogs(sock string) error {
// Don't return an error if nothing has been provided. This flag is optional.
if sock == "" {
return nil
}
agentLogsAddr, err := unixAddr(sock)
if err != nil {
logger().WithField("socket-address", sock).WithError(err).Fatal("invalid agent logs socket address")
return err
}
// Check permissions socket for "other" is 0.
// For security reasons, the socket shouldn't be accessible
// for the "other" group.
fileInfo, err := os.Stat(agentLogsAddr)
if err != nil {
return err
}
otherMask := 0007
other := int(fileInfo.Mode().Perm()) & otherMask
if other != 0 {
return fmt.Errorf("All socket permissions for 'other' should be disabled, got %3.3o", other)
}
conn, err := net.Dial("unix", agentLogsAddr)
if err != nil {
return err
}
// Allow log messages coming from the agent to be distinguished from
// messages originating from the shim itself.
agentLogger := logger().WithFields(logrus.Fields{
"source": "agent",
})
go func() {
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
agentLogger.Infof("%s\n", scanner.Text())
}
if err := scanner.Err(); err != nil {
logger().WithError(err).Error("Failed reading agent logs from socket")
}
}()
return nil
}
func realMain(ctx context.Context) (exitCode int) {
var (
logLevel string
agentAddr string
container string
execID string
agentLogsSocket string
terminal bool
proxyExitCode bool
showVersion bool
)
setThreads()
flag.BoolVar(&debug, "debug", false, "enable debug mode")
flag.BoolVar(&tracing, "trace", false, "enable opentracing support")
flag.BoolVar(&showVersion, "version", false, "display program version and exit")
flag.StringVar(&logLevel, "log", "warn", "set shim log level: debug, info, warn, error, fatal or panic")
flag.StringVar(&agentAddr, "agent", "", "agent gRPC socket endpoint")
flag.StringVar(&container, "container", "", "container id for the shim")
flag.StringVar(&execID, "exec-id", "", "process id for the shim")
flag.BoolVar(&terminal, "terminal", false, "specify if a terminal is setup")
flag.BoolVar(&proxyExitCode, "proxy-exit-code", true, "proxy exit code of the process")
flag.StringVar(&agentLogsSocket, "agent-logs-socket", "", "socket to listen on to retrieve agent logs")
flag.Parse()
if showVersion {
fmt.Printf("%v version %v\n", shimName, version)
return exitSuccess
}
if logLevel == "debug" {
debug = true
}
if debug {
crashOnError = true
}
if agentAddr == "" || container == "" || execID == "" {
logger().WithField("agentAddr", agentAddr).WithField("container", container).WithField("exec-id", execID).Error("container ID, exec ID and agent socket endpoint must be set")
return exitFailure
}
announceFields := logrus.Fields{
"version": version,
"debug": debug,
"log-level": logLevel,
"agent-socket": agentAddr,
"terminal": terminal,
"proxy-exit-code": proxyExitCode,
"tracing": tracing,
}
// The final parameter makes sure all output going to stdout/stderr is discarded.
err := initLogger(logLevel, container, execID, announceFields, ioutil.Discard)
if err != nil {
logger().WithError(err).WithField("loglevel", logLevel).Error("invalid log level")
return exitFailure
}
// Initialise tracing now the logger is ready
tracer, err := createTracer(shimName)
if err != nil {
logger().WithError(err).Fatal("failed to setup tracing")
return exitFailure
}
// create root span
span := tracer.StartSpan("realMain")
ctx = opentracing.ContextWithSpan(ctx, span)
defer span.Finish()
if err := printAgentLogs(agentLogsSocket); err != nil {
logger().WithError(err).Fatal("failed to print agent logs")
return exitFailure
}
shim, err := newShim(ctx, agentAddr, container, execID)
if err != nil {
logger().WithError(err).Error("failed to create new shim")
return exitFailure
}
// winsize
if terminal {
termios, err := setupTerminal(int(os.Stdin.Fd()))
if err != nil {
logger().WithError(err).Error("failed to set raw terminal")
return exitFailure
}
defer restoreTerminal(int(os.Stdin.Fd()), termios)
}
// signals
sigc := shim.handleSignals(ctx, os.Stdin)
defer signal.Stop(sigc)
// This wait call cannot be deferred and has to wait for every
// input/output to return before the code tries to go further
// and wait for the process. Indeed, after the process has been
// waited for, we cannot expect to do any more calls related to
// this process since it is going to be removed from the agent.
wg := &sync.WaitGroup{}
// Encapsulate the call the I/O handling function in a span here since
// that function returns quickly and we want to know how long I/O
// took.
stdioSpan, _ := trace(ctx, "proxyStdio")
// Add a tag to allow the I/O to be filtered out.
stdioSpan.SetTag("category", "interactive")
shim.proxyStdio(wg, terminal)
wg.Wait()
stdioSpan.Finish()
// wait until exit
exitcode, err := shim.wait()
if err != nil {
logger().WithError(err).WithField("exec-id", execID).Error("failed waiting for process")
return exitFailure
} else if proxyExitCode {
logger().WithField("exitcode", exitcode).Info("using shim to proxy exit code")
if exitcode != 0 {
return int(exitcode)
}
}
return exitSuccess
}
func main() {
// create a new empty context
ctx := context.Background()
defer handlePanic(ctx)
exitCode := realMain(ctx)
stopTracing(ctx)
os.Exit(exitCode)
}