deploy.go 19 KB

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