parse.go 16 KB

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