client.go 12 KB

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