blob: 013c05d0424715e94dde99a9fee0df8a171927d6 [file] [log] [blame]
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +04001package installer
2
3import (
gio3af43942024-04-16 08:13:50 +04004 "bytes"
5 "encoding/json"
6 "errors"
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +04007 "fmt"
gioefa0ed42024-06-13 12:31:43 +04008 "io"
gio3af43942024-04-16 08:13:50 +04009 "io/fs"
gio3af43942024-04-16 08:13:50 +040010 "net/http"
11 "path"
Giorgi Lekveishvili6e813182023-06-30 13:45:30 +040012 "path/filepath"
giof8843412024-05-22 16:38:05 +040013 "strings"
gio69731e82024-08-01 14:15:55 +040014 "sync"
gioe72b54f2024-04-22 10:44:41 +040015
gioefa0ed42024-06-13 12:31:43 +040016 gio "github.com/giolekva/pcloud/core/installer/io"
gioe72b54f2024-04-22 10:44:41 +040017 "github.com/giolekva/pcloud/core/installer/soft"
gio778577f2024-04-29 09:44:38 +040018
giof8843412024-05-22 16:38:05 +040019 helmv2 "github.com/fluxcd/helm-controller/api/v2"
gio778577f2024-04-29 09:44:38 +040020 "sigs.k8s.io/yaml"
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +040021)
22
gio5e49bb62024-07-20 10:43:19 +040023const (
24 configFileName = "config.yaml"
25 kustomizationFileName = "kustomization.yaml"
26 gitIgnoreFileName = ".gitignore"
27 includeEverything = "!*"
28)
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +040029
gio778577f2024-04-29 09:44:38 +040030var ErrorNotFound = errors.New("not found")
31
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +040032type AppManager struct {
gio69731e82024-08-01 14:15:55 +040033 l sync.Locker
gioe72b54f2024-04-22 10:44:41 +040034 repoIO soft.RepoIO
giof8843412024-05-22 16:38:05 +040035 nsc NamespaceCreator
36 jc JobCreator
37 hf HelmFetcher
gio36b23b32024-08-25 12:20:54 +040038 vpnKeyGen VPNAuthKeyGenerator
gio308105e2024-04-19 13:12:13 +040039 appDirRoot string
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +040040}
41
giof8843412024-05-22 16:38:05 +040042func NewAppManager(
43 repoIO soft.RepoIO,
44 nsc NamespaceCreator,
45 jc JobCreator,
46 hf HelmFetcher,
gio36b23b32024-08-25 12:20:54 +040047 vpnKeyGen VPNAuthKeyGenerator,
giof8843412024-05-22 16:38:05 +040048 appDirRoot string,
49) (*AppManager, error) {
Giorgi Lekveishvilibd6be7f2023-05-26 15:51:28 +040050 return &AppManager{
gio69731e82024-08-01 14:15:55 +040051 &sync.Mutex{},
Giorgi Lekveishvili0ccd1482023-06-21 15:02:24 +040052 repoIO,
giof8843412024-05-22 16:38:05 +040053 nsc,
54 jc,
55 hf,
gio36b23b32024-08-25 12:20:54 +040056 vpnKeyGen,
gio308105e2024-04-19 13:12:13 +040057 appDirRoot,
Giorgi Lekveishvilibd6be7f2023-05-26 15:51:28 +040058 }, nil
59}
60
gioe72b54f2024-04-22 10:44:41 +040061func (m *AppManager) Config() (EnvConfig, error) {
62 var cfg EnvConfig
63 if err := soft.ReadYaml(m.repoIO, configFileName, &cfg); err != nil {
64 return EnvConfig{}, err
gio3af43942024-04-16 08:13:50 +040065 } else {
66 return cfg, nil
67 }
68}
69
gio3cdee592024-04-17 10:15:56 +040070func (m *AppManager) appConfig(path string) (AppInstanceConfig, error) {
71 var cfg AppInstanceConfig
gioe72b54f2024-04-22 10:44:41 +040072 if err := soft.ReadJson(m.repoIO, path, &cfg); err != nil {
gio3cdee592024-04-17 10:15:56 +040073 return AppInstanceConfig{}, err
gio3af43942024-04-16 08:13:50 +040074 } else {
75 return cfg, nil
76 }
Giorgi Lekveishvili7efe22f2023-05-30 13:01:53 +040077}
78
gio7fbd4ad2024-08-27 10:06:39 +040079func (m *AppManager) GetAllInstances() ([]AppInstanceConfig, error) {
gio09a3e5b2024-04-26 14:11:06 +040080 m.repoIO.Pull()
gioe72b54f2024-04-22 10:44:41 +040081 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
gio3af43942024-04-16 08:13:50 +040082 if err != nil {
83 return nil, err
84 }
gio3cdee592024-04-17 10:15:56 +040085 ret := make([]AppInstanceConfig, 0)
gio3af43942024-04-16 08:13:50 +040086 for _, app := range kust.Resources {
gio308105e2024-04-19 13:12:13 +040087 cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
88 if err != nil {
89 return nil, err
90 }
91 cfg.Id = app
92 ret = append(ret, cfg)
93 }
94 return ret, nil
95}
96
gio7fbd4ad2024-08-27 10:06:39 +040097func (m *AppManager) GetAllAppInstances(name string) ([]AppInstanceConfig, error) {
gioe72b54f2024-04-22 10:44:41 +040098 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
gio308105e2024-04-19 13:12:13 +040099 if err != nil {
giocb34ad22024-07-11 08:01:13 +0400100 if errors.Is(err, fs.ErrNotExist) {
101 return nil, nil
102 } else {
103 return nil, err
104 }
gio308105e2024-04-19 13:12:13 +0400105 }
106 ret := make([]AppInstanceConfig, 0)
107 for _, app := range kust.Resources {
108 cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
gio3af43942024-04-16 08:13:50 +0400109 if err != nil {
110 return nil, err
111 }
112 cfg.Id = app
113 if cfg.AppId == name {
114 ret = append(ret, cfg)
115 }
116 }
117 return ret, nil
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400118}
119
gio7fbd4ad2024-08-27 10:06:39 +0400120func (m *AppManager) GetInstance(id string) (*AppInstanceConfig, error) {
121 appDir := filepath.Clean(filepath.Join(m.appDirRoot, id))
122 cfgPath := filepath.Join(appDir, "config.json")
123 // kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
124 // if err != nil {
125 // return nil, err
126 // }
127 // for _, app := range kust.Resources {
128 // if app == id {
129 // cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
130 cfg, err := m.appConfig(cfgPath)
gio3af43942024-04-16 08:13:50 +0400131 if err != nil {
gio778577f2024-04-29 09:44:38 +0400132 return nil, err
gio3af43942024-04-16 08:13:50 +0400133 }
gio7fbd4ad2024-08-27 10:06:39 +0400134 cfg.Id = id
135 return &cfg, err
136 // if err != nil {
137 // return nil, err
138 // }
139 // cfg.Id = id
140 // return &cfg, nil
141 // }
142 // }
143 // return nil, ErrorNotFound
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400144}
145
giof8843412024-05-22 16:38:05 +0400146func GetCueAppData(fs soft.RepoFS, dir string) (CueAppData, error) {
147 files, err := fs.ListDir(dir)
148 if err != nil {
149 return nil, err
150 }
151 cfg := CueAppData{}
152 for _, f := range files {
153 if !f.IsDir() && strings.HasSuffix(f.Name(), ".cue") {
154 contents, err := soft.ReadFile(fs, filepath.Join(dir, f.Name()))
155 if err != nil {
156 return nil, err
157 }
158 cfg[f.Name()] = contents
159 }
Giorgi Lekveishvili03ee5852023-05-30 13:20:10 +0400160 }
gio308105e2024-04-19 13:12:13 +0400161 return cfg, nil
Giorgi Lekveishvili03ee5852023-05-30 13:20:10 +0400162}
163
giof8843412024-05-22 16:38:05 +0400164func (m *AppManager) GetInstanceApp(id string) (EnvApp, error) {
165 cfg, err := GetCueAppData(m.repoIO, filepath.Join(m.appDirRoot, id))
166 if err != nil {
167 return nil, err
168 }
169 return NewCueEnvApp(cfg)
170}
171
gio3af43942024-04-16 08:13:50 +0400172type allocatePortReq struct {
173 Protocol string `json:"protocol"`
174 SourcePort int `json:"sourcePort"`
175 TargetService string `json:"targetService"`
176 TargetPort int `json:"targetPort"`
giocdfa3722024-06-13 20:10:14 +0400177 Secret string `json:"secret,omitempty"`
178}
179
180type removePortReq struct {
181 Protocol string `json:"protocol"`
182 SourcePort int `json:"sourcePort"`
183 TargetService string `json:"targetService"`
184 TargetPort int `json:"targetPort"`
gio3af43942024-04-16 08:13:50 +0400185}
186
gioefa0ed42024-06-13 12:31:43 +0400187type reservePortResp struct {
188 Port int `json:"port"`
189 Secret string `json:"secret"`
190}
191
192func reservePorts(ports map[string]string) (map[string]reservePortResp, error) {
193 ret := map[string]reservePortResp{}
194 for p, reserveAddr := range ports {
195 resp, err := http.Post(reserveAddr, "application/json", nil) // TODO(gio): address
196 if err != nil {
197 return nil, err
198 }
199 if resp.StatusCode != http.StatusOK {
200 var e bytes.Buffer
201 io.Copy(&e, resp.Body)
202 return nil, fmt.Errorf("Could not reserve port: %s", e.String())
203 }
204 var r reservePortResp
205 if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
206 return nil, err
207 }
208 ret[p] = r
209 }
210 return ret, nil
211}
212
213func openPorts(ports []PortForward, reservations map[string]reservePortResp, allocators map[string]string) error {
gio3af43942024-04-16 08:13:50 +0400214 for _, p := range ports {
215 var buf bytes.Buffer
216 req := allocatePortReq{
217 Protocol: p.Protocol,
218 SourcePort: p.SourcePort,
219 TargetService: p.TargetService,
220 TargetPort: p.TargetPort,
221 }
gioefa0ed42024-06-13 12:31:43 +0400222 allocator := ""
223 for n, r := range reservations {
224 if p.SourcePort == r.Port {
225 allocator = allocators[n]
giobd7ab0b2024-06-17 12:55:17 +0400226 req.Secret = r.Secret
gioefa0ed42024-06-13 12:31:43 +0400227 break
228 }
229 }
230 if allocator == "" {
231 return fmt.Errorf("Could not find allocator for: %d", p.SourcePort)
232 }
giobd7ab0b2024-06-17 12:55:17 +0400233 if err := json.NewEncoder(&buf).Encode(req); err != nil {
234 return err
235 }
gioefa0ed42024-06-13 12:31:43 +0400236 resp, err := http.Post(allocator, "application/json", &buf)
gio3af43942024-04-16 08:13:50 +0400237 if err != nil {
238 return err
239 }
240 if resp.StatusCode != http.StatusOK {
giocdfa3722024-06-13 20:10:14 +0400241 var r bytes.Buffer
242 io.Copy(&r, resp.Body)
243 return fmt.Errorf("Could not allocate port %d, status code %d, message: %s", p.SourcePort, resp.StatusCode, r.String())
gio3af43942024-04-16 08:13:50 +0400244 }
245 }
246 return nil
247}
248
giocdfa3722024-06-13 20:10:14 +0400249func closePorts(ports []PortForward) error {
250 var retErr error
251 for _, p := range ports {
252 var buf bytes.Buffer
253 req := removePortReq{
254 Protocol: p.Protocol,
255 SourcePort: p.SourcePort,
256 TargetService: p.TargetService,
257 TargetPort: p.TargetPort,
258 }
259 if err := json.NewEncoder(&buf).Encode(req); err != nil {
260 retErr = err
261 continue
262 }
263 resp, err := http.Post(p.RemoveAddr, "application/json", &buf)
264 if err != nil {
265 retErr = err
266 continue
267 }
268 if resp.StatusCode != http.StatusOK {
269 retErr = fmt.Errorf("Could not deallocate port %d, status code: %d", p.SourcePort, resp.StatusCode)
270 continue
271 }
272 }
273 return retErr
274}
275
gioe72b54f2024-04-22 10:44:41 +0400276func createKustomizationChain(r soft.RepoFS, path string) error {
gio3af43942024-04-16 08:13:50 +0400277 for p := filepath.Clean(path); p != "/"; {
278 parent, child := filepath.Split(p)
279 kustPath := filepath.Join(parent, "kustomization.yaml")
gioe72b54f2024-04-22 10:44:41 +0400280 kust, err := soft.ReadKustomization(r, kustPath)
gio3af43942024-04-16 08:13:50 +0400281 if err != nil {
282 if errors.Is(err, fs.ErrNotExist) {
gioefa0ed42024-06-13 12:31:43 +0400283 k := gio.NewKustomization()
gio3af43942024-04-16 08:13:50 +0400284 kust = &k
285 } else {
286 return err
287 }
288 }
289 kust.AddResources(child)
gioe72b54f2024-04-22 10:44:41 +0400290 if err := soft.WriteYaml(r, kustPath, kust); err != nil {
gio3af43942024-04-16 08:13:50 +0400291 return err
292 }
293 p = filepath.Clean(parent)
294 }
295 return nil
296}
297
gio778577f2024-04-29 09:44:38 +0400298type Resource struct {
giob4a3a192024-08-19 09:55:47 +0400299 Name string `json:"name"`
300 Namespace string `json:"namespace"`
301 Info string `json:"info"`
302 Annotations map[string]string `json:"annotations"`
gio778577f2024-04-29 09:44:38 +0400303}
304
305type ReleaseResources struct {
gio94904702024-07-26 16:58:34 +0400306 Release Release
307 Helm []Resource
308 RenderedRaw []byte
gio778577f2024-04-29 09:44:38 +0400309}
310
gio3cdee592024-04-17 10:15:56 +0400311// TODO(gio): rename to CommitApp
gio0eaf2712024-04-14 13:08:46 +0400312func installApp(
gioe72b54f2024-04-22 10:44:41 +0400313 repo soft.RepoIO,
314 appDir string,
315 name string,
316 config any,
gioe72b54f2024-04-22 10:44:41 +0400317 resources CueAppData,
318 data CueAppData,
giof8843412024-05-22 16:38:05 +0400319 opts ...InstallOption,
gio94904702024-07-26 16:58:34 +0400320) error {
giof8843412024-05-22 16:38:05 +0400321 var o installOptions
322 for _, i := range opts {
323 i(&o)
324 }
325 dopts := []soft.DoOption{}
326 if o.Branch != "" {
giof8843412024-05-22 16:38:05 +0400327 dopts = append(dopts, soft.WithCommitToBranch(o.Branch))
328 }
gio94904702024-07-26 16:58:34 +0400329 if o.NoPull {
330 dopts = append(dopts, soft.WithNoPull())
331 }
giof8843412024-05-22 16:38:05 +0400332 if o.NoPublish {
333 dopts = append(dopts, soft.WithNoCommit())
334 }
giof71a0832024-06-27 14:45:45 +0400335 if o.Force {
336 dopts = append(dopts, soft.WithForce())
337 }
gio9d66f322024-07-06 13:45:10 +0400338 if o.NoLock {
339 dopts = append(dopts, soft.WithNoLock())
340 }
giob4a3a192024-08-19 09:55:47 +0400341 _, err := repo.Do(func(r soft.RepoFS) (string, error) {
gio308105e2024-04-19 13:12:13 +0400342 if err := r.RemoveDir(appDir); err != nil {
343 return "", err
344 }
345 resourcesDir := path.Join(appDir, "resources")
346 if err := r.CreateDir(resourcesDir); err != nil {
gio3af43942024-04-16 08:13:50 +0400347 return "", err
348 }
gio94904702024-07-26 16:58:34 +0400349 if err := func() error {
gio5e49bb62024-07-20 10:43:19 +0400350 if err := soft.WriteFile(r, path.Join(appDir, gitIgnoreFileName), includeEverything); err != nil {
gio94904702024-07-26 16:58:34 +0400351 return err
gio5e49bb62024-07-20 10:43:19 +0400352 }
gioe72b54f2024-04-22 10:44:41 +0400353 if err := soft.WriteYaml(r, path.Join(appDir, configFileName), config); err != nil {
gio94904702024-07-26 16:58:34 +0400354 return err
gio3af43942024-04-16 08:13:50 +0400355 }
gioe72b54f2024-04-22 10:44:41 +0400356 if err := soft.WriteJson(r, path.Join(appDir, "config.json"), config); err != nil {
gio94904702024-07-26 16:58:34 +0400357 return err
gio308105e2024-04-19 13:12:13 +0400358 }
gioe72b54f2024-04-22 10:44:41 +0400359 for name, contents := range data {
gio308105e2024-04-19 13:12:13 +0400360 if name == "config.json" || name == "kustomization.yaml" || name == "resources" {
gio94904702024-07-26 16:58:34 +0400361 return fmt.Errorf("%s is forbidden", name)
gio308105e2024-04-19 13:12:13 +0400362 }
363 w, err := r.Writer(path.Join(appDir, name))
gio3af43942024-04-16 08:13:50 +0400364 if err != nil {
gio94904702024-07-26 16:58:34 +0400365 return err
gio3af43942024-04-16 08:13:50 +0400366 }
gio308105e2024-04-19 13:12:13 +0400367 defer w.Close()
368 if _, err := w.Write(contents); err != nil {
gio94904702024-07-26 16:58:34 +0400369 return err
gio3af43942024-04-16 08:13:50 +0400370 }
371 }
gio94904702024-07-26 16:58:34 +0400372 return nil
373 }(); err != nil {
374 return "", err
gio308105e2024-04-19 13:12:13 +0400375 }
gio94904702024-07-26 16:58:34 +0400376 if err := func() error {
gio308105e2024-04-19 13:12:13 +0400377 if err := createKustomizationChain(r, resourcesDir); err != nil {
gio94904702024-07-26 16:58:34 +0400378 return err
gio308105e2024-04-19 13:12:13 +0400379 }
gioefa0ed42024-06-13 12:31:43 +0400380 appKust := gio.NewKustomization()
gioe72b54f2024-04-22 10:44:41 +0400381 for name, contents := range resources {
gio308105e2024-04-19 13:12:13 +0400382 appKust.AddResources(name)
383 w, err := r.Writer(path.Join(resourcesDir, name))
384 if err != nil {
gio94904702024-07-26 16:58:34 +0400385 return err
gio308105e2024-04-19 13:12:13 +0400386 }
387 defer w.Close()
388 if _, err := w.Write(contents); err != nil {
gio94904702024-07-26 16:58:34 +0400389 return err
gio308105e2024-04-19 13:12:13 +0400390 }
391 }
gioe72b54f2024-04-22 10:44:41 +0400392 if err := soft.WriteYaml(r, path.Join(resourcesDir, "kustomization.yaml"), appKust); err != nil {
gio94904702024-07-26 16:58:34 +0400393 return err
gio3af43942024-04-16 08:13:50 +0400394 }
gio94904702024-07-26 16:58:34 +0400395 return nil
396 }(); err != nil {
397 return "", err
gio3af43942024-04-16 08:13:50 +0400398 }
gioe72b54f2024-04-22 10:44:41 +0400399 return fmt.Sprintf("install: %s", name), nil
giof8843412024-05-22 16:38:05 +0400400 }, dopts...)
giob4a3a192024-08-19 09:55:47 +0400401 return err
gio3af43942024-04-16 08:13:50 +0400402}
403
gio3cdee592024-04-17 10:15:56 +0400404// TODO(gio): commit instanceId -> appDir mapping as well
giof8843412024-05-22 16:38:05 +0400405func (m *AppManager) Install(
406 app EnvApp,
407 instanceId string,
408 appDir string,
409 namespace string,
410 values map[string]any,
411 opts ...InstallOption,
412) (ReleaseResources, error) {
gio69731e82024-08-01 14:15:55 +0400413 o := &installOptions{}
414 for _, i := range opts {
415 i(o)
416 }
417 if !o.NoLock {
418 m.l.Lock()
419 defer m.l.Unlock()
420 }
gioefa0ed42024-06-13 12:31:43 +0400421 portFields := findPortFields(app.Schema())
422 fakeReservations := map[string]reservePortResp{}
423 for i, f := range portFields {
424 fakeReservations[f] = reservePortResp{Port: i}
425 }
426 if err := setPortFields(values, fakeReservations); err != nil {
427 return ReleaseResources{}, err
428 }
gio3af43942024-04-16 08:13:50 +0400429 appDir = filepath.Clean(appDir)
gio94904702024-07-26 16:58:34 +0400430 if !o.NoPull {
431 if err := m.repoIO.Pull(); err != nil {
432 return ReleaseResources{}, err
433 }
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400434 }
gio94904702024-07-26 16:58:34 +0400435 opts = append(opts, WithNoPull())
giof8843412024-05-22 16:38:05 +0400436 if err := m.nsc.Create(namespace); err != nil {
gio778577f2024-04-29 09:44:38 +0400437 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400438 }
gio0eaf2712024-04-14 13:08:46 +0400439 var env EnvConfig
440 if o.Env != nil {
441 env = *o.Env
442 } else {
443 var err error
444 env, err = m.Config()
445 if err != nil {
446 return ReleaseResources{}, err
447 }
Giorgi Lekveishvili6e813182023-06-30 13:45:30 +0400448 }
giocb34ad22024-07-11 08:01:13 +0400449 var networks []Network
450 if o.Networks != nil {
451 networks = o.Networks
452 } else {
453 var err error
454 networks, err = m.CreateNetworks(env)
455 if err != nil {
456 return ReleaseResources{}, err
457 }
458 }
giof8843412024-05-22 16:38:05 +0400459 var lg LocalChartGenerator
460 if o.LG != nil {
461 lg = o.LG
462 } else {
463 lg = GitRepositoryLocalChartGenerator{env.Id, env.Id}
464 }
gio3cdee592024-04-17 10:15:56 +0400465 release := Release{
466 AppInstanceId: instanceId,
467 Namespace: namespace,
468 RepoAddr: m.repoIO.FullAddress(),
469 AppDir: appDir,
470 }
gio36b23b32024-08-25 12:20:54 +0400471 rendered, err := app.Render(release, env, networks, values, nil, m.vpnKeyGen)
gioef01fbb2024-04-12 16:52:59 +0400472 if err != nil {
gio778577f2024-04-29 09:44:38 +0400473 return ReleaseResources{}, err
Giorgi Lekveishvili7fb28bf2023-06-24 19:51:16 +0400474 }
gioefa0ed42024-06-13 12:31:43 +0400475 reservators := map[string]string{}
476 allocators := map[string]string{}
477 for _, pf := range rendered.Ports {
478 reservators[portFields[pf.SourcePort]] = pf.ReserveAddr
479 allocators[portFields[pf.SourcePort]] = pf.Allocator
480 }
481 portReservations, err := reservePorts(reservators)
482 if err != nil {
483 return ReleaseResources{}, err
484 }
485 if err := setPortFields(values, portReservations); err != nil {
486 return ReleaseResources{}, err
487 }
gio7841f4f2024-07-26 19:53:49 +0400488 // TODO(gio): env might not have private domain
giof8843412024-05-22 16:38:05 +0400489 imageRegistry := fmt.Sprintf("zot.%s", env.PrivateDomain)
490 if o.FetchContainerImages {
491 if err := pullContainerImages(instanceId, rendered.ContainerImages, imageRegistry, namespace, m.jc); err != nil {
492 return ReleaseResources{}, err
493 }
gio0eaf2712024-04-14 13:08:46 +0400494 }
giof71a0832024-06-27 14:45:45 +0400495 charts, err := pullHelmCharts(m.hf, rendered.HelmCharts, m.repoIO, "/helm-charts")
496 if err != nil {
giof8843412024-05-22 16:38:05 +0400497 return ReleaseResources{}, err
498 }
giof71a0832024-06-27 14:45:45 +0400499 localCharts := generateLocalCharts(lg, charts)
giof8843412024-05-22 16:38:05 +0400500 if o.FetchContainerImages {
501 release.ImageRegistry = imageRegistry
502 }
gio36b23b32024-08-25 12:20:54 +0400503 rendered, err = app.Render(release, env, networks, values, localCharts, m.vpnKeyGen)
giof8843412024-05-22 16:38:05 +0400504 if err != nil {
505 return ReleaseResources{}, err
506 }
gio94904702024-07-26 16:58:34 +0400507 if err := installApp(m.repoIO, appDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
gio778577f2024-04-29 09:44:38 +0400508 return ReleaseResources{}, err
509 }
gioff2a29a2024-05-01 17:06:42 +0400510 // TODO(gio): add ingress-nginx to release resources
gioefa0ed42024-06-13 12:31:43 +0400511 if err := openPorts(rendered.Ports, portReservations, allocators); err != nil {
gioff2a29a2024-05-01 17:06:42 +0400512 return ReleaseResources{}, err
513 }
gio778577f2024-04-29 09:44:38 +0400514 return ReleaseResources{
gio94904702024-07-26 16:58:34 +0400515 Release: rendered.Config.Release,
516 RenderedRaw: rendered.Raw,
517 Helm: extractHelm(rendered.Resources),
gio778577f2024-04-29 09:44:38 +0400518 }, nil
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +0400519}
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400520
gio778577f2024-04-29 09:44:38 +0400521type helmRelease struct {
giof9f0bee2024-06-11 20:10:05 +0400522 Metadata struct {
523 Name string `json:"name"`
524 Namespace string `json:"namespace"`
525 Annotations map[string]string `json:"annotations"`
526 } `json:"metadata"`
527 Kind string `json:"kind"`
528 Status struct {
gio778577f2024-04-29 09:44:38 +0400529 Conditions []struct {
530 Type string `json:"type"`
531 Status string `json:"status"`
532 } `json:"conditions"`
533 } `json:"status,omitempty"`
534}
535
536func extractHelm(resources CueAppData) []Resource {
537 ret := make([]Resource, 0, len(resources))
538 for _, contents := range resources {
539 var h helmRelease
540 if err := yaml.Unmarshal(contents, &h); err != nil {
541 panic(err) // TODO(gio): handle
542 }
gio0eaf2712024-04-14 13:08:46 +0400543 if h.Kind == "HelmRelease" {
giof9f0bee2024-06-11 20:10:05 +0400544 res := Resource{
giob4a3a192024-08-19 09:55:47 +0400545 Name: h.Metadata.Name,
546 Namespace: h.Metadata.Namespace,
547 Info: fmt.Sprintf("%s/%s", h.Metadata.Namespace, h.Metadata.Name),
548 Annotations: nil,
giof9f0bee2024-06-11 20:10:05 +0400549 }
550 if h.Metadata.Annotations != nil {
giob4a3a192024-08-19 09:55:47 +0400551 res.Annotations = h.Metadata.Annotations
giof9f0bee2024-06-11 20:10:05 +0400552 info, ok := h.Metadata.Annotations["dodo.cloud/installer-info"]
553 if ok && len(info) != 0 {
554 res.Info = info
555 }
556 }
557 ret = append(ret, res)
gio0eaf2712024-04-14 13:08:46 +0400558 }
gio778577f2024-04-29 09:44:38 +0400559 }
560 return ret
561}
562
giof8843412024-05-22 16:38:05 +0400563// TODO(gio): take app configuration from the repo
564func (m *AppManager) Update(
565 instanceId string,
566 values map[string]any,
567 opts ...InstallOption,
568) (ReleaseResources, error) {
gio69731e82024-08-01 14:15:55 +0400569 m.l.Lock()
570 defer m.l.Unlock()
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400571 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400572 return ReleaseResources{}, err
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400573 }
gio3cdee592024-04-17 10:15:56 +0400574 env, err := m.Config()
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400575 if err != nil {
gio778577f2024-04-29 09:44:38 +0400576 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400577 }
gio308105e2024-04-19 13:12:13 +0400578 instanceDir := filepath.Join(m.appDirRoot, instanceId)
giof8843412024-05-22 16:38:05 +0400579 app, err := m.GetInstanceApp(instanceId)
580 if err != nil {
581 return ReleaseResources{}, err
582 }
gio308105e2024-04-19 13:12:13 +0400583 instanceConfigPath := filepath.Join(instanceDir, "config.json")
gio3cdee592024-04-17 10:15:56 +0400584 config, err := m.appConfig(instanceConfigPath)
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400585 if err != nil {
gio778577f2024-04-29 09:44:38 +0400586 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400587 }
giocdfa3722024-06-13 20:10:14 +0400588 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
giof8843412024-05-22 16:38:05 +0400589 if err != nil {
590 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400591 }
giocb34ad22024-07-11 08:01:13 +0400592 networks, err := m.CreateNetworks(env)
593 if err != nil {
594 return ReleaseResources{}, err
595 }
gio36b23b32024-08-25 12:20:54 +0400596 rendered, err := app.Render(config.Release, env, networks, values, renderedCfg.LocalCharts, m.vpnKeyGen)
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400597 if err != nil {
gio778577f2024-04-29 09:44:38 +0400598 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400599 }
gio94904702024-07-26 16:58:34 +0400600 if err := installApp(m.repoIO, instanceDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
601 return ReleaseResources{}, err
602 }
603 return ReleaseResources{
604 Release: rendered.Config.Release,
605 RenderedRaw: rendered.Raw,
606 Helm: extractHelm(rendered.Resources),
607 }, nil
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400608}
609
610func (m *AppManager) Remove(instanceId string) error {
gio69731e82024-08-01 14:15:55 +0400611 m.l.Lock()
612 defer m.l.Unlock()
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400613 if err := m.repoIO.Pull(); err != nil {
614 return err
615 }
giocdfa3722024-06-13 20:10:14 +0400616 var portForward []PortForward
giob4a3a192024-08-19 09:55:47 +0400617 if _, err := m.repoIO.Do(func(r soft.RepoFS) (string, error) {
giocdfa3722024-06-13 20:10:14 +0400618 instanceDir := filepath.Join(m.appDirRoot, instanceId)
619 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
620 if err != nil {
621 return "", err
622 }
623 portForward = renderedCfg.PortForward
624 r.RemoveDir(instanceDir)
gio308105e2024-04-19 13:12:13 +0400625 kustPath := filepath.Join(m.appDirRoot, "kustomization.yaml")
gioe72b54f2024-04-22 10:44:41 +0400626 kust, err := soft.ReadKustomization(r, kustPath)
gio3af43942024-04-16 08:13:50 +0400627 if err != nil {
628 return "", err
629 }
630 kust.RemoveResources(instanceId)
gioe72b54f2024-04-22 10:44:41 +0400631 soft.WriteYaml(r, kustPath, kust)
gio3af43942024-04-16 08:13:50 +0400632 return fmt.Sprintf("uninstall: %s", instanceId), nil
giocdfa3722024-06-13 20:10:14 +0400633 }); err != nil {
634 return err
635 }
636 if err := closePorts(portForward); err != nil {
giocdfa3722024-06-13 20:10:14 +0400637 return err
638 }
639 return nil
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400640}
641
giocb34ad22024-07-11 08:01:13 +0400642func (m *AppManager) CreateNetworks(env EnvConfig) ([]Network, error) {
643 ret := []Network{
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400644 {
giocdfa3722024-06-13 20:10:14 +0400645 Name: "Public",
646 IngressClass: fmt.Sprintf("%s-ingress-public", env.InfraName),
647 CertificateIssuer: fmt.Sprintf("%s-public", env.Id),
648 Domain: env.Domain,
649 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", env.InfraName),
650 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", env.InfraName),
651 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", env.InfraName),
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400652 },
gio7841f4f2024-07-26 19:53:49 +0400653 }
654 if env.PrivateDomain != "" {
655 ret = append(ret, Network{
giocdfa3722024-06-13 20:10:14 +0400656 Name: "Private",
657 IngressClass: fmt.Sprintf("%s-ingress-private", env.Id),
658 Domain: env.PrivateDomain,
659 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/allocate", env.Id),
660 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/reserve", env.Id),
661 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/remove", env.Id),
gio7841f4f2024-07-26 19:53:49 +0400662 })
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400663 }
gio7fbd4ad2024-08-27 10:06:39 +0400664 n, err := m.GetAllAppInstances("network")
giocb34ad22024-07-11 08:01:13 +0400665 if err != nil {
666 return nil, err
667 }
668 for _, a := range n {
669 ret = append(ret, Network{
670 Name: a.Input["name"].(string),
671 IngressClass: fmt.Sprintf("%s-ingress-public", env.InfraName),
672 CertificateIssuer: fmt.Sprintf("%s-public", env.Id),
673 Domain: a.Input["domain"].(string),
674 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", env.InfraName),
675 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", env.InfraName),
676 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", env.InfraName),
677 })
678 }
679 return ret, nil
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400680}
gio3cdee592024-04-17 10:15:56 +0400681
gio0eaf2712024-04-14 13:08:46 +0400682type installOptions struct {
gio94904702024-07-26 16:58:34 +0400683 NoPull bool
giof8843412024-05-22 16:38:05 +0400684 NoPublish bool
685 Env *EnvConfig
giocb34ad22024-07-11 08:01:13 +0400686 Networks []Network
giof8843412024-05-22 16:38:05 +0400687 Branch string
688 LG LocalChartGenerator
689 FetchContainerImages bool
giof71a0832024-06-27 14:45:45 +0400690 Force bool
gio9d66f322024-07-06 13:45:10 +0400691 NoLock bool
gio0eaf2712024-04-14 13:08:46 +0400692}
693
694type InstallOption func(*installOptions)
695
696func WithConfig(env *EnvConfig) InstallOption {
697 return func(o *installOptions) {
698 o.Env = env
699 }
700}
701
giocb34ad22024-07-11 08:01:13 +0400702func WithNetworks(networks []Network) InstallOption {
703 return func(o *installOptions) {
704 o.Networks = networks
705 }
706}
707
gio23bdc1b2024-07-11 16:07:47 +0400708func WithNoNetworks() InstallOption {
709 return WithNetworks([]Network{})
710}
711
gio0eaf2712024-04-14 13:08:46 +0400712func WithBranch(branch string) InstallOption {
713 return func(o *installOptions) {
714 o.Branch = branch
715 }
716}
717
giof71a0832024-06-27 14:45:45 +0400718func WithForce() InstallOption {
719 return func(o *installOptions) {
720 o.Force = true
721 }
722}
723
giof8843412024-05-22 16:38:05 +0400724func WithLocalChartGenerator(lg LocalChartGenerator) InstallOption {
725 return func(o *installOptions) {
726 o.LG = lg
727 }
728}
729
730func WithFetchContainerImages() InstallOption {
731 return func(o *installOptions) {
732 o.FetchContainerImages = true
733 }
734}
735
736func WithNoPublish() InstallOption {
737 return func(o *installOptions) {
738 o.NoPublish = true
739 }
740}
741
gio94904702024-07-26 16:58:34 +0400742func WithNoPull() InstallOption {
743 return func(o *installOptions) {
744 o.NoPull = true
745 }
746}
747
gio9d66f322024-07-06 13:45:10 +0400748func WithNoLock() InstallOption {
749 return func(o *installOptions) {
750 o.NoLock = true
751 }
752}
753
giof8843412024-05-22 16:38:05 +0400754// InfraAppmanager
755
756type InfraAppManager struct {
757 repoIO soft.RepoIO
758 nsc NamespaceCreator
759 hf HelmFetcher
760 lg LocalChartGenerator
761}
762
763func NewInfraAppManager(
764 repoIO soft.RepoIO,
765 nsc NamespaceCreator,
766 hf HelmFetcher,
767 lg LocalChartGenerator,
768) (*InfraAppManager, error) {
gio3cdee592024-04-17 10:15:56 +0400769 return &InfraAppManager{
770 repoIO,
giof8843412024-05-22 16:38:05 +0400771 nsc,
772 hf,
773 lg,
gio3cdee592024-04-17 10:15:56 +0400774 }, nil
775}
776
777func (m *InfraAppManager) Config() (InfraConfig, error) {
778 var cfg InfraConfig
gioe72b54f2024-04-22 10:44:41 +0400779 if err := soft.ReadYaml(m.repoIO, configFileName, &cfg); err != nil {
gio3cdee592024-04-17 10:15:56 +0400780 return InfraConfig{}, err
781 } else {
782 return cfg, nil
783 }
784}
785
gioe72b54f2024-04-22 10:44:41 +0400786func (m *InfraAppManager) appConfig(path string) (InfraAppInstanceConfig, error) {
787 var cfg InfraAppInstanceConfig
788 if err := soft.ReadJson(m.repoIO, path, &cfg); err != nil {
789 return InfraAppInstanceConfig{}, err
790 } else {
791 return cfg, nil
792 }
793}
794
795func (m *InfraAppManager) FindInstance(id string) (InfraAppInstanceConfig, error) {
796 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join("/infrastructure", "kustomization.yaml"))
797 if err != nil {
798 return InfraAppInstanceConfig{}, err
799 }
800 for _, app := range kust.Resources {
801 if app == id {
802 cfg, err := m.appConfig(filepath.Join("/infrastructure", app, "config.json"))
803 if err != nil {
804 return InfraAppInstanceConfig{}, err
805 }
806 cfg.Id = id
807 return cfg, nil
808 }
809 }
810 return InfraAppInstanceConfig{}, nil
811}
812
gio778577f2024-04-29 09:44:38 +0400813func (m *InfraAppManager) Install(app InfraApp, appDir string, namespace string, values map[string]any) (ReleaseResources, error) {
gio3cdee592024-04-17 10:15:56 +0400814 appDir = filepath.Clean(appDir)
815 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400816 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400817 }
giof8843412024-05-22 16:38:05 +0400818 if err := m.nsc.Create(namespace); err != nil {
gio778577f2024-04-29 09:44:38 +0400819 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400820 }
821 infra, err := m.Config()
822 if err != nil {
gio778577f2024-04-29 09:44:38 +0400823 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400824 }
825 release := Release{
826 Namespace: namespace,
827 RepoAddr: m.repoIO.FullAddress(),
828 AppDir: appDir,
829 }
gio7841f4f2024-07-26 19:53:49 +0400830 networks := m.CreateNetworks(infra)
831 rendered, err := app.Render(release, infra, networks, values, nil)
giof8843412024-05-22 16:38:05 +0400832 if err != nil {
833 return ReleaseResources{}, err
834 }
giof71a0832024-06-27 14:45:45 +0400835 charts, err := pullHelmCharts(m.hf, rendered.HelmCharts, m.repoIO, "/helm-charts")
836 if err != nil {
giof8843412024-05-22 16:38:05 +0400837 return ReleaseResources{}, err
838 }
giof71a0832024-06-27 14:45:45 +0400839 localCharts := generateLocalCharts(m.lg, charts)
gio7841f4f2024-07-26 19:53:49 +0400840 rendered, err = app.Render(release, infra, networks, values, localCharts)
gio3cdee592024-04-17 10:15:56 +0400841 if err != nil {
gio778577f2024-04-29 09:44:38 +0400842 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400843 }
gio94904702024-07-26 16:58:34 +0400844 if err := installApp(m.repoIO, appDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data); err != nil {
845 return ReleaseResources{}, err
846 }
847 return ReleaseResources{
848 Release: rendered.Config.Release,
849 RenderedRaw: rendered.Raw,
850 Helm: extractHelm(rendered.Resources),
851 }, nil
gioe72b54f2024-04-22 10:44:41 +0400852}
853
giof8843412024-05-22 16:38:05 +0400854// TODO(gio): take app configuration from the repo
855func (m *InfraAppManager) Update(
856 instanceId string,
857 values map[string]any,
858 opts ...InstallOption,
859) (ReleaseResources, error) {
gioe72b54f2024-04-22 10:44:41 +0400860 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400861 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400862 }
gio7841f4f2024-07-26 19:53:49 +0400863 infra, err := m.Config()
gioe72b54f2024-04-22 10:44:41 +0400864 if err != nil {
gio778577f2024-04-29 09:44:38 +0400865 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400866 }
867 instanceDir := filepath.Join("/infrastructure", instanceId)
giof8843412024-05-22 16:38:05 +0400868 appCfg, err := GetCueAppData(m.repoIO, instanceDir)
869 if err != nil {
870 return ReleaseResources{}, err
871 }
872 app, err := NewCueInfraApp(appCfg)
873 if err != nil {
874 return ReleaseResources{}, err
875 }
gioe72b54f2024-04-22 10:44:41 +0400876 instanceConfigPath := filepath.Join(instanceDir, "config.json")
877 config, err := m.appConfig(instanceConfigPath)
878 if err != nil {
gio778577f2024-04-29 09:44:38 +0400879 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400880 }
giocdfa3722024-06-13 20:10:14 +0400881 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
giof8843412024-05-22 16:38:05 +0400882 if err != nil {
883 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400884 }
gio7841f4f2024-07-26 19:53:49 +0400885 networks := m.CreateNetworks(infra)
886 rendered, err := app.Render(config.Release, infra, networks, values, renderedCfg.LocalCharts)
gioe72b54f2024-04-22 10:44:41 +0400887 if err != nil {
gio778577f2024-04-29 09:44:38 +0400888 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400889 }
gio94904702024-07-26 16:58:34 +0400890 if err := installApp(m.repoIO, instanceDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
891 return ReleaseResources{}, err
892 }
893 return ReleaseResources{
894 Release: rendered.Config.Release,
895 RenderedRaw: rendered.Raw,
896 Helm: extractHelm(rendered.Resources),
897 }, nil
gio3cdee592024-04-17 10:15:56 +0400898}
giof8843412024-05-22 16:38:05 +0400899
gio7841f4f2024-07-26 19:53:49 +0400900func (m *InfraAppManager) CreateNetworks(infra InfraConfig) []InfraNetwork {
901 return []InfraNetwork{
902 {
903 Name: "Public",
904 IngressClass: fmt.Sprintf("%s-ingress-public", infra.Name),
905 CertificateIssuer: fmt.Sprintf("%s-public", infra.Name),
906 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", infra.Name),
907 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", infra.Name),
908 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", infra.Name),
909 },
910 }
911}
912
giof8843412024-05-22 16:38:05 +0400913func pullHelmCharts(hf HelmFetcher, charts HelmCharts, rfs soft.RepoFS, root string) (map[string]string, error) {
914 ret := make(map[string]string)
915 for name, chart := range charts.Git {
916 chartRoot := filepath.Join(root, name)
917 ret[name] = chartRoot
918 if err := hf.Pull(chart, rfs, chartRoot); err != nil {
919 return nil, err
920 }
921 }
922 return ret, nil
923}
924
925func generateLocalCharts(g LocalChartGenerator, charts map[string]string) map[string]helmv2.HelmChartTemplateSpec {
926 ret := make(map[string]helmv2.HelmChartTemplateSpec)
927 for name, path := range charts {
928 ret[name] = g.Generate(path)
929 }
930 return ret
931}
932
933func pullContainerImages(appName string, imgs map[string]ContainerImage, registry, namespace string, jc JobCreator) error {
934 for _, img := range imgs {
935 name := fmt.Sprintf("copy-image-%s-%s-%s-%s", appName, img.Repository, img.Name, img.Tag)
936 if err := jc.Create(name, namespace, "giolekva/skopeo:latest", []string{
937 "skopeo",
938 "--insecure-policy",
939 "copy",
940 "--dest-tls-verify=false", // TODO(gio): enable
941 "--multi-arch=all",
942 fmt.Sprintf("docker://%s/%s/%s:%s", img.Registry, img.Repository, img.Name, img.Tag),
943 fmt.Sprintf("docker://%s/%s/%s:%s", registry, img.Repository, img.Name, img.Tag),
944 }); err != nil {
945 return err
946 }
947 }
948 return nil
949}
950
951type renderedInstance struct {
952 LocalCharts map[string]helmv2.HelmChartTemplateSpec `json:"localCharts"`
giocdfa3722024-06-13 20:10:14 +0400953 PortForward []PortForward `json:"portForward"`
giof8843412024-05-22 16:38:05 +0400954}
955
giocdfa3722024-06-13 20:10:14 +0400956func readRendered(fs soft.RepoFS, path string) (renderedInstance, error) {
giof8843412024-05-22 16:38:05 +0400957 r, err := fs.Reader(path)
958 if err != nil {
giocdfa3722024-06-13 20:10:14 +0400959 return renderedInstance{}, err
giof8843412024-05-22 16:38:05 +0400960 }
961 defer r.Close()
962 var cfg renderedInstance
963 if err := json.NewDecoder(r).Decode(&cfg); err != nil {
giocdfa3722024-06-13 20:10:14 +0400964 return renderedInstance{}, err
giof8843412024-05-22 16:38:05 +0400965 }
giocdfa3722024-06-13 20:10:14 +0400966 return cfg, nil
giof8843412024-05-22 16:38:05 +0400967}
gioefa0ed42024-06-13 12:31:43 +0400968
969func findPortFields(scm Schema) []string {
970 switch scm.Kind() {
971 case KindBoolean:
972 return []string{}
973 case KindInt:
974 return []string{}
975 case KindString:
976 return []string{}
977 case KindStruct:
978 ret := []string{}
979 for _, f := range scm.Fields() {
980 for _, p := range findPortFields(f.Schema) {
981 if p == "" {
982 ret = append(ret, f.Name)
983 } else {
984 ret = append(ret, fmt.Sprintf("%s.%s", f.Name, p))
985 }
986 }
987 }
988 return ret
989 case KindNetwork:
990 return []string{}
gio4ece99c2024-07-18 11:05:50 +0400991 case KindMultiNetwork:
992 return []string{}
gioefa0ed42024-06-13 12:31:43 +0400993 case KindAuth:
994 return []string{}
995 case KindSSHKey:
996 return []string{}
997 case KindNumber:
998 return []string{}
999 case KindArrayString:
1000 return []string{}
1001 case KindPort:
1002 return []string{""}
gio36b23b32024-08-25 12:20:54 +04001003 case KindVPNAuthKey:
1004 return []string{}
gioefa0ed42024-06-13 12:31:43 +04001005 default:
1006 panic("MUST NOT REACH!")
1007 }
1008}
1009
1010func setPortFields(values map[string]any, ports map[string]reservePortResp) error {
1011 for p, r := range ports {
1012 if err := setPortField(values, p, r.Port); err != nil {
1013 return err
1014 }
1015 }
1016 return nil
1017}
1018
1019func setPortField(values map[string]any, field string, port int) error {
1020 f := strings.SplitN(field, ".", 2)
1021 if len(f) == 2 {
1022 var sub map[string]any
1023 if s, ok := values[f[0]]; ok {
1024 sub, ok = s.(map[string]any)
1025 if !ok {
1026 return fmt.Errorf("expected map")
1027 }
1028 } else {
1029 sub = map[string]any{}
1030 values[f[0]] = sub
1031 }
1032 if err := setPortField(sub, f[1], port); err != nil {
1033 return err
1034 }
1035 } else {
1036 values[f[0]] = port
1037 }
1038 return nil
1039}