server.go 6.3 KB

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