httppull_source.go 4.9 KB

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