forked from kata-containers/agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
348 lines (286 loc) · 8.24 KB
/
channel.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
//
// Copyright (c) 2017-2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package main
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/hashicorp/yamux"
"github.com/mdlayher/vsock"
"golang.org/x/sys/unix"
"google.golang.org/grpc/codes"
grpcStatus "google.golang.org/grpc/status"
)
var (
channelExistMaxTries = 200
channelExistWaitTime = 50 * time.Millisecond
channelCloseTimeout = 5 * time.Second
isAFVSockSupportedFunc = isAFVSockSupported
)
type channel interface {
setup() error
wait() error
listen() (net.Listener, error)
teardown() error
}
// Creates a new channel to communicate the agent with the proxy or shim.
// The runtime hot plugs a serial port or a vsock PCI depending of the configuration
// file and if the host has support for vsocks. newChannel iterates in a loop looking
// for the serial port or vsock device.
// The timeout is defined by channelExistMaxTries and channelExistWaitTime and it
// can be calculated by using the following operation:
// (channelExistMaxTries * channelExistWaitTime) / 1000 = timeout in seconds
// If there are neither vsocks nor serial ports, an error is returned.
func newChannel(ctx context.Context) (channel, error) {
span, _ := trace(ctx, "channel", "newChannel")
defer span.finish()
var serialErr error
var vsockErr error
var ch channel
for i := 0; i < channelExistMaxTries; i++ {
switch commCh {
case serialCh:
if ch, serialErr = checkForSerialChannel(ctx); serialErr == nil && ch.(*serialChannel) != nil {
return ch, nil
}
case vsockCh:
if ch, vsockErr = checkForVsockChannel(ctx); vsockErr == nil && ch.(*vSockChannel) != nil {
return ch, nil
}
case unknownCh:
// If we have not been explicitly passed if vsock is used or not, maybe due to
// an older runtime, try to check for vsock support.
if ch, vsockErr = checkForVsockChannel(ctx); vsockErr == nil && ch.(*vSockChannel) != nil {
return ch, nil
}
if ch, serialErr = checkForSerialChannel(ctx); serialErr == nil && ch.(*serialChannel) != nil {
return ch, nil
}
}
time.Sleep(channelExistWaitTime)
}
if serialErr != nil {
agentLog.WithError(serialErr).Error("Serial port not found")
}
if vsockErr != nil {
agentLog.WithError(vsockErr).Error("VSock not found")
}
return nil, fmt.Errorf("Neither vsocks nor serial ports were found")
}
func checkForSerialChannel(ctx context.Context) (*serialChannel, error) {
span, _ := trace(ctx, "channel", "checkForSerialChannel")
defer span.finish()
// Check serial port path
serialPath, serialErr := findVirtualSerialPath(serialChannelName)
if serialErr == nil {
span.setTag("channel-type", "serial")
span.setTag("serial-path", serialPath)
agentLog.Debug("Serial channel type detected")
return &serialChannel{serialPath: serialPath}, nil
}
return nil, serialErr
}
func checkForVsockChannel(ctx context.Context) (*vSockChannel, error) {
span, _ := trace(ctx, "channel", "checkForVsockChannel")
defer span.finish()
// check vsock path
if _, err := os.Stat(vSockDevPath); err != nil {
return nil, err
}
vSockSupported, vsockErr := isAFVSockSupportedFunc()
if vSockSupported && vsockErr == nil {
span.setTag("channel-type", "vsock")
agentLog.Debug("Vsock channel type detected")
return &vSockChannel{}, nil
}
return nil, fmt.Errorf("Vsock not found : %s", vsockErr)
}
type vSockChannel struct {
}
func (c *vSockChannel) setup() error {
return nil
}
func (c *vSockChannel) wait() error {
return nil
}
func (c *vSockChannel) listen() (net.Listener, error) {
l, err := vsock.Listen(vSockPort)
if err != nil {
return nil, err
}
return l, nil
}
func (c *vSockChannel) teardown() error {
return nil
}
type serialChannel struct {
serialPath string
serialConn *os.File
waitCh <-chan struct{}
}
func (c *serialChannel) setup() error {
// Open serial channel.
file, err := os.OpenFile(c.serialPath, os.O_RDWR, os.ModeDevice)
if err != nil {
return err
}
c.serialConn = file
return nil
}
func (c *serialChannel) wait() error {
var event unix.EpollEvent
var events [1]unix.EpollEvent
fd := c.serialConn.Fd()
if fd == 0 {
return fmt.Errorf("serial port IO closed")
}
epfd, err := unix.EpollCreate1(unix.EPOLL_CLOEXEC)
if err != nil {
return err
}
defer unix.Close(epfd)
// EPOLLOUT: Writable when there is a connection
// EPOLLET: Edge trigger as EPOLLHUP is always on when there is no connection
// 0xffffffff: EPOLLET is negative and cannot fit in uint32 in golang
event.Events = unix.EPOLLOUT | unix.EPOLLET&0xffffffff
event.Fd = int32(fd)
if err = unix.EpollCtl(epfd, unix.EPOLL_CTL_ADD, int(fd), &event); err != nil {
return err
}
defer unix.EpollCtl(epfd, unix.EPOLL_CTL_DEL, int(fd), nil)
for {
nev, err := unix.EpollWait(epfd, events[:], -1)
if err != nil {
return err
}
for i := 0; i < nev; i++ {
ev := events[i]
if ev.Fd == int32(fd) {
agentLog.WithField("events", ev.Events).Debug("New serial channel event")
if ev.Events&unix.EPOLLOUT != 0 {
return nil
}
if ev.Events&unix.EPOLLERR != 0 {
return fmt.Errorf("serial port IO failure")
}
if ev.Events&unix.EPOLLHUP != 0 {
continue
}
}
}
}
// Never reach here
}
// yamuxWriter is a type responsible for logging yamux messages to the agent
// log.
type yamuxWriter struct {
}
// Write implements the Writer interface for the yamuxWriter.
func (yw yamuxWriter) Write(bytes []byte) (int, error) {
message := string(bytes)
l := len(message)
// yamux messages are all warnings and errors
agentLog.WithField("component", "yamux").Warn(message)
return l, nil
}
func (c *serialChannel) listen() (net.Listener, error) {
config := yamux.DefaultConfig()
// yamux client runs on the proxy side, sometimes the client is
// handling other requests and it's not able to response to the
// ping sent by the server and the communication is closed. To
// avoid any IO timeouts in the communication between agent and
// proxy, keep alive should be disabled.
config.EnableKeepAlive = false
config.LogOutput = yamuxWriter{}
// Initialize Yamux server.
session, err := yamux.Server(c.serialConn, config)
if err != nil {
return nil, err
}
c.waitCh = session.CloseChan()
return session, nil
}
func (c *serialChannel) teardown() error {
// wait for the session to be fully shutdown first
if c.waitCh != nil {
t := time.NewTimer(channelCloseTimeout)
select {
case <-c.waitCh:
t.Stop()
case <-t.C:
return fmt.Errorf("timeout waiting for yamux channel to close")
}
}
return c.serialConn.Close()
}
// isAFVSockSupported checks if vsock channel is used by the runtime
// by checking for devices under the vhost-vsock driver path.
// It returns true if a device is found for the vhost-vsock driver.
func isAFVSockSupported() (bool, error) {
// Driver path for virtio-vsock
sysVsockPath := "/sys/bus/virtio/drivers/vmw_vsock_virtio_transport/"
files, err := ioutil.ReadDir(sysVsockPath)
// This should not happen for a hypervisor with vsock driver
if err != nil {
return false, err
}
// standard driver files that should be ignored
driverFiles := []string{"bind", "uevent", "unbind"}
for _, file := range files {
for _, f := range driverFiles {
if file.Name() == f {
continue
}
}
fPath := filepath.Join(sysVsockPath, file.Name())
fInfo, err := os.Lstat(fPath)
if err != nil {
return false, err
}
if fInfo.Mode()&os.ModeSymlink == 0 {
continue
}
link, err := os.Readlink(fPath)
if err != nil {
return false, err
}
if strings.Contains(link, "devices") {
return true, nil
}
}
return false, nil
}
func findVirtualSerialPath(serialName string) (string, error) {
dir, err := os.Open(virtIOPath)
if err != nil {
return "", err
}
defer dir.Close()
ports, err := dir.Readdirnames(0)
if err != nil {
return "", err
}
for _, port := range ports {
path := filepath.Join(virtIOPath, port, "name")
content, err := ioutil.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
agentLog.WithField("file", path).Debug("Skip parsing of non-existent file")
continue
}
return "", err
}
if strings.Contains(string(content), serialName) {
return filepath.Join(devRootPath, port), nil
}
}
return "", grpcStatus.Errorf(codes.NotFound, "Could not find virtio port %s", serialName)
}