server.go 6.6 KB

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