conf.go 5.1 KB

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