2025-07-15 14:36:06 +10:00
|
|
|
package agentapi
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"database/sql"
|
|
|
|
|
"sync/atomic"
|
|
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"golang.org/x/xerrors"
|
|
|
|
|
"google.golang.org/protobuf/types/known/emptypb"
|
|
|
|
|
|
2026-01-08 10:29:41 +04:00
|
|
|
"cdr.dev/slog/v3"
|
2025-07-15 14:36:06 +10:00
|
|
|
agentproto "github.com/coder/coder/v2/agent/proto"
|
|
|
|
|
"github.com/coder/coder/v2/coderd/connectionlog"
|
|
|
|
|
"github.com/coder/coder/v2/coderd/database"
|
|
|
|
|
"github.com/coder/coder/v2/coderd/database/db2sdk"
|
2026-10-12 15:56:40 +03:00
|
|
|
"github.com/coder/coder/v2/coderd/database/sdk2db"
|
2026-09-27 23:38:36 -07:00
|
|
|
"github.com/coder/coder/v2/coderd/tracing"
|
2026-10-19 23:06:41 +03:00
|
|
|
"github.com/coder/coder/v2/codersdk"
|
2025-07-15 14:36:06 +10:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type ConnLogAPI struct {
|
2026-10-19 23:06:41 +03:00
|
|
|
AgentID uuid.UUID
|
|
|
|
|
AgentName string
|
|
|
|
|
// WorkspaceBuildID is the build that created the agent.
|
|
|
|
|
WorkspaceBuildID uuid.UUID
|
2025-07-15 14:36:06 +10:00
|
|
|
ConnectionLogger *atomic.Pointer[connectionlog.ConnectionLogger]
|
2025-12-10 14:03:24 -08:00
|
|
|
Workspace *CachedWorkspaceFields
|
2025-07-15 14:36:06 +10:00
|
|
|
Database database.Store
|
|
|
|
|
Log slog.Logger
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (a *ConnLogAPI) ReportConnection(ctx context.Context, req *agentproto.ReportConnectionRequest) (*emptypb.Empty, error) {
|
|
|
|
|
// We use the connection ID to identify which connection log event to mark
|
|
|
|
|
// as closed, when we receive a close action for that ID.
|
|
|
|
|
connectionID, err := uuid.FromBytes(req.GetConnection().GetId())
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, xerrors.Errorf("connection id from bytes: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if connectionID == uuid.Nil {
|
|
|
|
|
return nil, xerrors.New("connection ID cannot be nil")
|
|
|
|
|
}
|
|
|
|
|
action, err := db2sdk.ConnectionLogStatusFromAgentProtoConnectionAction(req.GetConnection().GetAction())
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2026-10-14 13:54:17 +03:00
|
|
|
method, appName, err := sdk2db.ConnectionLogFromAgentConnection(req.GetConnection())
|
2025-07-15 14:36:06 +10:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-16 00:21:40 -08:00
|
|
|
var (
|
|
|
|
|
code sql.NullInt32
|
|
|
|
|
rxBytes sql.NullInt64
|
|
|
|
|
txBytes sql.NullInt64
|
|
|
|
|
)
|
2025-07-15 14:36:06 +10:00
|
|
|
if action == database.ConnectionStatusDisconnected {
|
|
|
|
|
code = sql.NullInt32{
|
|
|
|
|
Int32: req.GetConnection().GetStatusCode(),
|
|
|
|
|
Valid: true,
|
|
|
|
|
}
|
2026-10-16 00:21:40 -08:00
|
|
|
rxBytes = sql.NullInt64{
|
|
|
|
|
Int64: req.GetConnection().GetRxBytes(),
|
|
|
|
|
Valid: req.GetConnection().RxBytes != nil,
|
|
|
|
|
}
|
|
|
|
|
txBytes = sql.NullInt64{
|
|
|
|
|
Int64: req.GetConnection().GetTxBytes(),
|
|
|
|
|
Valid: req.GetConnection().TxBytes != nil,
|
|
|
|
|
}
|
2025-07-15 14:36:06 +10:00
|
|
|
}
|
|
|
|
|
|
2025-12-10 14:03:24 -08:00
|
|
|
var ws database.WorkspaceIdentity
|
|
|
|
|
if dbws, ok := a.Workspace.AsWorkspaceIdentity(); ok {
|
|
|
|
|
ws = dbws
|
2025-07-15 14:36:06 +10:00
|
|
|
}
|
2025-12-10 14:03:24 -08:00
|
|
|
if ws.Equal(database.WorkspaceIdentity{}) {
|
2026-03-20 15:42:05 -05:00
|
|
|
workspace, err := a.Database.GetWorkspaceByAgentID(ctx, a.AgentID)
|
2025-12-10 14:03:24 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, xerrors.Errorf("get workspace by agent id: %w", err)
|
|
|
|
|
}
|
|
|
|
|
ws = database.WorkspaceIdentityFromWorkspace(workspace)
|
2025-07-15 14:36:06 +10:00
|
|
|
}
|
|
|
|
|
|
2025-10-16 01:56:43 +11:00
|
|
|
// Some older clients may incorrectly report "localhost" as the IP address.
|
|
|
|
|
// Related to https://github.com/coder/coder/issues/20194
|
|
|
|
|
logIPRaw := req.GetConnection().GetIp()
|
|
|
|
|
if logIPRaw == "localhost" {
|
|
|
|
|
logIPRaw = "127.0.0.1"
|
|
|
|
|
}
|
|
|
|
|
logIP := database.ParseIP(logIPRaw) // will return null if invalid
|
|
|
|
|
|
2025-07-15 14:36:06 +10:00
|
|
|
reason := req.GetConnection().GetReason()
|
2026-10-19 23:06:41 +03:00
|
|
|
if action == database.ConnectionStatusDisconnected && reason == string(codersdk.DisconnectReasonServerShutdown) {
|
|
|
|
|
reason = a.workspaceShutdownReason(ctx, ws.ID, req.GetConnection())
|
|
|
|
|
}
|
2026-09-27 23:38:36 -07:00
|
|
|
clientSessionID := req.GetConnection().GetClientSessionId()
|
|
|
|
|
if !tracing.ValidSessionID(clientSessionID) {
|
|
|
|
|
clientSessionID = ""
|
|
|
|
|
}
|
2025-07-15 14:36:06 +10:00
|
|
|
connLogger := *a.ConnectionLogger.Load()
|
|
|
|
|
err = connLogger.Upsert(ctx, database.UpsertConnectionLogParams{
|
|
|
|
|
ID: uuid.New(),
|
|
|
|
|
Time: req.GetConnection().GetTimestamp().AsTime(),
|
2025-12-10 14:03:24 -08:00
|
|
|
OrganizationID: ws.OrganizationID,
|
|
|
|
|
WorkspaceOwnerID: ws.OwnerID,
|
|
|
|
|
WorkspaceID: ws.ID,
|
|
|
|
|
WorkspaceName: ws.Name,
|
2026-03-20 15:42:05 -05:00
|
|
|
AgentName: a.AgentName,
|
2026-10-12 15:56:40 +03:00
|
|
|
ConnectionMethod: method,
|
|
|
|
|
AppNameOrPort: sql.NullString{String: appName, Valid: appName != ""},
|
2025-07-15 14:36:06 +10:00
|
|
|
Code: code,
|
2026-04-03 15:47:26 -05:00
|
|
|
IP: logIP,
|
2025-07-15 14:36:06 +10:00
|
|
|
ConnectionID: uuid.NullUUID{
|
|
|
|
|
UUID: connectionID,
|
|
|
|
|
Valid: true,
|
|
|
|
|
},
|
2026-09-27 23:38:36 -07:00
|
|
|
ClientSessionID: sql.NullString{
|
|
|
|
|
String: clientSessionID,
|
|
|
|
|
Valid: clientSessionID != "",
|
|
|
|
|
},
|
2025-07-15 14:36:06 +10:00
|
|
|
DisconnectReason: sql.NullString{
|
|
|
|
|
String: reason,
|
|
|
|
|
Valid: reason != "",
|
|
|
|
|
},
|
|
|
|
|
// We supply the action:
|
|
|
|
|
// - So the DB can handle duplicate connections or disconnections properly.
|
|
|
|
|
// - To make it clear whether this is a connection or disconnection
|
|
|
|
|
// prior to it's insertion into the DB (logs)
|
|
|
|
|
ConnectionStatus: action,
|
|
|
|
|
|
|
|
|
|
// It's not possible to tell which user connected. Once we have
|
|
|
|
|
// the capability, this may be reported by the agent.
|
|
|
|
|
UserID: uuid.NullUUID{
|
|
|
|
|
Valid: false,
|
|
|
|
|
},
|
|
|
|
|
// N/A
|
|
|
|
|
UserAgent: sql.NullString{},
|
2026-10-16 00:21:40 -08:00
|
|
|
RxBytes: rxBytes,
|
|
|
|
|
TxBytes: txBytes,
|
2025-07-15 14:36:06 +10:00
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, xerrors.Errorf("export connection log: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return &emptypb.Empty{}, nil
|
|
|
|
|
}
|
2026-10-19 23:06:41 +03:00
|
|
|
|
|
|
|
|
func (a *ConnLogAPI) workspaceShutdownReason(ctx context.Context, workspaceID uuid.UUID, connection *agentproto.Connection) string {
|
|
|
|
|
reason := string(codersdk.DisconnectReasonServerShutdown)
|
|
|
|
|
clientSessionID := connection.GetClientSessionId()
|
|
|
|
|
if !tracing.ValidSessionID(clientSessionID) {
|
|
|
|
|
clientSessionID = ""
|
|
|
|
|
}
|
|
|
|
|
logger := a.Log.With(
|
|
|
|
|
slog.F("workspace_id", workspaceID),
|
|
|
|
|
slog.F("connection_id", uuid.UUID(connection.GetId())),
|
|
|
|
|
slog.F("client_session_id", clientSessionID),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
build, err := a.Database.GetLatestWorkspaceBuildByWorkspaceID(ctx, workspaceID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warn(ctx, "get shutdown workspace build", slog.Error(err))
|
|
|
|
|
return reason
|
|
|
|
|
}
|
|
|
|
|
// The agent stays connected after a newer build exists only while that
|
|
|
|
|
// build stops or deletes the workspace (see checkBuildIsLatest), so a newer
|
|
|
|
|
// build is the shutdown cause.
|
|
|
|
|
replaced := build.ID != a.WorkspaceBuildID
|
|
|
|
|
// A delayed report must not be attributed to a build requested after the
|
|
|
|
|
// connection closed.
|
|
|
|
|
requestedAfterClose := build.CreatedAt.After(connection.GetTimestamp().AsTime())
|
|
|
|
|
if !replaced || requestedAfterClose {
|
|
|
|
|
return reason
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
job, err := a.Database.GetProvisionerJobByID(ctx, build.JobID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
logger.Warn(ctx, "get shutdown provisioner job", slog.Error(err))
|
|
|
|
|
return reason
|
|
|
|
|
}
|
|
|
|
|
// Queued, failed, and canceled jobs do not establish a shutdown cause.
|
|
|
|
|
active := job.JobStatus == database.ProvisionerJobStatusRunning ||
|
|
|
|
|
job.JobStatus == database.ProvisionerJobStatusSucceeded
|
|
|
|
|
if !active {
|
|
|
|
|
return reason
|
|
|
|
|
}
|
|
|
|
|
return string(codersdk.DisconnectReasonWorkspaceStopped)
|
|
|
|
|
}
|