deploy.go 9.9 KB

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