httppull_source.go 7.2 KB

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