2
0

deploy.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package deploy
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. api "github.com/porter-dev/porter/api/client"
  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. client *api.Client
  28. release *api.GetReleaseResponse
  29. agent *docker.Agent
  30. opts *DeployOpts
  31. tag string
  32. envPrefix string
  33. env map[string]string
  34. imageExists bool
  35. imageRepo string
  36. dockerfilePath string
  37. }
  38. // DeployOpts are the options for creating a new DeployAgent
  39. type DeployOpts struct {
  40. ProjectID uint
  41. ClusterID uint
  42. Namespace string
  43. Local bool
  44. LocalPath string
  45. LocalDockerfile string
  46. OverrideTag string
  47. Method DeployBuildType
  48. }
  49. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  50. // name, and DeployOpts.
  51. func NewDeployAgent(client *api.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  52. deployAgent := &DeployAgent{
  53. App: app,
  54. opts: opts,
  55. client: client,
  56. env: make(map[string]string),
  57. }
  58. // get release from Porter API
  59. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  60. if err != nil {
  61. return nil, err
  62. }
  63. deployAgent.release = release
  64. // set an environment prefix to avoid collisions
  65. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  66. strings.ToUpper(app), "-", "_", -1,
  67. ))
  68. // get docker agent
  69. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  70. if err != nil {
  71. return nil, err
  72. }
  73. deployAgent.agent = agent
  74. // if build method is not set, determine based on release config
  75. if opts.Method == "" {
  76. if release.GitActionConfig != nil {
  77. // if the git action config exists, and dockerfile path is not empty, build type
  78. // is docker
  79. if release.GitActionConfig.DockerfilePath != "" {
  80. deployAgent.opts.Method = deployBuildTypeDocker
  81. }
  82. // otherwise build type is pack
  83. deployAgent.opts.Method = deployBuildTypePack
  84. } else {
  85. // if the git action config does not exist, we use pack by default
  86. deployAgent.opts.Method = deployBuildTypePack
  87. }
  88. }
  89. if deployAgent.opts.Method == deployBuildTypeDocker {
  90. if release.GitActionConfig != nil {
  91. deployAgent.dockerfilePath = release.GitActionConfig.DockerfilePath
  92. }
  93. if deployAgent.opts.LocalDockerfile != "" {
  94. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  95. }
  96. if deployAgent.opts.LocalDockerfile == "" {
  97. deployAgent.dockerfilePath = "./Dockerfile"
  98. }
  99. }
  100. // if the git action config is not set, we use local builds since pulling remote source
  101. // will fail. we set the image based on the git action config or the image written in the
  102. // helm values
  103. if release.GitActionConfig == nil {
  104. deployAgent.opts.Local = true
  105. imageRepo, err := deployAgent.getReleaseImage()
  106. if err != nil {
  107. return nil, err
  108. }
  109. deployAgent.imageRepo = imageRepo
  110. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  111. } else {
  112. deployAgent.imageRepo = release.GitActionConfig.ImageRepoURI
  113. }
  114. deployAgent.tag = opts.OverrideTag
  115. return deployAgent, nil
  116. }
  117. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  118. return d.getEnvFromRelease()
  119. }
  120. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  121. d.env = envVars
  122. // iterate through env and set the environment variables for the process
  123. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  124. // these prefixed env when calling a custom build command as a child process.
  125. for key, val := range envVars {
  126. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  127. err := os.Setenv(prefixedKey, val)
  128. if err != nil {
  129. return err
  130. }
  131. }
  132. return nil
  133. }
  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. func (d *DeployAgent) Build() error {
  153. // if build is not local, fetch remote source
  154. var dst string
  155. var err error
  156. if !d.opts.Local {
  157. zipResp, err := d.client.GetRepoZIPDownloadURL(
  158. context.Background(),
  159. d.opts.ProjectID,
  160. d.release.GitActionConfig,
  161. )
  162. if err != nil {
  163. return err
  164. }
  165. // download the repository from remote source into a temp directory
  166. dst, err = d.downloadRepoToDir(zipResp.URLString)
  167. if d.tag == "" {
  168. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  169. d.tag = shortRef
  170. }
  171. if err != nil {
  172. return err
  173. }
  174. } else {
  175. dst = filepath.Dir(d.opts.LocalPath)
  176. }
  177. if d.tag == "" {
  178. d.tag = "latest"
  179. }
  180. err = d.pullCurrentReleaseImage()
  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 d.BuildDocker(dst, d.tag)
  190. }
  191. return d.BuildPack(dst, d.tag)
  192. }
  193. func (d *DeployAgent) BuildDocker(dst, tag string) error {
  194. opts := &docker.BuildOpts{
  195. ImageRepo: d.imageRepo,
  196. Tag: tag,
  197. BuildContext: dst,
  198. Env: d.env,
  199. }
  200. return d.agent.BuildLocal(
  201. opts,
  202. d.dockerfilePath,
  203. )
  204. }
  205. func (d *DeployAgent) BuildPack(dst, tag string) error {
  206. // retag the image with "pack-cache" tag so that it doesn't re-pull from the registry
  207. if d.imageExists {
  208. err := d.agent.TagImage(
  209. fmt.Sprintf("%s:%s", d.imageRepo, tag),
  210. fmt.Sprintf("%s:%s", d.imageRepo, "pack-cache"),
  211. )
  212. if err != nil {
  213. return err
  214. }
  215. }
  216. // create pack agent and build opts
  217. packAgent := &pack.Agent{}
  218. opts := &docker.BuildOpts{
  219. ImageRepo: d.imageRepo,
  220. // We tag the image with a stable param "pack-cache" so that pack can use the
  221. // local image without attempting to re-pull from registry. We handle getting
  222. // registry credentials and pushing/pulling the image.
  223. Tag: "pack-cache",
  224. BuildContext: dst,
  225. Env: d.env,
  226. }
  227. // call builder
  228. err := packAgent.Build(opts)
  229. if err != nil {
  230. return err
  231. }
  232. return d.agent.TagImage(
  233. fmt.Sprintf("%s:%s", d.imageRepo, "pack-cache"),
  234. fmt.Sprintf("%s:%s", d.imageRepo, tag),
  235. )
  236. }
  237. func (d *DeployAgent) Push() error {
  238. return d.agent.PushImage(fmt.Sprintf("%s:%s", d.imageRepo, d.tag))
  239. }
  240. func (d *DeployAgent) CallWebhook() error {
  241. releaseExt, err := d.client.GetReleaseWebhook(
  242. context.Background(),
  243. d.opts.ProjectID,
  244. d.opts.ClusterID,
  245. d.release.Name,
  246. d.release.Namespace,
  247. )
  248. if err != nil {
  249. return err
  250. }
  251. return d.client.DeployWithWebhook(
  252. context.Background(),
  253. releaseExt.WebhookToken,
  254. d.tag,
  255. )
  256. }
  257. // HELPER METHODS
  258. func (d *DeployAgent) getEnvFromRelease() (map[string]string, error) {
  259. envConfig, err := getNestedMap(d.release.Config, "container", "env", "normal")
  260. // if the field is not found, set envConfig to an empty map; this release has no env set
  261. if e := (&NestedMapFieldNotFoundError{}); errors.As(err, &e) {
  262. envConfig = make(map[string]interface{})
  263. } else if err != nil {
  264. return nil, fmt.Errorf("could not get environment variables from release: %s", err.Error())
  265. }
  266. mapEnvConfig := make(map[string]string)
  267. for key, val := range envConfig {
  268. valStr, ok := val.(string)
  269. if !ok {
  270. return nil, fmt.Errorf("could not cast environment variables to object")
  271. }
  272. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  273. // run-time, so we ignore it
  274. if !strings.Contains(valStr, "PORTERSECRET") {
  275. mapEnvConfig[key] = valStr
  276. }
  277. }
  278. return mapEnvConfig, nil
  279. }
  280. func (d *DeployAgent) getReleaseImage() (string, error) {
  281. // pull the currently deployed image to use cache, if possible
  282. imageConfig, err := getNestedMap(d.release.Config, "image")
  283. if err != nil {
  284. return "", fmt.Errorf("could not get image config from release: %s", err.Error())
  285. }
  286. repoInterface, ok := imageConfig["repository"]
  287. if !ok {
  288. return "", fmt.Errorf("repository field does not exist for image")
  289. }
  290. repoStr, ok := repoInterface.(string)
  291. if !ok {
  292. return "", fmt.Errorf("could not cast image.image field to string")
  293. }
  294. return repoStr, nil
  295. }
  296. func (d *DeployAgent) pullCurrentReleaseImage() error {
  297. // pull the currently deployed image to use cache, if possible
  298. imageConfig, err := getNestedMap(d.release.Config, "image")
  299. if err != nil {
  300. return fmt.Errorf("could not get image config from release: %s", err.Error())
  301. }
  302. tagInterface, ok := imageConfig["tag"]
  303. if !ok {
  304. return fmt.Errorf("tag field does not exist for image")
  305. }
  306. tagStr, ok := tagInterface.(string)
  307. if !ok {
  308. return fmt.Errorf("could not cast image.tag field to string")
  309. }
  310. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  311. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  312. }
  313. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  314. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  315. downloader := &github.ZIPDownloader{
  316. ZipFolderDest: dstDir,
  317. AssetFolderDest: dstDir,
  318. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  319. RemoveAfterDownload: true,
  320. }
  321. err := downloader.DownloadToFile(downloadURL)
  322. if err != nil {
  323. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  324. }
  325. err = downloader.UnzipToDir()
  326. if err != nil {
  327. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  328. }
  329. var res string
  330. dstFiles, err := ioutil.ReadDir(dstDir)
  331. for _, info := range dstFiles {
  332. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  333. res = filepath.Join(dstDir, info.Name())
  334. }
  335. }
  336. if res == "" {
  337. return "", fmt.Errorf("unzipped file not found on host")
  338. }
  339. return res, nil
  340. }
  341. type NestedMapFieldNotFoundError struct {
  342. Field string
  343. }
  344. func (e *NestedMapFieldNotFoundError) Error() string {
  345. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  346. }
  347. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  348. var res map[string]interface{}
  349. curr := obj
  350. for _, field := range fields {
  351. objField, ok := curr[field]
  352. if !ok {
  353. return nil, &NestedMapFieldNotFoundError{field}
  354. }
  355. res, ok = objField.(map[string]interface{})
  356. if !ok {
  357. return nil, fmt.Errorf("%s is not a nested object", field)
  358. }
  359. curr = res
  360. }
  361. return res, nil
  362. }