Skip to content

Commit 8cf9560

Browse files
author
Andrew Farries
committed
Store usage after reconciler runs
1 parent 6de8456 commit 8cf9560

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

components/usage/pkg/controller/reconciler.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package controller
66

77
import (
88
"context"
9+
"database/sql"
910
"encoding/json"
1011
"fmt"
1112
"io/ioutil"
@@ -85,6 +86,11 @@ func (u *UsageReconciler) Reconcile() (err error) {
8586
}
8687
log.Infof("Wrote usage report into %s", filepath.Join(dir, stat.Name()))
8788

89+
err = db.CreateUsageRecords(ctx, u.conn, usageReportToUsageRecords(report))
90+
if err != nil {
91+
return fmt.Errorf("failed to write usage records to database: %s", err)
92+
}
93+
8894
return nil
8995
}
9096

@@ -225,3 +231,28 @@ func groupInstancesByAttributionID(instances []db.WorkspaceInstanceForUsage) Usa
225231

226232
return result
227233
}
234+
235+
func usageReportToUsageRecords(report UsageReport) []db.WorkspaceInstanceUsage {
236+
var usageRecords []db.WorkspaceInstanceUsage
237+
238+
for attributionId, instances := range report {
239+
for _, instance := range instances {
240+
var stoppedAt sql.NullTime
241+
if instance.StoppedTime.IsSet() {
242+
stoppedAt.Time = instance.StoppedTime.Time()
243+
}
244+
245+
usageRecords = append(usageRecords, db.WorkspaceInstanceUsage{
246+
WorkspaceID: instance.ID,
247+
AttributionID: attributionId,
248+
StartedAt: instance.CreationTime.Time(),
249+
StoppedAt: stoppedAt,
250+
CreditsUsed: 0,
251+
GenerationId: 0,
252+
Deleted: false,
253+
})
254+
}
255+
}
256+
257+
return usageRecords
258+
}

0 commit comments

Comments
 (0)