server.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package commands
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "github.com/fatih/color"
  9. "github.com/porter-dev/porter/cli/cmd/config"
  10. "github.com/porter-dev/porter/cli/cmd/docker"
  11. "github.com/porter-dev/porter/cli/cmd/github"
  12. "github.com/porter-dev/porter/cli/cmd/utils"
  13. "github.com/spf13/cobra"
  14. )
  15. type startOps struct {
  16. imageTag string `form:"required"`
  17. db string `form:"oneof=sqlite postgres"`
  18. driver string `form:"required"`
  19. port *int `form:"required"`
  20. }
  21. var opts = &startOps{}
  22. func registerCommand_Server(cliConf config.CLIConfig, currentProfile string) *cobra.Command {
  23. serverCmd := &cobra.Command{
  24. Use: "server",
  25. Aliases: []string{"svr"},
  26. Short: "Commands to control a local Porter server",
  27. }
  28. // startCmd represents the start command
  29. startCmd := &cobra.Command{
  30. Use: "start",
  31. Short: "Starts a Porter server instance on the host",
  32. Run: func(cmd *cobra.Command, args []string) {
  33. ctx := cmd.Context()
  34. if cliConf.Driver == "docker" {
  35. _ = cliConf.SetDriver("docker", currentProfile)
  36. err := startDocker(
  37. ctx,
  38. cliConf,
  39. opts.imageTag,
  40. opts.db,
  41. *opts.port,
  42. currentProfile,
  43. )
  44. if err != nil {
  45. red := color.New(color.FgRed)
  46. _, _ = red.Println("Error running start:", err.Error())
  47. _, _ = red.Println("Shutting down...")
  48. err = stopDocker(ctx)
  49. if err != nil {
  50. _, _ = red.Println("Shutdown unsuccessful:", err.Error())
  51. }
  52. os.Exit(1)
  53. }
  54. } else {
  55. _ = cliConf.SetDriver("local", currentProfile)
  56. err := startLocal(
  57. ctx,
  58. cliConf,
  59. opts.db,
  60. *opts.port,
  61. currentProfile,
  62. )
  63. if err != nil {
  64. red := color.New(color.FgRed)
  65. _, _ = red.Println("Error running start:", err.Error())
  66. os.Exit(1)
  67. }
  68. }
  69. },
  70. }
  71. stopCmd := &cobra.Command{
  72. Use: "stop",
  73. Short: "Stops a Porter instance running on the Docker engine",
  74. Run: func(cmd *cobra.Command, args []string) {
  75. if cliConf.Driver == "docker" {
  76. if err := stopDocker(cmd.Context()); err != nil {
  77. _, _ = color.New(color.FgRed).Println("Shutdown unsuccessful:", err.Error())
  78. os.Exit(1)
  79. }
  80. }
  81. },
  82. }
  83. serverCmd.AddCommand(startCmd)
  84. serverCmd.AddCommand(stopCmd)
  85. serverCmd.PersistentFlags().AddFlagSet(utils.DriverFlagSet)
  86. startCmd.PersistentFlags().StringVar(
  87. &opts.db,
  88. "db",
  89. "sqlite",
  90. "the db to use, one of sqlite or postgres",
  91. )
  92. startCmd.PersistentFlags().StringVar(
  93. &opts.imageTag,
  94. "image-tag",
  95. "latest",
  96. "the Porter image tag to use (if using docker driver)",
  97. )
  98. opts.port = startCmd.PersistentFlags().IntP(
  99. "port",
  100. "p",
  101. 8080,
  102. "the host port to run the server on",
  103. )
  104. return serverCmd
  105. }
  106. func startDocker(ctx context.Context, cliConf config.CLIConfig, imageTag string, db string, port int, currentProfile string) error {
  107. env := []string{
  108. "NODE_ENV=production",
  109. "FULLSTORY_ORG_ID=VXNSS",
  110. }
  111. var porterDB docker.PorterDB
  112. switch db {
  113. case "postgres":
  114. porterDB = docker.Postgres
  115. case "sqlite":
  116. porterDB = docker.SQLite
  117. }
  118. startOpts := &docker.PorterStartOpts{
  119. ProcessID: "main",
  120. ServerImageTag: imageTag,
  121. ServerPort: port,
  122. DB: porterDB,
  123. Env: env,
  124. }
  125. _, _, err := docker.StartPorter(ctx, startOpts)
  126. if err != nil {
  127. return err
  128. }
  129. green := color.New(color.FgGreen)
  130. green.Printf("Server ready: listening on localhost:%d\n", port)
  131. return cliConf.SetHost(fmt.Sprintf("http://localhost:%d", port), currentProfile)
  132. }
  133. func startLocal(ctx context.Context, cliConf config.CLIConfig, db string, port int, currentProfile string) error {
  134. if db == "postgres" {
  135. return fmt.Errorf("postgres not available for local driver, run \"porter server start --db postgres --driver docker\"")
  136. }
  137. err := cliConf.SetHost(fmt.Sprintf("http://localhost:%d", port), currentProfile)
  138. if err != nil {
  139. return fmt.Errorf("failed to set host: %s", err.Error())
  140. }
  141. porterDir := filepath.Join(home, ".porter")
  142. cmdPath := filepath.Join(home, ".porter", "portersvr")
  143. sqlLitePath := filepath.Join(home, ".porter", "porter.db")
  144. staticFilePath := filepath.Join(home, ".porter", "static")
  145. if _, err := os.Stat(cmdPath); os.IsNotExist(err) {
  146. err := downloadMatchingRelease(ctx, porterDir)
  147. if err != nil {
  148. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  149. os.Exit(1)
  150. }
  151. }
  152. // otherwise, check the version flag of the binary
  153. cmdVersionPorter := exec.Command(cmdPath, "--version")
  154. writer := &config.VersionWriter{}
  155. cmdVersionPorter.Stdout = writer
  156. err := cmdVersionPorter.Run()
  157. if err != nil || writer.Version != config.Version {
  158. err := downloadMatchingRelease(ctx, porterDir)
  159. if err != nil {
  160. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  161. os.Exit(1)
  162. }
  163. }
  164. cmdPorter := exec.Command(cmdPath)
  165. cmdPorter.Env = os.Environ()
  166. cmdPorter.Env = append(cmdPorter.Env, []string{
  167. "IS_LOCAL=true",
  168. "SQL_LITE=true",
  169. "SQL_LITE_PATH=" + sqlLitePath,
  170. "STATIC_FILE_PATH=" + staticFilePath,
  171. fmt.Sprintf("SERVER_PORT=%d", port),
  172. "REDIS_ENABLED=false",
  173. }...)
  174. if _, found := os.LookupEnv("GITHUB_ENABLED"); !found {
  175. cmdPorter.Env = append(cmdPorter.Env, "GITHUB_ENABLED=false")
  176. }
  177. if _, found := os.LookupEnv("PROVISIONER_ENABLED"); !found {
  178. cmdPorter.Env = append(cmdPorter.Env, "PROVISIONER_ENABLED=false")
  179. }
  180. cmdPorter.Stdout = os.Stdout
  181. cmdPorter.Stderr = os.Stderr
  182. err = cmdPorter.Run()
  183. if err != nil {
  184. color.New(color.FgRed).Println("Failed:", err.Error())
  185. os.Exit(1)
  186. }
  187. return nil
  188. }
  189. func stopDocker(ctx context.Context) error {
  190. agent, err := docker.NewAgentFromEnv(ctx)
  191. if err != nil {
  192. return err
  193. }
  194. err = agent.StopPorterContainersWithProcessID(ctx, "main", false)
  195. if err != nil {
  196. return err
  197. }
  198. green := color.New(color.FgGreen)
  199. green.Println("Successfully stopped the Porter server.")
  200. return nil
  201. }
  202. func downloadMatchingRelease(ctx context.Context, porterDir string) error {
  203. z := &github.ZIPReleaseGetter{
  204. AssetName: "portersvr",
  205. AssetFolderDest: porterDir,
  206. ZipFolderDest: porterDir,
  207. ZipName: "portersvr_latest.zip",
  208. EntityID: "porter-dev",
  209. RepoName: "porter",
  210. IsPlatformDependent: true,
  211. Downloader: &github.ZIPDownloader{
  212. ZipFolderDest: porterDir,
  213. AssetFolderDest: porterDir,
  214. ZipName: "portersvr_latest.zip",
  215. },
  216. }
  217. err := z.GetRelease(ctx, config.Version)
  218. if err != nil {
  219. return err
  220. }
  221. zStatic := &github.ZIPReleaseGetter{
  222. AssetName: "static",
  223. AssetFolderDest: filepath.Join(porterDir, "static"),
  224. ZipFolderDest: porterDir,
  225. ZipName: "static_latest.zip",
  226. EntityID: "porter-dev",
  227. RepoName: "porter",
  228. IsPlatformDependent: false,
  229. Downloader: &github.ZIPDownloader{
  230. ZipFolderDest: porterDir,
  231. AssetFolderDest: filepath.Join(porterDir, "static"),
  232. ZipName: "static_latest.zip",
  233. },
  234. }
  235. return zStatic.GetRelease(ctx, config.Version)
  236. }