root.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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/util/log"
  31. "github.com/fatedier/frp/pkg/util/version"
  32. )
  33. var (
  34. cfgFile string
  35. cfgDir string
  36. showVersion bool
  37. strictConfigMode bool
  38. )
  39. func init() {
  40. rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "./frpc.ini", "config file of frpc")
  41. rootCmd.PersistentFlags().StringVarP(&cfgDir, "config_dir", "", "", "config directory, run one frpc service for each file in config directory")
  42. rootCmd.PersistentFlags().BoolVarP(&showVersion, "version", "v", false, "version of frpc")
  43. rootCmd.PersistentFlags().BoolVarP(&strictConfigMode, "strict_config", "", true, "strict config parsing mode, unknown fields will cause an errors")
  44. }
  45. var rootCmd = &cobra.Command{
  46. Use: "frpc",
  47. Short: "frpc is the client of frp (https://github.com/fatedier/frp)",
  48. RunE: func(cmd *cobra.Command, args []string) error {
  49. if showVersion {
  50. fmt.Println(version.Full())
  51. return nil
  52. }
  53. // If cfgDir is not empty, run multiple frpc service for each config file in cfgDir.
  54. // Note that it's only designed for testing. It's not guaranteed to be stable.
  55. if cfgDir != "" {
  56. _ = runMultipleClients(cfgDir)
  57. return nil
  58. }
  59. // Do not show command usage here.
  60. err := runClient(cfgFile)
  61. if err != nil {
  62. fmt.Println(err)
  63. os.Exit(1)
  64. }
  65. return nil
  66. },
  67. }
  68. func runMultipleClients(cfgDir string) error {
  69. var wg sync.WaitGroup
  70. err := filepath.WalkDir(cfgDir, func(path string, d fs.DirEntry, err error) error {
  71. if err != nil || d.IsDir() {
  72. return nil
  73. }
  74. wg.Add(1)
  75. time.Sleep(time.Millisecond)
  76. go func() {
  77. defer wg.Done()
  78. err := runClient(path)
  79. if err != nil {
  80. fmt.Printf("frpc service error for config file [%s]\n", path)
  81. }
  82. }()
  83. return nil
  84. })
  85. wg.Wait()
  86. return err
  87. }
  88. func Execute() {
  89. rootCmd.SetGlobalNormalizationFunc(config.WordSepNormalizeFunc)
  90. if err := rootCmd.Execute(); err != nil {
  91. os.Exit(1)
  92. }
  93. }
  94. func handleTermSignal(svr *client.Service) {
  95. ch := make(chan os.Signal, 1)
  96. signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
  97. <-ch
  98. svr.GracefulClose(500 * time.Millisecond)
  99. }
  100. func runClient(cfgFilePath string) error {
  101. cfg, proxyCfgs, visitorCfgs, isLegacyFormat, err := config.LoadClientConfig(cfgFilePath, strictConfigMode)
  102. if err != nil {
  103. return err
  104. }
  105. if isLegacyFormat {
  106. fmt.Printf("WARNING: ini format is deprecated and the support will be removed in the future, " +
  107. "please use yaml/json/toml format instead!\n")
  108. }
  109. warning, err := validation.ValidateAllClientConfig(cfg, proxyCfgs, visitorCfgs)
  110. if warning != nil {
  111. fmt.Printf("WARNING: %v\n", warning)
  112. }
  113. if err != nil {
  114. return err
  115. }
  116. return startService(cfg, proxyCfgs, visitorCfgs, cfgFilePath)
  117. }
  118. func startService(
  119. cfg *v1.ClientCommonConfig,
  120. proxyCfgs []v1.ProxyConfigurer,
  121. visitorCfgs []v1.VisitorConfigurer,
  122. cfgFile string,
  123. ) error {
  124. log.InitLogger(cfg.Log.To, cfg.Log.Level, int(cfg.Log.MaxDays), cfg.Log.DisablePrintColor)
  125. if cfgFile != "" {
  126. log.Infof("start frpc service for config file [%s]", cfgFile)
  127. defer log.Infof("frpc service for config file [%s] stopped", cfgFile)
  128. }
  129. svr, err := client.NewService(client.ServiceOptions{
  130. Common: cfg,
  131. ProxyCfgs: proxyCfgs,
  132. VisitorCfgs: visitorCfgs,
  133. ConfigFilePath: cfgFile,
  134. })
  135. if err != nil {
  136. return err
  137. }
  138. shouldGracefulClose := cfg.Transport.Protocol == "kcp" || cfg.Transport.Protocol == "quic"
  139. // Capture the exit signal if we use kcp or quic.
  140. if shouldGracefulClose {
  141. go handleTermSignal(svr)
  142. }
  143. return svr.Run(context.Background())
  144. }