chart.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. "path/filepath"
  19. "strings"
  20. . "github.com/onsi/ginkgo/v2"
  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. frameworkutil "github.com/external-secrets/external-secrets-e2e/framework/util"
  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, err := frameworkutil.Command("helm", args...)
  60. if err != nil {
  61. return fmt.Errorf("resolve helm executable: %w", err)
  62. }
  63. output, err := cmd.CombinedOutput()
  64. if err != nil {
  65. return fmt.Errorf("unable to run update cmd: %w: %s", err, string(output))
  66. }
  67. }
  68. err := c.addRepo()
  69. if err != nil {
  70. return err
  71. }
  72. args := c.installArgs()
  73. output, err := c.runInstall(args)
  74. if err != nil {
  75. if !isHelmReleaseNameInUseError(string(output)) {
  76. return fmt.Errorf("unable to run cmd: %w: %s", err, string(output))
  77. }
  78. log.Logf("helm install detected stale release state for %q in namespace %q; attempting cleanup", c.ReleaseName, c.Namespace)
  79. if cleanupErr := c.cleanupExistingRelease(); cleanupErr != nil {
  80. return fmt.Errorf("unable to clean stale helm release %s/%s after install failure: %w", c.Namespace, c.ReleaseName, cleanupErr)
  81. }
  82. output, err = c.runInstall(args)
  83. if err != nil {
  84. return fmt.Errorf("unable to run cmd after stale release cleanup: %w: %s", err, string(output))
  85. }
  86. }
  87. log.Logf("finished running chart install")
  88. return nil
  89. }
  90. func helmDependencyUpdateEnabled() bool {
  91. return os.Getenv("E2E_SKIP_HELM_DEPENDENCY_UPDATE") != "true"
  92. }
  93. func (c *HelmChart) installArgs() []string {
  94. args := []string{"install", c.ReleaseName, c.Chart}
  95. if helmDependencyUpdateEnabled() {
  96. args = append(args, "--dependency-update")
  97. }
  98. args = append(args,
  99. "--debug",
  100. "--wait",
  101. "--timeout", "600s",
  102. "-o", "yaml",
  103. "--namespace", c.Namespace,
  104. )
  105. if c.ChartVersion != "" {
  106. args = append(args, "--version", c.ChartVersion)
  107. }
  108. for _, v := range c.Values {
  109. args = append(args, "--values", v)
  110. }
  111. for _, s := range c.Vars {
  112. args = append(args, "--set", fmt.Sprintf("%s=%s", s.Key, s.Value))
  113. }
  114. args = append(args, c.Args...)
  115. return args
  116. }
  117. func (c *HelmChart) uninstallArgs() []string {
  118. return []string{"uninstall", "--namespace", c.Namespace, c.ReleaseName, "--wait", "--ignore-not-found"}
  119. }
  120. func (c *HelmChart) cleanupUninstallArgs() []string {
  121. return []string{"uninstall", "--namespace", c.Namespace, c.ReleaseName, "--ignore-not-found"}
  122. }
  123. func (c *HelmChart) releaseStatusArgs() []string {
  124. return []string{"status", "--namespace", c.Namespace, c.ReleaseName}
  125. }
  126. func (c *HelmChart) runInstall(args []string) ([]byte, error) {
  127. log.Logf("installing chart with args: %+q", args)
  128. cmd, err := frameworkutil.Command("helm", args...)
  129. if err != nil {
  130. return nil, fmt.Errorf("resolve helm executable: %w", err)
  131. }
  132. return cmd.CombinedOutput()
  133. }
  134. func (c *HelmChart) cleanupExistingRelease() error {
  135. cmd, err := frameworkutil.Command("helm", c.cleanupUninstallArgs()...)
  136. if err != nil {
  137. return fmt.Errorf("resolve helm executable: %w", err)
  138. }
  139. output, err := cmd.CombinedOutput()
  140. if err != nil && !strings.Contains(string(output), "release: not found") {
  141. statusOutput, statusErr := c.releaseStatus()
  142. if canIgnoreHelmCleanupError(string(statusOutput)) {
  143. return nil
  144. }
  145. if statusErr != nil {
  146. return fmt.Errorf("unable to uninstall stale helm release: %w: %s (status check failed: %v: %s)", err, string(output), statusErr, string(statusOutput))
  147. }
  148. return fmt.Errorf("unable to uninstall stale helm release: %w: %s", err, string(output))
  149. }
  150. return nil
  151. }
  152. func (c *HelmChart) releaseStatus() ([]byte, error) {
  153. cmd, err := frameworkutil.Command("helm", c.releaseStatusArgs()...)
  154. if err != nil {
  155. return nil, fmt.Errorf("resolve helm executable: %w", err)
  156. }
  157. return cmd.CombinedOutput()
  158. }
  159. func isHelmReleaseNameInUseError(output string) bool {
  160. return strings.Contains(output, "cannot re-use a name that is still in use")
  161. }
  162. func isHelmReleaseNotFoundError(output string) bool {
  163. return strings.Contains(output, "release: not found")
  164. }
  165. func canIgnoreHelmCleanupError(statusOutput string) bool {
  166. return isHelmReleaseNotFoundError(statusOutput)
  167. }
  168. // Uninstall removes the chart aswell as the repo.
  169. func (c *HelmChart) Uninstall() error {
  170. cmd, err := frameworkutil.Command("helm", c.uninstallArgs()...)
  171. if err != nil {
  172. return fmt.Errorf("resolve helm executable: %w", err)
  173. }
  174. output, err := cmd.CombinedOutput()
  175. if err != nil {
  176. return fmt.Errorf("unable to uninstall helm release: %w: %s", err, string(output))
  177. }
  178. return c.removeRepo()
  179. }
  180. func (c *HelmChart) addRepo() error {
  181. if c.Repo.Name == "" || c.Repo.URL == "" {
  182. return nil
  183. }
  184. var sout, serr bytes.Buffer
  185. args := []string{"repo", "add", c.Repo.Name, c.Repo.URL}
  186. cmd, err := frameworkutil.Command("helm", args...)
  187. if err != nil {
  188. return fmt.Errorf("resolve helm executable: %w", err)
  189. }
  190. cmd.Stdout = &sout
  191. cmd.Stderr = &serr
  192. err = cmd.Run()
  193. if err != nil {
  194. return fmt.Errorf("unable to add helm repo: %w: %s, %s", err, sout.String(), serr.String())
  195. }
  196. return nil
  197. }
  198. func (c *HelmChart) removeRepo() error {
  199. if c.Repo.Name == "" || c.Repo.URL == "" {
  200. return nil
  201. }
  202. args := []string{"repo", "remove", c.Repo.Name}
  203. cmd, err := frameworkutil.Command("helm", args...)
  204. if err != nil {
  205. return fmt.Errorf("resolve helm executable: %w", err)
  206. }
  207. output, err := cmd.CombinedOutput()
  208. if err != nil {
  209. return fmt.Errorf("unable to remove repo: %w: %s", err, string(output))
  210. }
  211. return nil
  212. }
  213. // Logs fetches the logs from all pods managed by this release
  214. // and prints them out.
  215. func (c *HelmChart) Logs() error {
  216. kc := c.config.KubeClientSet
  217. podList, err := kc.CoreV1().Pods(c.Namespace).List(
  218. GinkgoT().Context(),
  219. metav1.ListOptions{LabelSelector: "app.kubernetes.io/instance=" + c.ReleaseName})
  220. if err != nil {
  221. return err
  222. }
  223. log.Logf("logs: found %d pods", len(podList.Items))
  224. tailLines := int64(200)
  225. for i := range podList.Items {
  226. pod := podList.Items[i]
  227. for _, con := range pod.Spec.Containers {
  228. for _, b := range []bool{true, false} {
  229. resp := kc.CoreV1().Pods(pod.Namespace).GetLogs(pod.Name, &corev1.PodLogOptions{
  230. Container: con.Name,
  231. Previous: b,
  232. TailLines: &tailLines,
  233. }).Do(GinkgoT().Context())
  234. err := resp.Error()
  235. if err != nil {
  236. continue
  237. }
  238. logs, err := resp.Raw()
  239. if err != nil {
  240. continue
  241. }
  242. log.Logf("[%s]: %s", c.ReleaseName, string(logs))
  243. }
  244. }
  245. }
  246. return nil
  247. }
  248. func (c *HelmChart) HasVar(key, value string) bool {
  249. for _, v := range c.Vars {
  250. if v.Key == key && v.Value == value {
  251. return true
  252. }
  253. }
  254. return false
  255. }