client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright 2023 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 http
  15. import (
  16. "crypto/md5"
  17. "encoding/hex"
  18. "encoding/json"
  19. "fmt"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. "github.com/lf-edge/ekuiper/internal/io/mock"
  22. "github.com/lf-edge/ekuiper/internal/pkg/cert"
  23. "github.com/lf-edge/ekuiper/internal/pkg/httpx"
  24. "github.com/lf-edge/ekuiper/pkg/api"
  25. "github.com/lf-edge/ekuiper/pkg/cast"
  26. "io"
  27. "net/http"
  28. "strings"
  29. "time"
  30. )
  31. // ClientConf is the configuration for http client
  32. // It is shared by httppull source and rest sink to configure their http client
  33. type ClientConf struct {
  34. config *RawConf
  35. accessConf *AccessTokenConf
  36. refreshConf *RefreshTokenConf
  37. tokens map[string]interface{}
  38. client *http.Client
  39. }
  40. type RawConf struct {
  41. Url string `json:"url"`
  42. Method string `json:"method"`
  43. Body string `json:"body"`
  44. BodyType string `json:"bodyType"`
  45. Headers interface{} `json:"headers"`
  46. InsecureSkipVerify bool `json:"insecureSkipVerify"`
  47. CertificationPath string `json:"certificationPath"`
  48. PrivateKeyPath string `json:"privateKeyPath"`
  49. RootCaPath string `json:"rootCaPath"`
  50. Timeout int `json:"timeout"`
  51. DebugResp bool `json:"debugResp"`
  52. // Could be code or body
  53. ResponseType string `json:"responseType"`
  54. OAuth map[string]map[string]interface{} `json:"oauth"`
  55. // source specific properties
  56. Interval int `json:"interval"`
  57. Incremental bool `json:"incremental"`
  58. // sink specific properties
  59. SendSingle bool `json:"sendSingle"`
  60. // inferred properties
  61. HeadersTemplate string
  62. HeadersMap map[string]string
  63. }
  64. const (
  65. DefaultInterval = 10000
  66. DefaultTimeout = 5000
  67. )
  68. type AccessTokenConf struct {
  69. Url string `json:"url"`
  70. Body string `json:"body"`
  71. Expire string `json:"expire"`
  72. ExpireInSecond int
  73. }
  74. type RefreshTokenConf struct {
  75. Url string `json:"url"`
  76. Headers map[string]string `json:"headers"`
  77. Body string `json:"body"`
  78. }
  79. type bodyResp struct {
  80. Code int `json:"code"`
  81. }
  82. var bodyTypeMap = map[string]string{"none": "", "text": "text/plain", "json": "application/json", "html": "text/html", "xml": "application/xml", "javascript": "application/javascript", "form": ""}
  83. func (cc *ClientConf) InitConf(device string, props map[string]interface{}) error {
  84. c := &RawConf{
  85. Url: "http://localhost",
  86. Method: http.MethodGet,
  87. Interval: DefaultInterval,
  88. Timeout: DefaultTimeout,
  89. InsecureSkipVerify: true,
  90. ResponseType: "code",
  91. }
  92. if err := cast.MapToStruct(props, c); err != nil {
  93. return fmt.Errorf("fail to parse the properties: %v", err)
  94. }
  95. if c.Url == "" {
  96. return fmt.Errorf("url is required")
  97. }
  98. c.Url = c.Url + device
  99. switch strings.ToUpper(c.Method) {
  100. case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete:
  101. c.Method = strings.ToUpper(c.Method)
  102. default:
  103. return fmt.Errorf("Not supported HTTP method %s.", c.Method)
  104. }
  105. if c.Interval <= 0 {
  106. return fmt.Errorf("interval must be greater than 0")
  107. }
  108. if c.Timeout < 0 {
  109. return fmt.Errorf("timeout must be greater than or equal to 0")
  110. }
  111. // Set default body type if not set
  112. if c.BodyType == "" {
  113. switch c.Method {
  114. case http.MethodGet, http.MethodHead:
  115. c.BodyType = "none"
  116. default:
  117. c.BodyType = "json"
  118. }
  119. }
  120. if _, ok2 := bodyTypeMap[strings.ToLower(c.BodyType)]; ok2 {
  121. c.BodyType = strings.ToLower(c.BodyType)
  122. } else {
  123. return fmt.Errorf("Not valid body type value %v.", c.BodyType)
  124. }
  125. switch c.ResponseType {
  126. case "code", "body":
  127. // correct
  128. default:
  129. return fmt.Errorf("Not valid response type value %v.", c.ResponseType)
  130. }
  131. err := httpx.IsHttpUrl(c.Url)
  132. if err != nil {
  133. return err
  134. }
  135. switch h := c.Headers.(type) {
  136. case map[string]interface{}:
  137. c.HeadersMap = make(map[string]string, len(h))
  138. for k, v := range h {
  139. c.HeadersMap[k] = v.(string)
  140. }
  141. case string:
  142. c.HeadersTemplate = h
  143. }
  144. tlsOpts := cert.TlsConfigurationOptions{
  145. SkipCertVerify: c.InsecureSkipVerify,
  146. CertFile: c.CertificationPath,
  147. KeyFile: c.PrivateKeyPath,
  148. CaFile: c.RootCaPath,
  149. }
  150. tlscfg, err := cert.GenerateTLSForClient(tlsOpts)
  151. if err != nil {
  152. return err
  153. }
  154. // validate oAuth
  155. if c.OAuth != nil {
  156. // validate access token
  157. if ap, ok := c.OAuth["access"]; ok {
  158. accessConf := &AccessTokenConf{}
  159. if err := cast.MapToStruct(ap, accessConf); err != nil {
  160. return fmt.Errorf("fail to parse the access properties of oAuth: %v", err)
  161. }
  162. if accessConf.Url == "" {
  163. return fmt.Errorf("access token url is required")
  164. }
  165. // expire time will update every time when access token is refreshed if expired is set
  166. cc.accessConf = accessConf
  167. } else {
  168. return fmt.Errorf("if setting oAuth, `access` property is required")
  169. }
  170. // validate refresh token, it is optional
  171. if rp, ok := c.OAuth["refresh"]; ok {
  172. refreshConf := &RefreshTokenConf{}
  173. if err := cast.MapToStruct(rp, refreshConf); err != nil {
  174. return fmt.Errorf("fail to parse the refresh token properties: %v", err)
  175. }
  176. if refreshConf.Url == "" {
  177. return fmt.Errorf("refresh token url is required")
  178. }
  179. cc.refreshConf = refreshConf
  180. }
  181. }
  182. tr := &http.Transport{
  183. TLSClientConfig: tlscfg,
  184. }
  185. cc.client = &http.Client{
  186. Transport: tr,
  187. Timeout: time.Duration(c.Timeout) * time.Millisecond,
  188. }
  189. cc.config = c
  190. // try to get access token
  191. if cc.accessConf != nil {
  192. conf.Log.Infof("Try to get access token from %s", cc.accessConf.Url)
  193. ctx := mock.NewMockContext("none", "httppull_init")
  194. cc.tokens = make(map[string]interface{})
  195. err := cc.auth(ctx)
  196. if err != nil {
  197. return fmt.Errorf("fail to authorize by oAuth: %v", err)
  198. }
  199. }
  200. return nil
  201. }
  202. // initialize the oAuth access token
  203. func (cc *ClientConf) auth(ctx api.StreamContext) error {
  204. if resp, e := httpx.Send(conf.Log, cc.client, "json", http.MethodPost, cc.accessConf.Url, nil, true, []byte(cc.accessConf.Body)); e == nil {
  205. conf.Log.Infof("try to get access token got response %v", resp)
  206. cc.tokens, _, e = cc.parseResponse(ctx, resp, true, nil)
  207. if e != nil {
  208. return fmt.Errorf("Cannot parse access token response to json: %v", e)
  209. }
  210. ctx.GetLogger().Infof("Got access token %v", cc.tokens)
  211. expireIn, err := ctx.ParseTemplate(cc.accessConf.Expire, cc.tokens)
  212. if err != nil {
  213. return fmt.Errorf("fail to parse the expire time for access token: %v", err)
  214. }
  215. cc.accessConf.ExpireInSecond, err = cast.ToInt(expireIn, cast.CONVERT_ALL)
  216. if err != nil {
  217. return fmt.Errorf("fail to covert the expire time %s for access token: %v", expireIn, err)
  218. }
  219. if cc.refreshConf != nil {
  220. err := cc.refresh(ctx)
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. } else {
  226. return fmt.Errorf("fail to get access token: %v", e)
  227. }
  228. return nil
  229. }
  230. func (cc *ClientConf) refresh(ctx api.StreamContext) error {
  231. if cc.refreshConf != nil {
  232. headers := make(map[string]string, len(cc.refreshConf.Headers))
  233. var err error
  234. for k, v := range cc.refreshConf.Headers {
  235. headers[k], err = ctx.ParseTemplate(v, cc.tokens)
  236. if err != nil {
  237. return fmt.Errorf("fail to parse the header for refresh token request %s: %v", k, err)
  238. }
  239. }
  240. rr, ee := httpx.Send(conf.Log, cc.client, "json", http.MethodPost, cc.refreshConf.Url, headers, true, []byte(cc.accessConf.Body))
  241. if ee != nil {
  242. return fmt.Errorf("fail to get refresh token: %v", ee)
  243. }
  244. nt, _, err := cc.parseResponse(ctx, rr, true, nil)
  245. for k, v := range nt {
  246. if v != nil {
  247. cc.tokens[k] = v
  248. }
  249. }
  250. if err != nil {
  251. return fmt.Errorf("Cannot parse refresh token response to json: %v", err)
  252. }
  253. return nil
  254. } else if cc.accessConf != nil {
  255. return cc.auth(ctx)
  256. } else {
  257. return fmt.Errorf("no oAuth config")
  258. }
  259. }
  260. func (cc *ClientConf) parseHeaders(ctx api.StreamContext, data interface{}) (map[string]string, error) {
  261. headers := make(map[string]string)
  262. var err error
  263. if cc.config.HeadersMap != nil {
  264. for k, v := range cc.config.HeadersMap {
  265. headers[k], err = ctx.ParseTemplate(v, data)
  266. if err != nil {
  267. return nil, fmt.Errorf("fail to parse the header entry %s: %v", k, err)
  268. }
  269. }
  270. } else if cc.config.HeadersTemplate != "" {
  271. tstr, err := ctx.ParseTemplate(cc.config.HeadersTemplate, data)
  272. if err != nil {
  273. return nil, fmt.Errorf("fail to parse the header template %s: %v", cc.config.HeadersTemplate, err)
  274. }
  275. err = json.Unmarshal([]byte(tstr), &headers)
  276. if err != nil {
  277. return nil, fmt.Errorf("parsed header template is not json: %s", tstr)
  278. }
  279. }
  280. return headers, nil
  281. }
  282. // parse the response status. For rest sink, it will not return the body by default if not need to debug
  283. func (cc *ClientConf) parseResponse(ctx api.StreamContext, resp *http.Response, returnBody bool, omd5 *string) (map[string]interface{}, []byte, error) {
  284. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  285. c, err := io.ReadAll(resp.Body)
  286. if err != nil {
  287. return nil, []byte("fail to read body"),
  288. fmt.Errorf("http return code error: %d", resp.StatusCode)
  289. }
  290. defer resp.Body.Close()
  291. return nil, c, fmt.Errorf("http return code error: %d", resp.StatusCode)
  292. } else if !returnBody { // For rest sink who only need to know if the request is successful
  293. return nil, nil, nil
  294. }
  295. c, err := io.ReadAll(resp.Body)
  296. if err != nil {
  297. return nil, []byte("fail to read body"), err
  298. }
  299. defer resp.Body.Close()
  300. if returnBody && cc.config.Incremental {
  301. nmd5 := getMD5Hash(c)
  302. if *omd5 == nmd5 {
  303. ctx.GetLogger().Debugf("Content has not changed since last fetch, so skip processing.")
  304. return nil, nil, nil
  305. } else {
  306. *omd5 = nmd5
  307. }
  308. }
  309. switch cc.config.ResponseType {
  310. case "code":
  311. if returnBody {
  312. m, e := decode(ctx, c)
  313. return m, c, e
  314. }
  315. return nil, nil, nil
  316. case "body":
  317. payload, err := decode(ctx, c)
  318. if err != nil {
  319. return nil, c, err
  320. }
  321. ro := &bodyResp{}
  322. err = cast.MapToStruct(payload, ro)
  323. if err != nil {
  324. return nil, c, fmt.Errorf("invalid body response: %v", err)
  325. }
  326. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  327. return nil, c, fmt.Errorf("http status code is not 200: %v", payload)
  328. }
  329. if returnBody {
  330. return payload, c, nil
  331. }
  332. return nil, nil, nil
  333. default:
  334. return nil, c, fmt.Errorf("unsupported response type: %s", cc.config.ResponseType)
  335. }
  336. }
  337. func getMD5Hash(text []byte) string {
  338. hash := md5.Sum(text)
  339. return hex.EncodeToString(hash[:])
  340. }
  341. // TODO remove this function after all the sources are migrated to use the new API
  342. func decode(ctx api.StreamContext, data []byte) (map[string]interface{}, error) {
  343. r, err := ctx.Decode(data)
  344. if err == nil {
  345. return r, nil
  346. }
  347. r = make(map[string]interface{})
  348. err = json.Unmarshal(data, &r)
  349. return r, nil
  350. }