chart.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package addon
  14. import (
  15. "bytes"
  16. "fmt"
  17. "os"
  18. "os/exec"
  19. "path/filepath"
  20. "strings"
  21. . "github.com/onsi/ginkgo/v2"
  22. corev1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "github.com/external-secrets/external-secrets-e2e/framework/log"
  25. )
  26. // HelmChart installs the specified Chart into the cluster.
  27. type HelmChart struct {
  28. Namespace string
  29. ReleaseName string
  30. Chart string
  31. ChartVersion string
  32. Repo ChartRepo
  33. Vars []StringTuple
  34. Values []string
  35. Args []string
  36. config *Config
  37. }
  38. type ChartRepo struct {
  39. Name string
  40. URL string
  41. }
  42. type StringTuple struct {
  43. Key string
  44. Value string
  45. }
  46. // Setup stores the config in an internal field
  47. // to get access to the k8s api in orderto fetch logs.
  48. func (c *HelmChart) Setup(cfg *Config) error {
  49. c.config = cfg
  50. return nil
  51. }
  52. // Install adds the chart repo and installs the helm chart.
  53. func (c *HelmChart) Install() error {
  54. if helmDependencyUpdateEnabled() {
  55. args := []string{
  56. "dependency", "update", filepath.Join(AssetDir(), "deploy/charts/external-secrets"),
  57. }
  58. log.Logf("updating chart dependencies with args: %+q", args)
  59. cmd := exec.Command("helm", args...)
  60. output, err := cmd.CombinedOutput()
  61. if err != nil {
  62. return fmt.Errorf("unable to run update cmd: %w: %s", err, string(output))
  63. }
  64. }
  65. err := c.addRepo()
  66. if err != nil {
  67. return err
  68. }
  69. args := c.installArgs()
  70. output, err := c.runInstall(args)
  71. if err != nil {
  72. if !isHelmReleaseNameInUseError(string(output)) {
  73. return fmt.Errorf("unable to run cmd: %w: %s", err, string(output))
  74. }
  75. log.Logf("helm install detected stale release state for %q in namespace %q; attempting cleanup", c.ReleaseName, c.Namespace)
  76. if cleanupErr := c.cleanupExistingRelease(); cleanupErr != nil {
  77. return fmt.Errorf("unable to clean stale helm release %s/%s after install failure: %w", c.Namespace, c.ReleaseName, cleanupErr)
  78. }
  79. output, err = c.runInstall(args)
  80. if err != nil {
  81. return fmt.Errorf("unable to run cmd after stale release cleanup: %w: %s", err, string(output))
  82. }
  83. }
  84. log.Logf("finished running chart install")
  85. return nil
  86. }
  87. func helmDependencyUpdateEnabled() bool {
  88. return os.Getenv("E2E_SKIP_HELM_DEPENDENCY_UPDATE") != "true"
  89. }
  90. func (c *HelmChart) installArgs() []string {
  91. args := []string{"install", c.ReleaseName, c.Chart}
  92. if helmDependencyUpdateEnabled() {
  93. args = append(args, "--dependency-update")
  94. }
  95. args = append(args,
  96. "--debug",
  97. "--wait",
  98. "--timeout", "600s",
  99. "-o", "yaml",
  100. "--namespace", c.Namespace,
  101. )
  102. if c.ChartVersion != "" {
  103. args = append(args, "--version", c.ChartVersion)
  104. }
  105. for _, v := range c.Values {
  106. args = append(args, "--values", v)
  107. }
  108. for _, s := range c.Vars {
  109. args = append(args, "--set", fmt.Sprintf("%s=%s", s.Key, s.Value))
  110. }
  111. args = append(args, c.Args...)
  112. return args
  113. }
  114. func (c *HelmChart) uninstallArgs() []string {
  115. return []string{"uninstall", "--namespace", c.Namespace, c.ReleaseName, "--wait", "--ignore-not-found"}
  116. }
  117. func (c *HelmChart) runInstall(args []string) ([]byte, error) {
  118. log.Logf("installing chart with args: %+q", args)
  119. cmd := exec.Command("helm", args...)
  120. return cmd.CombinedOutput()
  121. }
  122. func (c *HelmChart) cleanupExistingRelease() error {
  123. cmd := exec.Command("helm", c.uninstallArgs()...)
  124. output, err := cmd.CombinedOutput()
  125. if err != nil && !strings.Contains(string(output), "release: not found") {
  126. return fmt.Errorf("unable to uninstall stale helm release: %w: %s", err, string(output))
  127. }
  128. return nil
  129. }
  130. func isHelmReleaseNameInUseError(output string) bool {
  131. return strings.Contains(output, "cannot re-use a name that is still in use")
  132. }
  133. // Uninstall removes the chart aswell as the repo.
  134. func (c *HelmChart) Uninstall() error {
  135. cmd := exec.Command("helm", c.uninstallArgs()...)
  136. output, err := cmd.CombinedOutput()
  137. if err != nil {
  138. return fmt.Errorf("unable to uninstall helm release: %w: %s", err, string(output))
  139. }
  140. return c.removeRepo()
  141. }
  142. func (c *HelmChart) addRepo() error {
  143. if c.Repo.Name == "" || c.Repo.URL == "" {
  144. return nil
  145. }
  146. var sout, serr bytes.Buffer
  147. args := []string{"repo", "add", c.Repo.Name, c.Repo.URL}
  148. cmd := exec.Command("helm", args...)
  149. cmd.Stdout = &sout
  150. cmd.Stderr = &serr
  151. err := cmd.Run()
  152. if err != nil {
  153. return fmt.Errorf("unable to add helm repo: %w: %s, %s", err, sout.String(), serr.String())
  154. }
  155. return nil
  156. }
  157. func (c *HelmChart) removeRepo() error {
  158. if c.Repo.Name == "" || c.Repo.URL == "" {
  159. return nil
  160. }
  161. args := []string{"repo", "remove", c.Repo.Name}
  162. cmd := exec.Command("helm", args...)
  163. output, err := cmd.CombinedOutput()
  164. if err != nil {
  165. return fmt.Errorf("unable to remove repo: %w: %s", err, string(output))
  166. }
  167. return nil
  168. }
  169. // Logs fetches the logs from all pods managed by this release
  170. // and prints them out.
  171. func (c *HelmChart) Logs() error {
  172. kc := c.config.KubeClientSet
  173. podList, err := kc.CoreV1().Pods(c.Namespace).List(
  174. GinkgoT().Context(),
  175. metav1.ListOptions{LabelSelector: "app.kubernetes.io/instance=" + c.ReleaseName})
  176. if err != nil {
  177. return err
  178. }
  179. log.Logf("logs: found %d pods", len(podList.Items))
  180. tailLines := int64(200)
  181. for i := range podList.Items {
  182. pod := podList.Items[i]
  183. for _, con := range pod.Spec.Containers {
  184. for _, b := range []bool{true, false} {
  185. resp := kc.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
  186. Container: con.Name,
  187. Previous: b,
  188. TailLines: &tailLines,
  189. }).Do(GinkgoT().Context())
  190. err := resp.Error()
  191. if err != nil {
  192. continue
  193. }
  194. logs, err := resp.Raw()
  195. if err != nil {
  196. continue
  197. }
  198. log.Logf("[%s]: %s", c.ReleaseName, string(logs))
  199. }
  200. }
  201. }
  202. return nil
  203. }
  204. func (c *HelmChart) HasVar(key, value string) bool {
  205. for _, v := range c.Vars {
  206. if v.Key == key && v.Value == value {
  207. return true
  208. }
  209. }
  210. return false
  211. }