parse.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. package porter_app
  2. import (
  3. "context"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/api/types"
  9. porterAppUtils "github.com/porter-dev/porter/api/utils/porter_app"
  10. "github.com/porter-dev/porter/internal/helm/loader"
  11. "github.com/porter-dev/porter/internal/integrations/dns"
  12. "github.com/porter-dev/porter/internal/kubernetes"
  13. "github.com/porter-dev/porter/internal/kubernetes/domain"
  14. "github.com/porter-dev/porter/internal/kubernetes/environment_groups"
  15. "github.com/porter-dev/porter/internal/kubernetes/porter_app"
  16. "github.com/porter-dev/porter/internal/repository"
  17. "github.com/porter-dev/porter/internal/telemetry"
  18. "github.com/porter-dev/porter/internal/templater/utils"
  19. "github.com/stefanmcshane/helm/pkg/chart"
  20. "gopkg.in/yaml.v2"
  21. )
  22. type PorterStackYAML struct {
  23. Applications map[string]*Application `yaml:"applications" validate:"required_without=Services Apps"`
  24. Version *string `yaml:"version"`
  25. Build *Build `yaml:"build"`
  26. Env map[string]string `yaml:"env"`
  27. SyncedEnv []*SyncedEnvSection `yaml:"synced_env"`
  28. Apps map[string]*Service `yaml:"apps" validate:"required_without=Applications Services"`
  29. Services map[string]*Service `yaml:"services" validate:"required_without=Applications Apps"`
  30. Release *Service `yaml:"release"`
  31. }
  32. type Application struct {
  33. Services map[string]*Service `yaml:"services" validate:"required"`
  34. Build *Build `yaml:"build"`
  35. Env map[string]string `yaml:"env"`
  36. Release *Service `yaml:"release"`
  37. }
  38. type Build struct {
  39. Context *string `yaml:"context" validate:"dir"`
  40. Method *string `yaml:"method" validate:"required,oneof=pack docker registry"`
  41. Builder *string `yaml:"builder" validate:"required_if=Method pack"`
  42. Buildpacks []*string `yaml:"buildpacks"`
  43. Dockerfile *string `yaml:"dockerfile" validate:"required_if=Method docker"`
  44. Image *string `yaml:"image" validate:"required_if=Method registry"`
  45. }
  46. type Service struct {
  47. Run *string `yaml:"run"`
  48. Config map[string]interface{} `yaml:"config"`
  49. Type *string `yaml:"type" validate:"required, oneof=web worker job"`
  50. }
  51. type SyncedEnvSection struct {
  52. Name string `json:"name" yaml:"name"`
  53. Version uint `json:"version" yaml:"version"`
  54. Keys []SyncedEnvSectionKey `json:"keys" yaml:"keys"`
  55. }
  56. type SyncedEnvSectionKey struct {
  57. Name string `json:"name" yaml:"name"`
  58. Secret bool `json:"secret" yaml:"secret"`
  59. }
  60. type SubdomainCreateOpts struct {
  61. k8sAgent *kubernetes.Agent
  62. dnsRepo repository.DNSRecordRepository
  63. dnsClient *dns.Client
  64. appRootDomain string
  65. stackName string
  66. }
  67. type ParseConf struct {
  68. // PorterAppName is the name of the porter app
  69. PorterAppName string
  70. // PorterYaml is the raw porter yaml which is used to build the values + chart for helm upgrade
  71. PorterYaml []byte
  72. // ImageInfo contains the repository and tag of the image to use for the helm upgrade. Kept separate from the PorterYaml because the image info
  73. // is stored in the 'global' key of the values, which is not part of the porter yaml
  74. ImageInfo types.ImageInfo
  75. // ServerConfig is the server conf, used to find the default helm repo
  76. ServerConfig *config.Config
  77. // ProjectID
  78. ProjectID uint
  79. // UserUpdate used for synced env groups
  80. UserUpdate bool
  81. // EnvGroups used for synced env groups
  82. EnvGroups []string
  83. // EnvironmentGroups are used for syncing environment groups using ConfigMaps and Secrets from porter-env-groups namespace. This should be used instead of EnvGroups
  84. EnvironmentGroups []string
  85. // Namespace used for synced env groups
  86. Namespace string
  87. // ExistingHelmValues is the existing values for the helm release, if it exists
  88. ExistingHelmValues map[string]interface{}
  89. // ExistingChartDependencies is the existing dependencies for the helm release, if it exists
  90. ExistingChartDependencies []*chart.Dependency
  91. // SubdomainCreateOpts contains the necessary information to create a subdomain if necessary
  92. SubdomainCreateOpts SubdomainCreateOpts
  93. // InjectLauncherToStartCommand is a flag to determine whether to prepend the launcher to the start command
  94. InjectLauncherToStartCommand bool
  95. // ShouldValidateHelmValues is a flag to determine whether to validate helm values
  96. ShouldValidateHelmValues bool
  97. // FullHelmValues if provided, override anything specified in porter.yaml. Used as an escape hatch for support
  98. FullHelmValues string
  99. // AddCustomNodeSelector is a flag to determine whether to add porter.run/workload-kind: application to the nodeselector attribute of the helm values
  100. AddCustomNodeSelector bool
  101. }
  102. func parse(ctx context.Context, conf ParseConf) (*chart.Chart, map[string]interface{}, map[string]interface{}, error) {
  103. ctx, span := telemetry.NewSpan(ctx, "parse-porter-yaml")
  104. defer span.End()
  105. parsed := &PorterStackYAML{}
  106. if conf.FullHelmValues != "" {
  107. parsedHelmValues, err := convertHelmValuesToPorterYaml(conf.FullHelmValues)
  108. if err != nil {
  109. err = telemetry.Error(ctx, span, err, "error parsing raw helm values")
  110. return nil, nil, nil, err
  111. }
  112. parsed = parsedHelmValues
  113. } else {
  114. err := yaml.Unmarshal(conf.PorterYaml, parsed)
  115. if err != nil {
  116. err = telemetry.Error(ctx, span, err, "error parsing porter.yaml")
  117. return nil, nil, nil, err
  118. }
  119. }
  120. synced_env := make([]*SyncedEnvSection, 0)
  121. for i := range conf.EnvGroups {
  122. cm, _, err := conf.SubdomainCreateOpts.k8sAgent.GetLatestVersionedConfigMap(conf.EnvGroups[i], conf.Namespace)
  123. if err != nil {
  124. err = telemetry.Error(ctx, span, err, "error getting latest versioned config map")
  125. return nil, nil, nil, err
  126. }
  127. versionStr, ok := cm.ObjectMeta.Labels["version"]
  128. if !ok {
  129. err = telemetry.Error(ctx, span, nil, "error extracting version from config map")
  130. return nil, nil, nil, err
  131. }
  132. versionInt, err := strconv.Atoi(versionStr)
  133. if err != nil {
  134. err = telemetry.Error(ctx, span, err, "error converting version to int")
  135. return nil, nil, nil, err
  136. }
  137. version := uint(versionInt)
  138. newSection := &SyncedEnvSection{
  139. Name: conf.EnvGroups[i],
  140. Version: version,
  141. }
  142. newSectionKeys := make([]SyncedEnvSectionKey, 0)
  143. for key, val := range cm.Data {
  144. newSectionKeys = append(newSectionKeys, SyncedEnvSectionKey{
  145. Name: key,
  146. Secret: strings.Contains(val, "PORTERSECRET"),
  147. })
  148. }
  149. newSection.Keys = newSectionKeys
  150. synced_env = append(synced_env, newSection)
  151. }
  152. if parsed.Apps != nil && parsed.Services != nil {
  153. err := telemetry.Error(ctx, span, nil, "'apps' and 'services' are synonymous but both were defined")
  154. return nil, nil, nil, err
  155. }
  156. var services map[string]*Service
  157. if parsed.Apps != nil {
  158. services = parsed.Apps
  159. }
  160. if parsed.Services != nil {
  161. services = parsed.Services
  162. }
  163. for serviceName := range services {
  164. services[serviceName] = addLabelsToService(services[serviceName], conf.EnvironmentGroups, porter_app.LabelKey_PorterApplication)
  165. }
  166. application := &Application{
  167. Env: parsed.Env,
  168. Services: services,
  169. Build: parsed.Build,
  170. Release: parsed.Release,
  171. }
  172. values, err := buildUmbrellaChartValues(ctx, application, synced_env, conf.ImageInfo, conf.ExistingHelmValues, conf.SubdomainCreateOpts, conf.InjectLauncherToStartCommand, conf.ShouldValidateHelmValues, conf.UserUpdate, conf.Namespace, conf.AddCustomNodeSelector)
  173. if err != nil {
  174. err = telemetry.Error(ctx, span, err, "error building values")
  175. return nil, nil, nil, err
  176. }
  177. convertedValues, ok := convertMap(values).(map[string]interface{})
  178. if !ok {
  179. err = telemetry.Error(ctx, span, nil, "error converting values")
  180. return nil, nil, nil, err
  181. }
  182. umbrellaChart, err := buildUmbrellaChart(application, conf.ServerConfig, conf.ProjectID, conf.ExistingChartDependencies)
  183. if err != nil {
  184. err = telemetry.Error(ctx, span, err, "error building umbrella chart")
  185. return nil, nil, nil, err
  186. }
  187. // return the parsed release values for the release job chart, if they exist
  188. var preDeployJobValues map[string]interface{}
  189. if application.Release != nil && application.Release.Run != nil {
  190. application.Release = addLabelsToService(application.Release, conf.EnvironmentGroups, porter_app.LabelKey_PorterApplicationPreDeploy)
  191. preDeployJobValues = buildPreDeployJobChartValues(application.Release, application.Env, synced_env, conf.ImageInfo, conf.InjectLauncherToStartCommand, conf.ExistingHelmValues, porterAppUtils.PredeployJobNameFromPorterAppName(conf.PorterAppName), conf.UserUpdate, conf.AddCustomNodeSelector)
  192. }
  193. return umbrellaChart, convertedValues, preDeployJobValues, nil
  194. }
  195. func buildUmbrellaChartValues(
  196. ctx context.Context,
  197. application *Application,
  198. syncedEnv []*SyncedEnvSection,
  199. imageInfo types.ImageInfo,
  200. existingValues map[string]interface{},
  201. opts SubdomainCreateOpts,
  202. injectLauncher bool,
  203. shouldValidateHelmValues bool,
  204. userUpdate bool,
  205. namespace string,
  206. addCustomNodeSelector bool,
  207. ) (map[string]interface{}, error) {
  208. values := make(map[string]interface{})
  209. if application.Services == nil {
  210. if existingValues == nil {
  211. return nil, fmt.Errorf("porter.yaml must contain at least one service, or pre-deploy must exist and have values")
  212. }
  213. }
  214. for name, service := range application.Services {
  215. serviceType := getType(name, service)
  216. defaultValues := getDefaultValues(service, application.Env, syncedEnv, serviceType, existingValues, name, userUpdate, addCustomNodeSelector)
  217. convertedConfig := convertMap(service.Config).(map[string]interface{})
  218. helm_values := utils.DeepCoalesceValues(defaultValues, convertedConfig)
  219. // required to identify the chart type because of https://github.com/helm/helm/issues/9214
  220. helmName := getHelmName(name, serviceType)
  221. if existingValues != nil {
  222. if existingValues[helmName] != nil {
  223. existingValuesMap := existingValues[helmName].(map[string]interface{})
  224. helm_values = utils.DeepCoalesceValues(existingValuesMap, helm_values)
  225. }
  226. }
  227. validateErr := validateHelmValues(helm_values, shouldValidateHelmValues, serviceType)
  228. if validateErr != "" {
  229. return nil, fmt.Errorf("error validating service \"%s\": %s", name, validateErr)
  230. }
  231. err := syncEnvironmentGroupToNamespaceIfLabelsExist(ctx, opts.k8sAgent, service, namespace)
  232. if err != nil {
  233. return nil, fmt.Errorf("error syncing environment group to namespace: %w", err)
  234. }
  235. err = createSubdomainIfRequired(helm_values, opts) // modifies helm_values to add subdomains if necessary
  236. if err != nil {
  237. return nil, err
  238. }
  239. // just in case this slips by
  240. if serviceType == "web" {
  241. if helm_values["ingress"] == nil {
  242. helm_values["ingress"] = map[string]interface{}{
  243. "enabled": false,
  244. }
  245. }
  246. }
  247. values[helmName] = helm_values
  248. }
  249. // add back in the existing services that were not overwritten
  250. for k, v := range existingValues {
  251. if values[k] == nil {
  252. values[k] = v
  253. }
  254. }
  255. // prepend launcher to all start commands if we need to
  256. for _, v := range values {
  257. if serviceValues, ok := v.(map[string]interface{}); ok {
  258. if serviceValues["container"] != nil {
  259. containerMap := serviceValues["container"].(map[string]interface{})
  260. if containerMap["command"] != nil {
  261. command := containerMap["command"].(string)
  262. if injectLauncher && !strings.HasPrefix(command, "launcher") && !strings.HasPrefix(command, "/cnb/lifecycle/launcher") {
  263. containerMap["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", command)
  264. }
  265. }
  266. }
  267. }
  268. }
  269. values["global"] = map[string]interface{}{
  270. "image": map[string]interface{}{
  271. "repository": imageInfo.Repository,
  272. "tag": imageInfo.Tag,
  273. },
  274. }
  275. return values, nil
  276. }
  277. // syncEnvironmentGroupToNamespaceIfLabelsExist will sync the latest version of the environment group to the target namespace if the service has the appropriate label.
  278. func syncEnvironmentGroupToNamespaceIfLabelsExist(ctx context.Context, agent *kubernetes.Agent, service *Service, targetNamespace string) error {
  279. var linkedGroupNames string
  280. // patchwork because we are not consistent with the type of labels
  281. if labels, ok := service.Config["labels"].(map[string]any); ok {
  282. if linkedGroup, ok := labels[environment_groups.LabelKey_LinkedEnvironmentGroup].(string); ok {
  283. linkedGroupNames = linkedGroup
  284. }
  285. }
  286. if labels, ok := service.Config["labels"].(map[string]string); ok {
  287. if linkedGroup, ok := labels[environment_groups.LabelKey_LinkedEnvironmentGroup]; ok {
  288. linkedGroupNames = linkedGroup
  289. }
  290. }
  291. for _, linkedGroupName := range strings.Split(linkedGroupNames, ".") {
  292. inp := environment_groups.SyncLatestVersionToNamespaceInput{
  293. BaseEnvironmentGroupName: linkedGroupName,
  294. TargetNamespace: targetNamespace,
  295. }
  296. syncedEnvironment, err := environment_groups.SyncLatestVersionToNamespace(ctx, agent, inp)
  297. if err != nil {
  298. return fmt.Errorf("error syncing environment group: %w", err)
  299. }
  300. if syncedEnvironment.EnvironmentGroupVersionedName != "" {
  301. if service.Config["configMapRefs"] == nil {
  302. service.Config["configMapRefs"] = []string{}
  303. }
  304. if service.Config["secretRefs"] == nil {
  305. service.Config["secretRefs"] = []string{}
  306. }
  307. switch service.Config["configMapRefs"].(type) {
  308. case []string:
  309. service.Config["configMapRefs"] = append(service.Config["configMapRefs"].([]string), syncedEnvironment.EnvironmentGroupVersionedName)
  310. case []any:
  311. service.Config["configMapRefs"] = append(service.Config["configMapRefs"].([]any), syncedEnvironment.EnvironmentGroupVersionedName)
  312. }
  313. switch service.Config["configMapRefs"].(type) {
  314. case []string:
  315. service.Config["secretRefs"] = append(service.Config["secretRefs"].([]string), syncedEnvironment.EnvironmentGroupVersionedName)
  316. case []any:
  317. service.Config["secretRefs"] = append(service.Config["secretRefs"].([]any), syncedEnvironment.EnvironmentGroupVersionedName)
  318. }
  319. }
  320. }
  321. return nil
  322. }
  323. // we can add to this function up later or use an alternative
  324. func validateHelmValues(values map[string]interface{}, shouldValidateHelmValues bool, appType string) string {
  325. if shouldValidateHelmValues {
  326. // validate port for web services
  327. if appType == "web" {
  328. containerMap, err := getNestedMap(values, "container")
  329. if err != nil {
  330. return "error checking port: misformatted values"
  331. } else {
  332. portVal, portExists := containerMap["port"]
  333. if portExists {
  334. portStr, pOK := portVal.(string)
  335. if !pOK {
  336. return "error checking port: no port in container"
  337. }
  338. port, err := strconv.Atoi(portStr)
  339. if err != nil || port < 1024 || port > 65535 {
  340. return "port must be a number between 1024 and 65535"
  341. }
  342. } else {
  343. return "port must be specified for web services"
  344. }
  345. }
  346. }
  347. }
  348. return ""
  349. }
  350. func buildPreDeployJobChartValues(release *Service, env map[string]string, synced_env []*SyncedEnvSection, imageInfo types.ImageInfo, injectLauncher bool, existingValues map[string]interface{}, name string, userUpdate bool, addCustomNodeSelector bool) map[string]interface{} {
  351. defaultValues := getDefaultValues(release, env, synced_env, "job", existingValues, name+"-r", userUpdate, addCustomNodeSelector)
  352. convertedConfig := convertMap(release.Config).(map[string]interface{})
  353. helm_values := utils.DeepCoalesceValues(defaultValues, convertedConfig)
  354. if imageInfo.Repository != "" && imageInfo.Tag != "" {
  355. helm_values["image"] = map[string]interface{}{
  356. "repository": imageInfo.Repository,
  357. "tag": imageInfo.Tag,
  358. }
  359. }
  360. // prepend launcher if we need to
  361. if helm_values["container"] != nil {
  362. containerMap := helm_values["container"].(map[string]interface{})
  363. if containerMap["command"] != nil {
  364. command := containerMap["command"].(string)
  365. if injectLauncher && !strings.HasPrefix(command, "launcher") && !strings.HasPrefix(command, "/cnb/lifecycle/launcher") {
  366. containerMap["command"] = fmt.Sprintf("/cnb/lifecycle/launcher %s", command)
  367. }
  368. }
  369. }
  370. return helm_values
  371. }
  372. func getType(name string, service *Service) string {
  373. if service.Type != nil {
  374. return *service.Type
  375. }
  376. if strings.Contains(name, "web") {
  377. return "web"
  378. }
  379. if strings.Contains(name, "job") {
  380. return "job"
  381. }
  382. return "worker"
  383. }
  384. func getDefaultValues(service *Service, env map[string]string, synced_env []*SyncedEnvSection, appType string, existingValues map[string]interface{}, name string, userUpdate bool, addCustomNodeSelector bool) map[string]interface{} {
  385. var defaultValues map[string]interface{}
  386. var runCommand string
  387. if service.Run != nil {
  388. runCommand = *service.Run
  389. }
  390. var syncedEnvs []map[string]interface{}
  391. envConf, err := getStacksNestedMap(existingValues, name+"-"+appType, "container", "env")
  392. if !userUpdate && err == nil {
  393. syncedEnvs = envConf
  394. } else {
  395. syncedEnvs = deconstructSyncedEnvs(synced_env, env)
  396. }
  397. defaultValues = map[string]interface{}{
  398. "container": map[string]interface{}{
  399. "command": runCommand,
  400. "env": map[string]interface{}{
  401. "normal": CopyEnv(env),
  402. "synced": syncedEnvs,
  403. },
  404. },
  405. "nodeSelector": map[string]interface{}{},
  406. }
  407. if addCustomNodeSelector {
  408. defaultValues["nodeSelector"] = map[string]interface{}{
  409. "porter.run/workload-kind": "application",
  410. }
  411. }
  412. return defaultValues
  413. }
  414. func deconstructSyncedEnvs(synced_env []*SyncedEnvSection, env map[string]string) []map[string]interface{} {
  415. synced := make([]map[string]interface{}, 0)
  416. for _, group := range synced_env {
  417. keys := make([]map[string]interface{}, 0)
  418. for _, key := range group.Keys {
  419. if _, exists := env[key.Name]; !exists {
  420. // Only include keys not present in env
  421. keys = append(keys, map[string]interface{}{
  422. "name": key.Name,
  423. "secret": key.Secret,
  424. })
  425. }
  426. }
  427. syncedGroup := map[string]interface{}{
  428. "keys": keys,
  429. "name": group.Name,
  430. "version": group.Version,
  431. }
  432. synced = append(synced, syncedGroup)
  433. }
  434. return synced
  435. }
  436. func buildUmbrellaChart(application *Application, config *config.Config, projectID uint, existingDependencies []*chart.Dependency) (*chart.Chart, error) {
  437. deps := make([]*chart.Dependency, 0)
  438. for alias, service := range application.Services {
  439. var serviceType string
  440. if existingDependencies != nil {
  441. for _, dep := range existingDependencies {
  442. // 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
  443. if strings.HasPrefix(dep.Alias, fmt.Sprintf("%s-", alias)) && (strings.HasSuffix(dep.Alias, "-web") || strings.HasSuffix(dep.Alias, "-wkr") || strings.HasSuffix(dep.Alias, "-job")) {
  444. serviceType = getChartTypeFromHelmName(dep.Alias)
  445. if serviceType == "" {
  446. return nil, fmt.Errorf("unable to determine type of existing dependency")
  447. }
  448. }
  449. }
  450. // this is a new app, so we need to get the type from the app name or type
  451. if serviceType == "" {
  452. serviceType = getType(alias, service)
  453. }
  454. } else {
  455. serviceType = getType(alias, service)
  456. }
  457. selectedRepo := config.ServerConf.DefaultApplicationHelmRepoURL
  458. selectedVersion, err := getLatestTemplateVersion(serviceType, config, projectID)
  459. if err != nil {
  460. return nil, err
  461. }
  462. helmName := getHelmName(alias, serviceType)
  463. deps = append(deps, &chart.Dependency{
  464. Name: serviceType,
  465. Alias: helmName,
  466. Version: selectedVersion,
  467. Repository: selectedRepo,
  468. })
  469. }
  470. // add in the existing dependencies that were not overwritten
  471. for _, dep := range existingDependencies {
  472. if !dependencyExists(deps, dep) {
  473. // have to repair the dependency name because of https://github.com/helm/helm/issues/9214
  474. if strings.HasSuffix(dep.Name, "-web") || strings.HasSuffix(dep.Name, "-wkr") || strings.HasSuffix(dep.Name, "-job") {
  475. dep.Name = getChartTypeFromHelmName(dep.Name)
  476. if dep.Name == "" {
  477. return nil, fmt.Errorf("unable to determine type of existing dependency")
  478. }
  479. version, err := getLatestTemplateVersion(dep.Name, config, projectID)
  480. if err != nil {
  481. return nil, err
  482. }
  483. dep.Version = version
  484. }
  485. deps = append(deps, dep)
  486. }
  487. }
  488. chart, err := createChartFromDependencies(deps)
  489. if err != nil {
  490. return nil, err
  491. }
  492. return chart, nil
  493. }
  494. func dependencyExists(deps []*chart.Dependency, dep *chart.Dependency) bool {
  495. for _, d := range deps {
  496. if d.Alias == dep.Alias {
  497. return true
  498. }
  499. }
  500. return false
  501. }
  502. func createChartFromDependencies(deps []*chart.Dependency) (*chart.Chart, error) {
  503. metadata := &chart.Metadata{
  504. Name: "umbrella",
  505. Description: "Web application that is exposed to external traffic.",
  506. Version: "0.96.0",
  507. APIVersion: "v2",
  508. Home: "https://getporter.dev/",
  509. Icon: "https://user-images.githubusercontent.com/65516095/111255214-07d3da80-85ed-11eb-99e2-fddcbdb99bdb.png",
  510. Keywords: []string{
  511. "porter",
  512. "application",
  513. "service",
  514. "umbrella",
  515. },
  516. Type: "application",
  517. Dependencies: deps,
  518. }
  519. // create a new chart object with the metadata
  520. c := &chart.Chart{
  521. Metadata: metadata,
  522. }
  523. return c, nil
  524. }
  525. func getLatestTemplateVersion(templateName string, config *config.Config, projectID uint) (string, error) {
  526. repoIndex, err := loader.LoadRepoIndexPublic(config.ServerConf.DefaultApplicationHelmRepoURL)
  527. if err != nil {
  528. return "", fmt.Errorf("%s: %w", "unable to load porter chart repo", err)
  529. }
  530. templates := loader.RepoIndexToPorterChartList(repoIndex, config.ServerConf.DefaultApplicationHelmRepoURL)
  531. if err != nil {
  532. return "", fmt.Errorf("%s: %w", "unable to load porter chart list", err)
  533. }
  534. var version string
  535. // find the matching template name
  536. for _, template := range templates {
  537. if templateName == template.Name {
  538. version = template.Versions[0]
  539. break
  540. }
  541. }
  542. if version == "" {
  543. return "", fmt.Errorf("matching template version not found")
  544. }
  545. return version, nil
  546. }
  547. func convertMap(m interface{}) interface{} {
  548. switch m := m.(type) {
  549. case map[string]interface{}:
  550. for k, v := range m {
  551. m[k] = convertMap(v)
  552. }
  553. case map[string]string:
  554. result := map[string]interface{}{}
  555. for k, v := range m {
  556. result[k] = v
  557. }
  558. return result
  559. case map[interface{}]interface{}:
  560. result := map[string]interface{}{}
  561. for k, v := range m {
  562. result[k.(string)] = convertMap(v)
  563. }
  564. return result
  565. case []interface{}:
  566. for i, v := range m {
  567. m[i] = convertMap(v)
  568. }
  569. }
  570. return m
  571. }
  572. func CopyEnv(env map[string]string) map[string]interface{} {
  573. envCopy := make(map[string]interface{})
  574. if env == nil {
  575. return envCopy
  576. }
  577. for k, v := range env {
  578. if k == "" || v == "" {
  579. continue
  580. }
  581. envCopy[k] = v
  582. }
  583. return envCopy
  584. }
  585. func createSubdomainIfRequired(
  586. mergedValues map[string]interface{},
  587. opts SubdomainCreateOpts,
  588. ) error {
  589. // look for ingress.enabled and no custom domains set
  590. ingressMap, err := getNestedMap(mergedValues, "ingress")
  591. if err == nil {
  592. enabledVal, enabledExists := ingressMap["enabled"]
  593. if enabledExists {
  594. enabled, eOK := enabledVal.(bool)
  595. if eOK && enabled {
  596. // if custom domain, we don't need to create a subdomain
  597. customDomVal, customDomExists := ingressMap["custom_domain"]
  598. if customDomExists {
  599. customDomain, cOK := customDomVal.(bool)
  600. if cOK && customDomain {
  601. return nil
  602. }
  603. }
  604. // subdomain already exists, no need to create one
  605. if porterHosts, ok := ingressMap["porter_hosts"].([]interface{}); ok && len(porterHosts) > 0 {
  606. return nil
  607. }
  608. // in the case of ingress enabled but no custom domain, create subdomain
  609. dnsRecord, err := createDNSRecord(opts)
  610. if err != nil {
  611. return fmt.Errorf("error creating subdomain: %s", err.Error())
  612. }
  613. subdomain := dnsRecord.ExternalURL
  614. if ingressVal, ok := mergedValues["ingress"]; !ok {
  615. mergedValues["ingress"] = map[string]interface{}{
  616. "porter_hosts": []string{
  617. subdomain,
  618. },
  619. }
  620. } else {
  621. ingressValMap := ingressVal.(map[string]interface{})
  622. ingressValMap["porter_hosts"] = []string{
  623. subdomain,
  624. }
  625. }
  626. }
  627. }
  628. }
  629. return nil
  630. }
  631. func createDNSRecord(opts SubdomainCreateOpts) (*types.DNSRecord, error) {
  632. if opts.dnsClient == nil {
  633. return nil, fmt.Errorf("cannot create subdomain because dns client is nil")
  634. }
  635. endpoint, found, err := domain.GetNGINXIngressServiceIP(opts.k8sAgent.Clientset)
  636. if err != nil {
  637. return nil, err
  638. }
  639. if !found {
  640. return nil, fmt.Errorf("target cluster does not have nginx ingress")
  641. }
  642. createDomain := domain.CreateDNSRecordConfig{
  643. ReleaseName: opts.stackName,
  644. RootDomain: opts.appRootDomain,
  645. Endpoint: endpoint,
  646. }
  647. record := createDomain.NewDNSRecordForEndpoint()
  648. record, err = opts.dnsRepo.CreateDNSRecord(record)
  649. if err != nil {
  650. return nil, err
  651. }
  652. _record := domain.DNSRecord(*record)
  653. err = _record.CreateDomain(opts.dnsClient)
  654. if err != nil {
  655. return nil, err
  656. }
  657. return record.ToDNSRecordType(), nil
  658. }
  659. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  660. var res map[string]interface{}
  661. curr := obj
  662. for _, field := range fields {
  663. objField, ok := curr[field]
  664. if !ok {
  665. return nil, fmt.Errorf("%s not found", field)
  666. }
  667. res, ok = objField.(map[string]interface{})
  668. if !ok {
  669. return nil, fmt.Errorf("%s is not a nested object", field)
  670. }
  671. curr = res
  672. }
  673. return res, nil
  674. }
  675. func getHelmName(alias string, t string) string {
  676. var suffix string
  677. if t == "web" {
  678. suffix = "-web"
  679. } else if t == "worker" {
  680. suffix = "-wkr"
  681. } else if t == "job" {
  682. suffix = "-job"
  683. }
  684. return fmt.Sprintf("%s%s", alias, suffix)
  685. }
  686. func getChartTypeFromHelmName(name string) string {
  687. if strings.HasSuffix(name, "-web") {
  688. return "web"
  689. } else if strings.HasSuffix(name, "-wkr") {
  690. return "worker"
  691. } else if strings.HasSuffix(name, "-job") {
  692. return "job"
  693. }
  694. return ""
  695. }
  696. func getServiceNameAndTypeFromHelmName(name string) (string, string) {
  697. if strings.HasSuffix(name, "-web") {
  698. return strings.TrimSuffix(name, "-web"), "web"
  699. } else if strings.HasSuffix(name, "-wkr") {
  700. return strings.TrimSuffix(name, "-wkr"), "worker"
  701. } else if strings.HasSuffix(name, "-job") {
  702. return strings.TrimSuffix(name, "-job"), "job"
  703. }
  704. return "", ""
  705. }
  706. func attemptToGetImageInfoFromRelease(values map[string]interface{}) types.ImageInfo {
  707. imageInfo := types.ImageInfo{}
  708. if values == nil {
  709. return imageInfo
  710. }
  711. globalImage, err := getNestedMap(values, "global", "image")
  712. if err != nil {
  713. return imageInfo
  714. }
  715. repoVal, okRepo := globalImage["repository"]
  716. tagVal, okTag := globalImage["tag"]
  717. if okRepo && okTag {
  718. imageInfo.Repository = repoVal.(string)
  719. imageInfo.Tag = tagVal.(string)
  720. }
  721. return imageInfo
  722. }
  723. func attemptToGetImageInfoFromFullHelmValues(fullHelmValues string) (types.ImageInfo, error) {
  724. imageInfo := types.ImageInfo{}
  725. var values map[string]interface{}
  726. err := yaml.Unmarshal([]byte(fullHelmValues), &values)
  727. if err != nil {
  728. return imageInfo, fmt.Errorf("error unmarshaling full helm values to read image info: %w", err)
  729. }
  730. convertedValues := convertMap(values).(map[string]interface{})
  731. return attemptToGetImageInfoFromRelease(convertedValues), nil
  732. }
  733. func getStacksNestedMap(obj map[string]interface{}, fields ...string) ([]map[string]interface{}, error) {
  734. var res map[string]interface{}
  735. curr := obj
  736. for _, field := range fields {
  737. objField, ok := curr[field]
  738. if !ok {
  739. return nil, fmt.Errorf("%s not found", field)
  740. }
  741. res, ok = objField.(map[string]interface{})
  742. if !ok {
  743. return nil, fmt.Errorf("%s is not a nested object", field)
  744. }
  745. curr = res
  746. }
  747. syncedInterface, ok := curr["synced"]
  748. if !ok {
  749. return nil, fmt.Errorf("synced not found")
  750. }
  751. synced, ok := syncedInterface.([]interface{})
  752. if !ok {
  753. return nil, fmt.Errorf("synced is not a slice of interface{}")
  754. }
  755. result := make([]map[string]interface{}, len(synced))
  756. for i, v := range synced {
  757. mapElement, ok := v.(map[string]interface{})
  758. if !ok {
  759. return nil, fmt.Errorf("element %d in synced is not a map[string]interface{}", i)
  760. }
  761. result[i] = mapElement
  762. }
  763. return result, nil
  764. }
  765. func convertHelmValuesToPorterYaml(helmValues string) (*PorterStackYAML, error) {
  766. var values map[string]interface{}
  767. err := yaml.Unmarshal([]byte(helmValues), &values)
  768. if err != nil {
  769. return nil, err
  770. }
  771. services := make(map[string]*Service)
  772. for k, v := range values {
  773. if k == "global" {
  774. continue
  775. }
  776. serviceName, serviceType := getServiceNameAndTypeFromHelmName(k)
  777. if serviceName == "" {
  778. return nil, fmt.Errorf("invalid service key: %s. make sure that service key ends in either -web, -wkr, or -job", k)
  779. }
  780. config := convertMap(v).(map[string]interface{})
  781. var runCommand string
  782. if config["container"] != nil {
  783. containerMap := config["container"].(map[string]interface{})
  784. if containerMap["command"] != nil {
  785. runCommand = containerMap["command"].(string)
  786. }
  787. }
  788. services[serviceName] = &Service{
  789. Run: &runCommand,
  790. Config: config,
  791. Type: &serviceType,
  792. }
  793. }
  794. return &PorterStackYAML{
  795. Services: services,
  796. }, nil
  797. }
  798. // addLabelsToService always adds the default label to the service, and if envGroups is not empty, it adds the corresponding environment group label as well.
  799. func addLabelsToService(service *Service, envGroups []string, defaultLabelKey string) *Service {
  800. if _, ok := service.Config["labels"]; !ok {
  801. service.Config["labels"] = make(map[string]string)
  802. }
  803. if len(envGroups) != 0 {
  804. // delete the env group label so we can replace it
  805. if _, ok := service.Config["labels"].(map[string]any); ok {
  806. delete(service.Config["labels"].(map[string]any), environment_groups.LabelKey_LinkedEnvironmentGroup)
  807. }
  808. }
  809. switch service.Config["labels"].(type) {
  810. case map[string]string:
  811. service.Config["labels"].(map[string]string)[defaultLabelKey] = porter_app.LabelValue_PorterApplication
  812. if len(envGroups) != 0 {
  813. service.Config["labels"].(map[string]string)[environment_groups.LabelKey_LinkedEnvironmentGroup] = strings.Join(envGroups, ".")
  814. }
  815. case map[string]any:
  816. service.Config["labels"].(map[string]any)[defaultLabelKey] = porter_app.LabelValue_PorterApplication
  817. if len(envGroups) != 0 {
  818. service.Config["labels"].(map[string]any)[environment_groups.LabelKey_LinkedEnvironmentGroup] = strings.Join(envGroups, ".")
  819. }
  820. case any:
  821. if val, ok := service.Config["labels"].(string); ok {
  822. if val == "" {
  823. service.Config["labels"] = map[string]string{
  824. defaultLabelKey: porter_app.LabelValue_PorterApplication,
  825. }
  826. if len(envGroups) != 0 {
  827. service.Config["labels"].(map[string]string)[environment_groups.LabelKey_LinkedEnvironmentGroup] = strings.Join(envGroups, ".")
  828. }
  829. }
  830. }
  831. }
  832. if _, ok := service.Config["podLabels"]; !ok {
  833. service.Config["podLabels"] = make(map[string]string)
  834. }
  835. switch service.Config["podLabels"].(type) {
  836. case map[string]string:
  837. service.Config["podLabels"].(map[string]string)[defaultLabelKey] = porter_app.LabelValue_PorterApplication
  838. case map[string]any:
  839. service.Config["podLabels"].(map[string]any)[defaultLabelKey] = porter_app.LabelValue_PorterApplication
  840. case any:
  841. if val, ok := service.Config["podLabels"].(string); ok {
  842. if val == "" {
  843. service.Config["podLabels"] = map[string]string{
  844. defaultLabelKey: porter_app.LabelValue_PorterApplication,
  845. }
  846. }
  847. }
  848. }
  849. return service
  850. }
  851. func getServiceDeploymentMetadataFromValues(values map[string]interface{}, status types.PorterAppEventStatus) map[string]types.ServiceDeploymentMetadata {
  852. serviceDeploymentMap := make(map[string]types.ServiceDeploymentMetadata)
  853. for key := range values {
  854. if key != "global" {
  855. serviceName, serviceType := getServiceNameAndTypeFromHelmName(key)
  856. externalURI := getServiceExternalURIFromServiceValues(values[key].(map[string]interface{}))
  857. // jobs don't technically have a deployment, so hardcode the deployment status to success
  858. serviceStatus := status
  859. if serviceType == "job" {
  860. serviceStatus = types.PorterAppEventStatus_Success
  861. }
  862. serviceDeploymentMap[serviceName] = types.ServiceDeploymentMetadata{
  863. ExternalURI: externalURI,
  864. Status: serviceStatus,
  865. Type: serviceType,
  866. }
  867. }
  868. }
  869. return serviceDeploymentMap
  870. }
  871. func getServiceExternalURIFromServiceValues(serviceValues map[string]interface{}) string {
  872. ingressMap, err := getNestedMap(serviceValues, "ingress")
  873. if err == nil {
  874. enabledVal, enabledExists := ingressMap["enabled"]
  875. if enabledExists {
  876. enabled, eOK := enabledVal.(bool)
  877. if eOK && enabled {
  878. customDomVal, customDomExists := ingressMap["custom_domain"]
  879. if customDomExists {
  880. customDomain, cOK := customDomVal.(bool)
  881. if cOK && customDomain {
  882. hostsExists, hostsExistsOK := ingressMap["hosts"]
  883. if hostsExistsOK {
  884. if hosts, hostsOK := hostsExists.([]interface{}); hostsOK && len(hosts) == 1 {
  885. return hosts[0].(string)
  886. }
  887. }
  888. }
  889. }
  890. if porterHosts, ok := ingressMap["porter_hosts"].([]interface{}); ok && len(porterHosts) == 1 {
  891. return porterHosts[0].(string)
  892. }
  893. }
  894. }
  895. }
  896. return ""
  897. }