blob: a7c23f01849ae7ccdda0191f6c05dc01bda4b87c [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
gio308105e2024-04-19 13:12:13 +040038 appDirRoot string
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +040039}
40
giof8843412024-05-22 16:38:05 +040041func NewAppManager(
42 repoIO soft.RepoIO,
43 nsc NamespaceCreator,
44 jc JobCreator,
45 hf HelmFetcher,
46 appDirRoot string,
47) (*AppManager, error) {
Giorgi Lekveishvilibd6be7f2023-05-26 15:51:28 +040048 return &AppManager{
gio69731e82024-08-01 14:15:55 +040049 &sync.Mutex{},
Giorgi Lekveishvili0ccd1482023-06-21 15:02:24 +040050 repoIO,
giof8843412024-05-22 16:38:05 +040051 nsc,
52 jc,
53 hf,
gio308105e2024-04-19 13:12:13 +040054 appDirRoot,
Giorgi Lekveishvilibd6be7f2023-05-26 15:51:28 +040055 }, nil
56}
57
gioe72b54f2024-04-22 10:44:41 +040058func (m *AppManager) Config() (EnvConfig, error) {
59 var cfg EnvConfig
60 if err := soft.ReadYaml(m.repoIO, configFileName, &cfg); err != nil {
61 return EnvConfig{}, err
gio3af43942024-04-16 08:13:50 +040062 } else {
63 return cfg, nil
64 }
65}
66
gio3cdee592024-04-17 10:15:56 +040067func (m *AppManager) appConfig(path string) (AppInstanceConfig, error) {
68 var cfg AppInstanceConfig
gioe72b54f2024-04-22 10:44:41 +040069 if err := soft.ReadJson(m.repoIO, path, &cfg); err != nil {
gio3cdee592024-04-17 10:15:56 +040070 return AppInstanceConfig{}, err
gio3af43942024-04-16 08:13:50 +040071 } else {
72 return cfg, nil
73 }
Giorgi Lekveishvili7efe22f2023-05-30 13:01:53 +040074}
75
gio308105e2024-04-19 13:12:13 +040076func (m *AppManager) FindAllInstances() ([]AppInstanceConfig, error) {
gio09a3e5b2024-04-26 14:11:06 +040077 m.repoIO.Pull()
gioe72b54f2024-04-22 10:44:41 +040078 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
gio3af43942024-04-16 08:13:50 +040079 if err != nil {
80 return nil, err
81 }
gio3cdee592024-04-17 10:15:56 +040082 ret := make([]AppInstanceConfig, 0)
gio3af43942024-04-16 08:13:50 +040083 for _, app := range kust.Resources {
gio308105e2024-04-19 13:12:13 +040084 cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
85 if err != nil {
86 return nil, err
87 }
88 cfg.Id = app
89 ret = append(ret, cfg)
90 }
91 return ret, nil
92}
93
94func (m *AppManager) FindAllAppInstances(name string) ([]AppInstanceConfig, error) {
gioe72b54f2024-04-22 10:44:41 +040095 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
gio308105e2024-04-19 13:12:13 +040096 if err != nil {
giocb34ad22024-07-11 08:01:13 +040097 if errors.Is(err, fs.ErrNotExist) {
98 return nil, nil
99 } else {
100 return nil, err
101 }
gio308105e2024-04-19 13:12:13 +0400102 }
103 ret := make([]AppInstanceConfig, 0)
104 for _, app := range kust.Resources {
105 cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
gio3af43942024-04-16 08:13:50 +0400106 if err != nil {
107 return nil, err
108 }
109 cfg.Id = app
110 if cfg.AppId == name {
111 ret = append(ret, cfg)
112 }
113 }
114 return ret, nil
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400115}
116
gio778577f2024-04-29 09:44:38 +0400117func (m *AppManager) FindInstance(id string) (*AppInstanceConfig, error) {
gioe72b54f2024-04-22 10:44:41 +0400118 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join(m.appDirRoot, "kustomization.yaml"))
gio3af43942024-04-16 08:13:50 +0400119 if err != nil {
gio778577f2024-04-29 09:44:38 +0400120 return nil, err
gio3af43942024-04-16 08:13:50 +0400121 }
122 for _, app := range kust.Resources {
123 if app == id {
gio308105e2024-04-19 13:12:13 +0400124 cfg, err := m.appConfig(filepath.Join(m.appDirRoot, app, "config.json"))
gio3af43942024-04-16 08:13:50 +0400125 if err != nil {
gio778577f2024-04-29 09:44:38 +0400126 return nil, err
gio3af43942024-04-16 08:13:50 +0400127 }
128 cfg.Id = id
gio778577f2024-04-29 09:44:38 +0400129 return &cfg, nil
gio3af43942024-04-16 08:13:50 +0400130 }
131 }
gio778577f2024-04-29 09:44:38 +0400132 return nil, ErrorNotFound
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400133}
134
giof8843412024-05-22 16:38:05 +0400135func GetCueAppData(fs soft.RepoFS, dir string) (CueAppData, error) {
136 files, err := fs.ListDir(dir)
137 if err != nil {
138 return nil, err
139 }
140 cfg := CueAppData{}
141 for _, f := range files {
142 if !f.IsDir() && strings.HasSuffix(f.Name(), ".cue") {
143 contents, err := soft.ReadFile(fs, filepath.Join(dir, f.Name()))
144 if err != nil {
145 return nil, err
146 }
147 cfg[f.Name()] = contents
148 }
Giorgi Lekveishvili03ee5852023-05-30 13:20:10 +0400149 }
gio308105e2024-04-19 13:12:13 +0400150 return cfg, nil
Giorgi Lekveishvili03ee5852023-05-30 13:20:10 +0400151}
152
giof8843412024-05-22 16:38:05 +0400153func (m *AppManager) GetInstanceApp(id string) (EnvApp, error) {
154 cfg, err := GetCueAppData(m.repoIO, filepath.Join(m.appDirRoot, id))
155 if err != nil {
156 return nil, err
157 }
158 return NewCueEnvApp(cfg)
159}
160
gio3af43942024-04-16 08:13:50 +0400161type allocatePortReq struct {
162 Protocol string `json:"protocol"`
163 SourcePort int `json:"sourcePort"`
164 TargetService string `json:"targetService"`
165 TargetPort int `json:"targetPort"`
giocdfa3722024-06-13 20:10:14 +0400166 Secret string `json:"secret,omitempty"`
167}
168
169type removePortReq struct {
170 Protocol string `json:"protocol"`
171 SourcePort int `json:"sourcePort"`
172 TargetService string `json:"targetService"`
173 TargetPort int `json:"targetPort"`
gio3af43942024-04-16 08:13:50 +0400174}
175
gioefa0ed42024-06-13 12:31:43 +0400176type reservePortResp struct {
177 Port int `json:"port"`
178 Secret string `json:"secret"`
179}
180
181func reservePorts(ports map[string]string) (map[string]reservePortResp, error) {
182 ret := map[string]reservePortResp{}
183 for p, reserveAddr := range ports {
184 resp, err := http.Post(reserveAddr, "application/json", nil) // TODO(gio): address
185 if err != nil {
186 return nil, err
187 }
188 if resp.StatusCode != http.StatusOK {
189 var e bytes.Buffer
190 io.Copy(&e, resp.Body)
191 return nil, fmt.Errorf("Could not reserve port: %s", e.String())
192 }
193 var r reservePortResp
194 if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
195 return nil, err
196 }
197 ret[p] = r
198 }
199 return ret, nil
200}
201
202func openPorts(ports []PortForward, reservations map[string]reservePortResp, allocators map[string]string) error {
gio3af43942024-04-16 08:13:50 +0400203 for _, p := range ports {
204 var buf bytes.Buffer
205 req := allocatePortReq{
206 Protocol: p.Protocol,
207 SourcePort: p.SourcePort,
208 TargetService: p.TargetService,
209 TargetPort: p.TargetPort,
210 }
gioefa0ed42024-06-13 12:31:43 +0400211 allocator := ""
212 for n, r := range reservations {
213 if p.SourcePort == r.Port {
214 allocator = allocators[n]
giobd7ab0b2024-06-17 12:55:17 +0400215 req.Secret = r.Secret
gioefa0ed42024-06-13 12:31:43 +0400216 break
217 }
218 }
219 if allocator == "" {
220 return fmt.Errorf("Could not find allocator for: %d", p.SourcePort)
221 }
giobd7ab0b2024-06-17 12:55:17 +0400222 if err := json.NewEncoder(&buf).Encode(req); err != nil {
223 return err
224 }
gioefa0ed42024-06-13 12:31:43 +0400225 resp, err := http.Post(allocator, "application/json", &buf)
gio3af43942024-04-16 08:13:50 +0400226 if err != nil {
227 return err
228 }
229 if resp.StatusCode != http.StatusOK {
giocdfa3722024-06-13 20:10:14 +0400230 var r bytes.Buffer
231 io.Copy(&r, resp.Body)
232 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 +0400233 }
234 }
235 return nil
236}
237
giocdfa3722024-06-13 20:10:14 +0400238func closePorts(ports []PortForward) error {
239 var retErr error
240 for _, p := range ports {
241 var buf bytes.Buffer
242 req := removePortReq{
243 Protocol: p.Protocol,
244 SourcePort: p.SourcePort,
245 TargetService: p.TargetService,
246 TargetPort: p.TargetPort,
247 }
248 if err := json.NewEncoder(&buf).Encode(req); err != nil {
249 retErr = err
250 continue
251 }
252 resp, err := http.Post(p.RemoveAddr, "application/json", &buf)
253 if err != nil {
254 retErr = err
255 continue
256 }
257 if resp.StatusCode != http.StatusOK {
258 retErr = fmt.Errorf("Could not deallocate port %d, status code: %d", p.SourcePort, resp.StatusCode)
259 continue
260 }
261 }
262 return retErr
263}
264
gioe72b54f2024-04-22 10:44:41 +0400265func createKustomizationChain(r soft.RepoFS, path string) error {
gio3af43942024-04-16 08:13:50 +0400266 for p := filepath.Clean(path); p != "/"; {
267 parent, child := filepath.Split(p)
268 kustPath := filepath.Join(parent, "kustomization.yaml")
gioe72b54f2024-04-22 10:44:41 +0400269 kust, err := soft.ReadKustomization(r, kustPath)
gio3af43942024-04-16 08:13:50 +0400270 if err != nil {
271 if errors.Is(err, fs.ErrNotExist) {
gioefa0ed42024-06-13 12:31:43 +0400272 k := gio.NewKustomization()
gio3af43942024-04-16 08:13:50 +0400273 kust = &k
274 } else {
275 return err
276 }
277 }
278 kust.AddResources(child)
gioe72b54f2024-04-22 10:44:41 +0400279 if err := soft.WriteYaml(r, kustPath, kust); err != nil {
gio3af43942024-04-16 08:13:50 +0400280 return err
281 }
282 p = filepath.Clean(parent)
283 }
284 return nil
285}
286
gio778577f2024-04-29 09:44:38 +0400287type Resource struct {
288 Name string `json:"name"`
289 Namespace string `json:"namespace"`
giof9f0bee2024-06-11 20:10:05 +0400290 Info string `json:"info"`
gio778577f2024-04-29 09:44:38 +0400291}
292
293type ReleaseResources struct {
gio94904702024-07-26 16:58:34 +0400294 Release Release
295 Helm []Resource
296 RenderedRaw []byte
gio778577f2024-04-29 09:44:38 +0400297}
298
gio3cdee592024-04-17 10:15:56 +0400299// TODO(gio): rename to CommitApp
gio0eaf2712024-04-14 13:08:46 +0400300func installApp(
gioe72b54f2024-04-22 10:44:41 +0400301 repo soft.RepoIO,
302 appDir string,
303 name string,
304 config any,
gioe72b54f2024-04-22 10:44:41 +0400305 resources CueAppData,
306 data CueAppData,
giof8843412024-05-22 16:38:05 +0400307 opts ...InstallOption,
gio94904702024-07-26 16:58:34 +0400308) error {
giof8843412024-05-22 16:38:05 +0400309 var o installOptions
310 for _, i := range opts {
311 i(&o)
312 }
313 dopts := []soft.DoOption{}
314 if o.Branch != "" {
giof8843412024-05-22 16:38:05 +0400315 dopts = append(dopts, soft.WithCommitToBranch(o.Branch))
316 }
gio94904702024-07-26 16:58:34 +0400317 if o.NoPull {
318 dopts = append(dopts, soft.WithNoPull())
319 }
giof8843412024-05-22 16:38:05 +0400320 if o.NoPublish {
321 dopts = append(dopts, soft.WithNoCommit())
322 }
giof71a0832024-06-27 14:45:45 +0400323 if o.Force {
324 dopts = append(dopts, soft.WithForce())
325 }
gio9d66f322024-07-06 13:45:10 +0400326 if o.NoLock {
327 dopts = append(dopts, soft.WithNoLock())
328 }
gio94904702024-07-26 16:58:34 +0400329 return repo.Do(func(r soft.RepoFS) (string, error) {
gio308105e2024-04-19 13:12:13 +0400330 if err := r.RemoveDir(appDir); err != nil {
331 return "", err
332 }
333 resourcesDir := path.Join(appDir, "resources")
334 if err := r.CreateDir(resourcesDir); err != nil {
gio3af43942024-04-16 08:13:50 +0400335 return "", err
336 }
gio94904702024-07-26 16:58:34 +0400337 if err := func() error {
gio5e49bb62024-07-20 10:43:19 +0400338 if err := soft.WriteFile(r, path.Join(appDir, gitIgnoreFileName), includeEverything); err != nil {
gio94904702024-07-26 16:58:34 +0400339 return err
gio5e49bb62024-07-20 10:43:19 +0400340 }
gioe72b54f2024-04-22 10:44:41 +0400341 if err := soft.WriteYaml(r, path.Join(appDir, configFileName), config); err != nil {
gio94904702024-07-26 16:58:34 +0400342 return err
gio3af43942024-04-16 08:13:50 +0400343 }
gioe72b54f2024-04-22 10:44:41 +0400344 if err := soft.WriteJson(r, path.Join(appDir, "config.json"), config); err != nil {
gio94904702024-07-26 16:58:34 +0400345 return err
gio308105e2024-04-19 13:12:13 +0400346 }
gioe72b54f2024-04-22 10:44:41 +0400347 for name, contents := range data {
gio308105e2024-04-19 13:12:13 +0400348 if name == "config.json" || name == "kustomization.yaml" || name == "resources" {
gio94904702024-07-26 16:58:34 +0400349 return fmt.Errorf("%s is forbidden", name)
gio308105e2024-04-19 13:12:13 +0400350 }
351 w, err := r.Writer(path.Join(appDir, name))
gio3af43942024-04-16 08:13:50 +0400352 if err != nil {
gio94904702024-07-26 16:58:34 +0400353 return err
gio3af43942024-04-16 08:13:50 +0400354 }
gio308105e2024-04-19 13:12:13 +0400355 defer w.Close()
356 if _, err := w.Write(contents); err != nil {
gio94904702024-07-26 16:58:34 +0400357 return err
gio3af43942024-04-16 08:13:50 +0400358 }
359 }
gio94904702024-07-26 16:58:34 +0400360 return nil
361 }(); err != nil {
362 return "", err
gio308105e2024-04-19 13:12:13 +0400363 }
gio94904702024-07-26 16:58:34 +0400364 if err := func() error {
gio308105e2024-04-19 13:12:13 +0400365 if err := createKustomizationChain(r, resourcesDir); err != nil {
gio94904702024-07-26 16:58:34 +0400366 return err
gio308105e2024-04-19 13:12:13 +0400367 }
gioefa0ed42024-06-13 12:31:43 +0400368 appKust := gio.NewKustomization()
gioe72b54f2024-04-22 10:44:41 +0400369 for name, contents := range resources {
gio308105e2024-04-19 13:12:13 +0400370 appKust.AddResources(name)
371 w, err := r.Writer(path.Join(resourcesDir, name))
372 if err != nil {
gio94904702024-07-26 16:58:34 +0400373 return err
gio308105e2024-04-19 13:12:13 +0400374 }
375 defer w.Close()
376 if _, err := w.Write(contents); err != nil {
gio94904702024-07-26 16:58:34 +0400377 return err
gio308105e2024-04-19 13:12:13 +0400378 }
379 }
gioe72b54f2024-04-22 10:44:41 +0400380 if err := soft.WriteYaml(r, path.Join(resourcesDir, "kustomization.yaml"), appKust); err != nil {
gio94904702024-07-26 16:58:34 +0400381 return err
gio3af43942024-04-16 08:13:50 +0400382 }
gio94904702024-07-26 16:58:34 +0400383 return nil
384 }(); err != nil {
385 return "", err
gio3af43942024-04-16 08:13:50 +0400386 }
gioe72b54f2024-04-22 10:44:41 +0400387 return fmt.Sprintf("install: %s", name), nil
giof8843412024-05-22 16:38:05 +0400388 }, dopts...)
gio3af43942024-04-16 08:13:50 +0400389}
390
gio3cdee592024-04-17 10:15:56 +0400391// TODO(gio): commit instanceId -> appDir mapping as well
giof8843412024-05-22 16:38:05 +0400392func (m *AppManager) Install(
393 app EnvApp,
394 instanceId string,
395 appDir string,
396 namespace string,
397 values map[string]any,
398 opts ...InstallOption,
399) (ReleaseResources, error) {
gio69731e82024-08-01 14:15:55 +0400400 o := &installOptions{}
401 for _, i := range opts {
402 i(o)
403 }
404 if !o.NoLock {
405 m.l.Lock()
406 defer m.l.Unlock()
407 }
gioefa0ed42024-06-13 12:31:43 +0400408 portFields := findPortFields(app.Schema())
409 fakeReservations := map[string]reservePortResp{}
410 for i, f := range portFields {
411 fakeReservations[f] = reservePortResp{Port: i}
412 }
413 if err := setPortFields(values, fakeReservations); err != nil {
414 return ReleaseResources{}, err
415 }
gio3af43942024-04-16 08:13:50 +0400416 appDir = filepath.Clean(appDir)
gio94904702024-07-26 16:58:34 +0400417 if !o.NoPull {
418 if err := m.repoIO.Pull(); err != nil {
419 return ReleaseResources{}, err
420 }
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400421 }
gio94904702024-07-26 16:58:34 +0400422 opts = append(opts, WithNoPull())
giof8843412024-05-22 16:38:05 +0400423 if err := m.nsc.Create(namespace); err != nil {
gio778577f2024-04-29 09:44:38 +0400424 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400425 }
gio0eaf2712024-04-14 13:08:46 +0400426 var env EnvConfig
427 if o.Env != nil {
428 env = *o.Env
429 } else {
430 var err error
431 env, err = m.Config()
432 if err != nil {
433 return ReleaseResources{}, err
434 }
Giorgi Lekveishvili6e813182023-06-30 13:45:30 +0400435 }
giocb34ad22024-07-11 08:01:13 +0400436 var networks []Network
437 if o.Networks != nil {
438 networks = o.Networks
439 } else {
440 var err error
441 networks, err = m.CreateNetworks(env)
442 if err != nil {
443 return ReleaseResources{}, err
444 }
445 }
giof8843412024-05-22 16:38:05 +0400446 var lg LocalChartGenerator
447 if o.LG != nil {
448 lg = o.LG
449 } else {
450 lg = GitRepositoryLocalChartGenerator{env.Id, env.Id}
451 }
gio3cdee592024-04-17 10:15:56 +0400452 release := Release{
453 AppInstanceId: instanceId,
454 Namespace: namespace,
455 RepoAddr: m.repoIO.FullAddress(),
456 AppDir: appDir,
457 }
giocb34ad22024-07-11 08:01:13 +0400458 rendered, err := app.Render(release, env, networks, values, nil)
gioef01fbb2024-04-12 16:52:59 +0400459 if err != nil {
gio778577f2024-04-29 09:44:38 +0400460 return ReleaseResources{}, err
Giorgi Lekveishvili7fb28bf2023-06-24 19:51:16 +0400461 }
gioefa0ed42024-06-13 12:31:43 +0400462 reservators := map[string]string{}
463 allocators := map[string]string{}
464 for _, pf := range rendered.Ports {
465 reservators[portFields[pf.SourcePort]] = pf.ReserveAddr
466 allocators[portFields[pf.SourcePort]] = pf.Allocator
467 }
468 portReservations, err := reservePorts(reservators)
469 if err != nil {
470 return ReleaseResources{}, err
471 }
472 if err := setPortFields(values, portReservations); err != nil {
473 return ReleaseResources{}, err
474 }
gio7841f4f2024-07-26 19:53:49 +0400475 // TODO(gio): env might not have private domain
giof8843412024-05-22 16:38:05 +0400476 imageRegistry := fmt.Sprintf("zot.%s", env.PrivateDomain)
477 if o.FetchContainerImages {
478 if err := pullContainerImages(instanceId, rendered.ContainerImages, imageRegistry, namespace, m.jc); err != nil {
479 return ReleaseResources{}, err
480 }
gio0eaf2712024-04-14 13:08:46 +0400481 }
giof71a0832024-06-27 14:45:45 +0400482 charts, err := pullHelmCharts(m.hf, rendered.HelmCharts, m.repoIO, "/helm-charts")
483 if err != nil {
giof8843412024-05-22 16:38:05 +0400484 return ReleaseResources{}, err
485 }
giof71a0832024-06-27 14:45:45 +0400486 localCharts := generateLocalCharts(lg, charts)
giof8843412024-05-22 16:38:05 +0400487 if o.FetchContainerImages {
488 release.ImageRegistry = imageRegistry
489 }
giocb34ad22024-07-11 08:01:13 +0400490 rendered, err = app.Render(release, env, networks, values, localCharts)
giof8843412024-05-22 16:38:05 +0400491 if err != nil {
492 return ReleaseResources{}, err
493 }
gio94904702024-07-26 16:58:34 +0400494 if err := installApp(m.repoIO, appDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
gio778577f2024-04-29 09:44:38 +0400495 return ReleaseResources{}, err
496 }
gioff2a29a2024-05-01 17:06:42 +0400497 // TODO(gio): add ingress-nginx to release resources
gioefa0ed42024-06-13 12:31:43 +0400498 if err := openPorts(rendered.Ports, portReservations, allocators); err != nil {
gioff2a29a2024-05-01 17:06:42 +0400499 return ReleaseResources{}, err
500 }
gio778577f2024-04-29 09:44:38 +0400501 return ReleaseResources{
gio94904702024-07-26 16:58:34 +0400502 Release: rendered.Config.Release,
503 RenderedRaw: rendered.Raw,
504 Helm: extractHelm(rendered.Resources),
gio778577f2024-04-29 09:44:38 +0400505 }, nil
Giorgi Lekveishvili23ef7f82023-05-26 11:57:48 +0400506}
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400507
gio778577f2024-04-29 09:44:38 +0400508type helmRelease struct {
giof9f0bee2024-06-11 20:10:05 +0400509 Metadata struct {
510 Name string `json:"name"`
511 Namespace string `json:"namespace"`
512 Annotations map[string]string `json:"annotations"`
513 } `json:"metadata"`
514 Kind string `json:"kind"`
515 Status struct {
gio778577f2024-04-29 09:44:38 +0400516 Conditions []struct {
517 Type string `json:"type"`
518 Status string `json:"status"`
519 } `json:"conditions"`
520 } `json:"status,omitempty"`
521}
522
523func extractHelm(resources CueAppData) []Resource {
524 ret := make([]Resource, 0, len(resources))
525 for _, contents := range resources {
526 var h helmRelease
527 if err := yaml.Unmarshal(contents, &h); err != nil {
528 panic(err) // TODO(gio): handle
529 }
gio0eaf2712024-04-14 13:08:46 +0400530 if h.Kind == "HelmRelease" {
giof9f0bee2024-06-11 20:10:05 +0400531 res := Resource{
532 Name: h.Metadata.Name,
533 Namespace: h.Metadata.Namespace,
534 Info: fmt.Sprintf("%s/%s", h.Metadata.Namespace, h.Metadata.Name),
535 }
536 if h.Metadata.Annotations != nil {
537 info, ok := h.Metadata.Annotations["dodo.cloud/installer-info"]
538 if ok && len(info) != 0 {
539 res.Info = info
540 }
541 }
542 ret = append(ret, res)
gio0eaf2712024-04-14 13:08:46 +0400543 }
gio778577f2024-04-29 09:44:38 +0400544 }
545 return ret
546}
547
giof8843412024-05-22 16:38:05 +0400548// TODO(gio): take app configuration from the repo
549func (m *AppManager) Update(
550 instanceId string,
551 values map[string]any,
552 opts ...InstallOption,
553) (ReleaseResources, error) {
gio69731e82024-08-01 14:15:55 +0400554 m.l.Lock()
555 defer m.l.Unlock()
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400556 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400557 return ReleaseResources{}, err
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400558 }
gio3cdee592024-04-17 10:15:56 +0400559 env, err := m.Config()
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400560 if err != nil {
gio778577f2024-04-29 09:44:38 +0400561 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400562 }
gio308105e2024-04-19 13:12:13 +0400563 instanceDir := filepath.Join(m.appDirRoot, instanceId)
giof8843412024-05-22 16:38:05 +0400564 app, err := m.GetInstanceApp(instanceId)
565 if err != nil {
566 return ReleaseResources{}, err
567 }
gio308105e2024-04-19 13:12:13 +0400568 instanceConfigPath := filepath.Join(instanceDir, "config.json")
gio3cdee592024-04-17 10:15:56 +0400569 config, err := m.appConfig(instanceConfigPath)
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400570 if err != nil {
gio778577f2024-04-29 09:44:38 +0400571 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400572 }
giocdfa3722024-06-13 20:10:14 +0400573 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
giof8843412024-05-22 16:38:05 +0400574 if err != nil {
575 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400576 }
giocb34ad22024-07-11 08:01:13 +0400577 networks, err := m.CreateNetworks(env)
578 if err != nil {
579 return ReleaseResources{}, err
580 }
581 rendered, err := app.Render(config.Release, env, networks, values, renderedCfg.LocalCharts)
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400582 if err != nil {
gio778577f2024-04-29 09:44:38 +0400583 return ReleaseResources{}, err
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400584 }
gio94904702024-07-26 16:58:34 +0400585 if err := installApp(m.repoIO, instanceDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
586 return ReleaseResources{}, err
587 }
588 return ReleaseResources{
589 Release: rendered.Config.Release,
590 RenderedRaw: rendered.Raw,
591 Helm: extractHelm(rendered.Resources),
592 }, nil
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400593}
594
595func (m *AppManager) Remove(instanceId string) error {
gio69731e82024-08-01 14:15:55 +0400596 m.l.Lock()
597 defer m.l.Unlock()
Giorgi Lekveishvili5c1b06e2024-03-28 15:19:44 +0400598 if err := m.repoIO.Pull(); err != nil {
599 return err
600 }
giocdfa3722024-06-13 20:10:14 +0400601 var portForward []PortForward
602 if err := m.repoIO.Do(func(r soft.RepoFS) (string, error) {
603 instanceDir := filepath.Join(m.appDirRoot, instanceId)
604 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
605 if err != nil {
606 return "", err
607 }
608 portForward = renderedCfg.PortForward
609 r.RemoveDir(instanceDir)
gio308105e2024-04-19 13:12:13 +0400610 kustPath := filepath.Join(m.appDirRoot, "kustomization.yaml")
gioe72b54f2024-04-22 10:44:41 +0400611 kust, err := soft.ReadKustomization(r, kustPath)
gio3af43942024-04-16 08:13:50 +0400612 if err != nil {
613 return "", err
614 }
615 kust.RemoveResources(instanceId)
gioe72b54f2024-04-22 10:44:41 +0400616 soft.WriteYaml(r, kustPath, kust)
gio3af43942024-04-16 08:13:50 +0400617 return fmt.Sprintf("uninstall: %s", instanceId), nil
giocdfa3722024-06-13 20:10:14 +0400618 }); err != nil {
619 return err
620 }
621 if err := closePorts(portForward); err != nil {
giocdfa3722024-06-13 20:10:14 +0400622 return err
623 }
624 return nil
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400625}
626
giocb34ad22024-07-11 08:01:13 +0400627func (m *AppManager) CreateNetworks(env EnvConfig) ([]Network, error) {
628 ret := []Network{
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400629 {
giocdfa3722024-06-13 20:10:14 +0400630 Name: "Public",
631 IngressClass: fmt.Sprintf("%s-ingress-public", env.InfraName),
632 CertificateIssuer: fmt.Sprintf("%s-public", env.Id),
633 Domain: env.Domain,
634 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", env.InfraName),
635 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", env.InfraName),
636 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", env.InfraName),
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400637 },
gio7841f4f2024-07-26 19:53:49 +0400638 }
639 if env.PrivateDomain != "" {
640 ret = append(ret, Network{
giocdfa3722024-06-13 20:10:14 +0400641 Name: "Private",
642 IngressClass: fmt.Sprintf("%s-ingress-private", env.Id),
643 Domain: env.PrivateDomain,
644 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/allocate", env.Id),
645 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/reserve", env.Id),
646 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-private.svc.cluster.local/api/remove", env.Id),
gio7841f4f2024-07-26 19:53:49 +0400647 })
Giorgi Lekveishvili4257b902023-07-07 17:08:42 +0400648 }
giocb34ad22024-07-11 08:01:13 +0400649 n, err := m.FindAllAppInstances("network")
650 if err != nil {
651 return nil, err
652 }
653 for _, a := range n {
654 ret = append(ret, Network{
655 Name: a.Input["name"].(string),
656 IngressClass: fmt.Sprintf("%s-ingress-public", env.InfraName),
657 CertificateIssuer: fmt.Sprintf("%s-public", env.Id),
658 Domain: a.Input["domain"].(string),
659 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", env.InfraName),
660 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", env.InfraName),
661 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", env.InfraName),
662 })
663 }
664 return ret, nil
Giorgi Lekveishvili76951482023-06-30 23:25:09 +0400665}
gio3cdee592024-04-17 10:15:56 +0400666
gio0eaf2712024-04-14 13:08:46 +0400667type installOptions struct {
gio94904702024-07-26 16:58:34 +0400668 NoPull bool
giof8843412024-05-22 16:38:05 +0400669 NoPublish bool
670 Env *EnvConfig
giocb34ad22024-07-11 08:01:13 +0400671 Networks []Network
giof8843412024-05-22 16:38:05 +0400672 Branch string
673 LG LocalChartGenerator
674 FetchContainerImages bool
giof71a0832024-06-27 14:45:45 +0400675 Force bool
gio9d66f322024-07-06 13:45:10 +0400676 NoLock bool
gio0eaf2712024-04-14 13:08:46 +0400677}
678
679type InstallOption func(*installOptions)
680
681func WithConfig(env *EnvConfig) InstallOption {
682 return func(o *installOptions) {
683 o.Env = env
684 }
685}
686
giocb34ad22024-07-11 08:01:13 +0400687func WithNetworks(networks []Network) InstallOption {
688 return func(o *installOptions) {
689 o.Networks = networks
690 }
691}
692
gio23bdc1b2024-07-11 16:07:47 +0400693func WithNoNetworks() InstallOption {
694 return WithNetworks([]Network{})
695}
696
gio0eaf2712024-04-14 13:08:46 +0400697func WithBranch(branch string) InstallOption {
698 return func(o *installOptions) {
699 o.Branch = branch
700 }
701}
702
giof71a0832024-06-27 14:45:45 +0400703func WithForce() InstallOption {
704 return func(o *installOptions) {
705 o.Force = true
706 }
707}
708
giof8843412024-05-22 16:38:05 +0400709func WithLocalChartGenerator(lg LocalChartGenerator) InstallOption {
710 return func(o *installOptions) {
711 o.LG = lg
712 }
713}
714
715func WithFetchContainerImages() InstallOption {
716 return func(o *installOptions) {
717 o.FetchContainerImages = true
718 }
719}
720
721func WithNoPublish() InstallOption {
722 return func(o *installOptions) {
723 o.NoPublish = true
724 }
725}
726
gio94904702024-07-26 16:58:34 +0400727func WithNoPull() InstallOption {
728 return func(o *installOptions) {
729 o.NoPull = true
730 }
731}
732
gio9d66f322024-07-06 13:45:10 +0400733func WithNoLock() InstallOption {
734 return func(o *installOptions) {
735 o.NoLock = true
736 }
737}
738
giof8843412024-05-22 16:38:05 +0400739// InfraAppmanager
740
741type InfraAppManager struct {
742 repoIO soft.RepoIO
743 nsc NamespaceCreator
744 hf HelmFetcher
745 lg LocalChartGenerator
746}
747
748func NewInfraAppManager(
749 repoIO soft.RepoIO,
750 nsc NamespaceCreator,
751 hf HelmFetcher,
752 lg LocalChartGenerator,
753) (*InfraAppManager, error) {
gio3cdee592024-04-17 10:15:56 +0400754 return &InfraAppManager{
755 repoIO,
giof8843412024-05-22 16:38:05 +0400756 nsc,
757 hf,
758 lg,
gio3cdee592024-04-17 10:15:56 +0400759 }, nil
760}
761
762func (m *InfraAppManager) Config() (InfraConfig, error) {
763 var cfg InfraConfig
gioe72b54f2024-04-22 10:44:41 +0400764 if err := soft.ReadYaml(m.repoIO, configFileName, &cfg); err != nil {
gio3cdee592024-04-17 10:15:56 +0400765 return InfraConfig{}, err
766 } else {
767 return cfg, nil
768 }
769}
770
gioe72b54f2024-04-22 10:44:41 +0400771func (m *InfraAppManager) appConfig(path string) (InfraAppInstanceConfig, error) {
772 var cfg InfraAppInstanceConfig
773 if err := soft.ReadJson(m.repoIO, path, &cfg); err != nil {
774 return InfraAppInstanceConfig{}, err
775 } else {
776 return cfg, nil
777 }
778}
779
780func (m *InfraAppManager) FindInstance(id string) (InfraAppInstanceConfig, error) {
781 kust, err := soft.ReadKustomization(m.repoIO, filepath.Join("/infrastructure", "kustomization.yaml"))
782 if err != nil {
783 return InfraAppInstanceConfig{}, err
784 }
785 for _, app := range kust.Resources {
786 if app == id {
787 cfg, err := m.appConfig(filepath.Join("/infrastructure", app, "config.json"))
788 if err != nil {
789 return InfraAppInstanceConfig{}, err
790 }
791 cfg.Id = id
792 return cfg, nil
793 }
794 }
795 return InfraAppInstanceConfig{}, nil
796}
797
gio778577f2024-04-29 09:44:38 +0400798func (m *InfraAppManager) Install(app InfraApp, appDir string, namespace string, values map[string]any) (ReleaseResources, error) {
gio3cdee592024-04-17 10:15:56 +0400799 appDir = filepath.Clean(appDir)
800 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400801 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400802 }
giof8843412024-05-22 16:38:05 +0400803 if err := m.nsc.Create(namespace); err != nil {
gio778577f2024-04-29 09:44:38 +0400804 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400805 }
806 infra, err := m.Config()
807 if err != nil {
gio778577f2024-04-29 09:44:38 +0400808 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400809 }
810 release := Release{
811 Namespace: namespace,
812 RepoAddr: m.repoIO.FullAddress(),
813 AppDir: appDir,
814 }
gio7841f4f2024-07-26 19:53:49 +0400815 networks := m.CreateNetworks(infra)
816 rendered, err := app.Render(release, infra, networks, values, nil)
giof8843412024-05-22 16:38:05 +0400817 if err != nil {
818 return ReleaseResources{}, err
819 }
giof71a0832024-06-27 14:45:45 +0400820 charts, err := pullHelmCharts(m.hf, rendered.HelmCharts, m.repoIO, "/helm-charts")
821 if err != nil {
giof8843412024-05-22 16:38:05 +0400822 return ReleaseResources{}, err
823 }
giof71a0832024-06-27 14:45:45 +0400824 localCharts := generateLocalCharts(m.lg, charts)
gio7841f4f2024-07-26 19:53:49 +0400825 rendered, err = app.Render(release, infra, networks, values, localCharts)
gio3cdee592024-04-17 10:15:56 +0400826 if err != nil {
gio778577f2024-04-29 09:44:38 +0400827 return ReleaseResources{}, err
gio3cdee592024-04-17 10:15:56 +0400828 }
gio94904702024-07-26 16:58:34 +0400829 if err := installApp(m.repoIO, appDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data); err != nil {
830 return ReleaseResources{}, err
831 }
832 return ReleaseResources{
833 Release: rendered.Config.Release,
834 RenderedRaw: rendered.Raw,
835 Helm: extractHelm(rendered.Resources),
836 }, nil
gioe72b54f2024-04-22 10:44:41 +0400837}
838
giof8843412024-05-22 16:38:05 +0400839// TODO(gio): take app configuration from the repo
840func (m *InfraAppManager) Update(
841 instanceId string,
842 values map[string]any,
843 opts ...InstallOption,
844) (ReleaseResources, error) {
gioe72b54f2024-04-22 10:44:41 +0400845 if err := m.repoIO.Pull(); err != nil {
gio778577f2024-04-29 09:44:38 +0400846 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400847 }
gio7841f4f2024-07-26 19:53:49 +0400848 infra, err := m.Config()
gioe72b54f2024-04-22 10:44:41 +0400849 if err != nil {
gio778577f2024-04-29 09:44:38 +0400850 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400851 }
852 instanceDir := filepath.Join("/infrastructure", instanceId)
giof8843412024-05-22 16:38:05 +0400853 appCfg, err := GetCueAppData(m.repoIO, instanceDir)
854 if err != nil {
855 return ReleaseResources{}, err
856 }
857 app, err := NewCueInfraApp(appCfg)
858 if err != nil {
859 return ReleaseResources{}, err
860 }
gioe72b54f2024-04-22 10:44:41 +0400861 instanceConfigPath := filepath.Join(instanceDir, "config.json")
862 config, err := m.appConfig(instanceConfigPath)
863 if err != nil {
gio778577f2024-04-29 09:44:38 +0400864 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400865 }
giocdfa3722024-06-13 20:10:14 +0400866 renderedCfg, err := readRendered(m.repoIO, filepath.Join(instanceDir, "rendered.json"))
giof8843412024-05-22 16:38:05 +0400867 if err != nil {
868 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400869 }
gio7841f4f2024-07-26 19:53:49 +0400870 networks := m.CreateNetworks(infra)
871 rendered, err := app.Render(config.Release, infra, networks, values, renderedCfg.LocalCharts)
gioe72b54f2024-04-22 10:44:41 +0400872 if err != nil {
gio778577f2024-04-29 09:44:38 +0400873 return ReleaseResources{}, err
gioe72b54f2024-04-22 10:44:41 +0400874 }
gio94904702024-07-26 16:58:34 +0400875 if err := installApp(m.repoIO, instanceDir, rendered.Name, rendered.Config, rendered.Resources, rendered.Data, opts...); err != nil {
876 return ReleaseResources{}, err
877 }
878 return ReleaseResources{
879 Release: rendered.Config.Release,
880 RenderedRaw: rendered.Raw,
881 Helm: extractHelm(rendered.Resources),
882 }, nil
gio3cdee592024-04-17 10:15:56 +0400883}
giof8843412024-05-22 16:38:05 +0400884
gio7841f4f2024-07-26 19:53:49 +0400885func (m *InfraAppManager) CreateNetworks(infra InfraConfig) []InfraNetwork {
886 return []InfraNetwork{
887 {
888 Name: "Public",
889 IngressClass: fmt.Sprintf("%s-ingress-public", infra.Name),
890 CertificateIssuer: fmt.Sprintf("%s-public", infra.Name),
891 AllocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/allocate", infra.Name),
892 ReservePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/reserve", infra.Name),
893 DeallocatePortAddr: fmt.Sprintf("http://port-allocator.%s-ingress-public.svc.cluster.local/api/remove", infra.Name),
894 },
895 }
896}
897
giof8843412024-05-22 16:38:05 +0400898func pullHelmCharts(hf HelmFetcher, charts HelmCharts, rfs soft.RepoFS, root string) (map[string]string, error) {
899 ret := make(map[string]string)
900 for name, chart := range charts.Git {
901 chartRoot := filepath.Join(root, name)
902 ret[name] = chartRoot
903 if err := hf.Pull(chart, rfs, chartRoot); err != nil {
904 return nil, err
905 }
906 }
907 return ret, nil
908}
909
910func generateLocalCharts(g LocalChartGenerator, charts map[string]string) map[string]helmv2.HelmChartTemplateSpec {
911 ret := make(map[string]helmv2.HelmChartTemplateSpec)
912 for name, path := range charts {
913 ret[name] = g.Generate(path)
914 }
915 return ret
916}
917
918func pullContainerImages(appName string, imgs map[string]ContainerImage, registry, namespace string, jc JobCreator) error {
919 for _, img := range imgs {
920 name := fmt.Sprintf("copy-image-%s-%s-%s-%s", appName, img.Repository, img.Name, img.Tag)
921 if err := jc.Create(name, namespace, "giolekva/skopeo:latest", []string{
922 "skopeo",
923 "--insecure-policy",
924 "copy",
925 "--dest-tls-verify=false", // TODO(gio): enable
926 "--multi-arch=all",
927 fmt.Sprintf("docker://%s/%s/%s:%s", img.Registry, img.Repository, img.Name, img.Tag),
928 fmt.Sprintf("docker://%s/%s/%s:%s", registry, img.Repository, img.Name, img.Tag),
929 }); err != nil {
930 return err
931 }
932 }
933 return nil
934}
935
936type renderedInstance struct {
937 LocalCharts map[string]helmv2.HelmChartTemplateSpec `json:"localCharts"`
giocdfa3722024-06-13 20:10:14 +0400938 PortForward []PortForward `json:"portForward"`
giof8843412024-05-22 16:38:05 +0400939}
940
giocdfa3722024-06-13 20:10:14 +0400941func readRendered(fs soft.RepoFS, path string) (renderedInstance, error) {
giof8843412024-05-22 16:38:05 +0400942 r, err := fs.Reader(path)
943 if err != nil {
giocdfa3722024-06-13 20:10:14 +0400944 return renderedInstance{}, err
giof8843412024-05-22 16:38:05 +0400945 }
946 defer r.Close()
947 var cfg renderedInstance
948 if err := json.NewDecoder(r).Decode(&cfg); err != nil {
giocdfa3722024-06-13 20:10:14 +0400949 return renderedInstance{}, err
giof8843412024-05-22 16:38:05 +0400950 }
giocdfa3722024-06-13 20:10:14 +0400951 return cfg, nil
giof8843412024-05-22 16:38:05 +0400952}
gioefa0ed42024-06-13 12:31:43 +0400953
954func findPortFields(scm Schema) []string {
955 switch scm.Kind() {
956 case KindBoolean:
957 return []string{}
958 case KindInt:
959 return []string{}
960 case KindString:
961 return []string{}
962 case KindStruct:
963 ret := []string{}
964 for _, f := range scm.Fields() {
965 for _, p := range findPortFields(f.Schema) {
966 if p == "" {
967 ret = append(ret, f.Name)
968 } else {
969 ret = append(ret, fmt.Sprintf("%s.%s", f.Name, p))
970 }
971 }
972 }
973 return ret
974 case KindNetwork:
975 return []string{}
gio4ece99c2024-07-18 11:05:50 +0400976 case KindMultiNetwork:
977 return []string{}
gioefa0ed42024-06-13 12:31:43 +0400978 case KindAuth:
979 return []string{}
980 case KindSSHKey:
981 return []string{}
982 case KindNumber:
983 return []string{}
984 case KindArrayString:
985 return []string{}
986 case KindPort:
987 return []string{""}
988 default:
989 panic("MUST NOT REACH!")
990 }
991}
992
993func setPortFields(values map[string]any, ports map[string]reservePortResp) error {
994 for p, r := range ports {
995 if err := setPortField(values, p, r.Port); err != nil {
996 return err
997 }
998 }
999 return nil
1000}
1001
1002func setPortField(values map[string]any, field string, port int) error {
1003 f := strings.SplitN(field, ".", 2)
1004 if len(f) == 2 {
1005 var sub map[string]any
1006 if s, ok := values[f[0]]; ok {
1007 sub, ok = s.(map[string]any)
1008 if !ok {
1009 return fmt.Errorf("expected map")
1010 }
1011 } else {
1012 sub = map[string]any{}
1013 values[f[0]] = sub
1014 }
1015 if err := setPortField(sub, f[1], port); err != nil {
1016 return err
1017 }
1018 } else {
1019 values[f[0]] = port
1020 }
1021 return nil
1022}