11package controllers
22
33import (
4+ "bytes"
5+ "encoding/json"
6+ "fmt"
7+ "github.com/diggerhq/digger/next/dbmodels"
8+ "github.com/diggerhq/digger/next/utils"
49 "github.com/gin-gonic/gin"
510 "log"
611 "net/http"
12+ "net/url"
13+ "os"
14+ "time"
715)
816
917type TriggerDriftRequest struct {
@@ -23,10 +31,78 @@ func (d DiggerController) TriggerDriftDetectionForProject(c *gin.Context) {
2331 }
2432 projectId := request .ProjectId
2533
34+ log .Printf ("Drift requests for project: %v" , projectId )
35+
2636 c .JSON (200 , gin.H {
2737 "status" : "successful" ,
2838 "project_id" : projectId ,
2939 })
3040 return
3141
3242}
43+
44+ func (d DiggerController ) TriggerCronForMatchingProjects (c * gin.Context ) {
45+ webhookSecret := os .Getenv ("DIGGER_WEBHOOK_SECRET" )
46+ diggerHostName := os .Getenv ("DIGGER_HOSTNAME" )
47+
48+ driftUrl , err := url .JoinPath (diggerHostName , "_internal/trigger_drift" )
49+ if err != nil {
50+ log .Printf ("could not form drift url: %v" , err )
51+ c .JSON (500 , gin.H {"error" : "could not form drift url" })
52+ return
53+ }
54+
55+ p := dbmodels .DB .Query .Project
56+ driftEnabledProjects , err := dbmodels .DB .Query .Project .Where (p .IsDriftDetectionEnabled .Is (true )).Find ()
57+ if err != nil {
58+ log .Printf ("could not fetch drift enabled projects: %v" , err )
59+ c .JSON (500 , gin.H {"error" : "could not fetch drift enabled projects" })
60+ return
61+ }
62+
63+ for _ , proj := range driftEnabledProjects {
64+ matches , err := utils .MatchesCrontab (proj .DriftCrontab , time .Now ())
65+ if err != nil {
66+ log .Printf ("could not check for matching crontab, %v" , err )
67+ // TODO: send metrics here
68+ continue
69+ }
70+
71+ if matches {
72+ payload := TriggerDriftRequest {ProjectId : proj .ID }
73+
74+ // Convert payload to JSON
75+ jsonPayload , err := json .Marshal (payload )
76+ if err != nil {
77+ fmt .Println ("Error marshaling JSON:" , err )
78+ return
79+ }
80+
81+ // Create a new request
82+ req , err := http .NewRequest ("POST" , driftUrl , bytes .NewBuffer (jsonPayload ))
83+ if err != nil {
84+ fmt .Println ("Error creating request:" , err )
85+ return
86+ }
87+
88+ // Set headers
89+ req .Header .Set ("Content-Type" , "application/json" )
90+ req .Header .Set ("Authorization" , fmt .Sprintf ("Bearer %v" , webhookSecret ))
91+
92+ // Send the request
93+ client := & http.Client {}
94+ resp , err := client .Do (req )
95+ if err != nil {
96+ fmt .Println ("Error sending request:" , err )
97+ return
98+ }
99+ defer resp .Body .Close ()
100+
101+ // Get the status code
102+ statusCode := resp .StatusCode
103+ if statusCode != 200 {
104+ log .Printf ("got unexpected drift status for project: %v - status: %v" , proj .ID , statusCode )
105+ }
106+ }
107+ }
108+ }
0 commit comments