rule.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 processor
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/pkg/store"
  21. "github.com/lf-edge/ekuiper/internal/xsql"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. "github.com/lf-edge/ekuiper/pkg/cast"
  24. "github.com/lf-edge/ekuiper/pkg/errorx"
  25. "github.com/lf-edge/ekuiper/pkg/kv"
  26. )
  27. type RuleProcessor struct {
  28. db kv.KeyValue
  29. ruleStatusDb kv.KeyValue
  30. }
  31. func NewRuleProcessor() *RuleProcessor {
  32. db, err := store.GetKV("rule")
  33. if err != nil {
  34. panic(fmt.Sprintf("Can not initialize store for the rule processor at path 'rule': %v", err))
  35. }
  36. ruleStatusDb, err := store.GetKV("ruleStatus")
  37. if err != nil {
  38. panic(fmt.Sprintf("Can not initialize store for the rule processor at path 'rule': %v", err))
  39. }
  40. processor := &RuleProcessor{
  41. db: db,
  42. ruleStatusDb: ruleStatusDb,
  43. }
  44. return processor
  45. }
  46. func (p *RuleProcessor) ExecCreateWithValidation(name, ruleJson string) (*api.Rule, error) {
  47. rule, err := p.GetRuleByJson(name, ruleJson)
  48. if err != nil {
  49. return nil, err
  50. }
  51. err = p.db.Setnx(rule.Id, ruleJson)
  52. if err != nil {
  53. return nil, err
  54. } else {
  55. log.Infof("Rule %s is created.", rule.Id)
  56. }
  57. return rule, nil
  58. }
  59. func (p *RuleProcessor) ExecCreate(name, ruleJson string) error {
  60. err := p.db.Setnx(name, ruleJson)
  61. if err != nil {
  62. return err
  63. } else {
  64. log.Infof("Rule %s is created.", name)
  65. }
  66. return nil
  67. }
  68. func (p *RuleProcessor) ExecUpdate(name, ruleJson string) (*api.Rule, error) {
  69. rule, err := p.GetRuleByJson(name, ruleJson)
  70. if err != nil {
  71. return nil, err
  72. }
  73. err = p.db.Set(rule.Id, ruleJson)
  74. if err != nil {
  75. return nil, err
  76. } else {
  77. log.Infof("Rule %s is update.", rule.Id)
  78. }
  79. return rule, nil
  80. }
  81. func (p *RuleProcessor) ExecReplaceRuleState(name string, triggered bool) (err error) {
  82. rule, err := p.GetRuleById(name)
  83. if err != nil {
  84. return err
  85. }
  86. rule.Triggered = triggered
  87. ruleJson, err := json.Marshal(rule)
  88. if err != nil {
  89. return fmt.Errorf("Marshal rule %s error : %s.", name, err)
  90. }
  91. err = p.db.Set(name, string(ruleJson))
  92. if err != nil {
  93. return err
  94. } else {
  95. log.Infof("Rule %s is replaced.", name)
  96. }
  97. return err
  98. }
  99. func (p *RuleProcessor) GetRuleJson(id string) (string, error) {
  100. var s1 string
  101. f, _ := p.db.Get(id, &s1)
  102. if !f {
  103. return "", errorx.NewWithCode(errorx.NOT_FOUND, fmt.Sprintf("Rule %s is not found.", id))
  104. }
  105. return s1, nil
  106. }
  107. func (p *RuleProcessor) GetRuleById(id string) (*api.Rule, error) {
  108. var s1 string
  109. f, _ := p.db.Get(id, &s1)
  110. if !f {
  111. return nil, errorx.NewWithCode(errorx.NOT_FOUND, fmt.Sprintf("Rule %s is not found.", id))
  112. }
  113. return p.GetRuleByJsonValidated(s1)
  114. }
  115. func (p *RuleProcessor) getDefaultRule(name, sql string) *api.Rule {
  116. return &api.Rule{
  117. Id: name,
  118. Sql: sql,
  119. Options: &api.RuleOption{
  120. IsEventTime: false,
  121. LateTol: 1000,
  122. Concurrency: 1,
  123. BufferLength: 1024,
  124. SendMetaToSink: false,
  125. SendError: true,
  126. Qos: api.AtMostOnce,
  127. CheckpointInterval: 300000,
  128. Restart: &api.RestartStrategy{
  129. Attempts: 0,
  130. Delay: 1000,
  131. Multiplier: 2,
  132. MaxDelay: 30000,
  133. JitterFactor: 0.1,
  134. },
  135. },
  136. }
  137. }
  138. // GetRuleByJsonValidated called when the json is getting from trusted source like db
  139. func (p *RuleProcessor) GetRuleByJsonValidated(ruleJson string) (*api.Rule, error) {
  140. opt := conf.Config.Rule
  141. // set default rule options
  142. rule := &api.Rule{
  143. Triggered: true,
  144. Options: clone(opt),
  145. }
  146. if err := json.Unmarshal(cast.StringToBytes(ruleJson), &rule); err != nil {
  147. return nil, fmt.Errorf("Parse rule %s error : %s.", ruleJson, err)
  148. }
  149. if rule.Options == nil {
  150. rule.Options = &opt
  151. }
  152. return rule, nil
  153. }
  154. func (p *RuleProcessor) GetRuleByJson(id, ruleJson string) (*api.Rule, error) {
  155. rule, err := p.GetRuleByJsonValidated(ruleJson)
  156. if err != nil {
  157. return rule, err
  158. }
  159. // validation
  160. if rule.Id == "" && id == "" {
  161. return nil, fmt.Errorf("Missing rule id.")
  162. }
  163. if id != "" && rule.Id != "" && id != rule.Id {
  164. return nil, fmt.Errorf("RuleId is not consistent with rule id.")
  165. }
  166. if rule.Id == "" {
  167. rule.Id = id
  168. }
  169. if rule.Sql != "" {
  170. if rule.Graph != nil {
  171. return nil, fmt.Errorf("Rule %s has both sql and graph.", rule.Id)
  172. }
  173. if _, err := xsql.GetStatementFromSql(rule.Sql); err != nil {
  174. return nil, err
  175. }
  176. if rule.Actions == nil || len(rule.Actions) == 0 {
  177. return nil, fmt.Errorf("Missing rule actions.")
  178. }
  179. } else {
  180. if rule.Graph == nil {
  181. return nil, fmt.Errorf("Rule %s has neither sql nor graph.", rule.Id)
  182. }
  183. }
  184. err = conf.ValidateRuleOption(rule.Options)
  185. if err != nil {
  186. return nil, fmt.Errorf("Rule %s has invalid options: %s.", rule.Id, err)
  187. }
  188. return rule, nil
  189. }
  190. func clone(opt api.RuleOption) *api.RuleOption {
  191. return &api.RuleOption{
  192. IsEventTime: opt.IsEventTime,
  193. LateTol: opt.LateTol,
  194. Concurrency: opt.Concurrency,
  195. BufferLength: opt.BufferLength,
  196. SendMetaToSink: opt.SendMetaToSink,
  197. SendError: opt.SendError,
  198. Qos: opt.Qos,
  199. CheckpointInterval: opt.CheckpointInterval,
  200. Restart: &api.RestartStrategy{
  201. Attempts: opt.Restart.Attempts,
  202. Delay: opt.Restart.Delay,
  203. Multiplier: opt.Restart.Multiplier,
  204. MaxDelay: opt.Restart.MaxDelay,
  205. JitterFactor: opt.Restart.JitterFactor,
  206. },
  207. }
  208. }
  209. func (p *RuleProcessor) ExecDesc(name string) (string, error) {
  210. var s1 string
  211. f, _ := p.db.Get(name, &s1)
  212. if !f {
  213. return "", fmt.Errorf("Rule %s is not found.", name)
  214. }
  215. dst := &bytes.Buffer{}
  216. if err := json.Indent(dst, cast.StringToBytes(s1), "", " "); err != nil {
  217. return "", err
  218. }
  219. return fmt.Sprintln(dst.String()), nil
  220. }
  221. func (p *RuleProcessor) GetAllRules() ([]string, error) {
  222. return p.db.Keys()
  223. }
  224. func (p *RuleProcessor) GetAllRulesJson() (map[string]string, error) {
  225. return p.db.All()
  226. }
  227. func (p *RuleProcessor) ExecDrop(name string) (string, error) {
  228. result := fmt.Sprintf("Rule %s is dropped.", name)
  229. var ruleJson string
  230. if ok, _ := p.db.Get(name, &ruleJson); ok {
  231. if err := cleanSinkCache(name); err != nil {
  232. result = fmt.Sprintf("%s. Clean sink cache faile: %s.", result, err)
  233. }
  234. if err := cleanCheckpoint(name); err != nil {
  235. result = fmt.Sprintf("%s. Clean checkpoint cache faile: %s.", result, err)
  236. }
  237. }
  238. err := p.db.Delete(name)
  239. if err != nil {
  240. return "", err
  241. } else {
  242. return result, nil
  243. }
  244. }
  245. func cleanCheckpoint(name string) error {
  246. err := store.DropTS(name)
  247. if err != nil {
  248. return err
  249. }
  250. return nil
  251. }
  252. func cleanSinkCache(name string) error {
  253. err := store.DropCacheKVForRule(name)
  254. if err != nil {
  255. return err
  256. }
  257. return nil
  258. }