rule.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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.GetRuleByJson(id, 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. func (p *RuleProcessor) GetRuleByJson(id, ruleJson string) (*api.Rule, error) {
  132. opt := conf.Config.Rule
  133. //set default rule options
  134. rule := &api.Rule{
  135. Triggered: true,
  136. Options: clone(opt),
  137. }
  138. if err := json.Unmarshal([]byte(ruleJson), &rule); err != nil {
  139. return nil, fmt.Errorf("Parse rule %s error : %s.", ruleJson, err)
  140. }
  141. //validation
  142. if rule.Id == "" && id == "" {
  143. return nil, fmt.Errorf("Missing rule id.")
  144. }
  145. if id != "" && rule.Id != "" && id != rule.Id {
  146. return nil, fmt.Errorf("RuleId is not consistent with rule id.")
  147. }
  148. if rule.Id == "" {
  149. rule.Id = id
  150. }
  151. if rule.Sql != "" {
  152. if rule.Graph != nil {
  153. return nil, fmt.Errorf("Rule %s has both sql and graph.", rule.Id)
  154. }
  155. if _, err := xsql.GetStatementFromSql(rule.Sql); err != nil {
  156. return nil, err
  157. }
  158. if rule.Actions == nil || len(rule.Actions) == 0 {
  159. return nil, fmt.Errorf("Missing rule actions.")
  160. }
  161. } else {
  162. if rule.Graph == nil {
  163. return nil, fmt.Errorf("Rule %s has neither sql nor graph.", rule.Id)
  164. }
  165. }
  166. if rule.Options == nil {
  167. rule.Options = &opt
  168. }
  169. err := conf.ValidateRuleOption(rule.Options)
  170. if err != nil {
  171. return nil, fmt.Errorf("Rule %s has invalid options: %s.", rule.Id, err)
  172. }
  173. return rule, nil
  174. }
  175. func clone(opt api.RuleOption) *api.RuleOption {
  176. return &api.RuleOption{
  177. IsEventTime: opt.IsEventTime,
  178. LateTol: opt.LateTol,
  179. Concurrency: opt.Concurrency,
  180. BufferLength: opt.BufferLength,
  181. SendMetaToSink: opt.SendMetaToSink,
  182. SendError: opt.SendError,
  183. Qos: opt.Qos,
  184. CheckpointInterval: opt.CheckpointInterval,
  185. Restart: &api.RestartStrategy{
  186. Attempts: opt.Restart.Attempts,
  187. Delay: opt.Restart.Delay,
  188. Multiplier: opt.Restart.Multiplier,
  189. MaxDelay: opt.Restart.MaxDelay,
  190. JitterFactor: opt.Restart.JitterFactor,
  191. },
  192. }
  193. }
  194. func (p *RuleProcessor) ExecDesc(name string) (string, error) {
  195. var s1 string
  196. f, _ := p.db.Get(name, &s1)
  197. if !f {
  198. return "", fmt.Errorf("Rule %s is not found.", name)
  199. }
  200. dst := &bytes.Buffer{}
  201. if err := json.Indent(dst, []byte(s1), "", " "); err != nil {
  202. return "", err
  203. }
  204. return fmt.Sprintln(dst.String()), nil
  205. }
  206. func (p *RuleProcessor) GetAllRules() ([]string, error) {
  207. return p.db.Keys()
  208. }
  209. func (p *RuleProcessor) GetAllRulesJson() (map[string]string, error) {
  210. return p.db.All()
  211. }
  212. func (p *RuleProcessor) ExecDrop(name string) (string, error) {
  213. result := fmt.Sprintf("Rule %s is dropped.", name)
  214. var ruleJson string
  215. if ok, _ := p.db.Get(name, &ruleJson); ok {
  216. if err := cleanSinkCache(name); err != nil {
  217. result = fmt.Sprintf("%s. Clean sink cache faile: %s.", result, err)
  218. }
  219. if err := cleanCheckpoint(name); err != nil {
  220. result = fmt.Sprintf("%s. Clean checkpoint cache faile: %s.", result, err)
  221. }
  222. }
  223. err := p.db.Delete(name)
  224. if err != nil {
  225. return "", err
  226. } else {
  227. return result, nil
  228. }
  229. }
  230. func cleanCheckpoint(name string) error {
  231. err := store.DropTS(name)
  232. if err != nil {
  233. return err
  234. }
  235. return nil
  236. }
  237. func cleanSinkCache(name string) error {
  238. err := store.DropCacheKVForRule(name)
  239. if err != nil {
  240. return err
  241. }
  242. return nil
  243. }