blob: 609ce9f7f96882bd42ba132c1e364b41cea1ba64 [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
633type ingress struct {
giof078f462024-10-14 09:07:33 +0400634 Name string
giob4a3a192024-08-19 09:55:47 +0400635 Host string
giof078f462024-10-14 09:07:33 +0400636 Home string
giob4a3a192024-08-19 09:55:47 +0400637}
638
gio7fbd4ad2024-08-27 10:06:39 +0400639type vm struct {
640 Name string
641 User string
642 CPUCores int
643 Memory string
644}
645
giob4a3a192024-08-19 09:55:47 +0400646type resourceData struct {
gio7fbd4ad2024-08-27 10:06:39 +0400647 Volume []volume
648 PostgreSQL []postgresql
649 Ingress []ingress
650 VirtualMachine []vm
giob4a3a192024-08-19 09:55:47 +0400651}
652
653type commitStatusData struct {
654 Navigation []navItem
655 AppName string
656 Commit Commit
657 Resources resourceData
658}
659
gio59946282024-10-07 12:55:51 +0400660func (s *Server) handleAppCommit(w http.ResponseWriter, r *http.Request) {
giob4a3a192024-08-19 09:55:47 +0400661 vars := mux.Vars(r)
662 appName, ok := vars["app-name"]
663 if !ok || appName == "" {
664 http.Error(w, "missing app-name", http.StatusBadRequest)
665 return
666 }
667 hash, ok := vars["hash"]
668 if !ok || appName == "" {
669 http.Error(w, "missing app-name", http.StatusBadRequest)
670 return
671 }
672 u := r.Context().Value(userCtx)
673 if u == nil {
674 http.Error(w, "unauthorized", http.StatusUnauthorized)
675 return
676 }
677 user, ok := u.(string)
678 if !ok {
679 http.Error(w, "could not get user", http.StatusInternalServerError)
680 return
681 }
682 owner, err := s.st.GetAppOwner(appName)
683 if err != nil {
684 http.Error(w, err.Error(), http.StatusInternalServerError)
685 return
686 }
687 if owner != user {
688 http.Error(w, "unauthorized", http.StatusUnauthorized)
689 return
690 }
691 commit, err := s.st.GetCommit(hash)
692 if err != nil {
693 // TODO(gio): not-found ?
694 http.Error(w, err.Error(), http.StatusInternalServerError)
695 return
696 }
697 var res strings.Builder
698 if err := json.NewEncoder(&res).Encode(commit.Resources.Helm); err != nil {
699 http.Error(w, err.Error(), http.StatusInternalServerError)
700 return
701 }
702 resData, err := extractResourceData(commit.Resources.Helm)
703 if err != nil {
704 http.Error(w, err.Error(), http.StatusInternalServerError)
705 return
706 }
707 data := commitStatusData{
708 Navigation: []navItem{
709 navItem{"Home", "/"},
710 navItem{appName, "/" + appName},
711 navItem{hash, "/" + appName + "/" + hash},
712 },
713 AppName: appName,
714 Commit: commit,
715 Resources: resData,
716 }
717 if err := s.tmplts.commitStatus.Execute(w, data); err != nil {
718 http.Error(w, err.Error(), http.StatusInternalServerError)
719 return
720 }
721}
722
gio183e8342024-08-20 06:01:24 +0400723type logData struct {
724 Navigation []navItem
725 AppName string
726 Logs template.HTML
727}
728
gio59946282024-10-07 12:55:51 +0400729func (s *Server) handleAppLogs(w http.ResponseWriter, r *http.Request) {
gio183e8342024-08-20 06:01:24 +0400730 vars := mux.Vars(r)
731 appName, ok := vars["app-name"]
732 if !ok || appName == "" {
733 http.Error(w, "missing app-name", http.StatusBadRequest)
734 return
735 }
736 u := r.Context().Value(userCtx)
737 if u == nil {
738 http.Error(w, "unauthorized", http.StatusUnauthorized)
739 return
740 }
741 user, ok := u.(string)
742 if !ok {
743 http.Error(w, "could not get user", http.StatusInternalServerError)
744 return
745 }
746 owner, err := s.st.GetAppOwner(appName)
747 if err != nil {
748 http.Error(w, err.Error(), http.StatusInternalServerError)
749 return
750 }
751 if owner != user {
752 http.Error(w, "unauthorized", http.StatusUnauthorized)
753 return
754 }
755 data := logData{
756 Navigation: []navItem{
757 navItem{"Home", "/"},
758 navItem{appName, "/" + appName},
759 navItem{"Logs", "/" + appName + "/logs"},
760 },
761 AppName: appName,
762 Logs: template.HTML(strings.ReplaceAll(s.logs[appName], "\n", "<br/>")),
763 }
764 if err := s.tmplts.logs.Execute(w, data); err != nil {
765 fmt.Println(err)
766 http.Error(w, err.Error(), http.StatusInternalServerError)
767 return
768 }
769}
770
gio81246f02024-07-10 12:02:15 +0400771type apiUpdateReq struct {
gio266c04f2024-07-03 14:18:45 +0400772 Ref string `json:"ref"`
773 Repository struct {
774 Name string `json:"name"`
775 } `json:"repository"`
gioe2e31e12024-08-18 08:20:56 +0400776 After string `json:"after"`
777 Commits []struct {
778 Id string `json:"id"`
779 Message string `json:"message"`
780 } `json:"commits"`
gio0eaf2712024-04-14 13:08:46 +0400781}
782
gio59946282024-10-07 12:55:51 +0400783func (s *Server) handleAPIUpdate(w http.ResponseWriter, r *http.Request) {
gio0eaf2712024-04-14 13:08:46 +0400784 fmt.Println("update")
gio81246f02024-07-10 12:02:15 +0400785 var req apiUpdateReq
gio0eaf2712024-04-14 13:08:46 +0400786 var contents strings.Builder
787 io.Copy(&contents, r.Body)
788 c := contents.String()
789 fmt.Println(c)
790 if err := json.NewDecoder(strings.NewReader(c)).Decode(&req); err != nil {
gio23bdc1b2024-07-11 16:07:47 +0400791 http.Error(w, err.Error(), http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400792 return
793 }
gio7fbd4ad2024-08-27 10:06:39 +0400794 if strings.HasPrefix(req.Ref, "refs/heads/dodo_") || req.Repository.Name == ConfigRepoName {
795 return
796 }
797 branch, ok := strings.CutPrefix(req.Ref, "refs/heads/")
798 if !ok {
799 http.Error(w, "invalid branch", http.StatusBadRequest)
gio0eaf2712024-04-14 13:08:46 +0400800 return
801 }
gioa60f0de2024-07-08 10:49:48 +0400802 // TODO(gio): Create commit record on app init as well
gio0eaf2712024-04-14 13:08:46 +0400803 go func() {
gio11617ac2024-07-15 16:09:04 +0400804 owner, err := s.st.GetAppOwner(req.Repository.Name)
805 if err != nil {
806 return
807 }
808 networks, err := s.getNetworks(owner)
giocb34ad22024-07-11 08:01:13 +0400809 if err != nil {
810 return
811 }
giof15b9da2024-09-19 06:59:16 +0400812 // TODO(gio): get only available ones by owner
813 clusters, err := s.getClusters()
814 if err != nil {
815 return
816 }
gio94904702024-07-26 16:58:34 +0400817 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
818 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
819 if err != nil {
820 return
821 }
gioe2e31e12024-08-18 08:20:56 +0400822 found := false
823 commitMsg := ""
824 for _, c := range req.Commits {
825 if c.Id == req.After {
826 found = true
827 commitMsg = c.Message
828 break
gioa60f0de2024-07-08 10:49:48 +0400829 }
830 }
gioe2e31e12024-08-18 08:20:56 +0400831 if !found {
832 fmt.Printf("Error: could not find commit message")
833 return
834 }
gio7fbd4ad2024-08-27 10:06:39 +0400835 s.l.Lock()
836 defer s.l.Unlock()
giof15b9da2024-09-19 06:59:16 +0400837 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 +0400838 if err = s.createCommit(req.Repository.Name, branch, req.After, commitMsg, err, resources); err != nil {
gio12e887d2024-08-18 16:09:47 +0400839 fmt.Printf("Error: %s\n", err.Error())
gioe2e31e12024-08-18 08:20:56 +0400840 return
841 }
gioa60f0de2024-07-08 10:49:48 +0400842 for addr, _ := range s.workers[req.Repository.Name] {
843 go func() {
844 // TODO(gio): make port configurable
845 http.Get(fmt.Sprintf("http://%s/update", addr))
846 }()
gio0eaf2712024-04-14 13:08:46 +0400847 }
848 }()
gio0eaf2712024-04-14 13:08:46 +0400849}
850
gio81246f02024-07-10 12:02:15 +0400851type apiRegisterWorkerReq struct {
gio0eaf2712024-04-14 13:08:46 +0400852 Address string `json:"address"`
gio183e8342024-08-20 06:01:24 +0400853 Logs string `json:"logs"`
gio0eaf2712024-04-14 13:08:46 +0400854}
855
gio59946282024-10-07 12:55:51 +0400856func (s *Server) handleAPIRegisterWorker(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400857 // TODO(gio): lock
gioa60f0de2024-07-08 10:49:48 +0400858 vars := mux.Vars(r)
859 appName, ok := vars["app-name"]
860 if !ok || appName == "" {
861 http.Error(w, "missing app-name", http.StatusBadRequest)
862 return
863 }
gio81246f02024-07-10 12:02:15 +0400864 var req apiRegisterWorkerReq
gio0eaf2712024-04-14 13:08:46 +0400865 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
866 http.Error(w, err.Error(), http.StatusInternalServerError)
867 return
868 }
gioa60f0de2024-07-08 10:49:48 +0400869 if _, ok := s.workers[appName]; !ok {
870 s.workers[appName] = map[string]struct{}{}
gio266c04f2024-07-03 14:18:45 +0400871 }
gioa60f0de2024-07-08 10:49:48 +0400872 s.workers[appName][req.Address] = struct{}{}
gio183e8342024-08-20 06:01:24 +0400873 s.logs[appName] = req.Logs
gio0eaf2712024-04-14 13:08:46 +0400874}
875
gio59946282024-10-07 12:55:51 +0400876func (s *Server) handleCreateApp(w http.ResponseWriter, r *http.Request) {
gio11617ac2024-07-15 16:09:04 +0400877 u := r.Context().Value(userCtx)
878 if u == nil {
879 http.Error(w, "unauthorized", http.StatusUnauthorized)
880 return
881 }
882 user, ok := u.(string)
883 if !ok {
884 http.Error(w, "could not get user", http.StatusInternalServerError)
885 return
886 }
887 network := r.FormValue("network")
888 if network == "" {
889 http.Error(w, "missing network", http.StatusBadRequest)
890 return
891 }
gio5e49bb62024-07-20 10:43:19 +0400892 subdomain := r.FormValue("subdomain")
893 if subdomain == "" {
894 http.Error(w, "missing subdomain", http.StatusBadRequest)
895 return
896 }
897 appType := r.FormValue("type")
898 if appType == "" {
899 http.Error(w, "missing type", http.StatusBadRequest)
900 return
901 }
gio5cc6afc2024-10-06 09:33:44 +0400902 appName := r.FormValue("name")
903 var err error
904 if appName == "" {
905 g := installer.NewFixedLengthRandomNameGenerator(3)
906 appName, err = g.Generate()
907 }
gio11617ac2024-07-15 16:09:04 +0400908 if err != nil {
909 http.Error(w, err.Error(), http.StatusInternalServerError)
910 return
911 }
912 if ok, err := s.client.UserExists(user); err != nil {
913 http.Error(w, err.Error(), http.StatusInternalServerError)
914 return
915 } else if !ok {
giocafd4e62024-07-31 10:53:40 +0400916 http.Error(w, "user sync has not finished, please try again in few minutes", http.StatusFailedDependency)
917 return
gio11617ac2024-07-15 16:09:04 +0400918 }
giocafd4e62024-07-31 10:53:40 +0400919 if err := s.st.CreateUser(user, nil, network); err != nil && !errors.Is(err, ErrorAlreadyExists) {
gio11617ac2024-07-15 16:09:04 +0400920 http.Error(w, err.Error(), http.StatusInternalServerError)
921 return
922 }
923 if err := s.st.CreateApp(appName, user); err != nil {
924 http.Error(w, err.Error(), http.StatusInternalServerError)
925 return
926 }
giod8ab4f52024-07-26 16:58:34 +0400927 if err := s.createApp(user, appName, appType, network, subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +0400928 http.Error(w, err.Error(), http.StatusInternalServerError)
929 return
930 }
931 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
932}
933
gio59946282024-10-07 12:55:51 +0400934func (s *Server) handleCreateDevBranch(w http.ResponseWriter, r *http.Request) {
gio7fbd4ad2024-08-27 10:06:39 +0400935 u := r.Context().Value(userCtx)
936 if u == nil {
937 http.Error(w, "unauthorized", http.StatusUnauthorized)
938 return
939 }
940 user, ok := u.(string)
941 if !ok {
942 http.Error(w, "could not get user", http.StatusInternalServerError)
943 return
944 }
945 vars := mux.Vars(r)
946 appName, ok := vars["app-name"]
947 if !ok || appName == "" {
948 http.Error(w, "missing app-name", http.StatusBadRequest)
949 return
950 }
951 branch := r.FormValue("branch")
952 if branch == "" {
gio5887caa2024-10-03 15:07:23 +0400953 http.Error(w, "missing branch", http.StatusBadRequest)
gio7fbd4ad2024-08-27 10:06:39 +0400954 return
955 }
956 if err := s.createDevBranch(appName, "master", branch, user); err != nil {
957 http.Error(w, err.Error(), http.StatusInternalServerError)
958 return
959 }
960 http.Redirect(w, r, fmt.Sprintf("/%s/branch/%s", appName, branch), http.StatusSeeOther)
961}
962
gio59946282024-10-07 12:55:51 +0400963func (s *Server) handleBranchDelete(w http.ResponseWriter, r *http.Request) {
gio5887caa2024-10-03 15:07:23 +0400964 u := r.Context().Value(userCtx)
965 if u == nil {
966 http.Error(w, "unauthorized", http.StatusUnauthorized)
967 return
968 }
969 vars := mux.Vars(r)
970 appName, ok := vars["app-name"]
971 if !ok || appName == "" {
972 http.Error(w, "missing app-name", http.StatusBadRequest)
973 return
974 }
975 branch, ok := vars["branch"]
976 if !ok || branch == "" {
977 http.Error(w, "missing branch", http.StatusBadRequest)
978 return
979 }
980 if err := s.deleteBranch(appName, branch); err != nil {
981 http.Error(w, err.Error(), http.StatusInternalServerError)
982 return
983 }
984 http.Redirect(w, r, fmt.Sprintf("/%s", appName), http.StatusSeeOther)
985}
986
gio59946282024-10-07 12:55:51 +0400987func (s *Server) handleAppDelete(w http.ResponseWriter, r *http.Request) {
gio5887caa2024-10-03 15:07:23 +0400988 u := r.Context().Value(userCtx)
989 if u == nil {
990 http.Error(w, "unauthorized", http.StatusUnauthorized)
991 return
992 }
993 vars := mux.Vars(r)
994 appName, ok := vars["app-name"]
995 if !ok || appName == "" {
996 http.Error(w, "missing app-name", http.StatusBadRequest)
997 return
998 }
999 if err := s.deleteApp(appName); err != nil {
1000 http.Error(w, err.Error(), http.StatusInternalServerError)
1001 return
1002 }
gioe44c1512024-10-06 14:13:55 +04001003 http.Redirect(w, r, "/", http.StatusSeeOther)
gio5887caa2024-10-03 15:07:23 +04001004}
1005
gio81246f02024-07-10 12:02:15 +04001006type apiCreateAppReq struct {
gio5e49bb62024-07-20 10:43:19 +04001007 AppType string `json:"type"`
gio33059762024-07-05 13:19:07 +04001008 AdminPublicKey string `json:"adminPublicKey"`
gio11617ac2024-07-15 16:09:04 +04001009 Network string `json:"network"`
gio5e49bb62024-07-20 10:43:19 +04001010 Subdomain string `json:"subdomain"`
gio33059762024-07-05 13:19:07 +04001011}
1012
gio81246f02024-07-10 12:02:15 +04001013type apiCreateAppResp struct {
1014 AppName string `json:"appName"`
1015 Password string `json:"password"`
gio33059762024-07-05 13:19:07 +04001016}
1017
gio59946282024-10-07 12:55:51 +04001018func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001019 w.Header().Set("Access-Control-Allow-Origin", "*")
gio81246f02024-07-10 12:02:15 +04001020 var req apiCreateAppReq
gio33059762024-07-05 13:19:07 +04001021 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1022 http.Error(w, err.Error(), http.StatusBadRequest)
1023 return
1024 }
1025 g := installer.NewFixedLengthRandomNameGenerator(3)
1026 appName, err := g.Generate()
1027 if err != nil {
1028 http.Error(w, err.Error(), http.StatusInternalServerError)
1029 return
1030 }
gio11617ac2024-07-15 16:09:04 +04001031 user, err := s.client.FindUser(req.AdminPublicKey)
gio81246f02024-07-10 12:02:15 +04001032 if err != nil {
gio33059762024-07-05 13:19:07 +04001033 http.Error(w, err.Error(), http.StatusInternalServerError)
1034 return
1035 }
gio11617ac2024-07-15 16:09:04 +04001036 if user != "" {
1037 http.Error(w, "public key already registered", http.StatusBadRequest)
1038 return
1039 }
1040 user = appName
1041 if err := s.client.AddUser(user, req.AdminPublicKey); err != nil {
1042 http.Error(w, err.Error(), http.StatusInternalServerError)
1043 return
1044 }
1045 password := generatePassword()
1046 hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
1047 if err != nil {
1048 http.Error(w, err.Error(), http.StatusInternalServerError)
1049 return
1050 }
giocafd4e62024-07-31 10:53:40 +04001051 if err := s.st.CreateUser(user, hashed, req.Network); err != nil {
gio11617ac2024-07-15 16:09:04 +04001052 http.Error(w, err.Error(), http.StatusInternalServerError)
1053 return
1054 }
1055 if err := s.st.CreateApp(appName, user); err != nil {
1056 http.Error(w, err.Error(), http.StatusInternalServerError)
1057 return
1058 }
giod8ab4f52024-07-26 16:58:34 +04001059 if err := s.createApp(user, appName, req.AppType, req.Network, req.Subdomain); err != nil {
gio11617ac2024-07-15 16:09:04 +04001060 http.Error(w, err.Error(), http.StatusInternalServerError)
1061 return
1062 }
gio81246f02024-07-10 12:02:15 +04001063 resp := apiCreateAppResp{
1064 AppName: appName,
1065 Password: password,
1066 }
gio33059762024-07-05 13:19:07 +04001067 if err := json.NewEncoder(w).Encode(resp); err != nil {
1068 http.Error(w, err.Error(), http.StatusInternalServerError)
1069 return
1070 }
1071}
1072
gio59946282024-10-07 12:55:51 +04001073func (s *Server) isNetworkUseAllowed(network string) bool {
giocafd4e62024-07-31 10:53:40 +04001074 if !s.external {
giod8ab4f52024-07-26 16:58:34 +04001075 return true
1076 }
1077 for _, cfg := range s.appConfigs {
1078 if strings.ToLower(cfg.Network) == network {
1079 return false
1080 }
1081 }
1082 return true
1083}
1084
gio59946282024-10-07 12:55:51 +04001085func (s *Server) createApp(user, appName, appType, network, subdomain string) error {
gio9d66f322024-07-06 13:45:10 +04001086 s.l.Lock()
1087 defer s.l.Unlock()
gio33059762024-07-05 13:19:07 +04001088 fmt.Printf("Creating app: %s\n", appName)
giod8ab4f52024-07-26 16:58:34 +04001089 network = strings.ToLower(network)
1090 if !s.isNetworkUseAllowed(network) {
1091 return fmt.Errorf("network already used: %s", network)
1092 }
gio33059762024-07-05 13:19:07 +04001093 if ok, err := s.client.RepoExists(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001094 return err
gio33059762024-07-05 13:19:07 +04001095 } else if ok {
gio11617ac2024-07-15 16:09:04 +04001096 return nil
gioa60f0de2024-07-08 10:49:48 +04001097 }
gio5e49bb62024-07-20 10:43:19 +04001098 networks, err := s.getNetworks(user)
1099 if err != nil {
1100 return err
1101 }
giod8ab4f52024-07-26 16:58:34 +04001102 n, ok := installer.NetworkMap(networks)[network]
gio5e49bb62024-07-20 10:43:19 +04001103 if !ok {
1104 return fmt.Errorf("network not found: %s\n", network)
1105 }
gio33059762024-07-05 13:19:07 +04001106 if err := s.client.AddRepository(appName); err != nil {
gio11617ac2024-07-15 16:09:04 +04001107 return err
gio33059762024-07-05 13:19:07 +04001108 }
1109 appRepo, err := s.client.GetRepo(appName)
1110 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001111 return err
gio33059762024-07-05 13:19:07 +04001112 }
gio9f6b27d2024-10-14 10:08:40 +04001113 files, err := s.renderAppConfigTemplate(user, appType, n, subdomain)
gio7fbd4ad2024-08-27 10:06:39 +04001114 if err != nil {
1115 return err
1116 }
1117 return s.createAppForBranch(appRepo, appName, "master", user, network, files)
1118}
1119
gio59946282024-10-07 12:55:51 +04001120func (s *Server) createDevBranch(appName, fromBranch, toBranch, user string) error {
gio7fbd4ad2024-08-27 10:06:39 +04001121 s.l.Lock()
1122 defer s.l.Unlock()
1123 fmt.Printf("Creating dev branch app: %s %s %s\n", appName, fromBranch, toBranch)
1124 appRepo, err := s.client.GetRepoBranch(appName, fromBranch)
1125 if err != nil {
1126 return err
1127 }
gioc81a8472024-09-24 13:06:19 +02001128 appCfg, err := soft.ReadFile(appRepo, "app.json")
gio7fbd4ad2024-08-27 10:06:39 +04001129 if err != nil {
1130 return err
1131 }
gio9f6b27d2024-10-14 10:08:40 +04001132 network, branchCfg, err := createDevBranchAppConfig(appCfg, toBranch, user, s.selfPublic)
gio7fbd4ad2024-08-27 10:06:39 +04001133 if err != nil {
1134 return err
1135 }
gioc81a8472024-09-24 13:06:19 +02001136 return s.createAppForBranch(appRepo, appName, toBranch, user, network, map[string][]byte{"app.json": branchCfg})
gio7fbd4ad2024-08-27 10:06:39 +04001137}
1138
gio59946282024-10-07 12:55:51 +04001139func (s *Server) deleteBranch(appName string, branch string) error {
gio5887caa2024-10-03 15:07:23 +04001140 appBranch := fmt.Sprintf("dodo_%s", branch)
1141 hf := installer.NewGitHelmFetcher()
1142 if err := func() error {
1143 repo, err := s.client.GetRepoBranch(appName, appBranch)
1144 if err != nil {
1145 return err
1146 }
1147 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
1148 if err != nil {
1149 return err
1150 }
1151 return m.Remove("app")
1152 }(); err != nil {
1153 return err
1154 }
1155 configRepo, err := s.client.GetRepo(ConfigRepoName)
1156 if err != nil {
1157 return err
1158 }
1159 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
1160 if err != nil {
1161 return err
1162 }
1163 appPath := fmt.Sprintf("%s/%s", appName, branch)
gio829b1b72024-10-05 21:50:56 +04001164 if err := m.Remove(appPath); err != nil {
gio5887caa2024-10-03 15:07:23 +04001165 return err
1166 }
1167 if err := s.client.DeleteRepoBranch(appName, appBranch); err != nil {
1168 return err
1169 }
1170 if branch != "master" {
gioe44c1512024-10-06 14:13:55 +04001171 if err := s.client.DeleteRepoBranch(appName, branch); err != nil {
1172 return err
1173 }
gio5887caa2024-10-03 15:07:23 +04001174 }
gioe44c1512024-10-06 14:13:55 +04001175 return s.st.DeleteBranch(appName, branch)
gio5887caa2024-10-03 15:07:23 +04001176}
1177
gio59946282024-10-07 12:55:51 +04001178func (s *Server) deleteApp(appName string) error {
gio5887caa2024-10-03 15:07:23 +04001179 configRepo, err := s.client.GetRepo(ConfigRepoName)
1180 if err != nil {
1181 return err
1182 }
1183 branches, err := configRepo.ListDir(fmt.Sprintf("/%s", appName))
1184 if err != nil {
1185 return err
1186 }
1187 for _, b := range branches {
1188 if !b.IsDir() || strings.HasPrefix(b.Name(), "dodo_") {
1189 continue
1190 }
1191 if err := s.deleteBranch(appName, b.Name()); err != nil {
1192 return err
1193 }
1194 }
gioe44c1512024-10-06 14:13:55 +04001195 if err := s.client.DeleteRepo(appName); err != nil {
1196 return err
1197 }
1198 return s.st.DeleteApp(appName)
gio5887caa2024-10-03 15:07:23 +04001199}
1200
gio59946282024-10-07 12:55:51 +04001201func (s *Server) createAppForBranch(
gio7fbd4ad2024-08-27 10:06:39 +04001202 repo soft.RepoIO,
1203 appName string,
1204 branch string,
1205 user string,
1206 network string,
1207 files map[string][]byte,
1208) error {
1209 commit, err := repo.Do(func(fs soft.RepoFS) (string, error) {
1210 for path, contents := range files {
1211 if err := soft.WriteFile(fs, path, string(contents)); err != nil {
1212 return "", err
1213 }
1214 }
1215 return "init", nil
1216 }, soft.WithCommitToBranch(branch))
1217 if err != nil {
1218 return err
1219 }
1220 networks, err := s.getNetworks(user)
giob4a3a192024-08-19 09:55:47 +04001221 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001222 return err
gio33059762024-07-05 13:19:07 +04001223 }
giof15b9da2024-09-19 06:59:16 +04001224 // TODO(gio): get only available ones by owner
1225 clusters, err := s.getClusters()
1226 if err != nil {
1227 return err
1228 }
gio33059762024-07-05 13:19:07 +04001229 apps := installer.NewInMemoryAppRepository(installer.CreateAllApps())
gio94904702024-07-26 16:58:34 +04001230 instanceApp, err := installer.FindEnvApp(apps, "dodo-app-instance")
1231 if err != nil {
1232 return err
1233 }
1234 instanceAppStatus, err := installer.FindEnvApp(apps, "dodo-app-instance-status")
gio33059762024-07-05 13:19:07 +04001235 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001236 return err
gio33059762024-07-05 13:19:07 +04001237 }
1238 suffixGen := installer.NewFixedLengthRandomSuffixGenerator(3)
1239 suffix, err := suffixGen.Generate()
1240 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001241 return err
gio33059762024-07-05 13:19:07 +04001242 }
gio94904702024-07-26 16:58:34 +04001243 namespace := fmt.Sprintf("%s%s%s", s.env.NamespacePrefix, instanceApp.Namespace(), suffix)
gio7fbd4ad2024-08-27 10:06:39 +04001244 s.setAppConfig(appName, branch, appConfig{namespace, network})
giof15b9da2024-09-19 06:59:16 +04001245 resources, err := s.updateDodoApp(instanceAppStatus, appName, branch, namespace, networks, clusters, user)
giob4a3a192024-08-19 09:55:47 +04001246 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001247 fmt.Printf("Error: %s\n", err.Error())
giob4a3a192024-08-19 09:55:47 +04001248 return err
1249 }
gio7fbd4ad2024-08-27 10:06:39 +04001250 if err = s.createCommit(appName, branch, commit, initCommitMsg, err, resources); err != nil {
giob4a3a192024-08-19 09:55:47 +04001251 fmt.Printf("Error: %s\n", err.Error())
gio11617ac2024-07-15 16:09:04 +04001252 return err
gio33059762024-07-05 13:19:07 +04001253 }
giod8ab4f52024-07-26 16:58:34 +04001254 configRepo, err := s.client.GetRepo(ConfigRepoName)
gio33059762024-07-05 13:19:07 +04001255 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001256 return err
gio33059762024-07-05 13:19:07 +04001257 }
1258 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001259 m, err := installer.NewAppManager(configRepo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/")
gio33059762024-07-05 13:19:07 +04001260 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001261 return err
gio33059762024-07-05 13:19:07 +04001262 }
gio7fbd4ad2024-08-27 10:06:39 +04001263 appPath := fmt.Sprintf("/%s/%s", appName, branch)
giob4a3a192024-08-19 09:55:47 +04001264 _, err = configRepo.Do(func(fs soft.RepoFS) (string, error) {
giod8ab4f52024-07-26 16:58:34 +04001265 w, err := fs.Writer(appConfigsFile)
gio9d66f322024-07-06 13:45:10 +04001266 if err != nil {
1267 return "", err
1268 }
1269 defer w.Close()
giod8ab4f52024-07-26 16:58:34 +04001270 if err := json.NewEncoder(w).Encode(s.appConfigs); err != nil {
gio9d66f322024-07-06 13:45:10 +04001271 return "", err
1272 }
1273 if _, err := m.Install(
gio94904702024-07-26 16:58:34 +04001274 instanceApp,
gio9d66f322024-07-06 13:45:10 +04001275 appName,
gio7fbd4ad2024-08-27 10:06:39 +04001276 appPath,
gio9d66f322024-07-06 13:45:10 +04001277 namespace,
1278 map[string]any{
1279 "repoAddr": s.client.GetRepoAddress(appName),
1280 "repoHost": strings.Split(s.client.Address(), ":")[0],
gio7fbd4ad2024-08-27 10:06:39 +04001281 "branch": fmt.Sprintf("dodo_%s", branch),
gio9d66f322024-07-06 13:45:10 +04001282 "gitRepoPublicKey": s.gitRepoPublicKey,
1283 },
1284 installer.WithConfig(&s.env),
gio23bdc1b2024-07-11 16:07:47 +04001285 installer.WithNoNetworks(),
gio9d66f322024-07-06 13:45:10 +04001286 installer.WithNoPublish(),
1287 installer.WithNoLock(),
1288 ); err != nil {
1289 return "", err
1290 }
1291 return fmt.Sprintf("Installed app: %s", appName), nil
giob4a3a192024-08-19 09:55:47 +04001292 })
1293 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001294 return err
gio33059762024-07-05 13:19:07 +04001295 }
gio7fbd4ad2024-08-27 10:06:39 +04001296 return s.initAppACLs(m, appPath, appName, branch, user)
1297}
1298
gio59946282024-10-07 12:55:51 +04001299func (s *Server) initAppACLs(m *installer.AppManager, path, appName, branch, user string) error {
gio7fbd4ad2024-08-27 10:06:39 +04001300 cfg, err := m.GetInstance(path)
gio33059762024-07-05 13:19:07 +04001301 if err != nil {
gio11617ac2024-07-15 16:09:04 +04001302 return err
gio33059762024-07-05 13:19:07 +04001303 }
1304 fluxKeys, ok := cfg.Input["fluxKeys"]
1305 if !ok {
gio11617ac2024-07-15 16:09:04 +04001306 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001307 }
1308 fluxPublicKey, ok := fluxKeys.(map[string]any)["public"]
1309 if !ok {
gio11617ac2024-07-15 16:09:04 +04001310 return fmt.Errorf("Fluxcd keys not found")
gio33059762024-07-05 13:19:07 +04001311 }
1312 if ok, err := s.client.UserExists("fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001313 return err
gio33059762024-07-05 13:19:07 +04001314 } else if ok {
1315 if err := s.client.AddPublicKey("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001316 return err
gio33059762024-07-05 13:19:07 +04001317 }
1318 } else {
1319 if err := s.client.AddUser("fluxcd", fluxPublicKey.(string)); err != nil {
gio11617ac2024-07-15 16:09:04 +04001320 return err
gio33059762024-07-05 13:19:07 +04001321 }
1322 }
gio7fbd4ad2024-08-27 10:06:39 +04001323 if branch != "master" {
1324 return nil
1325 }
gio33059762024-07-05 13:19:07 +04001326 if err := s.client.AddReadOnlyCollaborator(appName, "fluxcd"); err != nil {
gio11617ac2024-07-15 16:09:04 +04001327 return err
gio33059762024-07-05 13:19:07 +04001328 }
gio7fbd4ad2024-08-27 10:06:39 +04001329 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
gio11617ac2024-07-15 16:09:04 +04001330 return err
gio33059762024-07-05 13:19:07 +04001331 }
gio7fbd4ad2024-08-27 10:06:39 +04001332 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 +04001333 return err
gio33059762024-07-05 13:19:07 +04001334 }
gio2ccb6e32024-08-15 12:01:33 +04001335 if !s.external {
1336 go func() {
1337 users, err := s.client.GetAllUsers()
1338 if err != nil {
1339 fmt.Println(err)
1340 return
1341 }
1342 for _, user := range users {
1343 // TODO(gio): fluxcd should have only read access
1344 if err := s.client.AddReadWriteCollaborator(appName, user); err != nil {
1345 fmt.Println(err)
1346 }
1347 }
1348 }()
1349 }
gio43b0f422024-08-21 10:40:13 +04001350 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1351 go s.reconciler.Reconcile(ctx, s.namespace, "config")
gio11617ac2024-07-15 16:09:04 +04001352 return nil
gio33059762024-07-05 13:19:07 +04001353}
1354
gio81246f02024-07-10 12:02:15 +04001355type apiAddAdminKeyReq struct {
gio7fbd4ad2024-08-27 10:06:39 +04001356 User string `json:"user"`
1357 PublicKey string `json:"publicKey"`
gio70be3e52024-06-26 18:27:19 +04001358}
1359
gio59946282024-10-07 12:55:51 +04001360func (s *Server) handleAPIAddPublicKey(w http.ResponseWriter, r *http.Request) {
gio81246f02024-07-10 12:02:15 +04001361 var req apiAddAdminKeyReq
gio70be3e52024-06-26 18:27:19 +04001362 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
1363 http.Error(w, err.Error(), http.StatusBadRequest)
1364 return
1365 }
gio7fbd4ad2024-08-27 10:06:39 +04001366 if req.User == "" {
1367 http.Error(w, "invalid user", http.StatusBadRequest)
1368 return
1369 }
1370 if req.PublicKey == "" {
1371 http.Error(w, "invalid public key", http.StatusBadRequest)
1372 return
1373 }
1374 if err := s.client.AddPublicKey(req.User, req.PublicKey); err != nil {
gio70be3e52024-06-26 18:27:19 +04001375 http.Error(w, err.Error(), http.StatusInternalServerError)
1376 return
1377 }
1378}
1379
gio94904702024-07-26 16:58:34 +04001380type dodoAppRendered struct {
1381 App struct {
1382 Ingress struct {
1383 Network string `json:"network"`
1384 Subdomain string `json:"subdomain"`
1385 } `json:"ingress"`
1386 } `json:"app"`
1387 Input struct {
1388 AppId string `json:"appId"`
1389 } `json:"input"`
1390}
1391
gio7fbd4ad2024-08-27 10:06:39 +04001392// TODO(gio): must not require owner, now we need it to bootstrap dev vm.
gio59946282024-10-07 12:55:51 +04001393func (s *Server) updateDodoApp(
gio43b0f422024-08-21 10:40:13 +04001394 appStatus installer.EnvApp,
gio7fbd4ad2024-08-27 10:06:39 +04001395 name string,
1396 branch string,
1397 namespace string,
gio43b0f422024-08-21 10:40:13 +04001398 networks []installer.Network,
giof15b9da2024-09-19 06:59:16 +04001399 clusters []installer.Cluster,
gio7fbd4ad2024-08-27 10:06:39 +04001400 owner string,
gio43b0f422024-08-21 10:40:13 +04001401) (installer.ReleaseResources, error) {
gio7fbd4ad2024-08-27 10:06:39 +04001402 repo, err := s.client.GetRepoBranch(name, branch)
gio0eaf2712024-04-14 13:08:46 +04001403 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001404 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001405 }
giof8843412024-05-22 16:38:05 +04001406 hf := installer.NewGitHelmFetcher()
giof6ad2982024-08-23 17:42:49 +04001407 m, err := installer.NewAppManager(repo, s.nsc, s.jc, hf, s.vpnKeyGen, s.cnc, "/.dodo")
gio0eaf2712024-04-14 13:08:46 +04001408 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001409 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001410 }
gioc81a8472024-09-24 13:06:19 +02001411 appCfg, err := soft.ReadFile(repo, "app.json")
gio0eaf2712024-04-14 13:08:46 +04001412 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001413 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001414 }
1415 app, err := installer.NewDodoApp(appCfg)
1416 if err != nil {
giob4a3a192024-08-19 09:55:47 +04001417 return installer.ReleaseResources{}, err
gio0eaf2712024-04-14 13:08:46 +04001418 }
giof8843412024-05-22 16:38:05 +04001419 lg := installer.GitRepositoryLocalChartGenerator{"app", namespace}
giob4a3a192024-08-19 09:55:47 +04001420 var ret installer.ReleaseResources
1421 if _, err := repo.Do(func(r soft.RepoFS) (string, error) {
1422 ret, err = m.Install(
gio94904702024-07-26 16:58:34 +04001423 app,
1424 "app",
1425 "/.dodo/app",
1426 namespace,
1427 map[string]any{
gio7fbd4ad2024-08-27 10:06:39 +04001428 "repoAddr": repo.FullAddress(),
1429 "repoPublicAddr": s.repoPublicAddr,
1430 "managerAddr": fmt.Sprintf("http://%s", s.self),
1431 "appId": name,
1432 "branch": branch,
1433 "sshPrivateKey": s.sshKey,
1434 "username": owner,
gio94904702024-07-26 16:58:34 +04001435 },
1436 installer.WithNoPull(),
1437 installer.WithNoPublish(),
1438 installer.WithConfig(&s.env),
1439 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001440 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001441 installer.WithLocalChartGenerator(lg),
1442 installer.WithNoLock(),
1443 )
1444 if err != nil {
1445 return "", err
1446 }
1447 var rendered dodoAppRendered
giob4a3a192024-08-19 09:55:47 +04001448 if err := json.NewDecoder(bytes.NewReader(ret.RenderedRaw)).Decode(&rendered); err != nil {
gio94904702024-07-26 16:58:34 +04001449 return "", nil
1450 }
1451 if _, err := m.Install(
1452 appStatus,
1453 "status",
1454 "/.dodo/status",
1455 s.namespace,
1456 map[string]any{
1457 "appName": rendered.Input.AppId,
1458 "network": rendered.App.Ingress.Network,
1459 "appSubdomain": rendered.App.Ingress.Subdomain,
1460 },
1461 installer.WithNoPull(),
1462 installer.WithNoPublish(),
1463 installer.WithConfig(&s.env),
1464 installer.WithNetworks(networks),
giof15b9da2024-09-19 06:59:16 +04001465 installer.WithClusters(clusters),
gio94904702024-07-26 16:58:34 +04001466 installer.WithLocalChartGenerator(lg),
1467 installer.WithNoLock(),
1468 ); err != nil {
1469 return "", err
1470 }
1471 return "install app", nil
1472 },
gio7fbd4ad2024-08-27 10:06:39 +04001473 soft.WithCommitToBranch(fmt.Sprintf("dodo_%s", branch)),
gio94904702024-07-26 16:58:34 +04001474 soft.WithForce(),
giob4a3a192024-08-19 09:55:47 +04001475 ); err != nil {
1476 return installer.ReleaseResources{}, err
1477 }
gio43b0f422024-08-21 10:40:13 +04001478 ctx, _ := context.WithTimeout(context.Background(), 2*time.Minute)
1479 go s.reconciler.Reconcile(ctx, namespace, "app")
giob4a3a192024-08-19 09:55:47 +04001480 return ret, nil
gio0eaf2712024-04-14 13:08:46 +04001481}
gio33059762024-07-05 13:19:07 +04001482
gio9f6b27d2024-10-14 10:08:40 +04001483func (s *Server) renderAppConfigTemplate(user, appType string, network installer.Network, subdomain string) (map[string][]byte, error) {
giob54db242024-07-30 18:49:33 +04001484 appType = strings.Replace(appType, ":", "-", 1)
gio5e49bb62024-07-20 10:43:19 +04001485 appTmpl, err := s.appTmpls.Find(appType)
1486 if err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001487 return nil, err
gio33059762024-07-05 13:19:07 +04001488 }
gio9f6b27d2024-10-14 10:08:40 +04001489 return appTmpl.Render(fmt.Sprintf("%s/schemas/%s/app.schema.json", s.selfPublic, user), network, subdomain)
gio33059762024-07-05 13:19:07 +04001490}
gio81246f02024-07-10 12:02:15 +04001491
1492func generatePassword() string {
1493 return "foo"
1494}
giocb34ad22024-07-11 08:01:13 +04001495
gio59946282024-10-07 12:55:51 +04001496func (s *Server) getNetworks(user string) ([]installer.Network, error) {
gio23bdc1b2024-07-11 16:07:47 +04001497 addr := fmt.Sprintf("%s/api/networks", s.envAppManagerAddr)
giocb34ad22024-07-11 08:01:13 +04001498 resp, err := http.Get(addr)
1499 if err != nil {
1500 return nil, err
1501 }
gio23bdc1b2024-07-11 16:07:47 +04001502 networks := []installer.Network{}
1503 if json.NewDecoder(resp.Body).Decode(&networks); err != nil {
giocb34ad22024-07-11 08:01:13 +04001504 return nil, err
1505 }
gio11617ac2024-07-15 16:09:04 +04001506 return s.nf.Filter(user, networks)
1507}
1508
gio59946282024-10-07 12:55:51 +04001509func (s *Server) getClusters() ([]installer.Cluster, error) {
giof15b9da2024-09-19 06:59:16 +04001510 addr := fmt.Sprintf("%s/api/clusters", s.envAppManagerAddr)
1511 resp, err := http.Get(addr)
1512 if err != nil {
1513 return nil, err
1514 }
1515 clusters := []installer.Cluster{}
1516 if json.NewDecoder(resp.Body).Decode(&clusters); err != nil {
1517 return nil, err
1518 }
1519 fmt.Printf("CLUSTERS %+v\n", clusters)
1520 return clusters, nil
1521}
1522
gio8fae3af2024-07-25 13:43:31 +04001523type publicNetworkData struct {
1524 Name string `json:"name"`
1525 Domain string `json:"domain"`
1526}
1527
1528type publicData struct {
1529 Networks []publicNetworkData `json:"networks"`
1530 Types []string `json:"types"`
1531}
1532
gio59946282024-10-07 12:55:51 +04001533func (s *Server) handleAPIPublicData(w http.ResponseWriter, r *http.Request) {
giod8ab4f52024-07-26 16:58:34 +04001534 w.Header().Set("Access-Control-Allow-Origin", "*")
1535 s.l.Lock()
1536 defer s.l.Unlock()
gio8fae3af2024-07-25 13:43:31 +04001537 networks, err := s.getNetworks("")
1538 if err != nil {
1539 http.Error(w, err.Error(), http.StatusInternalServerError)
1540 return
1541 }
1542 var ret publicData
1543 for _, n := range networks {
giod8ab4f52024-07-26 16:58:34 +04001544 if s.isNetworkUseAllowed(strings.ToLower(n.Name)) {
1545 ret.Networks = append(ret.Networks, publicNetworkData{n.Name, n.Domain})
1546 }
gio8fae3af2024-07-25 13:43:31 +04001547 }
1548 for _, t := range s.appTmpls.Types() {
giob54db242024-07-30 18:49:33 +04001549 ret.Types = append(ret.Types, strings.Replace(t, "-", ":", 1))
gio8fae3af2024-07-25 13:43:31 +04001550 }
gio8fae3af2024-07-25 13:43:31 +04001551 if err := json.NewEncoder(w).Encode(ret); err != nil {
1552 http.Error(w, err.Error(), http.StatusInternalServerError)
1553 return
1554 }
1555}
1556
gio59946282024-10-07 12:55:51 +04001557func (s *Server) createCommit(name, branch, hash, message string, err error, resources installer.ReleaseResources) error {
giob4a3a192024-08-19 09:55:47 +04001558 if err != nil {
1559 fmt.Printf("Error: %s\n", err.Error())
gio7fbd4ad2024-08-27 10:06:39 +04001560 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001561 fmt.Printf("Error: %s\n", err.Error())
1562 return err
1563 }
1564 return err
1565 }
1566 var resB bytes.Buffer
1567 if err := json.NewEncoder(&resB).Encode(resources); err != nil {
gio7fbd4ad2024-08-27 10:06:39 +04001568 if err := s.st.CreateCommit(name, branch, hash, message, "FAILED", err.Error(), nil); err != nil {
giob4a3a192024-08-19 09:55:47 +04001569 fmt.Printf("Error: %s\n", err.Error())
1570 return err
1571 }
1572 return err
1573 }
gio7fbd4ad2024-08-27 10:06:39 +04001574 if err := s.st.CreateCommit(name, branch, hash, message, "OK", "", resB.Bytes()); err != nil {
giob4a3a192024-08-19 09:55:47 +04001575 fmt.Printf("Error: %s\n", err.Error())
1576 return err
1577 }
1578 return nil
1579}
1580
gio11617ac2024-07-15 16:09:04 +04001581func pickNetwork(networks []installer.Network, network string) []installer.Network {
1582 for _, n := range networks {
1583 if n.Name == network {
1584 return []installer.Network{n}
1585 }
1586 }
1587 return []installer.Network{}
1588}
1589
1590type NetworkFilter interface {
1591 Filter(user string, networks []installer.Network) ([]installer.Network, error)
1592}
1593
1594type noNetworkFilter struct{}
1595
1596func NewNoNetworkFilter() NetworkFilter {
1597 return noNetworkFilter{}
1598}
1599
gio8fae3af2024-07-25 13:43:31 +04001600func (f noNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001601 return networks, nil
1602}
1603
1604type filterByOwner struct {
1605 st Store
1606}
1607
1608func NewNetworkFilterByOwner(st Store) NetworkFilter {
1609 return &filterByOwner{st}
1610}
1611
1612func (f *filterByOwner) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio8fae3af2024-07-25 13:43:31 +04001613 if user == "" {
1614 return networks, nil
1615 }
gio11617ac2024-07-15 16:09:04 +04001616 network, err := f.st.GetUserNetwork(user)
1617 if err != nil {
1618 return nil, err
gio23bdc1b2024-07-11 16:07:47 +04001619 }
1620 ret := []installer.Network{}
1621 for _, n := range networks {
gio11617ac2024-07-15 16:09:04 +04001622 if n.Name == network {
gio23bdc1b2024-07-11 16:07:47 +04001623 ret = append(ret, n)
1624 }
1625 }
giocb34ad22024-07-11 08:01:13 +04001626 return ret, nil
1627}
gio11617ac2024-07-15 16:09:04 +04001628
1629type allowListFilter struct {
1630 allowed []string
1631}
1632
1633func NewAllowListFilter(allowed []string) NetworkFilter {
1634 return &allowListFilter{allowed}
1635}
1636
gio8fae3af2024-07-25 13:43:31 +04001637func (f *allowListFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001638 ret := []installer.Network{}
1639 for _, n := range networks {
1640 if slices.Contains(f.allowed, n.Name) {
1641 ret = append(ret, n)
1642 }
1643 }
1644 return ret, nil
1645}
1646
1647type combinedNetworkFilter struct {
1648 filters []NetworkFilter
1649}
1650
1651func NewCombinedFilter(filters ...NetworkFilter) NetworkFilter {
1652 return &combinedNetworkFilter{filters}
1653}
1654
gio8fae3af2024-07-25 13:43:31 +04001655func (f *combinedNetworkFilter) Filter(user string, networks []installer.Network) ([]installer.Network, error) {
gio11617ac2024-07-15 16:09:04 +04001656 ret := networks
1657 var err error
1658 for _, f := range f.filters {
gio8fae3af2024-07-25 13:43:31 +04001659 ret, err = f.Filter(user, ret)
gio11617ac2024-07-15 16:09:04 +04001660 if err != nil {
1661 return nil, err
1662 }
1663 }
1664 return ret, nil
1665}
giocafd4e62024-07-31 10:53:40 +04001666
1667type user struct {
1668 Username string `json:"username"`
1669 Email string `json:"email"`
1670 SSHPublicKeys []string `json:"sshPublicKeys,omitempty"`
1671}
1672
gio59946282024-10-07 12:55:51 +04001673func (s *Server) handleAPISyncUsers(_ http.ResponseWriter, _ *http.Request) {
giocafd4e62024-07-31 10:53:40 +04001674 go s.syncUsers()
1675}
1676
gio59946282024-10-07 12:55:51 +04001677func (s *Server) syncUsers() {
giocafd4e62024-07-31 10:53:40 +04001678 if s.external {
1679 panic("MUST NOT REACH!")
1680 }
1681 resp, err := http.Get(fmt.Sprintf("%s?selfAddress=%s/api/sync-users", s.fetchUsersAddr, s.self))
1682 if err != nil {
1683 return
1684 }
1685 users := []user{}
1686 if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
1687 fmt.Println(err)
1688 return
1689 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001690 validUsernames := make(map[string]user)
1691 for _, u := range users {
1692 validUsernames[u.Username] = u
1693 }
1694 allClientUsers, err := s.client.GetAllUsers()
1695 if err != nil {
1696 fmt.Println(err)
1697 return
1698 }
1699 keyToUser := make(map[string]string)
1700 for _, clientUser := range allClientUsers {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001701 if clientUser == "admin" || clientUser == "fluxcd" {
1702 continue
1703 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001704 userData, ok := validUsernames[clientUser]
1705 if !ok {
1706 if err := s.client.RemoveUser(clientUser); err != nil {
1707 fmt.Println(err)
1708 return
1709 }
1710 } else {
1711 existingKeys, err := s.client.GetUserPublicKeys(clientUser)
1712 if err != nil {
1713 fmt.Println(err)
1714 return
1715 }
1716 for _, existingKey := range existingKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001717 cleanKey := soft.CleanKey(existingKey)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001718 keyOk := slices.ContainsFunc(userData.SSHPublicKeys, func(key string) bool {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001719 return cleanKey == soft.CleanKey(key)
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001720 })
1721 if !keyOk {
1722 if err := s.client.RemovePublicKey(clientUser, existingKey); err != nil {
1723 fmt.Println(err)
1724 }
1725 } else {
1726 keyToUser[cleanKey] = clientUser
1727 }
1728 }
1729 }
1730 }
giocafd4e62024-07-31 10:53:40 +04001731 for _, u := range users {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001732 if err := s.st.CreateUser(u.Username, nil, ""); err != nil && !errors.Is(err, ErrorAlreadyExists) {
1733 fmt.Println(err)
1734 return
1735 }
giocafd4e62024-07-31 10:53:40 +04001736 if len(u.SSHPublicKeys) == 0 {
1737 continue
1738 }
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001739 ok, err := s.client.UserExists(u.Username)
1740 if err != nil {
giocafd4e62024-07-31 10:53:40 +04001741 fmt.Println(err)
1742 return
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001743 }
1744 if !ok {
1745 if err := s.client.AddUser(u.Username, u.SSHPublicKeys[0]); err != nil {
1746 fmt.Println(err)
1747 return
1748 }
1749 } else {
1750 for _, key := range u.SSHPublicKeys {
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001751 cleanKey := soft.CleanKey(key)
1752 if user, ok := keyToUser[cleanKey]; ok {
1753 if u.Username != user {
1754 panic("MUST NOT REACH! IMPOSSIBLE KEY USER RECORD")
1755 }
1756 continue
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001757 }
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001758 if err := s.client.AddPublicKey(u.Username, cleanKey); err != nil {
Davit Tabidzea5ea5092024-08-01 15:28:09 +04001759 fmt.Println(err)
1760 return
giocafd4e62024-07-31 10:53:40 +04001761 }
1762 }
1763 }
1764 }
1765 repos, err := s.client.GetAllRepos()
1766 if err != nil {
1767 return
1768 }
1769 for _, r := range repos {
1770 if r == ConfigRepoName {
1771 continue
1772 }
1773 for _, u := range users {
1774 if err := s.client.AddReadWriteCollaborator(r, u.Username); err != nil {
1775 fmt.Println(err)
Davit Tabidze4aaa27b2024-08-05 20:23:50 +04001776 continue
giocafd4e62024-07-31 10:53:40 +04001777 }
1778 }
1779 }
1780}
giob4a3a192024-08-19 09:55:47 +04001781
1782func extractResourceData(resources []installer.Resource) (resourceData, error) {
1783 var ret resourceData
1784 for _, r := range resources {
1785 t, ok := r.Annotations["dodo.cloud/resource-type"]
1786 if !ok {
1787 continue
1788 }
giof078f462024-10-14 09:07:33 +04001789 internal, ok := r.Annotations["dodo.cloud/internal"]
1790 if ok && strings.ToLower(internal) == "true" {
1791 continue
1792 }
giob4a3a192024-08-19 09:55:47 +04001793 switch t {
1794 case "volume":
1795 name, ok := r.Annotations["dodo.cloud/resource.volume.name"]
1796 if !ok {
1797 return resourceData{}, fmt.Errorf("no name")
1798 }
1799 size, ok := r.Annotations["dodo.cloud/resource.volume.size"]
1800 if !ok {
1801 return resourceData{}, fmt.Errorf("no size")
1802 }
1803 ret.Volume = append(ret.Volume, volume{name, size})
1804 case "postgresql":
1805 name, ok := r.Annotations["dodo.cloud/resource.postgresql.name"]
1806 if !ok {
1807 return resourceData{}, fmt.Errorf("no name")
1808 }
1809 version, ok := r.Annotations["dodo.cloud/resource.postgresql.version"]
1810 if !ok {
1811 return resourceData{}, fmt.Errorf("no version")
1812 }
1813 volume, ok := r.Annotations["dodo.cloud/resource.postgresql.volume"]
1814 if !ok {
1815 return resourceData{}, fmt.Errorf("no volume")
1816 }
1817 ret.PostgreSQL = append(ret.PostgreSQL, postgresql{name, version, volume})
1818 case "ingress":
giof078f462024-10-14 09:07:33 +04001819 name, ok := r.Annotations["dodo.cloud/resource.ingress.name"]
1820 if !ok {
1821 return resourceData{}, fmt.Errorf("no name")
1822 }
1823 home, ok := r.Annotations["dodo.cloud/resource.ingress.home"]
1824 if !ok {
1825 home = ""
1826 }
giob4a3a192024-08-19 09:55:47 +04001827 host, ok := r.Annotations["dodo.cloud/resource.ingress.host"]
1828 if !ok {
1829 return resourceData{}, fmt.Errorf("no host")
1830 }
giof078f462024-10-14 09:07:33 +04001831 ret.Ingress = append(ret.Ingress, ingress{name, host, home})
gio7fbd4ad2024-08-27 10:06:39 +04001832 case "virtual-machine":
1833 name, ok := r.Annotations["dodo.cloud/resource.virtual-machine.name"]
1834 if !ok {
1835 return resourceData{}, fmt.Errorf("no name")
1836 }
1837 user, ok := r.Annotations["dodo.cloud/resource.virtual-machine.user"]
1838 if !ok {
1839 return resourceData{}, fmt.Errorf("no user")
1840 }
1841 cpuCoresS, ok := r.Annotations["dodo.cloud/resource.virtual-machine.cpu-cores"]
1842 if !ok {
1843 return resourceData{}, fmt.Errorf("no cpu cores")
1844 }
1845 cpuCores, err := strconv.Atoi(cpuCoresS)
1846 if err != nil {
1847 return resourceData{}, fmt.Errorf("invalid cpu cores: %s", cpuCoresS)
1848 }
1849 memory, ok := r.Annotations["dodo.cloud/resource.virtual-machine.memory"]
1850 if !ok {
1851 return resourceData{}, fmt.Errorf("no memory")
1852 }
1853 ret.VirtualMachine = append(ret.VirtualMachine, vm{name, user, cpuCores, memory})
giob4a3a192024-08-19 09:55:47 +04001854 default:
1855 fmt.Printf("Unknown resource: %+v\n", r.Annotations)
1856 }
1857 }
giof078f462024-10-14 09:07:33 +04001858 sort.Slice(ret.Ingress, func(i, j int) bool {
1859 return strings.Compare(ret.Ingress[i].Name, ret.Ingress[j].Name) < 0
1860 })
giob4a3a192024-08-19 09:55:47 +04001861 return ret, nil
1862}
gio7fbd4ad2024-08-27 10:06:39 +04001863
gio9f6b27d2024-10-14 10:08:40 +04001864func createDevBranchAppConfig(from []byte, branch, username, publicAddr string) (string, []byte, error) {
gioc81a8472024-09-24 13:06:19 +02001865 cfg, err := installer.ParseCueAppConfig(installer.CueAppData{
1866 "app.cue": from,
1867 })
gio7fbd4ad2024-08-27 10:06:39 +04001868 if err != nil {
1869 return "", nil, err
1870 }
1871 if err := cfg.Err(); err != nil {
1872 return "", nil, err
1873 }
1874 if err := cfg.Validate(); err != nil {
1875 return "", nil, err
1876 }
1877 subdomain := cfg.LookupPath(cue.ParsePath("app.ingress.subdomain"))
1878 if err := subdomain.Err(); err != nil {
1879 return "", nil, err
1880 }
1881 subdomainStr, err := subdomain.String()
1882 network := cfg.LookupPath(cue.ParsePath("app.ingress.network"))
1883 if err := network.Err(); err != nil {
1884 return "", nil, err
1885 }
1886 networkStr, err := network.String()
1887 if err != nil {
1888 return "", nil, err
1889 }
1890 newCfg := map[string]any{}
1891 if err := cfg.Decode(&newCfg); err != nil {
1892 return "", nil, err
1893 }
1894 app, ok := newCfg["app"].(map[string]any)
1895 if !ok {
1896 return "", nil, fmt.Errorf("not a map")
1897 }
1898 app["ingress"].(map[string]any)["subdomain"] = fmt.Sprintf("%s-%s", branch, subdomainStr)
1899 app["dev"] = map[string]any{
1900 "enabled": true,
1901 "username": username,
1902 }
gio9f6b27d2024-10-14 10:08:40 +04001903 newCfg["$schema"] = fmt.Sprintf("%s/schemas/%s/app.schema.json", publicAddr, username)
gio7fbd4ad2024-08-27 10:06:39 +04001904 buf, err := json.MarshalIndent(newCfg, "", "\t")
1905 if err != nil {
1906 return "", nil, err
1907 }
1908 return networkStr, buf, nil
1909}