forked from kubevirt/kubevirt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
isolation.go
207 lines (173 loc) · 5.96 KB
/
isolation.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
/*
* This file is part of the kubevirt project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2017 Red Hat, Inc.
*
*/
package isolation
//go:generate mockgen -source $GOFILE -package=$GOPACKAGE -destination=generated_mock_$GOFILE
/*
ATTENTION: Rerun code generators when interface signatures are modified.
*/
import (
"bufio"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"syscall"
"kubevirt.io/kubevirt/pkg/api/v1"
"kubevirt.io/kubevirt/pkg/log"
)
// PodIsolationDetector helps detecting cgroups, namespaces and PIDs of Pods from outside of them.
// Different strategies may be applied to do that.
type PodIsolationDetector interface {
// Detect takes a vm, looks up a socket based the VM and detects pid, cgroups and namespaces of the owner of that socket.
// It returns an IsolationResult containing all isolation information
Detect(vm *v1.VirtualMachine) (*IsolationResult, error)
// Whitelist allows specifying cgroup controller which should be considered to detect the cgroup slice
// It returns a PodIsolationDetector to allow configuring the PodIsolationDetector via the builder pattern.
Whitelist(controller []string) PodIsolationDetector
}
type socketBasedIsolationDetector struct {
virtShareDir string
controller []string
}
var defaultControllers = []string{"cpu", "cpuacct", "cpuset", "freezer", "memory", "net_cls", "perf_event"}
// NewSocketBasedIsolationDetector takes virtShareDir and creates a socket based IsolationDetector
// It returns a PodIsolationDetector which detects pid, cgroups and namespaces of the socket owner.
func NewSocketBasedIsolationDetector(virtShareDir string) PodIsolationDetector {
iso := &socketBasedIsolationDetector{virtShareDir: virtShareDir}
iso.controller = append(iso.controller, defaultControllers...)
return iso
}
func SocketFromNamespaceName(baseDir string, namespace string, name string) string {
sockFile := namespace + "_" + name + "_sock"
return filepath.Join(baseDir, "sockets", sockFile)
}
// This function is only used by unit test suite
func (s *socketBasedIsolationDetector) Whitelist(controller []string) PodIsolationDetector {
s.controller = controller
return s
}
func (s *socketBasedIsolationDetector) Detect(vm *v1.VirtualMachine) (*IsolationResult, error) {
var pid int
var slice string
var err error
var controller []string
// Look up the socket of the virt-launcher Pod which was created for that VM, and extract the PID from it
socket := SocketFromNamespaceName(s.virtShareDir, vm.ObjectMeta.Namespace, vm.ObjectMeta.Name)
if pid, err = s.getPid(socket); err != nil {
log.Log.Object(vm).V(3).Reason(err).Errorf("Could not get owner Pid of socket %s", socket)
return nil, err
}
// Look up the cgroup slice based on the whitelisted controller
if controller, slice, err = getSlice(pid, s.controller); err != nil {
log.Log.Object(vm).V(3).Reason(err).Errorf("Could not get cgroup slice for Pid %d", pid)
return nil, err
}
return NewIsolationResult(pid, slice, controller), nil
}
func NewIsolationResult(pid int, slice string, controller []string) *IsolationResult {
return &IsolationResult{pid: pid, slice: slice, controller: controller}
}
type IsolationResult struct {
pid int
slice string
controller []string
}
func (r *IsolationResult) Slice() string {
return r.slice
}
func (r *IsolationResult) PidNS() string {
return fmt.Sprintf("/proc/%d/ns/pid", r.pid)
}
func (r *IsolationResult) Pid() int {
return r.pid
}
func (r *IsolationResult) Controller() []string {
return r.controller
}
func (s *socketBasedIsolationDetector) getPid(socket string) (int, error) {
sock, err := net.Dial("unix", socket)
if err != nil {
return -1, err
}
defer sock.Close()
ufile, err := sock.(*net.UnixConn).File()
if err != nil {
return -1, err
}
// This is the tricky part, which will give us the PID of the owning socket
ucreds, err := syscall.GetsockoptUcred(int(ufile.Fd()), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
if err != nil {
return -1, err
}
if int(ucreds.Pid) == 0 {
return -1, fmt.Errorf("The detected PID is 0. Is the isolation detector running in the host PID namespace?")
}
return int(ucreds.Pid), nil
}
func GetDefaultSlice(pid int) ([]string, string, error) {
return getSlice(pid, defaultControllers)
}
func getSlice(pid int, supportedControllers []string) (controller []string, slice string, err error) {
cgroups, err := os.Open(fmt.Sprintf("/proc/%d/cgroup", pid))
if err != nil {
return
}
defer cgroups.Close()
scanner := bufio.NewScanner(cgroups)
for scanner.Scan() {
cgEntry := strings.Split(scanner.Text(), ":")
// Check if we have a sane cgroup line
if len(cgEntry) != 3 {
err = fmt.Errorf("Could not extract slice from cgroup line: %s", scanner.Text())
return
}
// Skip not supported cgroup controller
if !sliceContains(supportedControllers, cgEntry[1]) {
continue
}
// Set and check cgroup slice
if slice == "" {
slice = cgEntry[2]
} else if slice != cgEntry[2] {
err = fmt.Errorf("Process is part of more than one slice. Expected %s, found %s", slice, cgEntry[2])
return
}
// Add controller
controller = append(controller, cgEntry[1])
}
// Check if we encountered a read error
if scanner.Err() != nil {
err = scanner.Err()
return
}
if slice == "" {
err = fmt.Errorf("Could not detect slice of whitelisted controller: %v", supportedControllers)
return
}
return
}
func sliceContains(controllers []string, value string) bool {
for _, c := range controllers {
if c == value {
return true
}
}
return false
}