2022-03-07 11:40:54 -06:00
package cli
import (
2022-03-25 10:34:45 -06:00
"context"
2022-06-17 00:54:45 -05:00
"fmt"
2023-02-01 16:04:09 +02:00
"io"
2025-04-09 09:20:47 +01:00
"net"
2022-03-28 13:31:03 -06:00
"net/http"
2022-11-08 15:02:07 +01:00
"net/http/pprof"
2022-03-07 11:40:54 -06:00
"net/url"
2022-05-02 11:36:51 -05:00
"os"
2026-02-05 12:32:07 -06:00
"os/signal"
2022-05-02 11:36:51 -05:00
"path/filepath"
2022-06-17 11:51:46 -05:00
"runtime"
2025-11-05 14:22:24 +02:00
"slices"
2023-03-09 10:53:00 -06:00
"strconv"
2023-08-08 22:10:28 -07:00
"strings"
2022-03-25 10:34:45 -06:00
"time"
2022-03-07 11:40:54 -06:00
2026-04-02 23:51:02 +02:00
"github.com/google/uuid"
2026-01-08 15:24:11 +04:00
"github.com/prometheus/client_golang/prometheus"
2022-03-07 11:40:54 -06:00
"golang.org/x/xerrors"
2022-06-24 10:25:01 -05:00
"gopkg.in/natefinch/lumberjack.v2"
2022-03-07 11:40:54 -06:00
2026-01-08 10:29:41 +04:00
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/sloghuman"
"cdr.dev/slog/v3/sloggers/slogjson"
"cdr.dev/slog/v3/sloggers/slogstackdriver"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/agent"
2025-06-10 12:37:54 +03:00
"github.com/coder/coder/v2/agent/agentcontainers"
2026-04-28 17:58:28 +03:00
"github.com/coder/coder/v2/agent/agentcontextconfig"
2024-11-27 20:12:15 +02:00
"github.com/coder/coder/v2/agent/agentexec"
2024-06-10 14:12:23 +02:00
"github.com/coder/coder/v2/agent/agentssh"
2025-12-31 16:38:19 -07:00
"github.com/coder/coder/v2/agent/boundarylogproxy"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/agent/reaper"
"github.com/coder/coder/v2/buildinfo"
2024-11-19 19:47:35 +11:00
"github.com/coder/coder/v2/cli/clilog"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
2026-01-08 15:24:11 +04:00
"github.com/coder/serpent"
2022-03-07 11:40:54 -06:00
)
2025-09-03 10:38:42 +04:00
func workspaceAgent () * serpent . Command {
2022-03-25 13:48:08 -06:00
var (
2026-07-20 15:39:21 +02:00
logDir string
scriptDataDir string
pprofAddress string
noReap bool
sshMaxTimeout time . Duration
tailnetListenPort int64
prometheusAddress string
debugAddress string
slogHumanPath string
slogJSONPath string
slogStackdriverPath string
blockFileTransfer bool
blockReversePortForwarding bool
blockLocalPortForwarding bool
agentHeaderCommand string
agentHeader [] string
devcontainers bool
devcontainerProjectDiscovery bool
devcontainerDiscoveryAutostart bool
socketServerEnabled bool
socketPath string
agentFirewallLogProxySocketPath string
2022-03-25 13:48:08 -06:00
)
2025-09-03 10:38:42 +04:00
agentAuth := & AgentAuth {}
2024-03-17 09:45:26 -05:00
cmd := & serpent . Command {
2023-03-23 17:42:20 -05:00
Use : "agent" ,
Short : `Starts the Coder workspace agent.` ,
2022-03-25 10:34:45 -06:00
// This command isn't useful to manually execute.
2022-03-07 11:40:54 -06:00
Hidden : true ,
2024-03-15 11:24:38 -05:00
Handler : func ( inv * serpent . Invocation ) error {
2025-05-14 14:15:36 +02:00
ctx , cancel := context . WithCancelCause ( inv . Context ())
defer func () {
cancel ( xerrors . New ( "agent exited" ))
}()
2022-11-14 13:48:44 +02:00
2023-06-02 15:51:10 -05:00
var (
ignorePorts = map [ int ] string {}
isLinux = runtime . GOOS == "linux"
2022-05-02 11:36:51 -05:00
2023-06-02 15:51:10 -05:00
sinks = [] slog . Sink {}
logClosers = [] func () error {}
)
defer func () {
for _ , closer := range logClosers {
_ = closer ()
}
}()
addSinkIfProvided := func ( sinkFn func ( io . Writer ) slog . Sink , loc string ) error {
switch loc {
case "" :
// Do nothing.
case "/dev/stderr" :
sinks = append ( sinks , sinkFn ( inv . Stderr ))
case "/dev/stdout" :
sinks = append ( sinks , sinkFn ( inv . Stdout ))
default :
fi , err := os . OpenFile ( loc , os . O_WRONLY | os . O_CREATE | os . O_APPEND , 0 o644 )
if err != nil {
return xerrors . Errorf ( "open log file %q: %w" , loc , err )
}
sinks = append ( sinks , sinkFn ( fi ))
logClosers = append ( logClosers , fi . Close )
}
return nil
}
if err := addSinkIfProvided ( sloghuman . Sink , slogHumanPath ); err != nil {
return xerrors . Errorf ( "add human sink: %w" , err )
}
if err := addSinkIfProvided ( slogjson . Sink , slogJSONPath ); err != nil {
return xerrors . Errorf ( "add json sink: %w" , err )
}
if err := addSinkIfProvided ( slogstackdriver . Sink , slogStackdriverPath ); err != nil {
return xerrors . Errorf ( "add stackdriver sink: %w" , err )
}
2022-06-17 11:51:46 -05:00
// Spawn a reaper so that we don't accumulate a ton
// of zombie processes.
2022-06-21 18:01:34 -05:00
if reaper . IsInitProcess () && ! noReap && isLinux {
2024-11-19 19:47:35 +11:00
logWriter := & clilog . LumberjackWriteCloseFixer { Writer : & lumberjack . Logger {
2023-01-30 18:39:52 +02:00
Filename : filepath . Join ( logDir , "coder-agent-init.log" ),
2023-01-30 15:59:13 +02:00
MaxSize : 5 , // MB
2023-06-02 12:28:38 -05:00
// Without this, rotated logs will never be deleted.
MaxBackups : 1 ,
2023-06-27 15:49:44 +03:00
}}
2023-01-30 15:59:13 +02:00
defer logWriter . Close ()
2023-05-24 07:32:40 -07:00
2023-06-02 15:51:10 -05:00
sinks = append ( sinks , sloghuman . Sink ( logWriter ))
2023-11-14 22:56:27 +04:00
logger := inv . Logger . AppendSinks ( sinks ... ). Leveled ( slog . LevelDebug )
2026-02-05 12:32:07 -06:00
logger = logger . Named ( "reaper" )
2023-01-30 15:59:13 +02:00
2022-11-14 13:48:44 +02:00
logger . Info ( ctx , "spawning reaper process" )
2022-06-21 18:01:34 -05:00
// Do not start a reaper on the child process. It's important
// to do this else we fork bomb ourselves.
2025-03-26 01:56:39 -05:00
//nolint:gocritic
2022-06-21 18:01:34 -05:00
args := append ( os . Args , "--no-reap" )
2026-01-28 21:56:04 +00:00
exitCode , err := reaper . ForkReap (
2023-02-09 23:07:21 +02:00
reaper . WithExecArgs ( args ... ),
2024-03-15 14:16:36 +01:00
reaper . WithCatchSignals ( StopSignals ... ),
2026-02-05 12:32:07 -06:00
reaper . WithLogger ( logger ),
2023-02-09 23:07:21 +02:00
)
2022-06-17 11:51:46 -05:00
if err != nil {
2023-06-20 12:30:45 +02:00
logger . Error ( ctx , "agent process reaper unable to fork" , slog . Error ( err ))
2022-06-17 11:51:46 -05:00
return xerrors . Errorf ( "fork reap: %w" , err )
}
2026-02-05 12:32:07 -06:00
logger . Info ( ctx , "child process exited, propagating exit code" ,
slog . F ( "exit_code" , exitCode ),
)
2026-01-28 21:56:04 +00:00
return ExitError ( exitCode , nil )
2022-06-17 11:51:46 -05:00
}
2024-11-19 19:47:35 +11:00
logWriter := & clilog . LumberjackWriteCloseFixer { Writer : & lumberjack . Logger {
2023-01-30 18:39:52 +02:00
Filename : filepath . Join ( logDir , "coder-agent.log" ),
2023-01-30 15:59:13 +02:00
MaxSize : 5 , // MB
2026-06-30 20:24:51 +03:00
// Keep up to the debug logs response cap across the active log and rotations.
MaxBackups : 19 ,
2023-06-27 15:49:44 +03:00
}}
2023-01-30 15:59:13 +02:00
defer logWriter . Close ()
2023-02-01 16:04:09 +02:00
2023-06-02 15:51:10 -05:00
sinks = append ( sinks , sloghuman . Sink ( logWriter ))
2023-11-14 22:56:27 +04:00
logger := inv . Logger . AppendSinks ( sinks ... ). Leveled ( slog . LevelDebug )
2023-01-30 15:59:13 +02:00
2026-02-05 12:32:07 -06:00
// Handle interrupt signals to allow for graceful shutdown,
// note that calling stopNotify disables the signal handler
// and the next interrupt will terminate the program (you
// probably want cancel instead).
//
// Note that we also handle these signals in the
// process that runs as PID 1, mainly to forward it to the agent child
// so that it can shutdown gracefully.
ctx , stopNotify := logSignalNotifyContext ( ctx , logger , StopSignals ... )
defer stopNotify ()
// DumpHandler does signal handling, so we call it after the
// reaper.
go DumpHandler ( ctx , "agent" )
2022-08-31 16:33:50 +01:00
version := buildinfo . Version ()
2023-06-20 12:30:45 +02:00
logger . Info ( ctx , "agent is starting now" ,
2025-09-03 10:38:42 +04:00
slog . F ( "url" , agentAuth . agentURL ),
slog . F ( "auth" , agentAuth . agentAuth ),
2022-08-31 16:33:50 +01:00
slog . F ( "version" , version ),
)
2025-09-03 10:49:19 +04:00
client , err := agentAuth . CreateClient ()
2025-09-03 10:38:42 +04:00
if err != nil {
return xerrors . Errorf ( "create agent client: %w" , err )
}
2023-07-06 09:43:39 +01:00
client . SDK . SetLogger ( logger )
2022-10-23 22:35:08 -05:00
// Set a reasonable timeout so requests can't hang forever!
2023-03-23 14:09:13 -05:00
// The timeout needs to be reasonably long, because requests
// with large payloads can take a bit. e.g. startup scripts
// may take a while to insert.
client . SDK . HTTPClient . Timeout = 30 * time . Second
2024-08-29 14:15:15 +10:00
// Attach header transport so we process --agent-header and
// --agent-header-command flags
2025-09-03 10:38:42 +04:00
headerTransport , err := headerTransport ( ctx , & agentAuth . agentURL , agentHeader , agentHeaderCommand )
2024-08-29 14:15:15 +10:00
if err != nil {
return xerrors . Errorf ( "configure header transport: %w" , err )
}
headerTransport . Transport = client . SDK . HTTPClient . Transport
client . SDK . HTTPClient . Transport = headerTransport
2022-03-28 13:31:03 -06:00
2022-11-08 15:02:07 +01:00
// Enable pprof handler
// This prevents the pprof import from being accidentally deleted.
_ = pprof . Handler
2025-11-05 14:22:24 +02:00
if pprofAddress != "" {
pprofSrvClose := ServeHandler ( ctx , logger , nil , pprofAddress , "pprof" )
defer pprofSrvClose ()
2022-06-06 16:38:33 +03:00
2025-11-05 14:22:24 +02:00
if port , err := extractPort ( pprofAddress ); err == nil {
ignorePorts [ port ] = "pprof"
}
} else {
logger . Debug ( ctx , "pprof address is empty, disabling pprof server" )
2023-05-23 17:14:05 +02:00
}
2022-06-17 00:54:45 -05:00
executablePath , err := os . Executable ()
if err != nil {
return xerrors . Errorf ( "getting os executable: %w" , err )
}
err = os . Setenv ( "PATH" , fmt . Sprintf ( "%s%c%s" , os . Getenv ( "PATH" ), filepath . ListSeparator , filepath . Dir ( executablePath )))
if err != nil {
return xerrors . Errorf ( "add executable to $PATH: %w" , err )
}
2023-08-08 22:10:28 -07:00
subsystemsRaw := inv . Environ . Get ( agent . EnvAgentSubsystem )
subsystems := [] codersdk . AgentSubsystem {}
for _ , s := range strings . Split ( subsystemsRaw , "," ) {
subsystem := codersdk . AgentSubsystem ( strings . TrimSpace ( s ))
if subsystem == "" {
continue
}
if ! subsystem . Valid () {
return xerrors . Errorf ( "invalid subsystem %q" , subsystem )
}
subsystems = append ( subsystems , subsystem )
}
2024-02-19 16:30:00 +02:00
environmentVariables := map [ string ] string {
"GIT_ASKPASS" : executablePath ,
}
2024-11-27 20:12:15 +02:00
enabled := os . Getenv ( agentexec . EnvProcPrioMgmt )
if enabled != "" && runtime . GOOS == "linux" {
logger . Info ( ctx , "process priority management enabled" ,
slog . F ( "env_var" , agentexec . EnvProcPrioMgmt ),
slog . F ( "enabled" , enabled ),
slog . F ( "os" , runtime . GOOS ),
)
} else {
logger . Info ( ctx , "process priority management not enabled (linux-only) " ,
slog . F ( "env_var" , agentexec . EnvProcPrioMgmt ),
slog . F ( "enabled" , enabled ),
slog . F ( "os" , runtime . GOOS ),
)
2024-04-03 09:42:03 -05:00
}
2024-02-19 16:30:00 +02:00
2024-12-04 23:30:25 +02:00
execer , err := agentexec . NewExecer ()
if err != nil {
return xerrors . Errorf ( "create agent execer: %w" , err )
}
2025-06-24 21:17:04 +03:00
if devcontainers {
2025-02-11 15:29:59 +00:00
logger . Info ( ctx , "agent devcontainer detection enabled" )
2025-04-29 17:53:10 +03:00
} else {
logger . Info ( ctx , "agent devcontainer detection not enabled" )
2025-02-11 15:29:59 +00:00
}
2026-04-02 23:51:02 +02:00
reinitCtx , reinitCancel := context . WithCancel ( ctx )
defer reinitCancel ()
reinitEvents := agentsdk . WaitForReinitLoop ( reinitCtx , logger , client )
2023-05-25 12:52:36 +02:00
2026-04-28 17:58:28 +03:00
// Read and strip env vars before the reinit
// loop so config survives agent restarts.
contextConfig := agentcontextconfig . ReadEnvConfig ()
agentcontextconfig . ClearEnvVars ()
2025-05-14 14:15:36 +02:00
var (
2026-04-02 23:51:02 +02:00
lastOwnerID uuid . UUID
lastErr error
mustExit bool
2025-05-14 14:15:36 +02:00
)
for {
prometheusRegistry := prometheus . NewRegistry ()
2025-02-26 09:03:27 +00:00
2025-11-05 14:22:24 +02:00
promHandler := agent . PrometheusMetricsHandler ( prometheusRegistry , logger )
var serverClose [] func ()
if prometheusAddress != "" {
prometheusSrvClose := ServeHandler ( ctx , logger , promHandler , prometheusAddress , "prometheus" )
serverClose = append ( serverClose , prometheusSrvClose )
if port , err := extractPort ( prometheusAddress ); err == nil {
ignorePorts [ port ] = "prometheus"
}
} else {
logger . Debug ( ctx , "prometheus address is empty, disabling prometheus server" )
}
if debugAddress != "" {
// ServerHandle depends on `agnt.HTTPDebug()`, but `agnt`
// depends on `ignorePorts`. Keep this if statement in sync
// with below.
if port , err := extractPort ( debugAddress ); err == nil {
ignorePorts [ port ] = "debug"
}
}
2025-05-14 14:15:36 +02:00
agnt := agent . New ( agent . Options {
Client : client ,
Logger : logger ,
LogDir : logDir ,
ScriptDataDir : scriptDataDir ,
// #nosec G115 - Safe conversion as tailnet listen port is within uint16 range (0-65535)
2025-09-03 10:38:42 +04:00
TailnetListenPort : uint16 ( tailnetListenPort ),
2025-05-14 14:15:36 +02:00
EnvironmentVariables : environmentVariables ,
IgnorePorts : ignorePorts ,
SSHMaxTimeout : sshMaxTimeout ,
Subsystems : subsystems ,
2023-04-26 13:01:49 -05:00
2026-04-08 10:41:55 -04:00
PrometheusRegistry : prometheusRegistry ,
BlockFileTransfer : blockFileTransfer ,
BlockReversePortForwarding : blockReversePortForwarding ,
BlockLocalPortForwarding : blockLocalPortForwarding ,
Execer : execer ,
Devcontainers : devcontainers ,
2025-06-24 21:17:04 +03:00
DevcontainerAPIOptions : [] agentcontainers . Option {
2025-09-03 10:38:42 +04:00
agentcontainers . WithSubAgentURL ( agentAuth . agentURL . String ()),
2025-07-22 19:02:43 +01:00
agentcontainers . WithProjectDiscovery ( devcontainerProjectDiscovery ),
2025-08-04 16:21:13 +01:00
agentcontainers . WithDiscoveryAutostart ( devcontainerDiscoveryAutostart ),
2025-06-10 12:37:54 +03:00
},
2026-07-20 15:39:21 +02:00
SocketPath : socketPath ,
SocketServerEnabled : socketServerEnabled ,
AgentFirewallLogProxySocketPath : agentFirewallLogProxySocketPath ,
ContextConfig : contextConfig ,
2025-05-14 14:15:36 +02:00
})
2023-05-25 12:52:36 +02:00
2025-11-05 14:22:24 +02:00
if debugAddress != "" {
// ServerHandle depends on `agnt.HTTPDebug()`, but `agnt`
// depends on `ignorePorts`. Keep this if statement in sync
// with above.
debugSrvClose := ServeHandler ( ctx , logger , agnt . HTTPDebug (), debugAddress , "debug" )
serverClose = append ( serverClose , debugSrvClose )
} else {
logger . Debug ( ctx , "debug address is empty, disabling debug server" )
}
2025-05-14 14:15:36 +02:00
select {
case <- ctx . Done ():
logger . Info ( ctx , "agent shutting down" , slog . Error ( context . Cause ( ctx )))
mustExit = true
2026-04-02 23:51:02 +02:00
case event , ok := <- reinitEvents :
switch {
case ! ok :
// Channel closed — the reinit loop exited
// (terminal 409 or context expired). Keep
// running the current agent until the parent
// context is canceled.
logger . Info ( ctx , "reinit channel closed, running without reinit capability" )
reinitEvents = nil
<- ctx . Done ()
mustExit = true
case event . OwnerID != uuid . Nil && event . OwnerID == lastOwnerID :
// Duplicate reinit for same owner — already
// reinitialized. Cancel the reinit loop
// goroutine and keep the current agent.
logger . Info ( ctx , "skipping redundant reinit, owner unchanged" ,
slog . F ( "owner_id" , event . OwnerID ))
reinitCancel ()
reinitEvents = nil
<- ctx . Done ()
mustExit = true
default :
lastOwnerID = event . OwnerID
logger . Info ( ctx , "agent received instruction to reinitialize" ,
slog . F ( "workspace_id" , event . WorkspaceID ), slog . F ( "reason" , event . Reason ))
}
2025-05-14 14:15:36 +02:00
}
lastErr = agnt . Close ()
2025-11-05 14:22:24 +02:00
slices . Reverse ( serverClose )
for _ , closeFunc := range serverClose {
closeFunc ()
}
2025-05-14 14:15:36 +02:00
if mustExit {
break
}
logger . Info ( ctx , "agent reinitializing" )
}
return lastErr
2022-03-07 11:40:54 -06:00
},
}
2022-03-28 14:26:41 -05:00
2024-03-15 11:24:38 -05:00
cmd . Options = serpent . OptionSet {
2023-03-23 17:42:20 -05:00
{
Flag : "log-dir" ,
Default : os . TempDir (),
Description : "Specify the location for the agent log files." ,
Env : "CODER_AGENT_LOG_DIR" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & logDir ),
2023-03-23 17:42:20 -05:00
},
2024-02-20 13:26:18 +02:00
{
Flag : "script-data-dir" ,
Default : os . TempDir (),
Description : "Specify the location for storing script data." ,
Env : "CODER_AGENT_SCRIPT_DATA_DIR" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & scriptDataDir ),
2024-02-20 13:26:18 +02:00
},
2023-03-23 17:42:20 -05:00
{
Flag : "pprof-address" ,
Default : "127.0.0.1:6060" ,
Env : "CODER_AGENT_PPROF_ADDRESS" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & pprofAddress ),
2023-03-23 17:42:20 -05:00
Description : "The address to serve pprof." ,
},
2024-08-29 14:15:15 +10:00
{
Flag : "agent-header-command" ,
Env : "CODER_AGENT_HEADER_COMMAND" ,
Value : serpent . StringOf ( & agentHeaderCommand ),
Description : "An external command that outputs additional HTTP headers added to all requests. The command must output each header as `key=value` on its own line." ,
},
{
Flag : "agent-header" ,
Env : "CODER_AGENT_HEADER" ,
Value : serpent . StringArrayOf ( & agentHeader ),
Description : "Additional HTTP headers added to all requests. Provide as " + `key=value` + ". Can be specified multiple times." ,
},
2023-03-23 17:42:20 -05:00
{
Flag : "no-reap" ,
Env : "" ,
Description : "Do not start a process reaper." ,
2024-03-15 11:24:38 -05:00
Value : serpent . BoolOf ( & noReap ),
2023-03-23 17:42:20 -05:00
},
{
2023-06-16 15:22:18 +02:00
Flag : "ssh-max-timeout" ,
// tcpip.KeepaliveIdleOption = 72h + 1min (forwardTCPSockOpts() in tailnet/conn.go)
Default : "72h" ,
2023-03-23 17:42:20 -05:00
Env : "CODER_AGENT_SSH_MAX_TIMEOUT" ,
2023-06-16 15:22:18 +02:00
Description : "Specify the max timeout for a SSH connection, it is advisable to set it to a minimum of 60s, but no more than 72h." ,
2024-03-15 11:24:38 -05:00
Value : serpent . DurationOf ( & sshMaxTimeout ),
2023-03-23 17:42:20 -05:00
},
2023-04-03 11:20:19 -05:00
{
Flag : "tailnet-listen-port" ,
Default : "0" ,
Env : "CODER_AGENT_TAILNET_LISTEN_PORT" ,
Description : "Specify a static port for Tailscale to use for listening." ,
2024-03-15 11:24:38 -05:00
Value : serpent . Int64Of ( & tailnetListenPort ),
2023-04-03 11:20:19 -05:00
},
2023-04-19 09:09:23 +02:00
{
Flag : "prometheus-address" ,
Default : "127.0.0.1:2112" ,
Env : "CODER_AGENT_PROMETHEUS_ADDRESS" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & prometheusAddress ),
2023-04-19 09:09:23 +02:00
Description : "The bind address to serve Prometheus metrics." ,
},
2023-04-26 13:01:49 -05:00
{
Flag : "debug-address" ,
Default : "127.0.0.1:2113" ,
Env : "CODER_AGENT_DEBUG_ADDRESS" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & debugAddress ),
2023-04-26 13:01:49 -05:00
Description : "The bind address to serve a debug HTTP server." ,
},
2023-05-24 07:32:40 -07:00
{
Name : "Human Log Location" ,
Description : "Output human-readable logs to a given file." ,
Flag : "log-human" ,
Env : "CODER_AGENT_LOGGING_HUMAN" ,
Default : "/dev/stderr" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & slogHumanPath ),
2023-05-24 07:32:40 -07:00
},
{
Name : "JSON Log Location" ,
Description : "Output JSON logs to a given file." ,
Flag : "log-json" ,
Env : "CODER_AGENT_LOGGING_JSON" ,
Default : "" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & slogJSONPath ),
2023-05-24 07:32:40 -07:00
},
{
Name : "Stackdriver Log Location" ,
Description : "Output Stackdriver compatible logs to a given file." ,
Flag : "log-stackdriver" ,
Env : "CODER_AGENT_LOGGING_STACKDRIVER" ,
Default : "" ,
2024-03-15 11:24:38 -05:00
Value : serpent . StringOf ( & slogStackdriverPath ),
2023-05-24 07:32:40 -07:00
},
2024-06-10 14:12:23 +02:00
{
Flag : "block-file-transfer" ,
Default : "false" ,
Env : "CODER_AGENT_BLOCK_FILE_TRANSFER" ,
Description : fmt . Sprintf ( "Block file transfer using known applications: %s." , strings . Join ( agentssh . BlockedFileTransferCommands , "," )),
Value : serpent . BoolOf ( & blockFileTransfer ),
},
2026-04-08 10:41:55 -04:00
{
Flag : "block-reverse-port-forwarding" ,
Default : "false" ,
Env : "CODER_AGENT_BLOCK_REVERSE_PORT_FORWARDING" ,
Description : "Block reverse port forwarding through the SSH server (ssh -R)." ,
Value : serpent . BoolOf ( & blockReversePortForwarding ),
},
{
Flag : "block-local-port-forwarding" ,
Default : "false" ,
Env : "CODER_AGENT_BLOCK_LOCAL_PORT_FORWARDING" ,
Description : "Block local port forwarding through the SSH server (ssh -L)." ,
Value : serpent . BoolOf ( & blockLocalPortForwarding ),
},
2025-02-11 15:29:59 +00:00
{
Flag : "devcontainers-enable" ,
2025-06-24 21:17:04 +03:00
Default : "true" ,
2025-02-11 15:29:59 +00:00
Env : "CODER_AGENT_DEVCONTAINERS_ENABLE" ,
Description : "Allow the agent to automatically detect running devcontainers." ,
2025-06-24 21:17:04 +03:00
Value : serpent . BoolOf ( & devcontainers ),
2025-02-11 15:29:59 +00:00
},
2025-07-22 19:02:43 +01:00
{
Flag : "devcontainers-project-discovery-enable" ,
Default : "true" ,
Env : "CODER_AGENT_DEVCONTAINERS_PROJECT_DISCOVERY_ENABLE" ,
Description : "Allow the agent to search the filesystem for devcontainer projects." ,
Value : serpent . BoolOf ( & devcontainerProjectDiscovery ),
},
2025-08-04 16:21:13 +01:00
{
Flag : "devcontainers-discovery-autostart-enable" ,
Default : "false" ,
Env : "CODER_AGENT_DEVCONTAINERS_DISCOVERY_AUTOSTART_ENABLE" ,
Description : "Allow the agent to autostart devcontainer projects it discovers based on their configuration." ,
Value : serpent . BoolOf ( & devcontainerDiscoveryAutostart ),
},
2025-11-28 08:33:50 +02:00
{
Flag : "socket-server-enabled" ,
2026-03-03 21:23:59 +04:00
Default : "true" ,
2025-11-28 08:33:50 +02:00
Env : "CODER_AGENT_SOCKET_SERVER_ENABLED" ,
Description : "Enable the agent socket server." ,
Value : serpent . BoolOf ( & socketServerEnabled ),
},
{
Flag : "socket-path" ,
Env : "CODER_AGENT_SOCKET_PATH" ,
Description : "Specify the path for the agent socket." ,
Value : serpent . StringOf ( & socketPath ),
},
2025-12-31 16:38:19 -07:00
{
Flag : "boundary-log-proxy-socket-path" ,
Default : boundarylogproxy . DefaultSocketPath (),
Env : "CODER_AGENT_BOUNDARY_LOG_PROXY_SOCKET_PATH" ,
Description : "The path for the boundary log proxy server Unix socket. Boundary should write audit logs to this socket." ,
2026-07-20 15:39:21 +02:00
Value : serpent . StringOf ( & agentFirewallLogProxySocketPath ),
Hidden : true ,
UseInstead : [] serpent . Option {
{
Flag : "agent-firewall-log-proxy-socket-path" ,
Env : "CODER_AGENT_FIREWALL_LOG_PROXY_SOCKET_PATH" ,
},
},
},
{
Flag : "agent-firewall-log-proxy-socket-path" ,
Default : boundarylogproxy . DefaultSocketPath (),
Env : "CODER_AGENT_FIREWALL_LOG_PROXY_SOCKET_PATH" ,
Description : "The path for the agent firewall log proxy server Unix socket. Agent firewall should write audit logs to this socket." ,
Value : serpent . StringOf ( & agentFirewallLogProxySocketPath ),
2025-12-31 16:38:19 -07:00
},
2023-03-23 17:42:20 -05:00
}
2025-09-03 10:38:42 +04:00
agentAuth . AttachOptions ( cmd , false )
2022-03-25 13:48:08 -06:00
return cmd
2022-03-07 11:40:54 -06:00
}
2023-01-17 10:58:00 -06:00
2023-04-13 09:07:19 -05:00
func ServeHandler ( ctx context . Context , logger slog . Logger , handler http . Handler , addr , name string ) ( closeFunc func ()) {
2023-01-17 10:58:00 -06:00
// ReadHeaderTimeout is purposefully not enabled. It caused some issues with
// websockets over the dev tunnel.
// See: https://github.com/coder/coder/pull/3730
//nolint:gosec
srv := & http . Server {
Addr : addr ,
Handler : handler ,
}
go func () {
2025-04-09 09:20:47 +01:00
ln , err := net . Listen ( "tcp" , addr )
if err != nil {
logger . Error ( ctx , "http server listen" , slog . F ( "name" , name ), slog . F ( "addr" , addr ), slog . Error ( err ))
return
}
defer ln . Close ()
logger . Info ( ctx , "http server listening" , slog . F ( "addr" , ln . Addr ()), slog . F ( "name" , name ))
if err := srv . Serve ( ln ); err != nil && ! xerrors . Is ( err , http . ErrServerClosed ) {
logger . Error ( ctx , "http server serve" , slog . F ( "addr" , ln . Addr ()), slog . F ( "name" , name ), slog . Error ( err ))
2023-01-17 10:58:00 -06:00
}
}()
return func () {
_ = srv . Close ()
}
}
2023-02-01 16:04:09 +02:00
2023-03-09 10:53:00 -06:00
// extractPort handles different url strings.
// - localhost:6060
// - http://localhost:6060
func extractPort ( u string ) ( int , error ) {
port , firstError := urlPort ( u )
if firstError == nil {
return port , nil
}
// Try with a scheme
port , err := urlPort ( "http://" + u )
if err == nil {
return port , nil
}
return - 1 , xerrors . Errorf ( "invalid url %q: %w" , u , firstError )
}
// urlPort extracts the port from a valid URL.
func urlPort ( u string ) ( int , error ) {
parsed , err := url . Parse ( u )
if err != nil {
return - 1 , xerrors . Errorf ( "invalid url %q: %w" , u , err )
}
if parsed . Port () != "" {
2023-04-06 07:43:24 +10:00
port , err := strconv . ParseUint ( parsed . Port (), 10 , 16 )
if err == nil && port > 0 && port < 1 << 16 {
2023-03-09 10:53:00 -06:00
return int ( port ), nil
}
}
return - 1 , xerrors . Errorf ( "invalid port: %s" , u )
}
2026-02-05 12:32:07 -06:00
// logSignalNotifyContext is like signal.NotifyContext but logs the received
// signal before canceling the context.
func logSignalNotifyContext ( parent context . Context , logger slog . Logger , signals ... os . Signal ) ( context . Context , context . CancelFunc ) {
ctx , cancel := context . WithCancelCause ( parent )
c := make ( chan os . Signal , 1 )
signal . Notify ( c , signals ... )
go func () {
select {
case sig := <- c :
logger . Info ( ctx , "agent received signal" , slog . F ( "signal" , sig . String ()))
cancel ( xerrors . Errorf ( "signal: %s" , sig . String ()))
case <- ctx . Done ():
logger . Info ( ctx , "ctx canceled, stopping signal handler" )
}
}()
return ctx , func () {
cancel ( context . Canceled )
signal . Stop ( c )
}
}