deploy.go 17 KB

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