httppull_source.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package extensions
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/emqx/kuiper/common"
  8. "github.com/emqx/kuiper/xstream/api"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "time"
  14. )
  15. const DEFAULT_INTERVAL = 10000
  16. const DEFAULT_TIMEOUT = 5000
  17. type HTTPPullSource struct {
  18. url string
  19. method string
  20. interval int
  21. timeout int
  22. incremental bool
  23. body string
  24. bodyType string
  25. headers map[string]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"
  31. if u, ok := props["url"]; ok {
  32. if p, ok := u.(string); ok {
  33. hps.url = p
  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. if b, ok := props["body"]; ok {
  84. if b1, ok1 := b.(string); ok1 {
  85. hps.body = b1
  86. } else {
  87. return fmt.Errorf("Not valid incremental value %v, expect string.", b1)
  88. }
  89. }
  90. hps.headers = make(map[string]string)
  91. if h, ok := props["headers"]; ok {
  92. if h1, ok1 := h.(map[string]interface{}); ok1 {
  93. for k, v := range h1 {
  94. if v1, ok2 := CastToString(v); ok2 {
  95. hps.headers[k] = v1
  96. }
  97. }
  98. } else {
  99. return fmt.Errorf("Not valid header value %v.", h1)
  100. }
  101. }
  102. common.Log.Infof("Initialized with configurations %#v.", hps)
  103. return nil
  104. }
  105. func (hps *HTTPPullSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  106. _, e := url.Parse(hps.url)
  107. if e != nil {
  108. errCh <- e
  109. return
  110. }
  111. hps.client = &http.Client{Timeout: time.Duration(hps.timeout) * time.Millisecond}
  112. hps.initTimerPull(ctx, consumer, errCh)
  113. }
  114. func (hps *HTTPPullSource) Close(ctx api.StreamContext) error {
  115. logger := ctx.GetLogger()
  116. logger.Infof("Closing HTTP pull source")
  117. return nil
  118. }
  119. func (hps *HTTPPullSource) initTimerPull(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  120. ticker := time.NewTicker(time.Millisecond * time.Duration(hps.interval))
  121. logger := ctx.GetLogger()
  122. defer ticker.Stop()
  123. var omd5 = ""
  124. for {
  125. select {
  126. case <-ticker.C:
  127. if resp, e := common.Send(logger, hps.client, hps.bodyType, hps.method, hps.url, hps.headers, true, []byte(hps.body)); e != nil {
  128. logger.Warnf("Found error %s when trying to reach %v ", e, hps)
  129. } else {
  130. logger.Debugf("rest sink got response %v", resp)
  131. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  132. logger.Warnf("Found error http return code: %d when trying to reach %v ", resp.StatusCode, hps)
  133. break
  134. }
  135. defer resp.Body.Close()
  136. c, err := ioutil.ReadAll(resp.Body)
  137. if err != nil {
  138. logger.Warnf("Found error %s when trying to reach %v ", err, hps)
  139. }
  140. if hps.incremental {
  141. nmd5 := getMD5Hash(c)
  142. if omd5 == nmd5 {
  143. logger.Infof("Content has not changed since last fetch, so skip processing.")
  144. continue
  145. } else {
  146. omd5 = nmd5
  147. }
  148. }
  149. result := make(map[string]interface{})
  150. meta := make(map[string]interface{})
  151. if e := json.Unmarshal(c, &result); e != nil {
  152. logger.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(c), e)
  153. return
  154. }
  155. select {
  156. case consumer <- api.NewDefaultSourceTuple(result, meta):
  157. logger.Debugf("send data to device node")
  158. }
  159. }
  160. case <-ctx.Done():
  161. return
  162. }
  163. }
  164. }
  165. func getMD5Hash(text []byte) string {
  166. hash := md5.Sum(text)
  167. return hex.EncodeToString(hash[:])
  168. }