conf.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright 2021-2023 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. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path"
  21. "strings"
  22. "time"
  23. "github.com/lestrrat-go/file-rotatelogs"
  24. "github.com/sirupsen/logrus"
  25. "github.com/lf-edge/ekuiper/pkg/api"
  26. )
  27. const ConfFileName = "kuiper.yaml"
  28. var (
  29. Config *KuiperConf
  30. IsTesting bool
  31. )
  32. type tlsConf struct {
  33. Certfile string `yaml:"certfile"`
  34. Keyfile string `yaml:"keyfile"`
  35. }
  36. type SinkConf struct {
  37. MemoryCacheThreshold int `json:"memoryCacheThreshold" yaml:"memoryCacheThreshold"`
  38. MaxDiskCache int `json:"maxDiskCache" yaml:"maxDiskCache"`
  39. BufferPageSize int `json:"bufferPageSize" yaml:"bufferPageSize"`
  40. EnableCache bool `json:"enableCache" yaml:"enableCache"`
  41. ResendInterval int `json:"resendInterval" yaml:"resendInterval"`
  42. CleanCacheAtStop bool `json:"cleanCacheAtStop" yaml:"cleanCacheAtStop"`
  43. }
  44. // Validate the configuration and reset to the default value for invalid values.
  45. func (sc *SinkConf) Validate() error {
  46. var errs error
  47. if sc.MemoryCacheThreshold < 0 {
  48. sc.MemoryCacheThreshold = 1024
  49. Log.Warnf("memoryCacheThreshold is less than 0, set to 1024")
  50. errs = errors.Join(errs, errors.New("memoryCacheThreshold:memoryCacheThreshold must be positive"))
  51. }
  52. if sc.MaxDiskCache < 0 {
  53. sc.MaxDiskCache = 1024000
  54. Log.Warnf("maxDiskCache is less than 0, set to 1024000")
  55. errs = errors.Join(errs, errors.New("maxDiskCache:maxDiskCache must be positive"))
  56. }
  57. if sc.BufferPageSize <= 0 {
  58. sc.BufferPageSize = 256
  59. Log.Warnf("bufferPageSize is less than or equal to 0, set to 256")
  60. errs = errors.Join(errs, errors.New("bufferPageSize:bufferPageSize must be positive"))
  61. }
  62. if sc.ResendInterval < 0 {
  63. sc.ResendInterval = 0
  64. Log.Warnf("resendInterval is less than 0, set to 0")
  65. errs = errors.Join(errs, errors.New("resendInterval:resendInterval must be positive"))
  66. }
  67. if sc.BufferPageSize > sc.MemoryCacheThreshold {
  68. sc.MemoryCacheThreshold = sc.BufferPageSize
  69. Log.Warnf("memoryCacheThreshold is less than bufferPageSize, set to %d", sc.BufferPageSize)
  70. errs = errors.Join(errs, errors.New("memoryCacheThresholdTooSmall:memoryCacheThreshold must be greater than or equal to bufferPageSize"))
  71. }
  72. if sc.MemoryCacheThreshold%sc.BufferPageSize != 0 {
  73. sc.MemoryCacheThreshold = sc.BufferPageSize * (sc.MemoryCacheThreshold/sc.BufferPageSize + 1)
  74. Log.Warnf("memoryCacheThreshold is not a multiple of bufferPageSize, set to %d", sc.MemoryCacheThreshold)
  75. errs = errors.Join(errs, errors.New("memoryCacheThresholdNotMultiple:memoryCacheThreshold must be a multiple of bufferPageSize"))
  76. }
  77. if sc.BufferPageSize > sc.MaxDiskCache {
  78. sc.MaxDiskCache = sc.BufferPageSize
  79. Log.Warnf("maxDiskCache is less than bufferPageSize, set to %d", sc.BufferPageSize)
  80. errs = errors.Join(errs, errors.New("maxDiskCacheTooSmall:maxDiskCache must be greater than bufferPageSize"))
  81. }
  82. if sc.MaxDiskCache%sc.BufferPageSize != 0 {
  83. sc.MaxDiskCache = sc.BufferPageSize * (sc.MaxDiskCache/sc.BufferPageSize + 1)
  84. Log.Warnf("maxDiskCache is not a multiple of bufferPageSize, set to %d", sc.MaxDiskCache)
  85. errs = errors.Join(errs, errors.New("maxDiskCacheNotMultiple:maxDiskCache must be a multiple of bufferPageSize"))
  86. }
  87. return errs
  88. }
  89. type SourceConf struct {
  90. HttpServerIp string `json:"httpServerIp" yaml:"httpServerIp"`
  91. HttpServerPort int `json:"httpServerPort" yaml:"httpServerPort"`
  92. HttpServerTls *tlsConf `json:"httpServerTls" yaml:"httpServerTls"`
  93. }
  94. func (sc *SourceConf) Validate() error {
  95. var errs error
  96. if sc.HttpServerIp == "" {
  97. sc.HttpServerIp = "0.0.0.0"
  98. }
  99. if sc.HttpServerPort <= 0 || sc.HttpServerPort > 65535 {
  100. Log.Warnf("invalid source.httpServerPort configuration %d, set to 10081", sc.HttpServerPort)
  101. errs = errors.Join(errs, errors.New("invalidHttpServerPort:httpServerPort must between 0 and 65535"))
  102. sc.HttpServerPort = 10081
  103. }
  104. return errs
  105. }
  106. type SQLConf struct {
  107. MaxConnections int `yaml:"maxConnections"`
  108. }
  109. type KuiperConf struct {
  110. Basic struct {
  111. Debug bool `yaml:"debug"`
  112. ConsoleLog bool `yaml:"consoleLog"`
  113. FileLog bool `yaml:"fileLog"`
  114. RotateTime int `yaml:"rotateTime"`
  115. MaxAge int `yaml:"maxAge"`
  116. Ip string `yaml:"ip"`
  117. Port int `yaml:"port"`
  118. RestIp string `yaml:"restIp"`
  119. RestPort int `yaml:"restPort"`
  120. RestTls *tlsConf `yaml:"restTls"`
  121. Prometheus bool `yaml:"prometheus"`
  122. PrometheusPort int `yaml:"prometheusPort"`
  123. PluginHosts string `yaml:"pluginHosts"`
  124. Authentication bool `yaml:"authentication"`
  125. IgnoreCase bool `yaml:"ignoreCase"`
  126. SQLConf *SQLConf `yaml:"sql"`
  127. }
  128. Rule api.RuleOption
  129. Sink *SinkConf
  130. Source *SourceConf
  131. Store struct {
  132. Type string `yaml:"type"`
  133. ExtStateType string `yaml:"extStateType"`
  134. Redis struct {
  135. Host string `yaml:"host"`
  136. Port int `yaml:"port"`
  137. Password string `yaml:"password"`
  138. Timeout int `yaml:"timeout"`
  139. ConnectionSelector string `yaml:"connectionSelector"`
  140. }
  141. Sqlite struct {
  142. Name string `yaml:"name"`
  143. }
  144. }
  145. Portable struct {
  146. PythonBin string `yaml:"pythonBin"`
  147. InitTimeout int `yaml:"initTimeout"`
  148. }
  149. }
  150. func InitConf() {
  151. cpath, err := GetConfLoc()
  152. if err != nil {
  153. panic(err)
  154. }
  155. kc := KuiperConf{
  156. Rule: api.RuleOption{
  157. LateTol: 1000,
  158. Concurrency: 1,
  159. BufferLength: 1024,
  160. CheckpointInterval: 300000, // 5 minutes
  161. SendError: true,
  162. Restart: &api.RestartStrategy{
  163. Attempts: 0,
  164. Delay: 1000,
  165. Multiplier: 2,
  166. MaxDelay: 30000,
  167. JitterFactor: 0.1,
  168. },
  169. },
  170. }
  171. err = LoadConfigFromPath(path.Join(cpath, ConfFileName), &kc)
  172. if err != nil {
  173. Log.Fatal(err)
  174. panic(err)
  175. }
  176. Config = &kc
  177. if 0 == len(Config.Basic.Ip) {
  178. Config.Basic.Ip = "0.0.0.0"
  179. }
  180. if 0 == len(Config.Basic.RestIp) {
  181. Config.Basic.RestIp = "0.0.0.0"
  182. }
  183. if Config.Basic.Debug {
  184. Log.SetLevel(logrus.DebugLevel)
  185. }
  186. if Config.Basic.FileLog {
  187. logDir, err := GetLoc(logDir)
  188. if err != nil {
  189. Log.Fatal(err)
  190. }
  191. file := path.Join(logDir, logFileName)
  192. logWriter, err := rotatelogs.New(
  193. file+".%Y-%m-%d_%H-%M-%S",
  194. rotatelogs.WithLinkName(file),
  195. rotatelogs.WithRotationTime(time.Hour*time.Duration(Config.Basic.RotateTime)),
  196. rotatelogs.WithMaxAge(time.Hour*time.Duration(Config.Basic.MaxAge)),
  197. )
  198. if err != nil {
  199. fmt.Println("Failed to init log file settings..." + err.Error())
  200. Log.Infof("Failed to log to file, using default stderr.")
  201. } else if Config.Basic.ConsoleLog {
  202. mw := io.MultiWriter(os.Stdout, logWriter)
  203. Log.SetOutput(mw)
  204. } else if !Config.Basic.ConsoleLog {
  205. Log.SetOutput(logWriter)
  206. }
  207. gcOutdatedLog(logDir, time.Hour*time.Duration(Config.Basic.MaxAge))
  208. } else if Config.Basic.ConsoleLog {
  209. Log.SetOutput(os.Stdout)
  210. }
  211. if Config.Store.Type == "redis" && Config.Store.Redis.ConnectionSelector != "" {
  212. if err := RedisStorageConSelectorApply(Config.Store.Redis.ConnectionSelector, Config); err != nil {
  213. Log.Fatal(err)
  214. }
  215. }
  216. if Config.Store.ExtStateType == "" {
  217. Config.Store.ExtStateType = "sqlite"
  218. }
  219. if Config.Portable.PythonBin == "" {
  220. Config.Portable.PythonBin = "python"
  221. }
  222. if Config.Portable.InitTimeout <= 0 {
  223. Config.Portable.InitTimeout = 5000
  224. }
  225. if Config.Source == nil {
  226. Config.Source = &SourceConf{}
  227. }
  228. _ = Config.Source.Validate()
  229. if Config.Sink == nil {
  230. Config.Sink = &SinkConf{}
  231. }
  232. _ = Config.Sink.Validate()
  233. _ = ValidateRuleOption(&Config.Rule)
  234. }
  235. func ValidateRuleOption(option *api.RuleOption) error {
  236. var errs error
  237. if option.CheckpointInterval < 0 {
  238. option.CheckpointInterval = 0
  239. Log.Warnf("checkpointInterval is negative, set to 0")
  240. errs = errors.Join(errs, errors.New("invalidCheckpointInterval:checkpointInterval must be greater than 0"))
  241. }
  242. if option.Concurrency < 0 {
  243. option.Concurrency = 1
  244. Log.Warnf("concurrency is negative, set to 1")
  245. errs = errors.Join(errs, errors.New("invalidConcurrency:concurrency must be greater than 0"))
  246. }
  247. if option.BufferLength < 0 {
  248. option.BufferLength = 1024
  249. Log.Warnf("bufferLength is negative, set to 1024")
  250. errs = errors.Join(errs, errors.New("invalidBufferLength:bufferLength must be greater than 0"))
  251. }
  252. if option.LateTol < 0 {
  253. option.LateTol = 1000
  254. Log.Warnf("lateTol is negative, set to 1000")
  255. errs = errors.Join(errs, errors.New("invalidLateTol:lateTol must be greater than 0"))
  256. }
  257. if option.Restart != nil {
  258. if option.Restart.Multiplier <= 0 {
  259. option.Restart.Multiplier = 2
  260. Log.Warnf("restart multiplier is negative, set to 2")
  261. errs = errors.Join(errs, errors.New("invalidRestartMultiplier:restart multiplier must be greater than 0"))
  262. }
  263. if option.Restart.Attempts < 0 {
  264. option.Restart.Attempts = 0
  265. Log.Warnf("restart attempts is negative, set to 0")
  266. errs = errors.Join(errs, errors.New("invalidRestartAttempts:restart attempts must be greater than 0"))
  267. }
  268. if option.Restart.Delay <= 0 {
  269. option.Restart.Delay = 1000
  270. Log.Warnf("restart delay is negative, set to 1000")
  271. errs = errors.Join(errs, errors.New("invalidRestartDelay:restart delay must be greater than 0"))
  272. }
  273. if option.Restart.MaxDelay <= 0 {
  274. option.Restart.MaxDelay = option.Restart.Delay
  275. Log.Warnf("restart maxDelay is negative, set to %d", option.Restart.Delay)
  276. errs = errors.Join(errs, errors.New("invalidRestartMaxDelay:restart maxDelay must be greater than 0"))
  277. }
  278. if option.Restart.JitterFactor <= 0 || option.Restart.JitterFactor >= 1 {
  279. option.Restart.JitterFactor = 0.1
  280. Log.Warnf("restart jitterFactor must between 0 and 1, set to 0.1")
  281. errs = errors.Join(errs, errors.New("invalidRestartJitterFactor:restart jitterFactor must between [0, 1)"))
  282. }
  283. }
  284. return errs
  285. }
  286. func init() {
  287. InitLogger()
  288. InitClock()
  289. }
  290. func gcOutdatedLog(filePath string, maxDuration time.Duration) {
  291. entries, err := os.ReadDir(filePath)
  292. if err != nil {
  293. Log.Errorf("gc outdated logs when started failed, err:%v", err)
  294. }
  295. now := time.Now()
  296. for _, entry := range entries {
  297. if entry.IsDir() {
  298. continue
  299. }
  300. if isLogOutdated(entry.Name(), now, maxDuration) {
  301. err := os.Remove(path.Join(filePath, entry.Name()))
  302. if err != nil {
  303. Log.Errorf("remove outdated log %v failed, err:%v", entry.Name(), err)
  304. }
  305. }
  306. }
  307. }
  308. func isLogOutdated(name string, now time.Time, maxDuration time.Duration) bool {
  309. prefix := fmt.Sprintf("%s.", logFileName)
  310. layout := "2006-01-02_15-04-05"
  311. if strings.HasPrefix(name, prefix) {
  312. logDate := name[len(prefix):]
  313. t, err := time.Parse(layout, logDate)
  314. if err != nil {
  315. Log.Errorf("parse log %v datetime failed, err:%v", name, err)
  316. return false
  317. }
  318. if int64(now.Sub(t))-int64(maxDuration) > 0 {
  319. return true
  320. }
  321. }
  322. return false
  323. }