parse.go 14 KB

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