-
Notifications
You must be signed in to change notification settings - Fork 1
/
recorder.go
108 lines (98 loc) · 2.65 KB
/
recorder.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cluster
import (
"github.com/geowa4/ocm-workon/pkg/utils"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"time"
)
type RecordedCluster struct {
gorm.Model
Environment string
Name string
ID string
ExternalID string
InfraID string
HiveShard string
ManagementCluster string
ServiceCluster string
Elevations []Elevation `json:",omitempty"`
}
type Elevation struct {
gorm.Model
RecordedClusterID string `json:"-"`
RecordedCluster RecordedCluster
Source string
Reason string
}
func RecordElevation(baseDir string, clusterId string, source string, reason string) error {
db, err := makeDb(baseDir)
if err != nil {
return err
}
elevation := &Elevation{
RecordedCluster: RecordedCluster{ID: clusterId},
Source: source,
Reason: reason,
}
db.Save(elevation)
return nil
}
func NewRecordedCluster(environment string, ncd *NormalizedClusterData) *RecordedCluster {
return &RecordedCluster{
Environment: environment,
Name: ncd.Name,
ID: ncd.InternalID,
ExternalID: ncd.ExternalID,
InfraID: ncd.InfraID,
HiveShard: ncd.HiveShard,
ManagementCluster: ncd.ManagementCluster,
ServiceCluster: ncd.ServiceCluster,
}
}
func (cluster *RecordedCluster) RecordAccess(baseDir string) error {
db, err := makeDb(baseDir)
if err != nil {
return err
}
db.Save(cluster)
return nil
}
func makeDb(baseDir string) (*gorm.DB, error) {
db, err := gorm.Open(sqlite.Open(baseDir+utils.PathSep+"workon.db"), &gorm.Config{})
if err != nil {
return nil, err
}
if err = db.AutoMigrate(&Elevation{}, &RecordedCluster{}); err != nil {
return nil, err
}
return db, nil
}
func findRecordingsSince(baseDir, timeAgo string, queryFunc func(*gorm.DB, time.Time)) (err error) {
db, err := makeDb(baseDir)
if err != nil {
return
}
timeAgoAsDuration, err := time.ParseDuration(timeAgo)
if err != nil {
return
}
sinceWhen := time.Now().Add(-1 * timeAgoAsDuration)
queryFunc(db, sinceWhen)
return
}
func FindRecordedClustersSince(baseDir, timeAgo string) (clusters []RecordedCluster, err error) {
err = findRecordingsSince(baseDir, timeAgo, func(db *gorm.DB, sinceWhen time.Time) {
db.Where("updated_at > ?", sinceWhen).
Order("updated_at").
Find(&clusters)
})
return
}
func FindElevationsSince(baseDir, timeAgo string) (elevations []Elevation, err error) {
err = findRecordingsSince(baseDir, timeAgo, func(db *gorm.DB, sinceWhen time.Time) {
db.Joins("RecordedCluster").Where("elevations.updated_at > ?", sinceWhen).
Order("elevations.updated_at").
Find(&elevations)
})
return
}