rule.go 7.0 KB

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