deploy.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. "k8s.io/client-go/util/homedir"
  14. )
  15. // DeployAgent handles the deployment and redeployment of an application on Porter
  16. type DeployAgent struct {
  17. App string
  18. client *api.Client
  19. release *api.GetReleaseResponse
  20. agent *docker.Agent
  21. opts *DeployOpts
  22. tag string
  23. envPrefix string
  24. }
  25. // DeployOpts are the options for creating a new DeployAgent
  26. type DeployOpts struct {
  27. ProjectID uint
  28. ClusterID uint
  29. Namespace string
  30. }
  31. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  32. // name, and DeployOpts.
  33. func NewDeployAgent(client *api.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  34. deployAgent := &DeployAgent{
  35. App: app,
  36. opts: opts,
  37. client: client,
  38. }
  39. // get release from Porter API
  40. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  41. if err != nil {
  42. return nil, err
  43. }
  44. deployAgent.release = release
  45. // set an environment prefix to avoid collisions
  46. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  47. strings.ToUpper(app), "-", "_", -1,
  48. ))
  49. // get docker agent
  50. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  51. if err != nil {
  52. return nil, err
  53. }
  54. deployAgent.agent = agent
  55. return deployAgent, nil
  56. }
  57. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  58. return d.getEnvFromRelease()
  59. }
  60. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  61. // iterate through env and set the environment variables for the process
  62. // these are prefixed with PORTER_<RELEASE> to avoid collisions
  63. for key, val := range envVars {
  64. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  65. err := os.Setenv(prefixedKey, val)
  66. if err != nil {
  67. return err
  68. }
  69. }
  70. return nil
  71. }
  72. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  73. // join lines together
  74. lines := make([]string, 0)
  75. // use os.Environ to get output already formatted as KEY=value
  76. for _, line := range os.Environ() {
  77. // filter for PORTER_<RELEASE> and strip prefix
  78. if strings.Contains(line, d.envPrefix+"_") {
  79. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  80. }
  81. }
  82. output := strings.Join(lines, "\n")
  83. if fileDest != "" {
  84. ioutil.WriteFile(fileDest, []byte(output), 0700)
  85. } else {
  86. fmt.Println(output)
  87. }
  88. return nil
  89. }
  90. func (d *DeployAgent) Build() error {
  91. zipResp, err := d.client.GetRepoZIPDownloadURL(
  92. context.Background(),
  93. d.opts.ProjectID,
  94. d.release.GitActionConfig,
  95. )
  96. if err != nil {
  97. return err
  98. }
  99. // download the repository from remote source into a temp directory
  100. dst, err := d.downloadRepoToDir(zipResp.URLString)
  101. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  102. if err != nil {
  103. return err
  104. }
  105. agent, err := docker.NewAgentWithAuthGetter(d.client, d.opts.ProjectID)
  106. if err != nil {
  107. return err
  108. }
  109. err = d.pullCurrentReleaseImage()
  110. // if image is not found, don't return an error
  111. if err != nil && err != docker.PullImageErrNotFound {
  112. return err
  113. } else if err != nil && err == docker.PullImageErrNotFound {
  114. fmt.Println("could not find image, moving to build step")
  115. }
  116. // case on Dockerfile path
  117. if d.release.GitActionConfig.DockerfilePath != "" {
  118. err = agent.BuildLocal(
  119. d.release.GitActionConfig.DockerfilePath,
  120. fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, shortRef),
  121. dst,
  122. )
  123. if err != nil {
  124. return err
  125. }
  126. }
  127. d.tag = shortRef
  128. return nil
  129. }
  130. func (d *DeployAgent) Deploy() error {
  131. // push the created image
  132. err := d.agent.PushImage(fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, d.tag))
  133. if err != nil {
  134. return err
  135. }
  136. releaseExt, err := d.client.GetReleaseWebhook(
  137. context.Background(),
  138. d.opts.ProjectID,
  139. d.opts.ClusterID,
  140. d.release.Name,
  141. d.release.Namespace,
  142. )
  143. if err != nil {
  144. return err
  145. }
  146. return d.client.DeployWithWebhook(
  147. context.Background(),
  148. releaseExt.WebhookToken,
  149. d.tag,
  150. )
  151. }
  152. // func deployWithNewTag(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  153. // if release == nil {
  154. // err := deployInit(resp, client, args)
  155. // if err != nil {
  156. // return err
  157. // }
  158. // }
  159. // }
  160. // HELPER METHODS
  161. func (d *DeployAgent) getEnvFromRelease() (map[string]string, error) {
  162. envConfig, err := getNestedMap(d.release.Config, "container", "env", "normal")
  163. // if the field is not found, set envConfig to an empty map; this release has no env set
  164. if e := (&NestedMapFieldNotFoundError{}); errors.As(err, &e) {
  165. envConfig = make(map[string]interface{})
  166. } else if err != nil {
  167. return nil, fmt.Errorf("could not get environment variables from release: %s", err.Error())
  168. }
  169. mapEnvConfig := make(map[string]string)
  170. for key, val := range envConfig {
  171. valStr, ok := val.(string)
  172. if !ok {
  173. return nil, fmt.Errorf("could not cast environment variables to object")
  174. }
  175. mapEnvConfig[key] = valStr
  176. }
  177. return mapEnvConfig, nil
  178. }
  179. type NestedMapFieldNotFoundError struct {
  180. Field string
  181. }
  182. func (e *NestedMapFieldNotFoundError) Error() string {
  183. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  184. }
  185. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  186. var res map[string]interface{}
  187. curr := obj
  188. for _, field := range fields {
  189. objField, ok := curr[field]
  190. if !ok {
  191. return nil, &NestedMapFieldNotFoundError{field}
  192. }
  193. res, ok = objField.(map[string]interface{})
  194. if !ok {
  195. return nil, fmt.Errorf("%s is not a nested object", field)
  196. }
  197. curr = res
  198. }
  199. return res, nil
  200. }
  201. func (d *DeployAgent) pullCurrentReleaseImage() error {
  202. // pull the currently deployed image to use cache, if possible
  203. imageConfig, err := getNestedMap(d.release.Config, "image")
  204. if err != nil {
  205. return fmt.Errorf("could not get image config from release: %s", err.Error())
  206. }
  207. tagInterface, ok := imageConfig["tag"]
  208. if !ok {
  209. return fmt.Errorf("tag field does not exist for image")
  210. }
  211. tagStr, ok := tagInterface.(string)
  212. if !ok {
  213. return fmt.Errorf("could not cast image.tag field to string")
  214. }
  215. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tagStr))
  216. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.release.GitActionConfig.ImageRepoURI, tagStr))
  217. }
  218. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  219. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  220. downloader := &github.ZIPDownloader{
  221. ZipFolderDest: dstDir,
  222. AssetFolderDest: dstDir,
  223. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  224. RemoveAfterDownload: true,
  225. }
  226. err := downloader.DownloadToFile(downloadURL)
  227. if err != nil {
  228. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  229. }
  230. err = downloader.UnzipToDir()
  231. if err != nil {
  232. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  233. }
  234. var res string
  235. dstFiles, err := ioutil.ReadDir(dstDir)
  236. for _, info := range dstFiles {
  237. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  238. res = filepath.Join(dstDir, info.Name())
  239. }
  240. }
  241. if res == "" {
  242. return "", fmt.Errorf("unzipped file not found on host")
  243. }
  244. return res, nil
  245. }