2
0

server.go 6.6 KB

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