needle.go 4.8 KB

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