-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdeployment.go
executable file
·565 lines (452 loc) · 15.1 KB
/
deployment.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
Deployments
*/
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/rqlite/gorqlite"
)
const DeploymentStatusScheduled = "scheduled"
const DeploymentStatusBuildingImage = "building_image"
const DeploymentStatusStartingContainers = "starting_containers"
const DeploymentStatusFinished = "finished"
type Deployment struct {
Id string
Status string
EnvironmentId string
ImageId string
SourceFolder string
}
type GitHubPayload struct {
Ref string `json:"ref"`
}
type BitbucketPayload struct {
Push struct {
Changes []struct {
New struct {
Name string `json:"name"`
Type string `json:"type"`
Target struct {
Hash string `json:"hash"`
} `json:"target"`
} `json:"new"`
Old struct {
Name string `json:"name"`
Type string `json:"type"`
Target struct {
Hash string `json:"hash"`
} `json:"target"`
} `json:"old"`
} `json:"changes"`
} `json:"push"`
}
func handleEnvironmentDeploymentsGet(w http.ResponseWriter, r *http.Request) {
environmentId := r.PathValue("environmentId")
jsonBytes, err := json.Marshal(getDeploymentsByEnvironmentId(environmentId))
if err != nil {
fmt.Println("Cannot convert Services object into JSON:", err)
return
}
fmt.Fprint(w, string(jsonBytes))
}
func handleEnvironmentDeploymentGet(w http.ResponseWriter, r *http.Request) {
var deployment Deployment
environmentId := r.PathValue("environmentId")
var environment = getEnvironmentById(environmentId)
if environment == nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
id, err := NanoId(7)
if err != nil {
fmt.Println("Cannot generate new NanoId for Deployment:", err)
return
}
deployment.Id = id
deployment.EnvironmentId = environmentId
deployment.Status = DeploymentStatusScheduled
//Create a new image and schedule image building
var image Image
image.DeploymentId = deployment.Id
image.EnvironmentId = environmentId
image.Status = ImageStatusToBuild
newImage := addImage(image)
//Create a deployment
deployment.ImageId = newImage.Id
addDeployment(&deployment)
fmt.Println("Scheduling DeploymentJobs ")
fmt.Println(len(environment.MachineIds))
//Schedule DeploymentJobs
for _, machineId := range environment.MachineIds {
scheduleDeploymentJob(machineId, *environment, deployment)
}
jsonBytes, err := json.Marshal(deployment)
if err != nil {
fmt.Println("Cannot convert Proxy object into JSON:", err)
return
}
fmt.Fprint(w, string(jsonBytes))
}
func handleEnvironmentDeploymentPost(w http.ResponseWriter, r *http.Request) {
var deployment Deployment
environmentId := r.PathValue("environmentId")
var environment = getEnvironmentById(environmentId)
if environment == nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
err := decodeJSONBody(w, r, &deployment, false)
if err != nil {
var mr *malformedRequest
if errors.As(err, &mr) {
http.Error(w, mr.msg, mr.status)
} else {
log.Print(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
id, err := NanoId(7)
if err != nil {
fmt.Println("Cannot generate new NanoId for Deployment:", err)
return
}
deployment.Id = id
deployment.EnvironmentId = environmentId
deployment.Status = DeploymentStatusScheduled
//Create a new image and schedule image building
var image Image
image.DeploymentId = deployment.Id
image.EnvironmentId = environmentId
image.Status = ImageStatusToBuild
newImage := addImage(image)
//Create a deployment
deployment.ImageId = newImage.Id
addDeployment(&deployment)
fmt.Println("Scheduling DeploymentJobs ")
fmt.Println(len(environment.MachineIds))
//Schedule DeploymentJobs
for _, machineId := range environment.MachineIds {
scheduleDeploymentJob(machineId, *environment, deployment)
}
jsonBytes, err := json.Marshal(deployment)
if err != nil {
fmt.Println("Cannot convert Proxy object into JSON:", err)
return
}
fmt.Fprint(w, string(jsonBytes))
}
func handleServiceDeploymentPost(w http.ResponseWriter, r *http.Request) {
var deployment Deployment
serviceId := r.PathValue("serviceId")
var service = getServiceById(serviceId)
if service == nil {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
//We should load environment by branch name and service Id
//Check header to know the webhook source
branchName := ""
agentHeader := r.Header.Get("User-Agent")
if agentHeader != "" {
if strings.Contains(agentHeader, "GitHub") {
fmt.Println("New GitHub webhook event is received")
var githubPayload GitHubPayload
err := decodeJSONBody(w, r, &githubPayload, false)
if err != nil {
var mr *malformedRequest
if errors.As(err, &mr) {
http.Error(w, mr.msg, mr.status)
} else {
log.Print(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
if !strings.Contains(githubPayload.Ref, "refs/heads/") {
fmt.Println("GitHub Handler: Current version doesn't support deployments by Git tags:", err)
return
}
branchName = strings.Replace(githubPayload.Ref, "refs/heads/", "", 1)
} else if strings.Contains(agentHeader, "Bitbucket") {
fmt.Println("New Bitbucket webhook event is received")
var bitbucketPayload BitbucketPayload
err := decodeJSONBody(w, r, &bitbucketPayload, false)
if err != nil {
var mr *malformedRequest
if errors.As(err, &mr) {
http.Error(w, mr.msg, mr.status)
} else {
log.Print(err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
return
}
if bitbucketPayload.Push.Changes[0].New.Type == "branch" {
branchName = bitbucketPayload.Push.Changes[0].New.Name
} else {
fmt.Println("Bitbucket Handler: Current version doesn't support deployments by Git tags:", err)
}
}
}
if branchName == "" {
fmt.Println("Cannot parse Git branch from payload")
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
environment := getEnvironmentByServiceIdAndName(serviceId, branchName)
fmt.Println("Found environment getEnvironmentByServiceIdAndName:", environment.Id)
/////////////////////////////////////////////////////////
id, err := NanoId(7)
if err != nil {
fmt.Println("Cannot generate new NanoId for Deployment:", err)
return
}
deployment.Id = id
deployment.EnvironmentId = environment.Id
deployment.Status = DeploymentStatusScheduled
//Create a new image and schedule image building
var image Image
image.DeploymentId = deployment.Id
image.Status = ImageStatusToBuild
image.EnvironmentId = environment.Id
newImage := addImage(image)
//Create a deployment
deployment.ImageId = newImage.Id
addDeployment(&deployment)
fmt.Println("Scheduling DeploymentJobs ")
fmt.Println(len(environment.MachineIds))
//Schedule DeploymentJobs
for _, machineId := range environment.MachineIds {
scheduleDeploymentJob(machineId, *environment, deployment)
}
jsonBytes, err := json.Marshal(deployment)
if err != nil {
fmt.Println("Cannot convert Proxy object into JSON:", err)
return
}
fmt.Fprint(w, string(jsonBytes))
}
func scheduleDeploymentJob(machineId string, environment Environment, deployment Deployment) {
var job DeploymentJob
job.MachineId = machineId
job.Status = StatusToDeploy
job.DeploymentId = deployment.Id
addDeploymentJob(job)
var envLog EnvironmentLog
envLog.EnvironmentId = environment.Id
envLog.DeploymentId = deployment.Id
envLog.Level = "6"
envLog.MachineId = machineId
envLog.Message = "New deployment (ID='" + deployment.Id + "') for environment '" + environment.Name + "' has been scheduled on machine ID=" + machineId
saveEnvironmentLog(envLog)
}
func startDeploymentCheckerWorker() {
for range time.Tick(time.Second * 2) {
go func() {
scheduledDeployments := getDeploymentsByStatus(DeploymentStatusScheduled)
for _, deployment := range scheduledDeployments {
fmt.Println("Deployment: " + deployment.Id + ": " + " Status: " + deployment.Status)
images := getImageByDeploymentIdAndStatus(deployment.Id, ImageStatusToBuild)
if len(images) > 0 {
fmt.Println("Image: " + images[0].Id + ": " + images[0].Status)
buildImage(images[0], deployment)
}
}
readyToStartContainersDeployments := getDeploymentsByStatus(DeploymentStatusStartingContainers)
for _, deployment := range readyToStartContainersDeployments {
fmt.Println("Deployment: " + deployment.Id + ": " + " Status: " + deployment.Status)
//Check if there is already a built image for this deployment
images := getImageByDeploymentIdAndStatus(deployment.Id, ImageStatusReady)
if len(images) > 0 {
//The image has been built and uploaded to a container registry
//Time to pull the image and start containers
//Get DeploymentJobs with status StatusToDeploy and DeploymentId = deployment.Id
jobs := getDeploymentJobsByDeploymentIdAndStatus(deployment.Id, StatusToDeploy)
if len(jobs) > 0 {
//Deploy on this machine if job.MachineId = machine_id, where we run this code
for _, job := range jobs {
if job.MachineId == thisMachine.Id {
deployImage(images[0], job, deployment)
}
}
} else {
//All DeploymentJobs are finished, update status of Deployment
updateDeploymentStatus(deployment, DeploymentStatusFinished)
}
}
}
}()
}
}
func updateDeploymentStatus(deployment Deployment, status string) error {
_, err := connection.WriteParameterized(
[]gorqlite.ParameterizedStatement{
{
Query: "UPDATE Deployment SET Status = ? WHERE Id = ?",
Arguments: []interface{}{status, deployment.Id},
},
},
)
if err != nil {
fmt.Printf("Cannot update a row in Deployment: %s\n", err.Error())
return err
}
return nil
}
func deployImage(image Image, job DeploymentJob, deployment Deployment) {
fmt.Println("Pulling and starting a container from Image " + image.Id)
//Pull the image from a container registry over VPN
//Start a container
err := updateDeploymentJobStatus(job, StatusInProgress)
if err != nil {
fmt.Println("Cannot update DeploymentJob row:", err)
return
}
//Get environment
environment := getEnvironmentById(deployment.EnvironmentId)
portInt, err := GetFreePort()
if err != nil {
fmt.Println("Cannot get a free port on this machine:", err)
}
port := strconv.Itoa(portInt)
//Now we start only one replica but later we will add more replicas
//Container name has format "deploymentId.replica_number"
scriptTemplate := createTemplate("caddyfile", `
#!/bin/sh
docker image pull {{.CONTAINER_REGISTRY_IP}}:7000/{{.IMAGE_ID}}
docker container run -p 127.0.0.1:{{.MACHINE_PORT}}:{{.SERVICE_PORT}} -d --restart unless-stopped --log-driver=journald --name {{.DEPLOYMENT_ID}}.1 {{.CONTAINER_REGISTRY_IP}}:7000/{{.IMAGE_ID}}
`)
var templateBytes bytes.Buffer
templateData := map[string]string{
"IMAGE_ID": image.Id,
"SERVICE_PORT": environment.Port,
"MACHINE_PORT": port,
"DEPLOYMENT_ID": deployment.Id,
"CONTAINER_REGISTRY_IP": containerRegistryIp,
}
if err := scriptTemplate.Execute(&templateBytes, templateData); err != nil {
fmt.Println("Cannot execute template for Caddyfile:", err)
}
scriptString := templateBytes.String()
_, err = executeScriptString(scriptString, func(logLine string) {
//Save log message
var envLog EnvironmentLog
envLog.EnvironmentId = environment.Id
envLog.DeploymentId = deployment.Id
envLog.Level = "6"
envLog.MachineId = thisMachine.Id
envLog.Message = logLine
saveEnvironmentLog(envLog)
////////////////////////
})
if err != nil {
fmt.Println("Cannot start the image")
return
}
fmt.Println("Image " + image.Id + " has been started on machine " + job.MachineId)
err = updateDeploymentJobStatus(job, StatusDeployed)
if err != nil {
fmt.Printf(" Cannot update a row in DeploymentJob: %s\n", err.Error())
return
}
//Delete all proxies with the same EnvironmentId as this deployment
deleteProxiesIfDeploymentIdNotEqual(deployment.EnvironmentId, deployment.Id)
//Add a Proxy record
var proxy Proxy
proxy.ServerPrivateIP = thisMachine.VPNIp
proxy.Port = port
proxy.Domain = environment.Domains[0]
proxy.EnvironmentId = deployment.EnvironmentId
proxy.DeploymentId = deployment.Id
addProxy(&proxy)
stopPreviousContainer(deployment.EnvironmentId)
}
/*Database*/
func addDeployment(deployment *Deployment) {
_, err := connection.WriteParameterized(
[]gorqlite.ParameterizedStatement{
{
Query: "INSERT INTO Deployment( Id, Status, EnvironmentId, ImageId, SourceFolder) VALUES(?, ?, ?, ?, ?)",
Arguments: []interface{}{deployment.Id, deployment.Status, deployment.EnvironmentId, deployment.ImageId, deployment.SourceFolder},
},
},
)
if err != nil {
fmt.Printf(" Cannot write to Deployment table: %s\n", err.Error())
}
}
func getDeploymentById(deploymentId string) *Deployment {
rows, err := connection.QueryOneParameterized(
gorqlite.ParameterizedStatement{
Query: "SELECT Id, Status, EnvironmentId, ImageId, SourceFolder from Deployment where id = ?",
Arguments: []interface{}{deploymentId},
},
)
deployments := handleQuery(rows, err)
if len(deployments) == 0 {
return nil
}
return &deployments[0]
}
func getLastDeploymentByEnvironmentId(environmentId string) []Deployment {
rows, err := connection.QueryOneParameterized(
gorqlite.ParameterizedStatement{
Query: "SELECT Id, Status, EnvironmentId, ImageId, SourceFolder from Deployment where EnvironmentId = ? ORDER BY CreatedAt DESC LIMIT 1",
Arguments: []interface{}{environmentId},
},
)
return handleQuery(rows, err)
}
func getDeploymentsByEnvironmentId(environmentId string) []Deployment {
rows, err := connection.QueryOneParameterized(
gorqlite.ParameterizedStatement{
Query: "SELECT Id, Status, EnvironmentId, ImageId, SourceFolder from Deployment where EnvironmentId = ? ORDER BY CreatedAt DESC",
Arguments: []interface{}{environmentId},
},
)
return handleQuery(rows, err)
}
func getDeploymentsByStatus(status string) []Deployment {
rows, err := connection.QueryOneParameterized(
gorqlite.ParameterizedStatement{
Query: "SELECT Id, Status, EnvironmentId, ImageId, SourceFolder from Deployment where Status = ? ORDER BY CreatedAt DESC",
Arguments: []interface{}{status},
},
)
return handleQuery(rows, err)
}
func handleQuery(rows gorqlite.QueryResult, err error) []Deployment {
var deployments = []Deployment{}
if err != nil {
fmt.Printf(" Cannot read from Deployment table: %s\n", err.Error())
}
for rows.Next() {
var Id string
var Status string
var EnvironmentId string
var ImageId string
var SourceFolder string
err := rows.Scan(&Id, &Status, &EnvironmentId, &ImageId, &SourceFolder)
if err != nil {
fmt.Printf(" Cannot run Scan: %s\n", err.Error())
}
loadedDeployment := Deployment{
Id: Id,
Status: Status,
EnvironmentId: EnvironmentId,
ImageId: ImageId,
SourceFolder: SourceFolder,
}
deployments = append(deployments, loadedDeployment)
}
return deployments
}