httppull_source.go 6.1 KB

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