blob: 9a93afdac24220c9bbcb7ee597303110d37db684 [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
gio9d66f322024-07-06 13:45:10 +040038const (
gioa60f0de2024-07-08 10:49:48 +040039 ConfigRepoName = "config"
giod8ab4f52024-07-26 16:58:34 +040040 appConfigsFile = "/apps.json"
gio81246f02024-07-10 12:02:15 +040041 loginPath = "/login"
42 logoutPath = "/logout"
gio1bf00802024-08-17 12:31:41 +040043 staticPath = "/stat/"
gio8fae3af2024-07-25 13:43:31 +040044 apiPublicData = "/api/public-data"
45 apiCreateApp = "/api/apps"
gio81246f02024-07-10 12:02:15 +040046 sessionCookie = "dodo-app-session"
47 userCtx = "user"
giob4a3a192024-08-19 09:55:47 +040048 initCommitMsg = "init"
gio9d66f322024-07-06 13:45:10 +040049)
50
gio23bdc1b2024-07-11 16:07:47 +040051type dodoAppTmplts struct {
giob4a3a192024-08-19 09:55:47 +040052 index *template.Template
53 appStatus *template.Template
54 commitStatus *template.Template
gio183e8342024-08-20 06:01:24 +040055 logs *template.Template
gio23bdc1b2024-07-11 16:07:47 +040056}
57
58func parseTemplatesDodoApp(fs embed.FS) (dodoAppTmplts, error) {
gio5e49bb62024-07-20 10:43:19 +040059 base, err := template.ParseFS(fs, "dodo-app-tmpl/base.html")
gio23bdc1b2024-07-11 16:07:47 +040060 if err != nil {
61 return dodoAppTmplts{}, err
62 }
gio5e49bb62024-07-20 10:43:19 +040063 parse := func(path string) (*template.Template, error) {
64 if b, err := base.Clone(); err != nil {
65 return nil, err
66 } else {
67 return b.ParseFS(fs, path)
68 }
69 }
70 index, err := parse("dodo-app-tmpl/index.html")
71 if err != nil {
72 return dodoAppTmplts{}, err
73 }
74 appStatus, err := parse("dodo-app-tmpl/app_status.html")
75 if err != nil {
76 return dodoAppTmplts{}, err
77 }
giob4a3a192024-08-19 09:55:47 +040078 commitStatus, err := parse("dodo-app-tmpl/commit_status.html")
79 if err != nil {
80 return dodoAppTmplts{}, err
81 }
gio183e8342024-08-20 06:01:24 +040082 logs, err := parse("dodo-app-tmpl/logs.html")
83 if err != nil {
84 return dodoAppTmplts{}, err
85 }
86 return dodoAppTmplts{index, appStatus, commitStatus, logs}, nil
gio23bdc1b2024-07-11 16:07:47 +040087}
88
gio0eaf2712024-04-14 13:08:46 +040089type DodoAppServer struct {
giocb34ad22024-07-11 08:01:13 +040090 l sync.Locker
91 st Store
gio11617ac2024-07-15 16:09:04 +040092 nf NetworkFilter
93 ug UserGetter
giocb34ad22024-07-11 08:01:13 +040094 port int
95 apiPort int
96 self string
gio11617ac2024-07-15 16:09:04 +040097 repoPublicAddr string
giocb34ad22024-07-11 08:01:13 +040098 sshKey string
99 gitRepoPublicKey string
100 client soft.Client
101 namespace string
102 envAppManagerAddr string
103 env installer.EnvConfig
104 nsc installer.NamespaceCreator
105 jc installer.JobCreator
gio864b4332024-09-05 13:56:47 +0400106 vpnKeyGen installer.VPNAPIClient
giof6ad2982024-08-23 17:42:49 +0400107 cnc installer.ClusterNetworkConfigurator
giocb34ad22024-07-11 08:01:13 +0400108 workers map[string]map[string]struct{}
giod8ab4f52024-07-26 16:58:34 +0400109 appConfigs map[string]appConfig
gio23bdc1b2024-07-11 16:07:47 +0400110 tmplts dodoAppTmplts
gio5e49bb62024-07-20 10:43:19 +0400111 appTmpls AppTmplStore
giocafd4e62024-07-31 10:53:40 +0400112 external bool
113 fetchUsersAddr string
gio43b0f422024-08-21 10:40:13 +0400114 reconciler tasks.Reconciler
gio183e8342024-08-20 06:01:24 +0400115 logs map[string]string
giod8ab4f52024-07-26 16:58:34 +0400116}
117
118type appConfig struct {
119 Namespace string `json:"namespace"`
120 Network string `json:"network"`
gio0eaf2712024-04-14 13:08:46 +0400121}
122
gio33059762024-07-05 13:19:07 +0400123// TODO(gio): Initialize appNs on startup
gio0eaf2712024-04-14 13:08:46 +0400124func NewDodoAppServer(
gioa60f0de2024-07-08 10:49:48 +0400125 st Store,
gio11617ac2024-07-15 16:09:04 +0400126 nf NetworkFilter,
127 ug UserGetter,
gio0eaf2712024-04-14 13:08:46 +0400128 port int,
gioa60f0de2024-07-08 10:49:48 +0400129 apiPort int,
gio33059762024-07-05 13:19:07 +0400130 self string,
gio11617ac2024-07-15 16:09:04 +0400131 repoPublicAddr string,
gio0eaf2712024-04-14 13:08:46 +0400132 sshKey string,
gio33059762024-07-05 13:19:07 +0400133 gitRepoPublicKey string,
gio0eaf2712024-04-14 13:08:46 +0400134 client soft.Client,
135 namespace string,
giocb34ad22024-07-11 08:01:13 +0400136 envAppManagerAddr string,
gio33059762024-07-05 13:19:07 +0400137 nsc installer.NamespaceCreator,
giof8843412024-05-22 16:38:05 +0400138 jc installer.JobCreator,
gio864b4332024-09-05 13:56:47 +0400139 vpnKeyGen installer.VPNAPIClient,
giof6ad2982024-08-23 17:42:49 +0400140 cnc installer.ClusterNetworkConfigurator,
gio0eaf2712024-04-14 13:08:46 +0400141 env installer.EnvConfig,
giocafd4e62024-07-31 10:53:40 +0400142 external bool,
143 fetchUsersAddr string,
gio43b0f422024-08-21 10:40:13 +0400144 reconciler tasks.Reconciler,
gio9d66f322024-07-06 13:45:10 +0400145) (*DodoAppServer, error) {
gio23bdc1b2024-07-11 16:07:47 +0400146 tmplts, err := parseTemplatesDodoApp(dodoAppTmplFS)
147 if err != nil {
148 return nil, err
149 }
gio5e49bb62024-07-20 10:43:19 +0400150 apps, err := fs.Sub(appTmplsFS, "app-tmpl")
151 if err != nil {
152 return nil, err
153 }
154 appTmpls, err := NewAppTmplStoreFS(apps)
155 if err != nil {
156 return nil, err
157 }
gio9d66f322024-07-06 13:45:10 +0400158 s := &DodoAppServer{
159 &sync.Mutex{},
gioa60f0de2024-07-08 10:49:48 +0400160 st,
gio11617ac2024-07-15 16:09:04 +0400161 nf,
162 ug,
gio0eaf2712024-04-14 13:08:46 +0400163 port,
gioa60f0de2024-07-08 10:49:48 +0400164 apiPort,
gio33059762024-07-05 13:19:07 +0400165 self,
gio11617ac2024-07-15 16:09:04 +0400166 repoPublicAddr,
gio0eaf2712024-04-14 13:08:46 +0400167 sshKey,
gio33059762024-07-05 13:19:07 +0400168 gitRepoPublicKey,
gio0eaf2712024-04-14 13:08:46 +0400169 client,
170 namespace,
giocb34ad22024-07-11 08:01:13 +0400171 envAppManagerAddr,
gio0eaf2712024-04-14 13:08:46 +0400172 env,
gio33059762024-07-05 13:19:07 +0400173 nsc,
giof8843412024-05-22 16:38:05 +0400174 jc,
gio36b23b32024-08-25 12:20:54 +0400175 vpnKeyGen,
giof6ad2982024-08-23 17:42:49 +0400176 cnc,
gio266c04f2024-07-03 14:18:45 +0400177 map[string]map[string]struct{}{},
giod8ab4f52024-07-26 16:58:34 +0400178 map[string]appConfig{},
gio23bdc1b2024-07-11 16:07:47 +0400179 tmplts,
gio5e49bb62024-07-20 10:43:19 +0400180 appTmpls,
giocafd4e62024-07-31 10:53:40 +0400181 external,
182 fetchUsersAddr,
gio43b0f422024-08-21 10:40:13 +0400183 reconciler,
gio183e8342024-08-20 06:01:24 +0400184 map[string]string{},
gio0eaf2712024-04-14 13:08:46 +0400185 }
gioa60f0de2024-07-08 10:49:48 +0400186 config, err := client.GetRepo(ConfigRepoName)
gio9d66f322024-07-06 13:45:10 +0400187 if err != nil {
188 return nil, err
189 }
giod8ab4f52024-07-26 16:58:34 +0400190 r, err := config.Reader(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +0400191 if err == nil {
192 defer r.Close()
giod8ab4f52024-07-26 16:58:34 +0400193 if err := json.NewDecoder(r).Decode(&s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +0400194 return nil, err
195 }
196 } else if !errors.Is(err, fs.ErrNotExist) {
197 return nil, err
198 }
199 return s, nil
gio0eaf2712024-04-14 13:08:46 +0400200}
201
gio7fbd4ad2024-08-27 10:06:39 +0400202func (s *DodoAppServer) getAppConfig(app, branch string) appConfig {
203 return s.appConfigs[fmt.Sprintf("%s-%s", app, branch)]
204}
205
206func (s *DodoAppServer) setAppConfig(app, branch string, cfg appConfig) {
207 s.appConfigs[fmt.Sprintf("%s-%s", app, branch)] = cfg
208}
209
gio0eaf2712024-04-14 13:08:46 +0400210func (s *DodoAppServer) Start() error {
gio7fbd4ad2024-08-27 10:06:39 +0400211 // if err := s.client.DisableKeyless(); err != nil {
212 // return err
213 // }
214 // if err := s.client.DisableAnonAccess(); err != nil {
215 // return err
216 // }
gioa60f0de2024-07-08 10:49:48 +0400217 e := make(chan error)
218 go func() {
219 r := mux.NewRouter()
gio81246f02024-07-10 12:02:15 +0400220 r.Use(s.mwAuth)
gio1bf00802024-08-17 12:31:41 +0400221 r.PathPrefix(staticPath).Handler(cachingHandler{http.FileServer(http.FS(statAssets))})
gio81246f02024-07-10 12:02:15 +0400222 r.HandleFunc(logoutPath, s.handleLogout).Methods(http.MethodGet)
gio8fae3af2024-07-25 13:43:31 +0400223 r.HandleFunc(apiPublicData, s.handleAPIPublicData)
224 r.HandleFunc(apiCreateApp, s.handleAPICreateApp).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400225 r.HandleFunc("/{app-name}"+loginPath, s.handleLoginForm).Methods(http.MethodGet)
226 r.HandleFunc("/{app-name}"+loginPath, s.handleLogin).Methods(http.MethodPost)
gio183e8342024-08-20 06:01:24 +0400227 r.HandleFunc("/{app-name}/logs", s.handleAppLogs).Methods(http.MethodGet)
giob4a3a192024-08-19 09:55:47 +0400228 r.HandleFunc("/{app-name}/{hash}", s.handleAppCommit).Methods(http.MethodGet)
gio7fbd4ad2024-08-27 10:06:39 +0400229 r.HandleFunc("/{app-name}/dev-branch/create", s.handleCreateDevBranch).Methods(http.MethodPost)
230 r.HandleFunc("/{app-name}/branch/{branch}", s.handleAppStatus).Methods(http.MethodGet)
gio81246f02024-07-10 12:02:15 +0400231 r.HandleFunc("/{app-name}", s.handleAppStatus).Methods(http.MethodGet)
232 r.HandleFunc("/", s.handleStatus).Methods(http.MethodGet)
gio11617ac2024-07-15 16:09:04 +0400233 r.HandleFunc("/", s.handleCreateApp).Methods(http.MethodPost)
gioa60f0de2024-07-08 10:49:48 +0400234 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.port), r)
235 }()
236 go func() {
237 r := mux.NewRouter()
gio8fae3af2024-07-25 13:43:31 +0400238 r.HandleFunc("/update", s.handleAPIUpdate)
239 r.HandleFunc("/api/apps/{app-name}/workers", s.handleAPIRegisterWorker).Methods(http.MethodPost)
gio7fbd4ad2024-08-27 10:06:39 +0400240 r.HandleFunc("/api/add-public-key", s.handleAPIAddPublicKey).Methods(http.MethodPost)
giocfb228c2024-09-06 15:44:31 +0400241 r.HandleFunc("/api/apps/{app-name}/branch/{branch}/env-profile", s.handleBranchEnvProfile).Methods(http.MethodGet)
giocafd4e62024-07-31 10:53:40 +0400242 if !s.external {
243 r.HandleFunc("/api/sync-users", s.handleAPISyncUsers).Methods(http.MethodGet)
244 }
gioa60f0de2024-07-08 10:49:48 +0400245 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.apiPort), r)
246 }()
giocafd4e62024-07-31 10:53:40 +0400247 if !s.external {
248 go func() {
249 s.syncUsers()
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400250 for {
251 delay := time.Duration(rand.Intn(60)+60) * time.Second
252 time.Sleep(delay)
giocafd4e62024-07-31 10:53:40 +0400253 s.syncUsers()
254 }
255 }()
256 }
gioa60f0de2024-07-08 10:49:48 +0400257 return <-e
258}
259
gio11617ac2024-07-15 16:09:04 +0400260type UserGetter interface {
261 Get(r *http.Request) string
gio8fae3af2024-07-25 13:43:31 +0400262 Encode(w http.ResponseWriter, user string) error
gio11617ac2024-07-15 16:09:04 +0400263}
264
265type externalUserGetter struct {
266 sc *securecookie.SecureCookie
267}
268
269func NewExternalUserGetter() UserGetter {
gio8fae3af2024-07-25 13:43:31 +0400270 return &externalUserGetter{securecookie.New(
271 securecookie.GenerateRandomKey(64),
272 securecookie.GenerateRandomKey(32),
273 )}
gio11617ac2024-07-15 16:09:04 +0400274}
275
276func (ug *externalUserGetter) Get(r *http.Request) string {
277 cookie, err := r.Cookie(sessionCookie)
278 if err != nil {
279 return ""
280 }
281 var user string
282 if err := ug.sc.Decode(sessionCookie, cookie.Value, &user); err != nil {
283 return ""
284 }
285 return user
286}
287
gio8fae3af2024-07-25 13:43:31 +0400288func (ug *externalUserGetter) Encode(w http.ResponseWriter, user string) error {
289 if encoded, err := ug.sc.Encode(sessionCookie, user); err == nil {
290 cookie := &http.Cookie{
291 Name: sessionCookie,
292 Value: encoded,
293 Path: "/",
294 Secure: true,
295 HttpOnly: true,
296 }
297 http.SetCookie(w, cookie)
298 return nil
299 } else {
300 return err
301 }
302}
303
gio11617ac2024-07-15 16:09:04 +0400304type internalUserGetter struct{}
305
306func NewInternalUserGetter() UserGetter {
307 return internalUserGetter{}
308}
309
310func (ug internalUserGetter) Get(r *http.Request) string {
311 return r.Header.Get("X-User")
312}
313
gio8fae3af2024-07-25 13:43:31 +0400314func (ug internalUserGetter) Encode(w http.ResponseWriter, user string) error {
315 return nil
316}
317
gio81246f02024-07-10 12:02:15 +0400318func (s *DodoAppServer) mwAuth(next http.Handler) http.Handler {
319 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400320 if strings.HasSuffix(r.URL.Path, loginPath) ||
321 strings.HasPrefix(r.URL.Path, logoutPath) ||
322 strings.HasPrefix(r.URL.Path, staticPath) ||
323 strings.HasPrefix(r.URL.Path, apiPublicData) ||
324 strings.HasPrefix(r.URL.Path, apiCreateApp) {
gio81246f02024-07-10 12:02:15 +0400325 next.ServeHTTP(w, r)
326 return
327 }
gio11617ac2024-07-15 16:09:04 +0400328 user := s.ug.Get(r)
329 if user == "" {
gio81246f02024-07-10 12:02:15 +0400330 vars := mux.Vars(r)
331 appName, ok := vars["app-name"]
332 if !ok || appName == "" {
333 http.Error(w, "missing app-name", http.StatusBadRequest)
334 return
335 }
336 http.Redirect(w, r, fmt.Sprintf("/%s%s", appName, loginPath), http.StatusSeeOther)
337 return
338 }
gio81246f02024-07-10 12:02:15 +0400339 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userCtx, user)))
340 })
341}
342
343func (s *DodoAppServer) handleLogout(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400344 // TODO(gio): move to UserGetter
gio81246f02024-07-10 12:02:15 +0400345 http.SetCookie(w, &http.Cookie{
346 Name: sessionCookie,
347 Value: "",
348 Path: "/",
349 HttpOnly: true,
350 Secure: true,
351 })
352 http.Redirect(w, r, "/", http.StatusSeeOther)
353}
354
355func (s *DodoAppServer) handleLoginForm(w http.ResponseWriter, r *http.Request) {
356 vars := mux.Vars(r)
357 appName, ok := vars["app-name"]
358 if !ok || appName == "" {
359 http.Error(w, "missing app-name", http.StatusBadRequest)
360 return
361 }
362 fmt.Fprint(w, `
363<!DOCTYPE html>
364<html lang='en'>
365 <head>
366 <title>dodo: app - login</title>
367 <meta charset='utf-8'>
368 </head>
369 <body>
370 <form action="" method="POST">
371 <input type="password" placeholder="Password" name="password" required />
372 <button type="submit">Login</button>
373 </form>
374 </body>
375</html>
376`)
377}
378
379func (s *DodoAppServer) handleLogin(w http.ResponseWriter, r *http.Request) {
380 vars := mux.Vars(r)
381 appName, ok := vars["app-name"]
382 if !ok || appName == "" {
383 http.Error(w, "missing app-name", http.StatusBadRequest)
384 return
385 }
386 password := r.FormValue("password")
387 if password == "" {
388 http.Error(w, "missing password", http.StatusBadRequest)
389 return
390 }
391 user, err := s.st.GetAppOwner(appName)
392 if err != nil {
393 http.Error(w, err.Error(), http.StatusInternalServerError)
394 return
395 }
396 hashed, err := s.st.GetUserPassword(user)
397 if err != nil {
398 http.Error(w, err.Error(), http.StatusInternalServerError)
399 return
400 }
401 if err := bcrypt.CompareHashAndPassword(hashed, []byte(password)); err != nil {
402 http.Redirect(w, r, r.URL.Path, http.StatusSeeOther)
403 return
404 }
gio8fae3af2024-07-25 13:43:31 +0400405 if err := s.ug.Encode(w, user); err != nil {
406 http.Error(w, err.Error(), http.StatusInternalServerError)
407 return
gio81246f02024-07-10 12:02:15 +0400408 }
409 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
410}
411
giob4a3a192024-08-19 09:55:47 +0400412type navItem struct {
413 Name string
414 Address string
415}
416
gio23bdc1b2024-07-11 16:07:47 +0400417type statusData struct {
giob4a3a192024-08-19 09:55:47 +0400418 Navigation []navItem
419 Apps []string
420 Networks []installer.Network
421 Types []string
gio23bdc1b2024-07-11 16:07:47 +0400422}
423
gioa60f0de2024-07-08 10:49:48 +0400424func (s *DodoAppServer) handleStatus(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +0400425 user := r.Context().Value(userCtx)
426 if user == nil {
427 http.Error(w, "unauthorized", http.StatusUnauthorized)
428 return
429 }
430 apps, err := s.st.GetUserApps(user.(string))
gioa60f0de2024-07-08 10:49:48 +0400431 if err != nil {
432 http.Error(w, err.Error(), http.StatusInternalServerError)
433 return
434 }
gio11617ac2024-07-15 16:09:04 +0400435 networks, err := s.getNetworks(user.(string))
436 if err != nil {
437 http.Error(w, err.Error(), http.StatusInternalServerError)
438 return
439 }
giob54db242024-07-30 18:49:33 +0400440 var types []string
441 for _, t := range s.appTmpls.Types() {
442 types = append(types, strings.Replace(t, "-", ":", 1))
443 }
giob4a3a192024-08-19 09:55:47 +0400444 n := []navItem{navItem{"Home", "/"}}
445 data := statusData{n, apps, networks, types}
gio23bdc1b2024-07-11 16:07:47 +0400446 if err := s.tmplts.index.Execute(w, data); err != nil {
447 http.Error(w, err.Error(), http.StatusInternalServerError)
448 return
gioa60f0de2024-07-08 10:49:48 +0400449 }
450}
451
gio5e49bb62024-07-20 10:43:19 +0400452type appStatusData struct {
giob4a3a192024-08-19 09:55:47 +0400453 Navigation []navItem
gio5e49bb62024-07-20 10:43:19 +0400454 Name string
455 GitCloneCommand string
giob4a3a192024-08-19 09:55:47 +0400456 Commits []CommitMeta
gio183e8342024-08-20 06:01:24 +0400457 LastCommit resourceData
gio7fbd4ad2024-08-27 10:06:39 +0400458 Branches []string
gio5e49bb62024-07-20 10:43:19 +0400459}
460
gioa60f0de2024-07-08 10:49:48 +0400461func (s *DodoAppServer) handleAppStatus(w http.ResponseWriter, r *http.Request) {
462 vars := mux.Vars(r)
463 appName, ok := vars["app-name"]
464 if !ok || appName == "" {
465 http.Error(w, "missing app-name", http.StatusBadRequest)
466 return
467 }
gio7fbd4ad2024-08-27 10:06:39 +0400468 branch, ok := vars["branch"]
469 if !ok || branch == "" {
470 branch = "master"
471 }
gio94904702024-07-26 16:58:34 +0400472 u := r.Context().Value(userCtx)
473 if u == nil {
474 http.Error(w, "unauthorized", http.StatusUnauthorized)
475 return
476 }
477 user, ok := u.(string)
478 if !ok {
479 http.Error(w, "could not get user", http.StatusInternalServerError)
480 return
481 }
482 owner, err := s.st.GetAppOwner(appName)
483 if err != nil {
484 http.Error(w, err.Error(), http.StatusInternalServerError)
485 return
486 }
487 if owner != user {
488 http.Error(w, "unauthorized", http.StatusUnauthorized)
489 return
490 }
gio7fbd4ad2024-08-27 10:06:39 +0400491 commits, err := s.st.GetCommitHistory(appName, branch)
gioa60f0de2024-07-08 10:49:48 +0400492 if err != nil {
493 http.Error(w, err.Error(), http.StatusInternalServerError)
494 return
495 }
gio183e8342024-08-20 06:01:24 +0400496 var lastCommitResources resourceData
497 if len(commits) > 0 {
498 lastCommit, err := s.st.GetCommit(commits[len(commits)-1].Hash)
499 if err != nil {
500 http.Error(w, err.Error(), http.StatusInternalServerError)
501 return
502 }
503 r, err := extractResourceData(lastCommit.Resources.Helm)
504 if err != nil {
505 http.Error(w, err.Error(), http.StatusInternalServerError)
506 return
507 }
508 lastCommitResources = r
509 }
gio7fbd4ad2024-08-27 10:06:39 +0400510 branches, err := s.st.GetBranches(appName)
511 if err != nil {
512 http.Error(w, err.Error(), http.StatusInternalServerError)
513 return
514 }
gio5e49bb62024-07-20 10:43:19 +0400515 data := appStatusData{
giob4a3a192024-08-19 09:55:47 +0400516 Navigation: []navItem{
517 navItem{"Home", "/"},
518 navItem{appName, "/" + appName},
519 },
gio5e49bb62024-07-20 10:43:19 +0400520 Name: appName,
521 GitCloneCommand: fmt.Sprintf("git clone %s/%s\n\n\n", s.repoPublicAddr, appName),
522 Commits: commits,
gio183e8342024-08-20 06:01:24 +0400523 LastCommit: lastCommitResources,
gio7fbd4ad2024-08-27 10:06:39 +0400524 Branches: branches,
525 }
526 if branch != "master" {
527 data.Navigation = append(data.Navigation, navItem{branch, fmt.Sprintf("/%s/branch/%s", appName, branch)})
gio5e49bb62024-07-20 10:43:19 +0400528 }
529 if err := s.tmplts.appStatus.Execute(w, data); err != nil {
530 http.Error(w, err.Error(), http.StatusInternalServerError)
531 return
gioa60f0de2024-07-08 10:49:48 +0400532 }
gio0eaf2712024-04-14 13:08:46 +0400533}
534
giocfb228c2024-09-06 15:44:31 +0400535type appEnv struct {
536 Profile string `json:"envProfile"`
537}
538
539func (s *DodoAppServer) handleBranchEnvProfile(w http.ResponseWriter, r *http.Request) {
540 vars := mux.Vars(r)
541 appName, ok := vars["app-name"]
542 if !ok || appName == "" {
543 http.Error(w, "missing app-name", http.StatusBadRequest)
544 return
545 }
546 branch, ok := vars["branch"]
547 if !ok || branch == "" {
548 branch = "master"
549 }
550 info, err := s.st.GetLastCommitInfo(appName, branch)
551 if err != nil {
552 http.Error(w, err.Error(), http.StatusInternalServerError)
553 return
554 }
555 var e appEnv
556 if err := json.NewDecoder(bytes.NewReader(info.Resources.RenderedRaw)).Decode(&e); err != nil {
557 http.Error(w, err.Error(), http.StatusInternalServerError)
558 return
559 }
560 fmt.Fprintln(w, e.Profile)
561}
562
giob4a3a192024-08-19 09:55:47 +0400563type volume struct {
564 Name string
565 Size string
566}
567
568type postgresql struct {
569 Name string
570 Version string
571 Volume string
572}
573
574type ingress struct {
575 Host string
576}
577
gio7fbd4ad2024-08-27 10:06:39 +0400578type vm struct {
579 Name string
580 User string
581 CPUCores int
582 Memory string
583}
584
giob4a3a192024-08-19 09:55:47 +0400585type resourceData struct {
gio7fbd4ad2024-08-27 10:06:39 +0400586 Volume []volume
587 PostgreSQL []postgresql
588 Ingress []ingress
589 VirtualMachine []vm
giob4a3a192024-08-19 09:55:47 +0400590}
591
592type commitStatusData struct {
593 Navigation []navItem
594 AppName string
595 Commit Commit
596 Resources resourceData
597}
598
599func (s *DodoAppServer) handleAppCommit(w http.ResponseWriter, r *http.Request) {
600 vars := mux.Vars(r)
601 appName, ok := vars["app-name"]
602 if !ok || appName == "" {
603 http.Error(w, "missing app-name", http.StatusBadRequest)
604 return
605 }
606 hash, ok := vars["hash"]
607 if !ok || appName == "" {
608 http.Error(w, "missing app-name", http.StatusBadRequest)
609 return
610 }
611 u := r.Context().Value(userCtx)
612 if u == nil {
613 http.Error(w, "unauthorized", http.StatusUnauthorized)
614 return
615 }
616 user, ok := u.(string)
617 if !ok {
618 http.Error(w, "could not get user", http.StatusInternalServerError)
619 return
620 }
621 owner, err := s.st.GetAppOwner(appName)
622 if err != nil {
623 http.Error(w, err.Error(), http.StatusInternalServerError)
624 return
625 }
626 if owner != user {
627 http.Error(w, "unauthorized", http.StatusUnauthorized)
628 return
629 }
630 commit, err := s.st.GetCommit(hash)
631 if err != nil {
632 // TODO(gio): not-found ?
633 http.Error(w, err.Error(), http.StatusInternalServerError)
634 return
635 }
636 var res strings.Builder
637 if err := json.NewEncoder(&res).Encode(commit.Resources.Helm); err != nil {
638 http.Error(w, err.Error(), http.StatusInternalServerError)
639 return
640 }
641 resData, err := extractResourceData(commit.Resources.Helm)
642 if err != nil {
643 http.Error(w, err.Error(), http.StatusInternalServerError)
644 return
645 }
646 data := commitStatusData{
647 Navigation: []navItem{
648 navItem{"Home", "/"},
649 navItem{appName, "/" + appName},
650 navItem{hash, "/" + appName + "/" + hash},
651 },
652 AppName: appName,
653 Commit: commit,
654 Resources: resData,
655 }
656 if err := s.tmplts.commitStatus.Execute(w, data); err != nil {
657 http.Error(w, err.Error(), http.StatusInternalServerError)
658 return
659 }
660}
661
gio183e8342024-08-20 06:01:24 +0400662type logData struct {
663 Navigation []navItem
664 AppName string
665 Logs template.HTML
666}
667
668func (s *DodoAppServer) handleAppLogs(w http.ResponseWriter, r *http.Request) {
669 vars := mux.Vars(r)
670 appName, ok := vars["app-name"]
671 if !ok || appName == "" {
672 http.Error(w, "missing app-name", http.StatusBadRequest)
673 return
674 }
675 u := r.Context().Value(userCtx)
676 if u == nil {
677 http.Error(w, "unauthorized", http.StatusUnauthorized)
678 return
679 }
680 user, ok := u.(string)
681 if !ok {
682 http.Error(w, "could not get user", http.StatusInternalServerError)
683 return
684 }
685 owner, err := s.st.GetAppOwner(appName)
686 if err != nil {
687 http.Error(w, err.Error(), http.StatusInternalServerError)
688 return
689 }
690 if owner != user {
691 http.Error(w, "unauthorized", http.StatusUnauthorized)
692 return
693 }
694 data := logData{
695 Navigation: []navItem{
696 navItem{"Home", "/"},
697 navItem{appName, "/" + appName},
698 navItem{"Logs", "/" + appName + "/logs"},
699 },
700 AppName: appName,
701 Logs: template.HTML(strings.ReplaceAll(s.logs[appName], "\n", "<br/>")),
702 }
703 if err := s.tmplts.logs.Execute(w, data); err != nil {
704 fmt.Println(err)
705 http.Error(w, err.Error(), http.StatusInternalServerError)
706 return
707 }
708}
709
gio81246f02024-07-10 12:02:15 +0400710type apiUpdateReq struct {
gio266c04f2024-07-03 14:18:45 +0400711 Ref string `json:"ref"`
712 Repository struct {
713 Name string `json:"name"`
714 } `json:"repository"`
gioe2e31e12024-08-18 08:20:56 +0400715 After string `json:"after"`
716 Commits []struct {
717 Id string `json:"id"`
718 Message string `json:"message"`
719 } `json:"commits"`
gio0eaf2712024-04-14 13:08:46 +0400720}
721
gio8fae3af2024-07-25 13:43:31 +0400722func (s *DodoAppServer) handleAPIUpdate(w http.ResponseWriter, r *http.Request) {
gio0eaf2712024-04-14 13:08:46 +0400723 fmt.Println("update")
gio81246f02024-07-10 12:02:15 +0400724 var req apiUpdateReq
gio0eaf2712024-04-14 13:08:46 +0400725 var contents strings.Builder
726 io.Copy(&contents, r.Body)
727 c := contents.String()
728 fmt.Println(c)
729 if err := json.NewDecoder(strings.NewReader(c)).Decode(&req); err != nil {
gio23bdc1b2024-07-11 16:07:47 +0400730 http.Error(w, err.Error(), http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400731 return
732 }
gio7fbd4ad2024-08-27 10:06:39 +0400733 if strings.HasPrefix(req.Ref, "refs/heads/dodo_") || req.Repository.Name == ConfigRepoName {
734 return
735 }
736 branch, ok := strings.CutPrefix(req.Ref, "refs/heads/")
737 if !ok {
738 http.Error(w, "invalid branch", http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400739 return
740 }
gioa60f0de2024-07-08 10:49:48 +0400741 // TODO(gio): Create commit record on app init as well
gio0eaf2712024-04-14 13:08:46 +0400742 go func() {
gio11617ac2024-07-15 16:09:04 +0400743 owner, err := s.st.GetAppOwner(req.Repository.Name)
744 if err != nil {
745 return
746 }
747 networks, err := s.getNetworks(owner)
giocb34ad22024-07-11 08:01:13 +0400748 if err != nil {
749 return
750 }
gio94904702024-07-26 16:58:34 +0400751 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
752 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
753 if err != nil {
754 return
755 }
gioe2e31e12024-08-18 08:20:56 +0400756 found := false
757 commitMsg := ""
758 for _, c := range req.Commits {
759 if c.Id == req.After {
760 found = true
761 commitMsg = c.Message
762 break
gioa60f0de2024-07-08 10:49:48 +0400763 }
764 }
gioe2e31e12024-08-18 08:20:56 +0400765 if !found {
766 fmt.Printf("Error: could not find commit message")
767 return
768 }
gio7fbd4ad2024-08-27 10:06:39 +0400769 s.l.Lock()
770 defer s.l.Unlock()
771 resources, err := s.updateDodoApp(instanceAppStatus, req.Repository.Name, branch, s.getAppConfig(req.Repository.Name, branch).Namespace, networks, owner)
772 if err = s.createCommit(req.Repository.Name, branch, req.After, commitMsg, err, resources); err != nil {
gio12e887d2024-08-18 16:09:47 +0400773 fmt.Printf("Error: %s\n", err.Error())
gioe2e31e12024-08-18 08:20:56 +0400774 return
775 }
gioa60f0de2024-07-08 10:49:48 +0400776 for addr, _ := range s.workers[req.Repository.Name] {
777 go func() {
778 // TODO(gio): make port configurable
779 http.Get(fmt.Sprintf("http://%s/update", addr))
780 }()
gio0eaf2712024-04-14 13:08:46 +0400781 }
782 }()
gio0eaf2712024-04-14 13:08:46 +0400783}
784
gio81246f02024-07-10 12:02:15 +0400785type apiRegisterWorkerReq struct {
gio0eaf2712024-04-14 13:08:46 +0400786 Address string `json:"address"`
gio183e8342024-08-20 06:01:24 +0400787 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400788}
789
gio8fae3af2024-07-25 13:43:31 +0400790func (s *DodoAppServer) handleAPIRegisterWorker(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400791 // TODO(gio): lock
gioa60f0de2024-07-08 10:49:48 +0400792 vars := mux.Vars(r)
793 appName, ok := vars["app-name"]
794 if !ok || appName == "" {
795 http.Error(w, "missing app-name", http.StatusBadRequest)
796 return
797 }
gio81246f02024-07-10 12:02:15 +0400798 var req apiRegisterWorkerReq
gio0eaf2712024-04-14 13:08:46 +0400799 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
800 http.Error(w, err.Error(), http.StatusInternalServerError)
801 return
802 }
gioa60f0de2024-07-08 10:49:48 +0400803 if _, ok := s.workers[appName]; !ok {
804 s.workers[appName] = map[string]struct{}{}
gio266c04f2024-07-03 14:18:45 +0400805 }
gioa60f0de2024-07-08 10:49:48 +0400806 s.workers[appName][req.Address] = struct{}{}
gio183e8342024-08-20 06:01:24 +0400807 s.logs[appName] = req.Logs
gio0eaf2712024-04-14 13:08:46 +0400808}
809
gio11617ac2024-07-15 16:09:04 +0400810func (s *DodoAppServer) handleCreateApp(w http.ResponseWriter, r *http.Request) {
811 u := r.Context().Value(userCtx)
812 if u == nil {
813 http.Error(w, "unauthorized", http.StatusUnauthorized)
814 return
815 }
816 user, ok := u.(string)
817 if !ok {
818 http.Error(w, "could not get user", http.StatusInternalServerError)
819 return
820 }
821 network := r.FormValue("network")
822 if network == "" {
823 http.Error(w, "missing network", http.StatusBadRequest)
824 return
825 }
gio5e49bb62024-07-20 10:43:19 +0400826 subdomain := r.FormValue("subdomain")
827 if subdomain == "" {
828 http.Error(w, "missing subdomain", http.StatusBadRequest)
829 return
830 }
831 appType := r.FormValue("type")
832 if appType == "" {
833 http.Error(w, "missing type", http.StatusBadRequest)
834 return
835 }
gio11617ac2024-07-15 16:09:04 +0400836 g := installer.NewFixedLengthRandomNameGenerator(3)
837 appName, err := g.Generate()
838 if err != nil {
839 http.Error(w, err.Error(), http.StatusInternalServerError)
840 return
841 }
842 if ok, err := s.client.UserExists(user); err != nil {
843 http.Error(w, err.Error(), http.StatusInternalServerError)
844 return
845 } else if !ok {
giocafd4e62024-07-31 10:53:40 +0400846 http.Error(w, "user sync has not finished, please try again in few minutes", http.StatusFailedDependency)
847 return
gio11617ac2024-07-15 16:09:04 +0400848 }
giocafd4e62024-07-31 10:53:40 +0400849 if err := s.st.CreateUser(user, nil, network); err != nil && !errors.Is(err, ErrorAlreadyExists) {
gio11617ac2024-07-15 16:09:04 +0400850 http.Error(w, err.Error(), http.StatusInternalServerError)
851 return
852 }
853 if err := s.st.CreateApp(appName, user); err != nil {
854 http.Error(w, err.Error(), http.StatusInternalServerError)
855 return
856 }
giod8ab4f52024-07-26 16:58:34 +0400857 if err := s.createApp(user, appName, appType, network, subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +0400858 http.Error(w, err.Error(), http.StatusInternalServerError)
859 return
860 }
861 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
862}
863
gio7fbd4ad2024-08-27 10:06:39 +0400864func (s *DodoAppServer) handleCreateDevBranch(w http.ResponseWriter, r *http.Request) {
865 u := r.Context().Value(userCtx)
866 if u == nil {
867 http.Error(w, "unauthorized", http.StatusUnauthorized)
868 return
869 }
870 user, ok := u.(string)
871 if !ok {
872 http.Error(w, "could not get user", http.StatusInternalServerError)
873 return
874 }
875 vars := mux.Vars(r)
876 appName, ok := vars["app-name"]
877 if !ok || appName == "" {
878 http.Error(w, "missing app-name", http.StatusBadRequest)
879 return
880 }
881 branch := r.FormValue("branch")
882 if branch == "" {
883 http.Error(w, "missing network", http.StatusBadRequest)
884 return
885 }
886 if err := s.createDevBranch(appName, "master", branch, user); err != nil {
887 http.Error(w, err.Error(), http.StatusInternalServerError)
888 return
889 }
890 http.Redirect(w, r, fmt.Sprintf("/%s/branch/%s", appName, branch), http.StatusSeeOther)
891}
892
gio81246f02024-07-10 12:02:15 +0400893type apiCreateAppReq struct {
gio5e49bb62024-07-20 10:43:19 +0400894 AppType string `json:"type"`
gio33059762024-07-05 13:19:07 +0400895 AdminPublicKey string `json:"adminPublicKey"`
gio11617ac2024-07-15 16:09:04 +0400896 Network string `json:"network"`
gio5e49bb62024-07-20 10:43:19 +0400897 Subdomain string `json:"subdomain"`
gio33059762024-07-05 13:19:07 +0400898}
899
gio81246f02024-07-10 12:02:15 +0400900type apiCreateAppResp struct {
901 AppName string `json:"appName"`
902 Password string `json:"password"`
gio33059762024-07-05 13:19:07 +0400903}
904
gio8fae3af2024-07-25 13:43:31 +0400905func (s *DodoAppServer) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +0400906 w.Header().Set("Access-Control-Allow-Origin", "*")
gio81246f02024-07-10 12:02:15 +0400907 var req apiCreateAppReq
gio33059762024-07-05 13:19:07 +0400908 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
909 http.Error(w, err.Error(), http.StatusBadRequest)
910 return
911 }
912 g := installer.NewFixedLengthRandomNameGenerator(3)
913 appName, err := g.Generate()
914 if err != nil {
915 http.Error(w, err.Error(), http.StatusInternalServerError)
916 return
917 }
gio11617ac2024-07-15 16:09:04 +0400918 user, err := s.client.FindUser(req.AdminPublicKey)
gio81246f02024-07-10 12:02:15 +0400919 if err != nil {
gio33059762024-07-05 13:19:07 +0400920 http.Error(w, err.Error(), http.StatusInternalServerError)
921 return
922 }
gio11617ac2024-07-15 16:09:04 +0400923 if user != "" {
924 http.Error(w, "public key already registered", http.StatusBadRequest)
925 return
926 }
927 user = appName
928 if err := s.client.AddUser(user, req.AdminPublicKey); err != nil {
929 http.Error(w, err.Error(), http.StatusInternalServerError)
930 return
931 }
932 password := generatePassword()
933 hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
934 if err != nil {
935 http.Error(w, err.Error(), http.StatusInternalServerError)
936 return
937 }
giocafd4e62024-07-31 10:53:40 +0400938 if err := s.st.CreateUser(user, hashed, req.Network); err != nil {
gio11617ac2024-07-15 16:09:04 +0400939 http.Error(w, err.Error(), http.StatusInternalServerError)
940 return
941 }
942 if err := s.st.CreateApp(appName, user); err != nil {
943 http.Error(w, err.Error(), http.StatusInternalServerError)
944 return
945 }
giod8ab4f52024-07-26 16:58:34 +0400946 if err := s.createApp(user, appName, req.AppType, req.Network, req.Subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +0400947 http.Error(w, err.Error(), http.StatusInternalServerError)
948 return
949 }
gio81246f02024-07-10 12:02:15 +0400950 resp := apiCreateAppResp{
951 AppName: appName,
952 Password: password,
953 }
gio33059762024-07-05 13:19:07 +0400954 if err := json.NewEncoder(w).Encode(resp); err != nil {
955 http.Error(w, err.Error(), http.StatusInternalServerError)
956 return
957 }
958}
959
giod8ab4f52024-07-26 16:58:34 +0400960func (s *DodoAppServer) isNetworkUseAllowed(network string) bool {
giocafd4e62024-07-31 10:53:40 +0400961 if !s.external {
giod8ab4f52024-07-26 16:58:34 +0400962 return true
963 }
964 for _, cfg := range s.appConfigs {
965 if strings.ToLower(cfg.Network) == network {
966 return false
967 }
968 }
969 return true
970}
971
972func (s *DodoAppServer) createApp(user, appName, appType, network, subdomain string) error {
gio9d66f322024-07-06 13:45:10 +0400973 s.l.Lock()
974 defer s.l.Unlock()
gio33059762024-07-05 13:19:07 +0400975 fmt.Printf("Creating app: %s\n", appName)
giod8ab4f52024-07-26 16:58:34 +0400976 network = strings.ToLower(network)
977 if !s.isNetworkUseAllowed(network) {
978 return fmt.Errorf("network already used: %s", network)
979 }
gio33059762024-07-05 13:19:07 +0400980 if ok, err := s.client.RepoExists(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +0400981 return err
gio33059762024-07-05 13:19:07 +0400982 } else if ok {
gio11617ac2024-07-15 16:09:04 +0400983 return nil
gioa60f0de2024-07-08 10:49:48 +0400984 }
gio5e49bb62024-07-20 10:43:19 +0400985 networks, err := s.getNetworks(user)
986 if err != nil {
987 return err
988 }
giod8ab4f52024-07-26 16:58:34 +0400989 n, ok := installer.NetworkMap(networks)[network]
gio5e49bb62024-07-20 10:43:19 +0400990 if !ok {
991 return fmt.Errorf("network not found: %s\n", network)
992 }
gio33059762024-07-05 13:19:07 +0400993 if err := s.client.AddRepository(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +0400994 return err
gio33059762024-07-05 13:19:07 +0400995 }
996 appRepo, err := s.client.GetRepo(appName)
997 if err != nil {
gio11617ac2024-07-15 16:09:04 +0400998 return err
gio33059762024-07-05 13:19:07 +0400999 }
gio7fbd4ad2024-08-27 10:06:39 +04001000 files, err := s.renderAppConfigTemplate(appType, n, subdomain)
1001 if err != nil {
1002 return err
1003 }
1004 return s.createAppForBranch(appRepo, appName, "master", user, network, files)
1005}
1006
1007func (s *DodoAppServer) createDevBranch(appName, fromBranch, toBranch, user string) error {
1008 s.l.Lock()
1009 defer s.l.Unlock()
1010 fmt.Printf("Creating dev branch app: %s %s %s\n", appName, fromBranch, toBranch)
1011 appRepo, err := s.client.GetRepoBranch(appName, fromBranch)
1012 if err != nil {
1013 return err
1014 }
1015 appCfg, err := soft.ReadFile(appRepo, "app.cue")
1016 if err != nil {
1017 return err
1018 }
1019 network, branchCfg, err := createDevBranchAppConfig(appCfg, toBranch, user)
1020 if err != nil {
1021 return err
1022 }
1023 return s.createAppForBranch(appRepo, appName, toBranch, user, network, map[string][]byte{"app.cue": branchCfg})
1024}
1025
1026func (s *DodoAppServer) createAppForBranch(
1027 repo soft.RepoIO,
1028 appName string,
1029 branch string,
1030 user string,
1031 network string,
1032 files map[string][]byte,
1033) error {
1034 commit, err := repo.Do(func(fs soft.RepoFS) (string, error) {
1035 for path, contents := range files {
1036 if err := soft.WriteFile(fs, path, string(contents)); err != nil {
1037 return "", err
1038 }
1039 }
1040 return "init", nil
1041 }, soft.WithCommitToBranch(branch))
1042 if err != nil {
1043 return err
1044 }
1045 networks, err := s.getNetworks(user)
giob4a3a192024-08-19 09:55:47 +04001046 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001047 return err
gio33059762024-07-05 13:19:07 +04001048 }
1049 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
gio94904702024-07-26 16:58:34 +04001050 instanceApp, err := installer.FindEnvApp(apps, "dodo-app-instance")
1051 if err != nil {
1052 return err
1053 }
1054 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
gio33059762024-07-05 13:19:07 +04001055 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001056 return err
gio33059762024-07-05 13:19:07 +04001057 }
1058 suffixGen := installer.NewFixedLengthRandomSuffixGenerator(3)
1059 suffix, err := suffixGen.Generate()
1060 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001061 return err
gio33059762024-07-05 13:19:07 +04001062 }
gio94904702024-07-26 16:58:34 +04001063 namespace := fmt.Sprintf("%s%s%s", s.env.NamespacePrefix, instanceApp.Namespace(), suffix)
gio7fbd4ad2024-08-27 10:06:39 +04001064 s.setAppConfig(appName, branch, appConfig{namespace, network})
1065 resources, err := s.updateDodoApp(instanceAppStatus, appName, branch, namespace, networks, user)
giob4a3a192024-08-19 09:55:47 +04001066 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001067 fmt.Printf("Error: %s\n", err.Error())
giob4a3a192024-08-19 09:55:47 +04001068 return err
1069 }
gio7fbd4ad2024-08-27 10:06:39 +04001070 if err = s.createCommit(appName, branch, commit, initCommitMsg, err, resources); err != nil {
giob4a3a192024-08-19 09:55:47 +04001071 fmt.Printf("Error: %s\n", err.Error())
gio11617ac2024-07-15 16:09:04 +04001072 return err
gio33059762024-07-05 13:19:07 +04001073 }
giod8ab4f52024-07-26 16:58:34 +04001074 configRepo, err := s.client.GetRepo(ConfigRepoName)
gio33059762024-07-05 13:19:07 +04001075 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001076 return err
gio33059762024-07-05 13:19:07 +04001077 }
1078 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001079 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
gio33059762024-07-05 13:19:07 +04001080 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001081 return err
gio33059762024-07-05 13:19:07 +04001082 }
gio7fbd4ad2024-08-27 10:06:39 +04001083 appPath := fmt.Sprintf("/%s/%s", appName, branch)
giob4a3a192024-08-19 09:55:47 +04001084 _, err = configRepo.Do(func(fs soft.RepoFS) (string, error) {
giod8ab4f52024-07-26 16:58:34 +04001085 w, err := fs.Writer(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +04001086 if err != nil {
1087 return "", err
1088 }
1089 defer w.Close()
giod8ab4f52024-07-26 16:58:34 +04001090 if err := json.NewEncoder(w).Encode(s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +04001091 return "", err
1092 }
1093 if _, err := m.Install(
gio94904702024-07-26 16:58:34 +04001094 instanceApp,
gio9d66f322024-07-06 13:45:10 +04001095 appName,
gio7fbd4ad2024-08-27 10:06:39 +04001096 appPath,
gio9d66f322024-07-06 13:45:10 +04001097 namespace,
1098 map[string]any{
1099 "repoAddr": s.client.GetRepoAddress(appName),
1100 "repoHost": strings.Split(s.client.Address(), ":")[0],
gio7fbd4ad2024-08-27 10:06:39 +04001101 "branch": fmt.Sprintf("dodo_%s", branch),
gio9d66f322024-07-06 13:45:10 +04001102 "gitRepoPublicKey": s.gitRepoPublicKey,
1103 },
1104 installer.WithConfig(&s.env),
gio23bdc1b2024-07-11 16:07:47 +04001105 installer.WithNoNetworks(),
gio9d66f322024-07-06 13:45:10 +04001106 installer.WithNoPublish(),
1107 installer.WithNoLock(),
1108 ); err != nil {
1109 return "", err
1110 }
1111 return fmt.Sprintf("Installed app: %s", appName), nil
giob4a3a192024-08-19 09:55:47 +04001112 })
1113 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001114 return err
gio33059762024-07-05 13:19:07 +04001115 }
gio7fbd4ad2024-08-27 10:06:39 +04001116 return s.initAppACLs(m, appPath, appName, branch, user)
1117}
1118
1119func (s *DodoAppServer) initAppACLs(m *installer.AppManager, path, appName, branch, user string) error {
1120 cfg, err := m.GetInstance(path)
gio33059762024-07-05 13:19:07 +04001121 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001122 return err
gio33059762024-07-05 13:19:07 +04001123 }
1124 fluxKeys, ok := cfg.Input["fluxKeys"]
1125 if !ok {
gio11617ac2024-07-15 16:09:04 +04001126 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001127 }
1128 fluxPublicKey, ok := fluxKeys.(map[string]any)["public"]
1129 if !ok {
gio11617ac2024-07-15 16:09:04 +04001130 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001131 }
1132 if ok, err := s.client.UserExists("fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001133 return err
gio33059762024-07-05 13:19:07 +04001134 } else if ok {
1135 if err := s.client.AddPublicKey("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001136 return err
gio33059762024-07-05 13:19:07 +04001137 }
1138 } else {
1139 if err := s.client.AddUser("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001140 return err
gio33059762024-07-05 13:19:07 +04001141 }
1142 }
gio7fbd4ad2024-08-27 10:06:39 +04001143 if branch != "master" {
1144 return nil
1145 }
gio33059762024-07-05 13:19:07 +04001146 if err := s.client.AddReadOnlyCollaborator(appName, "fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001147 return err
gio33059762024-07-05 13:19:07 +04001148 }
gio7fbd4ad2024-08-27 10:06:39 +04001149 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
gio11617ac2024-07-15 16:09:04 +04001150 return err
gio33059762024-07-05 13:19:07 +04001151 }
gio7fbd4ad2024-08-27 10:06:39 +04001152 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 +04001153 return err
gio33059762024-07-05 13:19:07 +04001154 }
gio2ccb6e32024-08-15 12:01:33 +04001155 if !s.external {
1156 go func() {
1157 users, err := s.client.GetAllUsers()
1158 if err != nil {
1159 fmt.Println(err)
1160 return
1161 }
1162 for _, user := range users {
1163 // TODO(gio): fluxcd should have only read access
1164 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
1165 fmt.Println(err)
1166 }
1167 }
1168 }()
1169 }
gio43b0f422024-08-21 10:40:13 +04001170 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1171 go s.reconciler.Reconcile(ctx, s.namespace, "config")
gio11617ac2024-07-15 16:09:04 +04001172 return nil
gio33059762024-07-05 13:19:07 +04001173}
1174
gio81246f02024-07-10 12:02:15 +04001175type apiAddAdminKeyReq struct {
gio7fbd4ad2024-08-27 10:06:39 +04001176 User string `json:"user"`
1177 PublicKey string `json:"publicKey"`
gio70be3e52024-06-26 18:27:19 +04001178}
1179
gio7fbd4ad2024-08-27 10:06:39 +04001180func (s *DodoAppServer) handleAPIAddPublicKey(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +04001181 var req apiAddAdminKeyReq
gio70be3e52024-06-26 18:27:19 +04001182 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1183 http.Error(w, err.Error(), http.StatusBadRequest)
1184 return
1185 }
gio7fbd4ad2024-08-27 10:06:39 +04001186 if req.User == "" {
1187 http.Error(w, "invalid user", http.StatusBadRequest)
1188 return
1189 }
1190 if req.PublicKey == "" {
1191 http.Error(w, "invalid public key", http.StatusBadRequest)
1192 return
1193 }
1194 if err := s.client.AddPublicKey(req.User, req.PublicKey); err != nil {
gio70be3e52024-06-26 18:27:19 +04001195 http.Error(w, err.Error(), http.StatusInternalServerError)
1196 return
1197 }
1198}
1199
gio94904702024-07-26 16:58:34 +04001200type dodoAppRendered struct {
1201 App struct {
1202 Ingress struct {
1203 Network string `json:"network"`
1204 Subdomain string `json:"subdomain"`
1205 } `json:"ingress"`
1206 } `json:"app"`
1207 Input struct {
1208 AppId string `json:"appId"`
1209 } `json:"input"`
1210}
1211
gio7fbd4ad2024-08-27 10:06:39 +04001212// TODO(gio): must not require owner, now we need it to bootstrap dev vm.
gio43b0f422024-08-21 10:40:13 +04001213func (s *DodoAppServer) updateDodoApp(
1214 appStatus installer.EnvApp,
gio7fbd4ad2024-08-27 10:06:39 +04001215 name string,
1216 branch string,
1217 namespace string,
gio43b0f422024-08-21 10:40:13 +04001218 networks []installer.Network,
gio7fbd4ad2024-08-27 10:06:39 +04001219 owner string,
gio43b0f422024-08-21 10:40:13 +04001220) (installer.ReleaseResources, error) {
gio7fbd4ad2024-08-27 10:06:39 +04001221 repo, err := s.client.GetRepoBranch(name, branch)
gio0eaf2712024-04-14 13:08:46 +04001222 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001223 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001224 }
giof8843412024-05-22 16:38:05 +04001225 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001226 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
gio0eaf2712024-04-14 13:08:46 +04001227 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001228 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001229 }
1230 appCfg, err := soft.ReadFile(repo, "app.cue")
gio0eaf2712024-04-14 13:08:46 +04001231 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001232 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001233 }
1234 app, err := installer.NewDodoApp(appCfg)
1235 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001236 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001237 }
giof8843412024-05-22 16:38:05 +04001238 lg := installer.GitRepositoryLocalChartGenerator{"app", namespace}
giob4a3a192024-08-19 09:55:47 +04001239 var ret installer.ReleaseResources
1240 if _, err := repo.Do(func(r soft.RepoFS) (string, error) {
1241 ret, err = m.Install(
gio94904702024-07-26 16:58:34 +04001242 app,
1243 "app",
1244 "/.dodo/app",
1245 namespace,
1246 map[string]any{
gio7fbd4ad2024-08-27 10:06:39 +04001247 "repoAddr": repo.FullAddress(),
1248 "repoPublicAddr": s.repoPublicAddr,
1249 "managerAddr": fmt.Sprintf("http://%s", s.self),
1250 "appId": name,
1251 "branch": branch,
1252 "sshPrivateKey": s.sshKey,
1253 "username": owner,
gio94904702024-07-26 16:58:34 +04001254 },
1255 installer.WithNoPull(),
1256 installer.WithNoPublish(),
1257 installer.WithConfig(&s.env),
1258 installer.WithNetworks(networks),
1259 installer.WithLocalChartGenerator(lg),
1260 installer.WithNoLock(),
1261 )
1262 if err != nil {
1263 return "", err
1264 }
1265 var rendered dodoAppRendered
giob4a3a192024-08-19 09:55:47 +04001266 if err := json.NewDecoder(bytes.NewReader(ret.RenderedRaw)).Decode(&rendered); err != nil {
gio94904702024-07-26 16:58:34 +04001267 return "", nil
1268 }
1269 if _, err := m.Install(
1270 appStatus,
1271 "status",
1272 "/.dodo/status",
1273 s.namespace,
1274 map[string]any{
1275 "appName": rendered.Input.AppId,
1276 "network": rendered.App.Ingress.Network,
1277 "appSubdomain": rendered.App.Ingress.Subdomain,
1278 },
1279 installer.WithNoPull(),
1280 installer.WithNoPublish(),
1281 installer.WithConfig(&s.env),
1282 installer.WithNetworks(networks),
1283 installer.WithLocalChartGenerator(lg),
1284 installer.WithNoLock(),
1285 ); err != nil {
1286 return "", err
1287 }
1288 return "install app", nil
1289 },
gio7fbd4ad2024-08-27 10:06:39 +04001290 soft.WithCommitToBranch(fmt.Sprintf("dodo_%s", branch)),
gio94904702024-07-26 16:58:34 +04001291 soft.WithForce(),
giob4a3a192024-08-19 09:55:47 +04001292 ); err != nil {
1293 return installer.ReleaseResources{}, err
1294 }
gio43b0f422024-08-21 10:40:13 +04001295 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1296 go s.reconciler.Reconcile(ctx, namespace, "app")
giob4a3a192024-08-19 09:55:47 +04001297 return ret, nil
gio0eaf2712024-04-14 13:08:46 +04001298}
gio33059762024-07-05 13:19:07 +04001299
gio7fbd4ad2024-08-27 10:06:39 +04001300func (s *DodoAppServer) renderAppConfigTemplate(appType string, network installer.Network, subdomain string) (map[string][]byte, error) {
giob54db242024-07-30 18:49:33 +04001301 appType = strings.Replace(appType, ":", "-", 1)
gio5e49bb62024-07-20 10:43:19 +04001302 appTmpl, err := s.appTmpls.Find(appType)
1303 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001304 return nil, err
gio33059762024-07-05 13:19:07 +04001305 }
gio7fbd4ad2024-08-27 10:06:39 +04001306 return appTmpl.Render(network, subdomain)
gio33059762024-07-05 13:19:07 +04001307}
gio81246f02024-07-10 12:02:15 +04001308
1309func generatePassword() string {
1310 return "foo"
1311}
giocb34ad22024-07-11 08:01:13 +04001312
gio11617ac2024-07-15 16:09:04 +04001313func (s *DodoAppServer) getNetworks(user string) ([]installer.Network, error) {
gio23bdc1b2024-07-11 16:07:47 +04001314 addr := fmt.Sprintf("%s/api/networks", s.envAppManagerAddr)
giocb34ad22024-07-11 08:01:13 +04001315 resp, err := http.Get(addr)
1316 if err != nil {
1317 return nil, err
1318 }
gio23bdc1b2024-07-11 16:07:47 +04001319 networks := []installer.Network{}
1320 if json.NewDecoder(resp.Body).Decode(&networks); err != nil {
giocb34ad22024-07-11 08:01:13 +04001321 return nil, err
1322 }
gio11617ac2024-07-15 16:09:04 +04001323 return s.nf.Filter(user, networks)
1324}
1325
gio8fae3af2024-07-25 13:43:31 +04001326type publicNetworkData struct {
1327 Name string `json:"name"`
1328 Domain string `json:"domain"`
1329}
1330
1331type publicData struct {
1332 Networks []publicNetworkData `json:"networks"`
1333 Types []string `json:"types"`
1334}
1335
1336func (s *DodoAppServer) handleAPIPublicData(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001337 w.Header().Set("Access-Control-Allow-Origin", "*")
1338 s.l.Lock()
1339 defer s.l.Unlock()
gio8fae3af2024-07-25 13:43:31 +04001340 networks, err := s.getNetworks("")
1341 if err != nil {
1342 http.Error(w, err.Error(), http.StatusInternalServerError)
1343 return
1344 }
1345 var ret publicData
1346 for _, n := range networks {
giod8ab4f52024-07-26 16:58:34 +04001347 if s.isNetworkUseAllowed(strings.ToLower(n.Name)) {
1348 ret.Networks = append(ret.Networks, publicNetworkData{n.Name, n.Domain})
1349 }
gio8fae3af2024-07-25 13:43:31 +04001350 }
1351 for _, t := range s.appTmpls.Types() {
giob54db242024-07-30 18:49:33 +04001352 ret.Types = append(ret.Types, strings.Replace(t, "-", ":", 1))
gio8fae3af2024-07-25 13:43:31 +04001353 }
gio8fae3af2024-07-25 13:43:31 +04001354 if err := json.NewEncoder(w).Encode(ret); err != nil {
1355 http.Error(w, err.Error(), http.StatusInternalServerError)
1356 return
1357 }
1358}
1359
gio7fbd4ad2024-08-27 10:06:39 +04001360func (s *DodoAppServer) createCommit(name, branch, hash, message string, err error, resources installer.ReleaseResources) error {
giob4a3a192024-08-19 09:55:47 +04001361 if err != nil {
1362 fmt.Printf("Error: %s\n", err.Error())
gio7fbd4ad2024-08-27 10:06:39 +04001363 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001364 fmt.Printf("Error: %s\n", err.Error())
1365 return err
1366 }
1367 return err
1368 }
1369 var resB bytes.Buffer
1370 if err := json.NewEncoder(&resB).Encode(resources); err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001371 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001372 fmt.Printf("Error: %s\n", err.Error())
1373 return err
1374 }
1375 return err
1376 }
gio7fbd4ad2024-08-27 10:06:39 +04001377 if err := s.st.CreateCommit(name, branch, hash, message, "OK", "", resB.Bytes()); err != nil {
giob4a3a192024-08-19 09:55:47 +04001378 fmt.Printf("Error: %s\n", err.Error())
1379 return err
1380 }
1381 return nil
1382}
1383
gio11617ac2024-07-15 16:09:04 +04001384func pickNetwork(networks []installer.Network, network string) []installer.Network {
1385 for _, n := range networks {
1386 if n.Name == network {
1387 return []installer.Network{n}
1388 }
1389 }
1390 return []installer.Network{}
1391}
1392
1393type NetworkFilter interface {
1394 Filter(user string, networks []installer.Network) ([]installer.Network, error)
1395}
1396
1397type noNetworkFilter struct{}
1398
1399func NewNoNetworkFilter() NetworkFilter {
1400 return noNetworkFilter{}
1401}
1402
gio8fae3af2024-07-25 13:43:31 +04001403func (f noNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001404 return networks, nil
1405}
1406
1407type filterByOwner struct {
1408 st Store
1409}
1410
1411func NewNetworkFilterByOwner(st Store) NetworkFilter {
1412 return &filterByOwner{st}
1413}
1414
1415func (f *filterByOwner) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio8fae3af2024-07-25 13:43:31 +04001416 if user == "" {
1417 return networks, nil
1418 }
gio11617ac2024-07-15 16:09:04 +04001419 network, err := f.st.GetUserNetwork(user)
1420 if err != nil {
1421 return nil, err
gio23bdc1b2024-07-11 16:07:47 +04001422 }
1423 ret := []installer.Network{}
1424 for _, n := range networks {
gio11617ac2024-07-15 16:09:04 +04001425 if n.Name == network {
gio23bdc1b2024-07-11 16:07:47 +04001426 ret = append(ret, n)
1427 }
1428 }
giocb34ad22024-07-11 08:01:13 +04001429 return ret, nil
1430}
gio11617ac2024-07-15 16:09:04 +04001431
1432type allowListFilter struct {
1433 allowed []string
1434}
1435
1436func NewAllowListFilter(allowed []string) NetworkFilter {
1437 return &allowListFilter{allowed}
1438}
1439
gio8fae3af2024-07-25 13:43:31 +04001440func (f *allowListFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001441 ret := []installer.Network{}
1442 for _, n := range networks {
1443 if slices.Contains(f.allowed, n.Name) {
1444 ret = append(ret, n)
1445 }
1446 }
1447 return ret, nil
1448}
1449
1450type combinedNetworkFilter struct {
1451 filters []NetworkFilter
1452}
1453
1454func NewCombinedFilter(filters ...NetworkFilter) NetworkFilter {
1455 return &combinedNetworkFilter{filters}
1456}
1457
gio8fae3af2024-07-25 13:43:31 +04001458func (f *combinedNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001459 ret := networks
1460 var err error
1461 for _, f := range f.filters {
gio8fae3af2024-07-25 13:43:31 +04001462 ret, err = f.Filter(user, ret)
gio11617ac2024-07-15 16:09:04 +04001463 if err != nil {
1464 return nil, err
1465 }
1466 }
1467 return ret, nil
1468}
giocafd4e62024-07-31 10:53:40 +04001469
1470type user struct {
1471 Username string `json:"username"`
1472 Email string `json:"email"`
1473 SSHPublicKeys []string `json:"sshPublicKeys,omitempty"`
1474}
1475
1476func (s *DodoAppServer) handleAPISyncUsers(_ http.ResponseWriter, _ *http.Request) {
1477 go s.syncUsers()
1478}
1479
1480func (s *DodoAppServer) syncUsers() {
1481 if s.external {
1482 panic("MUST NOT REACH!")
1483 }
1484 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/api/sync-users", s.fetchUsersAddr, s.self))
1485 if err != nil {
1486 return
1487 }
1488 users := []user{}
1489 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
1490 fmt.Println(err)
1491 return
1492 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001493 validUsernames := make(map[string]user)
1494 for _, u := range users {
1495 validUsernames[u.Username] = u
1496 }
1497 allClientUsers, err := s.client.GetAllUsers()
1498 if err != nil {
1499 fmt.Println(err)
1500 return
1501 }
1502 keyToUser := make(map[string]string)
1503 for _, clientUser := range allClientUsers {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001504 if clientUser == "admin" || clientUser == "fluxcd" {
1505 continue
1506 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001507 userData, ok := validUsernames[clientUser]
1508 if !ok {
1509 if err := s.client.RemoveUser(clientUser); err != nil {
1510 fmt.Println(err)
1511 return
1512 }
1513 } else {
1514 existingKeys, err := s.client.GetUserPublicKeys(clientUser)
1515 if err != nil {
1516 fmt.Println(err)
1517 return
1518 }
1519 for _, existingKey := range existingKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001520 cleanKey := soft.CleanKey(existingKey)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001521 keyOk := slices.ContainsFunc(userData.SSHPublicKeys, func(key string) bool {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001522 return cleanKey == soft.CleanKey(key)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001523 })
1524 if !keyOk {
1525 if err := s.client.RemovePublicKey(clientUser, existingKey); err != nil {
1526 fmt.Println(err)
1527 }
1528 } else {
1529 keyToUser[cleanKey] = clientUser
1530 }
1531 }
1532 }
1533 }
giocafd4e62024-07-31 10:53:40 +04001534 for _, u := range users {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001535 if err := s.st.CreateUser(u.Username, nil, ""); err != nil && !errors.Is(err, ErrorAlreadyExists) {
1536 fmt.Println(err)
1537 return
1538 }
giocafd4e62024-07-31 10:53:40 +04001539 if len(u.SSHPublicKeys) == 0 {
1540 continue
1541 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001542 ok, err := s.client.UserExists(u.Username)
1543 if err != nil {
giocafd4e62024-07-31 10:53:40 +04001544 fmt.Println(err)
1545 return
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001546 }
1547 if !ok {
1548 if err := s.client.AddUser(u.Username, u.SSHPublicKeys[0]); err != nil {
1549 fmt.Println(err)
1550 return
1551 }
1552 } else {
1553 for _, key := range u.SSHPublicKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001554 cleanKey := soft.CleanKey(key)
1555 if user, ok := keyToUser[cleanKey]; ok {
1556 if u.Username != user {
1557 panic("MUST NOT REACH! IMPOSSIBLE KEY USER RECORD")
1558 }
1559 continue
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001560 }
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001561 if err := s.client.AddPublicKey(u.Username, cleanKey); err != nil {
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001562 fmt.Println(err)
1563 return
giocafd4e62024-07-31 10:53:40 +04001564 }
1565 }
1566 }
1567 }
1568 repos, err := s.client.GetAllRepos()
1569 if err != nil {
1570 return
1571 }
1572 for _, r := range repos {
1573 if r == ConfigRepoName {
1574 continue
1575 }
1576 for _, u := range users {
1577 if err := s.client.AddReadWriteCollaborator(r, u.Username); err != nil {
1578 fmt.Println(err)
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001579 continue
giocafd4e62024-07-31 10:53:40 +04001580 }
1581 }
1582 }
1583}
giob4a3a192024-08-19 09:55:47 +04001584
1585func extractResourceData(resources []installer.Resource) (resourceData, error) {
1586 var ret resourceData
1587 for _, r := range resources {
1588 t, ok := r.Annotations["dodo.cloud/resource-type"]
1589 if !ok {
1590 continue
1591 }
1592 switch t {
1593 case "volume":
1594 name, ok := r.Annotations["dodo.cloud/resource.volume.name"]
1595 if !ok {
1596 return resourceData{}, fmt.Errorf("no name")
1597 }
1598 size, ok := r.Annotations["dodo.cloud/resource.volume.size"]
1599 if !ok {
1600 return resourceData{}, fmt.Errorf("no size")
1601 }
1602 ret.Volume = append(ret.Volume, volume{name, size})
1603 case "postgresql":
1604 name, ok := r.Annotations["dodo.cloud/resource.postgresql.name"]
1605 if !ok {
1606 return resourceData{}, fmt.Errorf("no name")
1607 }
1608 version, ok := r.Annotations["dodo.cloud/resource.postgresql.version"]
1609 if !ok {
1610 return resourceData{}, fmt.Errorf("no version")
1611 }
1612 volume, ok := r.Annotations["dodo.cloud/resource.postgresql.volume"]
1613 if !ok {
1614 return resourceData{}, fmt.Errorf("no volume")
1615 }
1616 ret.PostgreSQL = append(ret.PostgreSQL, postgresql{name, version, volume})
1617 case "ingress":
1618 host, ok := r.Annotations["dodo.cloud/resource.ingress.host"]
1619 if !ok {
1620 return resourceData{}, fmt.Errorf("no host")
1621 }
1622 ret.Ingress = append(ret.Ingress, ingress{host})
gio7fbd4ad2024-08-27 10:06:39 +04001623 case "virtual-machine":
1624 name, ok := r.Annotations["dodo.cloud/resource.virtual-machine.name"]
1625 if !ok {
1626 return resourceData{}, fmt.Errorf("no name")
1627 }
1628 user, ok := r.Annotations["dodo.cloud/resource.virtual-machine.user"]
1629 if !ok {
1630 return resourceData{}, fmt.Errorf("no user")
1631 }
1632 cpuCoresS, ok := r.Annotations["dodo.cloud/resource.virtual-machine.cpu-cores"]
1633 if !ok {
1634 return resourceData{}, fmt.Errorf("no cpu cores")
1635 }
1636 cpuCores, err := strconv.Atoi(cpuCoresS)
1637 if err != nil {
1638 return resourceData{}, fmt.Errorf("invalid cpu cores: %s", cpuCoresS)
1639 }
1640 memory, ok := r.Annotations["dodo.cloud/resource.virtual-machine.memory"]
1641 if !ok {
1642 return resourceData{}, fmt.Errorf("no memory")
1643 }
1644 ret.VirtualMachine = append(ret.VirtualMachine, vm{name, user, cpuCores, memory})
giob4a3a192024-08-19 09:55:47 +04001645 default:
1646 fmt.Printf("Unknown resource: %+v\n", r.Annotations)
1647 }
1648 }
1649 return ret, nil
1650}
gio7fbd4ad2024-08-27 10:06:39 +04001651
1652func createDevBranchAppConfig(from []byte, branch, username string) (string, []byte, error) {
1653 cfg, err := installer.ParseCueAppConfig(installer.CueAppData{"app.cue": from})
1654 if err != nil {
1655 return "", nil, err
1656 }
1657 if err := cfg.Err(); err != nil {
1658 return "", nil, err
1659 }
1660 if err := cfg.Validate(); err != nil {
1661 return "", nil, err
1662 }
1663 subdomain := cfg.LookupPath(cue.ParsePath("app.ingress.subdomain"))
1664 if err := subdomain.Err(); err != nil {
1665 return "", nil, err
1666 }
1667 subdomainStr, err := subdomain.String()
1668 network := cfg.LookupPath(cue.ParsePath("app.ingress.network"))
1669 if err := network.Err(); err != nil {
1670 return "", nil, err
1671 }
1672 networkStr, err := network.String()
1673 if err != nil {
1674 return "", nil, err
1675 }
1676 newCfg := map[string]any{}
1677 if err := cfg.Decode(&newCfg); err != nil {
1678 return "", nil, err
1679 }
1680 app, ok := newCfg["app"].(map[string]any)
1681 if !ok {
1682 return "", nil, fmt.Errorf("not a map")
1683 }
1684 app["ingress"].(map[string]any)["subdomain"] = fmt.Sprintf("%s-%s", branch, subdomainStr)
1685 app["dev"] = map[string]any{
1686 "enabled": true,
1687 "username": username,
1688 }
1689 buf, err := json.MarshalIndent(newCfg, "", "\t")
1690 if err != nil {
1691 return "", nil, err
1692 }
1693 return networkStr, buf, nil
1694}