client.go 13 KB

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