deploy.go 18 KB

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