github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/main/commands/run.go (about)

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