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.

240 lines
6.9 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. package storage
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "os"
  8. "time"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  10. "github.com/chrislusf/seaweedfs/weed/storage/memory_map"
  11. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  12. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  13. )
  14. var ErrorNotFound = errors.New("not found")
  15. // isFileUnchanged checks whether this needle to write is same as last one.
  16. // It requires serialized access in the same volume.
  17. func (v *Volume) isFileUnchanged(n *needle.Needle) bool {
  18. if v.Ttl.String() != "" {
  19. return false
  20. }
  21. nv, ok := v.nm.Get(n.Id)
  22. if ok && !nv.Offset.IsZero() && nv.Size != TombstoneFileSize {
  23. oldNeedle := new(needle.Needle)
  24. err := oldNeedle.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())
  25. if err != nil {
  26. glog.V(0).Infof("Failed to check updated file at offset %d size %d: %v", nv.Offset.ToAcutalOffset(), nv.Size, err)
  27. return false
  28. }
  29. if oldNeedle.Cookie == n.Cookie && oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {
  30. n.DataSize = oldNeedle.DataSize
  31. return true
  32. }
  33. }
  34. return false
  35. }
  36. // Destroy removes everything related to this volume
  37. func (v *Volume) Destroy() (err error) {
  38. if v.isCompacting {
  39. err = fmt.Errorf("volume %d is compacting", v.Id)
  40. return
  41. }
  42. mMap, exists := memory_map.FileMemoryMap[v.dataFile.Name()]
  43. if exists {
  44. mMap.DeleteFileAndMemoryMap()
  45. delete(memory_map.FileMemoryMap, v.dataFile.Name())
  46. }
  47. v.Close()
  48. os.Remove(v.FileName() + ".dat")
  49. os.Remove(v.FileName() + ".idx")
  50. os.Remove(v.FileName() + ".cpd")
  51. os.Remove(v.FileName() + ".cpx")
  52. os.Remove(v.FileName() + ".ldb")
  53. os.Remove(v.FileName() + ".bdb")
  54. return
  55. }
  56. func (v *Volume) writeNeedle(n *needle.Needle) (offset uint64, size uint32, isUnchanged bool, err error) {
  57. glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  58. if v.readOnly {
  59. err = fmt.Errorf("%s is read-only", v.dataFile.Name())
  60. return
  61. }
  62. v.dataFileAccessLock.Lock()
  63. defer v.dataFileAccessLock.Unlock()
  64. if v.isFileUnchanged(n) {
  65. size = n.DataSize
  66. isUnchanged = true
  67. return
  68. }
  69. if n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {
  70. n.SetHasTtl()
  71. n.Ttl = v.Ttl
  72. }
  73. // check whether existing needle cookie matches
  74. nv, ok := v.nm.Get(n.Id)
  75. if ok {
  76. existingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.dataFile, v.Version(), nv.Offset.ToAcutalOffset())
  77. if existingNeedleReadErr != nil {
  78. err = fmt.Errorf("reading existing needle: %v", existingNeedleReadErr)
  79. return
  80. }
  81. if existingNeedle.Cookie != n.Cookie {
  82. glog.V(0).Infof("write cookie mismatch: existing %x, new %x", existingNeedle.Cookie, n.Cookie)
  83. err = fmt.Errorf("mismatching cookie %x", n.Cookie)
  84. return
  85. }
  86. }
  87. // append to dat file
  88. n.AppendAtNs = uint64(time.Now().UnixNano())
  89. if offset, size, _, err = n.Append(v.dataFile, v.Version()); err != nil {
  90. return
  91. }
  92. v.lastAppendAtNs = n.AppendAtNs
  93. // add to needle map
  94. if !ok || uint64(nv.Offset.ToAcutalOffset()) < offset {
  95. if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
  96. glog.V(4).Infof("failed to save in needle map %d: %v", n.Id, err)
  97. }
  98. }
  99. if v.lastModifiedTsSeconds < n.LastModified {
  100. v.lastModifiedTsSeconds = n.LastModified
  101. }
  102. return
  103. }
  104. func (v *Volume) deleteNeedle(n *needle.Needle) (uint32, error) {
  105. glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  106. if v.readOnly {
  107. return 0, fmt.Errorf("%s is read-only", v.dataFile.Name())
  108. }
  109. v.dataFileAccessLock.Lock()
  110. defer v.dataFileAccessLock.Unlock()
  111. nv, ok := v.nm.Get(n.Id)
  112. //fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  113. if ok && nv.Size != TombstoneFileSize {
  114. size := nv.Size
  115. n.Data = nil
  116. n.AppendAtNs = uint64(time.Now().UnixNano())
  117. offset, _, _, err := n.Append(v.dataFile, v.Version())
  118. if err != nil {
  119. return size, err
  120. }
  121. v.lastAppendAtNs = n.AppendAtNs
  122. if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
  123. return size, err
  124. }
  125. return size, err
  126. }
  127. return 0, nil
  128. }
  129. // read fills in Needle content by looking up n.Id from NeedleMapper
  130. func (v *Volume) readNeedle(n *needle.Needle) (int, error) {
  131. v.dataFileAccessLock.Lock()
  132. defer v.dataFileAccessLock.Unlock()
  133. nv, ok := v.nm.Get(n.Id)
  134. if !ok || nv.Offset.IsZero() {
  135. return -1, ErrorNotFound
  136. }
  137. if nv.Size == TombstoneFileSize {
  138. return -1, errors.New("already deleted")
  139. }
  140. if nv.Size == 0 {
  141. return 0, nil
  142. }
  143. err := n.ReadData(v.dataFile, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())
  144. if err != nil {
  145. return 0, err
  146. }
  147. bytesRead := len(n.Data)
  148. if !n.HasTtl() {
  149. return bytesRead, nil
  150. }
  151. ttlMinutes := n.Ttl.Minutes()
  152. if ttlMinutes == 0 {
  153. return bytesRead, nil
  154. }
  155. if !n.HasLastModifiedDate() {
  156. return bytesRead, nil
  157. }
  158. if uint64(time.Now().Unix()) < n.LastModified+uint64(ttlMinutes*60) {
  159. return bytesRead, nil
  160. }
  161. return -1, ErrorNotFound
  162. }
  163. type VolumeFileScanner interface {
  164. VisitSuperBlock(SuperBlock) error
  165. ReadNeedleBody() bool
  166. VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error
  167. }
  168. func ScanVolumeFile(dirname string, collection string, id needle.VolumeId,
  169. needleMapKind NeedleMapType,
  170. volumeFileScanner VolumeFileScanner) (err error) {
  171. var v *Volume
  172. if v, err = loadVolumeWithoutIndex(dirname, collection, id, needleMapKind); err != nil {
  173. return fmt.Errorf("failed to load volume %d: %v", id, err)
  174. }
  175. if err = volumeFileScanner.VisitSuperBlock(v.SuperBlock); err != nil {
  176. return fmt.Errorf("failed to process volume %d super block: %v", id, err)
  177. }
  178. defer v.Close()
  179. version := v.Version()
  180. offset := int64(v.SuperBlock.BlockSize())
  181. return ScanVolumeFileFrom(version, v.dataFile, offset, volumeFileScanner)
  182. }
  183. func ScanVolumeFileFrom(version needle.Version, dataFile *os.File, offset int64, volumeFileScanner VolumeFileScanner) (err error) {
  184. n, nh, rest, e := needle.ReadNeedleHeader(dataFile, version, offset)
  185. if e != nil {
  186. if e == io.EOF {
  187. return nil
  188. }
  189. return fmt.Errorf("cannot read %s at offset %d: %v", dataFile.Name(), offset, e)
  190. }
  191. for n != nil {
  192. var needleBody []byte
  193. if volumeFileScanner.ReadNeedleBody() {
  194. if needleBody, err = n.ReadNeedleBody(dataFile, version, offset+NeedleHeaderSize, rest); err != nil {
  195. glog.V(0).Infof("cannot read needle body: %v", err)
  196. //err = fmt.Errorf("cannot read needle body: %v", err)
  197. //return
  198. }
  199. }
  200. err := volumeFileScanner.VisitNeedle(n, offset, nh, needleBody)
  201. if err == io.EOF {
  202. return nil
  203. }
  204. if err != nil {
  205. glog.V(0).Infof("visit needle error: %v", err)
  206. return fmt.Errorf("visit needle error: %v", err)
  207. }
  208. offset += NeedleHeaderSize + rest
  209. glog.V(4).Infof("==> new entry offset %d", offset)
  210. if n, nh, rest, err = needle.ReadNeedleHeader(dataFile, version, offset); err != nil {
  211. if err == io.EOF {
  212. return nil
  213. }
  214. return fmt.Errorf("cannot read needle header at offset %d: %v", offset, err)
  215. }
  216. glog.V(4).Infof("new entry needle size:%d rest:%d", n.Size, rest)
  217. }
  218. return nil
  219. }