server.go 5.7 KB

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