chart.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. corev1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "github.com/external-secrets/external-secrets-e2e/framework/log"
  24. . "github.com/onsi/ginkgo/v2"
  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) cleanupUninstallArgs() []string {
  118. return []string{"uninstall", "--namespace", c.Namespace, c.ReleaseName, "--ignore-not-found"}
  119. }
  120. func (c *HelmChart) releaseStatusArgs() []string {
  121. return []string{"status", "--namespace", c.Namespace, c.ReleaseName}
  122. }
  123. func (c *HelmChart) runInstall(args []string) ([]byte, error) {
  124. log.Logf("installing chart with args: %+q", args)
  125. cmd := exec.Command("helm", args...)
  126. return cmd.CombinedOutput()
  127. }
  128. func (c *HelmChart) cleanupExistingRelease() error {
  129. cmd := exec.Command("helm", c.cleanupUninstallArgs()...)
  130. output, err := cmd.CombinedOutput()
  131. if err != nil && !strings.Contains(string(output), "release: not found") {
  132. statusOutput, statusErr := c.releaseStatus()
  133. if canIgnoreHelmCleanupError(string(statusOutput)) {
  134. return nil
  135. }
  136. if statusErr != nil {
  137. return fmt.Errorf("unable to uninstall stale helm release: %w: %s (status check failed: %v: %s)", err, string(output), statusErr, string(statusOutput))
  138. }
  139. return fmt.Errorf("unable to uninstall stale helm release: %w: %s", err, string(output))
  140. }
  141. return nil
  142. }
  143. func (c *HelmChart) releaseStatus() ([]byte, error) {
  144. cmd := exec.Command("helm", c.releaseStatusArgs()...)
  145. return cmd.CombinedOutput()
  146. }
  147. func isHelmReleaseNameInUseError(output string) bool {
  148. return strings.Contains(output, "cannot re-use a name that is still in use")
  149. }
  150. func isHelmReleaseNotFoundError(output string) bool {
  151. return strings.Contains(output, "release: not found")
  152. }
  153. func canIgnoreHelmCleanupError(statusOutput string) bool {
  154. return isHelmReleaseNotFoundError(statusOutput)
  155. }
  156. // Uninstall removes the chart aswell as the repo.
  157. func (c *HelmChart) Uninstall() error {
  158. cmd := exec.Command("helm", c.uninstallArgs()...)
  159. output, err := cmd.CombinedOutput()
  160. if err != nil {
  161. return fmt.Errorf("unable to uninstall helm release: %w: %s", err, string(output))
  162. }
  163. return c.removeRepo()
  164. }
  165. func (c *HelmChart) addRepo() error {
  166. if c.Repo.Name == "" || c.Repo.URL == "" {
  167. return nil
  168. }
  169. var sout, serr bytes.Buffer
  170. args := []string{"repo", "add", c.Repo.Name, c.Repo.URL}
  171. cmd := exec.Command("helm", args...)
  172. cmd.Stdout = &sout
  173. cmd.Stderr = &serr
  174. err := cmd.Run()
  175. if err != nil {
  176. return fmt.Errorf("unable to add helm repo: %w: %s, %s", err, sout.String(), serr.String())
  177. }
  178. return nil
  179. }
  180. func (c *HelmChart) removeRepo() error {
  181. if c.Repo.Name == "" || c.Repo.URL == "" {
  182. return nil
  183. }
  184. args := []string{"repo", "remove", c.Repo.Name}
  185. cmd := exec.Command("helm", args...)
  186. output, err := cmd.CombinedOutput()
  187. if err != nil {
  188. return fmt.Errorf("unable to remove repo: %w: %s", err, string(output))
  189. }
  190. return nil
  191. }
  192. // Logs fetches the logs from all pods managed by this release
  193. // and prints them out.
  194. func (c *HelmChart) Logs() error {
  195. kc := c.config.KubeClientSet
  196. podList, err := kc.CoreV1().Pods(c.Namespace).List(
  197. GinkgoT().Context(),
  198. metav1.ListOptions{LabelSelector: "app.kubernetes.io/instance=" + c.ReleaseName})
  199. if err != nil {
  200. return err
  201. }
  202. log.Logf("logs: found %d pods", len(podList.Items))
  203. tailLines := int64(200)
  204. for i := range podList.Items {
  205. pod := podList.Items[i]
  206. for _, con := range pod.Spec.Containers {
  207. for _, b := range []bool{true, false} {
  208. resp := kc.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
  209. Container: con.Name,
  210. Previous: b,
  211. TailLines: &tailLines,
  212. }).Do(GinkgoT().Context())
  213. err := resp.Error()
  214. if err != nil {
  215. continue
  216. }
  217. logs, err := resp.Raw()
  218. if err != nil {
  219. continue
  220. }
  221. log.Logf("[%s]: %s", c.ReleaseName, string(logs))
  222. }
  223. }
  224. }
  225. return nil
  226. }
  227. func (c *HelmChart) HasVar(key, value string) bool {
  228. for _, v := range c.Vars {
  229. if v.Key == key && v.Value == value {
  230. return true
  231. }
  232. }
  233. return false
  234. }