rules.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package worker
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "github.com/qntfy/kazaam"
  7. )
  8. var ErrRuleNotDefined = errors.New("Rule not defined")
  9. type RuleList struct {
  10. rules map[string]kazaam.Kazaam
  11. rulesSync sync.Mutex
  12. }
  13. var Rules = RuleList{
  14. rules: make(map[string]kazaam.Kazaam),
  15. }
  16. var kazaamConfig kazaam.Config
  17. func init() {
  18. kazaamConfig = kazaam.NewDefaultConfig()
  19. }
  20. //GetRuleName building the rule namespace name
  21. func GetRuleNsName(backendName string, rulename string) string {
  22. return fmt.Sprintf("%s.%s", backendName, rulename)
  23. }
  24. //GetRulelist getting a copy of the list of rules
  25. func (r *RuleList) GetRulelist() []string {
  26. list := make([]string, 0)
  27. r.rulesSync.Lock()
  28. for k, _ := range r.rules {
  29. list = append(list, k)
  30. }
  31. r.rulesSync.Unlock()
  32. return list
  33. }
  34. func (r *RuleList) Register(backendName, rulename string, config string) error {
  35. name := GetRuleNsName(backendName, rulename)
  36. k, err := kazaam.New(config, kazaamConfig)
  37. if err != nil {
  38. log.Alertf("Unable to transform message %v", err)
  39. return err
  40. }
  41. r.rulesSync.Lock()
  42. r.rules[name] = *k
  43. r.rulesSync.Unlock()
  44. return nil
  45. }
  46. func (r *RuleList) Deregister(backendName, rulename string) error {
  47. name := GetRuleNsName(backendName, rulename)
  48. r.rulesSync.Lock()
  49. delete(r.rules, name)
  50. r.rulesSync.Unlock()
  51. return nil
  52. }
  53. func (r *RuleList) TransformJSON(backendName, rulename string, json []byte) ([]byte, error) {
  54. name := GetRuleNsName(backendName, rulename)
  55. r.rulesSync.Lock()
  56. k, ok := r.rules[name]
  57. r.rulesSync.Unlock()
  58. if !ok {
  59. return []byte{}, ErrRuleNotDefined
  60. }
  61. out, transformError := k.TransformInPlace(json)
  62. if transformError != nil {
  63. log.Alertf("Unable to transform message %v", transformError)
  64. return []byte{}, transformError
  65. }
  66. return out, nil
  67. }