httppull_source.go 6.9 KB

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