Skip to content

Commit

Permalink
Merge pull request #380 from austinvazquez/vsock
Browse files Browse the repository at this point in the history
Refactor: pull in firecracker-containerd's internal vsock module as a package
  • Loading branch information
austinvazquez authored Feb 9, 2022
2 parents a6bf179 + a9057bd commit 46c9cb6
Show file tree
Hide file tree
Showing 4 changed files with 338 additions and 1 deletion.
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ require (
github.com/go-openapi/validate v0.20.3
github.com/google/uuid v1.3.0
github.com/hashicorp/go-multierror v1.1.1
github.com/mdlayher/vsock v1.0.0
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.8.1
github.com/sparrc/go-ping v0.0.0-20190613174326-4e5b6552494c
github.com/stretchr/testify v1.7.0
github.com/vishvananda/netlink v1.1.1-0.20210330154013-f5de75959ad5
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a
)
18 changes: 18 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,9 @@ github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
Expand Down Expand Up @@ -558,6 +561,10 @@ github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vq
github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
github.com/mdlayher/socket v0.1.1 h1:q3uOGirUPfAV2MUoaC7BavjQ154J7+JOkTWyiV+intI=
github.com/mdlayher/socket v0.1.1/go.mod h1:mYV5YIZAfHh4dzDVzI8x8tWLWCliuX8Mon5Awbj+qDs=
github.com/mdlayher/vsock v1.0.0 h1:xHmS5JFckaaTqj6VI7QrtvQKfrAm6N5n1dcjWeNa2rM=
github.com/mdlayher/vsock v1.0.0/go.mod h1:jMTGWjWntkzvtOi/ael17m1xiW22T9j2rbwsR4B/sE0=
github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=
github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
Expand Down Expand Up @@ -886,6 +893,9 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781 h1:DzZ89McO9/gWPsQXS/FVKAlG02ZjaQ6AlZRBimEYOd0=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd h1:O7DYs+zxREGLKzKoMQrtrEacpb0ZVXA5rIwylE2Xchk=
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
Expand All @@ -901,6 +911,8 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down Expand Up @@ -968,9 +980,15 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e h1:WUoyKPm6nCo1BnNUvPGnFG3T5DUVem42yDJZZ4CNxMA=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a h1:ppl5mZgokTT8uPkmYOyEUmPTr3ypaKkg5eFOGrAmxxE=
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
208 changes: 208 additions & 0 deletions vsock/dial.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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.

package vsock

import (
"bufio"
"context"
"fmt"
"net"
"strings"
"time"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

type Timeout struct {
DialTimeout time.Duration
RetryTimeout time.Duration
RetryInterval time.Duration
ConnectMsgTimeout time.Duration
AckMsgTimeout time.Duration
}

func DefaultTimeouts() Timeout {
return Timeout{
DialTimeout: 100 * time.Millisecond,
RetryTimeout: 20 * time.Second,
RetryInterval: 100 * time.Millisecond,
ConnectMsgTimeout: 100 * time.Millisecond,
AckMsgTimeout: 1 * time.Second,
}
}

// Dial connects to the Firecracker host-side vsock at the provided unix path and port.
//
// It will retry connect attempts if a temporary error is encountered up to a fixed
// timeout or the provided request is canceled.
//
// udsPath specifies the file system path of the UNIX domain socket.
//
// port will be used in the connect message to the firecracker vsock.
func Dial(ctx context.Context, logger *logrus.Entry, udsPath string, port uint32) (net.Conn, error) {
return DialTimeout(ctx, logger, udsPath, port, DefaultTimeouts())
}

// DialTimeout acts like Dial but takes a timeout.
//
// See func Dial for a description of the udsPath and port parameters.
func DialTimeout(ctx context.Context, logger *logrus.Entry, udsPath string, port uint32, timeout Timeout) (net.Conn, error) {
ticker := time.NewTicker(timeout.RetryInterval)
defer ticker.Stop()

tickerCh := ticker.C
var attemptCount int
for {
attemptCount++
logger := logger.WithField("attempt", attemptCount)

select {
case <-ctx.Done():
return nil, ctx.Err()
case <-tickerCh:
conn, err := tryConnect(logger, udsPath, port, timeout)
if isTemporaryNetErr(err) {
err = errors.Wrap(err, "temporary vsock dial failure")
logger.WithError(err).Debug()
continue
} else if err != nil {
err = errors.Wrap(err, "non-temporary vsock dial failure")
logger.WithError(err).Error()
return nil, err
}

return conn, nil
}
}
}

func connectMsg(port uint32) string {
// The message a host-side connection must write after connecting to a firecracker
// vsock unix socket in order to establish a connection with a guest-side listener
// at the provided port number. This is specified in Firecracker documentation:
// https://github.com/firecracker-microvm/firecracker/blob/main/docs/vsock.md#host-initiated-connections
return fmt.Sprintf("CONNECT %d\n", port)
}

// tryConnect attempts to dial a guest vsock listener at the provided host-side
// unix socket and provided guest-listener port.
func tryConnect(logger *logrus.Entry, udsPath string, port uint32, timeout Timeout) (net.Conn, error) {
conn, err := net.DialTimeout("unix", udsPath, timeout.DialTimeout)
if err != nil {
return nil, errors.Wrapf(err, "failed to dial %q within %s", udsPath, timeout.DialTimeout)
}

defer func() {
if err != nil {
closeErr := conn.Close()
if closeErr != nil {
logger.WithError(closeErr).Error(
"failed to close vsock socket after previous error")
}
}
}()

msg := connectMsg(port)
err = tryConnWrite(conn, msg, timeout.ConnectMsgTimeout)
if err != nil {
return nil, connectMsgError{
cause: errors.Wrapf(err, `failed to write %q within %s`, msg, timeout.ConnectMsgTimeout),
}
}

line, err := tryConnReadUntil(conn, '\n', timeout.AckMsgTimeout)
if err != nil {
return nil, ackError{
cause: errors.Wrapf(err, `failed to read "OK <port>" within %s`, timeout.AckMsgTimeout),
}
}

// The line would be "OK <assigned_hostside_port>\n", but we don't use the hostside port here.
// https://github.com/firecracker-microvm/firecracker/blob/main/docs/vsock.md#host-initiated-connections
if !strings.HasPrefix(line, "OK ") {
return nil, ackError{
cause: errors.Errorf(`expected to read "OK <port>", but instead read %q`, line),
}
}
return conn, nil
}

// tryConnReadUntil will try to do a read from the provided conn until the specified
// end character is encounteed. Returning an error if the read does not complete
// within the provided timeout. It will reset socket deadlines to none after returning.
// It's only intended to be used for connect/ack messages, not general purpose reads
// after the vsock connection is established fully.
func tryConnReadUntil(conn net.Conn, end byte, timeout time.Duration) (string, error) {
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})

return bufio.NewReaderSize(conn, 32).ReadString(end)
}

// tryConnWrite will try to do a write to the provided conn, returning an error if
// the write fails, is partial or does not complete within the provided timeout. It
// will reset socket deadlines to none after returning. It's only intended to be
// used for connect/ack messages, not general purpose writes after the vsock
// connection is established fully.
func tryConnWrite(conn net.Conn, expectedWrite string, timeout time.Duration) error {
conn.SetDeadline(time.Now().Add(timeout))
defer conn.SetDeadline(time.Time{})

bytesWritten, err := conn.Write([]byte(expectedWrite))
if err != nil {
return err
}
if bytesWritten != len(expectedWrite) {
return errors.Errorf("incomplete write, expected %d bytes but wrote %d",
len(expectedWrite), bytesWritten)
}

return nil
}

type connectMsgError struct {
cause error
}

func (e connectMsgError) Error() string {
return errors.Wrap(e.cause, "vsock connect message failure").Error()
}

func (e connectMsgError) Temporary() bool {
return false
}

type ackError struct {
cause error
}

func (e ackError) Error() string {
return errors.Wrap(e.cause, "vsock ack message failure").Error()
}

func (e ackError) Temporary() bool {
return true
}

// isTemporaryNetErr returns whether the provided error is a retriable
// error, according to the interface defined here:
// https://golang.org/pkg/net/#Error
func isTemporaryNetErr(err error) bool {
terr, ok := err.(interface {
Temporary() bool
})

return err != nil && ok && terr.Temporary()
}
110 changes: 110 additions & 0 deletions vsock/listener.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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.

package vsock

import (
"context"
"net"
"time"

"github.com/mdlayher/vsock"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

type listener struct {
listener net.Listener
port uint32
timeout Timeout
ctx context.Context
logger *logrus.Entry
}

// Listener returns a net.Listener implementation for guest-side Firecracker
// vsock connections.
func Listener(ctx context.Context, logger *logrus.Entry, port uint32) (net.Listener, error) {
l, err := vsock.Listen(port, nil)
if err != nil {
return nil, err
}

return listener{
listener: l,
port: port,
timeout: DefaultTimeouts(),
ctx: ctx,
logger: logger,
}, nil
}

func (l listener) Accept() (net.Conn, error) {
ctx, cancel := context.WithTimeout(l.ctx, l.timeout.RetryTimeout)
defer cancel()

var attemptCount int
ticker := time.NewTicker(l.timeout.RetryInterval)
defer ticker.Stop()
tickerCh := ticker.C
for {
attemptCount++
logger := l.logger.WithField("attempt", attemptCount)

select {
case <-ctx.Done():
return nil, ctx.Err()
case <-tickerCh:
conn, err := tryAccept(logger, l.listener, l.port)
if isTemporaryNetErr(err) {
err = errors.Wrap(err, "temporary vsock accept failure")
logger.WithError(err).Debug()
continue
} else if err != nil {
err = errors.Wrap(err, "non-temporary vsock accept failure")
logger.WithError(err).Error()
return nil, err
}

return conn, nil
}
}
}

func (l listener) Close() error {
return l.listener.Close()
}

func (l listener) Addr() net.Addr {
return l.listener.Addr()
}

// tryAccept attempts to accept a single host-side connection from the provided
// guest-side listener at the provided port.
func tryAccept(logger *logrus.Entry, listener net.Listener, port uint32) (net.Conn, error) {
conn, err := listener.Accept()
if err != nil {
return nil, err
}

defer func() {
if err != nil {
closeErr := conn.Close()
if closeErr != nil {
logger.WithError(closeErr).Error(
"failed to close vsock after previous error")
}
}
}()

return conn, nil
}

0 comments on commit 46c9cb6

Please sign in to comment.