deploy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/cli/cmd/api"
  11. "github.com/porter-dev/porter/cli/cmd/docker"
  12. "github.com/porter-dev/porter/cli/cmd/github"
  13. "github.com/porter-dev/porter/internal/templater/utils"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. // DeployBuildType is the option to use as a builder
  17. type DeployBuildType string
  18. const (
  19. // uses local Docker daemon to build and push images
  20. DeployBuildTypeDocker DeployBuildType = "docker"
  21. // uses cloud-native build pack to build and push images
  22. DeployBuildTypePack DeployBuildType = "pack"
  23. )
  24. // DeployAgent handles the deployment and redeployment of an application on Porter
  25. type DeployAgent struct {
  26. App string
  27. client *api.Client
  28. release *api.GetReleaseResponse
  29. agent *docker.Agent
  30. opts *DeployOpts
  31. tag string
  32. envPrefix string
  33. env map[string]string
  34. imageExists bool
  35. imageRepo string
  36. dockerfilePath string
  37. }
  38. // DeployOpts are the options for creating a new DeployAgent
  39. type DeployOpts struct {
  40. *SharedOpts
  41. Local bool
  42. }
  43. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  44. // name, and DeployOpts.
  45. func NewDeployAgent(client *api.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  46. deployAgent := &DeployAgent{
  47. App: app,
  48. opts: opts,
  49. client: client,
  50. env: make(map[string]string),
  51. }
  52. // get release from Porter API
  53. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  54. if err != nil {
  55. return nil, err
  56. }
  57. deployAgent.release = release
  58. // set an environment prefix to avoid collisions
  59. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  60. strings.ToUpper(app), "-", "_", -1,
  61. ))
  62. // get docker agent
  63. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  64. if err != nil {
  65. return nil, err
  66. }
  67. deployAgent.agent = agent
  68. // if build method is not set, determine based on release config
  69. if opts.Method == "" {
  70. if release.GitActionConfig != nil {
  71. // if the git action config exists, and dockerfile path is not empty, build type
  72. // is docker
  73. if release.GitActionConfig.DockerfilePath != "" {
  74. deployAgent.opts.Method = DeployBuildTypeDocker
  75. } else {
  76. // otherwise build type is pack
  77. deployAgent.opts.Method = DeployBuildTypePack
  78. }
  79. } else {
  80. // if the git action config does not exist, we use docker by default
  81. deployAgent.opts.Method = DeployBuildTypeDocker
  82. }
  83. }
  84. if deployAgent.opts.Method == DeployBuildTypeDocker {
  85. if release.GitActionConfig != nil {
  86. deployAgent.dockerfilePath = release.GitActionConfig.DockerfilePath
  87. }
  88. if deployAgent.opts.LocalDockerfile != "" {
  89. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  90. }
  91. if deployAgent.dockerfilePath == "" && deployAgent.opts.LocalDockerfile == "" {
  92. deployAgent.dockerfilePath = "./Dockerfile"
  93. }
  94. }
  95. // if the git action config is not set, we use local builds since pulling remote source
  96. // will fail. we set the image based on the git action config or the image written in the
  97. // helm values
  98. if release.GitActionConfig == nil {
  99. deployAgent.opts.Local = true
  100. imageRepo, err := deployAgent.getReleaseImage()
  101. if err != nil {
  102. return nil, err
  103. }
  104. deployAgent.imageRepo = imageRepo
  105. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  106. } else {
  107. deployAgent.imageRepo = release.GitActionConfig.ImageRepoURI
  108. deployAgent.opts.LocalPath = release.GitActionConfig.FolderPath
  109. }
  110. if deployAgent.opts.Method == DeployBuildTypeDocker {
  111. if deployAgent.opts.LocalPath == "" {
  112. deployAgent.opts.LocalPath = filepath.Dir(deployAgent.dockerfilePath)
  113. }
  114. }
  115. deployAgent.tag = opts.OverrideTag
  116. return deployAgent, nil
  117. }
  118. // GetBuildEnv retrieves the build env from the release config and returns it
  119. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  120. return GetEnvFromConfig(d.release.Config)
  121. }
  122. // SetBuildEnv sets the build env vars in the process so that other commands can
  123. // use them
  124. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  125. d.env = envVars
  126. // iterate through env and set the environment variables for the process
  127. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  128. // these prefixed env when calling a custom build command as a child process.
  129. for key, val := range envVars {
  130. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  131. err := os.Setenv(prefixedKey, val)
  132. if err != nil {
  133. return err
  134. }
  135. }
  136. return nil
  137. }
  138. // WriteBuildEnv writes the build env to either a file or stdout
  139. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  140. // join lines together
  141. lines := make([]string, 0)
  142. // use os.Environ to get output already formatted as KEY=value
  143. for _, line := range os.Environ() {
  144. // filter for PORTER_<RELEASE> and strip prefix
  145. if strings.Contains(line, d.envPrefix+"_") {
  146. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  147. }
  148. }
  149. output := strings.Join(lines, "\n")
  150. if fileDest != "" {
  151. ioutil.WriteFile(fileDest, []byte(output), 0700)
  152. } else {
  153. fmt.Println(output)
  154. }
  155. return nil
  156. }
  157. // Build uses the deploy agent options to build a new container image from either
  158. // buildpack or docker.
  159. func (d *DeployAgent) Build() error {
  160. // if build is not local, fetch remote source
  161. var basePath string
  162. buildCtx := d.opts.LocalPath
  163. var err error
  164. if !d.opts.Local {
  165. zipResp, err := d.client.GetRepoZIPDownloadURL(
  166. context.Background(),
  167. d.opts.ProjectID,
  168. d.release.GitActionConfig,
  169. )
  170. if err != nil {
  171. return err
  172. }
  173. // download the repository from remote source into a temp directory
  174. basePath, err = d.downloadRepoToDir(zipResp.URLString)
  175. if err != nil {
  176. return err
  177. }
  178. if d.tag == "" {
  179. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  180. d.tag = shortRef
  181. }
  182. } else {
  183. basePath, err = filepath.Abs(".")
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. if d.tag == "" {
  189. currImageSection := d.release.Config["image"].(map[string]interface{})
  190. d.tag = currImageSection["tag"].(string)
  191. }
  192. err = d.pullCurrentReleaseImage()
  193. buildAgent := &BuildAgent{
  194. SharedOpts: d.opts.SharedOpts,
  195. client: d.client,
  196. imageRepo: d.imageRepo,
  197. env: d.env,
  198. imageExists: d.imageExists,
  199. }
  200. // if image is not found, don't return an error
  201. if err != nil && err != docker.PullImageErrNotFound {
  202. return err
  203. } else if err != nil && err == docker.PullImageErrNotFound {
  204. fmt.Println("could not find image, moving to build step")
  205. d.imageExists = false
  206. }
  207. if d.opts.Method == DeployBuildTypeDocker {
  208. return buildAgent.BuildDocker(
  209. d.agent,
  210. basePath,
  211. buildCtx,
  212. d.dockerfilePath,
  213. d.tag,
  214. )
  215. }
  216. return buildAgent.BuildPack(d.agent, buildCtx, d.tag)
  217. }
  218. // Push pushes a local image to the remote repository linked in the release
  219. func (d *DeployAgent) Push() error {
  220. return d.agent.PushImage(fmt.Sprintf("%s:%s", d.imageRepo, d.tag))
  221. }
  222. // UpdateImageAndValues updates the current image for a release, along with new
  223. // configuration passed in via overrrideValues. If overrideValues is nil, it just
  224. // reuses the configuration set for the application. If overrideValues is not nil,
  225. // it will merge the overriding values with the existing configuration.
  226. func (d *DeployAgent) UpdateImageAndValues(overrideValues map[string]interface{}) error {
  227. mergedValues := utils.CoalesceValues(d.release.Config, overrideValues)
  228. // overwrite the tag based on a new image
  229. currImageSection := mergedValues["image"].(map[string]interface{})
  230. // if this is a job chart, set "paused" to false so that the job doesn't run
  231. if d.release.Chart.Name() == "job" {
  232. mergedValues["paused"] = true
  233. }
  234. // if the current image section is hello-porter, the image must be overriden
  235. if currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  236. currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  237. newImage, err := d.getReleaseImage()
  238. if err != nil {
  239. return fmt.Errorf("could not overwrite hello-porter image: %s", err.Error())
  240. }
  241. currImageSection["repository"] = newImage
  242. // set to latest just to be safe -- this will be overriden if "d.tag" is set in
  243. // the agent
  244. currImageSection["tag"] = "latest"
  245. }
  246. if d.tag != "" && currImageSection["tag"] != d.tag {
  247. currImageSection["tag"] = d.tag
  248. }
  249. bytes, err := json.Marshal(mergedValues)
  250. if err != nil {
  251. return err
  252. }
  253. return d.client.UpgradeRelease(
  254. context.Background(),
  255. d.opts.ProjectID,
  256. d.opts.ClusterID,
  257. d.release.Name,
  258. &api.UpgradeReleaseRequest{
  259. Values: string(bytes),
  260. Namespace: d.release.Namespace,
  261. },
  262. )
  263. }
  264. // GetEnvFromConfig gets the env vars for a standard Porter template config. These env
  265. // vars are found at `container.env.normal`.
  266. func GetEnvFromConfig(config map[string]interface{}) (map[string]string, error) {
  267. envConfig, err := getNestedMap(config, "container", "env", "normal")
  268. // if the field is not found, set envConfig to an empty map; this release has no env set
  269. if err != nil {
  270. envConfig = make(map[string]interface{})
  271. }
  272. mapEnvConfig := make(map[string]string)
  273. for key, val := range envConfig {
  274. valStr, ok := val.(string)
  275. if !ok {
  276. return nil, fmt.Errorf("could not cast environment variables to object")
  277. }
  278. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  279. // run-time, so we ignore it
  280. if !strings.Contains(valStr, "PORTERSECRET") {
  281. mapEnvConfig[key] = valStr
  282. }
  283. }
  284. return mapEnvConfig, nil
  285. }
  286. func (d *DeployAgent) getReleaseImage() (string, error) {
  287. if d.release.ImageRepoURI != "" {
  288. return d.release.ImageRepoURI, nil
  289. }
  290. // get the image from the conig
  291. imageConfig, err := getNestedMap(d.release.Config, "image")
  292. if err != nil {
  293. return "", fmt.Errorf("could not get image config from release: %s", err.Error())
  294. }
  295. repoInterface, ok := imageConfig["repository"]
  296. if !ok {
  297. return "", fmt.Errorf("repository field does not exist for image")
  298. }
  299. repoStr, ok := repoInterface.(string)
  300. if !ok {
  301. return "", fmt.Errorf("could not cast image.image field to string")
  302. }
  303. return repoStr, nil
  304. }
  305. func (d *DeployAgent) pullCurrentReleaseImage() error {
  306. // pull the currently deployed image to use cache, if possible
  307. imageConfig, err := getNestedMap(d.release.Config, "image")
  308. if err != nil {
  309. return fmt.Errorf("could not get image config from release: %s", err.Error())
  310. }
  311. tagInterface, ok := imageConfig["tag"]
  312. if !ok {
  313. return fmt.Errorf("tag field does not exist for image")
  314. }
  315. tagStr, ok := tagInterface.(string)
  316. if !ok {
  317. return fmt.Errorf("could not cast image.tag field to string")
  318. }
  319. // if image repo is a hello-porter image, skip
  320. if d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  321. d.imageRepo == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  322. return nil
  323. }
  324. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  325. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  326. }
  327. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  328. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  329. downloader := &github.ZIPDownloader{
  330. ZipFolderDest: dstDir,
  331. AssetFolderDest: dstDir,
  332. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  333. RemoveAfterDownload: true,
  334. }
  335. err := downloader.DownloadToFile(downloadURL)
  336. if err != nil {
  337. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  338. }
  339. err = downloader.UnzipToDir()
  340. if err != nil {
  341. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  342. }
  343. var res string
  344. dstFiles, err := ioutil.ReadDir(dstDir)
  345. for _, info := range dstFiles {
  346. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  347. res = filepath.Join(dstDir, info.Name())
  348. }
  349. }
  350. if res == "" {
  351. return "", fmt.Errorf("unzipped file not found on host")
  352. }
  353. return res, nil
  354. }
  355. func (d *DeployAgent) StreamEvent(event api.Event) error {
  356. return d.client.StreamEvent(event, d.opts.ProjectID, d.opts.ClusterID, d.release.Name, d.release.Namespace)
  357. }
  358. type NestedMapFieldNotFoundError struct {
  359. Field string
  360. }
  361. func (e *NestedMapFieldNotFoundError) Error() string {
  362. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  363. }
  364. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  365. var res map[string]interface{}
  366. curr := obj
  367. for _, field := range fields {
  368. objField, ok := curr[field]
  369. if !ok {
  370. return nil, &NestedMapFieldNotFoundError{field}
  371. }
  372. res, ok = objField.(map[string]interface{})
  373. if !ok {
  374. return nil, fmt.Errorf("%s is not a nested object", field)
  375. }
  376. curr = res
  377. }
  378. return res, nil
  379. }