default.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 context
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/topo/transform"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. "github.com/sirupsen/logrus"
  24. "regexp"
  25. "sync"
  26. "text/template"
  27. "time"
  28. )
  29. const LoggerKey = "$$logger"
  30. type DefaultContext struct {
  31. ruleId string
  32. opId string
  33. instanceId int
  34. ctx context.Context
  35. err error
  36. //Only initialized after withMeta set
  37. store api.Store
  38. state *sync.Map
  39. snapshot map[string]interface{}
  40. // cache
  41. tpReg sync.Map
  42. jpReg sync.Map
  43. }
  44. func Background() *DefaultContext {
  45. c := &DefaultContext{
  46. ctx: context.Background(),
  47. }
  48. return c
  49. }
  50. func WithValue(parent *DefaultContext, key, val interface{}) *DefaultContext {
  51. parent.ctx = context.WithValue(parent.ctx, key, val)
  52. return parent
  53. }
  54. //Implement context interface
  55. func (c *DefaultContext) Deadline() (deadline time.Time, ok bool) {
  56. return c.ctx.Deadline()
  57. }
  58. func (c *DefaultContext) Done() <-chan struct{} {
  59. return c.ctx.Done()
  60. }
  61. func (c *DefaultContext) Err() error {
  62. if c.err != nil {
  63. return c.err
  64. }
  65. return c.ctx.Err()
  66. }
  67. func (c *DefaultContext) Value(key interface{}) interface{} {
  68. return c.ctx.Value(key)
  69. }
  70. func (c *DefaultContext) GetContext() context.Context {
  71. return c.ctx
  72. }
  73. func (c *DefaultContext) GetLogger() api.Logger {
  74. l, ok := c.ctx.Value(LoggerKey).(*logrus.Entry)
  75. if l != nil && ok {
  76. return l
  77. }
  78. return conf.Log.WithField("caller", "default")
  79. }
  80. func (c *DefaultContext) GetRuleId() string {
  81. return c.ruleId
  82. }
  83. func (c *DefaultContext) GetOpId() string {
  84. return c.opId
  85. }
  86. func (c *DefaultContext) GetInstanceId() int {
  87. return c.instanceId
  88. }
  89. func (c *DefaultContext) GetRootPath() string {
  90. loc, _ := conf.GetLoc("")
  91. return loc
  92. }
  93. func (c *DefaultContext) SetError(err error) {
  94. c.err = err
  95. }
  96. func (c *DefaultContext) ParseTemplate(prop string, data interface{}) (string, error) {
  97. re := regexp.MustCompile(`{{(.*?)}}`)
  98. if re.Match([]byte(prop)) {
  99. var (
  100. tp *template.Template
  101. err error
  102. )
  103. if raw, ok := c.tpReg.Load(prop); ok {
  104. tp = raw.(*template.Template)
  105. } else {
  106. tp, err = transform.GenTp(prop)
  107. if err != nil {
  108. return fmt.Sprintf("%v", data), err
  109. }
  110. c.tpReg.Store(prop, tp)
  111. }
  112. var output bytes.Buffer
  113. err = tp.Execute(&output, data)
  114. if err != nil {
  115. return fmt.Sprintf("%v", data), err
  116. }
  117. return output.String(), nil
  118. } else {
  119. return prop, nil
  120. }
  121. }
  122. func (c *DefaultContext) ParseJsonPath(prop string, data interface{}) (interface{}, error) {
  123. var (
  124. je conf.JsonPathEval
  125. err error
  126. )
  127. if raw, ok := c.jpReg.Load(prop); ok {
  128. je = raw.(conf.JsonPathEval)
  129. } else {
  130. je, err = conf.GetJsonPathEval(prop)
  131. if err != nil {
  132. return nil, err
  133. }
  134. c.jpReg.Store(prop, je)
  135. }
  136. return je.Eval(data)
  137. }
  138. func (c *DefaultContext) WithMeta(ruleId string, opId string, store api.Store) api.StreamContext {
  139. s, err := store.GetOpState(opId)
  140. if err != nil {
  141. c.GetLogger().Warnf("Initialize context store error for %s: %s", opId, err)
  142. }
  143. return &DefaultContext{
  144. ruleId: ruleId,
  145. opId: opId,
  146. instanceId: 0,
  147. ctx: c.ctx,
  148. store: store,
  149. state: s,
  150. tpReg: sync.Map{},
  151. jpReg: sync.Map{},
  152. }
  153. }
  154. func (c *DefaultContext) WithInstance(instanceId int) api.StreamContext {
  155. return &DefaultContext{
  156. instanceId: instanceId,
  157. ruleId: c.ruleId,
  158. opId: c.opId,
  159. ctx: c.ctx,
  160. state: c.state,
  161. }
  162. }
  163. func (c *DefaultContext) WithCancel() (api.StreamContext, context.CancelFunc) {
  164. ctx, cancel := context.WithCancel(c.ctx)
  165. return &DefaultContext{
  166. ruleId: c.ruleId,
  167. opId: c.opId,
  168. instanceId: c.instanceId,
  169. ctx: ctx,
  170. state: c.state,
  171. }, cancel
  172. }
  173. func (c *DefaultContext) IncrCounter(key string, amount int) error {
  174. if v, ok := c.state.Load(key); ok {
  175. if vi, err := cast.ToInt(v, cast.STRICT); err != nil {
  176. return fmt.Errorf("state[%s] must be an int", key)
  177. } else {
  178. c.state.Store(key, vi+amount)
  179. }
  180. } else {
  181. c.state.Store(key, amount)
  182. }
  183. return nil
  184. }
  185. func (c *DefaultContext) GetCounter(key string) (int, error) {
  186. if v, ok := c.state.Load(key); ok {
  187. if vi, err := cast.ToInt(v, cast.STRICT); err != nil {
  188. return 0, fmt.Errorf("state[%s] is not a number, but %v", key, v)
  189. } else {
  190. return vi, nil
  191. }
  192. } else {
  193. c.state.Store(key, 0)
  194. return 0, nil
  195. }
  196. }
  197. func (c *DefaultContext) PutState(key string, value interface{}) error {
  198. c.state.Store(key, value)
  199. return nil
  200. }
  201. func (c *DefaultContext) GetState(key string) (interface{}, error) {
  202. if v, ok := c.state.Load(key); ok {
  203. return v, nil
  204. } else {
  205. return nil, nil
  206. }
  207. }
  208. func (c *DefaultContext) DeleteState(key string) error {
  209. c.state.Delete(key)
  210. return nil
  211. }
  212. func (c *DefaultContext) Snapshot() error {
  213. c.snapshot = cast.SyncMapToMap(c.state)
  214. return nil
  215. }
  216. func (c *DefaultContext) SaveState(checkpointId int64) error {
  217. err := c.store.SaveState(checkpointId, c.opId, c.snapshot)
  218. if err != nil {
  219. return err
  220. }
  221. c.snapshot = nil
  222. return nil
  223. }