http_util.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. package util
  2. import (
  3. "compress/gzip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "strings"
  12. "github.com/chrislusf/seaweedfs/weed/util/log"
  13. )
  14. var (
  15. client *http.Client
  16. Transport *http.Transport
  17. )
  18. func init() {
  19. Transport = &http.Transport{
  20. MaxIdleConnsPerHost: 1024,
  21. }
  22. client = &http.Client{
  23. Transport: Transport,
  24. }
  25. }
  26. func Post(url string, values url.Values) ([]byte, error) {
  27. r, err := client.PostForm(url, values)
  28. if err != nil {
  29. return nil, err
  30. }
  31. defer r.Body.Close()
  32. b, err := ioutil.ReadAll(r.Body)
  33. if r.StatusCode >= 400 {
  34. if err != nil {
  35. return nil, fmt.Errorf("%s: %d - %s", url, r.StatusCode, string(b))
  36. } else {
  37. return nil, fmt.Errorf("%s: %s", url, r.Status)
  38. }
  39. }
  40. if err != nil {
  41. return nil, err
  42. }
  43. return b, nil
  44. }
  45. // github.com/chrislusf/seaweedfs/unmaintained/repeated_vacuum/repeated_vacuum.go
  46. // may need increasing http.Client.Timeout
  47. func Get(url string) ([]byte, bool, error) {
  48. request, err := http.NewRequest("GET", url, nil)
  49. request.Header.Add("Accept-Encoding", "gzip")
  50. response, err := client.Do(request)
  51. if err != nil {
  52. return nil, true, err
  53. }
  54. defer response.Body.Close()
  55. var reader io.ReadCloser
  56. switch response.Header.Get("Content-Encoding") {
  57. case "gzip":
  58. reader, err = gzip.NewReader(response.Body)
  59. defer reader.Close()
  60. default:
  61. reader = response.Body
  62. }
  63. b, err := ioutil.ReadAll(reader)
  64. if response.StatusCode >= 400 {
  65. retryable := response.StatusCode >= 500
  66. return nil, retryable, fmt.Errorf("%s: %s", url, response.Status)
  67. }
  68. if err != nil {
  69. return nil, false, err
  70. }
  71. return b, false, nil
  72. }
  73. func Head(url string) (http.Header, error) {
  74. r, err := client.Head(url)
  75. if err != nil {
  76. return nil, err
  77. }
  78. defer CloseResponse(r)
  79. if r.StatusCode >= 400 {
  80. return nil, fmt.Errorf("%s: %s", url, r.Status)
  81. }
  82. return r.Header, nil
  83. }
  84. func Delete(url string, jwt string) error {
  85. req, err := http.NewRequest("DELETE", url, nil)
  86. if jwt != "" {
  87. req.Header.Set("Authorization", "BEARER "+string(jwt))
  88. }
  89. if err != nil {
  90. return err
  91. }
  92. resp, e := client.Do(req)
  93. if e != nil {
  94. return e
  95. }
  96. defer resp.Body.Close()
  97. body, err := ioutil.ReadAll(resp.Body)
  98. if err != nil {
  99. return err
  100. }
  101. switch resp.StatusCode {
  102. case http.StatusNotFound, http.StatusAccepted, http.StatusOK:
  103. return nil
  104. }
  105. m := make(map[string]interface{})
  106. if e := json.Unmarshal(body, &m); e == nil {
  107. if s, ok := m["error"].(string); ok {
  108. return errors.New(s)
  109. }
  110. }
  111. return errors.New(string(body))
  112. }
  113. func GetBufferStream(url string, values url.Values, allocatedBytes []byte, eachBuffer func([]byte)) error {
  114. r, err := client.PostForm(url, values)
  115. if err != nil {
  116. return err
  117. }
  118. defer CloseResponse(r)
  119. if r.StatusCode != 200 {
  120. return fmt.Errorf("%s: %s", url, r.Status)
  121. }
  122. for {
  123. n, err := r.Body.Read(allocatedBytes)
  124. if n > 0 {
  125. eachBuffer(allocatedBytes[:n])
  126. }
  127. if err != nil {
  128. if err == io.EOF {
  129. return nil
  130. }
  131. return err
  132. }
  133. }
  134. }
  135. func GetUrlStream(url string, values url.Values, readFn func(io.Reader) error) error {
  136. r, err := client.PostForm(url, values)
  137. if err != nil {
  138. return err
  139. }
  140. defer CloseResponse(r)
  141. if r.StatusCode != 200 {
  142. return fmt.Errorf("%s: %s", url, r.Status)
  143. }
  144. return readFn(r.Body)
  145. }
  146. func DownloadFile(fileUrl string) (filename string, header http.Header, resp *http.Response, e error) {
  147. response, err := client.Get(fileUrl)
  148. if err != nil {
  149. return "", nil, nil, err
  150. }
  151. header = response.Header
  152. contentDisposition := response.Header["Content-Disposition"]
  153. if len(contentDisposition) > 0 {
  154. idx := strings.Index(contentDisposition[0], "filename=")
  155. if idx != -1 {
  156. filename = contentDisposition[0][idx+len("filename="):]
  157. filename = strings.Trim(filename, "\"")
  158. }
  159. }
  160. resp = response
  161. return
  162. }
  163. func Do(req *http.Request) (resp *http.Response, err error) {
  164. return client.Do(req)
  165. }
  166. func NormalizeUrl(url string) string {
  167. if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
  168. return url
  169. }
  170. return "http://" + url
  171. }
  172. func ReadUrl(fileUrl string, cipherKey []byte, isContentCompressed bool, isFullChunk bool, offset int64, size int, buf []byte) (int64, error) {
  173. if cipherKey != nil {
  174. var n int
  175. _, err := readEncryptedUrl(fileUrl, cipherKey, isContentCompressed, isFullChunk, offset, size, func(data []byte) {
  176. n = copy(buf, data)
  177. })
  178. return int64(n), err
  179. }
  180. req, err := http.NewRequest("GET", fileUrl, nil)
  181. if err != nil {
  182. return 0, err
  183. }
  184. if !isFullChunk {
  185. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)-1))
  186. } else {
  187. req.Header.Set("Accept-Encoding", "gzip")
  188. }
  189. r, err := client.Do(req)
  190. if err != nil {
  191. return 0, err
  192. }
  193. defer r.Body.Close()
  194. if r.StatusCode >= 400 {
  195. return 0, fmt.Errorf("%s: %s", fileUrl, r.Status)
  196. }
  197. var reader io.ReadCloser
  198. contentEncoding := r.Header.Get("Content-Encoding")
  199. switch contentEncoding {
  200. case "gzip":
  201. reader, err = gzip.NewReader(r.Body)
  202. defer reader.Close()
  203. default:
  204. reader = r.Body
  205. }
  206. var (
  207. i, m int
  208. n int64
  209. )
  210. // refers to https://github.com/golang/go/blob/master/src/bytes/buffer.go#L199
  211. // commit id c170b14c2c1cfb2fd853a37add92a82fd6eb4318
  212. for {
  213. m, err = reader.Read(buf[i:])
  214. i += m
  215. n += int64(m)
  216. if err == io.EOF {
  217. return n, nil
  218. }
  219. if err != nil {
  220. return n, err
  221. }
  222. if n == int64(len(buf)) {
  223. break
  224. }
  225. }
  226. // drains the response body to avoid memory leak
  227. data, _ := ioutil.ReadAll(reader)
  228. if len(data) != 0 {
  229. log.Debugf("%s reader has remaining %d bytes", contentEncoding, len(data))
  230. }
  231. return n, err
  232. }
  233. func ReadUrlAsStream(fileUrl string, cipherKey []byte, isContentGzipped bool, isFullChunk bool, offset int64, size int, fn func(data []byte)) (retryable bool, err error) {
  234. if cipherKey != nil {
  235. return readEncryptedUrl(fileUrl, cipherKey, isContentGzipped, isFullChunk, offset, size, fn)
  236. }
  237. req, err := http.NewRequest("GET", fileUrl, nil)
  238. if err != nil {
  239. return false, err
  240. }
  241. if isFullChunk {
  242. req.Header.Add("Accept-Encoding", "gzip")
  243. } else {
  244. req.Header.Add("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+int64(size)-1))
  245. }
  246. r, err := client.Do(req)
  247. if err != nil {
  248. return true, err
  249. }
  250. defer CloseResponse(r)
  251. if r.StatusCode >= 400 {
  252. retryable = r.StatusCode >= 500
  253. return retryable, fmt.Errorf("%s: %s", fileUrl, r.Status)
  254. }
  255. var reader io.ReadCloser
  256. contentEncoding := r.Header.Get("Content-Encoding")
  257. switch contentEncoding {
  258. case "gzip":
  259. reader, err = gzip.NewReader(r.Body)
  260. defer reader.Close()
  261. default:
  262. reader = r.Body
  263. }
  264. var (
  265. m int
  266. )
  267. buf := make([]byte, 64*1024)
  268. for {
  269. m, err = reader.Read(buf)
  270. fn(buf[:m])
  271. if err == io.EOF {
  272. return false, nil
  273. }
  274. if err != nil {
  275. return false, err
  276. }
  277. }
  278. }
  279. func readEncryptedUrl(fileUrl string, cipherKey []byte, isContentCompressed bool, isFullChunk bool, offset int64, size int, fn func(data []byte)) (bool, error) {
  280. encryptedData, retryable, err := Get(fileUrl)
  281. if err != nil {
  282. return retryable, fmt.Errorf("fetch %s: %v", fileUrl, err)
  283. }
  284. decryptedData, err := Decrypt(encryptedData, CipherKey(cipherKey))
  285. if err != nil {
  286. return false, fmt.Errorf("decrypt %s: %v", fileUrl, err)
  287. }
  288. if isContentCompressed {
  289. decryptedData, err = DecompressData(decryptedData)
  290. if err != nil {
  291. log.Infof("unzip decrypt %s: %v", fileUrl, err)
  292. }
  293. }
  294. if len(decryptedData) < int(offset)+size {
  295. return false, fmt.Errorf("read decrypted %s size %d [%d, %d)", fileUrl, len(decryptedData), offset, int(offset)+size)
  296. }
  297. if isFullChunk {
  298. fn(decryptedData)
  299. } else {
  300. fn(decryptedData[int(offset) : int(offset)+size])
  301. }
  302. return false, nil
  303. }
  304. func ReadUrlAsReaderCloser(fileUrl string, rangeHeader string) (io.ReadCloser, error) {
  305. req, err := http.NewRequest("GET", fileUrl, nil)
  306. if err != nil {
  307. return nil, err
  308. }
  309. if rangeHeader != "" {
  310. req.Header.Add("Range", rangeHeader)
  311. } else {
  312. req.Header.Add("Accept-Encoding", "gzip")
  313. }
  314. r, err := client.Do(req)
  315. if err != nil {
  316. return nil, err
  317. }
  318. if r.StatusCode >= 400 {
  319. return nil, fmt.Errorf("%s: %s", fileUrl, r.Status)
  320. }
  321. var reader io.ReadCloser
  322. contentEncoding := r.Header.Get("Content-Encoding")
  323. switch contentEncoding {
  324. case "gzip":
  325. reader, err = gzip.NewReader(r.Body)
  326. defer reader.Close()
  327. default:
  328. reader = r.Body
  329. }
  330. return reader, nil
  331. }
  332. func CloseResponse(resp *http.Response) {
  333. io.Copy(ioutil.Discard, resp.Body)
  334. resp.Body.Close()
  335. }