2
0

deploy.go 20 KB

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