blob: b02f7e9ac50ea142ada0ce6012b27a63d3cae4f3 [file] [log] [blame]
gio0eaf2712024-04-14 13:08:46 +04001package welcome
2
3import (
gio94904702024-07-26 16:58:34 +04004 "bytes"
gio81246f02024-07-10 12:02:15 +04005 "context"
gio23bdc1b2024-07-11 16:07:47 +04006 "embed"
gio0eaf2712024-04-14 13:08:46 +04007 "encoding/json"
gio9d66f322024-07-06 13:45:10 +04008 "errors"
gio0eaf2712024-04-14 13:08:46 +04009 "fmt"
gio23bdc1b2024-07-11 16:07:47 +040010 "html/template"
gio0eaf2712024-04-14 13:08:46 +040011 "io"
gio9d66f322024-07-06 13:45:10 +040012 "io/fs"
gio0eaf2712024-04-14 13:08:46 +040013 "net/http"
gio23bdc1b2024-07-11 16:07:47 +040014 "slices"
gio7fbd4ad2024-08-27 10:06:39 +040015 "strconv"
gio0eaf2712024-04-14 13:08:46 +040016 "strings"
gio9d66f322024-07-06 13:45:10 +040017 "sync"
giocafd4e62024-07-31 10:53:40 +040018 "time"
gio0eaf2712024-04-14 13:08:46 +040019
Davit Tabidzea5ea5092024-08-01 15:28:09 +040020 "golang.org/x/crypto/bcrypt"
21 "golang.org/x/exp/rand"
22
gio0eaf2712024-04-14 13:08:46 +040023 "github.com/giolekva/pcloud/core/installer"
24 "github.com/giolekva/pcloud/core/installer/soft"
gio43b0f422024-08-21 10:40:13 +040025 "github.com/giolekva/pcloud/core/installer/tasks"
gio33059762024-07-05 13:19:07 +040026
gio7fbd4ad2024-08-27 10:06:39 +040027 "cuelang.org/go/cue"
gio33059762024-07-05 13:19:07 +040028 "github.com/gorilla/mux"
gio81246f02024-07-10 12:02:15 +040029 "github.com/gorilla/securecookie"
gio0eaf2712024-04-14 13:08:46 +040030)
31
gio23bdc1b2024-07-11 16:07:47 +040032//go:embed dodo-app-tmpl/*
33var dodoAppTmplFS embed.FS
34
gio5e49bb62024-07-20 10:43:19 +040035//go:embed all:app-tmpl
36var appTmplsFS embed.FS
37
gioc81a8472024-09-24 13:06:19 +020038//go:embed stat/schemas/app.schema.json
39var dodoAppJsonSchema []byte
40
gio9d66f322024-07-06 13:45:10 +040041const (
gioa60f0de2024-07-08 10:49:48 +040042 ConfigRepoName = "config"
giod8ab4f52024-07-26 16:58:34 +040043 appConfigsFile = "/apps.json"
gio81246f02024-07-10 12:02:15 +040044 loginPath = "/login"
45 logoutPath = "/logout"
gio1bf00802024-08-17 12:31:41 +040046 staticPath = "/stat/"
gioc81a8472024-09-24 13:06:19 +020047 schemasPath = "/schemas/"
gio8fae3af2024-07-25 13:43:31 +040048 apiPublicData = "/api/public-data"
49 apiCreateApp = "/api/apps"
gio81246f02024-07-10 12:02:15 +040050 sessionCookie = "dodo-app-session"
51 userCtx = "user"
giob4a3a192024-08-19 09:55:47 +040052 initCommitMsg = "init"
gio9d66f322024-07-06 13:45:10 +040053)
54
gio23bdc1b2024-07-11 16:07:47 +040055type dodoAppTmplts struct {
giob4a3a192024-08-19 09:55:47 +040056 index *template.Template
57 appStatus *template.Template
58 commitStatus *template.Template
gio183e8342024-08-20 06:01:24 +040059 logs *template.Template
gio23bdc1b2024-07-11 16:07:47 +040060}
61
62func parseTemplatesDodoApp(fs embed.FS) (dodoAppTmplts, error) {
gio5e49bb62024-07-20 10:43:19 +040063 base, err := template.ParseFS(fs, "dodo-app-tmpl/base.html")
gio23bdc1b2024-07-11 16:07:47 +040064 if err != nil {
65 return dodoAppTmplts{}, err
66 }
gio5e49bb62024-07-20 10:43:19 +040067 parse := func(path string) (*template.Template, error) {
68 if b, err := base.Clone(); err != nil {
69 return nil, err
70 } else {
71 return b.ParseFS(fs, path)
72 }
73 }
74 index, err := parse("dodo-app-tmpl/index.html")
75 if err != nil {
76 return dodoAppTmplts{}, err
77 }
78 appStatus, err := parse("dodo-app-tmpl/app_status.html")
79 if err != nil {
80 return dodoAppTmplts{}, err
81 }
giob4a3a192024-08-19 09:55:47 +040082 commitStatus, err := parse("dodo-app-tmpl/commit_status.html")
83 if err != nil {
84 return dodoAppTmplts{}, err
85 }
gio183e8342024-08-20 06:01:24 +040086 logs, err := parse("dodo-app-tmpl/logs.html")
87 if err != nil {
88 return dodoAppTmplts{}, err
89 }
90 return dodoAppTmplts{index, appStatus, commitStatus, logs}, nil
gio23bdc1b2024-07-11 16:07:47 +040091}
92
gio0eaf2712024-04-14 13:08:46 +040093type DodoAppServer struct {
giocb34ad22024-07-11 08:01:13 +040094 l sync.Locker
95 st Store
gio11617ac2024-07-15 16:09:04 +040096 nf NetworkFilter
97 ug UserGetter
giocb34ad22024-07-11 08:01:13 +040098 port int
99 apiPort int
100 self string
gioc81a8472024-09-24 13:06:19 +0200101 selfPublic string
gio11617ac2024-07-15 16:09:04 +0400102 repoPublicAddr string
giocb34ad22024-07-11 08:01:13 +0400103 sshKey string
104 gitRepoPublicKey string
105 client soft.Client
106 namespace string
107 envAppManagerAddr string
108 env installer.EnvConfig
109 nsc installer.NamespaceCreator
110 jc installer.JobCreator
gio864b4332024-09-05 13:56:47 +0400111 vpnKeyGen installer.VPNAPIClient
giof6ad2982024-08-23 17:42:49 +0400112 cnc installer.ClusterNetworkConfigurator
giocb34ad22024-07-11 08:01:13 +0400113 workers map[string]map[string]struct{}
giod8ab4f52024-07-26 16:58:34 +0400114 appConfigs map[string]appConfig
gio23bdc1b2024-07-11 16:07:47 +0400115 tmplts dodoAppTmplts
gio5e49bb62024-07-20 10:43:19 +0400116 appTmpls AppTmplStore
giocafd4e62024-07-31 10:53:40 +0400117 external bool
118 fetchUsersAddr string
gio43b0f422024-08-21 10:40:13 +0400119 reconciler tasks.Reconciler
gio183e8342024-08-20 06:01:24 +0400120 logs map[string]string
giod8ab4f52024-07-26 16:58:34 +0400121}
122
123type appConfig struct {
124 Namespace string `json:"namespace"`
125 Network string `json:"network"`
gio0eaf2712024-04-14 13:08:46 +0400126}
127
gio33059762024-07-05 13:19:07 +0400128// TODO(gio): Initialize appNs on startup
gio0eaf2712024-04-14 13:08:46 +0400129func NewDodoAppServer(
gioa60f0de2024-07-08 10:49:48 +0400130 st Store,
gio11617ac2024-07-15 16:09:04 +0400131 nf NetworkFilter,
132 ug UserGetter,
gio0eaf2712024-04-14 13:08:46 +0400133 port int,
gioa60f0de2024-07-08 10:49:48 +0400134 apiPort int,
gio33059762024-07-05 13:19:07 +0400135 self string,
gioc81a8472024-09-24 13:06:19 +0200136 selfPublic string,
gio11617ac2024-07-15 16:09:04 +0400137 repoPublicAddr string,
gio0eaf2712024-04-14 13:08:46 +0400138 sshKey string,
gio33059762024-07-05 13:19:07 +0400139 gitRepoPublicKey string,
gio0eaf2712024-04-14 13:08:46 +0400140 client soft.Client,
141 namespace string,
giocb34ad22024-07-11 08:01:13 +0400142 envAppManagerAddr string,
gio33059762024-07-05 13:19:07 +0400143 nsc installer.NamespaceCreator,
giof8843412024-05-22 16:38:05 +0400144 jc installer.JobCreator,
gio864b4332024-09-05 13:56:47 +0400145 vpnKeyGen installer.VPNAPIClient,
giof6ad2982024-08-23 17:42:49 +0400146 cnc installer.ClusterNetworkConfigurator,
gio0eaf2712024-04-14 13:08:46 +0400147 env installer.EnvConfig,
giocafd4e62024-07-31 10:53:40 +0400148 external bool,
149 fetchUsersAddr string,
gio43b0f422024-08-21 10:40:13 +0400150 reconciler tasks.Reconciler,
gio9d66f322024-07-06 13:45:10 +0400151) (*DodoAppServer, error) {
gio23bdc1b2024-07-11 16:07:47 +0400152 tmplts, err := parseTemplatesDodoApp(dodoAppTmplFS)
153 if err != nil {
154 return nil, err
155 }
gio5e49bb62024-07-20 10:43:19 +0400156 apps, err := fs.Sub(appTmplsFS, "app-tmpl")
157 if err != nil {
158 return nil, err
159 }
160 appTmpls, err := NewAppTmplStoreFS(apps)
161 if err != nil {
162 return nil, err
163 }
gio9d66f322024-07-06 13:45:10 +0400164 s := &DodoAppServer{
165 &sync.Mutex{},
gioa60f0de2024-07-08 10:49:48 +0400166 st,
gio11617ac2024-07-15 16:09:04 +0400167 nf,
168 ug,
gio0eaf2712024-04-14 13:08:46 +0400169 port,
gioa60f0de2024-07-08 10:49:48 +0400170 apiPort,
gio33059762024-07-05 13:19:07 +0400171 self,
gioc81a8472024-09-24 13:06:19 +0200172 selfPublic,
gio11617ac2024-07-15 16:09:04 +0400173 repoPublicAddr,
gio0eaf2712024-04-14 13:08:46 +0400174 sshKey,
gio33059762024-07-05 13:19:07 +0400175 gitRepoPublicKey,
gio0eaf2712024-04-14 13:08:46 +0400176 client,
177 namespace,
giocb34ad22024-07-11 08:01:13 +0400178 envAppManagerAddr,
gio0eaf2712024-04-14 13:08:46 +0400179 env,
gio33059762024-07-05 13:19:07 +0400180 nsc,
giof8843412024-05-22 16:38:05 +0400181 jc,
gio36b23b32024-08-25 12:20:54 +0400182 vpnKeyGen,
giof6ad2982024-08-23 17:42:49 +0400183 cnc,
gio266c04f2024-07-03 14:18:45 +0400184 map[string]map[string]struct{}{},
giod8ab4f52024-07-26 16:58:34 +0400185 map[string]appConfig{},
gio23bdc1b2024-07-11 16:07:47 +0400186 tmplts,
gio5e49bb62024-07-20 10:43:19 +0400187 appTmpls,
giocafd4e62024-07-31 10:53:40 +0400188 external,
189 fetchUsersAddr,
gio43b0f422024-08-21 10:40:13 +0400190 reconciler,
gio183e8342024-08-20 06:01:24 +0400191 map[string]string{},
gio0eaf2712024-04-14 13:08:46 +0400192 }
gioa60f0de2024-07-08 10:49:48 +0400193 config, err := client.GetRepo(ConfigRepoName)
gio9d66f322024-07-06 13:45:10 +0400194 if err != nil {
195 return nil, err
196 }
giod8ab4f52024-07-26 16:58:34 +0400197 r, err := config.Reader(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +0400198 if err == nil {
199 defer r.Close()
giod8ab4f52024-07-26 16:58:34 +0400200 if err := json.NewDecoder(r).Decode(&s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +0400201 return nil, err
202 }
203 } else if !errors.Is(err, fs.ErrNotExist) {
204 return nil, err
205 }
206 return s, nil
gio0eaf2712024-04-14 13:08:46 +0400207}
208
gio7fbd4ad2024-08-27 10:06:39 +0400209func (s *DodoAppServer) getAppConfig(app, branch string) appConfig {
210 return s.appConfigs[fmt.Sprintf("%s-%s", app, branch)]
211}
212
213func (s *DodoAppServer) setAppConfig(app, branch string, cfg appConfig) {
214 s.appConfigs[fmt.Sprintf("%s-%s", app, branch)] = cfg
215}
216
gio0eaf2712024-04-14 13:08:46 +0400217func (s *DodoAppServer) Start() error {
gio7fbd4ad2024-08-27 10:06:39 +0400218 // if err := s.client.DisableKeyless(); err != nil {
219 // return err
220 // }
221 // if err := s.client.DisableAnonAccess(); err != nil {
222 // return err
223 // }
gioa60f0de2024-07-08 10:49:48 +0400224 e := make(chan error)
225 go func() {
226 r := mux.NewRouter()
gio81246f02024-07-10 12:02:15 +0400227 r.Use(s.mwAuth)
gioc81a8472024-09-24 13:06:19 +0200228 r.HandleFunc(schemasPath+"app.schema.json", s.handleSchema).Methods(http.MethodGet)
gio1bf00802024-08-17 12:31:41 +0400229 r.PathPrefix(staticPath).Handler(cachingHandler{http.FileServer(http.FS(statAssets))})
gio81246f02024-07-10 12:02:15 +0400230 r.HandleFunc(logoutPath, s.handleLogout).Methods(http.MethodGet)
gio8fae3af2024-07-25 13:43:31 +0400231 r.HandleFunc(apiPublicData, s.handleAPIPublicData)
232 r.HandleFunc(apiCreateApp, s.handleAPICreateApp).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400233 r.HandleFunc("/{app-name}"+loginPath, s.handleLoginForm).Methods(http.MethodGet)
234 r.HandleFunc("/{app-name}"+loginPath, s.handleLogin).Methods(http.MethodPost)
gio183e8342024-08-20 06:01:24 +0400235 r.HandleFunc("/{app-name}/logs", s.handleAppLogs).Methods(http.MethodGet)
giob4a3a192024-08-19 09:55:47 +0400236 r.HandleFunc("/{app-name}/{hash}", s.handleAppCommit).Methods(http.MethodGet)
gio7fbd4ad2024-08-27 10:06:39 +0400237 r.HandleFunc("/{app-name}/dev-branch/create", s.handleCreateDevBranch).Methods(http.MethodPost)
238 r.HandleFunc("/{app-name}/branch/{branch}", s.handleAppStatus).Methods(http.MethodGet)
gio5887caa2024-10-03 15:07:23 +0400239 r.HandleFunc("/{app-name}/branch/{branch}/delete", s.handleBranchDelete).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400240 r.HandleFunc("/{app-name}", s.handleAppStatus).Methods(http.MethodGet)
gio5887caa2024-10-03 15:07:23 +0400241 r.HandleFunc("/{app-name}/delete", s.handleAppDelete).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400242 r.HandleFunc("/", s.handleStatus).Methods(http.MethodGet)
gio11617ac2024-07-15 16:09:04 +0400243 r.HandleFunc("/", s.handleCreateApp).Methods(http.MethodPost)
gioa60f0de2024-07-08 10:49:48 +0400244 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.port), r)
245 }()
246 go func() {
247 r := mux.NewRouter()
gio8fae3af2024-07-25 13:43:31 +0400248 r.HandleFunc("/update", s.handleAPIUpdate)
249 r.HandleFunc("/api/apps/{app-name}/workers", s.handleAPIRegisterWorker).Methods(http.MethodPost)
gio7fbd4ad2024-08-27 10:06:39 +0400250 r.HandleFunc("/api/add-public-key", s.handleAPIAddPublicKey).Methods(http.MethodPost)
giocfb228c2024-09-06 15:44:31 +0400251 r.HandleFunc("/api/apps/{app-name}/branch/{branch}/env-profile", s.handleBranchEnvProfile).Methods(http.MethodGet)
giocafd4e62024-07-31 10:53:40 +0400252 if !s.external {
253 r.HandleFunc("/api/sync-users", s.handleAPISyncUsers).Methods(http.MethodGet)
254 }
gioa60f0de2024-07-08 10:49:48 +0400255 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.apiPort), r)
256 }()
giocafd4e62024-07-31 10:53:40 +0400257 if !s.external {
258 go func() {
259 s.syncUsers()
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400260 for {
261 delay := time.Duration(rand.Intn(60)+60) * time.Second
262 time.Sleep(delay)
giocafd4e62024-07-31 10:53:40 +0400263 s.syncUsers()
264 }
265 }()
266 }
gioa60f0de2024-07-08 10:49:48 +0400267 return <-e
268}
269
gio11617ac2024-07-15 16:09:04 +0400270type UserGetter interface {
271 Get(r *http.Request) string
gio8fae3af2024-07-25 13:43:31 +0400272 Encode(w http.ResponseWriter, user string) error
gio11617ac2024-07-15 16:09:04 +0400273}
274
275type externalUserGetter struct {
276 sc *securecookie.SecureCookie
277}
278
279func NewExternalUserGetter() UserGetter {
gio8fae3af2024-07-25 13:43:31 +0400280 return &externalUserGetter{securecookie.New(
281 securecookie.GenerateRandomKey(64),
282 securecookie.GenerateRandomKey(32),
283 )}
gio11617ac2024-07-15 16:09:04 +0400284}
285
286func (ug *externalUserGetter) Get(r *http.Request) string {
287 cookie, err := r.Cookie(sessionCookie)
288 if err != nil {
289 return ""
290 }
291 var user string
292 if err := ug.sc.Decode(sessionCookie, cookie.Value, &user); err != nil {
293 return ""
294 }
295 return user
296}
297
gio8fae3af2024-07-25 13:43:31 +0400298func (ug *externalUserGetter) Encode(w http.ResponseWriter, user string) error {
299 if encoded, err := ug.sc.Encode(sessionCookie, user); err == nil {
300 cookie := &http.Cookie{
301 Name: sessionCookie,
302 Value: encoded,
303 Path: "/",
304 Secure: true,
305 HttpOnly: true,
306 }
307 http.SetCookie(w, cookie)
308 return nil
309 } else {
310 return err
311 }
312}
313
gio11617ac2024-07-15 16:09:04 +0400314type internalUserGetter struct{}
315
316func NewInternalUserGetter() UserGetter {
317 return internalUserGetter{}
318}
319
320func (ug internalUserGetter) Get(r *http.Request) string {
giodd213152024-09-27 11:26:59 +0200321 return r.Header.Get("X-Forwarded-User")
gio11617ac2024-07-15 16:09:04 +0400322}
323
gio8fae3af2024-07-25 13:43:31 +0400324func (ug internalUserGetter) Encode(w http.ResponseWriter, user string) error {
325 return nil
326}
327
gio81246f02024-07-10 12:02:15 +0400328func (s *DodoAppServer) mwAuth(next http.Handler) http.Handler {
329 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400330 if strings.HasSuffix(r.URL.Path, loginPath) ||
331 strings.HasPrefix(r.URL.Path, logoutPath) ||
332 strings.HasPrefix(r.URL.Path, staticPath) ||
gioc81a8472024-09-24 13:06:19 +0200333 strings.HasPrefix(r.URL.Path, schemasPath) ||
gio8fae3af2024-07-25 13:43:31 +0400334 strings.HasPrefix(r.URL.Path, apiPublicData) ||
335 strings.HasPrefix(r.URL.Path, apiCreateApp) {
gio81246f02024-07-10 12:02:15 +0400336 next.ServeHTTP(w, r)
337 return
338 }
gio11617ac2024-07-15 16:09:04 +0400339 user := s.ug.Get(r)
340 if user == "" {
gio81246f02024-07-10 12:02:15 +0400341 vars := mux.Vars(r)
342 appName, ok := vars["app-name"]
343 if !ok || appName == "" {
344 http.Error(w, "missing app-name", http.StatusBadRequest)
345 return
346 }
347 http.Redirect(w, r, fmt.Sprintf("/%s%s", appName, loginPath), http.StatusSeeOther)
348 return
349 }
gio81246f02024-07-10 12:02:15 +0400350 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userCtx, user)))
351 })
352}
353
gioc81a8472024-09-24 13:06:19 +0200354func (s *DodoAppServer) handleSchema(w http.ResponseWriter, r *http.Request) {
355 w.Header().Set("Content-Type", "application/schema+json")
356 w.Write(dodoAppJsonSchema)
357}
358
gio81246f02024-07-10 12:02:15 +0400359func (s *DodoAppServer) handleLogout(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400360 // TODO(gio): move to UserGetter
gio81246f02024-07-10 12:02:15 +0400361 http.SetCookie(w, &http.Cookie{
362 Name: sessionCookie,
363 Value: "",
364 Path: "/",
365 HttpOnly: true,
366 Secure: true,
367 })
368 http.Redirect(w, r, "/", http.StatusSeeOther)
369}
370
371func (s *DodoAppServer) handleLoginForm(w http.ResponseWriter, r *http.Request) {
372 vars := mux.Vars(r)
373 appName, ok := vars["app-name"]
374 if !ok || appName == "" {
375 http.Error(w, "missing app-name", http.StatusBadRequest)
376 return
377 }
378 fmt.Fprint(w, `
379<!DOCTYPE html>
380<html lang='en'>
381 <head>
382 <title>dodo: app - login</title>
383 <meta charset='utf-8'>
384 </head>
385 <body>
386 <form action="" method="POST">
387 <input type="password" placeholder="Password" name="password" required />
388 <button type="submit">Login</button>
389 </form>
390 </body>
391</html>
392`)
393}
394
395func (s *DodoAppServer) handleLogin(w http.ResponseWriter, r *http.Request) {
396 vars := mux.Vars(r)
397 appName, ok := vars["app-name"]
398 if !ok || appName == "" {
399 http.Error(w, "missing app-name", http.StatusBadRequest)
400 return
401 }
402 password := r.FormValue("password")
403 if password == "" {
404 http.Error(w, "missing password", http.StatusBadRequest)
405 return
406 }
407 user, err := s.st.GetAppOwner(appName)
408 if err != nil {
409 http.Error(w, err.Error(), http.StatusInternalServerError)
410 return
411 }
412 hashed, err := s.st.GetUserPassword(user)
413 if err != nil {
414 http.Error(w, err.Error(), http.StatusInternalServerError)
415 return
416 }
417 if err := bcrypt.CompareHashAndPassword(hashed, []byte(password)); err != nil {
418 http.Redirect(w, r, r.URL.Path, http.StatusSeeOther)
419 return
420 }
gio8fae3af2024-07-25 13:43:31 +0400421 if err := s.ug.Encode(w, user); err != nil {
422 http.Error(w, err.Error(), http.StatusInternalServerError)
423 return
gio81246f02024-07-10 12:02:15 +0400424 }
425 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
426}
427
giob4a3a192024-08-19 09:55:47 +0400428type navItem struct {
429 Name string
430 Address string
431}
432
gio23bdc1b2024-07-11 16:07:47 +0400433type statusData struct {
giob4a3a192024-08-19 09:55:47 +0400434 Navigation []navItem
435 Apps []string
436 Networks []installer.Network
437 Types []string
gio23bdc1b2024-07-11 16:07:47 +0400438}
439
gioa60f0de2024-07-08 10:49:48 +0400440func (s *DodoAppServer) handleStatus(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +0400441 user := r.Context().Value(userCtx)
442 if user == nil {
443 http.Error(w, "unauthorized", http.StatusUnauthorized)
444 return
445 }
446 apps, err := s.st.GetUserApps(user.(string))
gioa60f0de2024-07-08 10:49:48 +0400447 if err != nil {
448 http.Error(w, err.Error(), http.StatusInternalServerError)
449 return
450 }
gio11617ac2024-07-15 16:09:04 +0400451 networks, err := s.getNetworks(user.(string))
452 if err != nil {
453 http.Error(w, err.Error(), http.StatusInternalServerError)
454 return
455 }
giob54db242024-07-30 18:49:33 +0400456 var types []string
457 for _, t := range s.appTmpls.Types() {
458 types = append(types, strings.Replace(t, "-", ":", 1))
459 }
giob4a3a192024-08-19 09:55:47 +0400460 n := []navItem{navItem{"Home", "/"}}
461 data := statusData{n, apps, networks, types}
gio23bdc1b2024-07-11 16:07:47 +0400462 if err := s.tmplts.index.Execute(w, data); err != nil {
463 http.Error(w, err.Error(), http.StatusInternalServerError)
464 return
gioa60f0de2024-07-08 10:49:48 +0400465 }
466}
467
gio5e49bb62024-07-20 10:43:19 +0400468type appStatusData struct {
giob4a3a192024-08-19 09:55:47 +0400469 Navigation []navItem
gio5e49bb62024-07-20 10:43:19 +0400470 Name string
gio5887caa2024-10-03 15:07:23 +0400471 Branch string
gio5e49bb62024-07-20 10:43:19 +0400472 GitCloneCommand string
giob4a3a192024-08-19 09:55:47 +0400473 Commits []CommitMeta
gio183e8342024-08-20 06:01:24 +0400474 LastCommit resourceData
gio7fbd4ad2024-08-27 10:06:39 +0400475 Branches []string
gio5e49bb62024-07-20 10:43:19 +0400476}
477
gioa60f0de2024-07-08 10:49:48 +0400478func (s *DodoAppServer) handleAppStatus(w http.ResponseWriter, r *http.Request) {
479 vars := mux.Vars(r)
480 appName, ok := vars["app-name"]
481 if !ok || appName == "" {
482 http.Error(w, "missing app-name", http.StatusBadRequest)
483 return
484 }
gio7fbd4ad2024-08-27 10:06:39 +0400485 branch, ok := vars["branch"]
486 if !ok || branch == "" {
487 branch = "master"
488 }
gio94904702024-07-26 16:58:34 +0400489 u := r.Context().Value(userCtx)
490 if u == nil {
491 http.Error(w, "unauthorized", http.StatusUnauthorized)
492 return
493 }
494 user, ok := u.(string)
495 if !ok {
496 http.Error(w, "could not get user", http.StatusInternalServerError)
497 return
498 }
499 owner, err := s.st.GetAppOwner(appName)
500 if err != nil {
501 http.Error(w, err.Error(), http.StatusInternalServerError)
502 return
503 }
504 if owner != user {
505 http.Error(w, "unauthorized", http.StatusUnauthorized)
506 return
507 }
gio7fbd4ad2024-08-27 10:06:39 +0400508 commits, err := s.st.GetCommitHistory(appName, branch)
gioa60f0de2024-07-08 10:49:48 +0400509 if err != nil {
510 http.Error(w, err.Error(), http.StatusInternalServerError)
511 return
512 }
gio183e8342024-08-20 06:01:24 +0400513 var lastCommitResources resourceData
514 if len(commits) > 0 {
515 lastCommit, err := s.st.GetCommit(commits[len(commits)-1].Hash)
516 if err != nil {
517 http.Error(w, err.Error(), http.StatusInternalServerError)
518 return
519 }
520 r, err := extractResourceData(lastCommit.Resources.Helm)
521 if err != nil {
522 http.Error(w, err.Error(), http.StatusInternalServerError)
523 return
524 }
525 lastCommitResources = r
526 }
gio7fbd4ad2024-08-27 10:06:39 +0400527 branches, err := s.st.GetBranches(appName)
528 if err != nil {
529 http.Error(w, err.Error(), http.StatusInternalServerError)
530 return
531 }
gio5e49bb62024-07-20 10:43:19 +0400532 data := appStatusData{
giob4a3a192024-08-19 09:55:47 +0400533 Navigation: []navItem{
534 navItem{"Home", "/"},
535 navItem{appName, "/" + appName},
536 },
gio5e49bb62024-07-20 10:43:19 +0400537 Name: appName,
gio5887caa2024-10-03 15:07:23 +0400538 Branch: branch,
gio5e49bb62024-07-20 10:43:19 +0400539 GitCloneCommand: fmt.Sprintf("git clone %s/%s\n\n\n", s.repoPublicAddr, appName),
540 Commits: commits,
gio183e8342024-08-20 06:01:24 +0400541 LastCommit: lastCommitResources,
gio7fbd4ad2024-08-27 10:06:39 +0400542 Branches: branches,
543 }
544 if branch != "master" {
545 data.Navigation = append(data.Navigation, navItem{branch, fmt.Sprintf("/%s/branch/%s", appName, branch)})
gio5e49bb62024-07-20 10:43:19 +0400546 }
547 if err := s.tmplts.appStatus.Execute(w, data); err != nil {
548 http.Error(w, err.Error(), http.StatusInternalServerError)
549 return
gioa60f0de2024-07-08 10:49:48 +0400550 }
gio0eaf2712024-04-14 13:08:46 +0400551}
552
giocfb228c2024-09-06 15:44:31 +0400553type appEnv struct {
554 Profile string `json:"envProfile"`
555}
556
557func (s *DodoAppServer) handleBranchEnvProfile(w http.ResponseWriter, r *http.Request) {
558 vars := mux.Vars(r)
559 appName, ok := vars["app-name"]
560 if !ok || appName == "" {
561 http.Error(w, "missing app-name", http.StatusBadRequest)
562 return
563 }
564 branch, ok := vars["branch"]
565 if !ok || branch == "" {
566 branch = "master"
567 }
568 info, err := s.st.GetLastCommitInfo(appName, branch)
569 if err != nil {
570 http.Error(w, err.Error(), http.StatusInternalServerError)
571 return
572 }
573 var e appEnv
574 if err := json.NewDecoder(bytes.NewReader(info.Resources.RenderedRaw)).Decode(&e); err != nil {
575 http.Error(w, err.Error(), http.StatusInternalServerError)
576 return
577 }
578 fmt.Fprintln(w, e.Profile)
579}
580
giob4a3a192024-08-19 09:55:47 +0400581type volume struct {
582 Name string
583 Size string
584}
585
586type postgresql struct {
587 Name string
588 Version string
589 Volume string
590}
591
592type ingress struct {
593 Host string
594}
595
gio7fbd4ad2024-08-27 10:06:39 +0400596type vm struct {
597 Name string
598 User string
599 CPUCores int
600 Memory string
601}
602
giob4a3a192024-08-19 09:55:47 +0400603type resourceData struct {
gio7fbd4ad2024-08-27 10:06:39 +0400604 Volume []volume
605 PostgreSQL []postgresql
606 Ingress []ingress
607 VirtualMachine []vm
giob4a3a192024-08-19 09:55:47 +0400608}
609
610type commitStatusData struct {
611 Navigation []navItem
612 AppName string
613 Commit Commit
614 Resources resourceData
615}
616
617func (s *DodoAppServer) handleAppCommit(w http.ResponseWriter, r *http.Request) {
618 vars := mux.Vars(r)
619 appName, ok := vars["app-name"]
620 if !ok || appName == "" {
621 http.Error(w, "missing app-name", http.StatusBadRequest)
622 return
623 }
624 hash, ok := vars["hash"]
625 if !ok || appName == "" {
626 http.Error(w, "missing app-name", http.StatusBadRequest)
627 return
628 }
629 u := r.Context().Value(userCtx)
630 if u == nil {
631 http.Error(w, "unauthorized", http.StatusUnauthorized)
632 return
633 }
634 user, ok := u.(string)
635 if !ok {
636 http.Error(w, "could not get user", http.StatusInternalServerError)
637 return
638 }
639 owner, err := s.st.GetAppOwner(appName)
640 if err != nil {
641 http.Error(w, err.Error(), http.StatusInternalServerError)
642 return
643 }
644 if owner != user {
645 http.Error(w, "unauthorized", http.StatusUnauthorized)
646 return
647 }
648 commit, err := s.st.GetCommit(hash)
649 if err != nil {
650 // TODO(gio): not-found ?
651 http.Error(w, err.Error(), http.StatusInternalServerError)
652 return
653 }
654 var res strings.Builder
655 if err := json.NewEncoder(&res).Encode(commit.Resources.Helm); err != nil {
656 http.Error(w, err.Error(), http.StatusInternalServerError)
657 return
658 }
659 resData, err := extractResourceData(commit.Resources.Helm)
660 if err != nil {
661 http.Error(w, err.Error(), http.StatusInternalServerError)
662 return
663 }
664 data := commitStatusData{
665 Navigation: []navItem{
666 navItem{"Home", "/"},
667 navItem{appName, "/" + appName},
668 navItem{hash, "/" + appName + "/" + hash},
669 },
670 AppName: appName,
671 Commit: commit,
672 Resources: resData,
673 }
674 if err := s.tmplts.commitStatus.Execute(w, data); err != nil {
675 http.Error(w, err.Error(), http.StatusInternalServerError)
676 return
677 }
678}
679
gio183e8342024-08-20 06:01:24 +0400680type logData struct {
681 Navigation []navItem
682 AppName string
683 Logs template.HTML
684}
685
686func (s *DodoAppServer) handleAppLogs(w http.ResponseWriter, r *http.Request) {
687 vars := mux.Vars(r)
688 appName, ok := vars["app-name"]
689 if !ok || appName == "" {
690 http.Error(w, "missing app-name", http.StatusBadRequest)
691 return
692 }
693 u := r.Context().Value(userCtx)
694 if u == nil {
695 http.Error(w, "unauthorized", http.StatusUnauthorized)
696 return
697 }
698 user, ok := u.(string)
699 if !ok {
700 http.Error(w, "could not get user", http.StatusInternalServerError)
701 return
702 }
703 owner, err := s.st.GetAppOwner(appName)
704 if err != nil {
705 http.Error(w, err.Error(), http.StatusInternalServerError)
706 return
707 }
708 if owner != user {
709 http.Error(w, "unauthorized", http.StatusUnauthorized)
710 return
711 }
712 data := logData{
713 Navigation: []navItem{
714 navItem{"Home", "/"},
715 navItem{appName, "/" + appName},
716 navItem{"Logs", "/" + appName + "/logs"},
717 },
718 AppName: appName,
719 Logs: template.HTML(strings.ReplaceAll(s.logs[appName], "\n", "<br/>")),
720 }
721 if err := s.tmplts.logs.Execute(w, data); err != nil {
722 fmt.Println(err)
723 http.Error(w, err.Error(), http.StatusInternalServerError)
724 return
725 }
726}
727
gio81246f02024-07-10 12:02:15 +0400728type apiUpdateReq struct {
gio266c04f2024-07-03 14:18:45 +0400729 Ref string `json:"ref"`
730 Repository struct {
731 Name string `json:"name"`
732 } `json:"repository"`
gioe2e31e12024-08-18 08:20:56 +0400733 After string `json:"after"`
734 Commits []struct {
735 Id string `json:"id"`
736 Message string `json:"message"`
737 } `json:"commits"`
gio0eaf2712024-04-14 13:08:46 +0400738}
739
gio8fae3af2024-07-25 13:43:31 +0400740func (s *DodoAppServer) handleAPIUpdate(w http.ResponseWriter, r *http.Request) {
gio0eaf2712024-04-14 13:08:46 +0400741 fmt.Println("update")
gio81246f02024-07-10 12:02:15 +0400742 var req apiUpdateReq
gio0eaf2712024-04-14 13:08:46 +0400743 var contents strings.Builder
744 io.Copy(&contents, r.Body)
745 c := contents.String()
746 fmt.Println(c)
747 if err := json.NewDecoder(strings.NewReader(c)).Decode(&req); err != nil {
gio23bdc1b2024-07-11 16:07:47 +0400748 http.Error(w, err.Error(), http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400749 return
750 }
gio7fbd4ad2024-08-27 10:06:39 +0400751 if strings.HasPrefix(req.Ref, "refs/heads/dodo_") || req.Repository.Name == ConfigRepoName {
752 return
753 }
754 branch, ok := strings.CutPrefix(req.Ref, "refs/heads/")
755 if !ok {
756 http.Error(w, "invalid branch", http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400757 return
758 }
gioa60f0de2024-07-08 10:49:48 +0400759 // TODO(gio): Create commit record on app init as well
gio0eaf2712024-04-14 13:08:46 +0400760 go func() {
gio11617ac2024-07-15 16:09:04 +0400761 owner, err := s.st.GetAppOwner(req.Repository.Name)
762 if err != nil {
763 return
764 }
765 networks, err := s.getNetworks(owner)
giocb34ad22024-07-11 08:01:13 +0400766 if err != nil {
767 return
768 }
giof15b9da2024-09-19 06:59:16 +0400769 // TODO(gio): get only available ones by owner
770 clusters, err := s.getClusters()
771 if err != nil {
772 return
773 }
gio94904702024-07-26 16:58:34 +0400774 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
775 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
776 if err != nil {
777 return
778 }
gioe2e31e12024-08-18 08:20:56 +0400779 found := false
780 commitMsg := ""
781 for _, c := range req.Commits {
782 if c.Id == req.After {
783 found = true
784 commitMsg = c.Message
785 break
gioa60f0de2024-07-08 10:49:48 +0400786 }
787 }
gioe2e31e12024-08-18 08:20:56 +0400788 if !found {
789 fmt.Printf("Error: could not find commit message")
790 return
791 }
gio7fbd4ad2024-08-27 10:06:39 +0400792 s.l.Lock()
793 defer s.l.Unlock()
giof15b9da2024-09-19 06:59:16 +0400794 resources, err := s.updateDodoApp(instanceAppStatus, req.Repository.Name, branch, s.getAppConfig(req.Repository.Name, branch).Namespace, networks, clusters, owner)
gio7fbd4ad2024-08-27 10:06:39 +0400795 if err = s.createCommit(req.Repository.Name, branch, req.After, commitMsg, err, resources); err != nil {
gio12e887d2024-08-18 16:09:47 +0400796 fmt.Printf("Error: %s\n", err.Error())
gioe2e31e12024-08-18 08:20:56 +0400797 return
798 }
gioa60f0de2024-07-08 10:49:48 +0400799 for addr, _ := range s.workers[req.Repository.Name] {
800 go func() {
801 // TODO(gio): make port configurable
802 http.Get(fmt.Sprintf("http://%s/update", addr))
803 }()
gio0eaf2712024-04-14 13:08:46 +0400804 }
805 }()
gio0eaf2712024-04-14 13:08:46 +0400806}
807
gio81246f02024-07-10 12:02:15 +0400808type apiRegisterWorkerReq struct {
gio0eaf2712024-04-14 13:08:46 +0400809 Address string `json:"address"`
gio183e8342024-08-20 06:01:24 +0400810 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400811}
812
gio8fae3af2024-07-25 13:43:31 +0400813func (s *DodoAppServer) handleAPIRegisterWorker(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400814 // TODO(gio): lock
gioa60f0de2024-07-08 10:49:48 +0400815 vars := mux.Vars(r)
816 appName, ok := vars["app-name"]
817 if !ok || appName == "" {
818 http.Error(w, "missing app-name", http.StatusBadRequest)
819 return
820 }
gio81246f02024-07-10 12:02:15 +0400821 var req apiRegisterWorkerReq
gio0eaf2712024-04-14 13:08:46 +0400822 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
823 http.Error(w, err.Error(), http.StatusInternalServerError)
824 return
825 }
gioa60f0de2024-07-08 10:49:48 +0400826 if _, ok := s.workers[appName]; !ok {
827 s.workers[appName] = map[string]struct{}{}
gio266c04f2024-07-03 14:18:45 +0400828 }
gioa60f0de2024-07-08 10:49:48 +0400829 s.workers[appName][req.Address] = struct{}{}
gio183e8342024-08-20 06:01:24 +0400830 s.logs[appName] = req.Logs
gio0eaf2712024-04-14 13:08:46 +0400831}
832
gio11617ac2024-07-15 16:09:04 +0400833func (s *DodoAppServer) handleCreateApp(w http.ResponseWriter, r *http.Request) {
834 u := r.Context().Value(userCtx)
835 if u == nil {
836 http.Error(w, "unauthorized", http.StatusUnauthorized)
837 return
838 }
839 user, ok := u.(string)
840 if !ok {
841 http.Error(w, "could not get user", http.StatusInternalServerError)
842 return
843 }
844 network := r.FormValue("network")
845 if network == "" {
846 http.Error(w, "missing network", http.StatusBadRequest)
847 return
848 }
gio5e49bb62024-07-20 10:43:19 +0400849 subdomain := r.FormValue("subdomain")
850 if subdomain == "" {
851 http.Error(w, "missing subdomain", http.StatusBadRequest)
852 return
853 }
854 appType := r.FormValue("type")
855 if appType == "" {
856 http.Error(w, "missing type", http.StatusBadRequest)
857 return
858 }
gio11617ac2024-07-15 16:09:04 +0400859 g := installer.NewFixedLengthRandomNameGenerator(3)
860 appName, err := g.Generate()
861 if err != nil {
862 http.Error(w, err.Error(), http.StatusInternalServerError)
863 return
864 }
865 if ok, err := s.client.UserExists(user); err != nil {
866 http.Error(w, err.Error(), http.StatusInternalServerError)
867 return
868 } else if !ok {
giocafd4e62024-07-31 10:53:40 +0400869 http.Error(w, "user sync has not finished, please try again in few minutes", http.StatusFailedDependency)
870 return
gio11617ac2024-07-15 16:09:04 +0400871 }
giocafd4e62024-07-31 10:53:40 +0400872 if err := s.st.CreateUser(user, nil, network); err != nil && !errors.Is(err, ErrorAlreadyExists) {
gio11617ac2024-07-15 16:09:04 +0400873 http.Error(w, err.Error(), http.StatusInternalServerError)
874 return
875 }
876 if err := s.st.CreateApp(appName, user); err != nil {
877 http.Error(w, err.Error(), http.StatusInternalServerError)
878 return
879 }
giod8ab4f52024-07-26 16:58:34 +0400880 if err := s.createApp(user, appName, appType, network, subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +0400881 http.Error(w, err.Error(), http.StatusInternalServerError)
882 return
883 }
884 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
885}
886
gio7fbd4ad2024-08-27 10:06:39 +0400887func (s *DodoAppServer) handleCreateDevBranch(w http.ResponseWriter, r *http.Request) {
888 u := r.Context().Value(userCtx)
889 if u == nil {
890 http.Error(w, "unauthorized", http.StatusUnauthorized)
891 return
892 }
893 user, ok := u.(string)
894 if !ok {
895 http.Error(w, "could not get user", http.StatusInternalServerError)
896 return
897 }
898 vars := mux.Vars(r)
899 appName, ok := vars["app-name"]
900 if !ok || appName == "" {
901 http.Error(w, "missing app-name", http.StatusBadRequest)
902 return
903 }
904 branch := r.FormValue("branch")
905 if branch == "" {
gio5887caa2024-10-03 15:07:23 +0400906 http.Error(w, "missing branch", http.StatusBadRequest)
gio7fbd4ad2024-08-27 10:06:39 +0400907 return
908 }
909 if err := s.createDevBranch(appName, "master", branch, user); err != nil {
910 http.Error(w, err.Error(), http.StatusInternalServerError)
911 return
912 }
913 http.Redirect(w, r, fmt.Sprintf("/%s/branch/%s", appName, branch), http.StatusSeeOther)
914}
915
gio5887caa2024-10-03 15:07:23 +0400916func (s *DodoAppServer) handleBranchDelete(w http.ResponseWriter, r *http.Request) {
917 u := r.Context().Value(userCtx)
918 if u == nil {
919 http.Error(w, "unauthorized", http.StatusUnauthorized)
920 return
921 }
922 vars := mux.Vars(r)
923 appName, ok := vars["app-name"]
924 if !ok || appName == "" {
925 http.Error(w, "missing app-name", http.StatusBadRequest)
926 return
927 }
928 branch, ok := vars["branch"]
929 if !ok || branch == "" {
930 http.Error(w, "missing branch", http.StatusBadRequest)
931 return
932 }
933 if err := s.deleteBranch(appName, branch); err != nil {
934 http.Error(w, err.Error(), http.StatusInternalServerError)
935 return
936 }
937 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
938}
939
940func (s *DodoAppServer) handleAppDelete(w http.ResponseWriter, r *http.Request) {
941 u := r.Context().Value(userCtx)
942 if u == nil {
943 http.Error(w, "unauthorized", http.StatusUnauthorized)
944 return
945 }
946 vars := mux.Vars(r)
947 appName, ok := vars["app-name"]
948 if !ok || appName == "" {
949 http.Error(w, "missing app-name", http.StatusBadRequest)
950 return
951 }
952 if err := s.deleteApp(appName); err != nil {
953 http.Error(w, err.Error(), http.StatusInternalServerError)
954 return
955 }
956 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
957}
958
gio81246f02024-07-10 12:02:15 +0400959type apiCreateAppReq struct {
gio5e49bb62024-07-20 10:43:19 +0400960 AppType string `json:"type"`
gio33059762024-07-05 13:19:07 +0400961 AdminPublicKey string `json:"adminPublicKey"`
gio11617ac2024-07-15 16:09:04 +0400962 Network string `json:"network"`
gio5e49bb62024-07-20 10:43:19 +0400963 Subdomain string `json:"subdomain"`
gio33059762024-07-05 13:19:07 +0400964}
965
gio81246f02024-07-10 12:02:15 +0400966type apiCreateAppResp struct {
967 AppName string `json:"appName"`
968 Password string `json:"password"`
gio33059762024-07-05 13:19:07 +0400969}
970
gio8fae3af2024-07-25 13:43:31 +0400971func (s *DodoAppServer) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +0400972 w.Header().Set("Access-Control-Allow-Origin", "*")
gio81246f02024-07-10 12:02:15 +0400973 var req apiCreateAppReq
gio33059762024-07-05 13:19:07 +0400974 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
975 http.Error(w, err.Error(), http.StatusBadRequest)
976 return
977 }
978 g := installer.NewFixedLengthRandomNameGenerator(3)
979 appName, err := g.Generate()
980 if err != nil {
981 http.Error(w, err.Error(), http.StatusInternalServerError)
982 return
983 }
gio11617ac2024-07-15 16:09:04 +0400984 user, err := s.client.FindUser(req.AdminPublicKey)
gio81246f02024-07-10 12:02:15 +0400985 if err != nil {
gio33059762024-07-05 13:19:07 +0400986 http.Error(w, err.Error(), http.StatusInternalServerError)
987 return
988 }
gio11617ac2024-07-15 16:09:04 +0400989 if user != "" {
990 http.Error(w, "public key already registered", http.StatusBadRequest)
991 return
992 }
993 user = appName
994 if err := s.client.AddUser(user, req.AdminPublicKey); err != nil {
995 http.Error(w, err.Error(), http.StatusInternalServerError)
996 return
997 }
998 password := generatePassword()
999 hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
1000 if err != nil {
1001 http.Error(w, err.Error(), http.StatusInternalServerError)
1002 return
1003 }
giocafd4e62024-07-31 10:53:40 +04001004 if err := s.st.CreateUser(user, hashed, req.Network); err != nil {
gio11617ac2024-07-15 16:09:04 +04001005 http.Error(w, err.Error(), http.StatusInternalServerError)
1006 return
1007 }
1008 if err := s.st.CreateApp(appName, user); err != nil {
1009 http.Error(w, err.Error(), http.StatusInternalServerError)
1010 return
1011 }
giod8ab4f52024-07-26 16:58:34 +04001012 if err := s.createApp(user, appName, req.AppType, req.Network, req.Subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +04001013 http.Error(w, err.Error(), http.StatusInternalServerError)
1014 return
1015 }
gio81246f02024-07-10 12:02:15 +04001016 resp := apiCreateAppResp{
1017 AppName: appName,
1018 Password: password,
1019 }
gio33059762024-07-05 13:19:07 +04001020 if err := json.NewEncoder(w).Encode(resp); err != nil {
1021 http.Error(w, err.Error(), http.StatusInternalServerError)
1022 return
1023 }
1024}
1025
giod8ab4f52024-07-26 16:58:34 +04001026func (s *DodoAppServer) isNetworkUseAllowed(network string) bool {
giocafd4e62024-07-31 10:53:40 +04001027 if !s.external {
giod8ab4f52024-07-26 16:58:34 +04001028 return true
1029 }
1030 for _, cfg := range s.appConfigs {
1031 if strings.ToLower(cfg.Network) == network {
1032 return false
1033 }
1034 }
1035 return true
1036}
1037
1038func (s *DodoAppServer) createApp(user, appName, appType, network, subdomain string) error {
gio9d66f322024-07-06 13:45:10 +04001039 s.l.Lock()
1040 defer s.l.Unlock()
gio33059762024-07-05 13:19:07 +04001041 fmt.Printf("Creating app: %s\n", appName)
giod8ab4f52024-07-26 16:58:34 +04001042 network = strings.ToLower(network)
1043 if !s.isNetworkUseAllowed(network) {
1044 return fmt.Errorf("network already used: %s", network)
1045 }
gio33059762024-07-05 13:19:07 +04001046 if ok, err := s.client.RepoExists(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001047 return err
gio33059762024-07-05 13:19:07 +04001048 } else if ok {
gio11617ac2024-07-15 16:09:04 +04001049 return nil
gioa60f0de2024-07-08 10:49:48 +04001050 }
gio5e49bb62024-07-20 10:43:19 +04001051 networks, err := s.getNetworks(user)
1052 if err != nil {
1053 return err
1054 }
giod8ab4f52024-07-26 16:58:34 +04001055 n, ok := installer.NetworkMap(networks)[network]
gio5e49bb62024-07-20 10:43:19 +04001056 if !ok {
1057 return fmt.Errorf("network not found: %s\n", network)
1058 }
gio33059762024-07-05 13:19:07 +04001059 if err := s.client.AddRepository(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001060 return err
gio33059762024-07-05 13:19:07 +04001061 }
1062 appRepo, err := s.client.GetRepo(appName)
1063 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001064 return err
gio33059762024-07-05 13:19:07 +04001065 }
gio7fbd4ad2024-08-27 10:06:39 +04001066 files, err := s.renderAppConfigTemplate(appType, n, subdomain)
1067 if err != nil {
1068 return err
1069 }
1070 return s.createAppForBranch(appRepo, appName, "master", user, network, files)
1071}
1072
1073func (s *DodoAppServer) createDevBranch(appName, fromBranch, toBranch, user string) error {
1074 s.l.Lock()
1075 defer s.l.Unlock()
1076 fmt.Printf("Creating dev branch app: %s %s %s\n", appName, fromBranch, toBranch)
1077 appRepo, err := s.client.GetRepoBranch(appName, fromBranch)
1078 if err != nil {
1079 return err
1080 }
gioc81a8472024-09-24 13:06:19 +02001081 appCfg, err := soft.ReadFile(appRepo, "app.json")
gio7fbd4ad2024-08-27 10:06:39 +04001082 if err != nil {
1083 return err
1084 }
1085 network, branchCfg, err := createDevBranchAppConfig(appCfg, toBranch, user)
1086 if err != nil {
1087 return err
1088 }
gioc81a8472024-09-24 13:06:19 +02001089 return s.createAppForBranch(appRepo, appName, toBranch, user, network, map[string][]byte{"app.json": branchCfg})
gio7fbd4ad2024-08-27 10:06:39 +04001090}
1091
gio5887caa2024-10-03 15:07:23 +04001092func (s *DodoAppServer) deleteBranch(appName string, branch string) error {
1093 appBranch := fmt.Sprintf("dodo_%s", branch)
1094 hf := installer.NewGitHelmFetcher()
1095 if err := func() error {
1096 repo, err := s.client.GetRepoBranch(appName, appBranch)
1097 if err != nil {
1098 return err
1099 }
1100 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
1101 if err != nil {
1102 return err
1103 }
1104 return m.Remove("app")
1105 }(); err != nil {
1106 return err
1107 }
1108 configRepo, err := s.client.GetRepo(ConfigRepoName)
1109 if err != nil {
1110 return err
1111 }
1112 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
1113 if err != nil {
1114 return err
1115 }
1116 appPath := fmt.Sprintf("%s/%s", appName, branch)
gio829b1b72024-10-05 21:50:56 +04001117 if err := m.Remove(appPath); err != nil {
gio5887caa2024-10-03 15:07:23 +04001118 return err
1119 }
1120 if err := s.client.DeleteRepoBranch(appName, appBranch); err != nil {
1121 return err
1122 }
1123 if branch != "master" {
1124 return s.client.DeleteRepoBranch(appName, branch)
1125 }
1126 return nil
1127}
1128
1129func (s *DodoAppServer) deleteApp(appName string) error {
1130 configRepo, err := s.client.GetRepo(ConfigRepoName)
1131 if err != nil {
1132 return err
1133 }
1134 branches, err := configRepo.ListDir(fmt.Sprintf("/%s", appName))
1135 if err != nil {
1136 return err
1137 }
1138 for _, b := range branches {
1139 if !b.IsDir() || strings.HasPrefix(b.Name(), "dodo_") {
1140 continue
1141 }
1142 if err := s.deleteBranch(appName, b.Name()); err != nil {
1143 return err
1144 }
1145 }
1146 return s.client.DeleteRepo(appName)
1147}
1148
gio7fbd4ad2024-08-27 10:06:39 +04001149func (s *DodoAppServer) createAppForBranch(
1150 repo soft.RepoIO,
1151 appName string,
1152 branch string,
1153 user string,
1154 network string,
1155 files map[string][]byte,
1156) error {
1157 commit, err := repo.Do(func(fs soft.RepoFS) (string, error) {
1158 for path, contents := range files {
1159 if err := soft.WriteFile(fs, path, string(contents)); err != nil {
1160 return "", err
1161 }
1162 }
1163 return "init", nil
1164 }, soft.WithCommitToBranch(branch))
1165 if err != nil {
1166 return err
1167 }
1168 networks, err := s.getNetworks(user)
giob4a3a192024-08-19 09:55:47 +04001169 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001170 return err
gio33059762024-07-05 13:19:07 +04001171 }
giof15b9da2024-09-19 06:59:16 +04001172 // TODO(gio): get only available ones by owner
1173 clusters, err := s.getClusters()
1174 if err != nil {
1175 return err
1176 }
gio33059762024-07-05 13:19:07 +04001177 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
gio94904702024-07-26 16:58:34 +04001178 instanceApp, err := installer.FindEnvApp(apps, "dodo-app-instance")
1179 if err != nil {
1180 return err
1181 }
1182 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
gio33059762024-07-05 13:19:07 +04001183 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001184 return err
gio33059762024-07-05 13:19:07 +04001185 }
1186 suffixGen := installer.NewFixedLengthRandomSuffixGenerator(3)
1187 suffix, err := suffixGen.Generate()
1188 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001189 return err
gio33059762024-07-05 13:19:07 +04001190 }
gio94904702024-07-26 16:58:34 +04001191 namespace := fmt.Sprintf("%s%s%s", s.env.NamespacePrefix, instanceApp.Namespace(), suffix)
gio7fbd4ad2024-08-27 10:06:39 +04001192 s.setAppConfig(appName, branch, appConfig{namespace, network})
giof15b9da2024-09-19 06:59:16 +04001193 resources, err := s.updateDodoApp(instanceAppStatus, appName, branch, namespace, networks, clusters, user)
giob4a3a192024-08-19 09:55:47 +04001194 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001195 fmt.Printf("Error: %s\n", err.Error())
giob4a3a192024-08-19 09:55:47 +04001196 return err
1197 }
gio7fbd4ad2024-08-27 10:06:39 +04001198 if err = s.createCommit(appName, branch, commit, initCommitMsg, err, resources); err != nil {
giob4a3a192024-08-19 09:55:47 +04001199 fmt.Printf("Error: %s\n", err.Error())
gio11617ac2024-07-15 16:09:04 +04001200 return err
gio33059762024-07-05 13:19:07 +04001201 }
giod8ab4f52024-07-26 16:58:34 +04001202 configRepo, err := s.client.GetRepo(ConfigRepoName)
gio33059762024-07-05 13:19:07 +04001203 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001204 return err
gio33059762024-07-05 13:19:07 +04001205 }
1206 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001207 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
gio33059762024-07-05 13:19:07 +04001208 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001209 return err
gio33059762024-07-05 13:19:07 +04001210 }
gio7fbd4ad2024-08-27 10:06:39 +04001211 appPath := fmt.Sprintf("/%s/%s", appName, branch)
giob4a3a192024-08-19 09:55:47 +04001212 _, err = configRepo.Do(func(fs soft.RepoFS) (string, error) {
giod8ab4f52024-07-26 16:58:34 +04001213 w, err := fs.Writer(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +04001214 if err != nil {
1215 return "", err
1216 }
1217 defer w.Close()
giod8ab4f52024-07-26 16:58:34 +04001218 if err := json.NewEncoder(w).Encode(s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +04001219 return "", err
1220 }
1221 if _, err := m.Install(
gio94904702024-07-26 16:58:34 +04001222 instanceApp,
gio9d66f322024-07-06 13:45:10 +04001223 appName,
gio7fbd4ad2024-08-27 10:06:39 +04001224 appPath,
gio9d66f322024-07-06 13:45:10 +04001225 namespace,
1226 map[string]any{
1227 "repoAddr": s.client.GetRepoAddress(appName),
1228 "repoHost": strings.Split(s.client.Address(), ":")[0],
gio7fbd4ad2024-08-27 10:06:39 +04001229 "branch": fmt.Sprintf("dodo_%s", branch),
gio9d66f322024-07-06 13:45:10 +04001230 "gitRepoPublicKey": s.gitRepoPublicKey,
1231 },
1232 installer.WithConfig(&s.env),
gio23bdc1b2024-07-11 16:07:47 +04001233 installer.WithNoNetworks(),
gio9d66f322024-07-06 13:45:10 +04001234 installer.WithNoPublish(),
1235 installer.WithNoLock(),
1236 ); err != nil {
1237 return "", err
1238 }
1239 return fmt.Sprintf("Installed app: %s", appName), nil
giob4a3a192024-08-19 09:55:47 +04001240 })
1241 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001242 return err
gio33059762024-07-05 13:19:07 +04001243 }
gio7fbd4ad2024-08-27 10:06:39 +04001244 return s.initAppACLs(m, appPath, appName, branch, user)
1245}
1246
1247func (s *DodoAppServer) initAppACLs(m *installer.AppManager, path, appName, branch, user string) error {
1248 cfg, err := m.GetInstance(path)
gio33059762024-07-05 13:19:07 +04001249 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001250 return err
gio33059762024-07-05 13:19:07 +04001251 }
1252 fluxKeys, ok := cfg.Input["fluxKeys"]
1253 if !ok {
gio11617ac2024-07-15 16:09:04 +04001254 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001255 }
1256 fluxPublicKey, ok := fluxKeys.(map[string]any)["public"]
1257 if !ok {
gio11617ac2024-07-15 16:09:04 +04001258 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001259 }
1260 if ok, err := s.client.UserExists("fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001261 return err
gio33059762024-07-05 13:19:07 +04001262 } else if ok {
1263 if err := s.client.AddPublicKey("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001264 return err
gio33059762024-07-05 13:19:07 +04001265 }
1266 } else {
1267 if err := s.client.AddUser("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001268 return err
gio33059762024-07-05 13:19:07 +04001269 }
1270 }
gio7fbd4ad2024-08-27 10:06:39 +04001271 if branch != "master" {
1272 return nil
1273 }
gio33059762024-07-05 13:19:07 +04001274 if err := s.client.AddReadOnlyCollaborator(appName, "fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001275 return err
gio33059762024-07-05 13:19:07 +04001276 }
gio7fbd4ad2024-08-27 10:06:39 +04001277 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
gio11617ac2024-07-15 16:09:04 +04001278 return err
gio33059762024-07-05 13:19:07 +04001279 }
gio7fbd4ad2024-08-27 10:06:39 +04001280 if err := s.client.AddWebhook(appName, fmt.Sprintf("http://%s/update", s.self), "--active=true", "--events=push", "--content-type=json"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001281 return err
gio33059762024-07-05 13:19:07 +04001282 }
gio2ccb6e32024-08-15 12:01:33 +04001283 if !s.external {
1284 go func() {
1285 users, err := s.client.GetAllUsers()
1286 if err != nil {
1287 fmt.Println(err)
1288 return
1289 }
1290 for _, user := range users {
1291 // TODO(gio): fluxcd should have only read access
1292 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
1293 fmt.Println(err)
1294 }
1295 }
1296 }()
1297 }
gio43b0f422024-08-21 10:40:13 +04001298 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1299 go s.reconciler.Reconcile(ctx, s.namespace, "config")
gio11617ac2024-07-15 16:09:04 +04001300 return nil
gio33059762024-07-05 13:19:07 +04001301}
1302
gio81246f02024-07-10 12:02:15 +04001303type apiAddAdminKeyReq struct {
gio7fbd4ad2024-08-27 10:06:39 +04001304 User string `json:"user"`
1305 PublicKey string `json:"publicKey"`
gio70be3e52024-06-26 18:27:19 +04001306}
1307
gio7fbd4ad2024-08-27 10:06:39 +04001308func (s *DodoAppServer) handleAPIAddPublicKey(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +04001309 var req apiAddAdminKeyReq
gio70be3e52024-06-26 18:27:19 +04001310 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1311 http.Error(w, err.Error(), http.StatusBadRequest)
1312 return
1313 }
gio7fbd4ad2024-08-27 10:06:39 +04001314 if req.User == "" {
1315 http.Error(w, "invalid user", http.StatusBadRequest)
1316 return
1317 }
1318 if req.PublicKey == "" {
1319 http.Error(w, "invalid public key", http.StatusBadRequest)
1320 return
1321 }
1322 if err := s.client.AddPublicKey(req.User, req.PublicKey); err != nil {
gio70be3e52024-06-26 18:27:19 +04001323 http.Error(w, err.Error(), http.StatusInternalServerError)
1324 return
1325 }
1326}
1327
gio94904702024-07-26 16:58:34 +04001328type dodoAppRendered struct {
1329 App struct {
1330 Ingress struct {
1331 Network string `json:"network"`
1332 Subdomain string `json:"subdomain"`
1333 } `json:"ingress"`
1334 } `json:"app"`
1335 Input struct {
1336 AppId string `json:"appId"`
1337 } `json:"input"`
1338}
1339
gio7fbd4ad2024-08-27 10:06:39 +04001340// TODO(gio): must not require owner, now we need it to bootstrap dev vm.
gio43b0f422024-08-21 10:40:13 +04001341func (s *DodoAppServer) updateDodoApp(
1342 appStatus installer.EnvApp,
gio7fbd4ad2024-08-27 10:06:39 +04001343 name string,
1344 branch string,
1345 namespace string,
gio43b0f422024-08-21 10:40:13 +04001346 networks []installer.Network,
giof15b9da2024-09-19 06:59:16 +04001347 clusters []installer.Cluster,
gio7fbd4ad2024-08-27 10:06:39 +04001348 owner string,
gio43b0f422024-08-21 10:40:13 +04001349) (installer.ReleaseResources, error) {
gio7fbd4ad2024-08-27 10:06:39 +04001350 repo, err := s.client.GetRepoBranch(name, branch)
gio0eaf2712024-04-14 13:08:46 +04001351 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001352 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001353 }
giof8843412024-05-22 16:38:05 +04001354 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001355 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
gio0eaf2712024-04-14 13:08:46 +04001356 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001357 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001358 }
gioc81a8472024-09-24 13:06:19 +02001359 appCfg, err := soft.ReadFile(repo, "app.json")
gio0eaf2712024-04-14 13:08:46 +04001360 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001361 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001362 }
1363 app, err := installer.NewDodoApp(appCfg)
1364 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001365 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001366 }
giof8843412024-05-22 16:38:05 +04001367 lg := installer.GitRepositoryLocalChartGenerator{"app", namespace}
giob4a3a192024-08-19 09:55:47 +04001368 var ret installer.ReleaseResources
1369 if _, err := repo.Do(func(r soft.RepoFS) (string, error) {
1370 ret, err = m.Install(
gio94904702024-07-26 16:58:34 +04001371 app,
1372 "app",
1373 "/.dodo/app",
1374 namespace,
1375 map[string]any{
gio7fbd4ad2024-08-27 10:06:39 +04001376 "repoAddr": repo.FullAddress(),
1377 "repoPublicAddr": s.repoPublicAddr,
1378 "managerAddr": fmt.Sprintf("http://%s", s.self),
1379 "appId": name,
1380 "branch": branch,
1381 "sshPrivateKey": s.sshKey,
1382 "username": owner,
gio94904702024-07-26 16:58:34 +04001383 },
1384 installer.WithNoPull(),
1385 installer.WithNoPublish(),
1386 installer.WithConfig(&s.env),
1387 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001388 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001389 installer.WithLocalChartGenerator(lg),
1390 installer.WithNoLock(),
1391 )
1392 if err != nil {
1393 return "", err
1394 }
1395 var rendered dodoAppRendered
giob4a3a192024-08-19 09:55:47 +04001396 if err := json.NewDecoder(bytes.NewReader(ret.RenderedRaw)).Decode(&rendered); err != nil {
gio94904702024-07-26 16:58:34 +04001397 return "", nil
1398 }
1399 if _, err := m.Install(
1400 appStatus,
1401 "status",
1402 "/.dodo/status",
1403 s.namespace,
1404 map[string]any{
1405 "appName": rendered.Input.AppId,
1406 "network": rendered.App.Ingress.Network,
1407 "appSubdomain": rendered.App.Ingress.Subdomain,
1408 },
1409 installer.WithNoPull(),
1410 installer.WithNoPublish(),
1411 installer.WithConfig(&s.env),
1412 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001413 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001414 installer.WithLocalChartGenerator(lg),
1415 installer.WithNoLock(),
1416 ); err != nil {
1417 return "", err
1418 }
1419 return "install app", nil
1420 },
gio7fbd4ad2024-08-27 10:06:39 +04001421 soft.WithCommitToBranch(fmt.Sprintf("dodo_%s", branch)),
gio94904702024-07-26 16:58:34 +04001422 soft.WithForce(),
giob4a3a192024-08-19 09:55:47 +04001423 ); err != nil {
1424 return installer.ReleaseResources{}, err
1425 }
gio43b0f422024-08-21 10:40:13 +04001426 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1427 go s.reconciler.Reconcile(ctx, namespace, "app")
giob4a3a192024-08-19 09:55:47 +04001428 return ret, nil
gio0eaf2712024-04-14 13:08:46 +04001429}
gio33059762024-07-05 13:19:07 +04001430
gio7fbd4ad2024-08-27 10:06:39 +04001431func (s *DodoAppServer) renderAppConfigTemplate(appType string, network installer.Network, subdomain string) (map[string][]byte, error) {
giob54db242024-07-30 18:49:33 +04001432 appType = strings.Replace(appType, ":", "-", 1)
gio5e49bb62024-07-20 10:43:19 +04001433 appTmpl, err := s.appTmpls.Find(appType)
1434 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001435 return nil, err
gio33059762024-07-05 13:19:07 +04001436 }
gioc81a8472024-09-24 13:06:19 +02001437 return appTmpl.Render(fmt.Sprintf("%s/stat/schemas/dodo_app.jsonschema", s.selfPublic), network, subdomain)
gio33059762024-07-05 13:19:07 +04001438}
gio81246f02024-07-10 12:02:15 +04001439
1440func generatePassword() string {
1441 return "foo"
1442}
giocb34ad22024-07-11 08:01:13 +04001443
gio11617ac2024-07-15 16:09:04 +04001444func (s *DodoAppServer) getNetworks(user string) ([]installer.Network, error) {
gio23bdc1b2024-07-11 16:07:47 +04001445 addr := fmt.Sprintf("%s/api/networks", s.envAppManagerAddr)
giocb34ad22024-07-11 08:01:13 +04001446 resp, err := http.Get(addr)
1447 if err != nil {
1448 return nil, err
1449 }
gio23bdc1b2024-07-11 16:07:47 +04001450 networks := []installer.Network{}
1451 if json.NewDecoder(resp.Body).Decode(&networks); err != nil {
giocb34ad22024-07-11 08:01:13 +04001452 return nil, err
1453 }
gio11617ac2024-07-15 16:09:04 +04001454 return s.nf.Filter(user, networks)
1455}
1456
giof15b9da2024-09-19 06:59:16 +04001457func (s *DodoAppServer) getClusters() ([]installer.Cluster, error) {
1458 addr := fmt.Sprintf("%s/api/clusters", s.envAppManagerAddr)
1459 resp, err := http.Get(addr)
1460 if err != nil {
1461 return nil, err
1462 }
1463 clusters := []installer.Cluster{}
1464 if json.NewDecoder(resp.Body).Decode(&clusters); err != nil {
1465 return nil, err
1466 }
1467 fmt.Printf("CLUSTERS %+v\n", clusters)
1468 return clusters, nil
1469}
1470
gio8fae3af2024-07-25 13:43:31 +04001471type publicNetworkData struct {
1472 Name string `json:"name"`
1473 Domain string `json:"domain"`
1474}
1475
1476type publicData struct {
1477 Networks []publicNetworkData `json:"networks"`
1478 Types []string `json:"types"`
1479}
1480
1481func (s *DodoAppServer) handleAPIPublicData(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001482 w.Header().Set("Access-Control-Allow-Origin", "*")
1483 s.l.Lock()
1484 defer s.l.Unlock()
gio8fae3af2024-07-25 13:43:31 +04001485 networks, err := s.getNetworks("")
1486 if err != nil {
1487 http.Error(w, err.Error(), http.StatusInternalServerError)
1488 return
1489 }
1490 var ret publicData
1491 for _, n := range networks {
giod8ab4f52024-07-26 16:58:34 +04001492 if s.isNetworkUseAllowed(strings.ToLower(n.Name)) {
1493 ret.Networks = append(ret.Networks, publicNetworkData{n.Name, n.Domain})
1494 }
gio8fae3af2024-07-25 13:43:31 +04001495 }
1496 for _, t := range s.appTmpls.Types() {
giob54db242024-07-30 18:49:33 +04001497 ret.Types = append(ret.Types, strings.Replace(t, "-", ":", 1))
gio8fae3af2024-07-25 13:43:31 +04001498 }
gio8fae3af2024-07-25 13:43:31 +04001499 if err := json.NewEncoder(w).Encode(ret); err != nil {
1500 http.Error(w, err.Error(), http.StatusInternalServerError)
1501 return
1502 }
1503}
1504
gio7fbd4ad2024-08-27 10:06:39 +04001505func (s *DodoAppServer) createCommit(name, branch, hash, message string, err error, resources installer.ReleaseResources) error {
giob4a3a192024-08-19 09:55:47 +04001506 if err != nil {
1507 fmt.Printf("Error: %s\n", err.Error())
gio7fbd4ad2024-08-27 10:06:39 +04001508 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001509 fmt.Printf("Error: %s\n", err.Error())
1510 return err
1511 }
1512 return err
1513 }
1514 var resB bytes.Buffer
1515 if err := json.NewEncoder(&resB).Encode(resources); err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001516 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001517 fmt.Printf("Error: %s\n", err.Error())
1518 return err
1519 }
1520 return err
1521 }
gio7fbd4ad2024-08-27 10:06:39 +04001522 if err := s.st.CreateCommit(name, branch, hash, message, "OK", "", resB.Bytes()); err != nil {
giob4a3a192024-08-19 09:55:47 +04001523 fmt.Printf("Error: %s\n", err.Error())
1524 return err
1525 }
1526 return nil
1527}
1528
gio11617ac2024-07-15 16:09:04 +04001529func pickNetwork(networks []installer.Network, network string) []installer.Network {
1530 for _, n := range networks {
1531 if n.Name == network {
1532 return []installer.Network{n}
1533 }
1534 }
1535 return []installer.Network{}
1536}
1537
1538type NetworkFilter interface {
1539 Filter(user string, networks []installer.Network) ([]installer.Network, error)
1540}
1541
1542type noNetworkFilter struct{}
1543
1544func NewNoNetworkFilter() NetworkFilter {
1545 return noNetworkFilter{}
1546}
1547
gio8fae3af2024-07-25 13:43:31 +04001548func (f noNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001549 return networks, nil
1550}
1551
1552type filterByOwner struct {
1553 st Store
1554}
1555
1556func NewNetworkFilterByOwner(st Store) NetworkFilter {
1557 return &filterByOwner{st}
1558}
1559
1560func (f *filterByOwner) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio8fae3af2024-07-25 13:43:31 +04001561 if user == "" {
1562 return networks, nil
1563 }
gio11617ac2024-07-15 16:09:04 +04001564 network, err := f.st.GetUserNetwork(user)
1565 if err != nil {
1566 return nil, err
gio23bdc1b2024-07-11 16:07:47 +04001567 }
1568 ret := []installer.Network{}
1569 for _, n := range networks {
gio11617ac2024-07-15 16:09:04 +04001570 if n.Name == network {
gio23bdc1b2024-07-11 16:07:47 +04001571 ret = append(ret, n)
1572 }
1573 }
giocb34ad22024-07-11 08:01:13 +04001574 return ret, nil
1575}
gio11617ac2024-07-15 16:09:04 +04001576
1577type allowListFilter struct {
1578 allowed []string
1579}
1580
1581func NewAllowListFilter(allowed []string) NetworkFilter {
1582 return &allowListFilter{allowed}
1583}
1584
gio8fae3af2024-07-25 13:43:31 +04001585func (f *allowListFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001586 ret := []installer.Network{}
1587 for _, n := range networks {
1588 if slices.Contains(f.allowed, n.Name) {
1589 ret = append(ret, n)
1590 }
1591 }
1592 return ret, nil
1593}
1594
1595type combinedNetworkFilter struct {
1596 filters []NetworkFilter
1597}
1598
1599func NewCombinedFilter(filters ...NetworkFilter) NetworkFilter {
1600 return &combinedNetworkFilter{filters}
1601}
1602
gio8fae3af2024-07-25 13:43:31 +04001603func (f *combinedNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001604 ret := networks
1605 var err error
1606 for _, f := range f.filters {
gio8fae3af2024-07-25 13:43:31 +04001607 ret, err = f.Filter(user, ret)
gio11617ac2024-07-15 16:09:04 +04001608 if err != nil {
1609 return nil, err
1610 }
1611 }
1612 return ret, nil
1613}
giocafd4e62024-07-31 10:53:40 +04001614
1615type user struct {
1616 Username string `json:"username"`
1617 Email string `json:"email"`
1618 SSHPublicKeys []string `json:"sshPublicKeys,omitempty"`
1619}
1620
1621func (s *DodoAppServer) handleAPISyncUsers(_ http.ResponseWriter, _ *http.Request) {
1622 go s.syncUsers()
1623}
1624
1625func (s *DodoAppServer) syncUsers() {
1626 if s.external {
1627 panic("MUST NOT REACH!")
1628 }
1629 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/api/sync-users", s.fetchUsersAddr, s.self))
1630 if err != nil {
1631 return
1632 }
1633 users := []user{}
1634 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
1635 fmt.Println(err)
1636 return
1637 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001638 validUsernames := make(map[string]user)
1639 for _, u := range users {
1640 validUsernames[u.Username] = u
1641 }
1642 allClientUsers, err := s.client.GetAllUsers()
1643 if err != nil {
1644 fmt.Println(err)
1645 return
1646 }
1647 keyToUser := make(map[string]string)
1648 for _, clientUser := range allClientUsers {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001649 if clientUser == "admin" || clientUser == "fluxcd" {
1650 continue
1651 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001652 userData, ok := validUsernames[clientUser]
1653 if !ok {
1654 if err := s.client.RemoveUser(clientUser); err != nil {
1655 fmt.Println(err)
1656 return
1657 }
1658 } else {
1659 existingKeys, err := s.client.GetUserPublicKeys(clientUser)
1660 if err != nil {
1661 fmt.Println(err)
1662 return
1663 }
1664 for _, existingKey := range existingKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001665 cleanKey := soft.CleanKey(existingKey)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001666 keyOk := slices.ContainsFunc(userData.SSHPublicKeys, func(key string) bool {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001667 return cleanKey == soft.CleanKey(key)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001668 })
1669 if !keyOk {
1670 if err := s.client.RemovePublicKey(clientUser, existingKey); err != nil {
1671 fmt.Println(err)
1672 }
1673 } else {
1674 keyToUser[cleanKey] = clientUser
1675 }
1676 }
1677 }
1678 }
giocafd4e62024-07-31 10:53:40 +04001679 for _, u := range users {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001680 if err := s.st.CreateUser(u.Username, nil, ""); err != nil && !errors.Is(err, ErrorAlreadyExists) {
1681 fmt.Println(err)
1682 return
1683 }
giocafd4e62024-07-31 10:53:40 +04001684 if len(u.SSHPublicKeys) == 0 {
1685 continue
1686 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001687 ok, err := s.client.UserExists(u.Username)
1688 if err != nil {
giocafd4e62024-07-31 10:53:40 +04001689 fmt.Println(err)
1690 return
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001691 }
1692 if !ok {
1693 if err := s.client.AddUser(u.Username, u.SSHPublicKeys[0]); err != nil {
1694 fmt.Println(err)
1695 return
1696 }
1697 } else {
1698 for _, key := range u.SSHPublicKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001699 cleanKey := soft.CleanKey(key)
1700 if user, ok := keyToUser[cleanKey]; ok {
1701 if u.Username != user {
1702 panic("MUST NOT REACH! IMPOSSIBLE KEY USER RECORD")
1703 }
1704 continue
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001705 }
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001706 if err := s.client.AddPublicKey(u.Username, cleanKey); err != nil {
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001707 fmt.Println(err)
1708 return
giocafd4e62024-07-31 10:53:40 +04001709 }
1710 }
1711 }
1712 }
1713 repos, err := s.client.GetAllRepos()
1714 if err != nil {
1715 return
1716 }
1717 for _, r := range repos {
1718 if r == ConfigRepoName {
1719 continue
1720 }
1721 for _, u := range users {
1722 if err := s.client.AddReadWriteCollaborator(r, u.Username); err != nil {
1723 fmt.Println(err)
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001724 continue
giocafd4e62024-07-31 10:53:40 +04001725 }
1726 }
1727 }
1728}
giob4a3a192024-08-19 09:55:47 +04001729
1730func extractResourceData(resources []installer.Resource) (resourceData, error) {
1731 var ret resourceData
1732 for _, r := range resources {
1733 t, ok := r.Annotations["dodo.cloud/resource-type"]
1734 if !ok {
1735 continue
1736 }
1737 switch t {
1738 case "volume":
1739 name, ok := r.Annotations["dodo.cloud/resource.volume.name"]
1740 if !ok {
1741 return resourceData{}, fmt.Errorf("no name")
1742 }
1743 size, ok := r.Annotations["dodo.cloud/resource.volume.size"]
1744 if !ok {
1745 return resourceData{}, fmt.Errorf("no size")
1746 }
1747 ret.Volume = append(ret.Volume, volume{name, size})
1748 case "postgresql":
1749 name, ok := r.Annotations["dodo.cloud/resource.postgresql.name"]
1750 if !ok {
1751 return resourceData{}, fmt.Errorf("no name")
1752 }
1753 version, ok := r.Annotations["dodo.cloud/resource.postgresql.version"]
1754 if !ok {
1755 return resourceData{}, fmt.Errorf("no version")
1756 }
1757 volume, ok := r.Annotations["dodo.cloud/resource.postgresql.volume"]
1758 if !ok {
1759 return resourceData{}, fmt.Errorf("no volume")
1760 }
1761 ret.PostgreSQL = append(ret.PostgreSQL, postgresql{name, version, volume})
1762 case "ingress":
1763 host, ok := r.Annotations["dodo.cloud/resource.ingress.host"]
1764 if !ok {
1765 return resourceData{}, fmt.Errorf("no host")
1766 }
1767 ret.Ingress = append(ret.Ingress, ingress{host})
gio7fbd4ad2024-08-27 10:06:39 +04001768 case "virtual-machine":
1769 name, ok := r.Annotations["dodo.cloud/resource.virtual-machine.name"]
1770 if !ok {
1771 return resourceData{}, fmt.Errorf("no name")
1772 }
1773 user, ok := r.Annotations["dodo.cloud/resource.virtual-machine.user"]
1774 if !ok {
1775 return resourceData{}, fmt.Errorf("no user")
1776 }
1777 cpuCoresS, ok := r.Annotations["dodo.cloud/resource.virtual-machine.cpu-cores"]
1778 if !ok {
1779 return resourceData{}, fmt.Errorf("no cpu cores")
1780 }
1781 cpuCores, err := strconv.Atoi(cpuCoresS)
1782 if err != nil {
1783 return resourceData{}, fmt.Errorf("invalid cpu cores: %s", cpuCoresS)
1784 }
1785 memory, ok := r.Annotations["dodo.cloud/resource.virtual-machine.memory"]
1786 if !ok {
1787 return resourceData{}, fmt.Errorf("no memory")
1788 }
1789 ret.VirtualMachine = append(ret.VirtualMachine, vm{name, user, cpuCores, memory})
giob4a3a192024-08-19 09:55:47 +04001790 default:
1791 fmt.Printf("Unknown resource: %+v\n", r.Annotations)
1792 }
1793 }
1794 return ret, nil
1795}
gio7fbd4ad2024-08-27 10:06:39 +04001796
1797func createDevBranchAppConfig(from []byte, branch, username string) (string, []byte, error) {
gioc81a8472024-09-24 13:06:19 +02001798 cfg, err := installer.ParseCueAppConfig(installer.CueAppData{
1799 "app.cue": from,
1800 })
gio7fbd4ad2024-08-27 10:06:39 +04001801 if err != nil {
1802 return "", nil, err
1803 }
1804 if err := cfg.Err(); err != nil {
1805 return "", nil, err
1806 }
1807 if err := cfg.Validate(); err != nil {
1808 return "", nil, err
1809 }
1810 subdomain := cfg.LookupPath(cue.ParsePath("app.ingress.subdomain"))
1811 if err := subdomain.Err(); err != nil {
1812 return "", nil, err
1813 }
1814 subdomainStr, err := subdomain.String()
1815 network := cfg.LookupPath(cue.ParsePath("app.ingress.network"))
1816 if err := network.Err(); err != nil {
1817 return "", nil, err
1818 }
1819 networkStr, err := network.String()
1820 if err != nil {
1821 return "", nil, err
1822 }
1823 newCfg := map[string]any{}
1824 if err := cfg.Decode(&newCfg); err != nil {
1825 return "", nil, err
1826 }
1827 app, ok := newCfg["app"].(map[string]any)
1828 if !ok {
1829 return "", nil, fmt.Errorf("not a map")
1830 }
1831 app["ingress"].(map[string]any)["subdomain"] = fmt.Sprintf("%s-%s", branch, subdomainStr)
1832 app["dev"] = map[string]any{
1833 "enabled": true,
1834 "username": username,
1835 }
1836 buf, err := json.MarshalIndent(newCfg, "", "\t")
1837 if err != nil {
1838 return "", nil, err
1839 }
1840 return networkStr, buf, nil
1841}