run.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package commands
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "syscall"
  12. "github.com/v2fly/v2ray-core/v4"
  13. "github.com/v2fly/v2ray-core/v4/common/cmdarg"
  14. "github.com/v2fly/v2ray-core/v4/common/platform"
  15. "github.com/v2fly/v2ray-core/v4/main/commands/base"
  16. )
  17. // CmdRun runs V2Ray with config
  18. var CmdRun = &base.Command{
  19. CustomFlags: true,
  20. UsageLine: "{{.Exec}} run [-c config.json] [-d dir]",
  21. Short: "run V2Ray with config",
  22. Long: `
  23. Run V2Ray with config.
  24. {{.Exec}} will also use the config directory specified by environment
  25. variable "v2ray.location.confdir". If no config found, it tries
  26. to load config from one of below:
  27. 1. The default "config.json" in the current directory
  28. 2. The config file from ENV "v2ray.location.config"
  29. 3. The stdin if all failed above
  30. Arguments:
  31. -c, -config <file>
  32. Config file for V2Ray. Multiple assign is accepted.
  33. -d, -confdir <dir>
  34. A directory with config files. Multiple assign is accepted.
  35. -r
  36. Load confdir recursively.
  37. -format <format>
  38. Format of config input. (default "auto")
  39. Examples:
  40. {{.Exec}} {{.LongName}} -c config.json
  41. {{.Exec}} {{.LongName}} -d path/to/dir
  42. Use "{{.Exec}} help format-loader" for more information about format.
  43. `,
  44. Run: executeRun,
  45. }
  46. var (
  47. configFiles cmdarg.Arg
  48. configDirs cmdarg.Arg
  49. configFormat *string
  50. configDirRecursively *bool
  51. )
  52. func setConfigFlags(cmd *base.Command) {
  53. configFormat = cmd.Flag.String("format", core.FormatAuto, "")
  54. configDirRecursively = cmd.Flag.Bool("r", false, "")
  55. cmd.Flag.Var(&configFiles, "config", "")
  56. cmd.Flag.Var(&configFiles, "c", "")
  57. cmd.Flag.Var(&configDirs, "confdir", "")
  58. cmd.Flag.Var(&configDirs, "d", "")
  59. }
  60. func executeRun(cmd *base.Command, args []string) {
  61. setConfigFlags(cmd)
  62. cmd.Flag.Parse(args)
  63. printVersion()
  64. configFiles = getConfigFilePath()
  65. server, err := startV2Ray()
  66. if err != nil {
  67. base.Fatalf("Failed to start: %s", err)
  68. }
  69. if err := server.Start(); err != nil {
  70. base.Fatalf("Failed to start: %s", err)
  71. }
  72. defer server.Close()
  73. // Explicitly triggering GC to remove garbage from config loading.
  74. runtime.GC()
  75. {
  76. osSignals := make(chan os.Signal, 1)
  77. signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
  78. <-osSignals
  79. }
  80. }
  81. func fileExists(file string) bool {
  82. info, err := os.Stat(file)
  83. return err == nil && !info.IsDir()
  84. }
  85. func dirExists(file string) bool {
  86. if file == "" {
  87. return false
  88. }
  89. info, err := os.Stat(file)
  90. return err == nil && info.IsDir()
  91. }
  92. func readConfDir(dirPath string, extension []string) cmdarg.Arg {
  93. confs, err := ioutil.ReadDir(dirPath)
  94. if err != nil {
  95. base.Fatalf("failed to read dir %s: %s", dirPath, err)
  96. }
  97. files := make(cmdarg.Arg, 0)
  98. for _, f := range confs {
  99. ext := filepath.Ext(f.Name())
  100. for _, e := range extension {
  101. if strings.EqualFold(e, ext) {
  102. files.Set(filepath.Join(dirPath, f.Name()))
  103. break
  104. }
  105. }
  106. }
  107. return files
  108. }
  109. // getFolderFiles get files in the folder and it's children
  110. func readConfDirRecursively(dirPath string, extension []string) cmdarg.Arg {
  111. files := make(cmdarg.Arg, 0)
  112. err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
  113. ext := filepath.Ext(path)
  114. for _, e := range extension {
  115. if strings.EqualFold(e, ext) {
  116. files.Set(path)
  117. break
  118. }
  119. }
  120. return nil
  121. })
  122. if err != nil {
  123. base.Fatalf("failed to read dir %s: %s", dirPath, err)
  124. }
  125. return files
  126. }
  127. func getConfigFilePath() cmdarg.Arg {
  128. extension, err := core.GetLoaderExtensions(*configFormat)
  129. if err != nil {
  130. base.Fatalf(err.Error())
  131. }
  132. dirReader := readConfDir
  133. if *configDirRecursively {
  134. dirReader = readConfDirRecursively
  135. }
  136. if len(configDirs) > 0 {
  137. for _, d := range configDirs {
  138. log.Println("Using confdir from arg:", d)
  139. configFiles = append(configFiles, dirReader(d, extension)...)
  140. }
  141. } else if envConfDir := platform.GetConfDirPath(); dirExists(envConfDir) {
  142. log.Println("Using confdir from env:", envConfDir)
  143. configFiles = append(configFiles, dirReader(envConfDir, extension)...)
  144. }
  145. if len(configFiles) > 0 {
  146. return configFiles
  147. }
  148. if len(configFiles) == 0 && len(configDirs) > 0 {
  149. base.Fatalf("no config file found with extension: %s", extension)
  150. }
  151. if workingDir, err := os.Getwd(); err == nil {
  152. configFile := filepath.Join(workingDir, "config.json")
  153. if fileExists(configFile) {
  154. log.Println("Using default config: ", configFile)
  155. return cmdarg.Arg{configFile}
  156. }
  157. }
  158. if configFile := platform.GetConfigurationPath(); fileExists(configFile) {
  159. log.Println("Using config from env: ", configFile)
  160. return cmdarg.Arg{configFile}
  161. }
  162. return nil
  163. }
  164. func startV2Ray() (core.Server, error) {
  165. config, err := core.LoadConfig(*configFormat, configFiles)
  166. if err != nil {
  167. if len(configFiles) == 0 {
  168. err = newError("failed to load config").Base(err)
  169. } else {
  170. err = newError(fmt.Sprintf("failed to load config: %s", configFiles)).Base(err)
  171. }
  172. return nil, err
  173. }
  174. server, err := core.New(config)
  175. if err != nil {
  176. return nil, newError("failed to create server").Base(err)
  177. }
  178. return server, nil
  179. }