deploy.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. package deploy
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/porter-dev/porter/api/client"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/cli/cmd/docker"
  13. "github.com/porter-dev/porter/cli/cmd/github"
  14. "github.com/porter-dev/porter/internal/templater/utils"
  15. "k8s.io/client-go/util/homedir"
  16. )
  17. // DeployBuildType is the option to use as a builder
  18. type DeployBuildType string
  19. const (
  20. // uses local Docker daemon to build and push images
  21. DeployBuildTypeDocker DeployBuildType = "docker"
  22. // uses cloud-native build pack to build and push images
  23. DeployBuildTypePack DeployBuildType = "pack"
  24. )
  25. // DeployAgent handles the deployment and redeployment of an application on Porter
  26. type DeployAgent struct {
  27. App string
  28. Client *client.Client
  29. Opts *DeployOpts
  30. Release *types.GetReleaseResponse
  31. agent *docker.Agent
  32. tag string
  33. envPrefix string
  34. env map[string]string
  35. imageExists bool
  36. imageRepo string
  37. dockerfilePath string
  38. }
  39. // DeployOpts are the options for creating a new DeployAgent
  40. type DeployOpts struct {
  41. *SharedOpts
  42. Local bool
  43. }
  44. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  45. // name, and DeployOpts.
  46. func NewDeployAgent(client *client.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  47. deployAgent := &DeployAgent{
  48. App: app,
  49. Opts: opts,
  50. Client: client,
  51. env: make(map[string]string),
  52. }
  53. // get release from Porter API
  54. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  55. if err != nil {
  56. return nil, err
  57. }
  58. deployAgent.Release = release
  59. // set an environment prefix to avoid collisions
  60. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  61. strings.ToUpper(app), "-", "_", -1,
  62. ))
  63. // get docker agent
  64. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  65. if err != nil {
  66. return nil, err
  67. }
  68. deployAgent.agent = agent
  69. // if build method is not set, determine based on release config
  70. if opts.Method == "" {
  71. if release.GitActionConfig != nil {
  72. // if the git action config exists, and dockerfile path is not empty, build type
  73. // is docker
  74. if release.GitActionConfig.DockerfilePath != "" {
  75. deployAgent.Opts.Method = DeployBuildTypeDocker
  76. } else {
  77. // otherwise build type is pack
  78. deployAgent.Opts.Method = DeployBuildTypePack
  79. }
  80. } else {
  81. // if the git action config does not exist, we use docker by default
  82. deployAgent.Opts.Method = DeployBuildTypeDocker
  83. }
  84. }
  85. if deployAgent.Opts.Method == DeployBuildTypeDocker {
  86. if release.GitActionConfig != nil {
  87. deployAgent.dockerfilePath = release.GitActionConfig.DockerfilePath
  88. }
  89. if deployAgent.Opts.LocalDockerfile != "" {
  90. deployAgent.dockerfilePath = deployAgent.Opts.LocalDockerfile
  91. }
  92. if deployAgent.dockerfilePath == "" && deployAgent.Opts.LocalDockerfile == "" {
  93. deployAgent.dockerfilePath = "./Dockerfile"
  94. }
  95. }
  96. // if the git action config is not set, we use local builds since pulling remote source
  97. // will fail. we set the image based on the git action config or the image written in the
  98. // helm values
  99. if release.GitActionConfig == nil {
  100. deployAgent.Opts.Local = true
  101. imageRepo, err := deployAgent.getReleaseImage()
  102. if err != nil {
  103. return nil, err
  104. }
  105. deployAgent.imageRepo = imageRepo
  106. deployAgent.dockerfilePath = deployAgent.Opts.LocalDockerfile
  107. } else {
  108. deployAgent.imageRepo = release.GitActionConfig.ImageRepoURI
  109. deployAgent.Opts.LocalPath = release.GitActionConfig.FolderPath
  110. }
  111. deployAgent.tag = opts.OverrideTag
  112. err = coalesceEnvGroups(deployAgent.Client, deployAgent.Opts.ProjectID, deployAgent.Opts.ClusterID,
  113. deployAgent.Opts.Namespace, deployAgent.Opts.EnvGroups, deployAgent.Release.Config)
  114. deployAgent.imageExists = deployAgent.agent.CheckIfImageExists(deployAgent.imageRepo, deployAgent.tag)
  115. return deployAgent, err
  116. }
  117. type GetBuildEnvOpts struct {
  118. UseNewConfig bool
  119. NewConfig map[string]interface{}
  120. IncludeBuildEnv bool
  121. }
  122. // GetBuildEnv retrieves the build env from the release config and returns it.
  123. //
  124. // It returns a flattened map of all environment variables including:
  125. // 1. container.env.normal from the release config
  126. // 2. container.env.build from the release config
  127. // 3. container.env.synced from the release config
  128. // 4. any additional env var that was passed into the DeployAgent as opts.SharedOpts.AdditionalEnv
  129. func (d *DeployAgent) GetBuildEnv(opts *GetBuildEnvOpts) (map[string]string, error) {
  130. conf := d.Release.Config
  131. if opts.UseNewConfig {
  132. if opts.NewConfig != nil {
  133. conf = utils.CoalesceValues(d.Release.Config, opts.NewConfig)
  134. }
  135. }
  136. env, err := GetEnvForRelease(d.Client, conf, d.Opts.ProjectID, d.Opts.ClusterID, d.Opts.Namespace)
  137. if err != nil {
  138. return nil, err
  139. }
  140. envConfig, err := GetNestedMap(conf, "container", "env")
  141. if err == nil {
  142. _, exists := envConfig["build"]
  143. if exists {
  144. buildEnv, err := GetNestedMap(conf, "container", "env", "build")
  145. if err == nil {
  146. for key, val := range buildEnv {
  147. if valStr, ok := val.(string); ok {
  148. env[key] = valStr
  149. }
  150. }
  151. }
  152. }
  153. }
  154. // add additional env based on options
  155. for key, val := range d.Opts.SharedOpts.AdditionalEnv {
  156. env[key] = val
  157. }
  158. return env, nil
  159. }
  160. // SetBuildEnv sets the build env vars in the process so that other commands can
  161. // use them
  162. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  163. d.env = envVars
  164. // iterate through env and set the environment variables for the process
  165. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  166. // these prefixed env when calling a custom build command as a child process.
  167. for key, val := range envVars {
  168. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  169. err := os.Setenv(prefixedKey, val)
  170. if err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. // WriteBuildEnv writes the build env to either a file or stdout
  177. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  178. // join lines together
  179. lines := make([]string, 0)
  180. // use os.Environ to get output already formatted as KEY=value
  181. for _, line := range os.Environ() {
  182. // filter for PORTER_<RELEASE> and strip prefix
  183. if strings.Contains(line, d.envPrefix+"_") {
  184. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  185. }
  186. }
  187. output := strings.Join(lines, "\n")
  188. if fileDest != "" {
  189. ioutil.WriteFile(fileDest, []byte(output), 0700)
  190. } else {
  191. fmt.Println(output)
  192. }
  193. return nil
  194. }
  195. // Build uses the deploy agent options to build a new container image from either
  196. // buildpack or docker.
  197. func (d *DeployAgent) Build(overrideBuildConfig *types.BuildConfig) error {
  198. // retrieve current image to use for cache
  199. currImageSection := d.Release.Config["image"].(map[string]interface{})
  200. currentTag := currImageSection["tag"].(string)
  201. if d.tag == "" {
  202. d.tag = currentTag
  203. }
  204. // if build is not local, fetch remote source
  205. var basePath string
  206. var err error
  207. buildCtx := d.Opts.LocalPath
  208. if !d.Opts.Local {
  209. repoSplit := strings.Split(d.Release.GitActionConfig.GitRepo, "/")
  210. if len(repoSplit) != 2 {
  211. return fmt.Errorf("invalid formatting of repo name")
  212. }
  213. zipResp, err := d.Client.GetRepoZIPDownloadURL(
  214. context.Background(),
  215. d.Opts.ProjectID,
  216. int64(d.Release.GitActionConfig.GitRepoID),
  217. "github",
  218. repoSplit[0],
  219. repoSplit[1],
  220. d.Release.GitActionConfig.GitBranch,
  221. )
  222. if err != nil {
  223. return err
  224. }
  225. // download the repository from remote source into a temp directory
  226. basePath, err = d.downloadRepoToDir(zipResp.URLString)
  227. if err != nil {
  228. return err
  229. }
  230. if d.tag == "" {
  231. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  232. d.tag = shortRef
  233. }
  234. } else {
  235. basePath, err = filepath.Abs(".")
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. currTag, err := d.pullCurrentReleaseImage()
  241. // if image is not found, don't return an error
  242. if err != nil && err != docker.PullImageErrNotFound {
  243. return err
  244. }
  245. buildAgent := &BuildAgent{
  246. SharedOpts: d.Opts.SharedOpts,
  247. APIClient: d.Client,
  248. ImageRepo: d.imageRepo,
  249. Env: d.env,
  250. ImageExists: d.imageExists,
  251. }
  252. if d.Opts.Method == DeployBuildTypeDocker {
  253. return buildAgent.BuildDocker(
  254. d.agent,
  255. basePath,
  256. buildCtx,
  257. d.dockerfilePath,
  258. d.tag,
  259. currentTag,
  260. )
  261. }
  262. buildConfig := d.Release.BuildConfig
  263. if overrideBuildConfig != nil {
  264. buildConfig = overrideBuildConfig
  265. }
  266. return buildAgent.BuildPack(d.agent, buildCtx, d.tag, currTag, buildConfig)
  267. }
  268. // Push pushes a local image to the remote repository linked in the release
  269. func (d *DeployAgent) Push() error {
  270. return d.agent.PushImage(fmt.Sprintf("%s:%s", d.imageRepo, d.tag))
  271. }
  272. // UpdateImageAndValues updates the current image for a release, along with new
  273. // configuration passed in via overrrideValues. If overrideValues is nil, it just
  274. // reuses the configuration set for the application. If overrideValues is not nil,
  275. // it will merge the overriding values with the existing configuration.
  276. func (d *DeployAgent) UpdateImageAndValues(overrideValues map[string]interface{}) error {
  277. // if this is a job chart, set "paused" to false so that the job doesn't run, unless
  278. // the user has explicitly overriden the "paused" field
  279. if _, exists := overrideValues["paused"]; d.Release.Chart.Name() == "job" && !exists {
  280. overrideValues["paused"] = true
  281. }
  282. mergedValues := utils.CoalesceValues(d.Release.Config, overrideValues)
  283. activeBlueGreenTagVal := GetCurrActiveBlueGreenImage(mergedValues)
  284. // only overwrite if the active tag value is not the same as the target tag. otherwise
  285. // this has been modified already and inserted into overrideValues.
  286. if activeBlueGreenTagVal != "" && activeBlueGreenTagVal != d.tag {
  287. mergedValues["bluegreen"] = map[string]interface{}{
  288. "enabled": true,
  289. "disablePrimaryDeployment": true,
  290. "activeImageTag": activeBlueGreenTagVal,
  291. "imageTags": []string{activeBlueGreenTagVal, d.tag},
  292. }
  293. }
  294. // overwrite the tag based on a new image
  295. currImageSection := mergedValues["image"].(map[string]interface{})
  296. // if the current image section is hello-porter, the image must be overriden
  297. if currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  298. currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  299. newImage, err := d.getReleaseImage()
  300. if err != nil {
  301. return fmt.Errorf("could not overwrite hello-porter image: %s", err.Error())
  302. }
  303. currImageSection["repository"] = newImage
  304. // set to latest just to be safe -- this will be overriden if "d.tag" is set in
  305. // the agent
  306. currImageSection["tag"] = "latest"
  307. }
  308. if d.tag != "" && currImageSection["tag"] != d.tag {
  309. currImageSection["tag"] = d.tag
  310. }
  311. bytes, err := json.Marshal(mergedValues)
  312. if err != nil {
  313. return err
  314. }
  315. return d.Client.UpgradeRelease(
  316. context.Background(),
  317. d.Opts.ProjectID,
  318. d.Opts.ClusterID,
  319. d.Release.Namespace,
  320. d.Release.Name,
  321. &types.UpgradeReleaseRequest{
  322. Values: string(bytes),
  323. },
  324. )
  325. }
  326. type SyncedEnvSection struct {
  327. Name string `json:"name" yaml:"name"`
  328. Version uint `json:"version" yaml:"version"`
  329. Keys []SyncedEnvSectionKey `json:"keys" yaml:"keys"`
  330. }
  331. type SyncedEnvSectionKey struct {
  332. Name string `json:"name" yaml:"name"`
  333. Secret bool `json:"secret" yaml:"secret"`
  334. }
  335. // GetEnvForRelease gets the env vars for a standard Porter template config. These env
  336. // vars are found at `container.env.normal` and `container.env.synced`.
  337. func GetEnvForRelease(
  338. client *client.Client,
  339. config map[string]interface{},
  340. projID, clusterID uint,
  341. namespace string,
  342. ) (map[string]string, error) {
  343. res := make(map[string]string)
  344. // first, get the env vars from "container.env.normal"
  345. normalEnv, err := GetNormalEnv(client, config, projID, clusterID, namespace, true)
  346. if err != nil {
  347. return nil, fmt.Errorf("error while fetching container.env.normal variables: %w", err)
  348. }
  349. for k, v := range normalEnv {
  350. res[k] = v
  351. }
  352. // next, get the env vars specified by "container.env.synced"
  353. // look for container.env.synced
  354. syncedEnv, err := GetSyncedEnv(client, config, projID, clusterID, namespace, true)
  355. if err != nil {
  356. return nil, fmt.Errorf("error while fetching container.env.synced variables: %w", err)
  357. }
  358. for k, v := range syncedEnv {
  359. res[k] = v
  360. }
  361. return res, nil
  362. }
  363. func GetNormalEnv(
  364. client *client.Client,
  365. config map[string]interface{},
  366. projID, clusterID uint,
  367. namespace string,
  368. buildTime bool,
  369. ) (map[string]string, error) {
  370. res := make(map[string]string)
  371. envConfig, err := GetNestedMap(config, "container", "env", "normal")
  372. // if the field is not found, set envConfig to an empty map; this release has no env set
  373. if err != nil {
  374. envConfig = make(map[string]interface{})
  375. }
  376. for key, val := range envConfig {
  377. valStr, ok := val.(string)
  378. if !ok {
  379. return nil, fmt.Errorf("could not cast environment variables to object")
  380. }
  381. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  382. // run-time, so we ignore it
  383. if buildTime && strings.Contains(valStr, "PORTERSECRET") {
  384. continue
  385. } else {
  386. res[key] = valStr
  387. }
  388. }
  389. return res, nil
  390. }
  391. func GetSyncedEnv(
  392. client *client.Client,
  393. config map[string]interface{},
  394. projID, clusterID uint,
  395. namespace string,
  396. buildTime bool,
  397. ) (map[string]string, error) {
  398. res := make(map[string]string)
  399. envConf, err := GetNestedMap(config, "container", "env")
  400. // if error, just return the env detected from above
  401. if err != nil {
  402. return res, nil
  403. }
  404. syncedEnvInter, syncedEnvExists := envConf["synced"]
  405. if !syncedEnvExists {
  406. return res, nil
  407. } else {
  408. syncedArr := make([]*SyncedEnvSection, 0)
  409. syncedArrInter, ok := syncedEnvInter.([]interface{})
  410. if !ok {
  411. return nil, fmt.Errorf("could not convert to synced env section: not an array")
  412. }
  413. for _, syncedArrInterObj := range syncedArrInter {
  414. syncedArrObj := &SyncedEnvSection{}
  415. syncedArrInterObjMap, ok := syncedArrInterObj.(map[string]interface{})
  416. if !ok {
  417. continue
  418. }
  419. if nameField, nameFieldExists := syncedArrInterObjMap["name"]; nameFieldExists {
  420. syncedArrObj.Name, ok = nameField.(string)
  421. if !ok {
  422. continue
  423. }
  424. }
  425. if versionField, versionFieldExists := syncedArrInterObjMap["version"]; versionFieldExists {
  426. versionFloat, ok := versionField.(float64)
  427. if !ok {
  428. continue
  429. }
  430. syncedArrObj.Version = uint(versionFloat)
  431. }
  432. if keyField, keyFieldExists := syncedArrInterObjMap["keys"]; keyFieldExists {
  433. keyFieldInterArr, ok := keyField.([]interface{})
  434. if !ok {
  435. continue
  436. }
  437. keyFieldMapArr := make([]map[string]interface{}, 0)
  438. for _, keyFieldInter := range keyFieldInterArr {
  439. mapConv, ok := keyFieldInter.(map[string]interface{})
  440. if !ok {
  441. continue
  442. }
  443. keyFieldMapArr = append(keyFieldMapArr, mapConv)
  444. }
  445. keyFieldRes := make([]SyncedEnvSectionKey, 0)
  446. for _, keyFieldMap := range keyFieldMapArr {
  447. toAdd := SyncedEnvSectionKey{}
  448. if nameField, nameFieldExists := keyFieldMap["name"]; nameFieldExists {
  449. toAdd.Name, ok = nameField.(string)
  450. if !ok {
  451. continue
  452. }
  453. }
  454. if secretField, secretFieldExists := keyFieldMap["secret"]; secretFieldExists {
  455. toAdd.Secret, ok = secretField.(bool)
  456. if !ok {
  457. continue
  458. }
  459. }
  460. keyFieldRes = append(keyFieldRes, toAdd)
  461. }
  462. syncedArrObj.Keys = keyFieldRes
  463. }
  464. syncedArr = append(syncedArr, syncedArrObj)
  465. }
  466. for _, syncedEG := range syncedArr {
  467. // for each synced environment group, get the environment group from the client
  468. eg, err := client.GetEnvGroup(context.Background(), projID, clusterID, namespace,
  469. &types.GetEnvGroupRequest{
  470. Name: syncedEG.Name,
  471. },
  472. )
  473. if err != nil {
  474. continue
  475. }
  476. for key, val := range eg.Variables {
  477. if buildTime && strings.Contains(val, "PORTERSECRET") {
  478. continue
  479. } else {
  480. res[key] = val
  481. }
  482. }
  483. }
  484. }
  485. return res, nil
  486. }
  487. func (d *DeployAgent) getReleaseImage() (string, error) {
  488. if d.Release.ImageRepoURI != "" {
  489. return d.Release.ImageRepoURI, nil
  490. }
  491. // get the image from the conig
  492. imageConfig, err := GetNestedMap(d.Release.Config, "image")
  493. if err != nil {
  494. return "", fmt.Errorf("could not get image config from release: %s", err.Error())
  495. }
  496. repoInterface, ok := imageConfig["repository"]
  497. if !ok {
  498. return "", fmt.Errorf("repository field does not exist for image")
  499. }
  500. repoStr, ok := repoInterface.(string)
  501. if !ok {
  502. return "", fmt.Errorf("could not cast image.image field to string")
  503. }
  504. return repoStr, nil
  505. }
  506. func (d *DeployAgent) pullCurrentReleaseImage() (string, error) {
  507. // pull the currently deployed image to use cache, if possible
  508. imageConfig, err := GetNestedMap(d.Release.Config, "image")
  509. if err != nil {
  510. return "", fmt.Errorf("could not get image config from release: %s", err.Error())
  511. }
  512. tagInterface, ok := imageConfig["tag"]
  513. if !ok {
  514. return "", fmt.Errorf("tag field does not exist for image")
  515. }
  516. tagStr, ok := tagInterface.(string)
  517. if !ok {
  518. return "", fmt.Errorf("could not cast image.tag field to string")
  519. }
  520. // if image repo is a hello-porter image, skip
  521. if d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  522. d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  523. return "", nil
  524. }
  525. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  526. return tagStr, d.agent.PullImage(fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  527. }
  528. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  529. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  530. downloader := &github.ZIPDownloader{
  531. ZipFolderDest: dstDir,
  532. AssetFolderDest: dstDir,
  533. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.Release.GitActionConfig.GitRepo, "/", "-", 1)),
  534. RemoveAfterDownload: true,
  535. }
  536. err := downloader.DownloadToFile(downloadURL)
  537. if err != nil {
  538. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  539. }
  540. err = downloader.UnzipToDir()
  541. if err != nil {
  542. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  543. }
  544. var res string
  545. dstFiles, err := ioutil.ReadDir(dstDir)
  546. for _, info := range dstFiles {
  547. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.Release.GitActionConfig.GitRepo, "/", "-", 1)) {
  548. res = filepath.Join(dstDir, info.Name())
  549. }
  550. }
  551. if res == "" {
  552. return "", fmt.Errorf("unzipped file not found on host")
  553. }
  554. return res, nil
  555. }
  556. func (d *DeployAgent) StreamEvent(event types.SubEvent) error {
  557. return d.Client.CreateEvent(
  558. context.Background(),
  559. d.Opts.ProjectID, d.Opts.ClusterID,
  560. d.Release.Namespace, d.Release.Name,
  561. &types.UpdateReleaseStepsRequest{
  562. Event: event,
  563. },
  564. )
  565. }
  566. type NestedMapFieldNotFoundError struct {
  567. Field string
  568. }
  569. func (e *NestedMapFieldNotFoundError) Error() string {
  570. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  571. }
  572. func GetNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  573. var res map[string]interface{}
  574. curr := obj
  575. for _, field := range fields {
  576. objField, ok := curr[field]
  577. if !ok {
  578. return nil, &NestedMapFieldNotFoundError{field}
  579. }
  580. res, ok = objField.(map[string]interface{})
  581. if !ok {
  582. return nil, fmt.Errorf("%s is not a nested object", field)
  583. }
  584. curr = res
  585. }
  586. return res, nil
  587. }
  588. func GetCurrActiveBlueGreenImage(vals map[string]interface{}) string {
  589. if bgInter, ok := vals["bluegreen"]; ok {
  590. if bgVal, ok := bgInter.(map[string]interface{}); ok {
  591. if enabledInter, ok := bgVal["enabled"]; ok {
  592. if enabledVal, ok := enabledInter.(bool); ok && enabledVal {
  593. // they're enabled -- read the activeTagValue and construct the new bluegreen object
  594. if activeTagInter, ok := bgVal["activeImageTag"]; ok {
  595. if activeTagVal, ok := activeTagInter.(string); ok {
  596. return activeTagVal
  597. }
  598. }
  599. }
  600. }
  601. }
  602. }
  603. return ""
  604. }