deploy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. type EventStatus int64
  45. const (
  46. EventStatusSuccess EventStatus = 1
  47. EventStatusInProgress = 2
  48. EventStatusFailed = 3
  49. )
  50. // Event represents an event that happens during
  51. type Event struct {
  52. Id string // events with the same id wil be treated the same, and the highest index one is retained
  53. Name string
  54. Index int64 // priority of the event, used for sorting
  55. Status EventStatus
  56. Info string // extra information (can be error or success)
  57. }
  58. // NewDeployAgent creates a new DeployAgent given a Porter API client, application
  59. // name, and DeployOpts.
  60. func NewDeployAgent(client *api.Client, app string, opts *DeployOpts) (*DeployAgent, error) {
  61. deployAgent := &DeployAgent{
  62. App: app,
  63. opts: opts,
  64. client: client,
  65. env: make(map[string]string),
  66. }
  67. // get release from Porter API
  68. release, err := client.GetRelease(context.TODO(), opts.ProjectID, opts.ClusterID, opts.Namespace, app)
  69. if err != nil {
  70. return nil, err
  71. }
  72. deployAgent.release = release
  73. // set an environment prefix to avoid collisions
  74. deployAgent.envPrefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  75. strings.ToUpper(app), "-", "_", -1,
  76. ))
  77. // get docker agent
  78. agent, err := docker.NewAgentWithAuthGetter(client, opts.ProjectID)
  79. if err != nil {
  80. return nil, err
  81. }
  82. deployAgent.agent = agent
  83. // if build method is not set, determine based on release config
  84. if opts.Method == "" {
  85. if release.GitActionConfig != nil {
  86. // if the git action config exists, and dockerfile path is not empty, build type
  87. // is docker
  88. if release.GitActionConfig.DockerfilePath != "" {
  89. deployAgent.opts.Method = DeployBuildTypeDocker
  90. } else {
  91. // otherwise build type is pack
  92. deployAgent.opts.Method = DeployBuildTypePack
  93. }
  94. } else {
  95. // if the git action config does not exist, we use docker by default
  96. deployAgent.opts.Method = DeployBuildTypeDocker
  97. }
  98. }
  99. if deployAgent.opts.Method == DeployBuildTypeDocker {
  100. if release.GitActionConfig != nil {
  101. deployAgent.dockerfilePath = release.GitActionConfig.DockerfilePath
  102. }
  103. if deployAgent.opts.LocalDockerfile != "" {
  104. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  105. }
  106. if deployAgent.opts.LocalDockerfile == "" {
  107. deployAgent.dockerfilePath = "./Dockerfile"
  108. }
  109. }
  110. // if the git action config is not set, we use local builds since pulling remote source
  111. // will fail. we set the image based on the git action config or the image written in the
  112. // helm values
  113. if release.GitActionConfig == nil {
  114. deployAgent.opts.Local = true
  115. imageRepo, err := deployAgent.getReleaseImage()
  116. if err != nil {
  117. return nil, err
  118. }
  119. deployAgent.imageRepo = imageRepo
  120. deployAgent.dockerfilePath = deployAgent.opts.LocalDockerfile
  121. } else {
  122. deployAgent.imageRepo = release.GitActionConfig.ImageRepoURI
  123. }
  124. deployAgent.tag = opts.OverrideTag
  125. return deployAgent, nil
  126. }
  127. // GetBuildEnv retrieves the build env from the release config and returns it
  128. func (d *DeployAgent) GetBuildEnv() (map[string]string, error) {
  129. return GetEnvFromConfig(d.release.Config)
  130. }
  131. // SetBuildEnv sets the build env vars in the process so that other commands can
  132. // use them
  133. func (d *DeployAgent) SetBuildEnv(envVars map[string]string) error {
  134. d.env = envVars
  135. // iterate through env and set the environment variables for the process
  136. // these are prefixed with PORTER_<RELEASE> to avoid collisions. We use
  137. // these prefixed env when calling a custom build command as a child process.
  138. for key, val := range envVars {
  139. prefixedKey := fmt.Sprintf("%s_%s", d.envPrefix, key)
  140. err := os.Setenv(prefixedKey, val)
  141. if err != nil {
  142. return err
  143. }
  144. }
  145. return nil
  146. }
  147. // WriteBuildEnv writes the build env to either a file or stdout
  148. func (d *DeployAgent) WriteBuildEnv(fileDest string) error {
  149. // join lines together
  150. lines := make([]string, 0)
  151. // use os.Environ to get output already formatted as KEY=value
  152. for _, line := range os.Environ() {
  153. // filter for PORTER_<RELEASE> and strip prefix
  154. if strings.Contains(line, d.envPrefix+"_") {
  155. lines = append(lines, strings.Split(line, d.envPrefix+"_")[1])
  156. }
  157. }
  158. output := strings.Join(lines, "\n")
  159. if fileDest != "" {
  160. ioutil.WriteFile(fileDest, []byte(output), 0700)
  161. } else {
  162. fmt.Println(output)
  163. }
  164. return nil
  165. }
  166. // Build uses the deploy agent options to build a new container image from either
  167. // buildpack or docker.
  168. func (d *DeployAgent) Build() error {
  169. // if build is not local, fetch remote source
  170. var basePath string
  171. buildCtx := d.opts.LocalPath
  172. var err error
  173. if !d.opts.Local {
  174. zipResp, err := d.client.GetRepoZIPDownloadURL(
  175. context.Background(),
  176. d.opts.ProjectID,
  177. d.release.GitActionConfig,
  178. )
  179. if err != nil {
  180. return err
  181. }
  182. // download the repository from remote source into a temp directory
  183. basePath, err = d.downloadRepoToDir(zipResp.URLString)
  184. if err != nil {
  185. return err
  186. }
  187. if d.tag == "" {
  188. shortRef := fmt.Sprintf("%.7s", zipResp.LatestCommitSHA)
  189. d.tag = shortRef
  190. }
  191. } else {
  192. basePath, err = filepath.Abs(".")
  193. if err != nil {
  194. return err
  195. }
  196. }
  197. if d.tag == "" {
  198. currImageSection := d.release.Config["image"].(map[string]interface{})
  199. d.tag = currImageSection["tag"].(string)
  200. }
  201. err = d.pullCurrentReleaseImage()
  202. buildAgent := &BuildAgent{
  203. SharedOpts: d.opts.SharedOpts,
  204. client: d.client,
  205. imageRepo: d.imageRepo,
  206. env: d.env,
  207. imageExists: d.imageExists,
  208. }
  209. // if image is not found, don't return an error
  210. if err != nil && err != docker.PullImageErrNotFound {
  211. return err
  212. } else if err != nil && err == docker.PullImageErrNotFound {
  213. fmt.Println("could not find image, moving to build step")
  214. d.imageExists = false
  215. }
  216. if d.opts.Method == DeployBuildTypeDocker {
  217. return buildAgent.BuildDocker(
  218. d.agent,
  219. basePath,
  220. buildCtx,
  221. d.dockerfilePath,
  222. d.tag,
  223. )
  224. }
  225. return buildAgent.BuildPack(d.agent, buildCtx, d.tag)
  226. }
  227. // Push pushes a local image to the remote repository linked in the release
  228. func (d *DeployAgent) Push() error {
  229. return d.agent.PushImage(fmt.Sprintf("%s:%s", d.imageRepo, d.tag))
  230. }
  231. // UpdateImageAndValues updates the current image for a release, along with new
  232. // configuration passed in via overrrideValues. If overrideValues is nil, it just
  233. // reuses the configuration set for the application. If overrideValues is not nil,
  234. // it will merge the overriding values with the existing configuration.
  235. func (d *DeployAgent) UpdateImageAndValues(overrideValues map[string]interface{}) error {
  236. mergedValues := utils.CoalesceValues(d.release.Config, overrideValues)
  237. // overwrite the tag based on a new image
  238. currImageSection := mergedValues["image"].(map[string]interface{})
  239. // if the current image section is hello-porter, the image must be overriden
  240. if currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter" ||
  241. currImageSection["repository"] == "public.ecr.aws/o1j4x7p4/hello-porter-job" {
  242. newImage, err := d.getReleaseImage()
  243. if err != nil {
  244. return fmt.Errorf("could not overwrite hello-porter image: %s", err.Error())
  245. }
  246. currImageSection["repository"] = newImage
  247. // set to latest just to be safe -- this will be overriden if "d.tag" is set in
  248. // the agent
  249. currImageSection["tag"] = "latest"
  250. }
  251. if d.tag != "" && currImageSection["tag"] != d.tag {
  252. currImageSection["tag"] = d.tag
  253. }
  254. bytes, err := json.Marshal(mergedValues)
  255. if err != nil {
  256. return err
  257. }
  258. return d.client.UpgradeRelease(
  259. context.Background(),
  260. d.opts.ProjectID,
  261. d.opts.ClusterID,
  262. d.release.Name,
  263. &api.UpgradeReleaseRequest{
  264. Values: string(bytes),
  265. Namespace: d.release.Namespace,
  266. },
  267. )
  268. }
  269. // GetEnvFromConfig gets the env vars for a standard Porter template config. These env
  270. // vars are found at `container.env.normal`.
  271. func GetEnvFromConfig(config map[string]interface{}) (map[string]string, error) {
  272. envConfig, err := getNestedMap(config, "container", "env", "normal")
  273. // if the field is not found, set envConfig to an empty map; this release has no env set
  274. if e := (&NestedMapFieldNotFoundError{}); errors.As(err, &e) {
  275. envConfig = make(map[string]interface{})
  276. } else if err != nil {
  277. return nil, fmt.Errorf("could not get environment variables from release: %s", err.Error())
  278. }
  279. mapEnvConfig := make(map[string]string)
  280. for key, val := range envConfig {
  281. valStr, ok := val.(string)
  282. if !ok {
  283. return nil, fmt.Errorf("could not cast environment variables to object")
  284. }
  285. // if the value contains PORTERSECRET, this is a "dummy" env that gets injected during
  286. // run-time, so we ignore it
  287. if !strings.Contains(valStr, "PORTERSECRET") {
  288. mapEnvConfig[key] = valStr
  289. }
  290. }
  291. return mapEnvConfig, nil
  292. }
  293. func (d *DeployAgent) getReleaseImage() (string, error) {
  294. if d.release.ImageRepoURI != "" {
  295. return d.release.ImageRepoURI, nil
  296. }
  297. // get the image from the conig
  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. repoInterface, ok := imageConfig["repository"]
  303. if !ok {
  304. return "", fmt.Errorf("repository field does not exist for image")
  305. }
  306. repoStr, ok := repoInterface.(string)
  307. if !ok {
  308. return "", fmt.Errorf("could not cast image.image field to string")
  309. }
  310. return repoStr, nil
  311. }
  312. func (d *DeployAgent) pullCurrentReleaseImage() error {
  313. // pull the currently deployed image to use cache, if possible
  314. imageConfig, err := getNestedMap(d.release.Config, "image")
  315. if err != nil {
  316. return fmt.Errorf("could not get image config from release: %s", err.Error())
  317. }
  318. tagInterface, ok := imageConfig["tag"]
  319. if !ok {
  320. return fmt.Errorf("tag field does not exist for image")
  321. }
  322. tagStr, ok := tagInterface.(string)
  323. if !ok {
  324. return fmt.Errorf("could not cast image.tag field to string")
  325. }
  326. fmt.Printf("attempting to pull image: %s\n", fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  327. return d.agent.PullImage(fmt.Sprintf("%s:%s", d.imageRepo, tagStr))
  328. }
  329. func (d *DeployAgent) downloadRepoToDir(downloadURL string) (string, error) {
  330. dstDir := filepath.Join(homedir.HomeDir(), ".porter")
  331. downloader := &github.ZIPDownloader{
  332. ZipFolderDest: dstDir,
  333. AssetFolderDest: dstDir,
  334. ZipName: fmt.Sprintf("%s.zip", strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)),
  335. RemoveAfterDownload: true,
  336. }
  337. err := downloader.DownloadToFile(downloadURL)
  338. if err != nil {
  339. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  340. }
  341. err = downloader.UnzipToDir()
  342. if err != nil {
  343. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  344. }
  345. var res string
  346. dstFiles, err := ioutil.ReadDir(dstDir)
  347. for _, info := range dstFiles {
  348. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(d.release.GitActionConfig.GitRepo, "/", "-", 1)) {
  349. res = filepath.Join(dstDir, info.Name())
  350. }
  351. }
  352. if res == "" {
  353. return "", fmt.Errorf("unzipped file not found on host")
  354. }
  355. return res, nil
  356. }
  357. func (d *DeployAgent) StreamEvent(event *Event) error {
  358. return nil
  359. }
  360. type NestedMapFieldNotFoundError struct {
  361. Field string
  362. }
  363. func (e *NestedMapFieldNotFoundError) Error() string {
  364. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  365. }
  366. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  367. var res map[string]interface{}
  368. curr := obj
  369. for _, field := range fields {
  370. objField, ok := curr[field]
  371. if !ok {
  372. return nil, &NestedMapFieldNotFoundError{field}
  373. }
  374. res, ok = objField.(map[string]interface{})
  375. if !ok {
  376. return nil, fmt.Errorf("%s is not a nested object", field)
  377. }
  378. curr = res
  379. }
  380. return res, nil
  381. }