1
0

root.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package sub
  15. import (
  16. "context"
  17. "fmt"
  18. "io/fs"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "sync"
  23. "syscall"
  24. "time"
  25. "github.com/spf13/cobra"
  26. "github.com/fatedier/frp/client"
  27. "github.com/fatedier/frp/pkg/config"
  28. v1 "github.com/fatedier/frp/pkg/config/v1"
  29. "github.com/fatedier/frp/pkg/config/v1/validation"
  30. "github.com/fatedier/frp/pkg/featuregate"
  31. "github.com/fatedier/frp/pkg/util/log"
  32. "github.com/fatedier/frp/pkg/util/version"
  33. )
  34. var (
  35. cfgFile string
  36. cfgDir string
  37. showVersion bool
  38. strictConfigMode bool
  39. )
  40. func init() {
  41. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  42. rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
  43. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  44. rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause an errors")
  45. }
  46. var rootCmd = &cobra.Command{
  47. Use: "frpc",
  48. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  49. RunE: func(cmd *cobra.Command, args []string) error {
  50. if showVersion {
  51. fmt.Println(version.Full())
  52. return nil
  53. }
  54. // If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
  55. // Note that it's only designed for testing. It's not guaranteed to be stable.
  56. if cfgDir != "" {
  57. _ = runMultipleClients(cfgDir)
  58. return nil
  59. }
  60. // Do not show command usage here.
  61. err := runClient(cfgFile)
  62. if err != nil {
  63. fmt.Println(err)
  64. os.Exit(1)
  65. }
  66. return nil
  67. },
  68. }
  69. func runMultipleClients(cfgDir string) error {
  70. var wg sync.WaitGroup
  71. err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
  72. if err != nil || d.IsDir() {
  73. return nil
  74. }
  75. wg.Add(1)
  76. time.Sleep(time.Millisecond)
  77. go func() {
  78. defer wg.Done()
  79. err := runClient(path)
  80. if err != nil {
  81. fmt.Printf("frpc service error for config file [%s]\n", path)
  82. }
  83. }()
  84. return nil
  85. })
  86. wg.Wait()
  87. return err
  88. }
  89. func Execute() {
  90. rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
  91. if err := rootCmd.Execute(); err != nil {
  92. os.Exit(1)
  93. }
  94. }
  95. func handleTermSignal(svr *client.Service) {
  96. ch := make(chan os.Signal, 1)
  97. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  98. <-ch
  99. svr.GracefulClose(500 * time.Millisecond)
  100. }
  101. func runClient(cfgFilePath string) error {
  102. cfg, proxyCfgs, visitorCfgs, isLegacyFormat, err := config.LoadClientConfig(cfgFilePath, strictConfigMode)
  103. if err != nil {
  104. return err
  105. }
  106. if isLegacyFormat {
  107. fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
  108. "please use yaml/json/toml format instead!\n")
  109. }
  110. if len(cfg.FeatureGates) > 0 {
  111. if err := featuregate.SetFromMap(cfg.FeatureGates); err != nil {
  112. return err
  113. }
  114. }
  115. warning, err := validation.ValidateAllClientConfig(cfg, proxyCfgs, visitorCfgs)
  116. if warning != nil {
  117. fmt.Printf("WARNING: %v\n", warning)
  118. }
  119. if err != nil {
  120. return err
  121. }
  122. return startService(cfg, proxyCfgs, visitorCfgs, cfgFilePath)
  123. }
  124. func startService(
  125. cfg *v1.ClientCommonConfig,
  126. proxyCfgs []v1.ProxyConfigurer,
  127. visitorCfgs []v1.VisitorConfigurer,
  128. cfgFile string,
  129. ) error {
  130. log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
  131. if cfgFile != "" {
  132. log.Infof("start frpc service for config file [%s]", cfgFile)
  133. defer log.Infof("frpc service for config file [%s] stopped", cfgFile)
  134. }
  135. svr, err := client.NewService(client.ServiceOptions{
  136. Common: cfg,
  137. ProxyCfgs: proxyCfgs,
  138. VisitorCfgs: visitorCfgs,
  139. ConfigFilePath: cfgFile,
  140. })
  141. if err != nil {
  142. return err
  143. }
  144. shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
  145. // Capture the exit signal if we use kcp or quic.
  146. if shouldGracefulClose {
  147. go handleTermSignal(svr)
  148. }
  149. return svr.Run(context.Background())
  150. }