client.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. package blademaster
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "crypto/tls"
  7. "encoding/hex"
  8. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net"
  12. "net/url"
  13. "os"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "time"
  19. xhttp "net/http"
  20. "go-common/library/conf/env"
  21. "go-common/library/log"
  22. "go-common/library/net/metadata"
  23. "go-common/library/net/netutil/breaker"
  24. "go-common/library/stat"
  25. xtime "go-common/library/time"
  26. "github.com/gogo/protobuf/proto"
  27. pkgerr "github.com/pkg/errors"
  28. )
  29. const (
  30. _minRead = 16 * 1024 // 16kb
  31. _appKey = "appkey"
  32. _appSecret = "appsecret"
  33. _ts = "ts"
  34. )
  35. var (
  36. _noKickUserAgent = "haoguanwei@bilibili.com "
  37. clientStats = stat.HTTPClient
  38. )
  39. func init() {
  40. n, err := os.Hostname()
  41. if err == nil {
  42. _noKickUserAgent = _noKickUserAgent + runtime.Version() + " " + n
  43. }
  44. }
  45. // App bilibili intranet authorization.
  46. type App struct {
  47. Key string
  48. Secret string
  49. }
  50. // ClientConfig is http client conf.
  51. type ClientConfig struct {
  52. *App
  53. Dial xtime.Duration
  54. Timeout xtime.Duration
  55. KeepAlive xtime.Duration
  56. Breaker *breaker.Config
  57. URL map[string]*ClientConfig
  58. Host map[string]*ClientConfig
  59. }
  60. // Client is http client.
  61. type Client struct {
  62. conf *ClientConfig
  63. client *xhttp.Client
  64. dialer *net.Dialer
  65. transport xhttp.RoundTripper
  66. urlConf map[string]*ClientConfig
  67. hostConf map[string]*ClientConfig
  68. mutex sync.RWMutex
  69. breaker *breaker.Group
  70. }
  71. // NewClient new a http client.
  72. func NewClient(c *ClientConfig) *Client {
  73. client := new(Client)
  74. client.conf = c
  75. client.dialer = &net.Dialer{
  76. Timeout: time.Duration(c.Dial),
  77. KeepAlive: time.Duration(c.KeepAlive),
  78. }
  79. originTransport := &xhttp.Transport{
  80. DialContext: client.dialer.DialContext,
  81. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  82. }
  83. // wraps RoundTripper for tracer
  84. client.transport = &TraceTransport{RoundTripper: originTransport}
  85. client.client = &xhttp.Client{
  86. Transport: client.transport,
  87. }
  88. client.urlConf = make(map[string]*ClientConfig)
  89. client.hostConf = make(map[string]*ClientConfig)
  90. client.breaker = breaker.NewGroup(c.Breaker)
  91. // check appkey
  92. if c.Key == "" || c.Secret == "" {
  93. panic("http client must config appkey and appsecret")
  94. }
  95. if c.Timeout <= 0 {
  96. panic("must config http timeout!!!")
  97. }
  98. for uri, cfg := range c.URL {
  99. client.urlConf[uri] = cfg
  100. }
  101. for host, cfg := range c.Host {
  102. client.hostConf[host] = cfg
  103. }
  104. return client
  105. }
  106. // SetTransport set client transport
  107. func (client *Client) SetTransport(t xhttp.RoundTripper) {
  108. client.transport = t
  109. client.client.Transport = t
  110. }
  111. // SetConfig set client config.
  112. func (client *Client) SetConfig(c *ClientConfig) {
  113. client.mutex.Lock()
  114. if c.App != nil {
  115. client.conf.App.Key = c.App.Key
  116. client.conf.App.Secret = c.App.Secret
  117. }
  118. if c.Timeout > 0 {
  119. client.conf.Timeout = c.Timeout
  120. }
  121. if c.KeepAlive > 0 {
  122. client.dialer.KeepAlive = time.Duration(c.KeepAlive)
  123. client.conf.KeepAlive = c.KeepAlive
  124. }
  125. if c.Dial > 0 {
  126. client.dialer.Timeout = time.Duration(c.Dial)
  127. client.conf.Timeout = c.Dial
  128. }
  129. if c.Breaker != nil {
  130. client.conf.Breaker = c.Breaker
  131. client.breaker.Reload(c.Breaker)
  132. }
  133. for uri, cfg := range c.URL {
  134. client.urlConf[uri] = cfg
  135. }
  136. for host, cfg := range c.Host {
  137. client.hostConf[host] = cfg
  138. }
  139. client.mutex.Unlock()
  140. }
  141. // NewRequest new http request with method, uri, ip, values and headers.
  142. // TODO(zhoujiahui): param realIP should be removed later.
  143. func (client *Client) NewRequest(method, uri, realIP string, params url.Values) (req *xhttp.Request, err error) {
  144. enc, err := client.sign(params)
  145. if err != nil {
  146. err = pkgerr.Wrapf(err, "uri:%s,params:%v", uri, params)
  147. return
  148. }
  149. ru := uri
  150. if enc != "" {
  151. ru = uri + "?" + enc
  152. }
  153. if method == xhttp.MethodGet {
  154. req, err = xhttp.NewRequest(xhttp.MethodGet, ru, nil)
  155. } else {
  156. req, err = xhttp.NewRequest(xhttp.MethodPost, uri, strings.NewReader(enc))
  157. }
  158. if err != nil {
  159. err = pkgerr.Wrapf(err, "method:%s,uri:%s", method, ru)
  160. return
  161. }
  162. const (
  163. _contentType = "Content-Type"
  164. _urlencoded = "application/x-www-form-urlencoded"
  165. _userAgent = "User-Agent"
  166. )
  167. if method == xhttp.MethodPost {
  168. req.Header.Set(_contentType, _urlencoded)
  169. }
  170. if realIP != "" {
  171. req.Header.Set(_httpHeaderRemoteIP, realIP)
  172. }
  173. req.Header.Set(_userAgent, _noKickUserAgent+" "+env.AppID)
  174. return
  175. }
  176. // Get issues a GET to the specified URL.
  177. func (client *Client) Get(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {
  178. req, err := client.NewRequest(xhttp.MethodGet, uri, ip, params)
  179. if err != nil {
  180. return
  181. }
  182. return client.Do(c, req, res)
  183. }
  184. // Post issues a Post to the specified URL.
  185. func (client *Client) Post(c context.Context, uri, ip string, params url.Values, res interface{}) (err error) {
  186. req, err := client.NewRequest(xhttp.MethodPost, uri, ip, params)
  187. if err != nil {
  188. return
  189. }
  190. return client.Do(c, req, res)
  191. }
  192. // RESTfulGet issues a RESTful GET to the specified URL.
  193. func (client *Client) RESTfulGet(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error) {
  194. req, err := client.NewRequest(xhttp.MethodGet, fmt.Sprintf(uri, v...), ip, params)
  195. if err != nil {
  196. return
  197. }
  198. return client.Do(c, req, res, uri)
  199. }
  200. // RESTfulPost issues a RESTful Post to the specified URL.
  201. func (client *Client) RESTfulPost(c context.Context, uri, ip string, params url.Values, res interface{}, v ...interface{}) (err error) {
  202. req, err := client.NewRequest(xhttp.MethodPost, fmt.Sprintf(uri, v...), ip, params)
  203. if err != nil {
  204. return
  205. }
  206. return client.Do(c, req, res, uri)
  207. }
  208. // Raw sends an HTTP request and returns bytes response
  209. func (client *Client) Raw(c context.Context, req *xhttp.Request, v ...string) (bs []byte, err error) {
  210. var (
  211. ok bool
  212. code string
  213. cancel func()
  214. resp *xhttp.Response
  215. config *ClientConfig
  216. timeout time.Duration
  217. uri = fmt.Sprintf("%s://%s%s", req.URL.Scheme, req.Host, req.URL.Path)
  218. )
  219. // NOTE fix prom & config uri key.
  220. if len(v) == 1 {
  221. uri = v[0]
  222. }
  223. // breaker
  224. brk := client.breaker.Get(uri)
  225. if err = brk.Allow(); err != nil {
  226. code = "breaker"
  227. clientStats.Incr(uri, code)
  228. return
  229. }
  230. defer client.onBreaker(brk, &err)
  231. // stat
  232. now := time.Now()
  233. defer func() {
  234. clientStats.Timing(uri, int64(time.Since(now)/time.Millisecond))
  235. if code != "" {
  236. clientStats.Incr(uri, code)
  237. }
  238. }()
  239. // get config
  240. // 1.url config 2.host config 3.default
  241. client.mutex.RLock()
  242. if config, ok = client.urlConf[uri]; !ok {
  243. if config, ok = client.hostConf[req.Host]; !ok {
  244. config = client.conf
  245. }
  246. }
  247. client.mutex.RUnlock()
  248. // timeout
  249. deliver := true
  250. timeout = time.Duration(config.Timeout)
  251. if deadline, ok := c.Deadline(); ok {
  252. if ctimeout := time.Until(deadline); ctimeout < timeout {
  253. // deliver small timeout
  254. timeout = ctimeout
  255. deliver = false
  256. }
  257. }
  258. if deliver {
  259. c, cancel = context.WithTimeout(c, timeout)
  260. defer cancel()
  261. }
  262. setTimeout(req, timeout)
  263. req = req.WithContext(c)
  264. setCaller(req)
  265. if color := metadata.String(c, metadata.Color); color != "" {
  266. setColor(req, color)
  267. }
  268. if resp, err = client.client.Do(req); err != nil {
  269. err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
  270. code = "failed"
  271. return
  272. }
  273. defer resp.Body.Close()
  274. if resp.StatusCode >= xhttp.StatusBadRequest {
  275. err = pkgerr.Errorf("incorrect http status:%d host:%s, url:%s", resp.StatusCode, req.URL.Host, realURL(req))
  276. code = strconv.Itoa(resp.StatusCode)
  277. return
  278. }
  279. if bs, err = readAll(resp.Body, _minRead); err != nil {
  280. err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
  281. return
  282. }
  283. return
  284. }
  285. // Do sends an HTTP request and returns an HTTP json response.
  286. func (client *Client) Do(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error) {
  287. var bs []byte
  288. if bs, err = client.Raw(c, req, v...); err != nil {
  289. return
  290. }
  291. if res != nil {
  292. if err = json.Unmarshal(bs, res); err != nil {
  293. err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
  294. }
  295. }
  296. return
  297. }
  298. // JSON sends an HTTP request and returns an HTTP json response.
  299. func (client *Client) JSON(c context.Context, req *xhttp.Request, res interface{}, v ...string) (err error) {
  300. var bs []byte
  301. if bs, err = client.Raw(c, req, v...); err != nil {
  302. return
  303. }
  304. if res != nil {
  305. if err = json.Unmarshal(bs, res); err != nil {
  306. err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
  307. }
  308. }
  309. return
  310. }
  311. // PB sends an HTTP request and returns an HTTP proto response.
  312. func (client *Client) PB(c context.Context, req *xhttp.Request, res proto.Message, v ...string) (err error) {
  313. var bs []byte
  314. if bs, err = client.Raw(c, req, v...); err != nil {
  315. return
  316. }
  317. if res != nil {
  318. if err = proto.Unmarshal(bs, res); err != nil {
  319. err = pkgerr.Wrapf(err, "host:%s, url:%s", req.URL.Host, realURL(req))
  320. }
  321. }
  322. return
  323. }
  324. func (client *Client) onBreaker(breaker breaker.Breaker, err *error) {
  325. if err != nil && *err != nil {
  326. breaker.MarkFailed()
  327. } else {
  328. breaker.MarkSuccess()
  329. }
  330. }
  331. // sign calc appkey and appsecret sign.
  332. func (client *Client) sign(params url.Values) (query string, err error) {
  333. client.mutex.RLock()
  334. key := client.conf.Key
  335. secret := client.conf.Secret
  336. client.mutex.RUnlock()
  337. if params == nil {
  338. params = url.Values{}
  339. }
  340. params.Set(_appKey, key)
  341. if params.Get(_appSecret) != "" {
  342. log.Warn("utils http get must not have parameter appSecret")
  343. }
  344. if params.Get(_ts) == "" {
  345. params.Set(_ts, strconv.FormatInt(time.Now().Unix(), 10))
  346. }
  347. tmp := params.Encode()
  348. if strings.IndexByte(tmp, '+') > -1 {
  349. tmp = strings.Replace(tmp, "+", "%20", -1)
  350. }
  351. var b bytes.Buffer
  352. b.WriteString(tmp)
  353. b.WriteString(secret)
  354. mh := md5.Sum(b.Bytes())
  355. // query
  356. var qb bytes.Buffer
  357. qb.WriteString(tmp)
  358. qb.WriteString("&sign=")
  359. qb.WriteString(hex.EncodeToString(mh[:]))
  360. query = qb.String()
  361. return
  362. }
  363. // realUrl return url with http://host/params.
  364. func realURL(req *xhttp.Request) string {
  365. if req.Method == xhttp.MethodGet {
  366. return req.URL.String()
  367. } else if req.Method == xhttp.MethodPost {
  368. ru := req.URL.Path
  369. if req.Body != nil {
  370. rd, ok := req.Body.(io.Reader)
  371. if ok {
  372. buf := bytes.NewBuffer([]byte{})
  373. buf.ReadFrom(rd)
  374. ru = ru + "?" + buf.String()
  375. }
  376. }
  377. return ru
  378. }
  379. return req.URL.Path
  380. }
  381. // readAll reads from r until an error or EOF and returns the data it read
  382. // from the internal buffer allocated with a specified capacity.
  383. func readAll(r io.Reader, capacity int64) (b []byte, err error) {
  384. buf := bytes.NewBuffer(make([]byte, 0, capacity))
  385. // If the buffer overflows, we will get bytes.ErrTooLarge.
  386. // Return that as an error. Any other panic remains.
  387. defer func() {
  388. e := recover()
  389. if e == nil {
  390. return
  391. }
  392. if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
  393. err = panicErr
  394. } else {
  395. panic(e)
  396. }
  397. }()
  398. _, err = buf.ReadFrom(r)
  399. return buf.Bytes(), err
  400. }