httppull_source.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. // Copyright 2021 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 source
  15. import (
  16. "crypto/md5"
  17. "encoding/hex"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/internal/conf"
  20. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  21. "github.com/lf-edge/ekuiper/pkg/api"
  22. "github.com/lf-edge/ekuiper/pkg/cast"
  23. "github.com/lf-edge/ekuiper/pkg/message"
  24. "io/ioutil"
  25. "net/http"
  26. "net/url"
  27. "strings"
  28. "time"
  29. )
  30. const DEFAULT_INTERVAL = 10000
  31. const DEFAULT_TIMEOUT = 5000
  32. type HTTPPullSource struct {
  33. url string
  34. method string
  35. interval int
  36. timeout int
  37. incremental bool
  38. body string
  39. bodyType string
  40. headers map[string]string
  41. messageFormat string
  42. client *http.Client
  43. }
  44. var bodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  45. func (hps *HTTPPullSource) Configure(device string, props map[string]interface{}) error {
  46. hps.url = "http://localhost" + device
  47. if u, ok := props["url"]; ok {
  48. if p, ok := u.(string); ok {
  49. hps.url = p + device
  50. }
  51. }
  52. hps.method = http.MethodGet
  53. if m, ok := props["method"]; ok {
  54. if m1, ok1 := m.(string); ok1 {
  55. switch strings.ToUpper(m1) {
  56. case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete:
  57. hps.method = strings.ToUpper(m1)
  58. default:
  59. return fmt.Errorf("Not supported HTTP method %s.", m1)
  60. }
  61. }
  62. }
  63. hps.interval = DEFAULT_INTERVAL
  64. if i, ok := props["interval"]; ok {
  65. if i1, ok1 := i.(int); ok1 {
  66. hps.interval = i1
  67. } else {
  68. return fmt.Errorf("Not valid interval value %v.", i1)
  69. }
  70. }
  71. hps.timeout = DEFAULT_TIMEOUT
  72. if i, ok := props["timeout"]; ok {
  73. if i1, ok1 := i.(int); ok1 {
  74. hps.timeout = i1
  75. } else {
  76. return fmt.Errorf("Not valid timeout value %v.", i1)
  77. }
  78. }
  79. hps.incremental = false
  80. if i, ok := props["incremental"]; ok {
  81. if i1, ok1 := i.(bool); ok1 {
  82. hps.incremental = i1
  83. } else {
  84. return fmt.Errorf("Not valid incremental value %v.", i1)
  85. }
  86. }
  87. hps.bodyType = "json"
  88. if c, ok := props["bodyType"]; ok {
  89. if c1, ok1 := c.(string); ok1 {
  90. if _, ok2 := bodyTypeMap[strings.ToLower(c1)]; ok2 {
  91. hps.bodyType = strings.ToLower(c1)
  92. } else {
  93. return fmt.Errorf("Not valid body type value %v.", c)
  94. }
  95. } else {
  96. return fmt.Errorf("Not valid body type value %v.", c)
  97. }
  98. }
  99. hps.messageFormat = message.FormatJson
  100. if c, ok := props["format"]; ok {
  101. if c1, ok1 := c.(string); ok1 {
  102. hps.messageFormat = c1
  103. } else {
  104. return fmt.Errorf("Not valid format value %v.", c)
  105. }
  106. }
  107. if b, ok := props["body"]; ok {
  108. if b1, ok1 := b.(string); ok1 {
  109. hps.body = b1
  110. } else {
  111. return fmt.Errorf("Not valid incremental value %v, expect string.", b1)
  112. }
  113. }
  114. hps.headers = make(map[string]string)
  115. if h, ok := props["headers"]; ok {
  116. if h1, ok1 := h.(map[string]interface{}); ok1 {
  117. for k, v := range h1 {
  118. if v1, err := cast.ToString(v, cast.CONVERT_ALL); err == nil {
  119. hps.headers[k] = v1
  120. }
  121. }
  122. } else {
  123. return fmt.Errorf("Not valid header value %v.", h1)
  124. }
  125. }
  126. conf.Log.Debugf("Initialized with configurations %#v.", hps)
  127. return nil
  128. }
  129. func (hps *HTTPPullSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  130. _, e := url.Parse(hps.url)
  131. if e != nil {
  132. errCh <- e
  133. return
  134. }
  135. hps.client = &http.Client{Timeout: time.Duration(hps.timeout) * time.Millisecond}
  136. hps.initTimerPull(ctx, consumer, errCh)
  137. }
  138. func (hps *HTTPPullSource) Close(ctx api.StreamContext) error {
  139. logger := ctx.GetLogger()
  140. logger.Infof("Closing HTTP pull source")
  141. return nil
  142. }
  143. func (hps *HTTPPullSource) initTimerPull(ctx api.StreamContext, consumer chan<- api.SourceTuple, _ chan<- error) {
  144. ticker := time.NewTicker(time.Millisecond * time.Duration(hps.interval))
  145. logger := ctx.GetLogger()
  146. defer ticker.Stop()
  147. var omd5 = ""
  148. for {
  149. select {
  150. case <-ticker.C:
  151. if resp, e := httpx.Send(logger, hps.client, hps.bodyType, hps.method, hps.url, hps.headers, true, []byte(hps.body)); e != nil {
  152. logger.Warnf("Found error %s when trying to reach %v ", e, hps)
  153. } else {
  154. logger.Debugf("rest sink got response %v", resp)
  155. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  156. logger.Warnf("Found error http return code: %d when trying to reach %v ", resp.StatusCode, hps)
  157. break
  158. }
  159. defer resp.Body.Close()
  160. c, err := ioutil.ReadAll(resp.Body)
  161. if err != nil {
  162. logger.Warnf("Found error %s when trying to reach %v ", err, hps)
  163. }
  164. if hps.incremental {
  165. nmd5 := getMD5Hash(c)
  166. if omd5 == nmd5 {
  167. logger.Debugf("Content has not changed since last fetch, so skip processing.")
  168. continue
  169. } else {
  170. omd5 = nmd5
  171. }
  172. }
  173. result, e := message.Decode(c, hps.messageFormat)
  174. meta := make(map[string]interface{})
  175. if e != nil {
  176. logger.Errorf("Invalid data format, cannot decode %s to %s format with error %s", string(c), hps.messageFormat, e)
  177. return
  178. }
  179. select {
  180. case consumer <- api.NewDefaultSourceTuple(result, meta):
  181. logger.Debugf("send data to device node")
  182. }
  183. }
  184. case <-ctx.Done():
  185. return
  186. }
  187. }
  188. }
  189. func getMD5Hash(text []byte) string {
  190. hash := md5.Sum(text)
  191. return hex.EncodeToString(hash[:])
  192. }