utils.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package oss
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "hash/crc64"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "os/exec"
  14. "runtime"
  15. "strconv"
  16. "strings"
  17. "time"
  18. )
  19. // userAgent gets user agent
  20. // It has the SDK version information, OS information and GO version
  21. func userAgent() string {
  22. sys := getSysInfo()
  23. return fmt.Sprintf("aliyun-sdk-go/%s (%s/%s/%s;%s)", Version, sys.name,
  24. sys.release, sys.machine, runtime.Version())
  25. }
  26. type sysInfo struct {
  27. name string // OS name such as windows/Linux
  28. release string // OS version 2.6.32-220.23.2.ali1089.el5.x86_64 etc
  29. machine string // CPU type amd64/x86_64
  30. }
  31. // getSysInfo gets system info
  32. // gets the OS information and CPU type
  33. func getSysInfo() sysInfo {
  34. name := runtime.GOOS
  35. release := "-"
  36. machine := runtime.GOARCH
  37. if out, err := exec.Command("uname", "-s").CombinedOutput(); err == nil {
  38. name = string(bytes.TrimSpace(out))
  39. }
  40. if out, err := exec.Command("uname", "-r").CombinedOutput(); err == nil {
  41. release = string(bytes.TrimSpace(out))
  42. }
  43. if out, err := exec.Command("uname", "-m").CombinedOutput(); err == nil {
  44. machine = string(bytes.TrimSpace(out))
  45. }
  46. return sysInfo{name: name, release: release, machine: machine}
  47. }
  48. // GetRangeConfig gets the download range from the options.
  49. func GetRangeConfig(options []Option) (*UnpackedRange, error) {
  50. rangeOpt, err := FindOption(options, HTTPHeaderRange, nil)
  51. if err != nil || rangeOpt == nil {
  52. return nil, err
  53. }
  54. return ParseRange(rangeOpt.(string))
  55. }
  56. // UnpackedRange
  57. type UnpackedRange struct {
  58. HasStart bool // Flag indicates if the start point is specified
  59. HasEnd bool // Flag indicates if the end point is specified
  60. Start int64 // Start point
  61. End int64 // End point
  62. }
  63. // InvalidRangeError returns invalid range error
  64. func InvalidRangeError(r string) error {
  65. return fmt.Errorf("InvalidRange %s", r)
  66. }
  67. func GetRangeString(unpackRange UnpackedRange) string {
  68. var strRange string
  69. if unpackRange.HasStart && unpackRange.HasEnd {
  70. strRange = fmt.Sprintf("%d-%d", unpackRange.Start, unpackRange.End)
  71. } else if unpackRange.HasStart {
  72. strRange = fmt.Sprintf("%d-", unpackRange.Start)
  73. } else if unpackRange.HasEnd {
  74. strRange = fmt.Sprintf("-%d", unpackRange.End)
  75. }
  76. return strRange
  77. }
  78. // ParseRange parse various styles of range such as bytes=M-N
  79. func ParseRange(normalizedRange string) (*UnpackedRange, error) {
  80. var err error
  81. HasStart := false
  82. HasEnd := false
  83. var Start int64
  84. var End int64
  85. // Bytes==M-N or ranges=M-N
  86. nrSlice := strings.Split(normalizedRange, "=")
  87. if len(nrSlice) != 2 || nrSlice[0] != "bytes" {
  88. return nil, InvalidRangeError(normalizedRange)
  89. }
  90. // Bytes=M-N,X-Y
  91. rSlice := strings.Split(nrSlice[1], ",")
  92. rStr := rSlice[0]
  93. if strings.HasSuffix(rStr, "-") { // M-
  94. startStr := rStr[:len(rStr)-1]
  95. Start, err = strconv.ParseInt(startStr, 10, 64)
  96. if err != nil {
  97. return nil, InvalidRangeError(normalizedRange)
  98. }
  99. HasStart = true
  100. } else if strings.HasPrefix(rStr, "-") { // -N
  101. len := rStr[1:]
  102. End, err = strconv.ParseInt(len, 10, 64)
  103. if err != nil {
  104. return nil, InvalidRangeError(normalizedRange)
  105. }
  106. if End == 0 { // -0
  107. return nil, InvalidRangeError(normalizedRange)
  108. }
  109. HasEnd = true
  110. } else { // M-N
  111. valSlice := strings.Split(rStr, "-")
  112. if len(valSlice) != 2 {
  113. return nil, InvalidRangeError(normalizedRange)
  114. }
  115. Start, err = strconv.ParseInt(valSlice[0], 10, 64)
  116. if err != nil {
  117. return nil, InvalidRangeError(normalizedRange)
  118. }
  119. HasStart = true
  120. End, err = strconv.ParseInt(valSlice[1], 10, 64)
  121. if err != nil {
  122. return nil, InvalidRangeError(normalizedRange)
  123. }
  124. HasEnd = true
  125. }
  126. return &UnpackedRange{HasStart, HasEnd, Start, End}, nil
  127. }
  128. // AdjustRange returns adjusted range, adjust the range according to the length of the file
  129. func AdjustRange(ur *UnpackedRange, size int64) (Start, End int64) {
  130. if ur == nil {
  131. return 0, size
  132. }
  133. if ur.HasStart && ur.HasEnd {
  134. Start = ur.Start
  135. End = ur.End + 1
  136. if ur.Start < 0 || ur.Start >= size || ur.End > size || ur.Start > ur.End {
  137. Start = 0
  138. End = size
  139. }
  140. } else if ur.HasStart {
  141. Start = ur.Start
  142. End = size
  143. if ur.Start < 0 || ur.Start >= size {
  144. Start = 0
  145. }
  146. } else if ur.HasEnd {
  147. Start = size - ur.End
  148. End = size
  149. if ur.End < 0 || ur.End > size {
  150. Start = 0
  151. End = size
  152. }
  153. }
  154. return
  155. }
  156. // GetNowSec returns Unix time, the number of seconds elapsed since January 1, 1970 UTC.
  157. // gets the current time in Unix time, in seconds.
  158. func GetNowSec() int64 {
  159. return time.Now().Unix()
  160. }
  161. // GetNowNanoSec returns t as a Unix time, the number of nanoseconds elapsed
  162. // since January 1, 1970 UTC. The result is undefined if the Unix time
  163. // in nanoseconds cannot be represented by an int64. Note that this
  164. // means the result of calling UnixNano on the zero Time is undefined.
  165. // gets the current time in Unix time, in nanoseconds.
  166. func GetNowNanoSec() int64 {
  167. return time.Now().UnixNano()
  168. }
  169. // GetNowGMT gets the current time in GMT format.
  170. func GetNowGMT() string {
  171. return time.Now().UTC().Format(http.TimeFormat)
  172. }
  173. // FileChunk is the file chunk definition
  174. type FileChunk struct {
  175. Number int // Chunk number
  176. Offset int64 // Chunk offset
  177. Size int64 // Chunk size.
  178. }
  179. // SplitFileByPartNum splits big file into parts by the num of parts.
  180. // Split the file with specified parts count, returns the split result when error is nil.
  181. func SplitFileByPartNum(fileName string, chunkNum int) ([]FileChunk, error) {
  182. if chunkNum <= 0 || chunkNum > 10000 {
  183. return nil, errors.New("chunkNum invalid")
  184. }
  185. file, err := os.Open(fileName)
  186. if err != nil {
  187. return nil, err
  188. }
  189. defer file.Close()
  190. stat, err := file.Stat()
  191. if err != nil {
  192. return nil, err
  193. }
  194. if int64(chunkNum) > stat.Size() {
  195. return nil, errors.New("oss: chunkNum invalid")
  196. }
  197. var chunks []FileChunk
  198. var chunk = FileChunk{}
  199. var chunkN = (int64)(chunkNum)
  200. for i := int64(0); i < chunkN; i++ {
  201. chunk.Number = int(i + 1)
  202. chunk.Offset = i * (stat.Size() / chunkN)
  203. if i == chunkN-1 {
  204. chunk.Size = stat.Size()/chunkN + stat.Size()%chunkN
  205. } else {
  206. chunk.Size = stat.Size() / chunkN
  207. }
  208. chunks = append(chunks, chunk)
  209. }
  210. return chunks, nil
  211. }
  212. // SplitFileByPartSize splits big file into parts by the size of parts.
  213. // Splits the file by the part size. Returns the FileChunk when error is nil.
  214. func SplitFileByPartSize(fileName string, chunkSize int64) ([]FileChunk, error) {
  215. if chunkSize <= 0 {
  216. return nil, errors.New("chunkSize invalid")
  217. }
  218. file, err := os.Open(fileName)
  219. if err != nil {
  220. return nil, err
  221. }
  222. defer file.Close()
  223. stat, err := file.Stat()
  224. if err != nil {
  225. return nil, err
  226. }
  227. var chunkN = stat.Size() / chunkSize
  228. if chunkN >= 10000 {
  229. return nil, errors.New("Too many parts, please increase part size")
  230. }
  231. var chunks []FileChunk
  232. var chunk = FileChunk{}
  233. for i := int64(0); i < chunkN; i++ {
  234. chunk.Number = int(i + 1)
  235. chunk.Offset = i * chunkSize
  236. chunk.Size = chunkSize
  237. chunks = append(chunks, chunk)
  238. }
  239. if stat.Size()%chunkSize > 0 {
  240. chunk.Number = len(chunks) + 1
  241. chunk.Offset = int64(len(chunks)) * chunkSize
  242. chunk.Size = stat.Size() % chunkSize
  243. chunks = append(chunks, chunk)
  244. }
  245. return chunks, nil
  246. }
  247. // GetPartEnd calculates the end position
  248. func GetPartEnd(begin int64, total int64, per int64) int64 {
  249. if begin+per > total {
  250. return total - 1
  251. }
  252. return begin + per - 1
  253. }
  254. // CrcTable returns the table constructed from the specified polynomial
  255. var CrcTable = func() *crc64.Table {
  256. return crc64.MakeTable(crc64.ECMA)
  257. }
  258. func GetReaderLen(reader io.Reader) (int64, error) {
  259. var contentLength int64
  260. var err error
  261. switch v := reader.(type) {
  262. case *bytes.Buffer:
  263. contentLength = int64(v.Len())
  264. case *bytes.Reader:
  265. contentLength = int64(v.Len())
  266. case *strings.Reader:
  267. contentLength = int64(v.Len())
  268. case *os.File:
  269. fInfo, fError := v.Stat()
  270. if fError != nil {
  271. err = fmt.Errorf("can't get reader content length,%s", fError.Error())
  272. } else {
  273. contentLength = fInfo.Size()
  274. }
  275. case *io.LimitedReader:
  276. contentLength = int64(v.N)
  277. case *LimitedReadCloser:
  278. contentLength = int64(v.N)
  279. default:
  280. err = fmt.Errorf("can't get reader content length,unkown reader type")
  281. }
  282. return contentLength, err
  283. }
  284. func LimitReadCloser(r io.Reader, n int64) io.Reader {
  285. var lc LimitedReadCloser
  286. lc.R = r
  287. lc.N = n
  288. return &lc
  289. }
  290. // LimitedRC support Close()
  291. type LimitedReadCloser struct {
  292. io.LimitedReader
  293. }
  294. func (lc *LimitedReadCloser) Close() error {
  295. if closer, ok := lc.R.(io.ReadCloser); ok {
  296. return closer.Close()
  297. }
  298. return nil
  299. }
  300. type DiscardReadCloser struct {
  301. RC io.ReadCloser
  302. Discard int
  303. }
  304. func (drc *DiscardReadCloser) Read(b []byte) (int, error) {
  305. n, err := drc.RC.Read(b)
  306. if drc.Discard == 0 || n <= 0 {
  307. return n, err
  308. }
  309. if n <= drc.Discard {
  310. drc.Discard -= n
  311. return 0, err
  312. }
  313. realLen := n - drc.Discard
  314. copy(b[0:realLen], b[drc.Discard:n])
  315. drc.Discard = 0
  316. return realLen, err
  317. }
  318. func (drc *DiscardReadCloser) Close() error {
  319. closer, ok := drc.RC.(io.ReadCloser)
  320. if ok {
  321. return closer.Close()
  322. }
  323. return nil
  324. }
  325. func XmlUnmarshal(body io.Reader, v interface{}) error {
  326. data, err := ioutil.ReadAll(body)
  327. if err != nil {
  328. return err
  329. }
  330. return xml.Unmarshal(data, v)
  331. }
  332. // decodeListUploadedPartsResult decodes
  333. func DecodeListUploadedPartsResult(result *ListUploadedPartsResult) error {
  334. var err error
  335. result.Key, err = url.QueryUnescape(result.Key)
  336. if err != nil {
  337. return err
  338. }
  339. return nil
  340. }