deploy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. // GetBuildEnv retrieves the build env from the release config and returns it
  115. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  116. return GetEnvFromConfig(d.release.Config)
  117. }
  118. // SetBuildEnv sets the build env vars in the process so that other commands can
  119. // use them
  120. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  121. d.env = envVars
  122. // iterate through env and set the environment variables for the process
  123. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  124. // these prefixed env when calling a custom build command as a child process.
  125. for key, val := range envVars {
  126. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  127. err := os.Setenv(prefixedKey, val)
  128. if err != nil {
  129. return err
  130. }
  131. }
  132. return nil
  133. }
  134. // WriteBuildEnv writes the build env to either a file or stdout
  135. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  136. // join lines together
  137. lines := make([]string, 0)
  138. // use os.Environ to get output already formatted as KEY=value
  139. for _, line := range os.Environ() {
  140. // filter for PORTER_<RELEASE> and strip prefix
  141. if strings.Contains(line, d.envPrefix+"_") {
  142. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  143. }
  144. }
  145. output := strings.Join(lines, "\n")
  146. if fileDest != "" {
  147. ioutil.WriteFile(fileDest, []byte(output), 0700)
  148. } else {
  149. fmt.Println(output)
  150. }
  151. return nil
  152. }
  153. // Build uses the deploy agent options to build a new container image from either
  154. // buildpack or docker.
  155. func (d *DeployAgent) Build() error {
  156. // if build is not local, fetch remote source
  157. var basePath string
  158. buildCtx := d.opts.LocalPath
  159. var err error
  160. if !d.opts.Local {
  161. repoSplit := strings.Split(d.release.GitActionConfig.GitRepo, "/")
  162. if len(repoSplit) != 2 {
  163. return fmt.Errorf("invalid formatting of repo name")
  164. }
  165. zipResp, err := d.client.GetRepoZIPDownloadURL(
  166. context.Background(),
  167. d.opts.ProjectID,
  168. int64(d.release.GitActionConfig.GitRepoID),
  169. "github",
  170. repoSplit[0],
  171. repoSplit[1],
  172. d.release.GitActionConfig.GitBranch,
  173. )
  174. if err != nil {
  175. return err
  176. }
  177. // download the repository from remote source into a temp directory
  178. basePath, err = d.downloadRepoToDir(zipResp.URLString)
  179. if err != nil {
  180. return err
  181. }
  182. if d.tag == "" {
  183. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  184. d.tag = shortRef
  185. }
  186. } else {
  187. basePath, err = filepath.Abs(".")
  188. if err != nil {
  189. return err
  190. }
  191. }
  192. if d.tag == "" {
  193. currImageSection := d.release.Config["image"].(map[string]interface{})
  194. d.tag = currImageSection["tag"].(string)
  195. }
  196. err = d.pullCurrentReleaseImage()
  197. buildAgent := &BuildAgent{
  198. SharedOpts: d.opts.SharedOpts,
  199. client: d.client,
  200. imageRepo: d.imageRepo,
  201. env: d.env,
  202. imageExists: d.imageExists,
  203. }
  204. // if image is not found, don't return an error
  205. if err != nil && err != docker.PullImageErrNotFound {
  206. return err
  207. } else if err != nil && err == docker.PullImageErrNotFound {
  208. fmt.Println("could not find image, moving to build step")
  209. d.imageExists = false
  210. }
  211. if d.opts.Method == DeployBuildTypeDocker {
  212. return buildAgent.BuildDocker(
  213. d.agent,
  214. basePath,
  215. buildCtx,
  216. d.dockerfilePath,
  217. d.tag,
  218. )
  219. }
  220. return buildAgent.BuildPack(d.agent, buildCtx, d.tag)
  221. }
  222. // Push pushes a local image to the remote repository linked in the release
  223. func (d *DeployAgent) Push() error {
  224. return d.agent.PushImage(fmt.Sprintf("%s:%s", d.imageRepo, d.tag))
  225. }
  226. // UpdateImageAndValues updates the current image for a release, along with new
  227. // configuration passed in via overrrideValues. If overrideValues is nil, it just
  228. // reuses the configuration set for the application. If overrideValues is not nil,
  229. // it will merge the overriding values with the existing configuration.
  230. func (d *DeployAgent) UpdateImageAndValues(overrideValues map[string]interface{}) error {
  231. // if this is a job chart, set "paused" to false so that the job doesn't run, unless
  232. // the user has explicitly overriden the "paused" field
  233. if _, exists := overrideValues["paused"]; d.release.Chart.Name() == "job" && !exists {
  234. overrideValues["paused"] = true
  235. }
  236. mergedValues := utils.CoalesceValues(d.release.Config, overrideValues)
  237. // overwrite the tag based on a new image
  238. currImageSection := mergedValues["image"].(map[string]interface{})
  239. // if the current image section is hello-porter, the image must be overriden
  240. if currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  241. currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  242. newImage, err := d.getReleaseImage()
  243. if err != nil {
  244. return fmt.Errorf("could not overwrite hello-porter image: %s", err.Error())
  245. }
  246. currImageSection["repository"] = newImage
  247. // set to latest just to be safe -- this will be overriden if "d.tag" is set in
  248. // the agent
  249. currImageSection["tag"] = "latest"
  250. }
  251. if d.tag != "" && currImageSection["tag"] != d.tag {
  252. currImageSection["tag"] = d.tag
  253. }
  254. bytes, err := json.Marshal(mergedValues)
  255. if err != nil {
  256. return err
  257. }
  258. return d.client.UpgradeRelease(
  259. context.Background(),
  260. d.opts.ProjectID,
  261. d.opts.ClusterID,
  262. d.release.Namespace,
  263. d.release.Name,
  264. &types.UpgradeReleaseRequest{
  265. Values: string(bytes),
  266. },
  267. )
  268. }
  269. // GetEnvFromConfig gets the env vars for a standard Porter template config. These env
  270. // vars are found at `container.env.normal`.
  271. func GetEnvFromConfig(config map[string]interface{}) (map[string]string, error) {
  272. envConfig, err := getNestedMap(config, "container", "env", "normal")
  273. // if the field is not found, set envConfig to an empty map; this release has no env set
  274. if err != nil {
  275. envConfig = make(map[string]interface{})
  276. }
  277. mapEnvConfig := make(map[string]string)
  278. for key, val := range envConfig {
  279. valStr, ok := val.(string)
  280. if !ok {
  281. return nil, fmt.Errorf("could not cast environment variables to object")
  282. }
  283. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  284. // run-time, so we ignore it
  285. if !strings.Contains(valStr, "PORTERSECRET") {
  286. mapEnvConfig[key] = valStr
  287. }
  288. }
  289. return mapEnvConfig, nil
  290. }
  291. func (d *DeployAgent) getReleaseImage() (string, error) {
  292. if d.release.ImageRepoURI != "" {
  293. return d.release.ImageRepoURI, nil
  294. }
  295. // get the image from the conig
  296. imageConfig, err := getNestedMap(d.release.Config, "image")
  297. if err != nil {
  298. return "", fmt.Errorf("could not get image config from release: %s", err.Error())
  299. }
  300. repoInterface, ok := imageConfig["repository"]
  301. if !ok {
  302. return "", fmt.Errorf("repository field does not exist for image")
  303. }
  304. repoStr, ok := repoInterface.(string)
  305. if !ok {
  306. return "", fmt.Errorf("could not cast image.image field to string")
  307. }
  308. return repoStr, nil
  309. }
  310. func (d *DeployAgent) pullCurrentReleaseImage() error {
  311. // pull the currently deployed image to use cache, if possible
  312. imageConfig, err := getNestedMap(d.release.Config, "image")
  313. if err != nil {
  314. return fmt.Errorf("could not get image config from release: %s", err.Error())
  315. }
  316. tagInterface, ok := imageConfig["tag"]
  317. if !ok {
  318. return fmt.Errorf("tag field does not exist for image")
  319. }
  320. tagStr, ok := tagInterface.(string)
  321. if !ok {
  322. return fmt.Errorf("could not cast image.tag field to string")
  323. }
  324. // if image repo is a hello-porter image, skip
  325. if d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  326. d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  327. return nil
  328. }
  329. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  330. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  331. }
  332. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  333. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  334. downloader := &github.ZIPDownloader{
  335. ZipFolderDest: dstDir,
  336. AssetFolderDest: dstDir,
  337. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  338. RemoveAfterDownload: true,
  339. }
  340. err := downloader.DownloadToFile(downloadURL)
  341. if err != nil {
  342. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  343. }
  344. err = downloader.UnzipToDir()
  345. if err != nil {
  346. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  347. }
  348. var res string
  349. dstFiles, err := ioutil.ReadDir(dstDir)
  350. for _, info := range dstFiles {
  351. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  352. res = filepath.Join(dstDir, info.Name())
  353. }
  354. }
  355. if res == "" {
  356. return "", fmt.Errorf("unzipped file not found on host")
  357. }
  358. return res, nil
  359. }
  360. func (d *DeployAgent) StreamEvent(event types.SubEvent) error {
  361. return d.client.CreateEvent(
  362. context.Background(),
  363. d.opts.ProjectID, d.opts.ClusterID,
  364. d.release.Namespace, d.release.Name,
  365. &types.UpdateReleaseStepsRequest{
  366. Event: event,
  367. },
  368. )
  369. }
  370. type NestedMapFieldNotFoundError struct {
  371. Field string
  372. }
  373. func (e *NestedMapFieldNotFoundError) Error() string {
  374. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  375. }
  376. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  377. var res map[string]interface{}
  378. curr := obj
  379. for _, field := range fields {
  380. objField, ok := curr[field]
  381. if !ok {
  382. return nil, &NestedMapFieldNotFoundError{field}
  383. }
  384. res, ok = objField.(map[string]interface{})
  385. if !ok {
  386. return nil, fmt.Errorf("%s is not a nested object", field)
  387. }
  388. curr = res
  389. }
  390. return res, nil
  391. }