deploy.go 13 KB

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