conf.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  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 conf
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "io"
  20. "net/http"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "runtime"
  25. "time"
  26. "github.com/sirupsen/logrus"
  27. "gopkg.in/yaml.v3"
  28. )
  29. type (
  30. config struct {
  31. Port int `yaml:"port"`
  32. Timeout int `yaml:"timeout"`
  33. IntervalTime int `yaml:"intervalTime"`
  34. Ip string `yaml:"ip"`
  35. ConsoleLog bool `yaml:"consoleLog"`
  36. FileLog bool `yaml:"fileLog"`
  37. LogPath string `yaml:"logPath"`
  38. CommandDir string `yaml:"commandDir"`
  39. }
  40. )
  41. var gConf config
  42. func GetConf() *config {
  43. return &gConf
  44. }
  45. func (c *config) GetIntervalTime() int {
  46. return c.IntervalTime
  47. }
  48. func (c *config) GetIp() string {
  49. return c.Ip
  50. }
  51. func (c *config) GetPort() int {
  52. return c.Port
  53. }
  54. func (c *config) GetLogPath() string {
  55. return c.LogPath
  56. }
  57. func (c *config) GetCommandDir() string {
  58. return c.CommandDir
  59. }
  60. func processPath(path string) (string, error) {
  61. if abs, err := filepath.Abs(path); err != nil {
  62. return "", nil
  63. } else {
  64. if _, err := os.Stat(abs); os.IsNotExist(err) {
  65. return "", err
  66. }
  67. return abs, nil
  68. }
  69. }
  70. func (c *config) initConfig() bool {
  71. confPath, err := processPath(os.Args[1])
  72. if nil != err {
  73. fmt.Println("conf path err : ", err)
  74. return false
  75. }
  76. sliByte, err := os.ReadFile(confPath)
  77. if nil != err {
  78. fmt.Println("load conf err : ", err)
  79. return false
  80. }
  81. err = yaml.Unmarshal(sliByte, c)
  82. if nil != err {
  83. fmt.Println("unmashal conf err : ", err)
  84. return false
  85. }
  86. if c.CommandDir, err = filepath.Abs(c.CommandDir); err != nil {
  87. fmt.Println("command dir err : ", err)
  88. return false
  89. }
  90. if _, err = os.Stat(c.CommandDir); os.IsNotExist(err) {
  91. fmt.Println("not found dir : ", c.CommandDir)
  92. return false
  93. }
  94. if c.LogPath, err = filepath.Abs(c.LogPath); nil != err {
  95. fmt.Println("log dir err : ", err)
  96. return false
  97. }
  98. if _, err = os.Stat(c.LogPath); os.IsNotExist(err) {
  99. if err = os.MkdirAll(path.Dir(c.LogPath), 0o755); nil != err {
  100. fmt.Println("mak logdir err : ", err)
  101. return false
  102. }
  103. }
  104. return true
  105. }
  106. var (
  107. Log *logrus.Logger
  108. gClient http.Client
  109. )
  110. func (c *config) initTimeout() {
  111. gClient.Timeout = time.Duration(c.Timeout) * time.Millisecond
  112. }
  113. func (c *config) initLog() bool {
  114. Log = logrus.New()
  115. Log.SetReportCaller(true)
  116. Log.SetFormatter(&logrus.TextFormatter{
  117. CallerPrettyfier: func(f *runtime.Frame) (string, string) {
  118. filename := path.Base(f.File)
  119. return "", fmt.Sprintf("%s:%d", filename, f.Line)
  120. },
  121. DisableColors: true,
  122. FullTimestamp: true,
  123. })
  124. if c.FileLog {
  125. logFile, err := os.OpenFile(c.LogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
  126. if err != nil {
  127. fmt.Println("Failed to init log file settings..." + err.Error())
  128. Log.Infof("Failed to log to file, using default stderr.")
  129. return false
  130. } else if c.ConsoleLog {
  131. mw := io.MultiWriter(os.Stdout, logFile)
  132. Log.SetOutput(mw)
  133. } else if !c.ConsoleLog {
  134. Log.SetOutput(logFile)
  135. }
  136. } else if c.ConsoleLog {
  137. Log.SetOutput(os.Stdout)
  138. }
  139. return true
  140. }
  141. func (c *config) Init() bool {
  142. if !c.initConfig() {
  143. return false
  144. }
  145. if !c.initLog() {
  146. return false
  147. }
  148. c.initTimeout()
  149. return true
  150. }
  151. func fetchContents(request *http.Request) (data []byte, err error) {
  152. respon, err := gClient.Do(request)
  153. if nil != err {
  154. return nil, err
  155. }
  156. defer respon.Body.Close()
  157. data, err = io.ReadAll(respon.Body)
  158. if nil != err {
  159. return nil, err
  160. }
  161. /*
  162. if respon.StatusCode < 200 || respon.StatusCode > 299 {
  163. return data, fmt.Errorf("http return code: %d and error message %s.", respon.StatusCode, string(data))
  164. }
  165. */
  166. return data, err
  167. }
  168. func Get(inUrl string) (data []byte, err error) {
  169. request, err := http.NewRequest(http.MethodGet, inUrl, nil)
  170. if nil != err {
  171. return nil, err
  172. }
  173. return fetchContents(request)
  174. }
  175. func Post(inHead, inBody string) (data []byte, err error) {
  176. request, err := http.NewRequest(http.MethodPost, inHead, bytes.NewBuffer([]byte(inBody)))
  177. if nil != err {
  178. return nil, err
  179. }
  180. request.Header.Set("Content-Type", "application/json")
  181. return fetchContents(request)
  182. }
  183. func Put(inHead, inBody string) (data []byte, err error) {
  184. request, err := http.NewRequest(http.MethodPut, inHead, bytes.NewBuffer([]byte(inBody)))
  185. if nil != err {
  186. return nil, err
  187. }
  188. request.Header.Set("Content-Type", "application/json")
  189. return fetchContents(request)
  190. }
  191. func Delete(inUrl string) (data []byte, err error) {
  192. request, err := http.NewRequest(http.MethodDelete, inUrl, nil)
  193. if nil != err {
  194. return nil, err
  195. }
  196. return fetchContents(request)
  197. }
  198. func LoadFileUnmarshal(path string, ret interface{}) error {
  199. sliByte, err := os.ReadFile(path)
  200. if nil != err {
  201. return err
  202. }
  203. err = json.Unmarshal(sliByte, ret)
  204. if nil != err {
  205. return err
  206. }
  207. return nil
  208. }
  209. func SaveFileMarshal(path string, content interface{}) error {
  210. data, err := json.Marshal(content)
  211. if nil != err {
  212. return err
  213. }
  214. return os.WriteFile(path, data, 0o666)
  215. }