rule.go 6.8 KB

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