deploy.go 12 KB

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