httppull_source.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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. "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. client *http.Client
  26. }
  27. var bodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  28. func (hps *HTTPPullSource) Configure(device string, props map[string]interface{}) error {
  29. hps.url = "http://localhost";
  30. if u, ok := props["url"]; ok {
  31. if p, ok := u.(string); ok {
  32. hps.url = p
  33. }
  34. }
  35. hps.method = http.MethodGet
  36. if m, ok := props["method"]; ok {
  37. if m1, ok1 := m.(string); ok1 {
  38. switch strings.ToUpper(m1) {
  39. case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete:
  40. hps.method = m1
  41. default:
  42. return fmt.Errorf("Not supported HTTP method %s.", m1)
  43. }
  44. }
  45. }
  46. hps.interval = DEFAULT_INTERVAL
  47. if i, ok := props["interval"]; ok {
  48. if i1, ok1 := i.(int); ok1 {
  49. hps.interval = i1
  50. } else {
  51. return fmt.Errorf("Not valid interval value %v.", i1)
  52. }
  53. }
  54. hps.timeout = DEFAULT_TIMEOUT
  55. if i, ok := props["timeout"]; ok {
  56. if i1, ok1 := i.(int); ok1 {
  57. hps.timeout = i1
  58. } else {
  59. return fmt.Errorf("Not valid timeout value %v.", i1)
  60. }
  61. }
  62. hps.incremental = false
  63. if i, ok := props["incremental"]; ok {
  64. if i1, ok1 := i.(bool); ok1 {
  65. hps.incremental = i1
  66. } else {
  67. return fmt.Errorf("Not valid incremental value %v.", i1)
  68. }
  69. }
  70. hps.bodyType = "json"
  71. if c, ok := props["bodyType"]; ok {
  72. if c1, ok1 := c.(string); ok1 {
  73. if _, ok2 := bodyTypeMap[strings.ToLower(c1)]; ok2 {
  74. hps.bodyType = strings.ToLower(c1)
  75. } else {
  76. return fmt.Errorf("Not valid body type value %v.", c)
  77. }
  78. } else {
  79. return fmt.Errorf("Not valid body type value %v.", c)
  80. }
  81. }
  82. if b, ok := props["body"]; ok {
  83. if b1, ok1 := b.(string); ok1 {
  84. hps.body = b1
  85. } else {
  86. return fmt.Errorf("Not valid incremental value %v, expect string.", b1)
  87. }
  88. }
  89. hps.headers = make(map[string]string)
  90. if h, ok := props["headers"]; ok {
  91. if h1, ok1 := h.(map[string]interface{}); ok1 {
  92. for k, v := range h1 {
  93. if v1, ok2 := CastToString(v); ok2 {
  94. hps.headers[k] = v1
  95. }
  96. }
  97. } else {
  98. return fmt.Errorf("Not valid header value %v.", h1)
  99. }
  100. }
  101. common.Log.Infof("Initialized with configurations %#v.", hps)
  102. return nil
  103. }
  104. func (hps *HTTPPullSource) Open(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  105. _, e := url.Parse(hps.url)
  106. if e != nil {
  107. errCh <- e
  108. return
  109. }
  110. hps.client = &http.Client{Timeout: time.Duration(hps.timeout) * time.Millisecond}
  111. hps.initTimerPull(ctx, consumer, errCh)
  112. }
  113. func (hps *HTTPPullSource) Close(ctx api.StreamContext) error {
  114. logger := ctx.GetLogger()
  115. logger.Infof("Closing HTTP pull source")
  116. return nil
  117. }
  118. func (hps *HTTPPullSource) initTimerPull(ctx api.StreamContext, consumer chan<- api.SourceTuple, errCh chan<- error) {
  119. ticker := time.NewTicker(time.Millisecond * time.Duration(hps.interval))
  120. logger := ctx.GetLogger()
  121. defer ticker.Stop()
  122. var omd5 string = ""
  123. for {
  124. select {
  125. case <-ticker.C:
  126. if c, e := common.Send(logger, hps.client, hps.bodyType, hps.method, hps.url, hps.headers, true, []byte(hps.body)); e != nil {
  127. logger.Warnf("Found error %s when trying to reach %v ", e, hps)
  128. } else {
  129. if hps.incremental {
  130. nmd5 := getMD5Hash(c)
  131. if omd5 == nmd5 {
  132. logger.Infof("Content has not changed since last fetch, so skip processing.")
  133. continue
  134. } else {
  135. omd5 = nmd5
  136. }
  137. }
  138. result := make(map[string]interface{})
  139. meta := make(map[string]interface{})
  140. if e := json.Unmarshal(c, &result); e != nil {
  141. logger.Errorf("Invalid data format, cannot convert %s into JSON with error %s", string(c), e)
  142. return
  143. }
  144. select {
  145. case consumer <- api.NewDefaultSourceTuple(result, meta):
  146. logger.Debugf("send data to device node")
  147. }
  148. }
  149. case <-ctx.Done():
  150. return
  151. }
  152. }
  153. }
  154. func getMD5Hash(text []byte) string {
  155. hash := md5.Sum(text)
  156. return hex.EncodeToString(hash[:])
  157. }