conf.go 12 KB

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