rest_sink.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 sink
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "strings"
  24. "time"
  25. )
  26. type RestSink struct {
  27. method string
  28. url string
  29. headers map[string]string
  30. headersTemplate string
  31. bodyType string
  32. timeout int64
  33. sendSingle bool
  34. debugResp bool
  35. insecureSkipVerify bool
  36. client *http.Client
  37. }
  38. var methodsMap = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "DELETE": true, "PATCH": true}
  39. func (ms *RestSink) Configure(ps map[string]interface{}) error {
  40. temp, ok := ps["method"]
  41. if ok {
  42. ms.method, ok = temp.(string)
  43. if !ok {
  44. return fmt.Errorf("rest sink property method %v is not a string", temp)
  45. }
  46. ms.method = strings.ToUpper(strings.Trim(ms.method, ""))
  47. } else {
  48. ms.method = "GET"
  49. }
  50. if _, ok = methodsMap[ms.method]; !ok {
  51. return fmt.Errorf("invalid property method: %s", ms.method)
  52. }
  53. switch ms.method {
  54. case "GET", "HEAD":
  55. ms.bodyType = "none"
  56. default:
  57. ms.bodyType = "json"
  58. }
  59. temp, ok = ps["url"]
  60. if !ok {
  61. return fmt.Errorf("rest sink is missing property url")
  62. }
  63. ms.url, ok = temp.(string)
  64. if !ok {
  65. return fmt.Errorf("rest sink property url %v is not a string", temp)
  66. }
  67. ms.url = strings.Trim(ms.url, "")
  68. temp, ok = ps["headers"]
  69. if ok {
  70. switch h := temp.(type) {
  71. case map[string]interface{}:
  72. ms.headers = make(map[string]string)
  73. for k, v := range h {
  74. if v1, ok1 := v.(string); ok1 {
  75. ms.headers[k] = v1
  76. } else {
  77. return fmt.Errorf("header value %s for header %s is not a string", v, k)
  78. }
  79. }
  80. case string:
  81. ms.headersTemplate = h
  82. default:
  83. return fmt.Errorf("rest sink property headers %v is not a map[string]interface", temp)
  84. }
  85. }
  86. temp, ok = ps["bodyType"]
  87. if ok {
  88. ms.bodyType, ok = temp.(string)
  89. if !ok {
  90. return fmt.Errorf("rest sink property bodyType %v is not a string", temp)
  91. }
  92. ms.bodyType = strings.ToLower(strings.Trim(ms.bodyType, ""))
  93. }
  94. if _, ok = httpx.BodyTypeMap[ms.bodyType]; !ok {
  95. return fmt.Errorf("invalid property bodyType: %s, should be \"none\" or \"form\"", ms.bodyType)
  96. }
  97. temp, ok = ps["timeout"]
  98. if !ok {
  99. ms.timeout = 5000
  100. } else {
  101. to, ok := temp.(float64)
  102. if !ok {
  103. return fmt.Errorf("rest sink property timeout %v is not a number", temp)
  104. }
  105. ms.timeout = int64(to)
  106. }
  107. temp, ok = ps["sendSingle"]
  108. if !ok {
  109. ms.sendSingle = false
  110. } else {
  111. ms.sendSingle, ok = temp.(bool)
  112. if !ok {
  113. return fmt.Errorf("rest sink property sendSingle %v is not a bool", temp)
  114. }
  115. }
  116. temp, ok = ps["debugResp"]
  117. if !ok {
  118. ms.debugResp = false
  119. } else {
  120. ms.debugResp, ok = temp.(bool)
  121. if !ok {
  122. return fmt.Errorf("rest sink property debugResp %v is not a bool", temp)
  123. }
  124. }
  125. temp, ok = ps["insecureSkipVerify"]
  126. if !ok {
  127. ms.insecureSkipVerify = true
  128. } else {
  129. ms.insecureSkipVerify, ok = temp.(bool)
  130. if !ok {
  131. return fmt.Errorf("rest sink property insecureSkipVerify %v is not a bool", temp)
  132. }
  133. }
  134. return nil
  135. }
  136. func (ms *RestSink) Open(ctx api.StreamContext) error {
  137. logger := ctx.GetLogger()
  138. tr := &http.Transport{
  139. TLSClientConfig: &tls.Config{InsecureSkipVerify: ms.insecureSkipVerify},
  140. }
  141. ms.client = &http.Client{
  142. Transport: tr,
  143. Timeout: time.Duration(ms.timeout) * time.Millisecond}
  144. logger.Infof("open rest sink with configuration: {method: %s, url: %s, bodyType: %s, timeout: %d,header: %v, sendSingle: %v, insecureSkipVerify: %v", ms.method, ms.url, ms.bodyType, ms.timeout, ms.headers, ms.sendSingle, ms.insecureSkipVerify)
  145. if _, err := url.Parse(ms.url); err != nil {
  146. return err
  147. }
  148. return nil
  149. }
  150. type MultiErrors []error
  151. func (me MultiErrors) AddError(err error) MultiErrors {
  152. me = append(me, err)
  153. return me
  154. }
  155. func (me MultiErrors) Error() string {
  156. s := make([]string, len(me))
  157. for i, v := range me {
  158. s = append(s, fmt.Sprintf("Error %d with info %s. \n", i, v))
  159. }
  160. return strings.Join(s, " ")
  161. }
  162. func (ms *RestSink) Collect(ctx api.StreamContext, item interface{}) error {
  163. logger := ctx.GetLogger()
  164. logger.Debugf("rest sink receive %s", item)
  165. output, transed, err := ctx.TransformOutput()
  166. if err != nil {
  167. logger.Warnf("rest sink decode data error: %v", err)
  168. return nil
  169. }
  170. var d = item
  171. if transed {
  172. d = output
  173. }
  174. resp, err := ms.Send(ctx, d, logger)
  175. if err != nil {
  176. return fmt.Errorf("rest sink fails to send out the data: %s", err)
  177. } else {
  178. defer resp.Body.Close()
  179. logger.Debugf("rest sink got response %v", resp)
  180. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  181. if buf, bodyErr := ioutil.ReadAll(resp.Body); bodyErr != nil {
  182. logger.Errorf("%s\n", bodyErr)
  183. return fmt.Errorf("rest sink fails to err http return code: %d and error message %s.", resp.StatusCode, bodyErr)
  184. } else {
  185. logger.Errorf("%s\n", string(buf))
  186. return fmt.Errorf("rest sink fails to err http return code: %d and error message %s.", resp.StatusCode, string(buf))
  187. }
  188. } else {
  189. if ms.debugResp {
  190. if buf, bodyErr := ioutil.ReadAll(resp.Body); bodyErr != nil {
  191. logger.Errorf("%s\n", bodyErr)
  192. } else {
  193. logger.Infof("Response content: %s\n", string(buf))
  194. }
  195. }
  196. }
  197. }
  198. return nil
  199. }
  200. func (ms *RestSink) Send(ctx api.StreamContext, v interface{}, logger api.Logger) (*http.Response, error) {
  201. temp, err := ctx.ParseDynamicProp(ms.bodyType, v)
  202. if err != nil {
  203. return nil, err
  204. }
  205. bodyType, ok := temp.(string)
  206. if !ok {
  207. return nil, fmt.Errorf("the value %v of dynamic prop %s for bodyType is not a string", ms.bodyType, temp)
  208. }
  209. temp, err = ctx.ParseDynamicProp(ms.method, v)
  210. if err != nil {
  211. return nil, err
  212. }
  213. method, ok := temp.(string)
  214. if !ok {
  215. return nil, fmt.Errorf("the value %v of dynamic prop %s for method is not a string", ms.method, temp)
  216. }
  217. temp, err = ctx.ParseDynamicProp(ms.url, v)
  218. if err != nil {
  219. return nil, err
  220. }
  221. url, ok := temp.(string)
  222. if !ok {
  223. return nil, fmt.Errorf("the value %v of dynamic prop %s for url is not a string", ms.url, temp)
  224. }
  225. var headers map[string]string
  226. if ms.headers != nil {
  227. headers = ms.headers
  228. } else if ms.headersTemplate != "" {
  229. temp, err = ctx.ParseDynamicProp(ms.headersTemplate, v)
  230. if err != nil {
  231. return nil, err
  232. }
  233. headers, ok = temp.(map[string]string)
  234. if !ok {
  235. return nil, fmt.Errorf("the value %v of dynamic prop %s for headers is not a map[string]string", ms.headersTemplate, temp)
  236. }
  237. }
  238. return httpx.Send(logger, ms.client, bodyType, method, url, headers, ms.sendSingle, v)
  239. }
  240. func (ms *RestSink) Close(ctx api.StreamContext) error {
  241. logger := ctx.GetLogger()
  242. logger.Infof("Closing rest sink")
  243. return nil
  244. }