conf.go 11 KB

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