conf.go 12 KB

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