|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"). You may |
| 4 | +// not use this file except in compliance with the License. A copy of the |
| 5 | +// License is located at |
| 6 | +// |
| 7 | +// http://aws.amazon.com/apache2.0/ |
| 8 | +// |
| 9 | +// or in the "license" file accompanying this file. This file is distributed |
| 10 | +// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either |
| 11 | +// express or implied. See the License for the specific language governing |
| 12 | +// permissions and limitations under the License. |
| 13 | + |
| 14 | +package vsock |
| 15 | + |
| 16 | +import ( |
| 17 | + "bufio" |
| 18 | + "context" |
| 19 | + "fmt" |
| 20 | + "net" |
| 21 | + "strings" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/pkg/errors" |
| 25 | + "github.com/sirupsen/logrus" |
| 26 | +) |
| 27 | + |
| 28 | +type Timeout struct { |
| 29 | + DialTimeout time.Duration |
| 30 | + RetryTimeout time.Duration |
| 31 | + RetryInterval time.Duration |
| 32 | + ConnectMsgTimeout time.Duration |
| 33 | + AckMsgTimeout time.Duration |
| 34 | +} |
| 35 | + |
| 36 | +func DefaultTimeouts() Timeout { |
| 37 | + return Timeout{ |
| 38 | + DialTimeout: 100 * time.Millisecond, |
| 39 | + RetryTimeout: 20 * time.Second, |
| 40 | + RetryInterval: 100 * time.Millisecond, |
| 41 | + ConnectMsgTimeout: 100 * time.Millisecond, |
| 42 | + AckMsgTimeout: 1 * time.Second, |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// Dial connects to the Firecracker host-side vsock at the provided unix path and port. |
| 47 | +// |
| 48 | +// It will retry connect attempts if a temporary error is encountered up to a fixed |
| 49 | +// timeout or the provided request is canceled. |
| 50 | +// |
| 51 | +// udsPath specifies the file system path of the UNIX domain socket. |
| 52 | +// |
| 53 | +// port will be used in the connect message to the firecracker vsock. |
| 54 | +func Dial(ctx context.Context, logger *logrus.Entry, udsPath string, port uint32) (net.Conn, error) { |
| 55 | + return DialTimeout(ctx, logger, udsPath, port, DefaultTimeouts()) |
| 56 | +} |
| 57 | + |
| 58 | +// DialTimeout acts like Dial but takes a timeout. |
| 59 | +// |
| 60 | +// See func Dial for a description of the udsPath and port parameters. |
| 61 | +func DialTimeout(ctx context.Context, logger *logrus.Entry, udsPath string, port uint32, timeout Timeout) (net.Conn, error) { |
| 62 | + ticker := time.NewTicker(timeout.RetryInterval) |
| 63 | + defer ticker.Stop() |
| 64 | + |
| 65 | + tickerCh := ticker.C |
| 66 | + var attemptCount int |
| 67 | + for { |
| 68 | + attemptCount++ |
| 69 | + logger := logger.WithField("attempt", attemptCount) |
| 70 | + |
| 71 | + select { |
| 72 | + case <-ctx.Done(): |
| 73 | + return nil, ctx.Err() |
| 74 | + case <-tickerCh: |
| 75 | + conn, err := tryConnect(logger, udsPath, port, timeout) |
| 76 | + if isTemporaryNetErr(err) { |
| 77 | + err = errors.Wrap(err, "temporary vsock dial failure") |
| 78 | + logger.WithError(err).Debug() |
| 79 | + continue |
| 80 | + } else if err != nil { |
| 81 | + err = errors.Wrap(err, "non-temporary vsock dial failure") |
| 82 | + logger.WithError(err).Error() |
| 83 | + return nil, err |
| 84 | + } |
| 85 | + |
| 86 | + return conn, nil |
| 87 | + } |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +func connectMsg(port uint32) string { |
| 92 | + // The message a host-side connection must write after connecting to a firecracker |
| 93 | + // vsock unix socket in order to establish a connection with a guest-side listener |
| 94 | + // at the provided port number. This is specified in Firecracker documentation: |
| 95 | + // https://github.com/firecracker-microvm/firecracker/blob/main/docs/vsock.md#host-initiated-connections |
| 96 | + return fmt.Sprintf("CONNECT %d\n", port) |
| 97 | +} |
| 98 | + |
| 99 | +// tryConnect attempts to dial a guest vsock listener at the provided host-side |
| 100 | +// unix socket and provided guest-listener port. |
| 101 | +func tryConnect(logger *logrus.Entry, udsPath string, port uint32, timeout Timeout) (net.Conn, error) { |
| 102 | + conn, err := net.DialTimeout("unix", udsPath, timeout.DialTimeout) |
| 103 | + if err != nil { |
| 104 | + return nil, errors.Wrapf(err, "failed to dial %q within %s", udsPath, timeout.DialTimeout) |
| 105 | + } |
| 106 | + |
| 107 | + defer func() { |
| 108 | + if err != nil { |
| 109 | + closeErr := conn.Close() |
| 110 | + if closeErr != nil { |
| 111 | + logger.WithError(closeErr).Error( |
| 112 | + "failed to close vsock socket after previous error") |
| 113 | + } |
| 114 | + } |
| 115 | + }() |
| 116 | + |
| 117 | + msg := connectMsg(port) |
| 118 | + err = tryConnWrite(conn, msg, timeout.ConnectMsgTimeout) |
| 119 | + if err != nil { |
| 120 | + return nil, connectMsgError{ |
| 121 | + cause: errors.Wrapf(err, `failed to write %q within %s`, msg, timeout.ConnectMsgTimeout), |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + line, err := tryConnReadUntil(conn, '\n', timeout.AckMsgTimeout) |
| 126 | + if err != nil { |
| 127 | + return nil, ackError{ |
| 128 | + cause: errors.Wrapf(err, `failed to read "OK <port>" within %s`, timeout.AckMsgTimeout), |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + // The line would be "OK <assigned_hostside_port>\n", but we don't use the hostside port here. |
| 133 | + // https://github.com/firecracker-microvm/firecracker/blob/main/docs/vsock.md#host-initiated-connections |
| 134 | + if !strings.HasPrefix(line, "OK ") { |
| 135 | + return nil, ackError{ |
| 136 | + cause: errors.Errorf(`expected to read "OK <port>", but instead read %q`, line), |
| 137 | + } |
| 138 | + } |
| 139 | + return conn, nil |
| 140 | +} |
| 141 | + |
| 142 | +// tryConnReadUntil will try to do a read from the provided conn until the specified |
| 143 | +// end character is encounteed. Returning an error if the read does not complete |
| 144 | +// within the provided timeout. It will reset socket deadlines to none after returning. |
| 145 | +// It's only intended to be used for connect/ack messages, not general purpose reads |
| 146 | +// after the vsock connection is established fully. |
| 147 | +func tryConnReadUntil(conn net.Conn, end byte, timeout time.Duration) (string, error) { |
| 148 | + conn.SetDeadline(time.Now().Add(timeout)) |
| 149 | + defer conn.SetDeadline(time.Time{}) |
| 150 | + |
| 151 | + return bufio.NewReaderSize(conn, 32).ReadString(end) |
| 152 | +} |
| 153 | + |
| 154 | +// tryConnWrite will try to do a write to the provided conn, returning an error if |
| 155 | +// the write fails, is partial or does not complete within the provided timeout. It |
| 156 | +// will reset socket deadlines to none after returning. It's only intended to be |
| 157 | +// used for connect/ack messages, not general purpose writes after the vsock |
| 158 | +// connection is established fully. |
| 159 | +func tryConnWrite(conn net.Conn, expectedWrite string, timeout time.Duration) error { |
| 160 | + conn.SetDeadline(time.Now().Add(timeout)) |
| 161 | + defer conn.SetDeadline(time.Time{}) |
| 162 | + |
| 163 | + bytesWritten, err := conn.Write([]byte(expectedWrite)) |
| 164 | + if err != nil { |
| 165 | + return err |
| 166 | + } |
| 167 | + if bytesWritten != len(expectedWrite) { |
| 168 | + return errors.Errorf("incomplete write, expected %d bytes but wrote %d", |
| 169 | + len(expectedWrite), bytesWritten) |
| 170 | + } |
| 171 | + |
| 172 | + return nil |
| 173 | +} |
| 174 | + |
| 175 | +type connectMsgError struct { |
| 176 | + cause error |
| 177 | +} |
| 178 | + |
| 179 | +func (e connectMsgError) Error() string { |
| 180 | + return errors.Wrap(e.cause, "vsock connect message failure").Error() |
| 181 | +} |
| 182 | + |
| 183 | +func (e connectMsgError) Temporary() bool { |
| 184 | + return false |
| 185 | +} |
| 186 | + |
| 187 | +type ackError struct { |
| 188 | + cause error |
| 189 | +} |
| 190 | + |
| 191 | +func (e ackError) Error() string { |
| 192 | + return errors.Wrap(e.cause, "vsock ack message failure").Error() |
| 193 | +} |
| 194 | + |
| 195 | +func (e ackError) Temporary() bool { |
| 196 | + return true |
| 197 | +} |
| 198 | + |
| 199 | +// isTemporaryNetErr returns whether the provided error is a retriable |
| 200 | +// error, according to the interface defined here: |
| 201 | +// https://golang.org/pkg/net/#Error |
| 202 | +func isTemporaryNetErr(err error) bool { |
| 203 | + terr, ok := err.(interface { |
| 204 | + Temporary() bool |
| 205 | + }) |
| 206 | + |
| 207 | + return err != nil && ok && terr.Temporary() |
| 208 | +} |
0 commit comments