forked from cri-o/cri-o
/
server.go
627 lines (561 loc) · 18.2 KB
/
server.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package server
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"path/filepath"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/containers/libpod/pkg/apparmor"
"github.com/containers/storage/pkg/idtools"
"github.com/cri-o/cri-o/lib"
"github.com/cri-o/cri-o/lib/sandbox"
"github.com/cri-o/cri-o/oci"
"github.com/cri-o/cri-o/pkg/seccomp"
"github.com/cri-o/cri-o/pkg/storage"
"github.com/cri-o/cri-o/server/metrics"
"github.com/cri-o/cri-o/version"
"github.com/cri-o/ocicni/pkg/ocicni"
"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
knet "k8s.io/apimachinery/pkg/util/net"
pb "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2"
"k8s.io/kubernetes/pkg/kubelet/dockershim/network/hostport"
"k8s.io/kubernetes/pkg/kubelet/server/streaming"
iptablesproxy "k8s.io/kubernetes/pkg/proxy/iptables"
utildbus "k8s.io/kubernetes/pkg/util/dbus"
utiliptables "k8s.io/kubernetes/pkg/util/iptables"
utilexec "k8s.io/utils/exec"
)
const (
shutdownFile = "/var/lib/crio/crio.shutdown"
certRefreshInterval = time.Minute * 5
apparmorDefaultProfile = "crio-default-" + version.Version
apparmorRuntimeDefault = "runtime/default"
apparmorLocalHostPrefix = "localhost/"
)
// streamService implements streaming.Runtime.
type streamService struct {
runtimeServer *Server // needed by Exec() endpoint
streamServer streaming.Server
streamServerCloseCh chan struct{}
streaming.Runtime
}
// Server implements the RuntimeService and ImageService
type Server struct {
config Config
seccompProfile seccomp.Seccomp
stream streamService
netPlugin ocicni.CNIPlugin
hostportManager hostport.HostPortManager
appArmorProfile string
hostIP string
bindAddress string
*lib.ContainerServer
monitorsChan chan struct{}
defaultIDMappings *idtools.IDMappings
updateLock sync.RWMutex
seccompEnabled bool
appArmorEnabled bool
}
type certConfigCache struct {
config *tls.Config
expires time.Time
tlsCert string
tlsKey string
tlsCA string
}
// GetConfigForClient gets the tlsConfig for the streaming server.
// This allows the certs to be swapped, without shutting down crio.
func (cc *certConfigCache) GetConfigForClient(hello *tls.ClientHelloInfo) (*tls.Config, error) {
if cc.config != nil && time.Now().Before(cc.expires) {
return cc.config, nil
}
config := new(tls.Config)
cert, err := tls.LoadX509KeyPair(cc.tlsCert, cc.tlsKey)
if err != nil {
return nil, err
}
config.Certificates = []tls.Certificate{cert}
if len(cc.tlsCA) > 0 {
caBytes, err := ioutil.ReadFile(cc.tlsCA)
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caBytes)
config.ClientCAs = certPool
config.ClientAuth = tls.RequireAndVerifyClientCert
}
cc.config = config
cc.expires = time.Now().Add(certRefreshInterval)
return config, nil
}
// StopStreamServer stops the stream server
func (s *Server) StopStreamServer() error {
return s.stream.streamServer.Stop()
}
// StreamingServerCloseChan returns the close channel for the streaming server
func (s *Server) StreamingServerCloseChan() chan struct{} {
return s.stream.streamServerCloseCh
}
// getExec returns exec stream request
func (s *Server) getExec(req *pb.ExecRequest) (*pb.ExecResponse, error) {
return s.stream.streamServer.GetExec(req)
}
// getAttach returns attach stream request
func (s *Server) getAttach(req *pb.AttachRequest) (*pb.AttachResponse, error) {
return s.stream.streamServer.GetAttach(req)
}
// getPortForward returns port forward stream request
func (s *Server) getPortForward(req *pb.PortForwardRequest) (*pb.PortForwardResponse, error) {
return s.stream.streamServer.GetPortForward(req)
}
func (s *Server) restore() {
containers, err := s.Store().Containers()
if err != nil && !os.IsNotExist(errors.Cause(err)) {
logrus.Warnf("could not read containers and sandboxes: %v", err)
}
pods := map[string]*storage.RuntimeContainerMetadata{}
podContainers := map[string]*storage.RuntimeContainerMetadata{}
names := map[string][]string{}
deletedPods := map[string]bool{}
for i := range containers {
metadata, err2 := s.StorageRuntimeServer().GetContainerMetadata(containers[i].ID)
if err2 != nil {
logrus.Warnf("error parsing metadata for %s: %v, ignoring", containers[i].ID, err2)
continue
}
if !storage.IsCrioContainer(metadata) {
logrus.Debugf("container %s determined to not be a CRI-O container or sandbox", containers[i].ID)
continue
}
names[containers[i].ID] = containers[i].Names
if metadata.Pod {
pods[containers[i].ID] = &metadata
} else {
podContainers[containers[i].ID] = &metadata
}
}
// Go through all the pods and check if it can be restored. If an error occurs, delete the pod and any containers
// associated with it. Release the pod and container names as well.
for sbID, metadata := range pods {
if err = s.LoadSandbox(sbID); err == nil {
continue
}
logrus.Warnf("could not restore sandbox %s container %s: %v", metadata.PodID, sbID, err)
for _, n := range names[sbID] {
s.Store().DeleteContainer(n)
// Release the infra container name and the pod name for future use
if strings.Contains(n, infraName) {
s.ReleaseContainerName(n)
} else {
s.ReleasePodName(n)
}
}
// Go through the containers and delete any containers that were under the deleted pod
logrus.Warnf("deleting all containers under sandbox %s since it could not be restored", sbID)
for k, v := range podContainers {
if v.PodID == sbID {
for _, n := range names[k] {
s.Store().DeleteContainer(n)
// Release the container name for future use
s.ReleaseContainerName(n)
}
}
}
// Add the pod id to the list of deletedPods so we don't try to restore IPs for it later on
deletedPods[sbID] = true
}
// Go through all the containers and check if it can be restored. If an error occurs, delete the container and
// release the name associated with it.
for containerID := range podContainers {
if err := s.LoadContainer(containerID); err != nil {
logrus.Warnf("could not restore container %s: %v", containerID, err)
for _, n := range names[containerID] {
s.Store().DeleteContainer(n)
// Release the container name
s.ReleaseContainerName(n)
}
}
}
// Restore sandbox IPs
for _, sb := range s.ListSandboxes() {
// Move on if pod was deleted
if ok, _ := deletedPods[sb.ID()]; ok {
continue
}
ip, err := s.getSandboxIP(sb)
if err != nil {
logrus.Warnf("could not restore sandbox IP for %v: %v", sb.ID(), err)
}
sb.AddIP(ip)
}
// Clean up orphaned exit files
var exitIDs []string
exitDir := s.Config().RuntimeConfig.ContainerExitsDir
err = filepath.Walk(exitDir, func(path string, info os.FileInfo, err error) error {
exitFileName := filepath.Base(path)
if path != exitDir {
exitIDs = append(exitIDs, exitFileName)
}
return nil
})
if err != nil {
logrus.Warnf("Failed to walk exit dir %v: %v", exitDir, err)
}
for _, exitID := range exitIDs {
logrus.Warnf("Checking exit file: %v", exitID)
ctr := s.GetContainer(exitID)
if ctr != nil {
continue
} else {
sb := s.GetSandbox(exitID)
if sb != nil {
continue
}
}
logrus.Warnf("Removing exit file: %v", exitID)
if err := os.Remove(filepath.Join(exitDir, exitID)); err != nil && !os.IsNotExist(err) {
logrus.Warnf("Failed to remove container exit file during restore cleanup %s: %v", exitID, err)
}
}
}
// cleanupSandboxesOnShutdown Remove all running Sandboxes on system shutdown
func (s *Server) cleanupSandboxesOnShutdown(ctx context.Context) {
_, err := os.Stat(shutdownFile)
if err == nil || !os.IsNotExist(err) {
logrus.Debugf("shutting down all sandboxes, on shutdown")
s.stopAllPodSandboxes(ctx)
err = os.Remove(shutdownFile)
if err != nil {
logrus.Warnf("Failed to remove %q", shutdownFile)
}
}
}
// Shutdown attempts to shut down the server's storage cleanly
func (s *Server) Shutdown(ctx context.Context) error {
// why do this on clean shutdown! we want containers left running when crio
// is down for whatever reason no?!
// notice this won't trigger just on system halt but also on normal
// crio.service restart!!!
s.cleanupSandboxesOnShutdown(ctx)
return s.ContainerServer.Shutdown()
}
// configureMaxThreads sets the Go runtime max threads threshold
// which is 90% of the kernel setting from /proc/sys/kernel/threads-max
func configureMaxThreads() error {
mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
if err != nil {
return err
}
mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
if err != nil {
return err
}
maxThreads := (mtint / 100) * 90
debug.SetMaxThreads(maxThreads)
logrus.Debugf("Golang's threads limit set to %d", maxThreads)
return nil
}
func getIDMappings(config *Config) (*idtools.IDMappings, error) {
if config.UIDMappings == "" || config.GIDMappings == "" {
return nil, nil
}
parseTriple := func(spec []string) (container, host, size int, err error) {
cid, err := strconv.ParseUint(spec[0], 10, 32)
if err != nil {
return 0, 0, 0, fmt.Errorf("error parsing id map value %q: %v", spec[0], err)
}
hid, err := strconv.ParseUint(spec[1], 10, 32)
if err != nil {
return 0, 0, 0, fmt.Errorf("error parsing id map value %q: %v", spec[1], err)
}
sz, err := strconv.ParseUint(spec[2], 10, 32)
if err != nil {
return 0, 0, 0, fmt.Errorf("error parsing id map value %q: %v", spec[2], err)
}
return int(cid), int(hid), int(sz), nil
}
parseIDMap := func(spec []string) (idmap []idtools.IDMap, err error) {
for _, uid := range spec {
splitmap := strings.SplitN(uid, ":", 3)
if len(splitmap) < 3 {
return nil, fmt.Errorf("invalid mapping requires 3 fields: %q", uid)
}
cid, hid, size, err := parseTriple(splitmap)
if err != nil {
return nil, err
}
pmap := idtools.IDMap{
ContainerID: cid,
HostID: hid,
Size: size,
}
idmap = append(idmap, pmap)
}
return idmap, nil
}
parsedUIDsMappings, err := parseIDMap(strings.Split(config.UIDMappings, ","))
if err != nil {
return nil, err
}
parsedGIDsMappings, err := parseIDMap(strings.Split(config.GIDMappings, ","))
if err != nil {
return nil, err
}
return idtools.NewIDMappingsFromMaps(parsedUIDsMappings, parsedGIDsMappings), nil
}
// New creates a new Server with options provided
func New(ctx context.Context, config *Config) (*Server, error) {
if err := os.MkdirAll(oci.ContainerAttachSocketDir, 0755); err != nil {
return nil, err
}
// This is used to monitor container exits using inotify
if err := os.MkdirAll(config.ContainerExitsDir, 0755); err != nil {
return nil, err
}
containerServer, err := lib.New(ctx, &config.Config)
if err != nil {
return nil, err
}
netPlugin, err := ocicni.InitCNI("", config.NetworkDir, config.PluginDirs...)
if err != nil {
return nil, err
}
iptInterface := utiliptables.New(utilexec.New(), utildbus.New(), utiliptables.ProtocolIpv4)
iptInterface.EnsureChain(utiliptables.TableNAT, iptablesproxy.KubeMarkMasqChain)
hostportManager := hostport.NewHostportManager(iptInterface)
idMappings, err := getIDMappings(config)
if err != nil {
return nil, err
}
s := &Server{
ContainerServer: containerServer,
netPlugin: netPlugin,
hostportManager: hostportManager,
config: *config,
seccompEnabled: seccomp.IsEnabled(),
appArmorEnabled: apparmor.IsEnabled(),
appArmorProfile: config.ApparmorProfile,
monitorsChan: make(chan struct{}),
defaultIDMappings: idMappings,
}
if s.seccompEnabled {
seccompProfile, fileErr := ioutil.ReadFile(config.SeccompProfile)
if fileErr != nil {
return nil, fmt.Errorf("opening seccomp profile (%s) failed: %v", config.SeccompProfile, fileErr)
}
var seccompConfig seccomp.Seccomp
if jsonErr := json.Unmarshal(seccompProfile, &seccompConfig); jsonErr != nil {
return nil, fmt.Errorf("decoding seccomp profile failed: %v", jsonErr)
}
s.seccompProfile = seccompConfig
}
if s.appArmorEnabled && s.appArmorProfile == apparmorDefaultProfile {
if err := apparmor.InstallDefault(apparmorDefaultProfile); err != nil {
return nil, fmt.Errorf("ensuring the default apparmor profile %q is installed failed: %v", apparmorDefaultProfile, err)
}
}
if err := configureMaxThreads(); err != nil {
return nil, err
}
s.restore()
s.cleanupSandboxesOnShutdown(ctx)
hostIP := net.ParseIP(config.HostIP)
if hostIP == nil {
// First, attempt to find a primary IP from /proc/net/route deterministically
hostIP, err = knet.ChooseBindAddress(nil)
if err != nil {
// if that fails, check if we can find a primary IP address unambiguously
allAddrs, err2 := net.InterfaceAddrs()
if err2 != nil {
return nil, errors.Wrapf(err, "Failed to read InterfaceAddrs after failing to choose bind address")
}
// we are hoping for exactly 1 possible IP
numPossibleIPs := 0
// adapted from: https://stackoverflow.com/a/31551220
for _, addr := range allAddrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
numPossibleIPs++
hostIP = ipnet.IP
if numPossibleIPs > 1 {
break
}
}
}
}
// If there is no clear primary IP, we should fail
if numPossibleIPs != 1 {
return nil, errors.Wrapf(err, "Failed to find one IP address after failing to choose bind address")
}
}
}
bindAddress := net.ParseIP(config.StreamAddress)
if bindAddress == nil {
bindAddress = hostIP
}
s.bindAddress = bindAddress.String()
s.hostIP = hostIP.String()
_, err = net.LookupPort("tcp", config.StreamPort)
if err != nil {
return nil, err
}
// Prepare streaming server
streamServerConfig := streaming.DefaultConfig
streamServerConfig.Addr = net.JoinHostPort(bindAddress.String(), config.StreamPort)
if config.StreamEnableTLS {
certCache := &certConfigCache{
tlsCert: config.StreamTLSCert,
tlsKey: config.StreamTLSKey,
tlsCA: config.StreamTLSCA,
}
// We add the certs to the config, even thought the config is dynamic, because
// the http package method, ServeTLS, checks to make sure there is a cert in the
// config or it throws an error.
cert, err := tls.LoadX509KeyPair(config.StreamTLSCert, config.StreamTLSKey)
if err != nil {
return nil, err
}
streamServerConfig.TLSConfig = &tls.Config{
GetConfigForClient: certCache.GetConfigForClient,
Certificates: []tls.Certificate{cert},
}
}
s.stream.runtimeServer = s
s.stream.streamServer, err = streaming.NewServer(streamServerConfig, s.stream)
if err != nil {
return nil, fmt.Errorf("unable to create streaming server")
}
s.stream.streamServerCloseCh = make(chan struct{})
go func() {
defer close(s.stream.streamServerCloseCh)
if err := s.stream.streamServer.Start(true); err != nil && err != http.ErrServerClosed {
logrus.Errorf("Failed to start streaming server: %v", err)
}
}()
logrus.Debugf("sandboxes: %v", s.ContainerServer.ListSandboxes())
return s, nil
}
func (s *Server) addSandbox(sb *sandbox.Sandbox) {
s.ContainerServer.AddSandbox(sb)
}
func (s *Server) getSandbox(id string) *sandbox.Sandbox {
return s.ContainerServer.GetSandbox(id)
}
func (s *Server) removeSandbox(id string) {
s.ContainerServer.RemoveSandbox(id)
}
func (s *Server) addContainer(c *oci.Container) {
s.ContainerServer.AddContainer(c)
}
func (s *Server) addInfraContainer(c *oci.Container) {
s.ContainerServer.AddInfraContainer(c)
}
func (s *Server) getInfraContainer(id string) *oci.Container {
return s.ContainerServer.GetInfraContainer(id)
}
func (s *Server) removeContainer(c *oci.Container) {
s.ContainerServer.RemoveContainer(c)
}
func (s *Server) removeInfraContainer(c *oci.Container) {
s.ContainerServer.RemoveInfraContainer(c)
}
func (s *Server) getPodSandboxFromRequest(podSandboxID string) (*sandbox.Sandbox, error) {
if podSandboxID == "" {
return nil, sandbox.ErrIDEmpty
}
sandboxID, err := s.PodIDIndex().Get(podSandboxID)
if err != nil {
return nil, fmt.Errorf("PodSandbox with ID starting with %s not found: %v", podSandboxID, err)
}
sb := s.getSandbox(sandboxID)
if sb == nil {
return nil, fmt.Errorf("specified pod sandbox not found: %s", sandboxID)
}
return sb, nil
}
// CreateMetricsEndpoint creates a /metrics endpoint
// for prometheus monitoring
func (s *Server) CreateMetricsEndpoint() (*http.ServeMux, error) {
metrics.Register()
mux := &http.ServeMux{}
mux.Handle("/metrics", promhttp.Handler())
return mux, nil
}
// StopMonitors stops al the monitors
func (s *Server) StopMonitors() {
close(s.monitorsChan)
}
// MonitorsCloseChan returns the close chan for the exit monitor
func (s *Server) MonitorsCloseChan() chan struct{} {
return s.monitorsChan
}
// StartExitMonitor start a routine that monitors container exits
// and updates the container status
func (s *Server) StartExitMonitor() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
logrus.Fatalf("Failed to create new watch: %v", err)
}
defer watcher.Close()
done := make(chan struct{})
go func() {
for {
select {
case event := <-watcher.Events:
logrus.Debugf("event: %v", event)
if event.Op&fsnotify.Create == fsnotify.Create {
containerID := filepath.Base(event.Name)
logrus.Debugf("container or sandbox exited: %v", containerID)
c := s.GetContainer(containerID)
if c != nil {
logrus.Debugf("container exited and found: %v", containerID)
err := s.Runtime().UpdateContainerStatus(c)
if err != nil {
logrus.Warnf("Failed to update container status %s: %v", containerID, err)
} else {
s.ContainerStateToDisk(c)
}
} else {
sb := s.GetSandbox(containerID)
if sb != nil {
c := sb.InfraContainer()
logrus.Debugf("sandbox exited and found: %v", containerID)
err := s.Runtime().UpdateContainerStatus(c)
if err != nil {
logrus.Warnf("Failed to update sandbox infra container status %s: %v", c.ID(), err)
} else {
s.ContainerStateToDisk(c)
}
}
}
}
case err := <-watcher.Errors:
logrus.Debugf("watch error: %v", err)
return
case <-s.monitorsChan:
logrus.Debug("closing exit monitor...")
close(done)
return
}
}
}()
if err := watcher.Add(s.config.ContainerExitsDir); err != nil {
logrus.Errorf("watcher.Add(%q) failed: %s", s.config.ContainerExitsDir, err)
close(done)
}
<-done
}