parse.go 14 KB

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