server_env.go 2.2 KB

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