httppull_source.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. package http
  15. import (
  16. "fmt"
  17. "time"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/internal/io"
  20. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  21. "github.com/lf-edge/ekuiper/internal/xsql"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. )
  24. type pullTimeMeta struct {
  25. LastPullTime int64 `json:"lastPullTime"`
  26. PullTime int64 `json:"pullTime"`
  27. }
  28. type PullSource struct {
  29. ClientConf
  30. t *pullTimeMeta
  31. }
  32. func (hps *PullSource) Configure(device string, props map[string]interface{}) error {
  33. conf.Log.Infof("Initialized Httppull source with configurations %#v.", props)
  34. return hps.InitConf(device, props)
  35. }
  36. func (hps *PullSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  37. ctx.GetLogger().Infof("Opening HTTP pull source with conf %+v", hps.config)
  38. hps.initTimerPull(ctx, consumer, errCh)
  39. }
  40. func (hps *PullSource) Close(ctx api.StreamContext) error {
  41. logger := ctx.GetLogger()
  42. logger.Infof("Closing HTTP pull source")
  43. return nil
  44. }
  45. func (hps *PullSource) initTimerPull(ctx api.StreamContext, consumer chan<- api.SourceTuple, _ chan<- error) {
  46. logger := ctx.GetLogger()
  47. logger.Infof("Starting HTTP pull source with interval %d", hps.config.Interval)
  48. ticker := conf.GetTicker(int64(hps.config.Interval))
  49. defer ticker.Stop()
  50. omd5 := ""
  51. // Pulling data at initial start
  52. logger.Debugf("Pulling data at initial start")
  53. tuples := hps.doPull(ctx, conf.GetNow(), &omd5)
  54. io.ReceiveTuples(ctx, consumer, tuples)
  55. for {
  56. select {
  57. case rcvTime := <-ticker.C:
  58. logger.Debugf("Pulling data at %d", rcvTime.UnixMilli())
  59. tuples := hps.doPull(ctx, rcvTime, &omd5)
  60. io.ReceiveTuples(ctx, consumer, tuples)
  61. case <-ctx.Done():
  62. return
  63. }
  64. }
  65. }
  66. func (hps *PullSource) doPull(ctx api.StreamContext, rcvTime time.Time, omd5 *string) []api.SourceTuple {
  67. if hps.t == nil {
  68. hps.t = &pullTimeMeta{
  69. LastPullTime: rcvTime.UnixMilli() - int64(hps.config.Interval),
  70. PullTime: rcvTime.UnixMilli(),
  71. }
  72. } else {
  73. // only update last pull time when there is no error
  74. hps.t.PullTime = rcvTime.UnixMilli()
  75. }
  76. // Parse url which may contain dynamic time range
  77. url, err := ctx.ParseTemplate(hps.config.Url, hps.t)
  78. if err != nil {
  79. return []api.SourceTuple{
  80. &xsql.ErrorSourceTuple{
  81. Error: fmt.Errorf("parse url %s error %v", hps.config.Url, err),
  82. },
  83. }
  84. }
  85. // check oAuth token expiration
  86. if hps.accessConf != nil && hps.accessConf.ExpireInSecond > 0 &&
  87. int(time.Now().Sub(hps.tokenLastUpdateAt).Abs().Seconds()) >= hps.accessConf.ExpireInSecond {
  88. ctx.GetLogger().Debugf("Refreshing token for HTTP pull")
  89. if err := hps.refresh(ctx); err != nil {
  90. ctx.GetLogger().Warnf("Refresh HTTP pull token error: %v", err)
  91. }
  92. }
  93. headers, err := hps.parseHeaders(ctx, hps.tokens)
  94. if err != nil {
  95. return []api.SourceTuple{
  96. &xsql.ErrorSourceTuple{
  97. Error: fmt.Errorf("parse headers error %v", err),
  98. },
  99. }
  100. }
  101. body, err := ctx.ParseTemplate(hps.config.Body, hps.t)
  102. if err != nil {
  103. return []api.SourceTuple{
  104. &xsql.ErrorSourceTuple{
  105. Error: fmt.Errorf("parse body %s error %v", hps.config.Body, err),
  106. },
  107. }
  108. }
  109. ctx.GetLogger().Debugf("httppull source sending request url: %s, headers: %v, body %s", url, headers, hps.config.Body)
  110. if resp, e := httpx.Send(ctx.GetLogger(), hps.client, hps.config.BodyType, hps.config.Method, url, headers, true, body); e != nil {
  111. ctx.GetLogger().Warnf("Found error %s when trying to reach %v ", e, hps)
  112. return []api.SourceTuple{
  113. &xsql.ErrorSourceTuple{
  114. Error: fmt.Errorf("send request error %v", e),
  115. },
  116. }
  117. } else {
  118. ctx.GetLogger().Debugf("httppull source got response %v", resp)
  119. results, _, e := hps.parseResponse(ctx, resp, true, omd5)
  120. if e != nil {
  121. return []api.SourceTuple{
  122. &xsql.ErrorSourceTuple{
  123. Error: fmt.Errorf("parse response error %v", e),
  124. },
  125. }
  126. }
  127. hps.t.LastPullTime = hps.t.PullTime
  128. if results == nil {
  129. ctx.GetLogger().Debugf("no data to send for incremental")
  130. return nil
  131. }
  132. tuples := make([]api.SourceTuple, len(results))
  133. meta := make(map[string]interface{})
  134. for i, result := range results {
  135. tuples[i] = api.NewDefaultSourceTupleWithTime(result, meta, rcvTime)
  136. }
  137. return tuples
  138. }
  139. }