| 26 | } |
| 27 | |
| 28 | func (a *ConnLogAPI) ReportConnection(ctx context.Context, req *agentproto.ReportConnectionRequest) (*emptypb.Empty, error) { |
| 29 | // We use the connection ID to identify which connection log event to mark |
| 30 | // as closed, when we receive a close action for that ID. |
| 31 | connectionID, err := uuid.FromBytes(req.GetConnection().GetId()) |
| 32 | if err != nil { |
| 33 | return nil, xerrors.Errorf("connection id from bytes: %w", err) |
| 34 | } |
| 35 | |
| 36 | if connectionID == uuid.Nil { |
| 37 | return nil, xerrors.New("connection ID cannot be nil") |
| 38 | } |
| 39 | action, err := db2sdk.ConnectionLogStatusFromAgentProtoConnectionAction(req.GetConnection().GetAction()) |
| 40 | if err != nil { |
| 41 | return nil, err |
| 42 | } |
| 43 | connectionType, err := db2sdk.ConnectionLogConnectionTypeFromAgentProtoConnectionType(req.GetConnection().GetType()) |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | |
| 48 | var code sql.NullInt32 |
| 49 | if action == database.ConnectionStatusDisconnected { |
| 50 | code = sql.NullInt32{ |
| 51 | Int32: req.GetConnection().GetStatusCode(), |
| 52 | Valid: true, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | var ws database.WorkspaceIdentity |
| 57 | if dbws, ok := a.Workspace.AsWorkspaceIdentity(); ok { |
| 58 | ws = dbws |
| 59 | } |
| 60 | if ws.Equal(database.WorkspaceIdentity{}) { |
| 61 | workspace, err := a.Database.GetWorkspaceByAgentID(ctx, a.AgentID) |
| 62 | if err != nil { |
| 63 | return nil, xerrors.Errorf("get workspace by agent id: %w", err) |
| 64 | } |
| 65 | ws = database.WorkspaceIdentityFromWorkspace(workspace) |
| 66 | } |
| 67 | |
| 68 | // Some older clients may incorrectly report "localhost" as the IP address. |
| 69 | // Related to https://github.com/coder/coder/issues/20194 |
| 70 | logIPRaw := req.GetConnection().GetIp() |
| 71 | if logIPRaw == "localhost" { |
| 72 | logIPRaw = "127.0.0.1" |
| 73 | } |
| 74 | logIP := database.ParseIP(logIPRaw) // will return null if invalid |
| 75 | |
| 76 | reason := req.GetConnection().GetReason() |
| 77 | connLogger := *a.ConnectionLogger.Load() |
| 78 | err = connLogger.Upsert(ctx, database.UpsertConnectionLogParams{ |
| 79 | ID: uuid.New(), |
| 80 | Time: req.GetConnection().GetTimestamp().AsTime(), |
| 81 | OrganizationID: ws.OrganizationID, |
| 82 | WorkspaceOwnerID: ws.OwnerID, |
| 83 | WorkspaceID: ws.ID, |
| 84 | WorkspaceName: ws.Name, |
| 85 | AgentName: a.AgentName, |