parse.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. package stacks
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/porter-dev/porter/api/server/shared/config"
  6. "github.com/porter-dev/porter/api/types"
  7. "github.com/porter-dev/porter/internal/helm/loader"
  8. "github.com/porter-dev/porter/internal/integrations/powerdns"
  9. "github.com/porter-dev/porter/internal/kubernetes"
  10. "github.com/porter-dev/porter/internal/kubernetes/domain"
  11. "github.com/porter-dev/porter/internal/repository"
  12. "github.com/porter-dev/porter/internal/templater/utils"
  13. "github.com/stefanmcshane/helm/pkg/chart"
  14. "gopkg.in/yaml.v2"
  15. )
  16. type PorterStackYAML struct {
  17. Version *string `yaml:"version"`
  18. Build *Build `yaml:"build"`
  19. Env map[string]string `yaml:"env"`
  20. Apps map[string]*App `yaml:"apps"`
  21. Release *App `yaml:"release"`
  22. }
  23. type Build struct {
  24. Context *string `yaml:"context" validate:"dir"`
  25. Method *string `yaml:"method" validate:"required,oneof=pack docker registry"`
  26. Builder *string `yaml:"builder" validate:"required_if=Method pack"`
  27. Buildpacks []*string `yaml:"buildpacks"`
  28. Dockerfile *string `yaml:"dockerfile" validate:"required_if=Method docker"`
  29. Image *string `yaml:"image" validate:"required_if=Method registry"`
  30. }
  31. type App struct {
  32. Run *string `yaml:"run" validate:"required"`
  33. Config map[string]interface{} `yaml:"config"`
  34. Type *string `yaml:"type" validate:"oneof=web worker job"`
  35. }
  36. type SubdomainCreateOpts struct {
  37. k8sAgent *kubernetes.Agent
  38. dnsRepo repository.DNSRecordRepository
  39. powerDnsClient *powerdns.Client
  40. appRootDomain string
  41. stackName string
  42. }
  43. func parse(
  44. porterYaml []byte,
  45. imageInfo types.ImageInfo,
  46. config *config.Config,
  47. projectID uint,
  48. existingValues map[string]interface{},
  49. existingDependencies []*chart.Dependency,
  50. opts SubdomainCreateOpts,
  51. injectLauncher bool,
  52. ) (*chart.Chart, map[string]interface{}, map[string]interface{}, error) {
  53. parsed := &PorterStackYAML{}
  54. err := yaml.Unmarshal(porterYaml, parsed)
  55. if err != nil {
  56. return nil, nil, nil, fmt.Errorf("%s: %w", "error parsing porter.yaml", err)
  57. }
  58. values, err := buildStackValues(parsed, imageInfo, existingValues, opts, injectLauncher)
  59. if err != nil {
  60. return nil, nil, nil, fmt.Errorf("%s: %w", "error building values from porter.yaml", err)
  61. }
  62. convertedValues := convertMap(values).(map[string]interface{})
  63. chart, err := buildStackChart(parsed, config, projectID, existingDependencies)
  64. if err != nil {
  65. return nil, nil, nil, fmt.Errorf("%s: %w", "error building chart from porter.yaml", err)
  66. }
  67. // return the parsed release values for the release job chart, if they exist
  68. var releaseJobValues map[string]interface{}
  69. if parsed.Release != nil && parsed.Release.Run != nil {
  70. releaseJobValues = buildReleaseValues(parsed.Release, parsed.Env, imageInfo, injectLauncher)
  71. }
  72. return chart, convertedValues, releaseJobValues, nil
  73. }
  74. func buildStackValues(parsed *PorterStackYAML, imageInfo types.ImageInfo, existingValues map[string]interface{}, opts SubdomainCreateOpts, injectLauncher bool) (map[string]interface{}, error) {
  75. values := make(map[string]interface{})
  76. if parsed.Apps == nil {
  77. if existingValues == nil {
  78. return nil, fmt.Errorf("porter.yaml must contain at least one app, or release must exist and have values")
  79. }
  80. }
  81. for name, app := range parsed.Apps {
  82. appType := getType(name, app)
  83. defaultValues := getDefaultValues(app, parsed.Env, appType)
  84. convertedConfig := convertMap(app.Config).(map[string]interface{})
  85. helm_values := utils.DeepCoalesceValues(defaultValues, convertedConfig)
  86. // required to identify the chart type because of https://github.com/helm/helm/issues/9214
  87. helmName := getHelmName(name, appType)
  88. if existingValues != nil {
  89. if existingValues[helmName] != nil {
  90. existingValuesMap := existingValues[helmName].(map[string]interface{})
  91. helm_values = utils.DeepCoalesceValues(existingValuesMap, helm_values)
  92. }
  93. }
  94. err := createSubdomainIfRequired(helm_values, opts) // modifies helm_values to add subdomains if necessary
  95. if err != nil {
  96. return nil, err
  97. }
  98. // just in case this slips by
  99. if appType == "web" {
  100. if helm_values["ingress"] == nil {
  101. helm_values["ingress"] = map[string]interface{}{
  102. "enabled": false,
  103. }
  104. }
  105. }
  106. // prepend launcher if we need to
  107. if helm_values["container"] != nil {
  108. containerMap := helm_values["container"].(map[string]interface{})
  109. if containerMap["command"] != nil {
  110. command := containerMap["command"].(string)
  111. if injectLauncher && !strings.HasPrefix(command, "launcher") && !strings.HasPrefix(command, "/cnb/lifecycle/launcher") {
  112. containerMap["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", command)
  113. }
  114. }
  115. }
  116. values[helmName] = helm_values
  117. }
  118. // add back in the existing services that were not overwritten
  119. for k, v := range existingValues {
  120. if values[k] == nil {
  121. // make sure we prepend launcher to services that aren't specified in porter.yaml as well
  122. if existingServiceValues, ok := v.(map[string]interface{}); ok {
  123. if existingServiceValues["container"] != nil {
  124. containerMap := existingServiceValues["container"].(map[string]interface{})
  125. if containerMap["command"] != nil {
  126. command := containerMap["command"].(string)
  127. if injectLauncher && !strings.HasPrefix(command, "launcher") && !strings.HasPrefix(command, "/cnb/lifecycle/launcher") {
  128. containerMap["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", command)
  129. }
  130. }
  131. }
  132. }
  133. values[k] = v
  134. }
  135. }
  136. if imageInfo.Repository != "" && imageInfo.Tag != "" {
  137. values["global"] = map[string]interface{}{
  138. "image": map[string]interface{}{
  139. "repository": imageInfo.Repository,
  140. "tag": imageInfo.Tag,
  141. },
  142. }
  143. }
  144. return values, nil
  145. }
  146. func buildReleaseValues(release *App, env map[string]string, imageInfo types.ImageInfo, injectLauncher bool) map[string]interface{} {
  147. defaultValues := getDefaultValues(release, env, "job")
  148. convertedConfig := convertMap(release.Config).(map[string]interface{})
  149. helm_values := utils.DeepCoalesceValues(defaultValues, convertedConfig)
  150. if imageInfo.Repository != "" && imageInfo.Tag != "" {
  151. helm_values["image"] = map[string]interface{}{
  152. "repository": imageInfo.Repository,
  153. "tag": imageInfo.Tag,
  154. }
  155. }
  156. // prepend launcher if we need to
  157. if injectLauncher && release.Run != nil && !strings.HasPrefix(*release.Run, "launcher") && !strings.HasPrefix(*release.Run, "/cnb/lifecycle/launcher") {
  158. if helm_values["container"] == nil {
  159. helm_values["container"] = map[string]interface{}{}
  160. }
  161. helm_values["container"].(map[string]interface{})["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", *release.Run)
  162. }
  163. return helm_values
  164. }
  165. func getType(name string, app *App) string {
  166. if app.Type != nil {
  167. return *app.Type
  168. }
  169. if strings.Contains(name, "web") {
  170. return "web"
  171. }
  172. return "worker"
  173. }
  174. func getDefaultValues(app *App, env map[string]string, appType string) map[string]interface{} {
  175. var defaultValues map[string]interface{}
  176. var runCommand string
  177. if app.Run != nil {
  178. runCommand = *app.Run
  179. }
  180. defaultValues = map[string]interface{}{
  181. "container": map[string]interface{}{
  182. "command": runCommand,
  183. "env": map[string]interface{}{
  184. "normal": CopyEnv(env),
  185. },
  186. },
  187. }
  188. return defaultValues
  189. }
  190. func buildStackChart(parsed *PorterStackYAML, config *config.Config, projectID uint, existingDependencies []*chart.Dependency) (*chart.Chart, error) {
  191. deps := make([]*chart.Dependency, 0)
  192. for alias, app := range parsed.Apps {
  193. var appType string
  194. if existingDependencies != nil {
  195. for _, dep := range existingDependencies {
  196. // this condition checks that the dependency is of the form <alias>-web or <alias>-wkr or <alias>-job, meaning it already exists in the chart
  197. if strings.HasPrefix(dep.Alias, fmt.Sprintf("%s-", alias)) && (strings.HasSuffix(dep.Alias, "-web") || strings.HasSuffix(dep.Alias, "-wkr") || strings.HasSuffix(dep.Alias, "-job")) {
  198. appType = getChartTypeFromHelmName(dep.Alias)
  199. if appType == "" {
  200. return nil, fmt.Errorf("unable to determine type of existing dependency")
  201. }
  202. }
  203. }
  204. // this is a new app, so we need to get the type from the app name or type
  205. if appType == "" {
  206. appType = getType(alias, app)
  207. }
  208. } else {
  209. appType = getType(alias, app)
  210. }
  211. selectedRepo := config.ServerConf.DefaultApplicationHelmRepoURL
  212. selectedVersion, err := getLatestTemplateVersion(appType, config, projectID)
  213. if err != nil {
  214. return nil, err
  215. }
  216. helmName := getHelmName(alias, appType)
  217. deps = append(deps, &chart.Dependency{
  218. Name: appType,
  219. Alias: helmName,
  220. Version: selectedVersion,
  221. Repository: selectedRepo,
  222. })
  223. }
  224. // add in the existing dependencies that were not overwritten
  225. for _, dep := range existingDependencies {
  226. if !dependencyExists(deps, dep) {
  227. // have to repair the dependency name because of https://github.com/helm/helm/issues/9214
  228. if strings.HasSuffix(dep.Name, "-web") || strings.HasSuffix(dep.Name, "-wkr") || strings.HasSuffix(dep.Name, "-job") {
  229. dep.Name = getChartTypeFromHelmName(dep.Name)
  230. }
  231. deps = append(deps, dep)
  232. }
  233. }
  234. chart, err := createChartFromDependencies(deps)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return chart, nil
  239. }
  240. func dependencyExists(deps []*chart.Dependency, dep *chart.Dependency) bool {
  241. for _, d := range deps {
  242. if d.Alias == dep.Alias {
  243. return true
  244. }
  245. }
  246. return false
  247. }
  248. func createChartFromDependencies(deps []*chart.Dependency) (*chart.Chart, error) {
  249. metadata := &chart.Metadata{
  250. Name: "umbrella",
  251. Description: "Web application that is exposed to external traffic.",
  252. Version: "0.96.0",
  253. APIVersion: "v2",
  254. Home: "https://getporter.dev/",
  255. Icon: "https://user-images.githubusercontent.com/65516095/111255214-07d3da80-85ed-11eb-99e2-fddcbdb99bdb.png",
  256. Keywords: []string{
  257. "porter",
  258. "application",
  259. "service",
  260. "umbrella",
  261. },
  262. Type: "application",
  263. Dependencies: deps,
  264. }
  265. // create a new chart object with the metadata
  266. c := &chart.Chart{
  267. Metadata: metadata,
  268. }
  269. return c, nil
  270. }
  271. func getLatestTemplateVersion(templateName string, config *config.Config, projectID uint) (string, error) {
  272. repoIndex, err := loader.LoadRepoIndexPublic(config.ServerConf.DefaultApplicationHelmRepoURL)
  273. if err != nil {
  274. return "", fmt.Errorf("%s: %w", "unable to load porter chart repo", err)
  275. }
  276. templates := loader.RepoIndexToPorterChartList(repoIndex, config.ServerConf.DefaultApplicationHelmRepoURL)
  277. if err != nil {
  278. return "", fmt.Errorf("%s: %w", "unable to load porter chart list", err)
  279. }
  280. var version string
  281. // find the matching template name
  282. for _, template := range templates {
  283. if templateName == template.Name {
  284. version = template.Versions[0]
  285. break
  286. }
  287. }
  288. if version == "" {
  289. return "", fmt.Errorf("matching template version not found")
  290. }
  291. return version, nil
  292. }
  293. func convertMap(m interface{}) interface{} {
  294. switch m := m.(type) {
  295. case map[string]interface{}:
  296. for k, v := range m {
  297. m[k] = convertMap(v)
  298. }
  299. case map[interface{}]interface{}:
  300. result := map[string]interface{}{}
  301. for k, v := range m {
  302. result[k.(string)] = convertMap(v)
  303. }
  304. return result
  305. case []interface{}:
  306. for i, v := range m {
  307. m[i] = convertMap(v)
  308. }
  309. }
  310. return m
  311. }
  312. func CopyEnv(env map[string]string) map[string]interface{} {
  313. envCopy := make(map[string]interface{})
  314. if env == nil {
  315. return envCopy
  316. }
  317. for k, v := range env {
  318. if k == "" || v == "" {
  319. continue
  320. }
  321. envCopy[k] = v
  322. }
  323. return envCopy
  324. }
  325. func createSubdomainIfRequired(
  326. mergedValues map[string]interface{},
  327. opts SubdomainCreateOpts,
  328. ) error {
  329. // look for ingress.enabled and no custom domains set
  330. ingressMap, err := getNestedMap(mergedValues, "ingress")
  331. if err == nil {
  332. enabledVal, enabledExists := ingressMap["enabled"]
  333. if enabledExists {
  334. enabled, eOK := enabledVal.(bool)
  335. if eOK && enabled {
  336. // if custom domain, we don't need to create a subdomain
  337. customDomVal, customDomExists := ingressMap["custom_domain"]
  338. if customDomExists {
  339. customDomain, cOK := customDomVal.(bool)
  340. if cOK && customDomain {
  341. return nil
  342. }
  343. }
  344. // subdomain already exists, no need to create one
  345. if porterHosts, ok := ingressMap["porter_hosts"].([]interface{}); ok && len(porterHosts) > 0 {
  346. return nil
  347. }
  348. // in the case of ingress enabled but no custom domain, create subdomain
  349. dnsRecord, err := createDNSRecord(opts)
  350. if err != nil {
  351. return fmt.Errorf("error creating subdomain: %s", err.Error())
  352. }
  353. subdomain := dnsRecord.ExternalURL
  354. if ingressVal, ok := mergedValues["ingress"]; !ok {
  355. mergedValues["ingress"] = map[string]interface{}{
  356. "porter_hosts": []string{
  357. subdomain,
  358. },
  359. }
  360. } else {
  361. ingressValMap := ingressVal.(map[string]interface{})
  362. ingressValMap["porter_hosts"] = []string{
  363. subdomain,
  364. }
  365. }
  366. }
  367. }
  368. }
  369. return nil
  370. }
  371. func createDNSRecord(opts SubdomainCreateOpts) (*types.DNSRecord, error) {
  372. if opts.powerDnsClient == nil {
  373. return nil, fmt.Errorf("cannot create subdomain because powerdns client is nil")
  374. }
  375. endpoint, found, err := domain.GetNGINXIngressServiceIP(opts.k8sAgent.Clientset)
  376. if err != nil {
  377. return nil, err
  378. }
  379. if !found {
  380. return nil, fmt.Errorf("target cluster does not have nginx ingress")
  381. }
  382. createDomain := domain.CreateDNSRecordConfig{
  383. ReleaseName: opts.stackName,
  384. RootDomain: opts.appRootDomain,
  385. Endpoint: endpoint,
  386. }
  387. record := createDomain.NewDNSRecordForEndpoint()
  388. record, err = opts.dnsRepo.CreateDNSRecord(record)
  389. if err != nil {
  390. return nil, err
  391. }
  392. _record := domain.DNSRecord(*record)
  393. err = _record.CreateDomain(opts.powerDnsClient)
  394. if err != nil {
  395. return nil, err
  396. }
  397. return record.ToDNSRecordType(), nil
  398. }
  399. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  400. var res map[string]interface{}
  401. curr := obj
  402. for _, field := range fields {
  403. objField, ok := curr[field]
  404. if !ok {
  405. return nil, fmt.Errorf("%s not found", field)
  406. }
  407. res, ok = objField.(map[string]interface{})
  408. if !ok {
  409. return nil, fmt.Errorf("%s is not a nested object", field)
  410. }
  411. curr = res
  412. }
  413. return res, nil
  414. }
  415. func getHelmName(alias string, t string) string {
  416. var suffix string
  417. if t == "web" {
  418. suffix = "-web"
  419. } else if t == "worker" {
  420. suffix = "-wkr"
  421. } else if t == "job" {
  422. suffix = "-job"
  423. }
  424. return fmt.Sprintf("%s%s", alias, suffix)
  425. }
  426. func getChartTypeFromHelmName(name string) string {
  427. if strings.HasSuffix(name, "-web") {
  428. return "web"
  429. } else if strings.HasSuffix(name, "-wkr") {
  430. return "worker"
  431. } else if strings.HasSuffix(name, "-job") {
  432. return "job"
  433. }
  434. return ""
  435. }
  436. func attemptToGetImageInfoFromRelease(values map[string]interface{}) types.ImageInfo {
  437. imageInfo := types.ImageInfo{}
  438. if values == nil {
  439. return imageInfo
  440. }
  441. globalImage, err := getNestedMap(values, "global", "image")
  442. if err != nil {
  443. return imageInfo
  444. }
  445. repoVal, okRepo := globalImage["repository"]
  446. tagVal, okTag := globalImage["tag"]
  447. if okRepo && okTag {
  448. imageInfo.Repository = repoVal.(string)
  449. imageInfo.Tag = tagVal.(string)
  450. }
  451. return imageInfo
  452. }