chart.go 6.9 KB

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