You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 lines
5.3 KiB

6 years ago
12 years ago
12 years ago
5 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
9 years ago
7 years ago
12 years ago
  1. package needle
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/seaweedfs/seaweedfs/weed/images"
  13. . "github.com/seaweedfs/seaweedfs/weed/storage/types"
  14. )
  15. const (
  16. NeedleChecksumSize = 4
  17. PairNamePrefix = "Seaweed-"
  18. )
  19. /*
  20. * A Needle means a uploaded and stored file.
  21. * Needle file size is limited to 4GB for now.
  22. */
  23. type Needle struct {
  24. Cookie Cookie `comment:"random number to mitigate brute force lookups"`
  25. Id NeedleId `comment:"needle id"`
  26. Size Size `comment:"sum of DataSize,Data,NameSize,Name,MimeSize,Mime"`
  27. DataSize uint32 `comment:"Data size"` //version2
  28. Data []byte `comment:"The actual file data"`
  29. Flags byte `comment:"boolean flags"` //version2
  30. NameSize uint8 //version2
  31. Name []byte `comment:"maximum 255 characters"` //version2
  32. MimeSize uint8 //version2
  33. Mime []byte `comment:"maximum 255 characters"` //version2
  34. PairsSize uint16 //version2
  35. Pairs []byte `comment:"additional name value pairs, json format, maximum 64kB"`
  36. LastModified uint64 //only store LastModifiedBytesLength bytes, which is 5 bytes to disk
  37. Ttl *TTL
  38. Checksum CRC `comment:"CRC32 to check integrity"`
  39. AppendAtNs uint64 `comment:"append timestamp in nano seconds"` //version3
  40. Padding []byte `comment:"Aligned to 8 bytes"`
  41. }
  42. func (n *Needle) String() (str string) {
  43. str = fmt.Sprintf("%s Size:%d, DataSize:%d, Name:%s, Mime:%s Compressed:%v", formatNeedleIdCookie(n.Id, n.Cookie), n.Size, n.DataSize, n.Name, n.Mime, n.IsCompressed())
  44. return
  45. }
  46. func CreateNeedleSimple(vid VolumeId, id NeedleId, cookie Cookie, data []byte) (n *Needle, contentMd5 string) {
  47. n = new(Needle)
  48. checksum := NewCRC(data)
  49. n.Cookie = cookie
  50. n.Id = id
  51. n.Data = data
  52. n.DataSize = uint32(len(data))
  53. n.Checksum = checksum
  54. n.Size = Size(len(data))
  55. n.LastModified = uint64(time.Now().Unix())
  56. n.SetHasLastModifiedDate()
  57. h := md5.New()
  58. h.Write(data)
  59. contentMd5 = base64.StdEncoding.EncodeToString(h.Sum(nil))
  60. return
  61. }
  62. func CreateNeedleFromRequest(r *http.Request, fixJpgOrientation bool, sizeLimit int64, bytesBuffer *bytes.Buffer) (n *Needle, originalSize int, contentMd5 string, e error) {
  63. n = new(Needle)
  64. pu, e := ParseUpload(r, sizeLimit, bytesBuffer)
  65. if e != nil {
  66. return
  67. }
  68. n.Data = pu.Data
  69. originalSize = pu.OriginalDataSize
  70. n.LastModified = pu.ModifiedTime
  71. n.Ttl = pu.Ttl
  72. contentMd5 = pu.ContentMd5
  73. if len(pu.FileName) < 256 {
  74. n.Name = []byte(pu.FileName)
  75. n.SetHasName()
  76. }
  77. if len(pu.MimeType) < 256 {
  78. n.Mime = []byte(pu.MimeType)
  79. n.SetHasMime()
  80. }
  81. if len(pu.PairMap) != 0 {
  82. trimmedPairMap := make(map[string]string)
  83. for k, v := range pu.PairMap {
  84. trimmedPairMap[k[len(PairNamePrefix):]] = v
  85. }
  86. pairs, _ := json.Marshal(trimmedPairMap)
  87. if len(pairs) < 65536 {
  88. n.Pairs = pairs
  89. n.PairsSize = uint16(len(pairs))
  90. n.SetHasPairs()
  91. }
  92. }
  93. if pu.IsGzipped {
  94. // println(r.URL.Path, "is set to compressed", pu.FileName, pu.IsGzipped, "dataSize", pu.OriginalDataSize)
  95. n.SetIsCompressed()
  96. }
  97. if n.LastModified == 0 {
  98. n.LastModified = uint64(time.Now().Unix())
  99. }
  100. n.SetHasLastModifiedDate()
  101. if n.Ttl != EMPTY_TTL {
  102. n.SetHasTtl()
  103. }
  104. if pu.IsChunkedFile {
  105. n.SetIsChunkManifest()
  106. }
  107. if fixJpgOrientation {
  108. loweredName := strings.ToLower(pu.FileName)
  109. if pu.MimeType == "image/jpeg" || strings.HasSuffix(loweredName, ".jpg") || strings.HasSuffix(loweredName, ".jpeg") {
  110. n.Data = images.FixJpgOrientation(n.Data)
  111. }
  112. }
  113. n.Checksum = NewCRC(n.Data)
  114. commaSep := strings.LastIndex(r.URL.Path, ",")
  115. dotSep := strings.LastIndex(r.URL.Path, ".")
  116. fid := r.URL.Path[commaSep+1:]
  117. if dotSep > 0 {
  118. fid = r.URL.Path[commaSep+1 : dotSep]
  119. }
  120. e = n.ParsePath(fid)
  121. return
  122. }
  123. func (n *Needle) ParsePath(fid string) (err error) {
  124. length := len(fid)
  125. if length <= CookieSize*2 {
  126. return fmt.Errorf("Invalid fid: %s", fid)
  127. }
  128. delta := ""
  129. deltaIndex := strings.LastIndex(fid, "_")
  130. if deltaIndex > 0 {
  131. fid, delta = fid[0:deltaIndex], fid[deltaIndex+1:]
  132. }
  133. n.Id, n.Cookie, err = ParseNeedleIdCookie(fid)
  134. if err != nil {
  135. return err
  136. }
  137. if delta != "" {
  138. if d, e := strconv.ParseUint(delta, 10, 64); e == nil {
  139. n.Id += Uint64ToNeedleId(d)
  140. } else {
  141. return e
  142. }
  143. }
  144. return err
  145. }
  146. func GetAppendAtNs(volumeLastAppendAtNs uint64) uint64 {
  147. return max(uint64(time.Now().UnixNano()), volumeLastAppendAtNs+1)
  148. }
  149. func (n *Needle) UpdateAppendAtNs(volumeLastAppendAtNs uint64) {
  150. n.AppendAtNs = max(uint64(time.Now().UnixNano()), volumeLastAppendAtNs+1)
  151. }
  152. func ParseNeedleIdCookie(key_hash_string string) (NeedleId, Cookie, error) {
  153. if len(key_hash_string) <= CookieSize*2 {
  154. return NeedleIdEmpty, 0, fmt.Errorf("KeyHash is too short.")
  155. }
  156. if len(key_hash_string) > (NeedleIdSize+CookieSize)*2 {
  157. return NeedleIdEmpty, 0, fmt.Errorf("KeyHash is too long.")
  158. }
  159. split := len(key_hash_string) - CookieSize*2
  160. needleId, err := ParseNeedleId(key_hash_string[:split])
  161. if err != nil {
  162. return NeedleIdEmpty, 0, fmt.Errorf("Parse needleId error: %v", err)
  163. }
  164. cookie, err := ParseCookie(key_hash_string[split:])
  165. if err != nil {
  166. return NeedleIdEmpty, 0, fmt.Errorf("Parse cookie error: %v", err)
  167. }
  168. return needleId, cookie, nil
  169. }
  170. func (n *Needle) LastModifiedString() string {
  171. return time.Unix(int64(n.LastModified), 0).Format("2006-01-02T15:04:05")
  172. }
  173. func max(x, y uint64) uint64 {
  174. if x <= y {
  175. return y
  176. }
  177. return x
  178. }