reload.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. "encoding/base64"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "strings"
  22. "github.com/fatedier/frp/pkg/config"
  23. "github.com/spf13/cobra"
  24. )
  25. func init() {
  26. rootCmd.AddCommand(reloadCmd)
  27. }
  28. var reloadCmd = &cobra.Command{
  29. Use: "reload",
  30. Short: "Hot-Reload frpc configuration",
  31. RunE: func(cmd *cobra.Command, args []string) error {
  32. iniContent, err := config.GetRenderedConfFromFile(cfgFile)
  33. if err != nil {
  34. fmt.Println(err)
  35. os.Exit(1)
  36. }
  37. clientCfg, err := parseClientCommonCfg(CfgFileTypeIni, iniContent)
  38. if err != nil {
  39. fmt.Println(err)
  40. os.Exit(1)
  41. }
  42. err = reload(clientCfg)
  43. if err != nil {
  44. fmt.Printf("frpc reload error: %v\n", err)
  45. os.Exit(1)
  46. }
  47. fmt.Printf("reload success\n")
  48. return nil
  49. },
  50. }
  51. func reload(clientCfg config.ClientCommonConf) error {
  52. if clientCfg.AdminPort == 0 {
  53. return fmt.Errorf("admin_port shoud be set if you want to use reload feature")
  54. }
  55. req, err := http.NewRequest("GET", "http://"+
  56. clientCfg.AdminAddr+":"+fmt.Sprintf("%d", clientCfg.AdminPort)+"/api/reload", nil)
  57. if err != nil {
  58. return err
  59. }
  60. authStr := "Basic " + base64.StdEncoding.EncodeToString([]byte(clientCfg.AdminUser+":"+
  61. clientCfg.AdminPwd))
  62. req.Header.Add("Authorization", authStr)
  63. resp, err := http.DefaultClient.Do(req)
  64. if err != nil {
  65. return err
  66. }
  67. defer resp.Body.Close()
  68. if resp.StatusCode == 200 {
  69. return nil
  70. }
  71. body, err := ioutil.ReadAll(resp.Body)
  72. if err != nil {
  73. return err
  74. }
  75. return fmt.Errorf("code [%d], %s", resp.StatusCode, strings.TrimSpace(string(body)))
  76. }