httppull_source.go 6.8 KB

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