server_env.go 2.2 KB

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