parse.go 16 KB

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