server.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. cliConf.SetHost(fmt.Sprintf("http://localhost:%d", port), currentProfile)
  138. porterDir := filepath.Join(home, ".porter")
  139. cmdPath := filepath.Join(home, ".porter", "portersvr")
  140. sqlLitePath := filepath.Join(home, ".porter", "porter.db")
  141. staticFilePath := filepath.Join(home, ".porter", "static")
  142. if _, err := os.Stat(cmdPath); os.IsNotExist(err) {
  143. err := downloadMatchingRelease(ctx, porterDir)
  144. if err != nil {
  145. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  146. os.Exit(1)
  147. }
  148. }
  149. // otherwise, check the version flag of the binary
  150. cmdVersionPorter := exec.Command(cmdPath, "--version")
  151. writer := &config.VersionWriter{}
  152. cmdVersionPorter.Stdout = writer
  153. err := cmdVersionPorter.Run()
  154. if err != nil || writer.Version != config.Version {
  155. err := downloadMatchingRelease(ctx, porterDir)
  156. if err != nil {
  157. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  158. os.Exit(1)
  159. }
  160. }
  161. cmdPorter := exec.Command(cmdPath)
  162. cmdPorter.Env = os.Environ()
  163. cmdPorter.Env = append(cmdPorter.Env, []string{
  164. "IS_LOCAL=true",
  165. "SQL_LITE=true",
  166. "SQL_LITE_PATH=" + sqlLitePath,
  167. "STATIC_FILE_PATH=" + staticFilePath,
  168. fmt.Sprintf("SERVER_PORT=%d", port),
  169. "REDIS_ENABLED=false",
  170. }...)
  171. if _, found := os.LookupEnv("GITHUB_ENABLED"); !found {
  172. cmdPorter.Env = append(cmdPorter.Env, "GITHUB_ENABLED=false")
  173. }
  174. if _, found := os.LookupEnv("PROVISIONER_ENABLED"); !found {
  175. cmdPorter.Env = append(cmdPorter.Env, "PROVISIONER_ENABLED=false")
  176. }
  177. cmdPorter.Stdout = os.Stdout
  178. cmdPorter.Stderr = os.Stderr
  179. err = cmdPorter.Run()
  180. if err != nil {
  181. color.New(color.FgRed).Println("Failed:", err.Error())
  182. os.Exit(1)
  183. }
  184. return nil
  185. }
  186. func stopDocker(ctx context.Context) error {
  187. agent, err := docker.NewAgentFromEnv(ctx)
  188. if err != nil {
  189. return err
  190. }
  191. err = agent.StopPorterContainersWithProcessID(ctx, "main", false)
  192. if err != nil {
  193. return err
  194. }
  195. green := color.New(color.FgGreen)
  196. green.Println("Successfully stopped the Porter server.")
  197. return nil
  198. }
  199. func downloadMatchingRelease(ctx context.Context, porterDir string) error {
  200. z := &github.ZIPReleaseGetter{
  201. AssetName: "portersvr",
  202. AssetFolderDest: porterDir,
  203. ZipFolderDest: porterDir,
  204. ZipName: "portersvr_latest.zip",
  205. EntityID: "porter-dev",
  206. RepoName: "porter",
  207. IsPlatformDependent: true,
  208. Downloader: &github.ZIPDownloader{
  209. ZipFolderDest: porterDir,
  210. AssetFolderDest: porterDir,
  211. ZipName: "portersvr_latest.zip",
  212. },
  213. }
  214. err := z.GetRelease(ctx, config.Version)
  215. if err != nil {
  216. return err
  217. }
  218. zStatic := &github.ZIPReleaseGetter{
  219. AssetName: "static",
  220. AssetFolderDest: filepath.Join(porterDir, "static"),
  221. ZipFolderDest: porterDir,
  222. ZipName: "static_latest.zip",
  223. EntityID: "porter-dev",
  224. RepoName: "porter",
  225. IsPlatformDependent: false,
  226. Downloader: &github.ZIPDownloader{
  227. ZipFolderDest: porterDir,
  228. AssetFolderDest: filepath.Join(porterDir, "static"),
  229. ZipName: "static_latest.zip",
  230. },
  231. }
  232. return zStatic.GetRelease(ctx, config.Version)
  233. }