Skip to content

chore: added support for immortal streams to cli and agent #19328

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

Draft
wants to merge 1 commit into
base: mike/immortal-streams-agent-api
Choose a base branch
from
Draft
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
50 changes: 48 additions & 2 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,47 @@ const (
EnvProcOOMScore = "CODER_PROC_OOM_SCORE"
)

// agentImmortalDialer is a custom dialer for immortal streams that can
// connect to the agent's own services via tailnet addresses.
type agentImmortalDialer struct {
agent *agent
standardDialer *net.Dialer
}

func (d *agentImmortalDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(address)
if err != nil {
return nil, xerrors.Errorf("split host port %q: %w", address, err)
}

port, err := strconv.Atoi(portStr)
if err != nil {
return nil, xerrors.Errorf("parse port %q: %w", portStr, err)
}

// Check if this is a connection to one of the agent's own services
isLocalhost := host == "localhost" || host == "127.0.0.1" || host == "::1"
isAgentPort := port == int(workspacesdk.AgentSSHPort) || port == int(workspacesdk.AgentHTTPAPIServerPort) ||
port == int(workspacesdk.AgentReconnectingPTYPort) || port == int(workspacesdk.AgentSpeedtestPort)

if isLocalhost && isAgentPort {
// Get the agent ID from the current manifest
manifest := d.agent.manifest.Load()
if manifest == nil || manifest.AgentID == uuid.Nil {
// Fallback to standard dialing if no manifest available yet
return d.standardDialer.DialContext(ctx, network, address)
}

// Connect to the agent's own tailnet address instead of localhost
agentAddr := tailnet.TailscaleServicePrefix.AddrFromUUID(manifest.AgentID)
agentAddress := net.JoinHostPort(agentAddr.String(), portStr)
return d.standardDialer.DialContext(ctx, network, agentAddress)
}

// For other addresses, use standard dialing
return d.standardDialer.DialContext(ctx, network, address)
}

type Options struct {
Filesystem afero.Fs
LogDir string
Expand Down Expand Up @@ -351,8 +392,13 @@ func (a *agent) init() {

a.containerAPI = agentcontainers.NewAPI(a.logger.Named("containers"), containerAPIOpts...)

// Initialize immortal streams manager
a.immortalStreamsManager = immortalstreams.New(a.logger.Named("immortal-streams"), &net.Dialer{})
// Initialize immortal streams manager with a custom dialer
// that can connect to the agent's own services
immortalDialer := &agentImmortalDialer{
agent: a,
standardDialer: &net.Dialer{},
}
a.immortalStreamsManager = immortalstreams.New(a.logger.Named("immortal-streams"), immortalDialer)

a.reconnectingPTYServer = reconnectingpty.NewServer(
a.logger.Named("reconnecting-pty"),
Expand Down
1 change: 1 addition & 0 deletions cli/exp.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ func (r *RootCmd) expCmd() *serpent.Command {
r.mcpCommand(),
r.promptExample(),
r.rptyCommand(),
r.immortalStreamCmd(),
},
}
return cmd
Expand Down
188 changes: 188 additions & 0 deletions cli/immortalstreams.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package cli

import (
"context"
"fmt"

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

"cdr.dev/slog"
"github.com/coder/coder/v2/cli/cliui"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/serpent"
)

// immortalStreamClient provides methods to interact with immortal streams API
// This uses the main codersdk.Client to make server-proxied requests to agents
type immortalStreamClient struct {
client *codersdk.Client
agentID uuid.UUID
logger slog.Logger
}

// newImmortalStreamClient creates a new client for immortal streams
func newImmortalStreamClient(client *codersdk.Client, agentID uuid.UUID, logger slog.Logger) *immortalStreamClient {
return &immortalStreamClient{
client: client,
agentID: agentID,
logger: logger,
}
}

// createStream creates a new immortal stream
func (c *immortalStreamClient) createStream(ctx context.Context, port int) (*codersdk.ImmortalStream, error) {
stream, err := c.client.WorkspaceAgentCreateImmortalStream(ctx, c.agentID, codersdk.CreateImmortalStreamRequest{
TCPPort: port,
})
if err != nil {
return nil, err
}
return &stream, nil
}

// listStreams lists all immortal streams
func (c *immortalStreamClient) listStreams(ctx context.Context) ([]codersdk.ImmortalStream, error) {
return c.client.WorkspaceAgentImmortalStreams(ctx, c.agentID)
}

// deleteStream deletes an immortal stream
func (c *immortalStreamClient) deleteStream(ctx context.Context, streamID uuid.UUID) error {
return c.client.WorkspaceAgentDeleteImmortalStream(ctx, c.agentID, streamID)
}

// CLI Commands

func (r *RootCmd) immortalStreamCmd() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "immortal-stream",
Short: "Manage immortal streams in workspaces",
Long: "Immortal streams provide persistent TCP connections to workspace services that automatically reconnect when interrupted.",
Middleware: serpent.Chain(
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
return inv.Command.HelpHandler(inv)
},
Children: []*serpent.Command{
r.immortalStreamListCmd(),
r.immortalStreamDeleteCmd(),
},
}
return cmd
}

func (r *RootCmd) immortalStreamListCmd() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "list <workspace-name>",
Short: "List active immortal streams in a workspace",
Middleware: serpent.Chain(
serpent.RequireNArgs(1),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
workspaceName := inv.Args[0]

workspace, workspaceAgent, _, err := getWorkspaceAndAgent(ctx, inv, client, false, workspaceName)
if err != nil {
return err
}

if workspace.LatestBuild.Transition != codersdk.WorkspaceTransitionStart {
return xerrors.New("workspace must be running to list immortal streams")
}

// Create immortal stream client
// Note: We don't need to dial the agent for management operations
// as these go through the server's proxy endpoints
streamClient := newImmortalStreamClient(client, workspaceAgent.ID, inv.Logger)
streams, err := streamClient.listStreams(ctx)
if err != nil {
return xerrors.Errorf("list immortal streams: %w", err)
}

if len(streams) == 0 {
cliui.Info(inv.Stderr, "No active immortal streams found.")
return nil
}

// Display the streams in a table
displayImmortalStreams(inv, streams)
return nil
},
}
return cmd
}

func (r *RootCmd) immortalStreamDeleteCmd() *serpent.Command {
client := new(codersdk.Client)
cmd := &serpent.Command{
Use: "delete <workspace-name> <immortal-stream-name>",
Short: "Delete an active immortal stream",
Middleware: serpent.Chain(
serpent.RequireNArgs(2),
r.InitClient(client),
),
Handler: func(inv *serpent.Invocation) error {
ctx := inv.Context()
workspaceName := inv.Args[0]
streamName := inv.Args[1]

workspace, workspaceAgent, _, err := getWorkspaceAndAgent(ctx, inv, client, false, workspaceName)
if err != nil {
return err
}

if workspace.LatestBuild.Transition != codersdk.WorkspaceTransitionStart {
return xerrors.New("workspace must be running to delete immortal streams")
}

// Create immortal stream client
streamClient := newImmortalStreamClient(client, workspaceAgent.ID, inv.Logger)
streams, err := streamClient.listStreams(ctx)
if err != nil {
return xerrors.Errorf("list immortal streams: %w", err)
}

var targetStream *codersdk.ImmortalStream
for _, stream := range streams {
if stream.Name == streamName {
targetStream = &stream
break
}
}

if targetStream == nil {
return xerrors.Errorf("immortal stream %q not found", streamName)
}

// Delete the stream
err = streamClient.deleteStream(ctx, targetStream.ID)
if err != nil {
return xerrors.Errorf("delete immortal stream: %w", err)
}

cliui.Info(inv.Stderr, fmt.Sprintf("Deleted immortal stream %q (ID: %s)", streamName, targetStream.ID))
return nil
},
}
return cmd
}

func displayImmortalStreams(inv *serpent.Invocation, streams []codersdk.ImmortalStream) {
_, _ = fmt.Fprintf(inv.Stderr, "Active Immortal Streams:\n\n")
_, _ = fmt.Fprintf(inv.Stderr, "%-20s %-6s %-20s %-20s\n", "NAME", "PORT", "CREATED", "LAST CONNECTED")
_, _ = fmt.Fprintf(inv.Stderr, "%-20s %-6s %-20s %-20s\n", "----", "----", "-------", "--------------")

for _, stream := range streams {
createdTime := stream.CreatedAt.Format("2006-01-02 15:04:05")
lastConnTime := stream.LastConnectionAt.Format("2006-01-02 15:04:05")

_, _ = fmt.Fprintf(inv.Stderr, "%-20s %-6d %-20s %-20s\n",
stream.Name, stream.TCPPort, createdTime, lastConnTime)
}
_, _ = fmt.Fprintf(inv.Stderr, "\n")
}
17 changes: 17 additions & 0 deletions cli/portforward.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@
udpForwards []string // <port>:<port>
disableAutostart bool
appearanceConfig codersdk.AppearanceConfig

// Immortal streams flags
immortal bool
immortalFallback bool = true // Default to true for port-forward

Check failure on line 45 in cli/portforward.go

View workflow job for this annotation

GitHub Actions / lint

var-declaration: should omit type bool from declaration of var immortalFallback; it will be inferred from the right-hand side (revive)
)
client := new(codersdk.Client)
cmd := &serpent.Command{
Expand Down Expand Up @@ -212,6 +216,19 @@
Description: "Forward UDP port(s) from the workspace to the local machine. The UDP connection has TCP-like semantics to support stateful UDP protocols.",
Value: serpent.StringArrayOf(&udpForwards),
},
{
Flag: "immortal",
Description: "Use immortal streams for port forwarding connections, providing automatic reconnection when interrupted.",
Value: serpent.BoolOf(&immortal),
Hidden: true,
},
{
Flag: "immortal-fallback",
Description: "If immortal streams are unavailable due to connection limits, fall back to regular TCP connection.",
Default: "true",
Value: serpent.BoolOf(&immortalFallback),
Hidden: true,
},
sshDisableAutostartOption(serpent.BoolOf(&disableAutostart)),
}

Expand Down
Loading
Loading