deploy.go 17 KB

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