ruleset.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 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. "io"
  21. )
  22. type RulesetProcessor struct {
  23. r *RuleProcessor
  24. s *StreamProcessor
  25. }
  26. type ruleset struct {
  27. Streams map[string]string `json:"streams"`
  28. Tables map[string]string `json:"tables"`
  29. Rules map[string]string `json:"rules"`
  30. }
  31. func NewRulesetProcessor(r *RuleProcessor, s *StreamProcessor) *RulesetProcessor {
  32. return &RulesetProcessor{
  33. r: r,
  34. s: s,
  35. }
  36. }
  37. func (rs *RulesetProcessor) Export() (io.Reader, error) {
  38. var all ruleset
  39. allStreams, err := rs.s.GetAll()
  40. if err != nil {
  41. return nil, fmt.Errorf("fail to get all streams: %v", err)
  42. }
  43. all.Streams = allStreams["streams"]
  44. all.Tables = allStreams["tables"]
  45. rules, err := rs.r.GetAllRulesJson()
  46. if err != nil {
  47. return nil, fmt.Errorf("fail to get all rules: %v", err)
  48. }
  49. all.Rules = rules
  50. jsonBytes, err := json.Marshal(all)
  51. if err != nil {
  52. return nil, err
  53. }
  54. return bytes.NewBuffer(jsonBytes), nil
  55. }
  56. func (rs *RulesetProcessor) Import(content []byte, overwrite bool) error {
  57. all := &ruleset{}
  58. err := json.Unmarshal(content, all)
  59. if err != nil {
  60. return fmt.Errorf("invalid import file: %v", err)
  61. }
  62. // restore streams
  63. for k, v := range all.Streams {
  64. _, e := rs.s.ExecStreamSql(v)
  65. if e != nil {
  66. conf.Log.Errorf("Fail to import stream %s(%s) with error: %v", k, v, e)
  67. }
  68. }
  69. // restore tables
  70. for k, v := range all.Tables {
  71. _, e := rs.s.ExecStreamSql(v)
  72. if e != nil {
  73. conf.Log.Errorf("Fail to import table %s(%s) with error: %v", k, v, e)
  74. }
  75. }
  76. // restore rules
  77. for k, v := range all.Rules {
  78. _, e := rs.r.ExecCreate("", v)
  79. if e != nil {
  80. conf.Log.Errorf("Fail to import rule %s(%s) with error: %v", k, v, e)
  81. }
  82. }
  83. return nil
  84. }