parse.go 12 KB

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