deploy.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package cmd
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "github.com/fatih/color"
  11. "github.com/porter-dev/porter/cli/cmd/api"
  12. "github.com/porter-dev/porter/cli/cmd/github"
  13. "github.com/spf13/cobra"
  14. )
  15. var app = ""
  16. // deployCmd represents the "porter deploy" base command when called
  17. // without any subcommands
  18. var deployCmd = &cobra.Command{
  19. Use: "deploy",
  20. Short: "Builds and deploys a specified application given by the --app flag.",
  21. Run: func(cmd *cobra.Command, args []string) {
  22. err := checkLoginAndRun(args, deploy)
  23. if err != nil {
  24. os.Exit(1)
  25. }
  26. },
  27. }
  28. var deployInitCmd = &cobra.Command{
  29. Use: "init",
  30. Short: "Initializes a deployment for a specified application given by the --app flag.",
  31. Run: func(cmd *cobra.Command, args []string) {
  32. err := checkLoginAndRun(args, deployInit)
  33. if err != nil {
  34. os.Exit(1)
  35. }
  36. },
  37. }
  38. var getEnvFileDest = ""
  39. var deployGetEnvCmd = &cobra.Command{
  40. Use: "get-env",
  41. Short: "Gets environment variables for a deployment for a specified application given by the --app flag.",
  42. Long: fmt.Sprintf(`Gets environment variables for a deployment for a specified application given by the --app flag.
  43. By default, env variables are printed via stdout for use in downstream commands, for example:
  44. %s
  45. Output can also be written to a dotenv file via the --file flag, which should specify the destination
  46. path for a .env file. For example:
  47. %s
  48. `,
  49. color.New(color.FgGreen).Sprintf("porter deploy get-env --app <app> | xargs"),
  50. color.New(color.FgGreen).Sprintf("porter deploy get-env --app <app> --file .env"),
  51. ),
  52. Run: func(cmd *cobra.Command, args []string) {
  53. err := checkLoginAndRun(args, deployGetEnv)
  54. if err != nil {
  55. os.Exit(1)
  56. }
  57. },
  58. }
  59. var deployBuildCmd = &cobra.Command{
  60. Use: "build",
  61. Short: "TBD",
  62. Run: func(cmd *cobra.Command, args []string) {
  63. err := checkLoginAndRun(args, deployBuild)
  64. if err != nil {
  65. os.Exit(1)
  66. }
  67. },
  68. }
  69. func init() {
  70. rootCmd.AddCommand(deployCmd)
  71. deployCmd.PersistentFlags().StringVar(
  72. &app,
  73. "app",
  74. "",
  75. "Application in the Porter dashboard",
  76. )
  77. deployCmd.AddCommand(deployInitCmd)
  78. deployCmd.AddCommand(deployGetEnvCmd)
  79. deployGetEnvCmd.PersistentFlags().StringVar(
  80. &getEnvFileDest,
  81. "file",
  82. "",
  83. "file destination for .env files",
  84. )
  85. deployCmd.AddCommand(deployBuildCmd)
  86. }
  87. func deploy(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  88. color.New(color.FgGreen).Println("Deploying app:", app)
  89. return deployInit(resp, client, args)
  90. }
  91. var release *api.GetReleaseResponse = nil
  92. // deployInit first reads the release given by the --app or the --job flag. It then
  93. // configures docker with the registries linked to the project.
  94. func deployInit(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  95. pID := config.Project
  96. cID := config.Cluster
  97. var err error
  98. release, err = client.GetRelease(context.TODO(), pID, cID, namespace, app)
  99. if err != nil {
  100. return err
  101. }
  102. return dockerConfig(resp, client, args)
  103. }
  104. // deployGetEnv retrieves the env from a release and outputs it to either a file
  105. // or stdout depending on getEnvFileDest
  106. func deployGetEnv(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  107. if release == nil {
  108. err := deployInit(resp, client, args)
  109. if err != nil {
  110. return err
  111. }
  112. }
  113. prefix, err := deploySetEnv(client)
  114. if err != nil {
  115. return err
  116. }
  117. // join lines together
  118. lines := make([]string, 0)
  119. // use os.Environ to get output already formatted as KEY=value
  120. for _, line := range os.Environ() {
  121. // filter for PORTER_<RELEASE> and strip prefix
  122. if strings.Contains(line, prefix+"_") {
  123. lines = append(lines, strings.Split(line, prefix+"_")[1])
  124. }
  125. }
  126. output := strings.Join(lines, "\n")
  127. // case on output type
  128. if getEnvFileDest != "" {
  129. ioutil.WriteFile(getEnvFileDest, []byte(output), 0700)
  130. } else {
  131. fmt.Println(output)
  132. }
  133. return nil
  134. }
  135. func deploySetEnv(client *api.Client) (prefix string, err error) {
  136. prefix = fmt.Sprintf("PORTER_%s", strings.Replace(
  137. strings.ToUpper(app), "-", "_", -1,
  138. ))
  139. envVars, err := getEnvFromRelease()
  140. if err != nil {
  141. return prefix, err
  142. }
  143. // iterate through env and set the environment variables for the process
  144. // these are prefixed with PORTER_<RELEASE> to avoid collisions
  145. for key, val := range envVars {
  146. prefixedKey := fmt.Sprintf("%s_%s", prefix, key)
  147. err := os.Setenv(prefixedKey, val)
  148. if err != nil {
  149. return prefix, err
  150. }
  151. }
  152. return prefix, nil
  153. }
  154. func getEnvFromRelease() (map[string]string, error) {
  155. envConfig, err := getNestedMap(release.Config, "container", "env", "normal")
  156. // if the field is not found, set envConfig to an empty map; this release has no env set
  157. if e := (&NestedMapFieldNotFoundError{}); errors.As(err, &e) {
  158. envConfig = make(map[string]interface{})
  159. } else if err != nil {
  160. return nil, fmt.Errorf("could not get environment variables from release: %s", err.Error())
  161. }
  162. mapEnvConfig := make(map[string]string)
  163. for key, val := range envConfig {
  164. valStr, ok := val.(string)
  165. if !ok {
  166. return nil, fmt.Errorf("could not cast environment variables to object")
  167. }
  168. mapEnvConfig[key] = valStr
  169. }
  170. return mapEnvConfig, nil
  171. }
  172. type NestedMapFieldNotFoundError struct {
  173. Field string
  174. }
  175. func (e *NestedMapFieldNotFoundError) Error() string {
  176. return fmt.Sprintf("could not find field %s in configuration", e.Field)
  177. }
  178. func getNestedMap(obj map[string]interface{}, fields ...string) (map[string]interface{}, error) {
  179. var res map[string]interface{}
  180. curr := obj
  181. for _, field := range fields {
  182. objField, ok := curr[field]
  183. if !ok {
  184. return nil, &NestedMapFieldNotFoundError{field}
  185. }
  186. res, ok = objField.(map[string]interface{})
  187. if !ok {
  188. return nil, fmt.Errorf("%s is not a nested object", field)
  189. }
  190. curr = res
  191. }
  192. return res, nil
  193. }
  194. func deployBuild(resp *api.AuthCheckResponse, client *api.Client, args []string) error {
  195. if release == nil {
  196. err := deployInit(resp, client, args)
  197. if err != nil {
  198. return err
  199. }
  200. }
  201. // download the repository from remote source into a temp directory
  202. dst, err := downloadRepoToDir(client)
  203. if err != nil {
  204. return err
  205. }
  206. fmt.Println("DEST IS", dst)
  207. // agent, err := docker.NewAgentFromEnv()
  208. // if err != nil {
  209. // return err
  210. // }
  211. // return agent.BuildLocal("./docker/dev.Dockerfile", "test-porter:latest", "/Users/abelanger/porter/porter-server")
  212. return nil
  213. }
  214. func downloadRepoToDir(client *api.Client) (string, error) {
  215. resp, err := client.GetRepoZIPDownloadURL(
  216. context.Background(),
  217. config.Project,
  218. release.GitActionConfig,
  219. )
  220. if err != nil {
  221. return "", err
  222. }
  223. dstDir := filepath.Join(home, ".porter")
  224. downloader := &github.ZIPDownloader{
  225. ZipFolderDest: dstDir,
  226. AssetFolderDest: dstDir,
  227. ZipName: fmt.Sprintf("%s.zip", strings.Replace(release.GitActionConfig.GitRepo, "/", "-", 1)),
  228. RemoveAfterDownload: true,
  229. }
  230. err = downloader.DownloadToFile(resp.URLString)
  231. if err != nil {
  232. return "", fmt.Errorf("Error downloading to file: %s", err.Error())
  233. }
  234. err = downloader.UnzipToDir()
  235. if err != nil {
  236. return "", fmt.Errorf("Error unzipping to directory: %s", err.Error())
  237. }
  238. var res string
  239. dstFiles, err := ioutil.ReadDir(dstDir)
  240. for _, info := range dstFiles {
  241. if info.Mode().IsDir() && strings.Contains(info.Name(), strings.Replace(release.GitActionConfig.GitRepo, "/", "-", 1)) {
  242. res = filepath.Join(dstDir, info.Name())
  243. }
  244. }
  245. if res == "" {
  246. return "", fmt.Errorf("unzipped file not found on host")
  247. }
  248. return res, nil
  249. }