server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 getDriver() == "docker" {
  31. 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. 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 getDriver() == "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. startCmd.PersistentFlags().StringVar(
  78. &opts.db,
  79. "db",
  80. "sqlite",
  81. "the db to use, one of sqlite or postgres",
  82. )
  83. startCmd.PersistentFlags().StringVar(
  84. &opts.driver,
  85. "driver",
  86. "local",
  87. "the driver to use, one of \"local\" or \"docker\"",
  88. )
  89. startCmd.PersistentFlags().StringVar(
  90. &opts.imageTag,
  91. "image-tag",
  92. "latest",
  93. "the Porter image tag to use (if using docker driver)",
  94. )
  95. opts.port = startCmd.PersistentFlags().IntP(
  96. "port",
  97. "p",
  98. 8080,
  99. "the host port to run the server on",
  100. )
  101. }
  102. func startDocker(
  103. imageTag string,
  104. db string,
  105. port int,
  106. ) error {
  107. env := []string{
  108. "NODE_ENV=production",
  109. "FULLSTORY_ORG_ID=VXNSS",
  110. }
  111. var porterDB docker.PorterDB
  112. switch db {
  113. case "postgres":
  114. porterDB = docker.Postgres
  115. case "sqlite":
  116. porterDB = docker.SQLite
  117. }
  118. startOpts := &docker.PorterStartOpts{
  119. ProcessID: "main",
  120. ServerImageTag: imageTag,
  121. ServerPort: port,
  122. DB: porterDB,
  123. Env: env,
  124. }
  125. _, _, err := docker.StartPorter(startOpts)
  126. if err != nil {
  127. return err
  128. }
  129. green := color.New(color.FgGreen)
  130. green.Printf("Server ready: listening on localhost:%d\n", port)
  131. return setHost(fmt.Sprintf("http://localhost:%d", port))
  132. }
  133. func startLocal(
  134. db string,
  135. port int,
  136. ) error {
  137. if db == "postgres" {
  138. return fmt.Errorf("postgres not available for local driver, run \"porter server start --db postgres --driver docker\"")
  139. }
  140. setHost(fmt.Sprintf("http://localhost:%d", port))
  141. porterDir := filepath.Join(home, ".porter")
  142. cmdPath := filepath.Join(home, ".porter", "portersvr")
  143. sqlLitePath := filepath.Join(home, ".porter", "porter.db")
  144. staticFilePath := filepath.Join(home, ".porter", "static")
  145. if _, err := os.Stat(cmdPath); os.IsNotExist(err) {
  146. err := downloadMatchingRelease(porterDir)
  147. if err != nil {
  148. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  149. os.Exit(1)
  150. }
  151. }
  152. // otherwise, check the version flag of the binary
  153. cmdVersionPorter := exec.Command(cmdPath, "--version")
  154. writer := &versionWriter{}
  155. cmdVersionPorter.Stdout = writer
  156. err := cmdVersionPorter.Run()
  157. if err != nil || writer.Version != Version {
  158. err := downloadMatchingRelease(porterDir)
  159. if err != nil {
  160. color.New(color.FgRed).Println("Failed to download server binary:", err.Error())
  161. os.Exit(1)
  162. }
  163. }
  164. cmdPorter := exec.Command(cmdPath)
  165. cmdPorter.Env = os.Environ()
  166. cmdPorter.Env = append(cmdPorter.Env, []string{
  167. "IS_LOCAL=true",
  168. "SQL_LITE=true",
  169. "SQL_LITE_PATH=" + sqlLitePath,
  170. "STATIC_FILE_PATH=" + staticFilePath,
  171. "REDIS_ENABLED=false",
  172. }...)
  173. cmdPorter.Stdout = os.Stdout
  174. cmdPorter.Stderr = os.Stderr
  175. err = cmdPorter.Run()
  176. if err != nil {
  177. color.New(color.FgRed).Println("Failed:", err.Error())
  178. os.Exit(1)
  179. }
  180. return nil
  181. }
  182. func stopDocker() error {
  183. agent, err := docker.NewAgentFromEnv()
  184. if err != nil {
  185. return err
  186. }
  187. err = agent.StopPorterContainersWithProcessID("main", false)
  188. if err != nil {
  189. return err
  190. }
  191. green := color.New(color.FgGreen)
  192. green.Println("Successfully stopped the Porter server.")
  193. return nil
  194. }
  195. func downloadMatchingRelease(porterDir string) error {
  196. z := &github.ZIPReleaseGetter{
  197. AssetName: "portersvr",
  198. AssetFolderDest: porterDir,
  199. ZipFolderDest: porterDir,
  200. ZipName: "portersvr_latest.zip",
  201. EntityID: "porter-dev",
  202. RepoName: "porter",
  203. IsPlatformDependent: true,
  204. }
  205. err := z.GetRelease(Version)
  206. if err != nil {
  207. return err
  208. }
  209. zStatic := &github.ZIPReleaseGetter{
  210. AssetName: "static",
  211. AssetFolderDest: filepath.Join(porterDir, "static"),
  212. ZipFolderDest: porterDir,
  213. ZipName: "static_latest.zip",
  214. EntityID: "porter-dev",
  215. RepoName: "porter",
  216. IsPlatformDependent: false,
  217. }
  218. return zStatic.GetLatestRelease()
  219. }
  220. type versionWriter struct {
  221. Version string
  222. }
  223. func (v *versionWriter) Write(p []byte) (n int, err error) {
  224. v.Version = strings.TrimSpace(string(p))
  225. return len(p), nil
  226. }