2023-04-17 14:57:21 -05:00
package wsproxy
import (
"context"
2023-07-26 09:21:04 -07:00
"crypto/tls"
2024-01-11 16:55:34 -06:00
"errors"
2023-04-24 10:25:35 -05:00
"fmt"
2023-04-17 14:57:21 -05:00
"net/http"
"net/url"
"reflect"
"regexp"
2024-03-07 22:31:40 -08:00
"slices"
2023-04-17 14:57:21 -05:00
"strings"
2024-03-07 22:31:40 -08:00
"sync"
2023-04-17 14:57:21 -05:00
"time"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
2023-07-26 09:21:04 -07:00
"github.com/hashicorp/go-multierror"
2023-04-17 14:57:21 -05:00
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/trace"
2024-03-07 22:31:40 -08:00
"golang.org/x/sync/singleflight"
2023-04-17 14:57:21 -05:00
"golang.org/x/xerrors"
2023-07-26 09:21:04 -07:00
"tailscale.com/derp"
"tailscale.com/derp/derphttp"
"tailscale.com/types/key"
2023-04-17 14:57:21 -05:00
"cdr.dev/slog"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/buildinfo"
2023-12-07 16:59:13 +00:00
"github.com/coder/coder/v2/cli/cliutil"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd"
2024-10-25 17:14:35 +01:00
"github.com/coder/coder/v2/coderd/cryptokeys"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/httpmw"
2025-04-15 13:27:23 +02:00
"github.com/coder/coder/v2/coderd/httpmw/loggermw"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/coderd/tracing"
"github.com/coder/coder/v2/coderd/workspaceapps"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/enterprise/derpmesh"
2024-03-07 22:31:40 -08:00
"github.com/coder/coder/v2/enterprise/replicasync"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/enterprise/wsproxy/wsproxysdk"
"github.com/coder/coder/v2/site"
"github.com/coder/coder/v2/tailnet"
2023-04-17 14:57:21 -05:00
)
type Options struct {
2023-07-19 11:11:11 -05:00
Logger slog . Logger
Experiments codersdk . Experiments
2023-04-17 14:57:21 -05:00
2023-04-24 10:25:35 -05:00
HTTPClient * http . Client
2023-04-17 14:57:21 -05:00
// DashboardURL is the URL of the primary coderd instance.
DashboardURL * url . URL
2023-04-20 09:48:47 -05:00
// AccessURL is the URL of the WorkspaceProxy.
2023-04-17 14:57:21 -05:00
AccessURL * url . URL
// TODO: @emyrk We use these two fields in many places with this comment.
// Maybe we should make some shared options struct?
// AppHostname should be the wildcard hostname to use for workspace
// applications INCLUDING the asterisk, (optional) suffix and leading dot.
// It will use the same scheme and port number as the access URL.
// E.g. "*.apps.coder.com" or "*-apps.coder.com".
AppHostname string
// AppHostnameRegex contains the regex version of options.AppHostname as
2024-01-17 10:41:42 -06:00
// generated by appurl.CompileHostnamePattern(). It MUST be set if
2023-04-17 14:57:21 -05:00
// options.AppHostname is set.
AppHostnameRegex * regexp . Regexp
2023-07-26 09:21:04 -07:00
RealIPConfig * httpmw . RealIPConfig
2023-04-17 14:57:21 -05:00
Tracing trace . TracerProvider
PrometheusRegistry * prometheus . Registry
2023-07-26 09:21:04 -07:00
TLSCertificates [] tls . Certificate
2023-04-17 14:57:21 -05:00
2023-07-26 09:21:04 -07:00
APIRateLimit int
2025-04-08 14:15:14 -05:00
CookieConfig codersdk . HTTPCookieConfig
2023-07-26 09:21:04 -07:00
DisablePathApps bool
DERPEnabled bool
DERPServerRelayAddress string
2023-08-02 07:35:06 -07:00
// DERPOnly determines whether this proxy only provides DERP and does not
// provide access to workspace apps/terminal.
DERPOnly bool
2024-03-07 23:45:59 -06:00
// BlockDirect controls the servertailnet of the proxy, forcing it from
// negotiating direct connections.
BlockDirect bool
2023-04-17 14:57:21 -05:00
2024-03-07 22:31:40 -08:00
// ReplicaErrCallback is called when the proxy replica successfully or
// unsuccessfully pings its peers in the mesh.
ReplicaErrCallback func ( replicas [] codersdk . Replica , err string )
2023-04-17 14:57:21 -05:00
ProxySessionToken string
2023-05-22 20:02:39 +02:00
// AllowAllCors will set all CORs headers to '*'.
// By default, CORs is set to accept external requests
// from the dashboardURL. This should only be used in development.
AllowAllCors bool
2023-08-16 15:22:00 +03:00
StatsCollectorOptions workspaceapps . StatsCollectorOptions
2023-04-17 14:57:21 -05:00
}
func ( o * Options ) Validate () error {
var errs optErrors
errs . Required ( "Logger" , o . Logger )
errs . Required ( "DashboardURL" , o . DashboardURL )
errs . Required ( "AccessURL" , o . AccessURL )
errs . Required ( "RealIPConfig" , o . RealIPConfig )
errs . Required ( "PrometheusRegistry" , o . PrometheusRegistry )
errs . NotEmpty ( "ProxySessionToken" , o . ProxySessionToken )
if len ( errs ) > 0 {
return errs
}
return nil
}
// Server is an external workspace proxy server. This server can communicate
// directly with a workspace. It requires a primary coderd to establish a said
// connection.
type Server struct {
Options * Options
Handler chi . Router
DashboardURL * url . URL
AppServer * workspaceapps . Server
// Logging/Metrics
Logger slog . Logger
TracerProvider trace . TracerProvider
PrometheusRegistry * prometheus . Registry
// SDKClient is a client to the primary coderd instance authenticated with
// the moon's token.
SDKClient * wsproxysdk . Client
2024-10-25 17:14:35 +01:00
// apiKeyEncryptionKeycache manages the encryption keys for smuggling API
// tokens to the alternate domain when using workspace apps.
apiKeyEncryptionKeycache cryptokeys . EncryptionKeycache
// appTokenSigningKeycache manages the signing keys for signing the app
// tokens we use for workspace apps.
appTokenSigningKeycache cryptokeys . SigningKeycache
2023-07-26 09:21:04 -07:00
// DERP
2024-03-07 22:31:40 -08:00
derpMesh * derpmesh . Mesh
derpMeshTLSConfig * tls . Config
replicaPingSingleflight singleflight . Group
replicaErrMut sync . Mutex
replicaErr string
2023-04-17 14:57:21 -05:00
// Used for graceful shutdown. Required for the dialer.
2023-07-26 09:21:04 -07:00
ctx context . Context
cancel context . CancelFunc
derpCloseFunc func ()
2024-03-04 23:40:15 -08:00
registerLoop * wsproxysdk . RegisterWorkspaceProxyLoop
2023-04-17 14:57:21 -05:00
}
2023-04-20 09:48:47 -05:00
// New creates a new workspace proxy server. This requires a primary coderd
// instance to be reachable and the correct authorization access token to be
// provided. If the proxy cannot authenticate with the primary, this will fail.
func New ( ctx context . Context , opts * Options ) ( * Server , error ) {
2023-04-17 14:57:21 -05:00
if opts . PrometheusRegistry == nil {
opts . PrometheusRegistry = prometheus . NewRegistry ()
}
if err := opts . Validate (); err != nil {
return nil , err
}
client := wsproxysdk . New ( opts . DashboardURL )
err := client . SetSessionToken ( opts . ProxySessionToken )
if err != nil {
return nil , xerrors . Errorf ( "set client token: %w" , err )
}
2023-04-24 10:25:35 -05:00
// Use the configured client if provided.
if opts . HTTPClient != nil {
client . SDKClient . HTTPClient = opts . HTTPClient
}
2023-04-20 09:48:47 -05:00
info , err := client . SDKClient . BuildInfo ( ctx )
if err != nil {
2024-01-22 11:07:50 +04:00
return nil , xerrors . Errorf ( "buildinfo: %w" , errors . Join (
2024-01-19 16:04:19 -07:00
xerrors . Errorf ( "unable to fetch build info from primary coderd. Are you sure %q is a coderd instance?" , opts . DashboardURL ),
2024-01-11 16:55:34 -06:00
err ,
))
2023-04-20 09:48:47 -05:00
}
if info . WorkspaceProxy {
return nil , xerrors . Errorf ( "%q is a workspace proxy, not a primary coderd instance" , opts . DashboardURL )
}
2024-03-20 11:24:18 -07:00
// We don't want to crash the proxy if the versions don't match because
// it'll enter crash loop backoff (and most patches don't make any backwards
// incompatible changes to the proxy API anyways)
if ! buildinfo . VersionsMatch ( info . Version , buildinfo . Version ()) {
opts . Logger . Warn ( ctx , "workspace proxy version doesn't match Minor.Major version of the primary, please keep them in sync" ,
slog . F ( "primary_version" , info . Version ),
slog . F ( "proxy_version" , buildinfo . Version ()),
)
}
2023-04-20 09:48:47 -05:00
2024-03-07 22:31:40 -08:00
meshTLSConfig , err := replicasync . CreateDERPMeshTLSConfig ( opts . AccessURL . Hostname (), opts . TLSCertificates )
if err != nil {
return nil , xerrors . Errorf ( "create DERP mesh tls config: %w" , err )
2023-07-26 09:21:04 -07:00
}
2023-07-26 16:46:22 -05:00
derpServer := derp . NewServer ( key . NewNode (), tailnet . Logger ( opts . Logger . Named ( "net.derp" )))
2023-04-20 09:48:47 -05:00
2023-04-17 14:57:21 -05:00
ctx , cancel := context . WithCancel ( context . Background ())
2024-10-25 17:14:35 +01:00
encryptionCache , err := cryptokeys . NewEncryptionCache ( ctx ,
opts . Logger ,
& ProxyFetcher { Client : client },
codersdk . CryptoKeyFeatureWorkspaceAppsAPIKey ,
)
if err != nil {
cancel ()
return nil , xerrors . Errorf ( "create api key encryption cache: %w" , err )
}
signingCache , err := cryptokeys . NewSigningCache ( ctx ,
opts . Logger ,
& ProxyFetcher { Client : client },
codersdk . CryptoKeyFeatureWorkspaceAppsToken ,
)
if err != nil {
cancel ()
return nil , xerrors . Errorf ( "create api token signing cache: %w" , err )
}
2023-07-26 09:21:04 -07:00
r := chi . NewRouter ()
2023-04-17 14:57:21 -05:00
s := & Server {
2024-10-25 17:14:35 +01:00
ctx : ctx ,
cancel : cancel ,
Options : opts ,
Handler : r ,
DashboardURL : opts . DashboardURL ,
Logger : opts . Logger . Named ( "net.workspace-proxy" ),
TracerProvider : opts . Tracing ,
PrometheusRegistry : opts . PrometheusRegistry ,
SDKClient : client ,
derpMesh : derpmesh . New ( opts . Logger . Named ( "net.derpmesh" ), derpServer , meshTLSConfig ),
derpMeshTLSConfig : meshTLSConfig ,
apiKeyEncryptionKeycache : encryptionCache ,
appTokenSigningKeycache : signingCache ,
2023-04-17 14:57:21 -05:00
}
2023-07-26 09:21:04 -07:00
// Register the workspace proxy with the primary coderd instance and start a
// goroutine to periodically re-register.
2024-03-04 23:40:15 -08:00
registerLoop , regResp , err := client . RegisterWorkspaceProxyLoop ( ctx , wsproxysdk . RegisterWorkspaceProxyLoopOpts {
2023-07-26 09:21:04 -07:00
Logger : opts . Logger ,
Request : wsproxysdk . RegisterWorkspaceProxyRequest {
AccessURL : opts . AccessURL . String (),
WildcardHostname : opts . AppHostname ,
DerpEnabled : opts . DERPEnabled ,
2023-08-02 07:35:06 -07:00
DerpOnly : opts . DERPOnly ,
2024-03-07 22:31:40 -08:00
ReplicaID : uuid . New (),
ReplicaHostname : cliutil . Hostname (),
2023-07-26 09:21:04 -07:00
ReplicaError : "" ,
ReplicaRelayAddress : opts . DERPServerRelayAddress ,
Version : buildinfo . Version (),
},
MutateFn : s . mutateRegister ,
CallbackFn : s . handleRegister ,
FailureFn : s . handleRegisterFailure ,
})
if err != nil {
return nil , xerrors . Errorf ( "register proxy: %w" , err )
}
2024-03-04 23:40:15 -08:00
s . registerLoop = registerLoop
derpServer . SetMeshKey ( regResp . DERPMeshKey )
err = s . handleRegister ( regResp )
2023-07-26 09:21:04 -07:00
if err != nil {
return nil , xerrors . Errorf ( "handle register: %w" , err )
}
2024-11-08 13:18:56 +04:00
dialer , err := s . SDKClient . TailnetDialer ()
if err != nil {
return nil , xerrors . Errorf ( "create tailnet dialer: %w" , err )
}
2024-01-04 09:27:36 +04:00
agentProvider , err := coderd . NewServerTailnet ( ctx ,
s . Logger ,
nil ,
2024-11-08 13:18:56 +04:00
dialer ,
2024-01-04 09:27:36 +04:00
regResp . DERPForceWebSockets ,
2024-03-07 23:45:59 -06:00
opts . BlockDirect ,
2024-01-04 09:27:36 +04:00
s . TracerProvider ,
)
if err != nil {
return nil , xerrors . Errorf ( "create server tailnet: %w" , err )
2023-07-19 11:11:11 -05:00
}
2023-08-16 15:22:00 +03:00
workspaceAppsLogger := opts . Logger . Named ( "workspaceapps" )
if opts . StatsCollectorOptions . Logger == nil {
named := workspaceAppsLogger . Named ( "stats_collector" )
opts . StatsCollectorOptions . Logger = & named
}
if opts . StatsCollectorOptions . Reporter == nil {
opts . StatsCollectorOptions . Reporter = & appStatsReporter { Client : client }
}
2023-04-17 14:57:21 -05:00
s . AppServer = & workspaceapps . Server {
2023-08-16 15:22:00 +03:00
Logger : workspaceAppsLogger ,
2023-04-17 14:57:21 -05:00
DashboardURL : opts . DashboardURL ,
AccessURL : opts . AccessURL ,
Hostname : opts . AppHostname ,
HostnameRegex : opts . AppHostnameRegex ,
RealIPConfig : opts . RealIPConfig ,
SignedTokenProvider : & TokenProvider {
2024-10-25 17:14:35 +01:00
DashboardURL : opts . DashboardURL ,
AccessURL : opts . AccessURL ,
AppHostname : opts . AppHostname ,
Client : client ,
TokenSigningKeycache : signingCache ,
APIKeyEncryptionKeycache : encryptionCache ,
Logger : s . Logger . Named ( "proxy_token_provider" ),
2023-04-17 14:57:21 -05:00
},
2025-04-08 14:15:14 -05:00
DisablePathApps : opts . DisablePathApps ,
Cookies : opts . CookieConfig ,
2023-08-16 15:22:00 +03:00
2024-10-25 17:14:35 +01:00
AgentProvider : agentProvider ,
StatsCollector : workspaceapps . NewStatsCollector ( opts . StatsCollectorOptions ),
APIKeyEncryptionKeycache : encryptionCache ,
2023-04-17 14:57:21 -05:00
}
2023-07-26 09:21:04 -07:00
derpHandler := derphttp . Handler ( derpServer )
derpHandler , s . derpCloseFunc = tailnet . WithWebsocketSupport ( derpServer , derpHandler )
2023-05-11 15:42:30 -05:00
// The primary coderd dashboard needs to make some GET requests to
// the workspace proxies to check latency.
2023-05-22 20:02:39 +02:00
corsMW := httpmw . Cors ( opts . AllowAllCors , opts . DashboardURL . String ())
2023-06-06 10:26:13 -05:00
prometheusMW := httpmw . Prometheus ( s . PrometheusRegistry )
2023-05-11 15:42:30 -05:00
2023-04-17 14:57:21 -05:00
// Routes
apiRateLimiter := httpmw . RateLimit ( opts . APIRateLimit , time . Minute )
// Persistent middlewares to all routes
r . Use (
// TODO: @emyrk Should we standardize these in some other package?
httpmw . Recover ( s . Logger ),
2025-08-07 11:21:17 -05:00
httpmw . WithProfilingLabels ,
2023-04-17 14:57:21 -05:00
tracing . StatusWriterMiddleware ,
tracing . Middleware ( s . TracerProvider ),
httpmw . AttachRequestID ,
httpmw . ExtractRealIP ( s . Options . RealIPConfig ),
2025-04-15 13:27:23 +02:00
loggermw . Logger ( s . Logger ),
2023-06-06 10:26:13 -05:00
prometheusMW ,
2023-04-17 14:57:21 -05:00
// HandleSubdomain is a middleware that handles all requests to the
// subdomain-based workspace apps.
s . AppServer . HandleSubdomain ( apiRateLimiter ),
2025-07-30 13:42:39 -07:00
corsMW ,
2023-04-17 14:57:21 -05:00
// Build-Version is helpful for debugging.
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
2024-01-03 09:01:57 +00:00
w . Header (). Add ( codersdk . BuildVersionHeader , buildinfo . Version ())
2023-04-17 14:57:21 -05:00
next . ServeHTTP ( w , r )
})
},
// This header stops a browser from trying to MIME-sniff the content type and
// forces it to stick with the declared content-type. This is the only valid
// value for this header.
// See: https://github.com/coder/security/issues/12
func ( next http . Handler ) http . Handler {
return http . HandlerFunc ( func ( w http . ResponseWriter , r * http . Request ) {
w . Header (). Add ( "X-Content-Type-Options" , "nosniff" )
next . ServeHTTP ( w , r )
})
},
2024-01-08 16:33:57 -06:00
// CSRF is required here because we need to set the CSRF cookies on
// responses.
2025-04-08 14:15:14 -05:00
httpmw . CSRF ( s . Options . CookieConfig ),
2023-04-17 14:57:21 -05:00
)
// Attach workspace apps routes.
2023-08-02 07:35:06 -07:00
if ! opts . DERPOnly {
r . Group ( func ( r chi . Router ) {
r . Use ( apiRateLimiter )
s . AppServer . Attach ( r )
2023-07-26 09:21:04 -07:00
})
2023-08-02 07:35:06 -07:00
} else {
r . Group ( func ( r chi . Router ) {
derpOnlyHandler := func ( rw http . ResponseWriter , r * http . Request ) {
site . RenderStaticErrorPage ( rw , r , site . ErrorPageData {
Title : "Head to the Dashboard" ,
Status : http . StatusBadRequest ,
HideStatus : true ,
Description : "This workspace proxy is DERP-only and cannot be used for browser connections. " +
"Please use a different region directly from the dashboard. Click to be redirected!" ,
RetryEnabled : false ,
DashboardURL : opts . DashboardURL . String (),
})
}
serveDerpOnlyHandler := func ( r chi . Router ) {
r . HandleFunc ( "/*" , derpOnlyHandler )
}
r . Route ( "/%40{user}/{workspace_and_agent}/apps/{workspaceapp}" , serveDerpOnlyHandler )
r . Route ( "/@{user}/{workspace_and_agent}/apps/{workspaceapp}" , serveDerpOnlyHandler )
r . Get ( "/api/v2/workspaceagents/{workspaceagent}/pty" , derpOnlyHandler )
})
}
if opts . DERPEnabled {
r . Route ( "/derp" , func ( r chi . Router ) {
r . Get ( "/" , derpHandler . ServeHTTP )
// This is used when UDP is blocked, and latency must be checked via HTTP(s).
2025-03-26 01:56:39 -05:00
r . Get ( "/latency-check" , func ( w http . ResponseWriter , _ * http . Request ) {
2023-08-02 07:35:06 -07:00
w . WriteHeader ( http . StatusOK )
})
})
} else {
r . Route ( "/derp" , func ( r chi . Router ) {
2025-03-26 01:56:39 -05:00
r . HandleFunc ( "/*" , func ( rw http . ResponseWriter , _ * http . Request ) {
2023-08-02 07:35:06 -07:00
httpapi . Write ( ctx , rw , http . StatusBadRequest , codersdk . Response {
Message : "DERP is disabled on this proxy." ,
})
})
})
}
2023-07-26 09:21:04 -07:00
2023-05-01 15:02:51 -07:00
r . Get ( "/api/v2/buildinfo" , s . buildInfo )
2025-03-26 01:56:39 -05:00
r . Get ( "/healthz" , func ( w http . ResponseWriter , _ * http . Request ) { _ , _ = w . Write ([] byte ( "OK" )) })
2023-04-24 10:25:35 -05:00
// TODO: @emyrk should this be authenticated or debounced?
r . Get ( "/healthz-report" , s . healthReport )
2023-05-01 13:58:36 -05:00
r . NotFound ( func ( rw http . ResponseWriter , r * http . Request ) {
site . RenderStaticErrorPage ( rw , r , site . ErrorPageData {
2023-05-05 13:53:19 -05:00
Title : "Head to the Dashboard" ,
Status : http . StatusBadRequest ,
HideStatus : true ,
Description : "Workspace Proxies route traffic in terminals and apps directly to your workspace. " +
"This page must be loaded from the dashboard. Click to be redirected!" ,
2023-05-01 13:58:36 -05:00
RetryEnabled : false ,
DashboardURL : opts . DashboardURL . String (),
})
})
2023-04-17 14:57:21 -05:00
2023-05-11 15:42:30 -05:00
// See coderd/coderd.go for why we need this.
rootRouter := chi . NewRouter ()
// Make sure to add the cors middleware to the latency check route.
2023-06-06 10:26:13 -05:00
rootRouter . Get ( "/latency-check" , tracing . StatusWriterMiddleware ( prometheusMW ( coderd . LatencyCheck ())). ServeHTTP )
2023-05-11 15:42:30 -05:00
rootRouter . Mount ( "/" , r )
s . Handler = rootRouter
2023-04-17 14:57:21 -05:00
return s , nil
}
2024-03-04 23:40:15 -08:00
func ( s * Server ) RegisterNow () error {
_ , err := s . registerLoop . RegisterNow ()
return err
}
2023-04-17 14:57:21 -05:00
func ( s * Server ) Close () error {
2024-10-23 10:09:56 +04:00
s . Logger . Info ( s . ctx , "closing workspace proxy server" )
defer s . Logger . Debug ( s . ctx , "finished closing workspace proxy server" )
2023-04-17 14:57:21 -05:00
s . cancel ()
2023-05-10 19:23:16 -05:00
2023-07-26 09:21:04 -07:00
var err error
2024-03-04 23:40:15 -08:00
s . registerLoop . Close ()
2023-07-26 09:21:04 -07:00
s . derpCloseFunc ()
appServerErr := s . AppServer . Close ()
if appServerErr != nil {
err = multierror . Append ( err , appServerErr )
}
agentProviderErr := s . AppServer . AgentProvider . Close ()
if agentProviderErr != nil {
err = multierror . Append ( err , agentProviderErr )
}
s . SDKClient . SDKClient . HTTPClient . CloseIdleConnections ()
2024-10-25 17:14:35 +01:00
_ = s . appTokenSigningKeycache . Close ()
_ = s . apiKeyEncryptionKeycache . Close ()
2023-07-26 09:21:04 -07:00
return err
2023-04-17 14:57:21 -05:00
}
2024-03-07 22:31:40 -08:00
func ( s * Server ) mutateRegister ( req * wsproxysdk . RegisterWorkspaceProxyRequest ) {
s . replicaErrMut . Lock ()
defer s . replicaErrMut . Unlock ()
req . ReplicaError = s . replicaErr
2023-07-26 09:21:04 -07:00
}
2024-03-04 23:40:15 -08:00
func ( s * Server ) handleRegister ( res wsproxysdk . RegisterWorkspaceProxyResponse ) error {
2023-07-26 09:21:04 -07:00
addresses := make ([] string , len ( res . SiblingReplicas ))
for i , replica := range res . SiblingReplicas {
addresses [ i ] = replica . RelayAddress
}
2024-03-04 23:40:15 -08:00
s . Logger . Debug ( s . ctx , "setting DERP mesh sibling addresses" , slog . F ( "addresses" , addresses ))
2023-07-26 09:21:04 -07:00
s . derpMesh . SetAddresses ( addresses , false )
2024-03-07 22:31:40 -08:00
go s . pingSiblingReplicas ( res . SiblingReplicas )
2023-07-26 09:21:04 -07:00
return nil
}
2024-03-07 22:31:40 -08:00
func ( s * Server ) pingSiblingReplicas ( replicas [] codersdk . Replica ) {
2024-03-18 06:45:25 -07:00
ctx , cancel := context . WithTimeout ( s . ctx , 10 * time . Second )
defer cancel ()
errStr := pingSiblingReplicas ( ctx , s . Logger , & s . replicaPingSingleflight , s . derpMeshTLSConfig , replicas )
s . replicaErrMut . Lock ()
s . replicaErr = errStr
2024-08-05 14:30:44 -04:00
defer s . replicaErrMut . Unlock ()
2024-03-18 06:45:25 -07:00
if s . Options . ReplicaErrCallback != nil {
s . Options . ReplicaErrCallback ( replicas , s . replicaErr )
}
}
func pingSiblingReplicas ( ctx context . Context , logger slog . Logger , sf * singleflight . Group , derpMeshTLSConfig * tls . Config , replicas [] codersdk . Replica ) string {
2024-03-07 22:31:40 -08:00
if len ( replicas ) == 0 {
2024-03-18 06:45:25 -07:00
return ""
2024-03-07 22:31:40 -08:00
}
// Avoid pinging multiple times at once if the list hasn't changed.
relayURLs := make ([] string , len ( replicas ))
for i , r := range replicas {
relayURLs [ i ] = r . RelayAddress
}
slices . Sort ( relayURLs )
singleflightStr := strings . Join ( relayURLs , " " ) // URLs can't contain spaces.
//nolint:dogsled
2024-03-18 06:45:25 -07:00
errStrInterface , _ , _ := sf . Do ( singleflightStr , func () ( any , error ) {
2024-03-07 22:31:40 -08:00
client := http . Client {
2024-03-18 06:45:25 -07:00
Timeout : 3 * time . Second ,
2024-03-07 22:31:40 -08:00
Transport : & http . Transport {
2024-03-18 06:45:25 -07:00
TLSClientConfig : derpMeshTLSConfig ,
2024-03-07 22:31:40 -08:00
DisableKeepAlives : true ,
},
}
defer client . CloseIdleConnections ()
errs := make ( chan error , len ( replicas ))
for _ , peer := range replicas {
go func ( peer codersdk . Replica ) {
err := replicasync . PingPeerReplica ( ctx , client , peer . RelayAddress )
if err != nil {
errs <- xerrors . Errorf ( "ping sibling replica %s (%s): %w" , peer . Hostname , peer . RelayAddress , err )
2024-03-18 06:45:25 -07:00
logger . Warn ( ctx , "failed to ping sibling replica, this could happen if the replica has shutdown" ,
2024-03-07 22:31:40 -08:00
slog . F ( "replica_hostname" , peer . Hostname ),
slog . F ( "replica_relay_address" , peer . RelayAddress ),
slog . Error ( err ),
)
return
}
errs <- nil
}( peer )
}
replicaErrs := make ([] string , 0 , len ( replicas ))
for i := 0 ; i < len ( replicas ); i ++ {
err := <- errs
if err != nil {
replicaErrs = append ( replicaErrs , err . Error ())
}
}
2024-03-18 06:45:25 -07:00
if len ( replicaErrs ) == 0 {
return "" , nil
2024-03-07 22:31:40 -08:00
}
2024-03-18 06:45:25 -07:00
return fmt . Sprintf ( "Failed to dial peers: %s" , strings . Join ( replicaErrs , ", " )), nil
2024-03-07 22:31:40 -08:00
})
2024-03-18 06:45:25 -07:00
//nolint:forcetypeassert
return errStrInterface .( string )
2024-03-07 22:31:40 -08:00
}
2023-07-26 09:21:04 -07:00
func ( s * Server ) handleRegisterFailure ( err error ) {
if s . ctx . Err () != nil {
return
}
s . Logger . Fatal ( s . ctx ,
"failed to periodically re-register workspace proxy with primary Coder deployment" ,
slog . Error ( err ),
)
}
2023-04-17 14:57:21 -05:00
func ( s * Server ) buildInfo ( rw http . ResponseWriter , r * http . Request ) {
httpapi . Write ( r . Context (), rw , http . StatusOK , codersdk . BuildInfoResponse {
2023-12-08 12:50:25 +04:00
ExternalURL : buildinfo . ExternalURL (),
Version : buildinfo . Version (),
AgentAPIVersion : coderd . AgentAPIVersionREST ,
DashboardURL : s . DashboardURL . String (),
WorkspaceProxy : true ,
2023-04-17 14:57:21 -05:00
})
}
2023-04-24 10:25:35 -05:00
// healthReport is a more thorough health check than the '/healthz' endpoint.
// This endpoint not only responds if the server is running, but can do some
// internal diagnostics to ensure that the server is running correctly. The
// primary coderd will use this to determine if this workspace proxy can be used
// by the users. This endpoint will take longer to respond than the '/healthz'.
// Checks:
// - Can communicate with primary coderd
//
// TODO: Config checks to ensure consistent with primary
func ( s * Server ) healthReport ( rw http . ResponseWriter , r * http . Request ) {
ctx := r . Context ()
var report codersdk . ProxyHealthReport
2023-05-10 19:23:16 -05:00
// This is to catch edge cases where the server is shutting down, but might
// still serve a web request that returns "healthy". This is mainly just for
// unit tests, as shutting down the test webserver is tied to the lifecycle
// of the test. In practice, the webserver is tied to the lifecycle of the
// app, so the webserver AND the proxy will be shut down at the same time.
if s . ctx . Err () != nil {
httpapi . Write ( r . Context (), rw , http . StatusInternalServerError , "workspace proxy in middle of shutting down" )
return
}
2023-04-24 10:25:35 -05:00
// Hit the build info to do basic version checking.
primaryBuild , err := s . SDKClient . SDKClient . BuildInfo ( ctx )
if err != nil {
report . Errors = append ( report . Errors , fmt . Sprintf ( "failed to get build info: %s" , err . Error ()))
httpapi . Write ( r . Context (), rw , http . StatusOK , report )
return
}
if primaryBuild . WorkspaceProxy {
// This could be a simple mistake of using a proxy url as the dashboard url.
report . Errors = append ( report . Errors ,
fmt . Sprintf ( "dashboard url (%s) is a workspace proxy, must be a primary coderd" , s . DashboardURL . String ()))
}
// If we are in dev mode, never check versions.
if ! buildinfo . IsDev () && ! buildinfo . VersionsMatch ( primaryBuild . Version , buildinfo . Version ()) {
// Version mismatches are not fatal, but should be reported.
report . Warnings = append ( report . Warnings ,
fmt . Sprintf ( "version mismatch: primary coderd (%s) != workspace proxy (%s)" , primaryBuild . Version , buildinfo . Version ()))
}
2024-03-07 22:31:40 -08:00
s . replicaErrMut . Lock ()
if s . replicaErr != "" {
2024-03-18 06:45:25 -07:00
report . Warnings = append ( report . Warnings ,
"High availability networking: it appears you are running more than one replica of the proxy, but the replicas are unable to establish a mesh for networking: " + s . replicaErr )
2024-03-07 22:31:40 -08:00
}
s . replicaErrMut . Unlock ()
2023-04-24 10:25:35 -05:00
// TODO: We should hit the deployment config endpoint and do some config
2024-03-07 22:31:40 -08:00
// checks.
2023-04-24 10:25:35 -05:00
httpapi . Write ( r . Context (), rw , http . StatusOK , report )
}
2023-04-17 14:57:21 -05:00
type optErrors [] error
func ( e optErrors ) Error () string {
var b strings . Builder
for _ , err := range e {
_ , _ = b . WriteString ( err . Error ())
_ , _ = b . WriteString ( "\n" )
}
return b . String ()
}
func ( e * optErrors ) Required ( name string , v any ) {
if v == nil {
* e = append ( * e , xerrors . Errorf ( "%s is required, got <nil>" , name ))
}
}
func ( e * optErrors ) NotEmpty ( name string , v any ) {
if reflect . ValueOf ( v ). IsZero () {
* e = append ( * e , xerrors . Errorf ( "%s is required, got the zero value" , name ))
}
}