2
0

server.go 6.2 KB

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