server_env.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package scenarios
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "os/exec"
  6. "path/filepath"
  7. "runtime"
  8. "time"
  9. _ "github.com/v2ray/v2ray-core/app/router/rules"
  10. "github.com/v2ray/v2ray-core/common/log"
  11. // The following are necessary as they register handlers in their init functions.
  12. _ "github.com/v2ray/v2ray-core/proxy/blackhole"
  13. _ "github.com/v2ray/v2ray-core/proxy/dokodemo"
  14. _ "github.com/v2ray/v2ray-core/proxy/freedom"
  15. _ "github.com/v2ray/v2ray-core/proxy/http"
  16. _ "github.com/v2ray/v2ray-core/proxy/shadowsocks"
  17. _ "github.com/v2ray/v2ray-core/proxy/socks"
  18. _ "github.com/v2ray/v2ray-core/proxy/vmess/inbound"
  19. _ "github.com/v2ray/v2ray-core/proxy/vmess/outbound"
  20. )
  21. var (
  22. runningServers = make([]*exec.Cmd, 0, 10)
  23. binaryPath string
  24. )
  25. func BuildV2Ray() error {
  26. if len(binaryPath) > 0 {
  27. return nil
  28. }
  29. dir, err := ioutil.TempDir("", "v2ray")
  30. if err != nil {
  31. return err
  32. }
  33. binaryPath = filepath.Join(dir, "v2ray")
  34. if runtime.GOOS == "windows" {
  35. binaryPath += ".exe"
  36. }
  37. cmd := exec.Command("go", "build", "-tags=json", "-o="+binaryPath, filepath.Join("github.com", "v2ray", "v2ray-core", "release", "server"))
  38. return cmd.Run()
  39. }
  40. func TestFile(filename string) string {
  41. return filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "v2ray", "v2ray-core", "testing", "scenarios", "data", filename)
  42. }
  43. func InitializeServerSetOnce(testcase string) error {
  44. if err := InitializeServerServer(testcase); err != nil {
  45. return err
  46. }
  47. if err := InitializeServerClient(testcase); err != nil {
  48. return err
  49. }
  50. return nil
  51. }
  52. func InitializeServerServer(testcase string) error {
  53. return InitializeServer(TestFile(testcase + "_server.json"))
  54. }
  55. func InitializeServerClient(testcase string) error {
  56. return InitializeServer(TestFile(testcase + "_client.json"))
  57. }
  58. func InitializeServer(configFile string) error {
  59. err := BuildV2Ray()
  60. if err != nil {
  61. return err
  62. }
  63. proc := exec.Command(binaryPath, "-config="+configFile)
  64. proc.Stderr = os.Stderr
  65. proc.Stdout = os.Stdout
  66. err = proc.Start()
  67. if err != nil {
  68. return err
  69. }
  70. time.Sleep(time.Second)
  71. runningServers = append(runningServers, proc)
  72. return nil
  73. }
  74. func CloseAllServers() {
  75. log.Info("Closing all servers.")
  76. for _, server := range runningServers {
  77. server.Process.Kill()
  78. }
  79. runningServers = make([]*exec.Cmd, 0, 10)
  80. log.Info("All server closed.")
  81. }