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.

242 lines
7.1 KiB

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