parse.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. values[helmName] = helm_values
  107. }
  108. // add back in the existing services that were not overwritten
  109. for k, v := range existingValues {
  110. if values[k] == nil {
  111. values[k] = v
  112. }
  113. }
  114. // prepend launcher to all start commands if we need to
  115. for _, v := range values {
  116. if serviceValues, ok := v.(map[string]interface{}); ok {
  117. if serviceValues["container"] != nil {
  118. containerMap := serviceValues["container"].(map[string]interface{})
  119. if containerMap["command"] != nil {
  120. command := containerMap["command"].(string)
  121. if injectLauncher && !strings.HasPrefix(command, "launcher") && !strings.HasPrefix(command, "/cnb/lifecycle/launcher") {
  122. containerMap["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", command)
  123. }
  124. }
  125. }
  126. }
  127. }
  128. if imageInfo.Repository != "" && imageInfo.Tag != "" {
  129. values["global"] = map[string]interface{}{
  130. "image": map[string]interface{}{
  131. "repository": imageInfo.Repository,
  132. "tag": imageInfo.Tag,
  133. },
  134. }
  135. }
  136. return values, nil
  137. }
  138. func buildReleaseValues(release *App, env map[string]string, imageInfo types.ImageInfo, injectLauncher bool) map[string]interface{} {
  139. defaultValues := getDefaultValues(release, env, "job")
  140. convertedConfig := convertMap(release.Config).(map[string]interface{})
  141. helm_values := utils.DeepCoalesceValues(defaultValues, convertedConfig)
  142. if imageInfo.Repository != "" && imageInfo.Tag != "" {
  143. helm_values["image"] = map[string]interface{}{
  144. "repository": imageInfo.Repository,
  145. "tag": imageInfo.Tag,
  146. }
  147. }
  148. // prepend launcher if we need to
  149. if injectLauncher && release.Run != nil && !strings.HasPrefix(*release.Run, "launcher") && !strings.HasPrefix(*release.Run, "/cnb/lifecycle/launcher") {
  150. if helm_values["container"] == nil {
  151. helm_values["container"] = map[string]interface{}{}
  152. }
  153. helm_values["container"].(map[string]interface{})["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", *release.Run)
  154. }
  155. return helm_values
  156. }
  157. func getType(name string, app *App) string {
  158. if app.Type != nil {
  159. return *app.Type
  160. }
  161. if strings.Contains(name, "web") {
  162. return "web"
  163. }
  164. return "worker"
  165. }
  166. func getDefaultValues(app *App, env map[string]string, appType string) map[string]interface{} {
  167. var defaultValues map[string]interface{}
  168. var runCommand string
  169. if app.Run != nil {
  170. runCommand = *app.Run
  171. }
  172. defaultValues = map[string]interface{}{
  173. "container": map[string]interface{}{
  174. "command": runCommand,
  175. "env": map[string]interface{}{
  176. "normal": CopyEnv(env),
  177. },
  178. },
  179. }
  180. return defaultValues
  181. }
  182. func buildStackChart(parsed *PorterStackYAML, config *config.Config, projectID uint, existingDependencies []*chart.Dependency) (*chart.Chart, error) {
  183. deps := make([]*chart.Dependency, 0)
  184. for alias, app := range parsed.Apps {
  185. var appType string
  186. if existingDependencies != nil {
  187. for _, dep := range existingDependencies {
  188. // 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
  189. if strings.HasPrefix(dep.Alias, fmt.Sprintf("%s-", alias)) && (strings.HasSuffix(dep.Alias, "-web") || strings.HasSuffix(dep.Alias, "-wkr") || strings.HasSuffix(dep.Alias, "-job")) {
  190. appType = getChartTypeFromHelmName(dep.Alias)
  191. if appType == "" {
  192. return nil, fmt.Errorf("unable to determine type of existing dependency")
  193. }
  194. }
  195. }
  196. // this is a new app, so we need to get the type from the app name or type
  197. if appType == "" {
  198. appType = getType(alias, app)
  199. }
  200. } else {
  201. appType = getType(alias, app)
  202. }
  203. selectedRepo := config.ServerConf.DefaultApplicationHelmRepoURL
  204. selectedVersion, err := getLatestTemplateVersion(appType, config, projectID)
  205. if err != nil {
  206. return nil, err
  207. }
  208. helmName := getHelmName(alias, appType)
  209. deps = append(deps, &chart.Dependency{
  210. Name: appType,
  211. Alias: helmName,
  212. Version: selectedVersion,
  213. Repository: selectedRepo,
  214. })
  215. }
  216. // add in the existing dependencies that were not overwritten
  217. for _, dep := range existingDependencies {
  218. if !dependencyExists(deps, dep) {
  219. // have to repair the dependency name because of https://github.com/helm/helm/issues/9214
  220. if strings.HasSuffix(dep.Name, "-web") || strings.HasSuffix(dep.Name, "-wkr") || strings.HasSuffix(dep.Name, "-job") {
  221. dep.Name = getChartTypeFromHelmName(dep.Name)
  222. }
  223. deps = append(deps, dep)
  224. }
  225. }
  226. chart, err := createChartFromDependencies(deps)
  227. if err != nil {
  228. return nil, err
  229. }
  230. return chart, nil
  231. }
  232. func dependencyExists(deps []*chart.Dependency, dep *chart.Dependency) bool {
  233. for _, d := range deps {
  234. if d.Alias == dep.Alias {
  235. return true
  236. }
  237. }
  238. return false
  239. }
  240. func createChartFromDependencies(deps []*chart.Dependency) (*chart.Chart, error) {
  241. metadata := &chart.Metadata{
  242. Name: "umbrella",
  243. Description: "Web application that is exposed to external traffic.",
  244. Version: "0.96.0",
  245. APIVersion: "v2",
  246. Home: "https://getporter.dev/",
  247. Icon: "https://user-images.githubusercontent.com/65516095/111255214-07d3da80-85ed-11eb-99e2-fddcbdb99bdb.png",
  248. Keywords: []string{
  249. "porter",
  250. "application",
  251. "service",
  252. "umbrella",
  253. },
  254. Type: "application",
  255. Dependencies: deps,
  256. }
  257. // create a new chart object with the metadata
  258. c := &chart.Chart{
  259. Metadata: metadata,
  260. }
  261. return c, nil
  262. }
  263. func getLatestTemplateVersion(templateName string, config *config.Config, projectID uint) (string, error) {
  264. repoIndex, err := loader.LoadRepoIndexPublic(config.ServerConf.DefaultApplicationHelmRepoURL)
  265. if err != nil {
  266. return "", fmt.Errorf("%s: %w", "unable to load porter chart repo", err)
  267. }
  268. templates := loader.RepoIndexToPorterChartList(repoIndex, config.ServerConf.DefaultApplicationHelmRepoURL)
  269. if err != nil {
  270. return "", fmt.Errorf("%s: %w", "unable to load porter chart list", err)
  271. }
  272. var version string
  273. // find the matching template name
  274. for _, template := range templates {
  275. if templateName == template.Name {
  276. version = template.Versions[0]
  277. break
  278. }
  279. }
  280. if version == "" {
  281. return "", fmt.Errorf("matching template version not found")
  282. }
  283. return version, nil
  284. }
  285. func convertMap(m interface{}) interface{} {
  286. switch m := m.(type) {
  287. case map[string]interface{}:
  288. for k, v := range m {
  289. m[k] = convertMap(v)
  290. }
  291. case map[interface{}]interface{}:
  292. result := map[string]interface{}{}
  293. for k, v := range m {
  294. result[k.(string)] = convertMap(v)
  295. }
  296. return result
  297. case []interface{}:
  298. for i, v := range m {
  299. m[i] = convertMap(v)
  300. }
  301. }
  302. return m
  303. }
  304. func CopyEnv(env map[string]string) map[string]interface{} {
  305. envCopy := make(map[string]interface{})
  306. if env == nil {
  307. return envCopy
  308. }
  309. for k, v := range env {
  310. if k == "" || v == "" {
  311. continue
  312. }
  313. envCopy[k] = v
  314. }
  315. return envCopy
  316. }
  317. func createSubdomainIfRequired(
  318. mergedValues map[string]interface{},
  319. opts SubdomainCreateOpts,
  320. ) error {
  321. // look for ingress.enabled and no custom domains set
  322. ingressMap, err := getNestedMap(mergedValues, "ingress")
  323. if err == nil {
  324. enabledVal, enabledExists := ingressMap["enabled"]
  325. if enabledExists {
  326. enabled, eOK := enabledVal.(bool)
  327. if eOK && enabled {
  328. // if custom domain, we don't need to create a subdomain
  329. customDomVal, customDomExists := ingressMap["custom_domain"]
  330. if customDomExists {
  331. customDomain, cOK := customDomVal.(bool)
  332. if cOK && customDomain {
  333. return nil
  334. }
  335. }
  336. // subdomain already exists, no need to create one
  337. if porterHosts, ok := ingressMap["porter_hosts"].([]interface{}); ok && len(porterHosts) > 0 {
  338. return nil
  339. }
  340. // in the case of ingress enabled but no custom domain, create subdomain
  341. dnsRecord, err := createDNSRecord(opts)
  342. if err != nil {
  343. return fmt.Errorf("error creating subdomain: %s", err.Error())
  344. }
  345. subdomain := dnsRecord.ExternalURL
  346. if ingressVal, ok := mergedValues["ingress"]; !ok {
  347. mergedValues["ingress"] = map[string]interface{}{
  348. "porter_hosts": []string{
  349. subdomain,
  350. },
  351. }
  352. } else {
  353. ingressValMap := ingressVal.(map[string]interface{})
  354. ingressValMap["porter_hosts"] = []string{
  355. subdomain,
  356. }
  357. }
  358. }
  359. }
  360. }
  361. return nil
  362. }
  363. func createDNSRecord(opts SubdomainCreateOpts) (*types.DNSRecord, error) {
  364. if opts.powerDnsClient == nil {
  365. return nil, fmt.Errorf("cannot create subdomain because powerdns client is nil")
  366. }
  367. endpoint, found, err := domain.GetNGINXIngressServiceIP(opts.k8sAgent.Clientset)
  368. if err != nil {
  369. return nil, err
  370. }
  371. if !found {
  372. return nil, fmt.Errorf("target cluster does not have nginx ingress")
  373. }
  374. createDomain := domain.CreateDNSRecordConfig{
  375. ReleaseName: opts.stackName,
  376. RootDomain: opts.appRootDomain,
  377. Endpoint: endpoint,
  378. }
  379. record := createDomain.NewDNSRecordForEndpoint()
  380. record, err = opts.dnsRepo.CreateDNSRecord(record)
  381. if err != nil {
  382. return nil, err
  383. }
  384. _record := domain.DNSRecord(*record)
  385. err = _record.CreateDomain(opts.powerDnsClient)
  386. if err != nil {
  387. return nil, err
  388. }
  389. return record.ToDNSRecordType(), nil
  390. }
  391. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  392. var res map[string]interface{}
  393. curr := obj
  394. for _, field := range fields {
  395. objField, ok := curr[field]
  396. if !ok {
  397. return nil, fmt.Errorf("%s not found", field)
  398. }
  399. res, ok = objField.(map[string]interface{})
  400. if !ok {
  401. return nil, fmt.Errorf("%s is not a nested object", field)
  402. }
  403. curr = res
  404. }
  405. return res, nil
  406. }
  407. func getHelmName(alias string, t string) string {
  408. var suffix string
  409. if t == "web" {
  410. suffix = "-web"
  411. } else if t == "worker" {
  412. suffix = "-wkr"
  413. } else if t == "job" {
  414. suffix = "-job"
  415. }
  416. return fmt.Sprintf("%s%s", alias, suffix)
  417. }
  418. func getChartTypeFromHelmName(name string) string {
  419. if strings.HasSuffix(name, "-web") {
  420. return "web"
  421. } else if strings.HasSuffix(name, "-wkr") {
  422. return "worker"
  423. } else if strings.HasSuffix(name, "-job") {
  424. return "job"
  425. }
  426. return ""
  427. }
  428. func attemptToGetImageInfoFromRelease(values map[string]interface{}) types.ImageInfo {
  429. imageInfo := types.ImageInfo{}
  430. if values == nil {
  431. return imageInfo
  432. }
  433. globalImage, err := getNestedMap(values, "global", "image")
  434. if err != nil {
  435. return imageInfo
  436. }
  437. repoVal, okRepo := globalImage["repository"]
  438. tagVal, okTag := globalImage["tag"]
  439. if okRepo && okTag {
  440. imageInfo.Repository = repoVal.(string)
  441. imageInfo.Tag = tagVal.(string)
  442. }
  443. return imageInfo
  444. }