httppull_source.go 5.1 KB

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