deploy.go 13 KB

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