rule.go 6.3 KB

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