client.go 12 KB

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