client.go 13 KB

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