server.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. if _, found := os.LookupEnv("GITHUB_ENABLED"); !found {
  174. cmdPorter.Env = append(cmdPorter.Env, "GITHUB_ENABLED=false")
  175. }
  176. if _, found := os.LookupEnv("PROVISIONER_ENABLED"); !found {
  177. cmdPorter.Env = append(cmdPorter.Env, "PROVISIONER_ENABLED=false")
  178. }
  179. cmdPorter.Stdout = os.Stdout
  180. cmdPorter.Stderr = os.Stderr
  181. err = cmdPorter.Run()
  182. if err != nil {
  183. color.New(color.FgRed).Println("Failed:", err.Error())
  184. os.Exit(1)
  185. }
  186. return nil
  187. }
  188. func stopDocker() error {
  189. agent, err := docker.NewAgentFromEnv()
  190. if err != nil {
  191. return err
  192. }
  193. err = agent.StopPorterContainersWithProcessID("main", false)
  194. if err != nil {
  195. return err
  196. }
  197. green := color.New(color.FgGreen)
  198. green.Println("Successfully stopped the Porter server.")
  199. return nil
  200. }
  201. func downloadMatchingRelease(porterDir string) error {
  202. z := &github.ZIPReleaseGetter{
  203. AssetName: "portersvr",
  204. AssetFolderDest: porterDir,
  205. ZipFolderDest: porterDir,
  206. ZipName: "portersvr_latest.zip",
  207. EntityID: "porter-dev",
  208. RepoName: "porter",
  209. IsPlatformDependent: true,
  210. }
  211. err := z.GetRelease(Version)
  212. if err != nil {
  213. return err
  214. }
  215. zStatic := &github.ZIPReleaseGetter{
  216. AssetName: "static",
  217. AssetFolderDest: filepath.Join(porterDir, "static"),
  218. ZipFolderDest: porterDir,
  219. ZipName: "static_latest.zip",
  220. EntityID: "porter-dev",
  221. RepoName: "porter",
  222. IsPlatformDependent: false,
  223. }
  224. return zStatic.GetRelease(Version)
  225. }
  226. type versionWriter struct {
  227. Version string
  228. }
  229. func (v *versionWriter) Write(p []byte) (n int, err error) {
  230. v.Version = strings.TrimSpace(string(p))
  231. return len(p), nil
  232. }