-
Notifications
You must be signed in to change notification settings - Fork 563
/
Copy pathmain.go
243 lines (191 loc) · 8.01 KB
/
main.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
package bootstrap
import (
"embed"
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"github.com/diggerhq/digger/backend/config"
"github.com/diggerhq/digger/backend/segment"
pprof_gin "github.com/gin-contrib/pprof"
"time"
"github.com/diggerhq/digger/backend/controllers"
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
"github.com/getsentry/sentry-go"
sentrygin "github.com/getsentry/sentry-go/gin"
"github.com/gin-contrib/sessions"
gormsessions "github.com/gin-contrib/sessions/gorm"
"github.com/gin-gonic/gin"
)
// based on https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications
var Version = "dev"
func setupProfiler(r *gin.Engine) {
// Enable pprof endpoints
pprof_gin.Register(r)
// Create profiles directory if it doesn't exist
if err := os.MkdirAll("/tmp/profiles", 0755); err != nil {
log.Fatalf("Failed to create profiles directory: %v", err)
}
// Start periodic profiling goroutine
go periodicProfiling()
}
func periodicProfiling() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Trigger GC before taking memory profile
runtime.GC()
// Create memory profile
timestamp := time.Now().Format("2006-01-02-15-04-05")
memProfilePath := filepath.Join("/tmp/profiles", fmt.Sprintf("memory-%s.pprof", timestamp))
f, err := os.Create(memProfilePath)
if err != nil {
log.Printf("Failed to create memory profile: %v", err)
continue
}
if err := pprof.WriteHeapProfile(f); err != nil {
log.Printf("Failed to write memory profile: %v", err)
}
f.Close()
// Cleanup old profiles (keep last 24)
cleanupOldProfiles("/tmp/profiles", 168)
}
}
}
func cleanupOldProfiles(dir string, keep int) {
files, err := filepath.Glob(filepath.Join(dir, "memory-*.pprof"))
if err != nil {
log.Printf("Failed to list profile files: %v", err)
return
}
if len(files) <= keep {
return
}
// Sort files by name (which includes timestamp)
for i := 0; i < len(files)-keep; i++ {
if err := os.Remove(files[i]); err != nil {
log.Printf("Failed to remove old profile %s: %v", files[i], err)
}
}
}
func Bootstrap(templates embed.FS, diggerController controllers.DiggerController) *gin.Engine {
defer segment.CloseClient()
initLogging()
cfg := config.DiggerConfig
if err := sentry.Init(sentry.ClientOptions{
Dsn: os.Getenv("SENTRY_DSN"),
EnableTracing: true,
// Set TracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production,
TracesSampleRate: 0.1,
Release: "api@" + Version,
Debug: true,
}); err != nil {
log.Printf("Sentry initialization failed: %v\n", err)
}
//database migrations
models.ConnectDatabase()
r := gin.Default()
if _, exists := os.LookupEnv("DIGGER_PPROF_DEBUG_ENABLED"); exists {
setupProfiler(r)
}
// TODO: check "secret"
store := gormsessions.NewStore(models.DB.GormDB, true, []byte("secret"))
r.Use(sessions.Sessions("digger-session", store))
r.Use(sentrygin.New(sentrygin.Options{Repanic: true}))
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"build_date": cfg.GetString("build_date"),
"deployed_at": cfg.GetString("deployed_at"),
"version": Version,
"commit_sha": Version,
})
})
r.SetFuncMap(template.FuncMap{
"formatAsDate": func(msec int64) time.Time {
return time.UnixMilli(msec)
},
})
if _, err := os.Stat("templates"); err != nil {
matches, _ := fs.Glob(templates, "templates/*.tmpl")
for _, match := range matches {
r.LoadHTMLFiles(match)
}
r.StaticFS("/static", http.FS(templates))
} else {
r.Static("/static", "./templates/static")
r.LoadHTMLGlob("templates/*.tmpl")
}
r.POST("/github-app-webhook", diggerController.GithubAppWebHook)
tenantActionsGroup := r.Group("/api/tenants")
tenantActionsGroup.Use(middleware.CORSMiddleware())
tenantActionsGroup.Any("/associateTenantIdToDiggerOrg", controllers.AssociateTenantIdToDiggerOrg)
githubGroup := r.Group("/github")
githubGroup.Use(middleware.GetWebMiddleware())
// authless endpoint because we no longer rely on orgId
r.GET("/github/callback", diggerController.GithubAppCallbackPage)
githubGroup.GET("/repos", diggerController.GithubReposPage)
githubGroup.GET("/setup", controllers.GithubAppSetup)
githubGroup.GET("/exchange-code", diggerController.GithubSetupExchangeCode)
authorized := r.Group("/")
authorized.Use(middleware.GetApiMiddleware(), middleware.AccessLevel(models.CliJobAccessType, models.AccessPolicyType, models.AdminPolicyType))
admin := r.Group("/")
admin.Use(middleware.GetApiMiddleware(), middleware.AccessLevel(models.AdminPolicyType))
fronteggWebhookProcessor := r.Group("/")
fronteggWebhookProcessor.Use(middleware.SecretCodeAuth())
authorized.GET("/repos/:repo/projects/:projectName/access-policy", controllers.FindAccessPolicy)
authorized.GET("/orgs/:organisation/access-policy", controllers.FindAccessPolicyForOrg)
authorized.GET("/repos/:repo/projects/:projectName/plan-policy", controllers.FindPlanPolicy)
authorized.GET("/orgs/:organisation/plan-policy", controllers.FindPlanPolicyForOrg)
authorized.GET("/repos/:repo/projects/:projectName/drift-policy", controllers.FindDriftPolicy)
authorized.GET("/orgs/:organisation/drift-policy", controllers.FindDriftPolicyForOrg)
authorized.GET("/repos/:repo/projects/:projectName/runs", controllers.RunHistoryForProject)
authorized.POST("/repos/:repo/projects/:projectName/runs", controllers.CreateRunForProject)
authorized.POST("/repos/:repo/projects/:projectName/jobs/:jobId/set-status", diggerController.SetJobStatusForProject)
authorized.GET("/repos/:repo/projects", controllers.FindProjectsForRepo)
authorized.POST("/repos/:repo/report-projects", controllers.ReportProjectsForRepo)
authorized.GET("/orgs/:organisation/projects", controllers.FindProjectsForOrg)
admin.PUT("/repos/:repo/projects/:projectName/access-policy", controllers.UpsertAccessPolicyForRepoAndProject)
admin.PUT("/orgs/:organisation/access-policy", controllers.UpsertAccessPolicyForOrg)
admin.PUT("/repos/:repo/projects/:projectName/plan-policy", controllers.UpsertPlanPolicyForRepoAndProject)
admin.PUT("/orgs/:organisation/plan-policy", controllers.UpsertPlanPolicyForOrg)
admin.PUT("/repos/:repo/projects/:projectName/drift-policy", controllers.UpsertDriftPolicyForRepoAndProject)
admin.PUT("/orgs/:organisation/drift-policy", controllers.UpsertDriftPolicyForOrg)
admin.POST("/tokens/issue-access-token", controllers.IssueAccessTokenForOrg)
r.Use(middleware.CORSMiddleware())
// internal endpoints not meant to be exposed to public and protected behind webhook secret
if enableInternal := os.Getenv("DIGGER_ENABLE_INTERNAL_ENDPOINTS"); enableInternal == "true" {
r.POST("_internal/update_repo_cache", middleware.InternalApiAuth(), diggerController.UpdateRepoCache)
r.POST("_internal/api/create_user", middleware.InternalApiAuth(), diggerController.CreateUserInternal)
r.POST("_internal/api/upsert_org", middleware.InternalApiAuth(), diggerController.UpsertOrgInternal)
}
if enableApi := os.Getenv("DIGGER_ENABLE_API_ENDPOINTS"); enableApi == "true" {
apiGroup := r.Group("/api")
apiGroup.Use(middleware.InternalApiAuth(), middleware.HeadersApiAuth())
reposApiGroup := apiGroup.Group("/repos")
reposApiGroup.GET("/", controllers.ListReposApi)
reposApiGroup.GET("/:repo_id/jobs", controllers.GetJobsForRepoApi)
githubApiGroup := apiGroup.Group("/github")
githubApiGroup.POST("/link", controllers.LinkGithubInstallationToOrgApi)
vcsApiGroup := apiGroup.Group("/connections")
vcsApiGroup.GET("/:id", controllers.GetVCSConnection)
vcsApiGroup.GET("/", controllers.ListVCSConnectionsApi)
vcsApiGroup.POST("/", controllers.CreateVCSConnectionApi)
vcsApiGroup.DELETE("/:id", controllers.DeleteVCSConnection)
}
return r
}
func initLogging() {
log.SetOutput(os.Stdout)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
log.Println("Initialized the logger successfully")
}