apply.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package v2beta1
  2. import (
  3. "context"
  4. "fmt"
  5. "regexp"
  6. api "github.com/porter-dev/porter/api/client"
  7. "github.com/porter-dev/porter/cli/cmd/config"
  8. "github.com/porter-dev/switchboard/pkg/types"
  9. "gopkg.in/yaml.v3"
  10. )
  11. // const (
  12. // constantsEnvGroup = "preview-env-constants"
  13. // defaultCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~`!@#$%^&*()_+-={}[]"
  14. // )
  15. type PreviewApplier struct {
  16. apiClient *api.Client
  17. rawBytes []byte
  18. namespace string
  19. parsed *PorterYAML
  20. // variablesMap map[string]string
  21. // osEnv map[string]string
  22. // envGroups map[string]*apiTypes.EnvGroup
  23. }
  24. func NewApplier(client *api.Client, raw []byte, namespace string) (*PreviewApplier, error) {
  25. // replace all instances of ${{ porter.env.FOO }} with { .get-env.FOO }
  26. re := regexp.MustCompile(`\$\{\{\s*porter\.env\.(.*)\s*\}\}`)
  27. raw = re.ReplaceAll(raw, []byte("{.get-env.$1}"))
  28. parsed := &PorterYAML{}
  29. err := yaml.Unmarshal(raw, parsed)
  30. if err != nil {
  31. errMsg := composePreviewMessage("error parsing porter.yaml", Error)
  32. return nil, fmt.Errorf("%s: %w", errMsg, err)
  33. }
  34. // err = validator.ValidatePorterYAML(parsed)
  35. // if err != nil {
  36. // return nil, err
  37. // }
  38. err = config.ValidateCLIEnvironment()
  39. if err != nil {
  40. errMsg := composePreviewMessage("porter CLI is not configured correctly", Error)
  41. return nil, fmt.Errorf("%s: %w", errMsg, err)
  42. }
  43. return &PreviewApplier{
  44. apiClient: client,
  45. rawBytes: raw,
  46. namespace: namespace,
  47. parsed: parsed,
  48. }, nil
  49. }
  50. func (a *PreviewApplier) Apply() error {
  51. // for v2beta1, check if the namespace exists in the current project-cluster pair
  52. //
  53. // this is a sanity check to ensure that the user does not see any internal
  54. // errors that are caused by the namespace not existing
  55. nsList, err := a.apiClient.GetK8sNamespaces(
  56. context.Background(),
  57. config.GetCLIConfig().Project,
  58. config.GetCLIConfig().Cluster,
  59. )
  60. if err != nil {
  61. errMsg := composePreviewMessage(fmt.Sprintf("error listing namespaces for project '%d', cluster '%d'",
  62. config.GetCLIConfig().Project, config.GetCLIConfig().Cluster), Error)
  63. return fmt.Errorf("%s: %w", errMsg, err)
  64. }
  65. namespaces := *nsList
  66. nsFound := false
  67. for _, ns := range namespaces {
  68. if ns.Name == a.namespace {
  69. nsFound = true
  70. break
  71. }
  72. }
  73. if !nsFound {
  74. // errMsg := composePreviewMessage(fmt.Sprintf("namespace '%s' does not exist in project '%d', cluster '%d'",
  75. // a.namespace, config.GetCLIConfig().Project, config.GetCLIConfig().Cluster), Error)
  76. // return fmt.Errorf("%s: %w", errMsg, err)
  77. }
  78. printInfoMessage(fmt.Sprintf("Applying porter.yaml with the following attributes:\n"+
  79. "\tHost: %s\n\tProject ID: %d\n\tCluster ID: %d\n\tNamespace: %s",
  80. config.GetCLIConfig().Host,
  81. config.GetCLIConfig().Project,
  82. config.GetCLIConfig().Cluster,
  83. a.namespace),
  84. )
  85. // err = a.readOSEnv()
  86. // if err != nil {
  87. // errMsg := composePreviewMessage("error reading OS environment variables", Error)
  88. // return fmt.Errorf("%s: %w", errMsg, err)
  89. // }
  90. // err = a.processVariables()
  91. // if err != nil {
  92. // return err
  93. // }
  94. // err = a.processEnvGroups()
  95. // if err != nil {
  96. // return err
  97. // }
  98. return nil
  99. }
  100. func (a *PreviewApplier) DowngradeToV1() (*types.ResourceGroup, error) {
  101. err := a.Apply()
  102. if err != nil {
  103. return nil, err
  104. }
  105. v1File := &types.ResourceGroup{
  106. Version: "v1",
  107. Resources: []*types.Resource{
  108. {
  109. Name: "get-env",
  110. Driver: "os-env",
  111. },
  112. },
  113. }
  114. buildRefs := make(map[string]*Build)
  115. for _, b := range a.parsed.Builds {
  116. if b == nil {
  117. continue
  118. }
  119. buildRefs[b.GetName()] = b
  120. bi, err := b.getV1BuildImage()
  121. if err != nil {
  122. return nil, err
  123. }
  124. pi, err := b.getV1PushImage()
  125. if err != nil {
  126. return nil, err
  127. }
  128. v1File.Resources = append(v1File.Resources, bi, pi)
  129. }
  130. for _, app := range a.parsed.Apps {
  131. if app == nil {
  132. continue
  133. }
  134. if _, ok := buildRefs[app.GetBuildRef()]; !ok {
  135. errMsg := composePreviewMessage(fmt.Sprintf("build_ref '%s' referenced by app '%s' does not exist",
  136. app.GetBuildRef(), app.GetName()), Error)
  137. return nil, fmt.Errorf("%s: %w", errMsg, err)
  138. }
  139. ai, err := app.getV1Resource(buildRefs[app.GetBuildRef()])
  140. if err != nil {
  141. return nil, err
  142. }
  143. v1File.Resources = append(v1File.Resources, ai)
  144. }
  145. for _, addon := range a.parsed.Addons {
  146. if addon == nil {
  147. continue
  148. }
  149. ai, err := addon.getV1Addon()
  150. if err != nil {
  151. return nil, err
  152. }
  153. v1File.Resources = append(v1File.Resources, ai)
  154. }
  155. return v1File, nil
  156. }
  157. // func (a *PreviewApplier) readOSEnv() error {
  158. // printInfoMessage("Reading OS environment variables")
  159. // env := os.Environ()
  160. // osEnv := make(map[string]string)
  161. // for _, e := range env {
  162. // k, v, _ := strings.Cut(e, "=")
  163. // kCopy := k
  164. // if k != "" && v != "" && strings.HasPrefix(k, "PORTER_APPLY_") {
  165. // // we only read in env variables that start with PORTER_APPLY_
  166. // for strings.HasPrefix(k, "PORTER_APPLY_") {
  167. // k = strings.TrimPrefix(k, "PORTER_APPLY_")
  168. // }
  169. // if k == "" {
  170. // printWarningMessage(fmt.Sprintf("Ignoring invalid OS environment variable '%s'", kCopy))
  171. // }
  172. // osEnv[k] = v
  173. // }
  174. // }
  175. // a.osEnv = osEnv
  176. // return nil
  177. // }
  178. // func (a *PreviewApplier) processVariables() error {
  179. // printInfoMessage("Processing variables")
  180. // constantsMap := make(map[string]string)
  181. // variablesMap := make(map[string]string)
  182. // for _, v := range a.parsed.Variables {
  183. // if v == nil {
  184. // continue
  185. // }
  186. // if v.Once != nil && *v.Once {
  187. // // a constant which should be stored in the env group on first run
  188. // if exists, err := a.constantExistsInEnvGroup(*v.Name); err == nil {
  189. // if exists == nil {
  190. // // this should not happen
  191. // return fmt.Errorf("internal error: please let the Porter team know about this and quote the following " +
  192. // "error:\n-----\nERROR: checking for constant existence in env group returned nil with no error")
  193. // }
  194. // val := *exists
  195. // if !val {
  196. // // create the constant in the env group
  197. // if *v.Value != "" {
  198. // constantsMap[*v.Name] = *v.Value
  199. // } else if v.Random != nil && *v.Random {
  200. // constantsMap[*v.Name] = randomString(*v.Length, defaultCharset)
  201. // } else {
  202. // // this should not happen
  203. // return fmt.Errorf("internal error: please let the Porter team know about this and quote the following "+
  204. // "error:\n-----\nERROR: for variable '%s', random is false and value is empty", *v.Name)
  205. // }
  206. // }
  207. // } else {
  208. // return fmt.Errorf("error checking for existence of constant %s: %w", *v.Name, err)
  209. // }
  210. // } else {
  211. // if v.Value != nil && *v.Value != "" {
  212. // variablesMap[*v.Name] = *v.Value
  213. // } else if v.Random != nil && *v.Random {
  214. // variablesMap[*v.Name] = randomString(*v.Length, defaultCharset)
  215. // } else {
  216. // // this should not happen
  217. // return fmt.Errorf("internal error: please let the Porter team know about this and quote the following "+
  218. // "error:\n-----\nERROR: for variable '%s', random is false and value is empty", *v.Name)
  219. // }
  220. // }
  221. // }
  222. // if len(constantsMap) > 0 {
  223. // // we need to create these constants in the env group
  224. // _, err := a.apiClient.CreateEnvGroup(
  225. // context.Background(),
  226. // config.GetCLIConfig().Project,
  227. // config.GetCLIConfig().Cluster,
  228. // a.namespace,
  229. // &apiTypes.CreateEnvGroupRequest{
  230. // Name: constantsEnvGroup,
  231. // Variables: constantsMap,
  232. // },
  233. // )
  234. // if err != nil {
  235. // return fmt.Errorf("error creating constants (variables with once set to true) in env group: %w", err)
  236. // }
  237. // for k, v := range constantsMap {
  238. // variablesMap[k] = v
  239. // }
  240. // }
  241. // a.variablesMap = variablesMap
  242. // return nil
  243. // }
  244. // func (a *PreviewApplier) constantExistsInEnvGroup(name string) (*bool, error) {
  245. // apiResponse, err := a.apiClient.GetEnvGroup(
  246. // context.Background(),
  247. // config.GetCLIConfig().Project,
  248. // config.GetCLIConfig().Cluster,
  249. // a.namespace,
  250. // &apiTypes.GetEnvGroupRequest{
  251. // Name: constantsEnvGroup,
  252. // // we do not care about the version because it always needs to be the latest
  253. // },
  254. // )
  255. // if err != nil {
  256. // if strings.Contains(err.Error(), "env group not found") {
  257. // return booleanptr(false), nil
  258. // }
  259. // return nil, err
  260. // }
  261. // if _, ok := apiResponse.Variables[name]; ok {
  262. // return booleanptr(true), nil
  263. // }
  264. // return booleanptr(false), nil
  265. // }
  266. // func (a *PreviewApplier) processEnvGroups() error {
  267. // printInfoMessage("Processing env groups")
  268. // for _, eg := range a.parsed.EnvGroups {
  269. // if eg == nil {
  270. // continue
  271. // }
  272. // if eg.Name == nil || *eg.Name == "" {
  273. // }
  274. // envGroup, err := a.apiClient.GetEnvGroup(
  275. // context.Background(),
  276. // config.GetCLIConfig().Project,
  277. // config.GetCLIConfig().Cluster,
  278. // a.namespace,
  279. // &apiTypes.GetEnvGroupRequest{
  280. // Name: *eg.Name,
  281. // },
  282. // )
  283. // if err != nil && strings.Contains(err.Error(), "env group not found") {
  284. // if eg.CloneFrom == nil {
  285. // return fmt.Errorf(composePreviewMessage(fmt.Sprintf("empty clone_from for env group '%s'", *eg.Name), Error))
  286. // }
  287. // egNS, egName, found := strings.Cut(*eg.CloneFrom, "/")
  288. // if !found {
  289. // return fmt.Errorf("error parsing clone_from for env group '%s': invalid format", *eg.Name)
  290. // }
  291. // // clone the env group
  292. // envGroup, err := a.apiClient.CloneEnvGroup(
  293. // context.Background(),
  294. // config.GetCLIConfig().Project,
  295. // config.GetCLIConfig().Cluster,
  296. // egNS,
  297. // &apiTypes.CloneEnvGroupRequest{
  298. // SourceName: egName,
  299. // TargetNamespace: a.namespace,
  300. // TargetName: *eg.Name,
  301. // },
  302. // )
  303. // if err != nil {
  304. // return fmt.Errorf("error cloning env group '%s' from '%s': %w", egName, egNS, err)
  305. // }
  306. // a.envGroups[*eg.Name] = &apiTypes.EnvGroup{
  307. // Name: envGroup.Name,
  308. // Variables: envGroup.Variables,
  309. // }
  310. // } else if err != nil {
  311. // return fmt.Errorf("error checking for env group '%s': %w", *eg.Name, err)
  312. // } else {
  313. // a.envGroups[*eg.Name] = &apiTypes.EnvGroup{
  314. // Name: envGroup.Name,
  315. // Variables: envGroup.Variables,
  316. // }
  317. // }
  318. // }
  319. // return nil
  320. // }