1// +build !windows
2
3/*
4   Copyright The containerd Authors.
5
6   Licensed under the Apache License, Version 2.0 (the "License");
7   you may not use this file except in compliance with the License.
8   You may obtain a copy of the License at
9
10       http://www.apache.org/licenses/LICENSE-2.0
11
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17*/
18
19package shim
20
21import (
22	"context"
23	"crypto/sha256"
24	"fmt"
25	"net"
26	"os"
27	"path/filepath"
28	"strings"
29	"syscall"
30	"time"
31
32	"github.com/containerd/containerd/namespaces"
33	"github.com/containerd/containerd/sys"
34	"github.com/pkg/errors"
35)
36
37const shimBinaryFormat = "containerd-shim-%s-%s"
38
39func getSysProcAttr() *syscall.SysProcAttr {
40	return &syscall.SysProcAttr{
41		Setpgid: true,
42	}
43}
44
45// SetScore sets the oom score for a process
46func SetScore(pid int) error {
47	return sys.SetOOMScore(pid, sys.OOMScoreMaxKillable)
48}
49
50// AdjustOOMScore sets the OOM score for the process to the parents OOM score +1
51// to ensure that they parent has a lower* score than the shim
52func AdjustOOMScore(pid int) error {
53	parent := os.Getppid()
54	score, err := sys.GetOOMScoreAdj(parent)
55	if err != nil {
56		return errors.Wrap(err, "get parent OOM score")
57	}
58	shimScore := score + 1
59	if err := sys.SetOOMScore(pid, shimScore); err != nil {
60		return errors.Wrap(err, "set shim OOM score")
61	}
62	return nil
63}
64
65// SocketAddress returns an abstract socket address
66func SocketAddress(ctx context.Context, id string) (string, error) {
67	ns, err := namespaces.NamespaceRequired(ctx)
68	if err != nil {
69		return "", err
70	}
71	d := sha256.Sum256([]byte(filepath.Join(ns, id)))
72	return filepath.Join(string(filepath.Separator), "containerd-shim", fmt.Sprintf("%x.sock", d)), nil
73}
74
75// AnonDialer returns a dialer for an abstract socket
76func AnonDialer(address string, timeout time.Duration) (net.Conn, error) {
77	address = strings.TrimPrefix(address, "unix://")
78	return net.DialTimeout("unix", "\x00"+address, timeout)
79}
80
81func AnonReconnectDialer(address string, timeout time.Duration) (net.Conn, error) {
82	return AnonDialer(address, timeout)
83}
84
85// NewSocket returns a new socket
86func NewSocket(address string) (*net.UnixListener, error) {
87	if len(address) > 106 {
88		return nil, errors.Errorf("%q: unix socket path too long (> 106)", address)
89	}
90	l, err := net.Listen("unix", "\x00"+address)
91	if err != nil {
92		return nil, errors.Wrapf(err, "failed to listen to abstract unix socket %q", address)
93	}
94	return l.(*net.UnixListener), nil
95}
96