deploy.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. package deploy
  2. import (
  3. "context"
  4. "errors"
  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/cli/cmd/pack"
  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. buildType deployBuildType
  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. }
  37. // DeployOpts are the options for creating a new DeployAgent
  38. type DeployOpts struct {
  39. ProjectID uint
  40. ClusterID uint
  41. Namespace string
  42. Local bool
  43. LocalPath string
  44. OverrideTag string
  45. }
  46. var ErrNoGitActionConfig error = fmt.Errorf("specified release does not have a git action config")
  47. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  48. // name, and DeployOpts.
  49. func NewDeployAgent(client *api.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  50. deployAgent := &DeployAgent{
  51. App: app,
  52. opts: opts,
  53. client: client,
  54. env: make(map[string]string),
  55. }
  56. // get release from Porter API
  57. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  58. if err != nil {
  59. return nil, err
  60. }
  61. // if the git action config is nil, return an error
  62. if release.GitActionConfig == nil {
  63. return nil, ErrNoGitActionConfig
  64. }
  65. deployAgent.release = release
  66. // set an environment prefix to avoid collisions
  67. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  68. strings.ToUpper(app), "-", "_", -1,
  69. ))
  70. // get docker agent
  71. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  72. if err != nil {
  73. return nil, err
  74. }
  75. deployAgent.agent = agent
  76. if release.GitActionConfig.DockerfilePath != "" {
  77. deployAgent.buildType = deployBuildTypeDocker
  78. } else {
  79. deployAgent.buildType = deployBuildTypePack
  80. }
  81. deployAgent.tag = opts.OverrideTag
  82. return deployAgent, nil
  83. }
  84. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  85. return d.getEnvFromRelease()
  86. }
  87. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  88. d.env = envVars
  89. // iterate through env and set the environment variables for the process
  90. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  91. // these prefixed env when calling a custom build command as a child process.
  92. for key, val := range envVars {
  93. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  94. err := os.Setenv(prefixedKey, val)
  95. if err != nil {
  96. return err
  97. }
  98. }
  99. return nil
  100. }
  101. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  102. // join lines together
  103. lines := make([]string, 0)
  104. // use os.Environ to get output already formatted as KEY=value
  105. for _, line := range os.Environ() {
  106. // filter for PORTER_<RELEASE> and strip prefix
  107. if strings.Contains(line, d.envPrefix+"_") {
  108. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  109. }
  110. }
  111. output := strings.Join(lines, "\n")
  112. if fileDest != "" {
  113. ioutil.WriteFile(fileDest, []byte(output), 0700)
  114. } else {
  115. fmt.Println(output)
  116. }
  117. return nil
  118. }
  119. func (d *DeployAgent) Build() error {
  120. // if build is not local, fetch remote source
  121. var dst string
  122. var err error
  123. if !d.opts.Local {
  124. zipResp, err := d.client.GetRepoZIPDownloadURL(
  125. context.Background(),
  126. d.opts.ProjectID,
  127. d.release.GitActionConfig,
  128. )
  129. if err != nil {
  130. return err
  131. }
  132. // download the repository from remote source into a temp directory
  133. dst, err = d.downloadRepoToDir(zipResp.URLString)
  134. if d.tag == "" {
  135. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  136. d.tag = shortRef
  137. }
  138. if err != nil {
  139. return err
  140. }
  141. } else {
  142. dst = filepath.Dir(d.opts.LocalPath)
  143. }
  144. if d.tag == "" {
  145. d.tag = "latest"
  146. }
  147. err = d.pullCurrentReleaseImage()
  148. // if image is not found, don't return an error
  149. if err != nil && err != docker.PullImageErrNotFound {
  150. return err
  151. } else if err != nil && err == docker.PullImageErrNotFound {
  152. fmt.Println("could not find image, moving to build step")
  153. d.imageExists = false
  154. }
  155. if d.buildType == deployBuildTypeDocker {
  156. return d.BuildDocker(dst, d.tag)
  157. }
  158. return d.BuildPack(dst, d.tag)
  159. }
  160. func (d *DeployAgent) BuildDocker(dst, tag string) error {
  161. opts := &docker.BuildOpts{
  162. ImageRepo: d.release.GitActionConfig.ImageRepoURI,
  163. Tag: tag,
  164. BuildContext: dst,
  165. Env: d.env,
  166. }
  167. return d.agent.BuildLocal(
  168. opts,
  169. d.release.GitActionConfig.DockerfilePath,
  170. )
  171. }
  172. func (d *DeployAgent) BuildPack(dst, tag string) error {
  173. // retag the image with "pack-cache" tag so that it doesn't re-pull from the registry
  174. if d.imageExists {
  175. err := d.agent.TagImage(
  176. fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tag),
  177. fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, "pack-cache"),
  178. )
  179. if err != nil {
  180. return err
  181. }
  182. }
  183. // create pack agent and build opts
  184. packAgent := &pack.Agent{}
  185. opts := &docker.BuildOpts{
  186. ImageRepo: d.release.GitActionConfig.ImageRepoURI,
  187. // We tag the image with a stable param "pack-cache" so that pack can use the
  188. // local image without attempting to re-pull from registry. We handle getting
  189. // registry credentials and pushing/pulling the image.
  190. Tag: "pack-cache",
  191. BuildContext: dst,
  192. Env: d.env,
  193. }
  194. // call builder
  195. err := packAgent.Build(opts)
  196. if err != nil {
  197. return err
  198. }
  199. return d.agent.TagImage(
  200. fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, "pack-cache"),
  201. fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tag),
  202. )
  203. }
  204. func (d *DeployAgent) Deploy() error {
  205. // push the created image
  206. err := d.agent.PushImage(fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, d.tag))
  207. if err != nil {
  208. return err
  209. }
  210. releaseExt, err := d.client.GetReleaseWebhook(
  211. context.Background(),
  212. d.opts.ProjectID,
  213. d.opts.ClusterID,
  214. d.release.Name,
  215. d.release.Namespace,
  216. )
  217. if err != nil {
  218. return err
  219. }
  220. return d.client.DeployWithWebhook(
  221. context.Background(),
  222. releaseExt.WebhookToken,
  223. d.tag,
  224. )
  225. }
  226. // HELPER METHODS
  227. func (d *DeployAgent) getEnvFromRelease() (map[string]string, error) {
  228. envConfig, err := getNestedMap(d.release.Config, "container", "env", "normal")
  229. // if the field is not found, set envConfig to an empty map; this release has no env set
  230. if e := (&NestedMapFieldNotFoundError{}); errors.As(err, &e) {
  231. envConfig = make(map[string]interface{})
  232. } else if err != nil {
  233. return nil, fmt.Errorf("could not get environment variables from release: %s", err.Error())
  234. }
  235. mapEnvConfig := make(map[string]string)
  236. for key, val := range envConfig {
  237. valStr, ok := val.(string)
  238. if !ok {
  239. return nil, fmt.Errorf("could not cast environment variables to object")
  240. }
  241. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  242. // run-time, so we ignore it
  243. if !strings.Contains(valStr, "PORTERSECRET") {
  244. mapEnvConfig[key] = valStr
  245. }
  246. }
  247. return mapEnvConfig, nil
  248. }
  249. type NestedMapFieldNotFoundError struct {
  250. Field string
  251. }
  252. func (e *NestedMapFieldNotFoundError) Error() string {
  253. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  254. }
  255. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  256. var res map[string]interface{}
  257. curr := obj
  258. for _, field := range fields {
  259. objField, ok := curr[field]
  260. if !ok {
  261. return nil, &NestedMapFieldNotFoundError{field}
  262. }
  263. res, ok = objField.(map[string]interface{})
  264. if !ok {
  265. return nil, fmt.Errorf("%s is not a nested object", field)
  266. }
  267. curr = res
  268. }
  269. return res, nil
  270. }
  271. func (d *DeployAgent) pullCurrentReleaseImage() error {
  272. // pull the currently deployed image to use cache, if possible
  273. imageConfig, err := getNestedMap(d.release.Config, "image")
  274. if err != nil {
  275. return fmt.Errorf("could not get image config from release: %s", err.Error())
  276. }
  277. tagInterface, ok := imageConfig["tag"]
  278. if !ok {
  279. return fmt.Errorf("tag field does not exist for image")
  280. }
  281. tagStr, ok := tagInterface.(string)
  282. if !ok {
  283. return fmt.Errorf("could not cast image.tag field to string")
  284. }
  285. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tagStr))
  286. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tagStr))
  287. }
  288. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  289. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  290. downloader := &github.ZIPDownloader{
  291. ZipFolderDest: dstDir,
  292. AssetFolderDest: dstDir,
  293. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  294. RemoveAfterDownload: true,
  295. }
  296. err := downloader.DownloadToFile(downloadURL)
  297. if err != nil {
  298. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  299. }
  300. err = downloader.UnzipToDir()
  301. if err != nil {
  302. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  303. }
  304. var res string
  305. dstFiles, err := ioutil.ReadDir(dstDir)
  306. for _, info := range dstFiles {
  307. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  308. res = filepath.Join(dstDir, info.Name())
  309. }
  310. }
  311. if res == "" {
  312. return "", fmt.Errorf("unzipped file not found on host")
  313. }
  314. return res, nil
  315. }