parse.go 13 KB

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