-
Notifications
You must be signed in to change notification settings - Fork 563
/
Copy pathdrift.go
333 lines (288 loc) · 9.91 KB
/
drift.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
package controllers
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"time"
"github.com/diggerhq/digger/backend/ci_backends"
"github.com/diggerhq/digger/ee/drift/dbmodels"
services2 "github.com/diggerhq/digger/ee/drift/services"
"github.com/diggerhq/digger/ee/drift/utils"
"github.com/diggerhq/digger/libs/ci/generic"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
"github.com/diggerhq/digger/libs/scheduler"
"github.com/diggerhq/digger/libs/spec"
utils2 "github.com/diggerhq/digger/next/utils"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type TriggerDriftRunRequest struct {
ProjectId string `json:"project_id"`
}
func (mc MainController) TriggerDriftRunForProject(c *gin.Context) {
var request TriggerDriftRunRequest
err := c.BindJSON(&request)
if err != nil {
log.Printf("Error binding JSON: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error binding JSON"})
return
}
projectId := request.ProjectId
p := dbmodels.DB.Query.Project
project, err := dbmodels.DB.Query.Project.Where(p.ID.Eq(projectId)).First()
if err != nil {
log.Printf("could not find project %v: %v", projectId, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "could not find project"})
return
}
r := dbmodels.DB.Query.Repo
repo, err := dbmodels.DB.Query.Repo.Where(r.ID.Eq(project.RepoID)).First()
if err != nil {
log.Printf("could not find repo: %v for project %v: %v", project.RepoID, project.ID, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "could not find repo"})
return
}
orgId := repo.OrganisationID
issueNumber := 0
repoFullName := repo.RepoFullName
repoOwner := repo.RepoOrganisation
repoName := repo.RepoName
githubAppId := repo.GithubAppID
installationid := repo.GithubInstallationID
installationid64, err := strconv.ParseInt(installationid, 10, 64)
cloneUrl := repo.CloneURL
branch := repo.DefaultBranch
command := "digger plan"
workflowFile := "digger_workflow.yml"
if err != nil {
log.Printf("could not convert installationID to int64 %v", installationid)
c.JSON(http.StatusInternalServerError, gin.H{"error": "could not prarse installation id"})
return
}
_, _, config, _, err := utils.GetDiggerConfigForBranch(mc.GithubClientProvider, installationid64, repoFullName, repoOwner, repoName, cloneUrl, branch)
if err != nil {
log.Printf("Error loading digger config: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "error loading digger config"})
return
}
theProject := config.GetProject(project.Name)
if theProject == nil {
log.Printf("Could find project %v in digger yml", project.Name)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not find project %v in digger.yml", theProject)})
return
}
projects := []dg_configuration.Project{*theProject}
jobsForImpactedProjects, err := generic.CreateJobsForProjects(projects, command, "drift", repoFullName, "digger", config.Workflows, &issueNumber, nil, branch, branch, false)
if err != nil {
log.Printf("error converting digger project %v to job", project.Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not find project %v in digger.yml", theProject)})
return
}
jobToken, err := dbmodels.DB.CreateDiggerJobToken(orgId)
if err != nil {
log.Printf("Error creating job token: %v %v", project.Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("error creating job token")})
return
}
backendHostName := os.Getenv("DIGGER_HOSTNAME")
jobSpec := scheduler.JobToJson(jobsForImpactedProjects[0], "plan", "digger", branch, "", jobToken.Value, backendHostName, *theProject)
spec := spec.Spec{
JobId: uuid.NewString(),
CommentId: "",
Job: jobSpec,
Reporter: spec.ReporterSpec{
ReportingStrategy: "noop",
ReportTerraformOutput: true,
},
Lock: spec.LockSpec{
LockType: "noop",
},
Backend: spec.BackendSpec{
BackendHostname: jobSpec.BackendHostname,
BackendOrganisationName: jobSpec.BackendOrganisationName,
BackendJobToken: jobSpec.BackendJobToken,
BackendType: "backend",
},
VCS: spec.VcsSpec{
VcsType: "noop",
Actor: "digger",
RepoFullname: repoFullName,
RepoOwner: repoOwner,
RepoName: repoName,
WorkflowFile: workflowFile,
},
Variables: make([]spec.VariableSpec, 0),
Policy: spec.PolicySpec{
PolicyType: "http",
},
CommentUpdater: spec.CommentUpdaterSpec{
CommentUpdaterType: "noop",
},
}
runName, err := services2.GetRunNameFromJob(spec)
if err != nil {
log.Printf("Error creating ru name: %v %v", project.Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("error creating run name")})
return
}
vcsToken, err := services2.GetVCSToken("github", repoFullName, repoOwner, repoName, installationid64, mc.GithubClientProvider)
if err != nil {
log.Printf("Error creating vcs token: %v %v", project.Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("error creating vcs token")})
return
}
ciBackend, err := mc.CiBackendProvider.GetCiBackend(
ci_backends.CiBackendOptions{
GithubClientProvider: mc.GithubClientProvider,
GithubInstallationId: installationid64,
GithubAppId: githubAppId,
RepoName: repoName,
RepoOwner: repoOwner,
RepoFullName: repoFullName,
},
)
if err != nil {
log.Printf("Error creating CI backend: %v %v", project.Name, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("error creating CI backend")})
return
}
_, err = dbmodels.DB.CreateCiJobFromSpec(spec, *runName, project.ID)
if err != nil {
log.Printf("error creating the job: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Error creating job entry")})
return
}
err = ciBackend.TriggerWorkflow(spec, *runName, *vcsToken)
if err != nil {
log.Printf("TriggerWorkflow err: %v\n", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Trigger workflow error")})
return
}
}
func (mc MainController) ProcessAllDrift(c *gin.Context) {
orgSettings, err := dbmodels.DB.Query.OrgSetting.Find()
if err != nil {
log.Printf("could not select all orgs: %v", err)
}
if err != nil {
log.Printf("could not form drift url: %v", err)
c.JSON(500, gin.H{"error": "could not form drift url"})
return
}
for _, orgSetting := range orgSettings {
cron := orgSetting.Schedule
matches, err := utils2.MatchesCrontab(cron, time.Now())
if err != nil {
log.Printf("could not check matching crontab for org: %v %v", orgSetting.OrgID, err)
continue
}
if matches {
log.Printf("Crontab matched for org: %v %v", orgSetting.OrgID, cron)
err := sendProcessDriftForOrgRequest(orgSetting.OrgID)
if err != nil {
log.Printf("Failed to send request to process drift for org: %v", orgSetting.OrgID)
continue
}
} else {
log.Printf("Crontab ignored for org: %v %v", orgSetting.OrgID, cron)
}
}
c.String(200, "success")
}
func sendProcessDriftForOrgRequest(orgId string) error {
diggerHostname := os.Getenv("DIGGER_HOSTNAME")
webhookSecret := os.Getenv("DIGGER_WEBHOOK_SECRET")
payload := DriftForOrgRequest{orgId}
driftUrl, _ := url.JoinPath(diggerHostname, "_internal/process_drift_for_org")
jsonPayload, err := json.Marshal(payload)
if err != nil {
fmt.Println("Process Drift: error marshaling JSON:", err)
return err
}
req, err := http.NewRequest("POST", driftUrl, bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Process Drift: Error creating request:", err)
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", webhookSecret))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return err
}
defer resp.Body.Close()
statusCode := resp.StatusCode
if statusCode != 200 {
log.Printf("got unexpected drift status for org: %v - status: %v", orgId, statusCode)
}
return nil
}
type DriftForOrgRequest struct {
OrgId string `json:"org_id"`
}
func (mc MainController) ProcessDriftForOrg(c *gin.Context) {
diggerHostname := os.Getenv("DIGGER_HOSTNAME")
webhookSecret := os.Getenv("DIGGER_WEBHOOK_SECRET")
triggerDriftUrl, err := url.JoinPath(diggerHostname, "_internal/trigger_drift_for_project")
if err != nil {
log.Printf("could not form drift url: %v", err)
c.JSON(500, gin.H{"error": "could not form drift url"})
return
}
var request DriftForOrgRequest
err = c.BindJSON(&request)
if err != nil {
log.Printf("Error binding JSON: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error binding JSON"})
return
}
orgId := request.OrgId
log.Printf("Processing drift for org: %v", orgId)
projects, err := dbmodels.DB.LoadProjectsForOrg(orgId)
if err != nil {
fmt.Println("Process Drift: failed to load projects for org:", err)
return
}
for _, project := range projects {
if project.DriftEnabled {
projectId := project.ID
payload := TriggerDriftRunRequest{ProjectId: projectId}
// Convert payload to JSON
jsonPayload, err := json.Marshal(payload)
if err != nil {
fmt.Println("Process Drift: error marshaling JSON:", err)
return
}
// Create a new request
req, err := http.NewRequest("POST", triggerDriftUrl, bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Process Drift: Error creating request:", err)
return
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", webhookSecret))
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer resp.Body.Close()
// Get the status code
statusCode := resp.StatusCode
if statusCode != 200 {
log.Printf("got unexpected drift status for project: %v - status: %v", projectId, statusCode)
}
}
}
c.String(200, "success")
}