client.go 12 KB

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