httppull_source.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. for {
  52. select {
  53. case rcvTime := <-ticker.C:
  54. logger.Debugf("Pulling data at %d", rcvTime.UnixMilli())
  55. tuples := hps.doPull(ctx, rcvTime, &omd5)
  56. io.ReceiveTuples(ctx, consumer, tuples)
  57. case <-ctx.Done():
  58. return
  59. }
  60. }
  61. }
  62. func (hps *PullSource) doPull(ctx api.StreamContext, rcvTime time.Time, omd5 *string) []api.SourceTuple {
  63. if hps.t == nil {
  64. hps.t = &pullTimeMeta{
  65. LastPullTime: rcvTime.UnixMilli() - int64(hps.config.Interval),
  66. PullTime: rcvTime.UnixMilli(),
  67. }
  68. } else {
  69. // only update last pull time when there is no error
  70. hps.t.PullTime = rcvTime.UnixMilli()
  71. }
  72. // Parse url which may contain dynamic time range
  73. url, err := ctx.ParseTemplate(hps.config.Url, hps.t)
  74. if err != nil {
  75. return []api.SourceTuple{
  76. &xsql.ErrorSourceTuple{
  77. Error: fmt.Errorf("parse url %s error %v", hps.config.Url, err),
  78. },
  79. }
  80. }
  81. // check oAuth token expiration
  82. if hps.accessConf != nil && hps.accessConf.ExpireInSecond > 0 &&
  83. int(time.Now().Sub(hps.tokenLastUpdateAt).Abs().Seconds()) >= hps.accessConf.ExpireInSecond {
  84. ctx.GetLogger().Debugf("Refreshing token for HTTP pull")
  85. if err := hps.refresh(ctx); err != nil {
  86. ctx.GetLogger().Warnf("Refresh HTTP pull token error: %v", err)
  87. }
  88. }
  89. headers, err := hps.parseHeaders(ctx, hps.tokens)
  90. if err != nil {
  91. return []api.SourceTuple{
  92. &xsql.ErrorSourceTuple{
  93. Error: fmt.Errorf("parse headers error %v", err),
  94. },
  95. }
  96. }
  97. body, err := ctx.ParseTemplate(hps.config.Body, hps.t)
  98. if err != nil {
  99. return []api.SourceTuple{
  100. &xsql.ErrorSourceTuple{
  101. Error: fmt.Errorf("parse body %s error %v", hps.config.Body, err),
  102. },
  103. }
  104. }
  105. ctx.GetLogger().Debugf("httppull source sending request url: %s, headers: %v, body %s", url, headers, hps.config.Body)
  106. if resp, e := httpx.Send(ctx.GetLogger(), hps.client, hps.config.BodyType, hps.config.Method, url, headers, true, body); e != nil {
  107. ctx.GetLogger().Warnf("Found error %s when trying to reach %v ", e, hps)
  108. return []api.SourceTuple{
  109. &xsql.ErrorSourceTuple{
  110. Error: fmt.Errorf("send request error %v", e),
  111. },
  112. }
  113. } else {
  114. ctx.GetLogger().Debugf("httppull source got response %v", resp)
  115. results, _, e := hps.parseResponse(ctx, resp, true, omd5)
  116. if e != nil {
  117. return []api.SourceTuple{
  118. &xsql.ErrorSourceTuple{
  119. Error: fmt.Errorf("parse response error %v", e),
  120. },
  121. }
  122. }
  123. hps.t.LastPullTime = hps.t.PullTime
  124. if results == nil {
  125. ctx.GetLogger().Debugf("no data to send for incremental")
  126. return nil
  127. }
  128. tuples := make([]api.SourceTuple, len(results))
  129. meta := make(map[string]interface{})
  130. for i, result := range results {
  131. tuples[i] = api.NewDefaultSourceTupleWithTime(result, meta, rcvTime)
  132. }
  133. return tuples
  134. }
  135. }