crc_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. package oss
  2. import (
  3. "crypto/md5"
  4. "encoding/base64"
  5. "hash/crc64"
  6. "io"
  7. "io/ioutil"
  8. "math/rand"
  9. "os"
  10. "strings"
  11. . "gopkg.in/check.v1"
  12. )
  13. type OssCrcSuite struct {
  14. client *Client
  15. bucket *Bucket
  16. }
  17. var _ = Suite(&OssCrcSuite{})
  18. // SetUpSuite runs once when the suite starts running
  19. func (s *OssCrcSuite) SetUpSuite(c *C) {
  20. client, err := New(endpoint, accessID, accessKey)
  21. c.Assert(err, IsNil)
  22. s.client = client
  23. s.client.CreateBucket(bucketName)
  24. bucket, err := s.client.Bucket(bucketName)
  25. c.Assert(err, IsNil)
  26. s.bucket = bucket
  27. testLogger.Println("test crc started")
  28. }
  29. // TearDownSuite runs before each test or benchmark starts running
  30. func (s *OssCrcSuite) TearDownSuite(c *C) {
  31. // Delete part
  32. keyMarker := KeyMarker("")
  33. uploadIDMarker := UploadIDMarker("")
  34. for {
  35. lmur, err := s.bucket.ListMultipartUploads(keyMarker, uploadIDMarker)
  36. c.Assert(err, IsNil)
  37. for _, upload := range lmur.Uploads {
  38. var imur = InitiateMultipartUploadResult{Bucket: s.bucket.BucketName,
  39. Key: upload.Key, UploadID: upload.UploadID}
  40. err = s.bucket.AbortMultipartUpload(imur)
  41. c.Assert(err, IsNil)
  42. }
  43. keyMarker = KeyMarker(lmur.NextKeyMarker)
  44. uploadIDMarker = UploadIDMarker(lmur.NextUploadIDMarker)
  45. if !lmur.IsTruncated {
  46. break
  47. }
  48. }
  49. // Delete objects
  50. marker := Marker("")
  51. for {
  52. lor, err := s.bucket.ListObjects(marker)
  53. c.Assert(err, IsNil)
  54. for _, object := range lor.Objects {
  55. err = s.bucket.DeleteObject(object.Key)
  56. c.Assert(err, IsNil)
  57. }
  58. marker = Marker(lor.NextMarker)
  59. if !lor.IsTruncated {
  60. break
  61. }
  62. }
  63. // Delete bucket
  64. err := s.client.DeleteBucket(s.bucket.BucketName)
  65. c.Assert(err, IsNil)
  66. testLogger.Println("test crc completed")
  67. }
  68. // SetUpTest runs after each test or benchmark runs
  69. func (s *OssCrcSuite) SetUpTest(c *C) {
  70. err := removeTempFiles("../oss", ".jpg")
  71. c.Assert(err, IsNil)
  72. }
  73. // TearDownTest runs once after all tests or benchmarks have finished running
  74. func (s *OssCrcSuite) TearDownTest(c *C) {
  75. err := removeTempFiles("../oss", ".jpg")
  76. c.Assert(err, IsNil)
  77. }
  78. // TestCRCGolden tests OSS's CRC64
  79. func (s *OssCrcSuite) TestCRCGolden(c *C) {
  80. type crcTest struct {
  81. out uint64
  82. in string
  83. }
  84. var crcGolden = []crcTest{
  85. {0x0, ""},
  86. {0x3420000000000000, "a"},
  87. {0x36c4200000000000, "ab"},
  88. {0x3776c42000000000, "abc"},
  89. {0x336776c420000000, "abcd"},
  90. {0x32d36776c4200000, "abcde"},
  91. {0x3002d36776c42000, "abcdef"},
  92. {0x31b002d36776c420, "abcdefg"},
  93. {0xe21b002d36776c4, "abcdefgh"},
  94. {0x8b6e21b002d36776, "abcdefghi"},
  95. {0x7f5b6e21b002d367, "abcdefghij"},
  96. {0x8ec0e7c835bf9cdf, "Discard medicine more than two years old."},
  97. {0xc7db1759e2be5ab4, "He who has a shady past knows that nice guys finish last."},
  98. {0xfbf9d9603a6fa020, "I wouldn't marry him with a ten foot pole."},
  99. {0xeafc4211a6daa0ef, "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"},
  100. {0x3e05b21c7a4dc4da, "The days of the digital watch are numbered. -Tom Stoppard"},
  101. {0x5255866ad6ef28a6, "Nepal premier won't resign."},
  102. {0x8a79895be1e9c361, "For every action there is an equal and opposite government program."},
  103. {0x8878963a649d4916, "His money is twice tainted: 'taint yours and 'taint mine."},
  104. {0xa7b9d53ea87eb82f, "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"},
  105. {0xdb6805c0966a2f9c, "It's a tiny change to the code and not completely disgusting. - Bob Manchek"},
  106. {0xf3553c65dacdadd2, "size: a.out: bad magic"},
  107. {0x9d5e034087a676b9, "The major problem is with sendmail. -Mark Horton"},
  108. {0xa6db2d7f8da96417, "Give me a rock, paper and scissors and I will move the world. CCFestoon"},
  109. {0x325e00cd2fe819f9, "If the enemy is within range, then so are you."},
  110. {0x88c6600ce58ae4c6, "It's well we cannot hear the screams/That we create in others' dreams."},
  111. {0x28c4a3f3b769e078, "You remind me of a TV show, but that's all right: I watch it anyway."},
  112. {0xa698a34c9d9f1dca, "C is as portable as Stonehedge!!"},
  113. {0xf6c1e2a8c26c5cfc, "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"},
  114. {0xd402559dfe9b70c, "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"},
  115. {0xdb6efff26aa94946, "How can you write a big system without C++? -Paul Glick"},
  116. }
  117. var tab = crc64.MakeTable(crc64.ISO)
  118. for i := 0; i < len(crcGolden); i++ {
  119. golden := crcGolden[i]
  120. crc := NewCRC(tab, 0)
  121. io.WriteString(crc, golden.in)
  122. sum := crc.Sum64()
  123. c.Assert(sum, Equals, golden.out)
  124. }
  125. }
  126. // testCRC64Combine tests CRC64 on vector[0..pos] which should have CRC64 crc.
  127. // Also test CRC64Combine on vector[] split in two.
  128. func testCRC64Combine(c *C, str string, pos int, crc uint64) {
  129. tabECMA := crc64.MakeTable(crc64.ECMA)
  130. // Test CRC64
  131. hash := crc64.New(tabECMA)
  132. io.WriteString(hash, str)
  133. crc1 := hash.Sum64()
  134. c.Assert(crc1, Equals, crc)
  135. // Test CRC64 combine
  136. hash = crc64.New(tabECMA)
  137. io.WriteString(hash, str[0:pos])
  138. crc1 = hash.Sum64()
  139. hash = crc64.New(tabECMA)
  140. io.WriteString(hash, str[pos:len(str)])
  141. crc2 := hash.Sum64()
  142. crc1 = CRC64Combine(crc1, crc2, uint64(len(str)-pos))
  143. c.Assert(crc1, Equals, crc)
  144. }
  145. // TestCRCCombine tests CRC64Combine
  146. func (s *OssCrcSuite) TestCRCCombine(c *C) {
  147. str := "123456789"
  148. testCRC64Combine(c, str, (len(str)+1)>>1, 0x995DC9BBDF1939FA)
  149. str = "This is a test of the emergency broadcast system."
  150. testCRC64Combine(c, str, (len(str)+1)>>1, 0x27DB187FC15BBC72)
  151. }
  152. // TestCRCRepeatedCombine tests CRC64Combine
  153. func (s *OssCrcSuite) TestCRCRepeatedCombine(c *C) {
  154. tab := crc64.MakeTable(crc64.ECMA)
  155. str := "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"
  156. for i := 0; i <= len(str); i++ {
  157. hash := crc64.New(tab)
  158. io.WriteString(hash, string(str[0:i]))
  159. prev := hash.Sum64()
  160. hash = crc64.New(tab)
  161. io.WriteString(hash, string(str[i:len(str)]))
  162. post := hash.Sum64()
  163. crc := CRC64Combine(prev, post, uint64(len(str)-i))
  164. testLogger.Println("TestCRCRepeatedCombine:", prev, post, crc, i, len(str))
  165. c.Assert(crc == 0x7AD25FAFA1710407, Equals, true)
  166. }
  167. }
  168. // TestCRCRandomCombine tests CRC64Combine
  169. func (s *OssCrcSuite) TestCRCRandomCombine(c *C) {
  170. tab := crc64.MakeTable(crc64.ECMA)
  171. fileName := "../sample/BingWallpaper-2015-11-07.jpg"
  172. body, err := ioutil.ReadFile(fileName)
  173. c.Assert(err, IsNil)
  174. for i := 0; i < 10; i++ {
  175. fileParts, err := SplitFileByPartNum(fileName, 1+rand.Intn(9999))
  176. c.Assert(err, IsNil)
  177. var crc uint64
  178. for _, part := range fileParts {
  179. calc := NewCRC(tab, 0)
  180. calc.Write(body[part.Offset : part.Offset+part.Size])
  181. crc = CRC64Combine(crc, calc.Sum64(), (uint64)(part.Size))
  182. }
  183. testLogger.Println("TestCRCRandomCombine:", crc, i, fileParts)
  184. c.Assert(crc == 0x2B612D24FFF64222, Equals, true)
  185. }
  186. }
  187. // TestEnableCRCAndMD5 tests MD5 and CRC check
  188. func (s *OssCrcSuite) TestEnableCRCAndMD5(c *C) {
  189. objectName := objectNamePrefix + randStr(8)
  190. fileName := "../sample/BingWallpaper-2015-11-07.jpg"
  191. newFileName := "BingWallpaper-2015-11-07-2.jpg"
  192. objectValue := "空山新雨后,天气晚来秋。明月松间照,清泉石上流。竹喧归浣女,莲动下渔舟。随意春芳歇,王孙自可留。"
  193. client, err := New(endpoint, accessID, accessKey, EnableCRC(true), EnableMD5(true), MD5ThresholdCalcInMemory(200*1024))
  194. c.Assert(err, IsNil)
  195. bucket, err := client.Bucket(bucketName)
  196. c.Assert(err, IsNil)
  197. // PutObject
  198. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  199. c.Assert(err, IsNil)
  200. // GetObject
  201. body, err := bucket.GetObject(objectName)
  202. c.Assert(err, IsNil)
  203. _, err = ioutil.ReadAll(body)
  204. c.Assert(err, IsNil)
  205. body.Close()
  206. // GetObjectWithCRC
  207. getResult, err := bucket.DoGetObject(&GetObjectRequest{objectName}, nil)
  208. c.Assert(err, IsNil)
  209. str, err := readBody(getResult.Response.Body)
  210. c.Assert(err, IsNil)
  211. c.Assert(str, Equals, objectValue)
  212. c.Assert(getResult.ClientCRC.Sum64(), Equals, getResult.ServerCRC)
  213. // PutObjectFromFile
  214. err = bucket.PutObjectFromFile(objectName, fileName)
  215. c.Assert(err, IsNil)
  216. // GetObjectToFile
  217. err = bucket.GetObjectToFile(objectName, newFileName)
  218. c.Assert(err, IsNil)
  219. eq, err := compareFiles(fileName, newFileName)
  220. c.Assert(err, IsNil)
  221. c.Assert(eq, Equals, true)
  222. // DeleteObject
  223. err = bucket.DeleteObject(objectName)
  224. c.Assert(err, IsNil)
  225. // AppendObject
  226. var nextPos int64
  227. nextPos, err = bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  228. c.Assert(err, IsNil)
  229. nextPos, err = bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  230. c.Assert(err, IsNil)
  231. err = bucket.DeleteObject(objectName)
  232. c.Assert(err, IsNil)
  233. request := &AppendObjectRequest{
  234. ObjectKey: objectName,
  235. Reader: strings.NewReader(objectValue),
  236. Position: 0,
  237. }
  238. appendResult, err := bucket.DoAppendObject(request, []Option{InitCRC(0)})
  239. c.Assert(err, IsNil)
  240. request.Position = appendResult.NextPosition
  241. appendResult, err = bucket.DoAppendObject(request, []Option{InitCRC(appendResult.CRC)})
  242. c.Assert(err, IsNil)
  243. err = s.bucket.DeleteObject(objectName)
  244. c.Assert(err, IsNil)
  245. // MultipartUpload
  246. chunks, err := SplitFileByPartSize(fileName, 100*1024)
  247. imurUpload, err := bucket.InitiateMultipartUpload(objectName)
  248. c.Assert(err, IsNil)
  249. var partsUpload []UploadPart
  250. for _, chunk := range chunks {
  251. part, err := bucket.UploadPartFromFile(imurUpload, fileName, chunk.Offset, chunk.Size, (int)(chunk.Number))
  252. c.Assert(err, IsNil)
  253. partsUpload = append(partsUpload, part)
  254. }
  255. _, err = bucket.CompleteMultipartUpload(imurUpload, partsUpload)
  256. c.Assert(err, IsNil)
  257. // Check MultipartUpload
  258. err = bucket.GetObjectToFile(objectName, newFileName)
  259. c.Assert(err, IsNil)
  260. eq, err = compareFiles(fileName, newFileName)
  261. c.Assert(err, IsNil)
  262. c.Assert(eq, Equals, true)
  263. // DeleteObjects
  264. _, err = bucket.DeleteObjects([]string{objectName})
  265. c.Assert(err, IsNil)
  266. }
  267. // TestDisableCRCAndMD5 disables MD5 and CRC
  268. func (s *OssCrcSuite) TestDisableCRCAndMD5(c *C) {
  269. objectName := objectNamePrefix + randStr(8)
  270. fileName := "../sample/BingWallpaper-2015-11-07.jpg"
  271. newFileName := "BingWallpaper-2015-11-07-3.jpg"
  272. objectValue := "中岁颇好道,晚家南山陲。兴来每独往,胜事空自知。行到水穷处,坐看云起时。偶然值林叟,谈笑无还期。"
  273. client, err := New(endpoint, accessID, accessKey, EnableCRC(false), EnableMD5(false))
  274. c.Assert(err, IsNil)
  275. bucket, err := client.Bucket(bucketName)
  276. c.Assert(err, IsNil)
  277. // PutObject
  278. err = bucket.PutObject(objectName, strings.NewReader(objectValue))
  279. c.Assert(err, IsNil)
  280. // GetObject
  281. body, err := bucket.GetObject(objectName)
  282. c.Assert(err, IsNil)
  283. _, err = ioutil.ReadAll(body)
  284. c.Assert(err, IsNil)
  285. body.Close()
  286. // GetObjectWithCRC
  287. getResult, err := bucket.DoGetObject(&GetObjectRequest{objectName}, nil)
  288. c.Assert(err, IsNil)
  289. str, err := readBody(getResult.Response.Body)
  290. c.Assert(err, IsNil)
  291. c.Assert(str, Equals, objectValue)
  292. // PutObjectFromFile
  293. err = bucket.PutObjectFromFile(objectName, fileName)
  294. c.Assert(err, IsNil)
  295. // GetObjectToFile
  296. err = bucket.GetObjectToFile(objectName, newFileName)
  297. c.Assert(err, IsNil)
  298. eq, err := compareFiles(fileName, newFileName)
  299. c.Assert(err, IsNil)
  300. c.Assert(eq, Equals, true)
  301. // DeleteObject
  302. err = bucket.DeleteObject(objectName)
  303. c.Assert(err, IsNil)
  304. // AppendObject
  305. var nextPos int64
  306. nextPos, err = bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  307. c.Assert(err, IsNil)
  308. nextPos, err = bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  309. c.Assert(err, IsNil)
  310. err = bucket.DeleteObject(objectName)
  311. c.Assert(err, IsNil)
  312. request := &AppendObjectRequest{
  313. ObjectKey: objectName,
  314. Reader: strings.NewReader(objectValue),
  315. Position: 0,
  316. }
  317. appendResult, err := bucket.DoAppendObject(request, []Option{InitCRC(0)})
  318. c.Assert(err, IsNil)
  319. request.Position = appendResult.NextPosition
  320. appendResult, err = bucket.DoAppendObject(request, []Option{InitCRC(appendResult.CRC)})
  321. c.Assert(err, IsNil)
  322. err = s.bucket.DeleteObject(objectName)
  323. c.Assert(err, IsNil)
  324. // MultipartUpload
  325. chunks, err := SplitFileByPartSize(fileName, 100*1024)
  326. imurUpload, err := bucket.InitiateMultipartUpload(objectName)
  327. c.Assert(err, IsNil)
  328. var partsUpload []UploadPart
  329. for _, chunk := range chunks {
  330. part, err := bucket.UploadPartFromFile(imurUpload, fileName, chunk.Offset, chunk.Size, (int)(chunk.Number))
  331. c.Assert(err, IsNil)
  332. partsUpload = append(partsUpload, part)
  333. }
  334. _, err = bucket.CompleteMultipartUpload(imurUpload, partsUpload)
  335. c.Assert(err, IsNil)
  336. // Check MultipartUpload
  337. err = bucket.GetObjectToFile(objectName, newFileName)
  338. c.Assert(err, IsNil)
  339. eq, err = compareFiles(fileName, newFileName)
  340. c.Assert(err, IsNil)
  341. c.Assert(eq, Equals, true)
  342. // DeleteObjects
  343. _, err = bucket.DeleteObjects([]string{objectName})
  344. c.Assert(err, IsNil)
  345. }
  346. // TestSpecifyContentMD5 specifies MD5
  347. func (s *OssCrcSuite) TestSpecifyContentMD5(c *C) {
  348. objectName := objectNamePrefix + randStr(8)
  349. fileName := "../sample/BingWallpaper-2015-11-07.jpg"
  350. objectValue := "积雨空林烟火迟,蒸藜炊黍饷东菑。漠漠水田飞白鹭,阴阴夏木啭黄鹂。山中习静观朝槿,松下清斋折露葵。野老与人争席罢,海鸥何事更相疑。"
  351. mh := md5.Sum([]byte(objectValue))
  352. md5B64 := base64.StdEncoding.EncodeToString(mh[:])
  353. // PutObject
  354. err := s.bucket.PutObject(objectName, strings.NewReader(objectValue), ContentMD5(md5B64))
  355. c.Assert(err, IsNil)
  356. // PutObjectFromFile
  357. file, err := os.Open(fileName)
  358. md5 := md5.New()
  359. io.Copy(md5, file)
  360. mdHex := base64.StdEncoding.EncodeToString(md5.Sum(nil)[:])
  361. err = s.bucket.PutObjectFromFile(objectName, fileName, ContentMD5(mdHex))
  362. c.Assert(err, IsNil)
  363. err = s.bucket.DeleteObject(objectName)
  364. c.Assert(err, IsNil)
  365. // AppendObject
  366. var nextPos int64
  367. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  368. c.Assert(err, IsNil)
  369. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos)
  370. c.Assert(err, IsNil)
  371. err = s.bucket.DeleteObject(objectName)
  372. c.Assert(err, IsNil)
  373. request := &AppendObjectRequest{
  374. ObjectKey: objectName,
  375. Reader: strings.NewReader(objectValue),
  376. Position: 0,
  377. }
  378. appendResult, err := s.bucket.DoAppendObject(request, []Option{InitCRC(0)})
  379. c.Assert(err, IsNil)
  380. request.Position = appendResult.NextPosition
  381. appendResult, err = s.bucket.DoAppendObject(request, []Option{InitCRC(appendResult.CRC)})
  382. c.Assert(err, IsNil)
  383. err = s.bucket.DeleteObject(objectName)
  384. c.Assert(err, IsNil)
  385. // MultipartUpload
  386. imurUpload, err := s.bucket.InitiateMultipartUpload(objectName)
  387. c.Assert(err, IsNil)
  388. var partsUpload []UploadPart
  389. part, err := s.bucket.UploadPart(imurUpload, strings.NewReader(objectValue), (int64)(len([]byte(objectValue))), 1)
  390. c.Assert(err, IsNil)
  391. partsUpload = append(partsUpload, part)
  392. _, err = s.bucket.CompleteMultipartUpload(imurUpload, partsUpload)
  393. c.Assert(err, IsNil)
  394. // DeleteObject
  395. err = s.bucket.DeleteObject(objectName)
  396. c.Assert(err, IsNil)
  397. }
  398. // TestAppendObjectNegative
  399. func (s *OssCrcSuite) TestAppendObjectNegative(c *C) {
  400. objectName := objectNamePrefix + randStr(8)
  401. objectValue := "空山不见人,但闻人语响。返影入深林,复照青苔上。"
  402. nextPos, err := s.bucket.AppendObject(objectName, strings.NewReader(objectValue), 0, InitCRC(0))
  403. c.Assert(err, IsNil)
  404. nextPos, err = s.bucket.AppendObject(objectName, strings.NewReader(objectValue), nextPos, InitCRC(0))
  405. c.Assert(err, NotNil)
  406. c.Assert(strings.HasPrefix(err.Error(), "oss: the crc"), Equals, true)
  407. }