sink.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2021-2023 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. //go:build redisdb || !core
  15. package redis
  16. import (
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/pkg/ast"
  21. "time"
  22. "github.com/go-redis/redis/v7"
  23. "github.com/lf-edge/ekuiper/pkg/api"
  24. "github.com/lf-edge/ekuiper/pkg/cast"
  25. )
  26. type config struct {
  27. // host:port address.
  28. Addr string `json:"addr,omitempty"`
  29. Username string `json:"username,omitempty"`
  30. // Optional password. Must match the password specified in the
  31. Password string `json:"password,omitempty"`
  32. // Database to be selected after connecting to the server.
  33. Db int `json:"db,omitempty"`
  34. // key of field
  35. Field string `json:"field,omitempty"`
  36. // key define
  37. Key string `json:"key,omitempty"`
  38. DataType string `json:"dataType,omitempty"`
  39. Expiration time.Duration `json:"expiration,omitempty"`
  40. RowkindField string `json:"rowkindField"`
  41. DataTemplate string `json:"dataTemplate"`
  42. }
  43. type RedisSink struct {
  44. c *config
  45. cli *redis.Client
  46. }
  47. func (r *RedisSink) Configure(props map[string]interface{}) error {
  48. c := &config{DataType: "string", Expiration: -1}
  49. err := cast.MapToStruct(props, c)
  50. if err != nil {
  51. return err
  52. }
  53. if c.Key == "" && c.Field == "" {
  54. return errors.New("redis sink must have key or field")
  55. }
  56. if c.DataType != "string" && c.DataType != "list" {
  57. return errors.New("redis sink only support string or list data type")
  58. }
  59. r.c = c
  60. return nil
  61. }
  62. func (r *RedisSink) Open(ctx api.StreamContext) (err error) {
  63. logger := ctx.GetLogger()
  64. logger.Debug("Opening redis sink")
  65. r.cli = redis.NewClient(&redis.Options{
  66. Addr: r.c.Addr,
  67. Username: r.c.Username,
  68. Password: r.c.Password,
  69. DB: r.c.Db, // use default DB
  70. })
  71. _, err = r.cli.Ping().Result()
  72. return err
  73. }
  74. func (r *RedisSink) Collect(ctx api.StreamContext, data interface{}) error {
  75. logger := ctx.GetLogger()
  76. var val string
  77. if r.c.DataTemplate != "" { // The result is a string
  78. v, _, err := ctx.TransformOutput(data)
  79. if err != nil {
  80. logger.Error(err)
  81. return err
  82. }
  83. m := make(map[string]interface{})
  84. err = json.Unmarshal(v, &m)
  85. if err != nil {
  86. return fmt.Errorf("fail to decode data %s after applying dataTemplate for error %v", string(v), err)
  87. }
  88. data = m
  89. val = string(v)
  90. }
  91. switch d := data.(type) {
  92. case []map[string]interface{}:
  93. for _, el := range d {
  94. err := r.save(ctx, el, val)
  95. if err != nil {
  96. return err
  97. }
  98. }
  99. case map[string]interface{}:
  100. err := r.save(ctx, d, val)
  101. if err != nil {
  102. return err
  103. }
  104. default:
  105. return fmt.Errorf("unrecognized format of %s", data)
  106. }
  107. logger.Debug("insert success %v", data)
  108. return nil
  109. }
  110. func (r *RedisSink) Close(ctx api.StreamContext) error {
  111. ctx.GetLogger().Infof("Closing redis sink")
  112. err := r.cli.Close()
  113. return err
  114. }
  115. func (r *RedisSink) save(ctx api.StreamContext, data map[string]interface{}, val string) error {
  116. logger := ctx.GetLogger()
  117. if val == "" {
  118. jsonBytes, err := json.Marshal(data)
  119. if err != nil {
  120. return err
  121. }
  122. val = string(jsonBytes)
  123. }
  124. key := r.c.Key
  125. var err error
  126. if r.c.Field != "" {
  127. keyval, ok := data[r.c.Field]
  128. if !ok {
  129. return fmt.Errorf("field %s does not exist in data %v", r.c.Field, data)
  130. }
  131. key, err = cast.ToString(keyval, cast.CONVERT_ALL)
  132. if err != nil {
  133. return fmt.Errorf("key must be string or convertible to string, but got %v", keyval)
  134. }
  135. }
  136. rowkind := ast.RowkindUpsert
  137. if r.c.RowkindField != "" {
  138. c, ok := data[r.c.RowkindField]
  139. if ok {
  140. rowkind, ok = c.(string)
  141. if !ok {
  142. return fmt.Errorf("rowkind field %s is not a string in data %v", r.c.RowkindField, data)
  143. }
  144. if rowkind != ast.RowkindInsert && rowkind != ast.RowkindUpdate && rowkind != ast.RowkindDelete && rowkind != ast.RowkindUpsert {
  145. return fmt.Errorf("invalid rowkind %s", rowkind)
  146. }
  147. }
  148. }
  149. switch rowkind {
  150. case ast.RowkindInsert, ast.RowkindUpdate, ast.RowkindUpsert:
  151. if r.c.DataType == "list" {
  152. err = r.cli.LPush(key, val).Err()
  153. if err != nil {
  154. return fmt.Errorf("lpush %s:%s error, %v", key, val, err)
  155. }
  156. logger.Debugf("push redis list success, key:%s data: %v", key, val)
  157. } else {
  158. err = r.cli.Set(key, val, r.c.Expiration*time.Second).Err()
  159. if err != nil {
  160. return fmt.Errorf("set %s:%s error, %v", key, val, err)
  161. }
  162. logger.Debugf("set redis string success, key:%s data: %s", key, val)
  163. }
  164. case ast.RowkindDelete:
  165. if r.c.DataType == "list" {
  166. err = r.cli.LPop(key).Err()
  167. if err != nil {
  168. return fmt.Errorf("lpop %s error, %v", key, err)
  169. }
  170. logger.Debugf("pop redis list success, key:%s data: %v", key, val)
  171. } else {
  172. err = r.cli.Del(key).Err()
  173. if err != nil {
  174. logger.Error(err)
  175. return err
  176. }
  177. logger.Debugf("delete redis string success, key:%s data: %s", key, val)
  178. }
  179. default:
  180. // never happen
  181. logger.Errorf("unexpected rowkind %s", rowkind)
  182. }
  183. return nil
  184. }
  185. func GetSink() api.Sink {
  186. return &RedisSink{}
  187. }