1
0

reload.go 2.2 KB

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