parse.go 13 KB

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