Skip to content

feat: add tailnet v2 support to wsproxy coordinate endpoint #11637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions enterprise/coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,15 @@ func New(ctx context.Context, options *Options) (_ *API, err error) {
}
return api.fetchRegions(ctx)
}
api.tailnetService, err = tailnet.NewClientService(
api.Logger.Named("tailnetclient"),
&api.AGPL.TailnetCoordinator,
api.Options.DERPMapUpdateFrequency,
api.AGPL.DERPMap,
)
if err != nil {
api.Logger.Fatal(api.ctx, "failed to initialize tailnet client service", slog.Error(err))
}

oauthConfigs := &httpmw.OAuth2Configs{
Github: options.GithubOAuth2Config,
Expand Down Expand Up @@ -483,6 +492,7 @@ type API struct {
provisionerDaemonAuth *provisionerDaemonAuth

licenseMetricsCollector license.MetricsCollector
tailnetService *tailnet.ClientService
}

func (api *API) Close() error {
Expand Down
25 changes: 20 additions & 5 deletions enterprise/coderd/workspaceproxycoordinate.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import (
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/enterprise/tailnet"
"github.com/coder/coder/v2/enterprise/wsproxy/wsproxysdk"
agpl "github.com/coder/coder/v2/tailnet"
)

// @Summary Agent is legacy
Expand Down Expand Up @@ -52,6 +52,21 @@ func (api *API) agentIsLegacy(rw http.ResponseWriter, r *http.Request) {
func (api *API) workspaceProxyCoordinate(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

version := "1.0"
qv := r.URL.Query().Get("version")
if qv != "" {
version = qv
}
if err := agpl.CurrentVersion.Validate(version); err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Unknown or unsupported API version",
Validations: []codersdk.ValidationError{
{Field: "version", Detail: err.Error()},
},
})
return
}

api.AGPL.WebsocketWaitMutex.Lock()
api.AGPL.WebsocketWaitGroup.Add(1)
api.AGPL.WebsocketWaitMutex.Unlock()
Expand All @@ -66,14 +81,14 @@ func (api *API) workspaceProxyCoordinate(rw http.ResponseWriter, r *http.Request
return
}

id := uuid.New()
sub := (*api.AGPL.TailnetCoordinator.Load()).ServeMultiAgent(id)

ctx, nc := websocketNetConn(ctx, conn, websocket.MessageText)
defer nc.Close()

err = tailnet.ServeWorkspaceProxy(ctx, nc, sub)
id := uuid.New()
err = api.tailnetService.ServeMultiAgentClient(ctx, version, nc, id)
if err != nil {
_ = conn.Close(websocket.StatusInternalError, err.Error())
} else {
_ = conn.Close(websocket.StatusGoingAway, "")
}
}
51 changes: 51 additions & 0 deletions enterprise/tailnet/workspaceproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,65 @@ import (
"encoding/json"
"errors"
"net"
"sync/atomic"
"time"

"github.com/google/uuid"
"golang.org/x/xerrors"
"tailscale.com/tailcfg"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/util/apiversion"
"github.com/coder/coder/v2/enterprise/wsproxy/wsproxysdk"
agpl "github.com/coder/coder/v2/tailnet"
)

type ClientService struct {
*agpl.ClientService
}

// NewClientService returns a ClientService based on the given Coordinator pointer. The pointer is
// loaded on each processed connection.
func NewClientService(
logger slog.Logger,
coordPtr *atomic.Pointer[agpl.Coordinator],
derpMapUpdateFrequency time.Duration,
derpMapFn func() *tailcfg.DERPMap,
) (
*ClientService, error,
) {
s, err := agpl.NewClientService(logger, coordPtr, derpMapUpdateFrequency, derpMapFn)
if err != nil {
return nil, err
}
return &ClientService{ClientService: s}, nil
}

func (s *ClientService) ServeMultiAgentClient(ctx context.Context, version string, conn net.Conn, id uuid.UUID) error {
major, _, err := apiversion.Parse(version)
if err != nil {
s.Logger.Warn(ctx, "serve client called with unparsable version", slog.Error(err))
return err
}
switch major {
case 1:
coord := *(s.CoordPtr.Load())
sub := coord.ServeMultiAgent(id)
return ServeWorkspaceProxy(ctx, conn, sub)
case 2:
auth := agpl.SingleTailnetTunnelAuth{}
streamID := agpl.StreamID{
Name: id.String(),
ID: id,
Auth: auth,
}
return s.ServeConnV2(ctx, conn, streamID)
default:
s.Logger.Warn(ctx, "serve client called with unsupported version", slog.F("version", version))
return xerrors.New("unsupported version")
}
}

func ServeWorkspaceProxy(ctx context.Context, conn net.Conn, ma agpl.MultiAgentConn) error {
go func() {
err := forwardNodesToWorkspaceProxy(ctx, conn, ma)
Expand Down
32 changes: 18 additions & 14 deletions tailnet/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,8 @@ func WithStreamID(ctx context.Context, streamID StreamID) context.Context {
// ClientService is a tailnet coordination service that accepts a connection and version from a
// tailnet client, and support versions 1.0 and 2.x of the Tailnet API protocol.
type ClientService struct {
logger slog.Logger
coordPtr *atomic.Pointer[Coordinator]
Logger slog.Logger
CoordPtr *atomic.Pointer[Coordinator]
drpc *drpcserver.Server
}

Expand All @@ -61,7 +61,7 @@ func NewClientService(
) (
*ClientService, error,
) {
s := &ClientService{logger: logger, coordPtr: coordPtr}
s := &ClientService{Logger: logger, CoordPtr: coordPtr}
mux := drpcmux.New()
drpcService := &DRPCService{
CoordPtr: coordPtr,
Expand All @@ -88,34 +88,38 @@ func NewClientService(
func (s *ClientService) ServeClient(ctx context.Context, version string, conn net.Conn, id uuid.UUID, agent uuid.UUID) error {
major, _, err := apiversion.Parse(version)
if err != nil {
s.logger.Warn(ctx, "serve client called with unparsable version", slog.Error(err))
s.Logger.Warn(ctx, "serve client called with unparsable version", slog.Error(err))
return err
}
switch major {
case 1:
coord := *(s.coordPtr.Load())
coord := *(s.CoordPtr.Load())
return coord.ServeClient(conn, id, agent)
case 2:
config := yamux.DefaultConfig()
config.LogOutput = io.Discard
session, err := yamux.Server(conn, config)
if err != nil {
return xerrors.Errorf("yamux init failed: %w", err)
}
auth := ClientTunnelAuth{AgentID: agent}
streamID := StreamID{
Name: "client",
ID: id,
Auth: auth,
}
ctx = WithStreamID(ctx, streamID)
return s.drpc.Serve(ctx, session)
return s.ServeConnV2(ctx, conn, streamID)
default:
s.logger.Warn(ctx, "serve client called with unsupported version", slog.F("version", version))
s.Logger.Warn(ctx, "serve client called with unsupported version", slog.F("version", version))
return xerrors.New("unsupported version")
}
}

func (s ClientService) ServeConnV2(ctx context.Context, conn net.Conn, streamID StreamID) error {
config := yamux.DefaultConfig()
config.LogOutput = io.Discard
session, err := yamux.Server(conn, config)
if err != nil {
return xerrors.Errorf("yamux init failed: %w", err)
}
ctx = WithStreamID(ctx, streamID)
return s.drpc.Serve(ctx, session)
}

// DRPCService is the dRPC-based, version 2.x of the tailnet API and implements proto.DRPCClientServer
type DRPCService struct {
CoordPtr *atomic.Pointer[Coordinator]
Expand Down