server.go 7.2 KB

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