chart.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // +build kube
  2. /*
  3. Copyright 2020 Docker Compose CLI authors
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package helm
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "html/template"
  19. "os"
  20. "path/filepath"
  21. "strings"
  22. "github.com/compose-spec/compose-go/types"
  23. "github.com/docker/compose-cli/kube/resources"
  24. "github.com/pkg/errors"
  25. "gopkg.in/yaml.v3"
  26. chart "helm.sh/helm/v3/pkg/chart"
  27. loader "helm.sh/helm/v3/pkg/chart/loader"
  28. "k8s.io/apimachinery/pkg/runtime"
  29. )
  30. //ConvertToChart convert Kube objects to helm chart
  31. func ConvertToChart(name string, objects map[string]runtime.Object) (*chart.Chart, error) {
  32. files := []*loader.BufferedFile{
  33. {
  34. Name: "README.md",
  35. Data: []byte("This chart was created by converting a Compose file"),
  36. }}
  37. chart := `name: {{.Name}}
  38. description: A generated Helm Chart for {{.Name}} from Skippbox Kompose
  39. version: 0.0.1
  40. apiVersion: v1
  41. keywords:
  42. - {{.Name}}
  43. sources:
  44. home:
  45. `
  46. t, err := template.New("ChartTmpl").Parse(chart)
  47. if err != nil {
  48. return nil, err
  49. }
  50. type ChartDetails struct {
  51. Name string
  52. }
  53. var chartData bytes.Buffer
  54. err = t.Execute(&chartData, ChartDetails{Name: name})
  55. if err != nil {
  56. return nil, err
  57. }
  58. files = append(files, &loader.BufferedFile{
  59. Name: "Chart.yaml",
  60. Data: chartData.Bytes(),
  61. })
  62. for name, o := range objects {
  63. j, err := json.Marshal(o)
  64. if err != nil {
  65. return nil, err
  66. }
  67. buf, err := jsonToYaml(j, 2)
  68. if err != nil {
  69. return nil, err
  70. }
  71. files = append(files, &loader.BufferedFile{
  72. Name: filepath.Join("templates", name),
  73. Data: buf,
  74. })
  75. }
  76. return loader.LoadFiles(files)
  77. }
  78. // Convert JSON to YAML.
  79. func jsonToYaml(j []byte, spaces int) ([]byte, error) {
  80. // Convert the JSON to an object.
  81. var jsonObj interface{}
  82. // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the
  83. // Go JSON library doesn't try to pick the right number type (int, float,
  84. // etc.) when unmarshling to interface{}, it just picks float64
  85. // universally. go-yaml does go through the effort of picking the right
  86. // number type, so we can preserve number type throughout this process.
  87. err := yaml.Unmarshal(j, &jsonObj)
  88. if err != nil {
  89. return nil, err
  90. }
  91. var b bytes.Buffer
  92. encoder := yaml.NewEncoder(&b)
  93. encoder.SetIndent(spaces)
  94. if err := encoder.Encode(jsonObj); err != nil {
  95. return nil, err
  96. }
  97. return b.Bytes(), nil
  98. }
  99. // GetChartInMemory get memory representation of helm chart
  100. func GetChartInMemory(project *types.Project) (*chart.Chart, error) {
  101. // replace _ with - in volume names
  102. for k, v := range project.Volumes {
  103. volumeName := strings.ReplaceAll(k, "_", "-")
  104. if volumeName != k {
  105. project.Volumes[volumeName] = v
  106. delete(project.Volumes, k)
  107. }
  108. }
  109. objects, err := resources.MapToKubernetesObjects(project)
  110. if err != nil {
  111. return nil, err
  112. }
  113. //in memory files
  114. return ConvertToChart(project.Name, objects)
  115. }
  116. // SaveChart saves the chart to directory
  117. func SaveChart(c *chart.Chart, dest string) (string, error) {
  118. dir, err := filepath.Abs(dest)
  119. if err != nil {
  120. return "", err
  121. }
  122. for _, file := range c.Raw {
  123. filename := filepath.Join(dir, file.Name)
  124. filedir := filepath.Dir(filename)
  125. stat, err := os.Stat(filedir)
  126. if err != nil {
  127. if os.IsNotExist(err) {
  128. if err2 := os.MkdirAll(filedir, 0755); err2 != nil {
  129. return "", err2
  130. }
  131. } else {
  132. return "", err
  133. }
  134. } else if !stat.IsDir() {
  135. return "", errors.Errorf("%s: not a directory", dest)
  136. }
  137. f, err := os.Create(filename)
  138. if err != nil {
  139. return "", err
  140. }
  141. _, err = f.Write(file.Data)
  142. if err != nil {
  143. return "", err
  144. }
  145. }
  146. return dir, nil
  147. }