client.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. return nil
  211. }
  212. // initialize the oAuth access token
  213. func (cc *ClientConf) auth(ctx api.StreamContext) error {
  214. if resp, e := httpx.Send(conf.Log, cc.client, "json", http.MethodPost, cc.accessConf.Url, nil, true, cc.accessConf.Body); e == nil {
  215. conf.Log.Infof("try to get access token got response %v", resp)
  216. tokens, _, e := cc.parseResponse(ctx, resp, true, nil)
  217. if e != nil {
  218. return fmt.Errorf("Cannot parse access token response to json: %v", e)
  219. }
  220. cc.tokens = tokens[0]
  221. ctx.GetLogger().Infof("Got access token %v", cc.tokens)
  222. expireIn, err := ctx.ParseTemplate(cc.accessConf.Expire, cc.tokens)
  223. if err != nil {
  224. return fmt.Errorf("fail to parse the expire time for access token: %v", err)
  225. }
  226. cc.accessConf.ExpireInSecond, err = cast.ToInt(expireIn, cast.CONVERT_ALL)
  227. if err != nil {
  228. return fmt.Errorf("fail to covert the expire time %s for access token: %v", expireIn, err)
  229. }
  230. if cc.refreshConf != nil {
  231. err := cc.refresh(ctx)
  232. if err != nil {
  233. return err
  234. }
  235. } else {
  236. cc.tokenLastUpdateAt = time.Now()
  237. }
  238. } else {
  239. return fmt.Errorf("fail to get access token: %v", e)
  240. }
  241. return nil
  242. }
  243. func (cc *ClientConf) refresh(ctx api.StreamContext) error {
  244. if cc.refreshConf != nil {
  245. headers := make(map[string]string, len(cc.refreshConf.Headers))
  246. var err error
  247. for k, v := range cc.refreshConf.Headers {
  248. headers[k], err = ctx.ParseTemplate(v, cc.tokens)
  249. if err != nil {
  250. return fmt.Errorf("fail to parse the header for refresh token request %s: %v", k, err)
  251. }
  252. }
  253. rr, ee := httpx.Send(conf.Log, cc.client, "json", http.MethodPost, cc.refreshConf.Url, headers, true, cc.accessConf.Body)
  254. if ee != nil {
  255. return fmt.Errorf("fail to get refresh token: %v", ee)
  256. }
  257. nt, _, err := cc.parseResponse(ctx, rr, true, nil)
  258. if err != nil {
  259. return fmt.Errorf("Cannot parse refresh token response to json: %v", err)
  260. }
  261. for k, v := range nt[0] {
  262. if v != nil {
  263. cc.tokens[k] = v
  264. }
  265. }
  266. cc.tokenLastUpdateAt = time.Now()
  267. return nil
  268. } else if cc.accessConf != nil {
  269. return cc.auth(ctx)
  270. } else {
  271. return fmt.Errorf("no oAuth config")
  272. }
  273. }
  274. func (cc *ClientConf) parseHeaders(ctx api.StreamContext, data interface{}) (map[string]string, error) {
  275. headers := make(map[string]string)
  276. var err error
  277. if cc.config.HeadersMap != nil {
  278. for k, v := range cc.config.HeadersMap {
  279. headers[k], err = ctx.ParseTemplate(v, data)
  280. if err != nil {
  281. return nil, fmt.Errorf("fail to parse the header entry %s: %v", k, err)
  282. }
  283. }
  284. } else if cc.config.HeadersTemplate != "" {
  285. tstr, err := ctx.ParseTemplate(cc.config.HeadersTemplate, data)
  286. if err != nil {
  287. return nil, fmt.Errorf("fail to parse the header template %s: %v", cc.config.HeadersTemplate, err)
  288. }
  289. err = json.Unmarshal(cast.StringToBytes(tstr), &headers)
  290. if err != nil {
  291. return nil, fmt.Errorf("parsed header template is not json: %s", tstr)
  292. }
  293. }
  294. return headers, nil
  295. }
  296. // parse the response status. For rest sink, it will not return the body by default if not need to debug
  297. func (cc *ClientConf) parseResponse(ctx api.StreamContext, resp *http.Response, returnBody bool, omd5 *string) ([]map[string]interface{}, []byte, error) {
  298. if resp.StatusCode < 200 || resp.StatusCode > 299 {
  299. c, err := io.ReadAll(resp.Body)
  300. if err != nil {
  301. return nil, []byte("fail to read body"),
  302. fmt.Errorf("http return code error: %d", resp.StatusCode)
  303. }
  304. defer func(Body io.ReadCloser) {
  305. err := Body.Close()
  306. if err != nil {
  307. conf.Log.Errorf("fail to close the response body: %v", err)
  308. }
  309. }(resp.Body)
  310. return nil, c, fmt.Errorf("http return code error: %d", resp.StatusCode)
  311. } else if !returnBody { // For rest sink who only need to know if the request is successful
  312. return nil, nil, nil
  313. }
  314. c, err := io.ReadAll(resp.Body)
  315. if err != nil {
  316. return nil, []byte("fail to read body"), err
  317. }
  318. defer func(Body io.ReadCloser) {
  319. err := Body.Close()
  320. if err != nil {
  321. conf.Log.Errorf("fail to close the response body: %v", err)
  322. }
  323. }(resp.Body)
  324. if returnBody && cc.config.Incremental {
  325. nmd5 := getMD5Hash(c)
  326. if *omd5 == nmd5 {
  327. ctx.GetLogger().Debugf("Content has not changed since last fetch, so skip processing.")
  328. return nil, nil, nil
  329. } else {
  330. *omd5 = nmd5
  331. }
  332. }
  333. switch cc.config.ResponseType {
  334. case "code":
  335. if returnBody {
  336. m, e := decode(ctx, c)
  337. return m, c, e
  338. }
  339. return nil, nil, nil
  340. case "body":
  341. payloads, err := decode(ctx, c)
  342. if err != nil {
  343. return nil, c, err
  344. }
  345. for _, payload := range payloads {
  346. ro := &bodyResp{}
  347. err = cast.MapToStruct(payload, ro)
  348. if err != nil {
  349. return nil, c, fmt.Errorf("invalid body response: %v", err)
  350. }
  351. if ro.Code < 200 || ro.Code > 299 {
  352. return nil, c, fmt.Errorf("http status code is not 200: %v", ro.Code)
  353. }
  354. }
  355. if returnBody {
  356. return payloads, c, nil
  357. }
  358. return nil, nil, nil
  359. default:
  360. return nil, c, fmt.Errorf("unsupported response type: %s", cc.config.ResponseType)
  361. }
  362. }
  363. func getMD5Hash(text []byte) string {
  364. hash := md5.Sum(text)
  365. return hex.EncodeToString(hash[:])
  366. }
  367. // TODO remove this function after all the sources are migrated to use the new API
  368. func decode(ctx api.StreamContext, data []byte) ([]map[string]interface{}, error) {
  369. r, err := ctx.DecodeIntoList(data)
  370. if err == nil {
  371. return r, nil
  372. }
  373. var r1 interface{}
  374. err = json.Unmarshal(data, &r1)
  375. if err != nil {
  376. return nil, err
  377. }
  378. switch rt := r1.(type) {
  379. case map[string]interface{}:
  380. return []map[string]interface{}{rt}, nil
  381. case []map[string]interface{}:
  382. return rt, nil
  383. case []interface{}:
  384. r2 := make([]map[string]interface{}, len(rt))
  385. for i, m := range rt {
  386. if rm, ok := m.(map[string]interface{}); ok {
  387. r2[i] = rm
  388. } else {
  389. return nil, fmt.Errorf("only map[string]interface{} and []map[string]interface{} is supported")
  390. }
  391. }
  392. return r2, nil
  393. }
  394. return nil, fmt.Errorf("only map[string]interface{} and []map[string]interface{} is supported")
  395. }