deploy.go 17 KB

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