deploy.go 12 KB

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