This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
devstats.go
318 lines (302 loc) · 8.71 KB
/
devstats.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"time"
"github.com/lib/pq"
"github.com/ti-community-infra/devstats/internal/pkg/lib"
yaml "gopkg.in/yaml.v2"
)
// Sync all projects from "projects.yaml", calling `gha2db_sync` for all of them
func syncAllProjects() bool {
// Environment context parse
var ctx lib.Ctx
ctx.Init()
// Local or cron mode?
dataPrefix := ctx.DataDir
if ctx.Local {
dataPrefix = "./"
}
cmdPrefix := ""
if ctx.LocalCmd {
cmdPrefix = "./"
}
// Read defined projects
data, err := ioutil.ReadFile(dataPrefix + ctx.ProjectsYaml)
lib.FatalOnError(err)
var projects lib.AllProjects
lib.FatalOnError(yaml.Unmarshal(data, &projects))
// Get ordered & filtered projects
names, projs := lib.GetProjectsList(&ctx, &projects)
// If check provision flag is set, we need to iterate all projects
// and check if all of them are provisioned
if ctx.CheckProvisionFlag {
missing := 0
for _, proj := range projs {
db := proj.PDB
con := lib.PgConnDB(&ctx, db)
provisionFlag := "provisioned"
rows, err := lib.QuerySQL(con, &ctx, "select 1 from gha_computed where metric = "+lib.NValue(1)+" limit 1", provisionFlag)
if err != nil {
switch e := err.(type) {
case *pq.Error:
errName := e.Code.Name()
if errName == lib.InvalidCatalogName {
lib.Printf("No '%s' database, missing provisioning flag\n", db)
missing++
lib.FatalOnError(con.Close())
continue
} else {
lib.FatalOnError(err)
}
default:
lib.FatalOnError(err)
}
}
provisioned := 0
for rows.Next() {
lib.FatalOnError(rows.Scan(&provisioned))
}
lib.FatalOnError(rows.Err())
lib.FatalOnError(rows.Close())
lib.FatalOnError(con.Close())
if provisioned != 1 {
lib.Printf("Missing provisioned flag on '%s' database and check provisioned flag is set\n", db)
missing++
}
}
if missing > 0 {
lib.Printf("Not all databases provisioned, pending: %d, exiting\n", missing)
return false
}
}
// If running provision flag is set on any project, we skip running this devstats instance
runningFlag := "devstats_running"
if ctx.CheckRunningFlag {
for _, proj := range projs {
db := proj.PDB
con := lib.PgConnDB(&ctx, db)
rows, err := lib.QuerySQL(
con,
&ctx,
"select dt from gha_computed where metric = "+lib.NValue(1)+" order by dt desc limit 1",
runningFlag,
)
if err != nil {
switch e := err.(type) {
case *pq.Error:
errName := e.Code.Name()
if errName == lib.InvalidCatalogName {
lib.Printf("No '%s' database, cannot check running flag\n", db)
lib.FatalOnError(con.Close())
return false
}
lib.FatalOnError(err)
default:
lib.FatalOnError(err)
}
}
running := time.Now()
runningSet := false
for rows.Next() {
lib.FatalOnError(rows.Scan(&running))
runningSet = true
}
lib.FatalOnError(rows.Err())
lib.FatalOnError(rows.Close())
if runningSet {
age := time.Now().Sub(running)
lib.Printf("Running flag on '%s' set, age %+v, maximum allowed age: %+v\n", db, age, ctx.MaxRunningFlagAge)
if age <= ctx.MaxRunningFlagAge {
lib.Printf("Running flag on '%s' set, exiting\n", db)
lib.FatalOnError(con.Close())
return false
}
lib.Printf("Running flag on '%s' expired, removing (this may be due to some error)\n", db)
lib.ExecSQLWithErr(con, &ctx, "delete from gha_computed where metric ="+lib.NValue(1), runningFlag)
lib.FatalOnError(con.Close())
lib.Printf("Running flag on '%s' force removed\n", db)
}
}
}
// Set 'devstats_running' flag on 'gha_computed' table and defer clearing that flag
if ctx.SetRunningFlag {
if ctx.Debug > 0 {
lib.Printf("Setting running flag\n")
}
missing := 0
for _, proj := range projs {
db := proj.PDB
con := lib.PgConnDB(&ctx, db)
_, err := lib.ExecSQL(
con,
&ctx,
"insert into gha_computed(metric, dt) select "+lib.NValue(1)+", now() where not exists(select 1 from gha_computed where metric = "+lib.NValue(2)+")",
runningFlag,
runningFlag,
)
if err != nil {
switch e := err.(type) {
case *pq.Error:
errName := e.Code.Name()
if errName == lib.InvalidCatalogName {
lib.Printf("No '%s' database, cannot set running flag\n", db)
missing++
lib.FatalOnError(con.Close())
continue
} else {
lib.FatalOnError(err)
}
default:
lib.FatalOnError(err)
}
}
lib.FatalOnError(con.Close())
if ctx.Debug > 0 {
lib.Printf("Set running flag on %s\n", db)
}
}
// Defer clearing that flag
defer func() {
if ctx.Debug > 0 {
lib.Printf("Deleting running flag\n")
}
for _, proj := range projs {
db := proj.PDB
sleepTime := 1
for {
con := lib.PgConnDB(&ctx, db)
_, err := lib.ExecSQL(con, &ctx, "delete from gha_computed where metric = "+lib.NValue(1), runningFlag)
con.Close()
if err == nil {
if ctx.Debug > 0 || sleepTime > 1 {
lib.Printf("Cleared running flag on %s\n", db)
}
break
} else {
if sleepTime >= 90 {
lib.Fatalf("something really bad happened, tried to clear running flag 60 times without success")
}
lib.Printf("Failed to clear running flag on %s: %+v, retrying after %d seconds\n", db, err, sleepTime)
time.Sleep(time.Duration(sleepTime) * time.Second)
sleepTime++
}
}
}
}()
if missing > 0 {
lib.Printf("Not all databases present, missing: %d, exiting\n", missing)
return false
}
}
// Set non-fatal exec mode, we want to run sync for next project(s) if current fails
ctx.ExecFatal = false
if !ctx.SkipPIDFile {
// Create PID file (if not exists)
// If PID file exists, exit
pid := os.Getpid()
pidFile := "/tmp/" + ctx.PidFileRoot + ".pid"
f, err := os.OpenFile(pidFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0700)
if err != nil {
lib.Printf("Another `devstats` instance is running, PID file '%s' exists, exiting (not an error)\n", pidFile)
return false
}
fmt.Fprintf(f, "%d", pid)
lib.FatalOnError(f.Close())
// Schedule remove PID file when finished
defer func() { lib.FatalOnError(os.Remove(pidFile)) }()
}
// Only run clone/pull part here
// Remaining commit analysis in"gha2db_sync"
// after new commits are fetched from GHA
// So here we get repo files to the newest state
// And the gha2db_sync takes Postgres DB commits to the newest state
// after this it need to update commit files
if !ctx.SkipGetRepos {
lib.Printf("Updating git repos for all projects\n")
dtStart := time.Now()
_, res := lib.ExecCommand(
&ctx,
[]string{
cmdPrefix + "get_repos",
},
map[string]string{
"GHA2DB_PROCESS_REPOS": "1",
},
)
dtEnd := time.Now()
if res != nil {
lib.Printf("Error updating git repos (took %v): %+v\n", dtEnd.Sub(dtStart), res)
fmt.Fprintf(os.Stderr, "%v: Error updating git repos (took %v): %+v\n", dtEnd, dtEnd.Sub(dtStart), res)
return false
}
lib.Printf("Updated git repos, took: %v\n", dtEnd.Sub(dtStart))
}
// Sync all projects
for i, name := range names {
proj := projs[i]
if proj.SyncProbability != nil {
rand.Seed(time.Now().UnixNano())
if rand.Float64() >= *proj.SyncProbability {
lib.Printf("Skipping #%d %s\n", proj.Order, name)
continue
}
}
projEnv := map[string]string{
"GHA2DB_PROJECT": name,
"PG_DB": proj.PDB,
"ENV_SET": "1",
}
// Apply eventual per project specific environment
for envName, envValue := range proj.Env {
projEnv[envName] = envValue
}
lib.Printf("Syncing #%d %s\n", proj.Order, name)
dtStart := time.Now()
_, res := lib.ExecCommand(
&ctx,
[]string{
cmdPrefix + "gha2db_sync",
},
projEnv,
)
dtEnd := time.Now()
if res != nil {
lib.Printf("Error result for %s (took %v): %+v\n", name, dtEnd.Sub(dtStart), res)
fmt.Fprintf(os.Stderr, "%v: Error result for %s (took %v): %+v\n", dtEnd, name, dtEnd.Sub(dtStart), res)
continue
}
lib.Printf("Synced %s, took: %v\n", name, dtEnd.Sub(dtStart))
}
if ctx.WebsiteData {
lib.Printf("Generating website data for all projects\n")
dtStart := time.Now()
_, res := lib.ExecCommand(
&ctx,
[]string{
cmdPrefix + "website_data",
},
nil,
)
dtEnd := time.Now()
if res != nil {
lib.Printf("Error generating website data (took %v): %+v\n", dtEnd.Sub(dtStart), res)
fmt.Fprintf(os.Stderr, "%v: Error generating website (took %v): %+v\n", dtEnd, dtEnd.Sub(dtStart), res)
return false
}
lib.Printf("Generated website data, took: %v\n", dtEnd.Sub(dtStart))
}
return true
}
func main() {
dtStart := time.Now()
synced := syncAllProjects()
dtEnd := time.Now()
if synced {
lib.Printf("Synced all projects in: %v\n", dtEnd.Sub(dtStart))
} else {
lib.Printf("There were sync errors, took: %v\n", dtEnd.Sub(dtStart))
}
}