utils.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package oss
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "hash/crc64"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. // userAgent gets user agent
  16. // It has the SDK version information, OS information and GO version
  17. func userAgent() string {
  18. sys := getSysInfo()
  19. return fmt.Sprintf("aliyun-sdk-go/%s (%s/%s/%s;%s)", Version, sys.name,
  20. sys.release, sys.machine, runtime.Version())
  21. }
  22. type sysInfo struct {
  23. name string // OS name such as windows/Linux
  24. release string // OS version 2.6.32-220.23.2.ali1089.el5.x86_64 etc
  25. machine string // CPU type amd64/x86_64
  26. }
  27. // getSysInfo gets system info
  28. // gets the OS information and CPU type
  29. func getSysInfo() sysInfo {
  30. name := runtime.GOOS
  31. release := "-"
  32. machine := runtime.GOARCH
  33. if out, err := exec.Command("uname", "-s").CombinedOutput(); err == nil {
  34. name = string(bytes.TrimSpace(out))
  35. }
  36. if out, err := exec.Command("uname", "-r").CombinedOutput(); err == nil {
  37. release = string(bytes.TrimSpace(out))
  38. }
  39. if out, err := exec.Command("uname", "-m").CombinedOutput(); err == nil {
  40. machine = string(bytes.TrimSpace(out))
  41. }
  42. return sysInfo{name: name, release: release, machine: machine}
  43. }
  44. // unpackedRange
  45. type unpackedRange struct {
  46. hasStart bool // Flag indicates if the start point is specified
  47. hasEnd bool // Flag indicates if the end point is specified
  48. start int64 // Start point
  49. end int64 // End point
  50. }
  51. // invalidRangeError returns invalid range error
  52. func invalidRangeError(r string) error {
  53. return fmt.Errorf("InvalidRange %s", r)
  54. }
  55. // parseRange parse various styles of range such as bytes=M-N
  56. func parseRange(normalizedRange string) (*unpackedRange, error) {
  57. var err error
  58. hasStart := false
  59. hasEnd := false
  60. var start int64
  61. var end int64
  62. // Bytes==M-N or ranges=M-N
  63. nrSlice := strings.Split(normalizedRange, "=")
  64. if len(nrSlice) != 2 || nrSlice[0] != "bytes" {
  65. return nil, invalidRangeError(normalizedRange)
  66. }
  67. // Bytes=M-N,X-Y
  68. rSlice := strings.Split(nrSlice[1], ",")
  69. rStr := rSlice[0]
  70. if strings.HasSuffix(rStr, "-") { // M-
  71. startStr := rStr[:len(rStr)-1]
  72. start, err = strconv.ParseInt(startStr, 10, 64)
  73. if err != nil {
  74. return nil, invalidRangeError(normalizedRange)
  75. }
  76. hasStart = true
  77. } else if strings.HasPrefix(rStr, "-") { // -N
  78. len := rStr[1:]
  79. end, err = strconv.ParseInt(len, 10, 64)
  80. if err != nil {
  81. return nil, invalidRangeError(normalizedRange)
  82. }
  83. if end == 0 { // -0
  84. return nil, invalidRangeError(normalizedRange)
  85. }
  86. hasEnd = true
  87. } else { // M-N
  88. valSlice := strings.Split(rStr, "-")
  89. if len(valSlice) != 2 {
  90. return nil, invalidRangeError(normalizedRange)
  91. }
  92. start, err = strconv.ParseInt(valSlice[0], 10, 64)
  93. if err != nil {
  94. return nil, invalidRangeError(normalizedRange)
  95. }
  96. hasStart = true
  97. end, err = strconv.ParseInt(valSlice[1], 10, 64)
  98. if err != nil {
  99. return nil, invalidRangeError(normalizedRange)
  100. }
  101. hasEnd = true
  102. }
  103. return &unpackedRange{hasStart, hasEnd, start, end}, nil
  104. }
  105. // adjustRange returns adjusted range, adjust the range according to the length of the file
  106. func adjustRange(ur *unpackedRange, size int64) (start, end int64) {
  107. if ur == nil {
  108. return 0, size
  109. }
  110. if ur.hasStart && ur.hasEnd {
  111. start = ur.start
  112. end = ur.end + 1
  113. if ur.start < 0 || ur.start >= size || ur.end > size || ur.start > ur.end {
  114. start = 0
  115. end = size
  116. }
  117. } else if ur.hasStart {
  118. start = ur.start
  119. end = size
  120. if ur.start < 0 || ur.start >= size {
  121. start = 0
  122. }
  123. } else if ur.hasEnd {
  124. start = size - ur.end
  125. end = size
  126. if ur.end < 0 || ur.end > size {
  127. start = 0
  128. end = size
  129. }
  130. }
  131. return
  132. }
  133. // GetNowSec returns Unix time, the number of seconds elapsed since January 1, 1970 UTC.
  134. // gets the current time in Unix time, in seconds.
  135. func GetNowSec() int64 {
  136. return time.Now().Unix()
  137. }
  138. // GetNowNanoSec returns t as a Unix time, the number of nanoseconds elapsed
  139. // since January 1, 1970 UTC. The result is undefined if the Unix time
  140. // in nanoseconds cannot be represented by an int64. Note that this
  141. // means the result of calling UnixNano on the zero Time is undefined.
  142. // gets the current time in Unix time, in nanoseconds.
  143. func GetNowNanoSec() int64 {
  144. return time.Now().UnixNano()
  145. }
  146. // GetNowGMT gets the current time in GMT format.
  147. func GetNowGMT() string {
  148. return time.Now().UTC().Format(http.TimeFormat)
  149. }
  150. // FileChunk is the file chunk definition
  151. type FileChunk struct {
  152. Number int // Chunk number
  153. Offset int64 // Chunk offset
  154. Size int64 // Chunk size.
  155. }
  156. // SplitFileByPartNum splits big file into parts by the num of parts.
  157. // Split the file with specified parts count, returns the split result when error is nil.
  158. func SplitFileByPartNum(fileName string, chunkNum int) ([]FileChunk, error) {
  159. if chunkNum <= 0 || chunkNum > 10000 {
  160. return nil, errors.New("chunkNum invalid")
  161. }
  162. file, err := os.Open(fileName)
  163. if err != nil {
  164. return nil, err
  165. }
  166. defer file.Close()
  167. stat, err := file.Stat()
  168. if err != nil {
  169. return nil, err
  170. }
  171. if int64(chunkNum) > stat.Size() {
  172. return nil, errors.New("oss: chunkNum invalid")
  173. }
  174. var chunks []FileChunk
  175. var chunk = FileChunk{}
  176. var chunkN = (int64)(chunkNum)
  177. for i := int64(0); i < chunkN; i++ {
  178. chunk.Number = int(i + 1)
  179. chunk.Offset = i * (stat.Size() / chunkN)
  180. if i == chunkN-1 {
  181. chunk.Size = stat.Size()/chunkN + stat.Size()%chunkN
  182. } else {
  183. chunk.Size = stat.Size() / chunkN
  184. }
  185. chunks = append(chunks, chunk)
  186. }
  187. return chunks, nil
  188. }
  189. // SplitFileByPartSize splits big file into parts by the size of parts.
  190. // Splits the file by the part size. Returns the FileChunk when error is nil.
  191. func SplitFileByPartSize(fileName string, chunkSize int64) ([]FileChunk, error) {
  192. if chunkSize <= 0 {
  193. return nil, errors.New("chunkSize invalid")
  194. }
  195. file, err := os.Open(fileName)
  196. if err != nil {
  197. return nil, err
  198. }
  199. defer file.Close()
  200. stat, err := file.Stat()
  201. if err != nil {
  202. return nil, err
  203. }
  204. var chunkN = stat.Size() / chunkSize
  205. if chunkN >= 10000 {
  206. return nil, errors.New("Too many parts, please increase part size")
  207. }
  208. var chunks []FileChunk
  209. var chunk = FileChunk{}
  210. for i := int64(0); i < chunkN; i++ {
  211. chunk.Number = int(i + 1)
  212. chunk.Offset = i * chunkSize
  213. chunk.Size = chunkSize
  214. chunks = append(chunks, chunk)
  215. }
  216. if stat.Size()%chunkSize > 0 {
  217. chunk.Number = len(chunks) + 1
  218. chunk.Offset = int64(len(chunks)) * chunkSize
  219. chunk.Size = stat.Size() % chunkSize
  220. chunks = append(chunks, chunk)
  221. }
  222. return chunks, nil
  223. }
  224. // GetPartEnd calculates the end position
  225. func GetPartEnd(begin int64, total int64, per int64) int64 {
  226. if begin+per > total {
  227. return total - 1
  228. }
  229. return begin + per - 1
  230. }
  231. // crcTable returns the table constructed from the specified polynomial
  232. var crcTable = func() *crc64.Table {
  233. return crc64.MakeTable(crc64.ECMA)
  234. }