reload.go 2.1 KB

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