forked from applikatoni/applikatoni
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
371 lines (292 loc) · 9.77 KB
/
database.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
"errors"
"log"
"strings"
"time"
"github.com/pborman/uuid"
"github.com/applikatoni/applikatoni/deploy"
"github.com/applikatoni/applikatoni/models"
"database/sql"
)
const (
deploymentStmt = `SELECT id, user_id, application_name, target_name, commit_sha, branch, comment, state, created_at FROM deployments WHERE deployments.id = ?`
deploymentInsertStmt = `INSERT INTO deployments (user_id, application_name, target_name, commit_sha, branch, comment, state, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`
deploymentUpdateStateStmt = `UPDATE deployments SET state = ? WHERE deployments.id = ?`
deploymentFailUnfinishedStmt = `UPDATE deployments SET state = ? WHERE deployments.state = ? OR deployments.state = ?`
lastTargetDeploymentStmt = `SELECT id, user_id, application_name, target_name, commit_sha, branch, comment, state, created_at FROM deployments WHERE deployments.state = ? AND deployments.application_name = ? AND deployments.target_name = ? ORDER BY created_at DESC LIMIT 1`
applicationDeploymentsStmt = `SELECT id, user_id, target_name, commit_sha, branch, comment, state, created_at FROM deployments WHERE deployments.application_name = ? ORDER BY created_at DESC LIMIT ?`
logEntryInsertStmt = `INSERT INTO log_entries (deployment_id, entry_type, origin, message, timestamp, created_at) VALUES (?, ?, ?, ?, ?, ?);`
deploymentLogEntriesStmt = `SELECT id, deployment_id, entry_type, origin, message, timestamp FROM log_entries WHERE log_entries.deployment_id = ? ORDER BY timestamp ASC`
userInsertStmt = `INSERT INTO users(id, name, access_token, avatar_url, api_token) VALUES(?, ?, ?, ?, ?);`
userStmt = `SELECT id, name, access_token, avatar_url, api_token FROM users WHERE id = ?;`
userApiTokenStmt = `SELECT id, name, access_token, avatar_url, api_token FROM users WHERE api_token = ?;`
activeDeploymentsStmt = `SELECT state FROM deployments WHERE target_name = ? AND state = 'active' LIMIT 1;`
dailyDigestDeploymentsStmt = `SELECT id, user_id, target_name, commit_sha, branch, comment, state, created_at FROM deployments WHERE state = 'successful' AND application_name = ? AND target_name = ? AND created_at > ? ORDER BY created_at ASC;`
)
var ErrDeployInProgress = errors.New("another deployment to target already in progress")
func createDeployment(db *sql.DB, d *models.Deployment) error {
var id int64
var state models.DeploymentState = models.DEPLOYMENT_NEW
var createdAt time.Time = time.Now()
tx, err := db.Begin()
if err != nil {
return err
}
exists, err := activeDeploymentExists(tx, d.TargetName)
if err != nil {
tx.Rollback()
return err
}
if exists {
tx.Rollback()
return ErrDeployInProgress
}
result, err := tx.Exec(deploymentInsertStmt, d.UserId, d.ApplicationName,
d.TargetName, d.CommitSha, d.Branch, d.Comment, string(state), createdAt)
if err != nil {
tx.Rollback()
return err
}
id, err = result.LastInsertId()
if err != nil {
tx.Rollback()
return err
}
d.Id = int(id)
d.State = state
d.CreatedAt = createdAt
tx.Commit()
return nil
}
func updateDeploymentState(db *sql.DB, d *models.Deployment, state models.DeploymentState) error {
_, err := db.Exec(deploymentUpdateStateStmt, string(state), d.Id)
if err != nil {
return err
}
d.State = state
return nil
}
func getRecentApplicationDeployments(db *sql.DB, a *models.Application) ([]*models.Deployment, error) {
return getApplicationDeployments(db, a, 10)
}
func getAllApplicationDeployments(db *sql.DB, a *models.Application) ([]*models.Deployment, error) {
return getApplicationDeployments(db, a, -1)
}
func getApplicationDeployments(db *sql.DB, a *models.Application, limit int) ([]*models.Deployment, error) {
deployments := []*models.Deployment{}
rows, err := db.Query(applicationDeploymentsStmt, a.Name, limit)
if err != nil {
return deployments, err
}
defer rows.Close()
for rows.Next() {
var state string
d := &models.Deployment{}
err = rows.Scan(&d.Id, &d.UserId, &d.TargetName, &d.CommitSha, &d.Branch, &d.Comment, &state, &d.CreatedAt)
if err != nil {
return deployments, err
}
d.State = models.DeploymentState(state)
deployments = append(deployments, d)
}
if err := rows.Err(); err != nil {
return deployments, err
}
return deployments, nil
}
func getDeployment(db *sql.DB, id int) (*models.Deployment, error) {
return queryDeploymentRow(db, deploymentStmt, id)
}
func getLastTargetDeployment(db *sql.DB, a *models.Application, targetName string) (*models.Deployment, error) {
return queryDeploymentRow(db, lastTargetDeploymentStmt,
string(models.DEPLOYMENT_SUCCESSFUL), a.Name, targetName)
}
func getDailyDigestDeployments(db *sql.DB, a *models.Application, targetName string, since time.Time) ([]*models.Deployment, error) {
deployments := []*models.Deployment{}
rows, err := db.Query(dailyDigestDeploymentsStmt, a.Name, targetName, since)
if err != nil {
return deployments, err
}
defer rows.Close()
for rows.Next() {
var state string
d := &models.Deployment{}
err = rows.Scan(&d.Id, &d.UserId, &d.TargetName, &d.CommitSha, &d.Branch, &d.Comment, &state, &d.CreatedAt)
if err != nil {
return deployments, err
}
d.State = models.DeploymentState(state)
deployments = append(deployments, d)
}
if err := rows.Err(); err != nil {
return deployments, err
}
return deployments, nil
}
func failUnfinishedDeployments(db *sql.DB) error {
_, err := db.Exec(deploymentFailUnfinishedStmt,
string(models.DEPLOYMENT_FAILED), string(models.DEPLOYMENT_NEW),
string(models.DEPLOYMENT_ACTIVE))
return err
}
func createLogEntry(db *sql.DB, entry *deploy.LogEntry) error {
result, err := db.Exec(logEntryInsertStmt, entry.DeploymentId,
string(entry.EntryType), entry.Origin, entry.Message,
entry.Timestamp, time.Now())
if err != nil {
return err
}
id, err := result.LastInsertId()
if err != nil {
return err
}
entry.Id = int(id)
return err
}
func getDeploymentLogEntries(db *sql.DB, d *models.Deployment) ([]*deploy.LogEntry, error) {
entries := []*deploy.LogEntry{}
rows, err := db.Query(deploymentLogEntriesStmt, d.Id)
if err != nil {
return entries, err
}
defer rows.Close()
for rows.Next() {
var entryType string
e := &deploy.LogEntry{}
err = rows.Scan(&e.Id, &e.DeploymentId, &entryType, &e.Origin, &e.Message, &e.Timestamp)
if err != nil {
return entries, err
}
e.EntryType = deploy.LogEntryType(entryType)
entries = append(entries, e)
}
if err := rows.Err(); err != nil {
return entries, err
}
return entries, nil
}
func newLogEntrySaver(db *sql.DB) deploy.Listener {
fn := func(logs <-chan deploy.LogEntry) {
for entry := range logs {
err := createLogEntry(db, &entry)
if err != nil {
log.Printf("error saving log entry: %s", err)
}
}
}
return fn
}
func createUser(db *sql.DB, u *models.User) error {
u.ApiToken = uuid.New()
_, err := db.Exec(userInsertStmt, u.Id, u.Name, u.AccessToken, u.AvatarUrl, u.ApiToken)
return err
}
func getUser(db *sql.DB, id int) (*models.User, error) {
u := &models.User{}
err := db.QueryRow(userStmt, id).Scan(&u.Id, &u.Name, &u.AccessToken, &u.AvatarUrl, &u.ApiToken)
if err != nil {
return nil, err
}
return u, nil
}
func getUserByApiToken(db *sql.DB, token string) (*models.User, error) {
u := &models.User{}
err := db.QueryRow(userApiTokenStmt, token).Scan(&u.Id, &u.Name, &u.AccessToken, &u.AvatarUrl, &u.ApiToken)
if err != nil {
return nil, err
}
return u, nil
}
func getUsers(db *sql.DB, ids []int) ([]*models.User, error) {
users := []*models.User{}
if len(ids) == 0 {
return users, nil
}
stmt := selectUsersStmt(ids)
args := []interface{}{}
for _, id := range ids {
args = append(args, id)
}
rows, err := db.Query(stmt, args...)
if err != nil {
return users, err
}
defer rows.Close()
for rows.Next() {
u := &models.User{}
err = rows.Scan(&u.Id, &u.Name, &u.AccessToken, &u.AvatarUrl)
if err != nil {
return users, err
}
users = append(users, u)
}
if err := rows.Err(); err != nil {
return users, err
}
return users, nil
}
func getOrCreateUser(db *sql.DB, u *models.User) error {
saved, err := getUser(db, u.Id)
if saved != nil && err == nil {
return nil
}
err = createUser(db, u)
return err
}
func loadDeploymentsUsers(db *sql.DB, deployments []*models.Deployment) error {
// Set up map to have unique id->pointer mappings
uniqueUserIds := map[int]*models.User{}
for _, d := range deployments {
uniqueUserIds[d.UserId] = nil
}
// Collect the now unique (keys in map are unique)
userIds := []int{}
for k := range uniqueUserIds {
userIds = append(userIds, k)
}
users, err := getUsers(db, userIds)
if err != nil {
return err
}
// Set up the pointers to the users
for _, u := range users {
uniqueUserIds[u.Id] = u
}
// Go over deployments again, set pointers to correct user
for _, d := range deployments {
d.User = uniqueUserIds[d.UserId]
}
return nil
}
func selectUsersStmt(ids []int) string {
tmpl := "SELECT id, name, access_token, avatar_url FROM users WHERE id IN (?"
stmt := tmpl + strings.Repeat(",?", len(ids)-1) + ");"
return stmt
}
func activeDeploymentExists(tx *sql.Tx, targetName string) (bool, error) {
var state string
err := tx.QueryRow(activeDeploymentsStmt, targetName).Scan(&state)
switch {
case err == sql.ErrNoRows:
return false, nil
case err != nil:
return false, err
default:
return true, nil
}
}
func queryDeploymentRow(db *sql.DB, query string, args ...interface{}) (*models.Deployment, error) {
d := &models.Deployment{}
var state string
err := db.QueryRow(query, args...).Scan(&d.Id, &d.UserId, &d.ApplicationName,
&d.TargetName, &d.CommitSha, &d.Branch, &d.Comment, &state, &d.CreatedAt)
if err == sql.ErrNoRows {
return nil, nil
}
if err != nil {
return nil, err
}
d.State = models.DeploymentState(state)
return d, nil
}