blob: 4fbd6c23fb8c038943f8892c88b9f04cca63d23e [file] [log] [blame]
gio59946282024-10-07 12:55:51 +04001package dodoapp
gio0eaf2712024-04-14 13:08:46 +04002
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"
giof078f462024-10-14 09:07:33 +040015 "sort"
gio7fbd4ad2024-08-27 10:06:39 +040016 "strconv"
gio0eaf2712024-04-14 13:08:46 +040017 "strings"
gio9d66f322024-07-06 13:45:10 +040018 "sync"
gio9f6b27d2024-10-14 10:08:40 +040019 ttemplate "text/template"
giocafd4e62024-07-31 10:53:40 +040020 "time"
gio0eaf2712024-04-14 13:08:46 +040021
Davit Tabidzea5ea5092024-08-01 15:28:09 +040022 "golang.org/x/crypto/bcrypt"
23 "golang.org/x/exp/rand"
24
gio0eaf2712024-04-14 13:08:46 +040025 "github.com/giolekva/pcloud/core/installer"
gio59946282024-10-07 12:55:51 +040026 "github.com/giolekva/pcloud/core/installer/server"
gio0eaf2712024-04-14 13:08:46 +040027 "github.com/giolekva/pcloud/core/installer/soft"
gio43b0f422024-08-21 10:40:13 +040028 "github.com/giolekva/pcloud/core/installer/tasks"
gio33059762024-07-05 13:19:07 +040029
gio7fbd4ad2024-08-27 10:06:39 +040030 "cuelang.org/go/cue"
gio33059762024-07-05 13:19:07 +040031 "github.com/gorilla/mux"
gio81246f02024-07-10 12:02:15 +040032 "github.com/gorilla/securecookie"
gio0eaf2712024-04-14 13:08:46 +040033)
34
gio59946282024-10-07 12:55:51 +040035//go:embed templates/*
36var templates embed.FS
gio23bdc1b2024-07-11 16:07:47 +040037
gio59946282024-10-07 12:55:51 +040038//go:embed all:app-templates
gio5e49bb62024-07-20 10:43:19 +040039var appTmplsFS embed.FS
40
gio59946282024-10-07 12:55:51 +040041//go:embed static/*
42var staticAssets embed.FS
43
gio9f6b27d2024-10-14 10:08:40 +040044//go:embed schemas/app.schema.json
45var dodoAppJsonSchema string
gioc81a8472024-09-24 13:06:19 +020046
gio9d66f322024-07-06 13:45:10 +040047const (
gioa60f0de2024-07-08 10:49:48 +040048 ConfigRepoName = "config"
giod8ab4f52024-07-26 16:58:34 +040049 appConfigsFile = "/apps.json"
gio81246f02024-07-10 12:02:15 +040050 loginPath = "/login"
51 logoutPath = "/logout"
gio59946282024-10-07 12:55:51 +040052 staticPath = "/static/"
gioc81a8472024-09-24 13:06:19 +020053 schemasPath = "/schemas/"
gio8fae3af2024-07-25 13:43:31 +040054 apiPublicData = "/api/public-data"
55 apiCreateApp = "/api/apps"
gio81246f02024-07-10 12:02:15 +040056 sessionCookie = "dodo-app-session"
57 userCtx = "user"
giob4a3a192024-08-19 09:55:47 +040058 initCommitMsg = "init"
gio9d66f322024-07-06 13:45:10 +040059)
60
gio59946282024-10-07 12:55:51 +040061type tmplts struct {
giob4a3a192024-08-19 09:55:47 +040062 index *template.Template
63 appStatus *template.Template
64 commitStatus *template.Template
gio183e8342024-08-20 06:01:24 +040065 logs *template.Template
gio23bdc1b2024-07-11 16:07:47 +040066}
67
gio59946282024-10-07 12:55:51 +040068func parseTemplates(fs embed.FS) (tmplts, error) {
69 base, err := template.ParseFS(fs, "templates/base.html")
gio23bdc1b2024-07-11 16:07:47 +040070 if err != nil {
gio59946282024-10-07 12:55:51 +040071 return tmplts{}, err
gio23bdc1b2024-07-11 16:07:47 +040072 }
gio5e49bb62024-07-20 10:43:19 +040073 parse := func(path string) (*template.Template, error) {
74 if b, err := base.Clone(); err != nil {
75 return nil, err
76 } else {
77 return b.ParseFS(fs, path)
78 }
79 }
gio59946282024-10-07 12:55:51 +040080 index, err := parse("templates/index.html")
gio5e49bb62024-07-20 10:43:19 +040081 if err != nil {
gio59946282024-10-07 12:55:51 +040082 return tmplts{}, err
gio5e49bb62024-07-20 10:43:19 +040083 }
gio59946282024-10-07 12:55:51 +040084 appStatus, err := parse("templates/app_status.html")
gio5e49bb62024-07-20 10:43:19 +040085 if err != nil {
gio59946282024-10-07 12:55:51 +040086 return tmplts{}, err
gio5e49bb62024-07-20 10:43:19 +040087 }
gio59946282024-10-07 12:55:51 +040088 commitStatus, err := parse("templates/commit_status.html")
giob4a3a192024-08-19 09:55:47 +040089 if err != nil {
gio59946282024-10-07 12:55:51 +040090 return tmplts{}, err
giob4a3a192024-08-19 09:55:47 +040091 }
gio59946282024-10-07 12:55:51 +040092 logs, err := parse("templates/logs.html")
gio183e8342024-08-20 06:01:24 +040093 if err != nil {
gio59946282024-10-07 12:55:51 +040094 return tmplts{}, err
gio183e8342024-08-20 06:01:24 +040095 }
gio59946282024-10-07 12:55:51 +040096 return tmplts{index, appStatus, commitStatus, logs}, nil
gio23bdc1b2024-07-11 16:07:47 +040097}
98
gio59946282024-10-07 12:55:51 +040099type Server struct {
giocb34ad22024-07-11 08:01:13 +0400100 l sync.Locker
101 st Store
gio11617ac2024-07-15 16:09:04 +0400102 nf NetworkFilter
103 ug UserGetter
giocb34ad22024-07-11 08:01:13 +0400104 port int
105 apiPort int
106 self string
gioc81a8472024-09-24 13:06:19 +0200107 selfPublic string
gio11617ac2024-07-15 16:09:04 +0400108 repoPublicAddr string
giocb34ad22024-07-11 08:01:13 +0400109 sshKey string
110 gitRepoPublicKey string
111 client soft.Client
112 namespace string
113 envAppManagerAddr string
114 env installer.EnvConfig
115 nsc installer.NamespaceCreator
116 jc installer.JobCreator
gio864b4332024-09-05 13:56:47 +0400117 vpnKeyGen installer.VPNAPIClient
giof6ad2982024-08-23 17:42:49 +0400118 cnc installer.ClusterNetworkConfigurator
giocb34ad22024-07-11 08:01:13 +0400119 workers map[string]map[string]struct{}
giod8ab4f52024-07-26 16:58:34 +0400120 appConfigs map[string]appConfig
gio59946282024-10-07 12:55:51 +0400121 tmplts tmplts
gio5e49bb62024-07-20 10:43:19 +0400122 appTmpls AppTmplStore
giocafd4e62024-07-31 10:53:40 +0400123 external bool
124 fetchUsersAddr string
gio43b0f422024-08-21 10:40:13 +0400125 reconciler tasks.Reconciler
gio183e8342024-08-20 06:01:24 +0400126 logs map[string]string
gio9f6b27d2024-10-14 10:08:40 +0400127 schemaTmpl *ttemplate.Template
giod8ab4f52024-07-26 16:58:34 +0400128}
129
130type appConfig struct {
131 Namespace string `json:"namespace"`
132 Network string `json:"network"`
gio0eaf2712024-04-14 13:08:46 +0400133}
134
gio33059762024-07-05 13:19:07 +0400135// TODO(gio): Initialize appNs on startup
gio59946282024-10-07 12:55:51 +0400136func NewServer(
gioa60f0de2024-07-08 10:49:48 +0400137 st Store,
gio11617ac2024-07-15 16:09:04 +0400138 nf NetworkFilter,
139 ug UserGetter,
gio0eaf2712024-04-14 13:08:46 +0400140 port int,
gioa60f0de2024-07-08 10:49:48 +0400141 apiPort int,
gio33059762024-07-05 13:19:07 +0400142 self string,
gioc81a8472024-09-24 13:06:19 +0200143 selfPublic string,
gio11617ac2024-07-15 16:09:04 +0400144 repoPublicAddr string,
gio0eaf2712024-04-14 13:08:46 +0400145 sshKey string,
gio33059762024-07-05 13:19:07 +0400146 gitRepoPublicKey string,
gio0eaf2712024-04-14 13:08:46 +0400147 client soft.Client,
148 namespace string,
giocb34ad22024-07-11 08:01:13 +0400149 envAppManagerAddr string,
gio33059762024-07-05 13:19:07 +0400150 nsc installer.NamespaceCreator,
giof8843412024-05-22 16:38:05 +0400151 jc installer.JobCreator,
gio864b4332024-09-05 13:56:47 +0400152 vpnKeyGen installer.VPNAPIClient,
giof6ad2982024-08-23 17:42:49 +0400153 cnc installer.ClusterNetworkConfigurator,
gio0eaf2712024-04-14 13:08:46 +0400154 env installer.EnvConfig,
giocafd4e62024-07-31 10:53:40 +0400155 external bool,
156 fetchUsersAddr string,
gio43b0f422024-08-21 10:40:13 +0400157 reconciler tasks.Reconciler,
gio59946282024-10-07 12:55:51 +0400158) (*Server, error) {
159 tmplts, err := parseTemplates(templates)
gio23bdc1b2024-07-11 16:07:47 +0400160 if err != nil {
161 return nil, err
162 }
gio5e4d1a72024-10-09 15:25:29 +0400163 apps, err := fs.Sub(appTmplsFS, "app-templates")
gio5e49bb62024-07-20 10:43:19 +0400164 if err != nil {
165 return nil, err
166 }
167 appTmpls, err := NewAppTmplStoreFS(apps)
168 if err != nil {
169 return nil, err
170 }
gio9f6b27d2024-10-14 10:08:40 +0400171 schemaTmpl, err := ttemplate.New("app.schema.json").Parse(dodoAppJsonSchema)
172 if err != nil {
173 return nil, err
174 }
gio59946282024-10-07 12:55:51 +0400175 s := &Server{
gio9d66f322024-07-06 13:45:10 +0400176 &sync.Mutex{},
gioa60f0de2024-07-08 10:49:48 +0400177 st,
gio11617ac2024-07-15 16:09:04 +0400178 nf,
179 ug,
gio0eaf2712024-04-14 13:08:46 +0400180 port,
gioa60f0de2024-07-08 10:49:48 +0400181 apiPort,
gio33059762024-07-05 13:19:07 +0400182 self,
gioc81a8472024-09-24 13:06:19 +0200183 selfPublic,
gio11617ac2024-07-15 16:09:04 +0400184 repoPublicAddr,
gio0eaf2712024-04-14 13:08:46 +0400185 sshKey,
gio33059762024-07-05 13:19:07 +0400186 gitRepoPublicKey,
gio0eaf2712024-04-14 13:08:46 +0400187 client,
188 namespace,
giocb34ad22024-07-11 08:01:13 +0400189 envAppManagerAddr,
gio0eaf2712024-04-14 13:08:46 +0400190 env,
gio33059762024-07-05 13:19:07 +0400191 nsc,
giof8843412024-05-22 16:38:05 +0400192 jc,
gio36b23b32024-08-25 12:20:54 +0400193 vpnKeyGen,
giof6ad2982024-08-23 17:42:49 +0400194 cnc,
gio266c04f2024-07-03 14:18:45 +0400195 map[string]map[string]struct{}{},
giod8ab4f52024-07-26 16:58:34 +0400196 map[string]appConfig{},
gio23bdc1b2024-07-11 16:07:47 +0400197 tmplts,
gio5e49bb62024-07-20 10:43:19 +0400198 appTmpls,
giocafd4e62024-07-31 10:53:40 +0400199 external,
200 fetchUsersAddr,
gio43b0f422024-08-21 10:40:13 +0400201 reconciler,
gio183e8342024-08-20 06:01:24 +0400202 map[string]string{},
gio9f6b27d2024-10-14 10:08:40 +0400203 schemaTmpl,
gio0eaf2712024-04-14 13:08:46 +0400204 }
gioa60f0de2024-07-08 10:49:48 +0400205 config, err := client.GetRepo(ConfigRepoName)
gio9d66f322024-07-06 13:45:10 +0400206 if err != nil {
207 return nil, err
208 }
giod8ab4f52024-07-26 16:58:34 +0400209 r, err := config.Reader(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +0400210 if err == nil {
211 defer r.Close()
giod8ab4f52024-07-26 16:58:34 +0400212 if err := json.NewDecoder(r).Decode(&s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +0400213 return nil, err
214 }
215 } else if !errors.Is(err, fs.ErrNotExist) {
216 return nil, err
217 }
218 return s, nil
gio0eaf2712024-04-14 13:08:46 +0400219}
220
gio59946282024-10-07 12:55:51 +0400221func (s *Server) getAppConfig(app, branch string) appConfig {
gio7fbd4ad2024-08-27 10:06:39 +0400222 return s.appConfigs[fmt.Sprintf("%s-%s", app, branch)]
223}
224
gio59946282024-10-07 12:55:51 +0400225func (s *Server) setAppConfig(app, branch string, cfg appConfig) {
gio7fbd4ad2024-08-27 10:06:39 +0400226 s.appConfigs[fmt.Sprintf("%s-%s", app, branch)] = cfg
227}
228
gio59946282024-10-07 12:55:51 +0400229func (s *Server) Start() error {
gio7fbd4ad2024-08-27 10:06:39 +0400230 // if err := s.client.DisableKeyless(); err != nil {
231 // return err
232 // }
233 // if err := s.client.DisableAnonAccess(); err != nil {
234 // return err
235 // }
gioa60f0de2024-07-08 10:49:48 +0400236 e := make(chan error)
237 go func() {
238 r := mux.NewRouter()
gio81246f02024-07-10 12:02:15 +0400239 r.Use(s.mwAuth)
gio9f6b27d2024-10-14 10:08:40 +0400240 r.HandleFunc(schemasPath+"{user}/app.schema.json", s.handleSchema).Methods(http.MethodGet)
gio59946282024-10-07 12:55:51 +0400241 r.PathPrefix(staticPath).Handler(server.NewCachingHandler(http.FileServer(http.FS(staticAssets))))
gio81246f02024-07-10 12:02:15 +0400242 r.HandleFunc(logoutPath, s.handleLogout).Methods(http.MethodGet)
gio8fae3af2024-07-25 13:43:31 +0400243 r.HandleFunc(apiPublicData, s.handleAPIPublicData)
244 r.HandleFunc(apiCreateApp, s.handleAPICreateApp).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400245 r.HandleFunc("/{app-name}"+loginPath, s.handleLoginForm).Methods(http.MethodGet)
246 r.HandleFunc("/{app-name}"+loginPath, s.handleLogin).Methods(http.MethodPost)
gio183e8342024-08-20 06:01:24 +0400247 r.HandleFunc("/{app-name}/logs", s.handleAppLogs).Methods(http.MethodGet)
giob4a3a192024-08-19 09:55:47 +0400248 r.HandleFunc("/{app-name}/{hash}", s.handleAppCommit).Methods(http.MethodGet)
gio7fbd4ad2024-08-27 10:06:39 +0400249 r.HandleFunc("/{app-name}/dev-branch/create", s.handleCreateDevBranch).Methods(http.MethodPost)
250 r.HandleFunc("/{app-name}/branch/{branch}", s.handleAppStatus).Methods(http.MethodGet)
gio5887caa2024-10-03 15:07:23 +0400251 r.HandleFunc("/{app-name}/branch/{branch}/delete", s.handleBranchDelete).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400252 r.HandleFunc("/{app-name}", s.handleAppStatus).Methods(http.MethodGet)
gio5887caa2024-10-03 15:07:23 +0400253 r.HandleFunc("/{app-name}/delete", s.handleAppDelete).Methods(http.MethodPost)
gio81246f02024-07-10 12:02:15 +0400254 r.HandleFunc("/", s.handleStatus).Methods(http.MethodGet)
gio11617ac2024-07-15 16:09:04 +0400255 r.HandleFunc("/", s.handleCreateApp).Methods(http.MethodPost)
gioa60f0de2024-07-08 10:49:48 +0400256 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.port), r)
257 }()
258 go func() {
259 r := mux.NewRouter()
gio8fae3af2024-07-25 13:43:31 +0400260 r.HandleFunc("/update", s.handleAPIUpdate)
261 r.HandleFunc("/api/apps/{app-name}/workers", s.handleAPIRegisterWorker).Methods(http.MethodPost)
gio7fbd4ad2024-08-27 10:06:39 +0400262 r.HandleFunc("/api/add-public-key", s.handleAPIAddPublicKey).Methods(http.MethodPost)
giocfb228c2024-09-06 15:44:31 +0400263 r.HandleFunc("/api/apps/{app-name}/branch/{branch}/env-profile", s.handleBranchEnvProfile).Methods(http.MethodGet)
giocafd4e62024-07-31 10:53:40 +0400264 if !s.external {
265 r.HandleFunc("/api/sync-users", s.handleAPISyncUsers).Methods(http.MethodGet)
266 }
gioa60f0de2024-07-08 10:49:48 +0400267 e <- http.ListenAndServe(fmt.Sprintf(":%d", s.apiPort), r)
268 }()
giocafd4e62024-07-31 10:53:40 +0400269 if !s.external {
270 go func() {
271 s.syncUsers()
Davit Tabidzea5ea5092024-08-01 15:28:09 +0400272 for {
273 delay := time.Duration(rand.Intn(60)+60) * time.Second
274 time.Sleep(delay)
giocafd4e62024-07-31 10:53:40 +0400275 s.syncUsers()
276 }
277 }()
278 }
gioa60f0de2024-07-08 10:49:48 +0400279 return <-e
280}
281
gio11617ac2024-07-15 16:09:04 +0400282type UserGetter interface {
283 Get(r *http.Request) string
gio8fae3af2024-07-25 13:43:31 +0400284 Encode(w http.ResponseWriter, user string) error
gio11617ac2024-07-15 16:09:04 +0400285}
286
287type externalUserGetter struct {
288 sc *securecookie.SecureCookie
289}
290
291func NewExternalUserGetter() UserGetter {
gio8fae3af2024-07-25 13:43:31 +0400292 return &externalUserGetter{securecookie.New(
293 securecookie.GenerateRandomKey(64),
294 securecookie.GenerateRandomKey(32),
295 )}
gio11617ac2024-07-15 16:09:04 +0400296}
297
298func (ug *externalUserGetter) Get(r *http.Request) string {
299 cookie, err := r.Cookie(sessionCookie)
300 if err != nil {
301 return ""
302 }
303 var user string
304 if err := ug.sc.Decode(sessionCookie, cookie.Value, &user); err != nil {
305 return ""
306 }
307 return user
308}
309
gio8fae3af2024-07-25 13:43:31 +0400310func (ug *externalUserGetter) Encode(w http.ResponseWriter, user string) error {
311 if encoded, err := ug.sc.Encode(sessionCookie, user); err == nil {
312 cookie := &http.Cookie{
313 Name: sessionCookie,
314 Value: encoded,
315 Path: "/",
316 Secure: true,
317 HttpOnly: true,
318 }
319 http.SetCookie(w, cookie)
320 return nil
321 } else {
322 return err
323 }
324}
325
gio11617ac2024-07-15 16:09:04 +0400326type internalUserGetter struct{}
327
328func NewInternalUserGetter() UserGetter {
329 return internalUserGetter{}
330}
331
332func (ug internalUserGetter) Get(r *http.Request) string {
giodd213152024-09-27 11:26:59 +0200333 return r.Header.Get("X-Forwarded-User")
gio11617ac2024-07-15 16:09:04 +0400334}
335
gio8fae3af2024-07-25 13:43:31 +0400336func (ug internalUserGetter) Encode(w http.ResponseWriter, user string) error {
337 return nil
338}
339
gio59946282024-10-07 12:55:51 +0400340func (s *Server) mwAuth(next http.Handler) http.Handler {
gio81246f02024-07-10 12:02:15 +0400341 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400342 if strings.HasSuffix(r.URL.Path, loginPath) ||
343 strings.HasPrefix(r.URL.Path, logoutPath) ||
344 strings.HasPrefix(r.URL.Path, staticPath) ||
gioc81a8472024-09-24 13:06:19 +0200345 strings.HasPrefix(r.URL.Path, schemasPath) ||
gio8fae3af2024-07-25 13:43:31 +0400346 strings.HasPrefix(r.URL.Path, apiPublicData) ||
347 strings.HasPrefix(r.URL.Path, apiCreateApp) {
gio81246f02024-07-10 12:02:15 +0400348 next.ServeHTTP(w, r)
349 return
350 }
gio11617ac2024-07-15 16:09:04 +0400351 user := s.ug.Get(r)
352 if user == "" {
gio81246f02024-07-10 12:02:15 +0400353 vars := mux.Vars(r)
354 appName, ok := vars["app-name"]
355 if !ok || appName == "" {
356 http.Error(w, "missing app-name", http.StatusBadRequest)
357 return
358 }
359 http.Redirect(w, r, fmt.Sprintf("/%s%s", appName, loginPath), http.StatusSeeOther)
360 return
361 }
gio81246f02024-07-10 12:02:15 +0400362 next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), userCtx, user)))
363 })
364}
365
gio9f6b27d2024-10-14 10:08:40 +0400366type schemaNetwork struct {
367 Value string `json:"const"`
368}
369
gio59946282024-10-07 12:55:51 +0400370func (s *Server) handleSchema(w http.ResponseWriter, r *http.Request) {
gioc81a8472024-09-24 13:06:19 +0200371 w.Header().Set("Content-Type", "application/schema+json")
gio9f6b27d2024-10-14 10:08:40 +0400372 vars := mux.Vars(r)
373 user, ok := vars["user"]
374 if !ok {
375 http.Error(w, "no user", http.StatusBadRequest)
376 return
377 }
378 networks, err := s.getNetworks(user)
379 if err != nil {
380 http.Error(w, err.Error(), http.StatusInternalServerError)
381 return
382 }
383 var names []schemaNetwork
384 for _, n := range networks {
385 names = append(names, schemaNetwork{n.Name})
386 }
387 var tmp strings.Builder
388 if err := json.NewEncoder(&tmp).Encode(names); err != nil {
389 http.Error(w, err.Error(), http.StatusInternalServerError)
390 return
391 }
392 if err := s.schemaTmpl.Execute(w, map[string]any{
393 "Networks": tmp.String(),
394 }); err != nil {
395 http.Error(w, err.Error(), http.StatusInternalServerError)
396 return
397 }
gioc81a8472024-09-24 13:06:19 +0200398}
399
gio59946282024-10-07 12:55:51 +0400400func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
gio8fae3af2024-07-25 13:43:31 +0400401 // TODO(gio): move to UserGetter
gio81246f02024-07-10 12:02:15 +0400402 http.SetCookie(w, &http.Cookie{
403 Name: sessionCookie,
404 Value: "",
405 Path: "/",
406 HttpOnly: true,
407 Secure: true,
408 })
409 http.Redirect(w, r, "/", http.StatusSeeOther)
410}
411
gio59946282024-10-07 12:55:51 +0400412func (s *Server) handleLoginForm(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +0400413 vars := mux.Vars(r)
414 appName, ok := vars["app-name"]
415 if !ok || appName == "" {
416 http.Error(w, "missing app-name", http.StatusBadRequest)
417 return
418 }
419 fmt.Fprint(w, `
420<!DOCTYPE html>
421<html lang='en'>
422 <head>
423 <title>dodo: app - login</title>
424 <meta charset='utf-8'>
425 </head>
426 <body>
427 <form action="" method="POST">
428 <input type="password" placeholder="Password" name="password" required />
429 <button type="submit">Login</button>
430 </form>
431 </body>
432</html>
433`)
434}
435
gio59946282024-10-07 12:55:51 +0400436func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +0400437 vars := mux.Vars(r)
438 appName, ok := vars["app-name"]
439 if !ok || appName == "" {
440 http.Error(w, "missing app-name", http.StatusBadRequest)
441 return
442 }
443 password := r.FormValue("password")
444 if password == "" {
445 http.Error(w, "missing password", http.StatusBadRequest)
446 return
447 }
448 user, err := s.st.GetAppOwner(appName)
449 if err != nil {
450 http.Error(w, err.Error(), http.StatusInternalServerError)
451 return
452 }
453 hashed, err := s.st.GetUserPassword(user)
454 if err != nil {
455 http.Error(w, err.Error(), http.StatusInternalServerError)
456 return
457 }
458 if err := bcrypt.CompareHashAndPassword(hashed, []byte(password)); err != nil {
459 http.Redirect(w, r, r.URL.Path, http.StatusSeeOther)
460 return
461 }
gio8fae3af2024-07-25 13:43:31 +0400462 if err := s.ug.Encode(w, user); err != nil {
463 http.Error(w, err.Error(), http.StatusInternalServerError)
464 return
gio81246f02024-07-10 12:02:15 +0400465 }
466 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
467}
468
giob4a3a192024-08-19 09:55:47 +0400469type navItem struct {
470 Name string
471 Address string
472}
473
gio23bdc1b2024-07-11 16:07:47 +0400474type statusData struct {
giob4a3a192024-08-19 09:55:47 +0400475 Navigation []navItem
476 Apps []string
477 Networks []installer.Network
478 Types []string
gio23bdc1b2024-07-11 16:07:47 +0400479}
480
gio59946282024-10-07 12:55:51 +0400481func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +0400482 user := r.Context().Value(userCtx)
483 if user == nil {
484 http.Error(w, "unauthorized", http.StatusUnauthorized)
485 return
486 }
487 apps, err := s.st.GetUserApps(user.(string))
gioa60f0de2024-07-08 10:49:48 +0400488 if err != nil {
489 http.Error(w, err.Error(), http.StatusInternalServerError)
490 return
491 }
gio11617ac2024-07-15 16:09:04 +0400492 networks, err := s.getNetworks(user.(string))
493 if err != nil {
494 http.Error(w, err.Error(), http.StatusInternalServerError)
495 return
496 }
giob54db242024-07-30 18:49:33 +0400497 var types []string
498 for _, t := range s.appTmpls.Types() {
499 types = append(types, strings.Replace(t, "-", ":", 1))
500 }
giob4a3a192024-08-19 09:55:47 +0400501 n := []navItem{navItem{"Home", "/"}}
502 data := statusData{n, apps, networks, types}
gio23bdc1b2024-07-11 16:07:47 +0400503 if err := s.tmplts.index.Execute(w, data); err != nil {
504 http.Error(w, err.Error(), http.StatusInternalServerError)
505 return
gioa60f0de2024-07-08 10:49:48 +0400506 }
507}
508
gio5e49bb62024-07-20 10:43:19 +0400509type appStatusData struct {
giob4a3a192024-08-19 09:55:47 +0400510 Navigation []navItem
gio5e49bb62024-07-20 10:43:19 +0400511 Name string
gio5887caa2024-10-03 15:07:23 +0400512 Branch string
gio5e49bb62024-07-20 10:43:19 +0400513 GitCloneCommand string
giob4a3a192024-08-19 09:55:47 +0400514 Commits []CommitMeta
gio183e8342024-08-20 06:01:24 +0400515 LastCommit resourceData
gio7fbd4ad2024-08-27 10:06:39 +0400516 Branches []string
gio5e49bb62024-07-20 10:43:19 +0400517}
518
gio59946282024-10-07 12:55:51 +0400519func (s *Server) handleAppStatus(w http.ResponseWriter, r *http.Request) {
gioa60f0de2024-07-08 10:49:48 +0400520 vars := mux.Vars(r)
521 appName, ok := vars["app-name"]
522 if !ok || appName == "" {
523 http.Error(w, "missing app-name", http.StatusBadRequest)
524 return
525 }
gio7fbd4ad2024-08-27 10:06:39 +0400526 branch, ok := vars["branch"]
527 if !ok || branch == "" {
528 branch = "master"
529 }
gio94904702024-07-26 16:58:34 +0400530 u := r.Context().Value(userCtx)
531 if u == nil {
532 http.Error(w, "unauthorized", http.StatusUnauthorized)
533 return
534 }
535 user, ok := u.(string)
536 if !ok {
537 http.Error(w, "could not get user", http.StatusInternalServerError)
538 return
539 }
540 owner, err := s.st.GetAppOwner(appName)
541 if err != nil {
542 http.Error(w, err.Error(), http.StatusInternalServerError)
543 return
544 }
545 if owner != user {
546 http.Error(w, "unauthorized", http.StatusUnauthorized)
547 return
548 }
gio7fbd4ad2024-08-27 10:06:39 +0400549 commits, err := s.st.GetCommitHistory(appName, branch)
gioa60f0de2024-07-08 10:49:48 +0400550 if err != nil {
551 http.Error(w, err.Error(), http.StatusInternalServerError)
552 return
553 }
gio183e8342024-08-20 06:01:24 +0400554 var lastCommitResources resourceData
555 if len(commits) > 0 {
556 lastCommit, err := s.st.GetCommit(commits[len(commits)-1].Hash)
557 if err != nil {
558 http.Error(w, err.Error(), http.StatusInternalServerError)
559 return
560 }
561 r, err := extractResourceData(lastCommit.Resources.Helm)
562 if err != nil {
563 http.Error(w, err.Error(), http.StatusInternalServerError)
564 return
565 }
566 lastCommitResources = r
567 }
gio7fbd4ad2024-08-27 10:06:39 +0400568 branches, err := s.st.GetBranches(appName)
569 if err != nil {
570 http.Error(w, err.Error(), http.StatusInternalServerError)
571 return
572 }
gio5e49bb62024-07-20 10:43:19 +0400573 data := appStatusData{
giob4a3a192024-08-19 09:55:47 +0400574 Navigation: []navItem{
575 navItem{"Home", "/"},
576 navItem{appName, "/" + appName},
577 },
gio5e49bb62024-07-20 10:43:19 +0400578 Name: appName,
gio5887caa2024-10-03 15:07:23 +0400579 Branch: branch,
gio5e49bb62024-07-20 10:43:19 +0400580 GitCloneCommand: fmt.Sprintf("git clone %s/%s\n\n\n", s.repoPublicAddr, appName),
581 Commits: commits,
gio183e8342024-08-20 06:01:24 +0400582 LastCommit: lastCommitResources,
gio7fbd4ad2024-08-27 10:06:39 +0400583 Branches: branches,
584 }
585 if branch != "master" {
586 data.Navigation = append(data.Navigation, navItem{branch, fmt.Sprintf("/%s/branch/%s", appName, branch)})
gio5e49bb62024-07-20 10:43:19 +0400587 }
588 if err := s.tmplts.appStatus.Execute(w, data); err != nil {
589 http.Error(w, err.Error(), http.StatusInternalServerError)
590 return
gioa60f0de2024-07-08 10:49:48 +0400591 }
gio0eaf2712024-04-14 13:08:46 +0400592}
593
giocfb228c2024-09-06 15:44:31 +0400594type appEnv struct {
595 Profile string `json:"envProfile"`
596}
597
gio59946282024-10-07 12:55:51 +0400598func (s *Server) handleBranchEnvProfile(w http.ResponseWriter, r *http.Request) {
giocfb228c2024-09-06 15:44:31 +0400599 vars := mux.Vars(r)
600 appName, ok := vars["app-name"]
601 if !ok || appName == "" {
602 http.Error(w, "missing app-name", http.StatusBadRequest)
603 return
604 }
605 branch, ok := vars["branch"]
606 if !ok || branch == "" {
607 branch = "master"
608 }
609 info, err := s.st.GetLastCommitInfo(appName, branch)
610 if err != nil {
611 http.Error(w, err.Error(), http.StatusInternalServerError)
612 return
613 }
614 var e appEnv
615 if err := json.NewDecoder(bytes.NewReader(info.Resources.RenderedRaw)).Decode(&e); err != nil {
616 http.Error(w, err.Error(), http.StatusInternalServerError)
617 return
618 }
619 fmt.Fprintln(w, e.Profile)
620}
621
giob4a3a192024-08-19 09:55:47 +0400622type volume struct {
623 Name string
624 Size string
625}
626
627type postgresql struct {
628 Name string
629 Version string
630 Volume string
631}
632
gio07eb1082024-10-25 14:35:56 +0400633type mongodb struct {
634 Name string
635 Version string
636 Volume string
637}
638
giob4a3a192024-08-19 09:55:47 +0400639type ingress struct {
giof078f462024-10-14 09:07:33 +0400640 Name string
giob4a3a192024-08-19 09:55:47 +0400641 Host string
giof078f462024-10-14 09:07:33 +0400642 Home string
giob4a3a192024-08-19 09:55:47 +0400643}
644
gio7fbd4ad2024-08-27 10:06:39 +0400645type vm struct {
646 Name string
647 User string
648 CPUCores int
649 Memory string
650}
651
giob4a3a192024-08-19 09:55:47 +0400652type resourceData struct {
gio7fbd4ad2024-08-27 10:06:39 +0400653 Volume []volume
654 PostgreSQL []postgresql
gio07eb1082024-10-25 14:35:56 +0400655 MongoDB []mongodb
gio7fbd4ad2024-08-27 10:06:39 +0400656 Ingress []ingress
657 VirtualMachine []vm
giob4a3a192024-08-19 09:55:47 +0400658}
659
660type commitStatusData struct {
661 Navigation []navItem
662 AppName string
663 Commit Commit
664 Resources resourceData
665}
666
gio59946282024-10-07 12:55:51 +0400667func (s *Server) handleAppCommit(w http.ResponseWriter, r *http.Request) {
giob4a3a192024-08-19 09:55:47 +0400668 vars := mux.Vars(r)
669 appName, ok := vars["app-name"]
670 if !ok || appName == "" {
671 http.Error(w, "missing app-name", http.StatusBadRequest)
672 return
673 }
674 hash, ok := vars["hash"]
675 if !ok || appName == "" {
676 http.Error(w, "missing app-name", http.StatusBadRequest)
677 return
678 }
679 u := r.Context().Value(userCtx)
680 if u == nil {
681 http.Error(w, "unauthorized", http.StatusUnauthorized)
682 return
683 }
684 user, ok := u.(string)
685 if !ok {
686 http.Error(w, "could not get user", http.StatusInternalServerError)
687 return
688 }
689 owner, err := s.st.GetAppOwner(appName)
690 if err != nil {
691 http.Error(w, err.Error(), http.StatusInternalServerError)
692 return
693 }
694 if owner != user {
695 http.Error(w, "unauthorized", http.StatusUnauthorized)
696 return
697 }
698 commit, err := s.st.GetCommit(hash)
699 if err != nil {
700 // TODO(gio): not-found ?
701 http.Error(w, err.Error(), http.StatusInternalServerError)
702 return
703 }
704 var res strings.Builder
705 if err := json.NewEncoder(&res).Encode(commit.Resources.Helm); err != nil {
706 http.Error(w, err.Error(), http.StatusInternalServerError)
707 return
708 }
709 resData, err := extractResourceData(commit.Resources.Helm)
710 if err != nil {
711 http.Error(w, err.Error(), http.StatusInternalServerError)
712 return
713 }
714 data := commitStatusData{
715 Navigation: []navItem{
716 navItem{"Home", "/"},
717 navItem{appName, "/" + appName},
718 navItem{hash, "/" + appName + "/" + hash},
719 },
720 AppName: appName,
721 Commit: commit,
722 Resources: resData,
723 }
724 if err := s.tmplts.commitStatus.Execute(w, data); err != nil {
725 http.Error(w, err.Error(), http.StatusInternalServerError)
726 return
727 }
728}
729
gio183e8342024-08-20 06:01:24 +0400730type logData struct {
731 Navigation []navItem
732 AppName string
733 Logs template.HTML
734}
735
gio59946282024-10-07 12:55:51 +0400736func (s *Server) handleAppLogs(w http.ResponseWriter, r *http.Request) {
gio183e8342024-08-20 06:01:24 +0400737 vars := mux.Vars(r)
738 appName, ok := vars["app-name"]
739 if !ok || appName == "" {
740 http.Error(w, "missing app-name", http.StatusBadRequest)
741 return
742 }
743 u := r.Context().Value(userCtx)
744 if u == nil {
745 http.Error(w, "unauthorized", http.StatusUnauthorized)
746 return
747 }
748 user, ok := u.(string)
749 if !ok {
750 http.Error(w, "could not get user", http.StatusInternalServerError)
751 return
752 }
753 owner, err := s.st.GetAppOwner(appName)
754 if err != nil {
755 http.Error(w, err.Error(), http.StatusInternalServerError)
756 return
757 }
758 if owner != user {
759 http.Error(w, "unauthorized", http.StatusUnauthorized)
760 return
761 }
762 data := logData{
763 Navigation: []navItem{
764 navItem{"Home", "/"},
765 navItem{appName, "/" + appName},
766 navItem{"Logs", "/" + appName + "/logs"},
767 },
768 AppName: appName,
769 Logs: template.HTML(strings.ReplaceAll(s.logs[appName], "\n", "<br/>")),
770 }
771 if err := s.tmplts.logs.Execute(w, data); err != nil {
772 fmt.Println(err)
773 http.Error(w, err.Error(), http.StatusInternalServerError)
774 return
775 }
776}
777
gio81246f02024-07-10 12:02:15 +0400778type apiUpdateReq struct {
gio266c04f2024-07-03 14:18:45 +0400779 Ref string `json:"ref"`
780 Repository struct {
781 Name string `json:"name"`
782 } `json:"repository"`
gioe2e31e12024-08-18 08:20:56 +0400783 After string `json:"after"`
784 Commits []struct {
785 Id string `json:"id"`
786 Message string `json:"message"`
787 } `json:"commits"`
gio0eaf2712024-04-14 13:08:46 +0400788}
789
gio59946282024-10-07 12:55:51 +0400790func (s *Server) handleAPIUpdate(w http.ResponseWriter, r *http.Request) {
gio0eaf2712024-04-14 13:08:46 +0400791 fmt.Println("update")
gio81246f02024-07-10 12:02:15 +0400792 var req apiUpdateReq
gio0eaf2712024-04-14 13:08:46 +0400793 var contents strings.Builder
794 io.Copy(&contents, r.Body)
795 c := contents.String()
796 fmt.Println(c)
797 if err := json.NewDecoder(strings.NewReader(c)).Decode(&req); err != nil {
gio23bdc1b2024-07-11 16:07:47 +0400798 http.Error(w, err.Error(), http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400799 return
800 }
gio7fbd4ad2024-08-27 10:06:39 +0400801 if strings.HasPrefix(req.Ref, "refs/heads/dodo_") || req.Repository.Name == ConfigRepoName {
802 return
803 }
804 branch, ok := strings.CutPrefix(req.Ref, "refs/heads/")
805 if !ok {
806 http.Error(w, "invalid branch", http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400807 return
808 }
gioa60f0de2024-07-08 10:49:48 +0400809 // TODO(gio): Create commit record on app init as well
gio0eaf2712024-04-14 13:08:46 +0400810 go func() {
gio11617ac2024-07-15 16:09:04 +0400811 owner, err := s.st.GetAppOwner(req.Repository.Name)
812 if err != nil {
813 return
814 }
815 networks, err := s.getNetworks(owner)
giocb34ad22024-07-11 08:01:13 +0400816 if err != nil {
817 return
818 }
giof15b9da2024-09-19 06:59:16 +0400819 // TODO(gio): get only available ones by owner
820 clusters, err := s.getClusters()
821 if err != nil {
822 return
823 }
gio94904702024-07-26 16:58:34 +0400824 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
825 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
826 if err != nil {
827 return
828 }
gioe2e31e12024-08-18 08:20:56 +0400829 found := false
830 commitMsg := ""
831 for _, c := range req.Commits {
832 if c.Id == req.After {
833 found = true
834 commitMsg = c.Message
835 break
gioa60f0de2024-07-08 10:49:48 +0400836 }
837 }
gioe2e31e12024-08-18 08:20:56 +0400838 if !found {
839 fmt.Printf("Error: could not find commit message")
840 return
841 }
gio7fbd4ad2024-08-27 10:06:39 +0400842 s.l.Lock()
843 defer s.l.Unlock()
giof15b9da2024-09-19 06:59:16 +0400844 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 +0400845 if err = s.createCommit(req.Repository.Name, branch, req.After, commitMsg, err, resources); err != nil {
gio12e887d2024-08-18 16:09:47 +0400846 fmt.Printf("Error: %s\n", err.Error())
gioe2e31e12024-08-18 08:20:56 +0400847 return
848 }
gioa60f0de2024-07-08 10:49:48 +0400849 for addr, _ := range s.workers[req.Repository.Name] {
850 go func() {
851 // TODO(gio): make port configurable
852 http.Get(fmt.Sprintf("http://%s/update", addr))
853 }()
gio0eaf2712024-04-14 13:08:46 +0400854 }
855 }()
gio0eaf2712024-04-14 13:08:46 +0400856}
857
gio81246f02024-07-10 12:02:15 +0400858type apiRegisterWorkerReq struct {
gio0eaf2712024-04-14 13:08:46 +0400859 Address string `json:"address"`
gio183e8342024-08-20 06:01:24 +0400860 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400861}
862
gio59946282024-10-07 12:55:51 +0400863func (s *Server) handleAPIRegisterWorker(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400864 // TODO(gio): lock
gioa60f0de2024-07-08 10:49:48 +0400865 vars := mux.Vars(r)
866 appName, ok := vars["app-name"]
867 if !ok || appName == "" {
868 http.Error(w, "missing app-name", http.StatusBadRequest)
869 return
870 }
gio81246f02024-07-10 12:02:15 +0400871 var req apiRegisterWorkerReq
gio0eaf2712024-04-14 13:08:46 +0400872 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
873 http.Error(w, err.Error(), http.StatusInternalServerError)
874 return
875 }
gioa60f0de2024-07-08 10:49:48 +0400876 if _, ok := s.workers[appName]; !ok {
877 s.workers[appName] = map[string]struct{}{}
gio266c04f2024-07-03 14:18:45 +0400878 }
gioa60f0de2024-07-08 10:49:48 +0400879 s.workers[appName][req.Address] = struct{}{}
gio183e8342024-08-20 06:01:24 +0400880 s.logs[appName] = req.Logs
gio0eaf2712024-04-14 13:08:46 +0400881}
882
gio59946282024-10-07 12:55:51 +0400883func (s *Server) handleCreateApp(w http.ResponseWriter, r *http.Request) {
gio11617ac2024-07-15 16:09:04 +0400884 u := r.Context().Value(userCtx)
885 if u == nil {
886 http.Error(w, "unauthorized", http.StatusUnauthorized)
887 return
888 }
889 user, ok := u.(string)
890 if !ok {
891 http.Error(w, "could not get user", http.StatusInternalServerError)
892 return
893 }
894 network := r.FormValue("network")
895 if network == "" {
896 http.Error(w, "missing network", http.StatusBadRequest)
897 return
898 }
gio5e49bb62024-07-20 10:43:19 +0400899 subdomain := r.FormValue("subdomain")
900 if subdomain == "" {
901 http.Error(w, "missing subdomain", http.StatusBadRequest)
902 return
903 }
904 appType := r.FormValue("type")
905 if appType == "" {
906 http.Error(w, "missing type", http.StatusBadRequest)
907 return
908 }
gio5cc6afc2024-10-06 09:33:44 +0400909 appName := r.FormValue("name")
910 var err error
911 if appName == "" {
912 g := installer.NewFixedLengthRandomNameGenerator(3)
913 appName, err = g.Generate()
914 }
gio11617ac2024-07-15 16:09:04 +0400915 if err != nil {
916 http.Error(w, err.Error(), http.StatusInternalServerError)
917 return
918 }
919 if ok, err := s.client.UserExists(user); err != nil {
920 http.Error(w, err.Error(), http.StatusInternalServerError)
921 return
922 } else if !ok {
giocafd4e62024-07-31 10:53:40 +0400923 http.Error(w, "user sync has not finished, please try again in few minutes", http.StatusFailedDependency)
924 return
gio11617ac2024-07-15 16:09:04 +0400925 }
giocafd4e62024-07-31 10:53:40 +0400926 if err := s.st.CreateUser(user, nil, network); err != nil && !errors.Is(err, ErrorAlreadyExists) {
gio11617ac2024-07-15 16:09:04 +0400927 http.Error(w, err.Error(), http.StatusInternalServerError)
928 return
929 }
930 if err := s.st.CreateApp(appName, user); err != nil {
931 http.Error(w, err.Error(), http.StatusInternalServerError)
932 return
933 }
giod8ab4f52024-07-26 16:58:34 +0400934 if err := s.createApp(user, appName, appType, network, subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +0400935 http.Error(w, err.Error(), http.StatusInternalServerError)
936 return
937 }
938 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
939}
940
gio59946282024-10-07 12:55:51 +0400941func (s *Server) handleCreateDevBranch(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400942 u := r.Context().Value(userCtx)
943 if u == nil {
944 http.Error(w, "unauthorized", http.StatusUnauthorized)
945 return
946 }
947 user, ok := u.(string)
948 if !ok {
949 http.Error(w, "could not get user", http.StatusInternalServerError)
950 return
951 }
952 vars := mux.Vars(r)
953 appName, ok := vars["app-name"]
954 if !ok || appName == "" {
955 http.Error(w, "missing app-name", http.StatusBadRequest)
956 return
957 }
958 branch := r.FormValue("branch")
959 if branch == "" {
gio5887caa2024-10-03 15:07:23 +0400960 http.Error(w, "missing branch", http.StatusBadRequest)
gio7fbd4ad2024-08-27 10:06:39 +0400961 return
962 }
963 if err := s.createDevBranch(appName, "master", branch, user); err != nil {
964 http.Error(w, err.Error(), http.StatusInternalServerError)
965 return
966 }
967 http.Redirect(w, r, fmt.Sprintf("/%s/branch/%s", appName, branch), http.StatusSeeOther)
968}
969
gio59946282024-10-07 12:55:51 +0400970func (s *Server) handleBranchDelete(w http.ResponseWriter, r *http.Request) {
gio5887caa2024-10-03 15:07:23 +0400971 u := r.Context().Value(userCtx)
972 if u == nil {
973 http.Error(w, "unauthorized", http.StatusUnauthorized)
974 return
975 }
976 vars := mux.Vars(r)
977 appName, ok := vars["app-name"]
978 if !ok || appName == "" {
979 http.Error(w, "missing app-name", http.StatusBadRequest)
980 return
981 }
982 branch, ok := vars["branch"]
983 if !ok || branch == "" {
984 http.Error(w, "missing branch", http.StatusBadRequest)
985 return
986 }
987 if err := s.deleteBranch(appName, branch); err != nil {
988 http.Error(w, err.Error(), http.StatusInternalServerError)
989 return
990 }
991 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
992}
993
gio59946282024-10-07 12:55:51 +0400994func (s *Server) handleAppDelete(w http.ResponseWriter, r *http.Request) {
gio5887caa2024-10-03 15:07:23 +0400995 u := r.Context().Value(userCtx)
996 if u == nil {
997 http.Error(w, "unauthorized", http.StatusUnauthorized)
998 return
999 }
1000 vars := mux.Vars(r)
1001 appName, ok := vars["app-name"]
1002 if !ok || appName == "" {
1003 http.Error(w, "missing app-name", http.StatusBadRequest)
1004 return
1005 }
1006 if err := s.deleteApp(appName); err != nil {
1007 http.Error(w, err.Error(), http.StatusInternalServerError)
1008 return
1009 }
gioe44c1512024-10-06 14:13:55 +04001010 http.Redirect(w, r, "/", http.StatusSeeOther)
gio5887caa2024-10-03 15:07:23 +04001011}
1012
gio81246f02024-07-10 12:02:15 +04001013type apiCreateAppReq struct {
gio5e49bb62024-07-20 10:43:19 +04001014 AppType string `json:"type"`
gio33059762024-07-05 13:19:07 +04001015 AdminPublicKey string `json:"adminPublicKey"`
gio11617ac2024-07-15 16:09:04 +04001016 Network string `json:"network"`
gio5e49bb62024-07-20 10:43:19 +04001017 Subdomain string `json:"subdomain"`
gio33059762024-07-05 13:19:07 +04001018}
1019
gio81246f02024-07-10 12:02:15 +04001020type apiCreateAppResp struct {
1021 AppName string `json:"appName"`
1022 Password string `json:"password"`
gio33059762024-07-05 13:19:07 +04001023}
1024
gio59946282024-10-07 12:55:51 +04001025func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001026 w.Header().Set("Access-Control-Allow-Origin", "*")
gio81246f02024-07-10 12:02:15 +04001027 var req apiCreateAppReq
gio33059762024-07-05 13:19:07 +04001028 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1029 http.Error(w, err.Error(), http.StatusBadRequest)
1030 return
1031 }
1032 g := installer.NewFixedLengthRandomNameGenerator(3)
1033 appName, err := g.Generate()
1034 if err != nil {
1035 http.Error(w, err.Error(), http.StatusInternalServerError)
1036 return
1037 }
gio11617ac2024-07-15 16:09:04 +04001038 user, err := s.client.FindUser(req.AdminPublicKey)
gio81246f02024-07-10 12:02:15 +04001039 if err != nil {
gio33059762024-07-05 13:19:07 +04001040 http.Error(w, err.Error(), http.StatusInternalServerError)
1041 return
1042 }
gio11617ac2024-07-15 16:09:04 +04001043 if user != "" {
1044 http.Error(w, "public key already registered", http.StatusBadRequest)
1045 return
1046 }
1047 user = appName
1048 if err := s.client.AddUser(user, req.AdminPublicKey); err != nil {
1049 http.Error(w, err.Error(), http.StatusInternalServerError)
1050 return
1051 }
1052 password := generatePassword()
1053 hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
1054 if err != nil {
1055 http.Error(w, err.Error(), http.StatusInternalServerError)
1056 return
1057 }
giocafd4e62024-07-31 10:53:40 +04001058 if err := s.st.CreateUser(user, hashed, req.Network); err != nil {
gio11617ac2024-07-15 16:09:04 +04001059 http.Error(w, err.Error(), http.StatusInternalServerError)
1060 return
1061 }
1062 if err := s.st.CreateApp(appName, user); err != nil {
1063 http.Error(w, err.Error(), http.StatusInternalServerError)
1064 return
1065 }
giod8ab4f52024-07-26 16:58:34 +04001066 if err := s.createApp(user, appName, req.AppType, req.Network, req.Subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +04001067 http.Error(w, err.Error(), http.StatusInternalServerError)
1068 return
1069 }
gio81246f02024-07-10 12:02:15 +04001070 resp := apiCreateAppResp{
1071 AppName: appName,
1072 Password: password,
1073 }
gio33059762024-07-05 13:19:07 +04001074 if err := json.NewEncoder(w).Encode(resp); err != nil {
1075 http.Error(w, err.Error(), http.StatusInternalServerError)
1076 return
1077 }
1078}
1079
gio59946282024-10-07 12:55:51 +04001080func (s *Server) isNetworkUseAllowed(network string) bool {
giocafd4e62024-07-31 10:53:40 +04001081 if !s.external {
giod8ab4f52024-07-26 16:58:34 +04001082 return true
1083 }
1084 for _, cfg := range s.appConfigs {
1085 if strings.ToLower(cfg.Network) == network {
1086 return false
1087 }
1088 }
1089 return true
1090}
1091
gio59946282024-10-07 12:55:51 +04001092func (s *Server) createApp(user, appName, appType, network, subdomain string) error {
gio9d66f322024-07-06 13:45:10 +04001093 s.l.Lock()
1094 defer s.l.Unlock()
gio33059762024-07-05 13:19:07 +04001095 fmt.Printf("Creating app: %s\n", appName)
giod8ab4f52024-07-26 16:58:34 +04001096 network = strings.ToLower(network)
1097 if !s.isNetworkUseAllowed(network) {
1098 return fmt.Errorf("network already used: %s", network)
1099 }
gio33059762024-07-05 13:19:07 +04001100 if ok, err := s.client.RepoExists(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001101 return err
gio33059762024-07-05 13:19:07 +04001102 } else if ok {
gio11617ac2024-07-15 16:09:04 +04001103 return nil
gioa60f0de2024-07-08 10:49:48 +04001104 }
gio5e49bb62024-07-20 10:43:19 +04001105 networks, err := s.getNetworks(user)
1106 if err != nil {
1107 return err
1108 }
giod8ab4f52024-07-26 16:58:34 +04001109 n, ok := installer.NetworkMap(networks)[network]
gio5e49bb62024-07-20 10:43:19 +04001110 if !ok {
1111 return fmt.Errorf("network not found: %s\n", network)
1112 }
gio33059762024-07-05 13:19:07 +04001113 if err := s.client.AddRepository(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001114 return err
gio33059762024-07-05 13:19:07 +04001115 }
1116 appRepo, err := s.client.GetRepo(appName)
1117 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001118 return err
gio33059762024-07-05 13:19:07 +04001119 }
gio9f6b27d2024-10-14 10:08:40 +04001120 files, err := s.renderAppConfigTemplate(user, appType, n, subdomain)
gio7fbd4ad2024-08-27 10:06:39 +04001121 if err != nil {
1122 return err
1123 }
1124 return s.createAppForBranch(appRepo, appName, "master", user, network, files)
1125}
1126
gio59946282024-10-07 12:55:51 +04001127func (s *Server) createDevBranch(appName, fromBranch, toBranch, user string) error {
gio7fbd4ad2024-08-27 10:06:39 +04001128 s.l.Lock()
1129 defer s.l.Unlock()
1130 fmt.Printf("Creating dev branch app: %s %s %s\n", appName, fromBranch, toBranch)
1131 appRepo, err := s.client.GetRepoBranch(appName, fromBranch)
1132 if err != nil {
1133 return err
1134 }
gioc81a8472024-09-24 13:06:19 +02001135 appCfg, err := soft.ReadFile(appRepo, "app.json")
gio7fbd4ad2024-08-27 10:06:39 +04001136 if err != nil {
1137 return err
1138 }
gio9f6b27d2024-10-14 10:08:40 +04001139 network, branchCfg, err := createDevBranchAppConfig(appCfg, toBranch, user, s.selfPublic)
gio7fbd4ad2024-08-27 10:06:39 +04001140 if err != nil {
1141 return err
1142 }
gioc81a8472024-09-24 13:06:19 +02001143 return s.createAppForBranch(appRepo, appName, toBranch, user, network, map[string][]byte{"app.json": branchCfg})
gio7fbd4ad2024-08-27 10:06:39 +04001144}
1145
gio59946282024-10-07 12:55:51 +04001146func (s *Server) deleteBranch(appName string, branch string) error {
gio5887caa2024-10-03 15:07:23 +04001147 appBranch := fmt.Sprintf("dodo_%s", branch)
1148 hf := installer.NewGitHelmFetcher()
1149 if err := func() error {
1150 repo, err := s.client.GetRepoBranch(appName, appBranch)
1151 if err != nil {
1152 return err
1153 }
1154 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
1155 if err != nil {
1156 return err
1157 }
1158 return m.Remove("app")
1159 }(); err != nil {
1160 return err
1161 }
1162 configRepo, err := s.client.GetRepo(ConfigRepoName)
1163 if err != nil {
1164 return err
1165 }
1166 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
1167 if err != nil {
1168 return err
1169 }
1170 appPath := fmt.Sprintf("%s/%s", appName, branch)
gio829b1b72024-10-05 21:50:56 +04001171 if err := m.Remove(appPath); err != nil {
gio5887caa2024-10-03 15:07:23 +04001172 return err
1173 }
1174 if err := s.client.DeleteRepoBranch(appName, appBranch); err != nil {
1175 return err
1176 }
1177 if branch != "master" {
gioe44c1512024-10-06 14:13:55 +04001178 if err := s.client.DeleteRepoBranch(appName, branch); err != nil {
1179 return err
1180 }
gio5887caa2024-10-03 15:07:23 +04001181 }
gioe44c1512024-10-06 14:13:55 +04001182 return s.st.DeleteBranch(appName, branch)
gio5887caa2024-10-03 15:07:23 +04001183}
1184
gio59946282024-10-07 12:55:51 +04001185func (s *Server) deleteApp(appName string) error {
gio5887caa2024-10-03 15:07:23 +04001186 configRepo, err := s.client.GetRepo(ConfigRepoName)
1187 if err != nil {
1188 return err
1189 }
1190 branches, err := configRepo.ListDir(fmt.Sprintf("/%s", appName))
1191 if err != nil {
1192 return err
1193 }
1194 for _, b := range branches {
1195 if !b.IsDir() || strings.HasPrefix(b.Name(), "dodo_") {
1196 continue
1197 }
1198 if err := s.deleteBranch(appName, b.Name()); err != nil {
1199 return err
1200 }
1201 }
gioe44c1512024-10-06 14:13:55 +04001202 if err := s.client.DeleteRepo(appName); err != nil {
1203 return err
1204 }
1205 return s.st.DeleteApp(appName)
gio5887caa2024-10-03 15:07:23 +04001206}
1207
gio59946282024-10-07 12:55:51 +04001208func (s *Server) createAppForBranch(
gio7fbd4ad2024-08-27 10:06:39 +04001209 repo soft.RepoIO,
1210 appName string,
1211 branch string,
1212 user string,
1213 network string,
1214 files map[string][]byte,
1215) error {
1216 commit, err := repo.Do(func(fs soft.RepoFS) (string, error) {
1217 for path, contents := range files {
1218 if err := soft.WriteFile(fs, path, string(contents)); err != nil {
1219 return "", err
1220 }
1221 }
1222 return "init", nil
1223 }, soft.WithCommitToBranch(branch))
1224 if err != nil {
1225 return err
1226 }
1227 networks, err := s.getNetworks(user)
giob4a3a192024-08-19 09:55:47 +04001228 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001229 return err
gio33059762024-07-05 13:19:07 +04001230 }
giof15b9da2024-09-19 06:59:16 +04001231 // TODO(gio): get only available ones by owner
1232 clusters, err := s.getClusters()
1233 if err != nil {
1234 return err
1235 }
gio33059762024-07-05 13:19:07 +04001236 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
gio94904702024-07-26 16:58:34 +04001237 instanceApp, err := installer.FindEnvApp(apps, "dodo-app-instance")
1238 if err != nil {
1239 return err
1240 }
1241 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
gio33059762024-07-05 13:19:07 +04001242 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001243 return err
gio33059762024-07-05 13:19:07 +04001244 }
1245 suffixGen := installer.NewFixedLengthRandomSuffixGenerator(3)
1246 suffix, err := suffixGen.Generate()
1247 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001248 return err
gio33059762024-07-05 13:19:07 +04001249 }
gio94904702024-07-26 16:58:34 +04001250 namespace := fmt.Sprintf("%s%s%s", s.env.NamespacePrefix, instanceApp.Namespace(), suffix)
gio7fbd4ad2024-08-27 10:06:39 +04001251 s.setAppConfig(appName, branch, appConfig{namespace, network})
giof15b9da2024-09-19 06:59:16 +04001252 resources, err := s.updateDodoApp(instanceAppStatus, appName, branch, namespace, networks, clusters, user)
giob4a3a192024-08-19 09:55:47 +04001253 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001254 fmt.Printf("Error: %s\n", err.Error())
giob4a3a192024-08-19 09:55:47 +04001255 return err
1256 }
gio7fbd4ad2024-08-27 10:06:39 +04001257 if err = s.createCommit(appName, branch, commit, initCommitMsg, err, resources); err != nil {
giob4a3a192024-08-19 09:55:47 +04001258 fmt.Printf("Error: %s\n", err.Error())
gio11617ac2024-07-15 16:09:04 +04001259 return err
gio33059762024-07-05 13:19:07 +04001260 }
giod8ab4f52024-07-26 16:58:34 +04001261 configRepo, err := s.client.GetRepo(ConfigRepoName)
gio33059762024-07-05 13:19:07 +04001262 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001263 return err
gio33059762024-07-05 13:19:07 +04001264 }
1265 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001266 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
gio33059762024-07-05 13:19:07 +04001267 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001268 return err
gio33059762024-07-05 13:19:07 +04001269 }
gio7fbd4ad2024-08-27 10:06:39 +04001270 appPath := fmt.Sprintf("/%s/%s", appName, branch)
giob4a3a192024-08-19 09:55:47 +04001271 _, err = configRepo.Do(func(fs soft.RepoFS) (string, error) {
giod8ab4f52024-07-26 16:58:34 +04001272 w, err := fs.Writer(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +04001273 if err != nil {
1274 return "", err
1275 }
1276 defer w.Close()
giod8ab4f52024-07-26 16:58:34 +04001277 if err := json.NewEncoder(w).Encode(s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +04001278 return "", err
1279 }
1280 if _, err := m.Install(
gio94904702024-07-26 16:58:34 +04001281 instanceApp,
gio9d66f322024-07-06 13:45:10 +04001282 appName,
gio7fbd4ad2024-08-27 10:06:39 +04001283 appPath,
gio9d66f322024-07-06 13:45:10 +04001284 namespace,
1285 map[string]any{
1286 "repoAddr": s.client.GetRepoAddress(appName),
1287 "repoHost": strings.Split(s.client.Address(), ":")[0],
gio7fbd4ad2024-08-27 10:06:39 +04001288 "branch": fmt.Sprintf("dodo_%s", branch),
gio9d66f322024-07-06 13:45:10 +04001289 "gitRepoPublicKey": s.gitRepoPublicKey,
1290 },
1291 installer.WithConfig(&s.env),
gio23bdc1b2024-07-11 16:07:47 +04001292 installer.WithNoNetworks(),
gio9d66f322024-07-06 13:45:10 +04001293 installer.WithNoPublish(),
1294 installer.WithNoLock(),
1295 ); err != nil {
1296 return "", err
1297 }
1298 return fmt.Sprintf("Installed app: %s", appName), nil
giob4a3a192024-08-19 09:55:47 +04001299 })
1300 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001301 return err
gio33059762024-07-05 13:19:07 +04001302 }
gio7fbd4ad2024-08-27 10:06:39 +04001303 return s.initAppACLs(m, appPath, appName, branch, user)
1304}
1305
gio59946282024-10-07 12:55:51 +04001306func (s *Server) initAppACLs(m *installer.AppManager, path, appName, branch, user string) error {
gio7fbd4ad2024-08-27 10:06:39 +04001307 cfg, err := m.GetInstance(path)
gio33059762024-07-05 13:19:07 +04001308 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001309 return err
gio33059762024-07-05 13:19:07 +04001310 }
1311 fluxKeys, ok := cfg.Input["fluxKeys"]
1312 if !ok {
gio11617ac2024-07-15 16:09:04 +04001313 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001314 }
1315 fluxPublicKey, ok := fluxKeys.(map[string]any)["public"]
1316 if !ok {
gio11617ac2024-07-15 16:09:04 +04001317 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001318 }
1319 if ok, err := s.client.UserExists("fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001320 return err
gio33059762024-07-05 13:19:07 +04001321 } else if ok {
1322 if err := s.client.AddPublicKey("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001323 return err
gio33059762024-07-05 13:19:07 +04001324 }
1325 } else {
1326 if err := s.client.AddUser("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001327 return err
gio33059762024-07-05 13:19:07 +04001328 }
1329 }
gio7fbd4ad2024-08-27 10:06:39 +04001330 if branch != "master" {
1331 return nil
1332 }
gio33059762024-07-05 13:19:07 +04001333 if err := s.client.AddReadOnlyCollaborator(appName, "fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001334 return err
gio33059762024-07-05 13:19:07 +04001335 }
gio7fbd4ad2024-08-27 10:06:39 +04001336 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
gio11617ac2024-07-15 16:09:04 +04001337 return err
gio33059762024-07-05 13:19:07 +04001338 }
gio7fbd4ad2024-08-27 10:06:39 +04001339 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 +04001340 return err
gio33059762024-07-05 13:19:07 +04001341 }
gio2ccb6e32024-08-15 12:01:33 +04001342 if !s.external {
1343 go func() {
1344 users, err := s.client.GetAllUsers()
1345 if err != nil {
1346 fmt.Println(err)
1347 return
1348 }
1349 for _, user := range users {
1350 // TODO(gio): fluxcd should have only read access
1351 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
1352 fmt.Println(err)
1353 }
1354 }
1355 }()
1356 }
gio43b0f422024-08-21 10:40:13 +04001357 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1358 go s.reconciler.Reconcile(ctx, s.namespace, "config")
gio11617ac2024-07-15 16:09:04 +04001359 return nil
gio33059762024-07-05 13:19:07 +04001360}
1361
gio81246f02024-07-10 12:02:15 +04001362type apiAddAdminKeyReq struct {
gio7fbd4ad2024-08-27 10:06:39 +04001363 User string `json:"user"`
1364 PublicKey string `json:"publicKey"`
gio70be3e52024-06-26 18:27:19 +04001365}
1366
gio59946282024-10-07 12:55:51 +04001367func (s *Server) handleAPIAddPublicKey(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +04001368 var req apiAddAdminKeyReq
gio70be3e52024-06-26 18:27:19 +04001369 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1370 http.Error(w, err.Error(), http.StatusBadRequest)
1371 return
1372 }
gio7fbd4ad2024-08-27 10:06:39 +04001373 if req.User == "" {
1374 http.Error(w, "invalid user", http.StatusBadRequest)
1375 return
1376 }
1377 if req.PublicKey == "" {
1378 http.Error(w, "invalid public key", http.StatusBadRequest)
1379 return
1380 }
1381 if err := s.client.AddPublicKey(req.User, req.PublicKey); err != nil {
gio70be3e52024-06-26 18:27:19 +04001382 http.Error(w, err.Error(), http.StatusInternalServerError)
1383 return
1384 }
1385}
1386
gio94904702024-07-26 16:58:34 +04001387type dodoAppRendered struct {
1388 App struct {
1389 Ingress struct {
1390 Network string `json:"network"`
1391 Subdomain string `json:"subdomain"`
1392 } `json:"ingress"`
1393 } `json:"app"`
1394 Input struct {
1395 AppId string `json:"appId"`
1396 } `json:"input"`
1397}
1398
gio7fbd4ad2024-08-27 10:06:39 +04001399// TODO(gio): must not require owner, now we need it to bootstrap dev vm.
gio59946282024-10-07 12:55:51 +04001400func (s *Server) updateDodoApp(
gio43b0f422024-08-21 10:40:13 +04001401 appStatus installer.EnvApp,
gio7fbd4ad2024-08-27 10:06:39 +04001402 name string,
1403 branch string,
1404 namespace string,
gio43b0f422024-08-21 10:40:13 +04001405 networks []installer.Network,
giof15b9da2024-09-19 06:59:16 +04001406 clusters []installer.Cluster,
gio7fbd4ad2024-08-27 10:06:39 +04001407 owner string,
gio43b0f422024-08-21 10:40:13 +04001408) (installer.ReleaseResources, error) {
gio7fbd4ad2024-08-27 10:06:39 +04001409 repo, err := s.client.GetRepoBranch(name, branch)
gio0eaf2712024-04-14 13:08:46 +04001410 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001411 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001412 }
giof8843412024-05-22 16:38:05 +04001413 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001414 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
gio0eaf2712024-04-14 13:08:46 +04001415 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001416 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001417 }
gioc81a8472024-09-24 13:06:19 +02001418 appCfg, err := soft.ReadFile(repo, "app.json")
gio0eaf2712024-04-14 13:08:46 +04001419 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001420 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001421 }
1422 app, err := installer.NewDodoApp(appCfg)
1423 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001424 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001425 }
giof8843412024-05-22 16:38:05 +04001426 lg := installer.GitRepositoryLocalChartGenerator{"app", namespace}
giob4a3a192024-08-19 09:55:47 +04001427 var ret installer.ReleaseResources
1428 if _, err := repo.Do(func(r soft.RepoFS) (string, error) {
1429 ret, err = m.Install(
gio94904702024-07-26 16:58:34 +04001430 app,
1431 "app",
1432 "/.dodo/app",
1433 namespace,
1434 map[string]any{
gio7fbd4ad2024-08-27 10:06:39 +04001435 "repoAddr": repo.FullAddress(),
1436 "repoPublicAddr": s.repoPublicAddr,
1437 "managerAddr": fmt.Sprintf("http://%s", s.self),
1438 "appId": name,
1439 "branch": branch,
1440 "sshPrivateKey": s.sshKey,
1441 "username": owner,
gio94904702024-07-26 16:58:34 +04001442 },
1443 installer.WithNoPull(),
1444 installer.WithNoPublish(),
1445 installer.WithConfig(&s.env),
1446 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001447 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001448 installer.WithLocalChartGenerator(lg),
1449 installer.WithNoLock(),
1450 )
1451 if err != nil {
1452 return "", err
1453 }
1454 var rendered dodoAppRendered
giob4a3a192024-08-19 09:55:47 +04001455 if err := json.NewDecoder(bytes.NewReader(ret.RenderedRaw)).Decode(&rendered); err != nil {
gio94904702024-07-26 16:58:34 +04001456 return "", nil
1457 }
1458 if _, err := m.Install(
1459 appStatus,
1460 "status",
1461 "/.dodo/status",
1462 s.namespace,
1463 map[string]any{
1464 "appName": rendered.Input.AppId,
1465 "network": rendered.App.Ingress.Network,
1466 "appSubdomain": rendered.App.Ingress.Subdomain,
1467 },
1468 installer.WithNoPull(),
1469 installer.WithNoPublish(),
1470 installer.WithConfig(&s.env),
1471 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001472 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001473 installer.WithLocalChartGenerator(lg),
1474 installer.WithNoLock(),
1475 ); err != nil {
1476 return "", err
1477 }
1478 return "install app", nil
1479 },
gio7fbd4ad2024-08-27 10:06:39 +04001480 soft.WithCommitToBranch(fmt.Sprintf("dodo_%s", branch)),
gio94904702024-07-26 16:58:34 +04001481 soft.WithForce(),
giob4a3a192024-08-19 09:55:47 +04001482 ); err != nil {
1483 return installer.ReleaseResources{}, err
1484 }
gio43b0f422024-08-21 10:40:13 +04001485 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1486 go s.reconciler.Reconcile(ctx, namespace, "app")
giob4a3a192024-08-19 09:55:47 +04001487 return ret, nil
gio0eaf2712024-04-14 13:08:46 +04001488}
gio33059762024-07-05 13:19:07 +04001489
gio9f6b27d2024-10-14 10:08:40 +04001490func (s *Server) renderAppConfigTemplate(user, appType string, network installer.Network, subdomain string) (map[string][]byte, error) {
giob54db242024-07-30 18:49:33 +04001491 appType = strings.Replace(appType, ":", "-", 1)
gio5e49bb62024-07-20 10:43:19 +04001492 appTmpl, err := s.appTmpls.Find(appType)
1493 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001494 return nil, err
gio33059762024-07-05 13:19:07 +04001495 }
gio9f6b27d2024-10-14 10:08:40 +04001496 return appTmpl.Render(fmt.Sprintf("%s/schemas/%s/app.schema.json", s.selfPublic, user), network, subdomain)
gio33059762024-07-05 13:19:07 +04001497}
gio81246f02024-07-10 12:02:15 +04001498
1499func generatePassword() string {
1500 return "foo"
1501}
giocb34ad22024-07-11 08:01:13 +04001502
gio59946282024-10-07 12:55:51 +04001503func (s *Server) getNetworks(user string) ([]installer.Network, error) {
gio23bdc1b2024-07-11 16:07:47 +04001504 addr := fmt.Sprintf("%s/api/networks", s.envAppManagerAddr)
giocb34ad22024-07-11 08:01:13 +04001505 resp, err := http.Get(addr)
1506 if err != nil {
1507 return nil, err
1508 }
gio23bdc1b2024-07-11 16:07:47 +04001509 networks := []installer.Network{}
1510 if json.NewDecoder(resp.Body).Decode(&networks); err != nil {
giocb34ad22024-07-11 08:01:13 +04001511 return nil, err
1512 }
gio11617ac2024-07-15 16:09:04 +04001513 return s.nf.Filter(user, networks)
1514}
1515
gio59946282024-10-07 12:55:51 +04001516func (s *Server) getClusters() ([]installer.Cluster, error) {
giof15b9da2024-09-19 06:59:16 +04001517 addr := fmt.Sprintf("%s/api/clusters", s.envAppManagerAddr)
1518 resp, err := http.Get(addr)
1519 if err != nil {
1520 return nil, err
1521 }
1522 clusters := []installer.Cluster{}
1523 if json.NewDecoder(resp.Body).Decode(&clusters); err != nil {
1524 return nil, err
1525 }
1526 fmt.Printf("CLUSTERS %+v\n", clusters)
1527 return clusters, nil
1528}
1529
gio8fae3af2024-07-25 13:43:31 +04001530type publicNetworkData struct {
1531 Name string `json:"name"`
1532 Domain string `json:"domain"`
1533}
1534
1535type publicData struct {
1536 Networks []publicNetworkData `json:"networks"`
1537 Types []string `json:"types"`
1538}
1539
gio59946282024-10-07 12:55:51 +04001540func (s *Server) handleAPIPublicData(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001541 w.Header().Set("Access-Control-Allow-Origin", "*")
1542 s.l.Lock()
1543 defer s.l.Unlock()
gio8fae3af2024-07-25 13:43:31 +04001544 networks, err := s.getNetworks("")
1545 if err != nil {
1546 http.Error(w, err.Error(), http.StatusInternalServerError)
1547 return
1548 }
1549 var ret publicData
1550 for _, n := range networks {
giod8ab4f52024-07-26 16:58:34 +04001551 if s.isNetworkUseAllowed(strings.ToLower(n.Name)) {
1552 ret.Networks = append(ret.Networks, publicNetworkData{n.Name, n.Domain})
1553 }
gio8fae3af2024-07-25 13:43:31 +04001554 }
1555 for _, t := range s.appTmpls.Types() {
giob54db242024-07-30 18:49:33 +04001556 ret.Types = append(ret.Types, strings.Replace(t, "-", ":", 1))
gio8fae3af2024-07-25 13:43:31 +04001557 }
gio8fae3af2024-07-25 13:43:31 +04001558 if err := json.NewEncoder(w).Encode(ret); err != nil {
1559 http.Error(w, err.Error(), http.StatusInternalServerError)
1560 return
1561 }
1562}
1563
gio59946282024-10-07 12:55:51 +04001564func (s *Server) createCommit(name, branch, hash, message string, err error, resources installer.ReleaseResources) error {
giob4a3a192024-08-19 09:55:47 +04001565 if err != nil {
1566 fmt.Printf("Error: %s\n", err.Error())
gio7fbd4ad2024-08-27 10:06:39 +04001567 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001568 fmt.Printf("Error: %s\n", err.Error())
1569 return err
1570 }
1571 return err
1572 }
1573 var resB bytes.Buffer
1574 if err := json.NewEncoder(&resB).Encode(resources); err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001575 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001576 fmt.Printf("Error: %s\n", err.Error())
1577 return err
1578 }
1579 return err
1580 }
gio7fbd4ad2024-08-27 10:06:39 +04001581 if err := s.st.CreateCommit(name, branch, hash, message, "OK", "", resB.Bytes()); err != nil {
giob4a3a192024-08-19 09:55:47 +04001582 fmt.Printf("Error: %s\n", err.Error())
1583 return err
1584 }
1585 return nil
1586}
1587
gio11617ac2024-07-15 16:09:04 +04001588func pickNetwork(networks []installer.Network, network string) []installer.Network {
1589 for _, n := range networks {
1590 if n.Name == network {
1591 return []installer.Network{n}
1592 }
1593 }
1594 return []installer.Network{}
1595}
1596
1597type NetworkFilter interface {
1598 Filter(user string, networks []installer.Network) ([]installer.Network, error)
1599}
1600
1601type noNetworkFilter struct{}
1602
1603func NewNoNetworkFilter() NetworkFilter {
1604 return noNetworkFilter{}
1605}
1606
gio8fae3af2024-07-25 13:43:31 +04001607func (f noNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001608 return networks, nil
1609}
1610
1611type filterByOwner struct {
1612 st Store
1613}
1614
1615func NewNetworkFilterByOwner(st Store) NetworkFilter {
1616 return &filterByOwner{st}
1617}
1618
1619func (f *filterByOwner) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio8fae3af2024-07-25 13:43:31 +04001620 if user == "" {
1621 return networks, nil
1622 }
gio11617ac2024-07-15 16:09:04 +04001623 network, err := f.st.GetUserNetwork(user)
1624 if err != nil {
1625 return nil, err
gio23bdc1b2024-07-11 16:07:47 +04001626 }
1627 ret := []installer.Network{}
1628 for _, n := range networks {
gio11617ac2024-07-15 16:09:04 +04001629 if n.Name == network {
gio23bdc1b2024-07-11 16:07:47 +04001630 ret = append(ret, n)
1631 }
1632 }
giocb34ad22024-07-11 08:01:13 +04001633 return ret, nil
1634}
gio11617ac2024-07-15 16:09:04 +04001635
1636type allowListFilter struct {
1637 allowed []string
1638}
1639
1640func NewAllowListFilter(allowed []string) NetworkFilter {
1641 return &allowListFilter{allowed}
1642}
1643
gio8fae3af2024-07-25 13:43:31 +04001644func (f *allowListFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001645 ret := []installer.Network{}
1646 for _, n := range networks {
1647 if slices.Contains(f.allowed, n.Name) {
1648 ret = append(ret, n)
1649 }
1650 }
1651 return ret, nil
1652}
1653
1654type combinedNetworkFilter struct {
1655 filters []NetworkFilter
1656}
1657
1658func NewCombinedFilter(filters ...NetworkFilter) NetworkFilter {
1659 return &combinedNetworkFilter{filters}
1660}
1661
gio8fae3af2024-07-25 13:43:31 +04001662func (f *combinedNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001663 ret := networks
1664 var err error
1665 for _, f := range f.filters {
gio8fae3af2024-07-25 13:43:31 +04001666 ret, err = f.Filter(user, ret)
gio11617ac2024-07-15 16:09:04 +04001667 if err != nil {
1668 return nil, err
1669 }
1670 }
1671 return ret, nil
1672}
giocafd4e62024-07-31 10:53:40 +04001673
1674type user struct {
1675 Username string `json:"username"`
1676 Email string `json:"email"`
1677 SSHPublicKeys []string `json:"sshPublicKeys,omitempty"`
1678}
1679
gio59946282024-10-07 12:55:51 +04001680func (s *Server) handleAPISyncUsers(_ http.ResponseWriter, _ *http.Request) {
giocafd4e62024-07-31 10:53:40 +04001681 go s.syncUsers()
1682}
1683
gio59946282024-10-07 12:55:51 +04001684func (s *Server) syncUsers() {
giocafd4e62024-07-31 10:53:40 +04001685 if s.external {
1686 panic("MUST NOT REACH!")
1687 }
1688 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/api/sync-users", s.fetchUsersAddr, s.self))
1689 if err != nil {
1690 return
1691 }
1692 users := []user{}
1693 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
1694 fmt.Println(err)
1695 return
1696 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001697 validUsernames := make(map[string]user)
1698 for _, u := range users {
1699 validUsernames[u.Username] = u
1700 }
1701 allClientUsers, err := s.client.GetAllUsers()
1702 if err != nil {
1703 fmt.Println(err)
1704 return
1705 }
1706 keyToUser := make(map[string]string)
1707 for _, clientUser := range allClientUsers {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001708 if clientUser == "admin" || clientUser == "fluxcd" {
1709 continue
1710 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001711 userData, ok := validUsernames[clientUser]
1712 if !ok {
1713 if err := s.client.RemoveUser(clientUser); err != nil {
1714 fmt.Println(err)
1715 return
1716 }
1717 } else {
1718 existingKeys, err := s.client.GetUserPublicKeys(clientUser)
1719 if err != nil {
1720 fmt.Println(err)
1721 return
1722 }
1723 for _, existingKey := range existingKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001724 cleanKey := soft.CleanKey(existingKey)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001725 keyOk := slices.ContainsFunc(userData.SSHPublicKeys, func(key string) bool {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001726 return cleanKey == soft.CleanKey(key)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001727 })
1728 if !keyOk {
1729 if err := s.client.RemovePublicKey(clientUser, existingKey); err != nil {
1730 fmt.Println(err)
1731 }
1732 } else {
1733 keyToUser[cleanKey] = clientUser
1734 }
1735 }
1736 }
1737 }
giocafd4e62024-07-31 10:53:40 +04001738 for _, u := range users {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001739 if err := s.st.CreateUser(u.Username, nil, ""); err != nil && !errors.Is(err, ErrorAlreadyExists) {
1740 fmt.Println(err)
1741 return
1742 }
giocafd4e62024-07-31 10:53:40 +04001743 if len(u.SSHPublicKeys) == 0 {
1744 continue
1745 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001746 ok, err := s.client.UserExists(u.Username)
1747 if err != nil {
giocafd4e62024-07-31 10:53:40 +04001748 fmt.Println(err)
1749 return
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001750 }
1751 if !ok {
1752 if err := s.client.AddUser(u.Username, u.SSHPublicKeys[0]); err != nil {
1753 fmt.Println(err)
1754 return
1755 }
1756 } else {
1757 for _, key := range u.SSHPublicKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001758 cleanKey := soft.CleanKey(key)
1759 if user, ok := keyToUser[cleanKey]; ok {
1760 if u.Username != user {
1761 panic("MUST NOT REACH! IMPOSSIBLE KEY USER RECORD")
1762 }
1763 continue
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001764 }
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001765 if err := s.client.AddPublicKey(u.Username, cleanKey); err != nil {
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001766 fmt.Println(err)
1767 return
giocafd4e62024-07-31 10:53:40 +04001768 }
1769 }
1770 }
1771 }
1772 repos, err := s.client.GetAllRepos()
1773 if err != nil {
1774 return
1775 }
1776 for _, r := range repos {
1777 if r == ConfigRepoName {
1778 continue
1779 }
1780 for _, u := range users {
1781 if err := s.client.AddReadWriteCollaborator(r, u.Username); err != nil {
1782 fmt.Println(err)
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001783 continue
giocafd4e62024-07-31 10:53:40 +04001784 }
1785 }
1786 }
1787}
giob4a3a192024-08-19 09:55:47 +04001788
1789func extractResourceData(resources []installer.Resource) (resourceData, error) {
1790 var ret resourceData
1791 for _, r := range resources {
1792 t, ok := r.Annotations["dodo.cloud/resource-type"]
1793 if !ok {
1794 continue
1795 }
giof078f462024-10-14 09:07:33 +04001796 internal, ok := r.Annotations["dodo.cloud/internal"]
1797 if ok && strings.ToLower(internal) == "true" {
1798 continue
1799 }
giob4a3a192024-08-19 09:55:47 +04001800 switch t {
1801 case "volume":
1802 name, ok := r.Annotations["dodo.cloud/resource.volume.name"]
1803 if !ok {
1804 return resourceData{}, fmt.Errorf("no name")
1805 }
1806 size, ok := r.Annotations["dodo.cloud/resource.volume.size"]
1807 if !ok {
1808 return resourceData{}, fmt.Errorf("no size")
1809 }
1810 ret.Volume = append(ret.Volume, volume{name, size})
1811 case "postgresql":
1812 name, ok := r.Annotations["dodo.cloud/resource.postgresql.name"]
1813 if !ok {
1814 return resourceData{}, fmt.Errorf("no name")
1815 }
1816 version, ok := r.Annotations["dodo.cloud/resource.postgresql.version"]
1817 if !ok {
1818 return resourceData{}, fmt.Errorf("no version")
1819 }
1820 volume, ok := r.Annotations["dodo.cloud/resource.postgresql.volume"]
1821 if !ok {
1822 return resourceData{}, fmt.Errorf("no volume")
1823 }
1824 ret.PostgreSQL = append(ret.PostgreSQL, postgresql{name, version, volume})
gio07eb1082024-10-25 14:35:56 +04001825 case "mongodb":
1826 name, ok := r.Annotations["dodo.cloud/resource.mongodb.name"]
1827 if !ok {
1828 return resourceData{}, fmt.Errorf("no name")
1829 }
1830 version, ok := r.Annotations["dodo.cloud/resource.mongodb.version"]
1831 if !ok {
1832 return resourceData{}, fmt.Errorf("no version")
1833 }
1834 volume, ok := r.Annotations["dodo.cloud/resource.mongodb.volume"]
1835 if !ok {
1836 return resourceData{}, fmt.Errorf("no volume")
1837 }
1838 ret.MongoDB = append(ret.MongoDB, mongodb{name, version, volume})
giob4a3a192024-08-19 09:55:47 +04001839 case "ingress":
giof078f462024-10-14 09:07:33 +04001840 name, ok := r.Annotations["dodo.cloud/resource.ingress.name"]
1841 if !ok {
1842 return resourceData{}, fmt.Errorf("no name")
1843 }
1844 home, ok := r.Annotations["dodo.cloud/resource.ingress.home"]
1845 if !ok {
1846 home = ""
1847 }
giob4a3a192024-08-19 09:55:47 +04001848 host, ok := r.Annotations["dodo.cloud/resource.ingress.host"]
1849 if !ok {
1850 return resourceData{}, fmt.Errorf("no host")
1851 }
giof078f462024-10-14 09:07:33 +04001852 ret.Ingress = append(ret.Ingress, ingress{name, host, home})
gio7fbd4ad2024-08-27 10:06:39 +04001853 case "virtual-machine":
1854 name, ok := r.Annotations["dodo.cloud/resource.virtual-machine.name"]
1855 if !ok {
1856 return resourceData{}, fmt.Errorf("no name")
1857 }
1858 user, ok := r.Annotations["dodo.cloud/resource.virtual-machine.user"]
1859 if !ok {
1860 return resourceData{}, fmt.Errorf("no user")
1861 }
1862 cpuCoresS, ok := r.Annotations["dodo.cloud/resource.virtual-machine.cpu-cores"]
1863 if !ok {
1864 return resourceData{}, fmt.Errorf("no cpu cores")
1865 }
1866 cpuCores, err := strconv.Atoi(cpuCoresS)
1867 if err != nil {
1868 return resourceData{}, fmt.Errorf("invalid cpu cores: %s", cpuCoresS)
1869 }
1870 memory, ok := r.Annotations["dodo.cloud/resource.virtual-machine.memory"]
1871 if !ok {
1872 return resourceData{}, fmt.Errorf("no memory")
1873 }
1874 ret.VirtualMachine = append(ret.VirtualMachine, vm{name, user, cpuCores, memory})
giob4a3a192024-08-19 09:55:47 +04001875 default:
1876 fmt.Printf("Unknown resource: %+v\n", r.Annotations)
1877 }
1878 }
giof078f462024-10-14 09:07:33 +04001879 sort.Slice(ret.Ingress, func(i, j int) bool {
1880 return strings.Compare(ret.Ingress[i].Name, ret.Ingress[j].Name) < 0
1881 })
giob4a3a192024-08-19 09:55:47 +04001882 return ret, nil
1883}
gio7fbd4ad2024-08-27 10:06:39 +04001884
gio9f6b27d2024-10-14 10:08:40 +04001885func createDevBranchAppConfig(from []byte, branch, username, publicAddr string) (string, []byte, error) {
gioc81a8472024-09-24 13:06:19 +02001886 cfg, err := installer.ParseCueAppConfig(installer.CueAppData{
1887 "app.cue": from,
1888 })
gio7fbd4ad2024-08-27 10:06:39 +04001889 if err != nil {
1890 return "", nil, err
1891 }
1892 if err := cfg.Err(); err != nil {
1893 return "", nil, err
1894 }
1895 if err := cfg.Validate(); err != nil {
1896 return "", nil, err
1897 }
1898 subdomain := cfg.LookupPath(cue.ParsePath("app.ingress.subdomain"))
1899 if err := subdomain.Err(); err != nil {
1900 return "", nil, err
1901 }
1902 subdomainStr, err := subdomain.String()
1903 network := cfg.LookupPath(cue.ParsePath("app.ingress.network"))
1904 if err := network.Err(); err != nil {
1905 return "", nil, err
1906 }
1907 networkStr, err := network.String()
1908 if err != nil {
1909 return "", nil, err
1910 }
1911 newCfg := map[string]any{}
1912 if err := cfg.Decode(&newCfg); err != nil {
1913 return "", nil, err
1914 }
1915 app, ok := newCfg["app"].(map[string]any)
1916 if !ok {
1917 return "", nil, fmt.Errorf("not a map")
1918 }
1919 app["ingress"].(map[string]any)["subdomain"] = fmt.Sprintf("%s-%s", branch, subdomainStr)
1920 app["dev"] = map[string]any{
1921 "enabled": true,
1922 "username": username,
1923 }
gio9f6b27d2024-10-14 10:08:40 +04001924 newCfg["$schema"] = fmt.Sprintf("%s/schemas/%s/app.schema.json", publicAddr, username)
gio7fbd4ad2024-08-27 10:06:39 +04001925 buf, err := json.MarshalIndent(newCfg, "", "\t")
1926 if err != nil {
1927 return "", nil, err
1928 }
1929 return networkStr, buf, nil
1930}