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.

448 lines
14 KiB

6 years ago
4 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 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. var ErrorDeleted = errors.New("already deleted")
  17. var ErrorSizeMismatch = errors.New("size mismatch")
  18. // isFileUnchanged checks whether this needle to write is same as last one.
  19. // It requires serialized access in the same volume.
  20. func (v *Volume) isFileUnchanged(n *needle.Needle) bool {
  21. if v.Ttl.String() != "" {
  22. return false
  23. }
  24. nv, ok := v.nm.Get(n.Id)
  25. if ok && !nv.Offset.IsZero() && nv.Size.IsValid() {
  26. oldNeedle := new(needle.Needle)
  27. err := oldNeedle.ReadData(v.DataBackend, nv.Offset.ToAcutalOffset(), nv.Size, v.Version())
  28. if err != nil {
  29. glog.V(0).Infof("Failed to check updated file at offset %d size %d: %v", nv.Offset.ToAcutalOffset(), nv.Size, err)
  30. return false
  31. }
  32. if oldNeedle.Cookie == n.Cookie && oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {
  33. n.DataSize = oldNeedle.DataSize
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. // Destroy removes everything related to this volume
  40. func (v *Volume) Destroy() (err error) {
  41. if v.isCompacting {
  42. err = fmt.Errorf("volume %d is compacting", v.Id)
  43. return
  44. }
  45. close(v.asyncRequestsChan)
  46. storageName, storageKey := v.RemoteStorageNameKey()
  47. if v.HasRemoteFile() && storageName != "" && storageKey != "" {
  48. if backendStorage, found := backend.BackendStorages[storageName]; found {
  49. backendStorage.DeleteFile(storageKey)
  50. }
  51. }
  52. v.Close()
  53. removeVolumeFiles(v.FileName())
  54. return
  55. }
  56. func removeVolumeFiles(filename string) {
  57. // basic
  58. os.Remove(filename + ".dat")
  59. os.Remove(filename + ".idx")
  60. os.Remove(filename + ".vif")
  61. // sorted index file
  62. os.Remove(filename + ".sdx")
  63. // compaction
  64. os.Remove(filename + ".cpd")
  65. os.Remove(filename + ".cpx")
  66. // level db indx file
  67. os.RemoveAll(filename + ".ldb")
  68. // marker for damaged or incomplete volume
  69. os.Remove(filename + ".note")
  70. }
  71. func (v *Volume) asyncRequestAppend(request *needle.AsyncRequest) {
  72. v.asyncRequestsChan <- request
  73. }
  74. func (v *Volume) syncWrite(n *needle.Needle) (offset uint64, size Size, isUnchanged bool, err error) {
  75. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  76. actualSize := needle.GetActualSize(Size(len(n.Data)), v.Version())
  77. v.dataFileAccessLock.Lock()
  78. defer v.dataFileAccessLock.Unlock()
  79. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(actualSize) {
  80. err = fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  81. return
  82. }
  83. if v.isFileUnchanged(n) {
  84. size = Size(n.DataSize)
  85. isUnchanged = true
  86. return
  87. }
  88. // check whether existing needle cookie matches
  89. nv, ok := v.nm.Get(n.Id)
  90. if ok {
  91. existingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.DataBackend, v.Version(), nv.Offset.ToAcutalOffset())
  92. if existingNeedleReadErr != nil {
  93. err = fmt.Errorf("reading existing needle: %v", existingNeedleReadErr)
  94. return
  95. }
  96. if existingNeedle.Cookie != n.Cookie {
  97. glog.V(0).Infof("write cookie mismatch: existing %x, new %x", existingNeedle.Cookie, n.Cookie)
  98. err = fmt.Errorf("mismatching cookie %x", n.Cookie)
  99. return
  100. }
  101. }
  102. // append to dat file
  103. n.AppendAtNs = uint64(time.Now().UnixNano())
  104. if offset, size, _, err = n.Append(v.DataBackend, v.Version()); err != nil {
  105. return
  106. }
  107. v.lastAppendAtNs = n.AppendAtNs
  108. // add to needle map
  109. if !ok || uint64(nv.Offset.ToAcutalOffset()) < offset {
  110. if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
  111. glog.V(4).Infof("failed to save in needle map %d: %v", n.Id, err)
  112. }
  113. }
  114. if v.lastModifiedTsSeconds < n.LastModified {
  115. v.lastModifiedTsSeconds = n.LastModified
  116. }
  117. return
  118. }
  119. func (v *Volume) writeNeedle2(n *needle.Needle, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
  120. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  121. if n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {
  122. n.SetHasTtl()
  123. n.Ttl = v.Ttl
  124. }
  125. if !fsync {
  126. return v.syncWrite(n)
  127. } else {
  128. asyncRequest := needle.NewAsyncRequest(n, true)
  129. // using len(n.Data) here instead of n.Size before n.Size is populated in n.Append()
  130. asyncRequest.ActualSize = needle.GetActualSize(Size(len(n.Data)), v.Version())
  131. v.asyncRequestAppend(asyncRequest)
  132. offset, _, isUnchanged, err = asyncRequest.WaitComplete()
  133. return
  134. }
  135. }
  136. func (v *Volume) doWriteRequest(n *needle.Needle) (offset uint64, size Size, isUnchanged bool, err error) {
  137. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  138. if v.isFileUnchanged(n) {
  139. size = Size(n.DataSize)
  140. isUnchanged = true
  141. return
  142. }
  143. // check whether existing needle cookie matches
  144. nv, ok := v.nm.Get(n.Id)
  145. if ok {
  146. existingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.DataBackend, v.Version(), nv.Offset.ToAcutalOffset())
  147. if existingNeedleReadErr != nil {
  148. err = fmt.Errorf("reading existing needle: %v", existingNeedleReadErr)
  149. return
  150. }
  151. if existingNeedle.Cookie != n.Cookie {
  152. glog.V(0).Infof("write cookie mismatch: existing %x, new %x", existingNeedle.Cookie, n.Cookie)
  153. err = fmt.Errorf("mismatching cookie %x", n.Cookie)
  154. return
  155. }
  156. }
  157. // append to dat file
  158. n.AppendAtNs = uint64(time.Now().UnixNano())
  159. if offset, size, _, err = n.Append(v.DataBackend, v.Version()); err != nil {
  160. return
  161. }
  162. v.lastAppendAtNs = n.AppendAtNs
  163. // add to needle map
  164. if !ok || uint64(nv.Offset.ToAcutalOffset()) < offset {
  165. if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
  166. glog.V(4).Infof("failed to save in needle map %d: %v", n.Id, err)
  167. }
  168. }
  169. if v.lastModifiedTsSeconds < n.LastModified {
  170. v.lastModifiedTsSeconds = n.LastModified
  171. }
  172. return
  173. }
  174. func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
  175. // glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  176. actualSize := needle.GetActualSize(0, v.Version())
  177. v.dataFileAccessLock.Lock()
  178. defer v.dataFileAccessLock.Unlock()
  179. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(actualSize) {
  180. err := fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  181. return 0, err
  182. }
  183. nv, ok := v.nm.Get(n.Id)
  184. // fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  185. if ok && nv.Size.IsValid() {
  186. size := nv.Size
  187. n.Data = nil
  188. n.AppendAtNs = uint64(time.Now().UnixNano())
  189. offset, _, _, err := n.Append(v.DataBackend, v.Version())
  190. if err != nil {
  191. return size, err
  192. }
  193. v.lastAppendAtNs = n.AppendAtNs
  194. if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
  195. return size, err
  196. }
  197. return size, err
  198. }
  199. return 0, nil
  200. }
  201. func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
  202. // todo: delete info is always appended no fsync, it may need fsync in future
  203. fsync := false
  204. if !fsync {
  205. return v.syncDelete(n)
  206. } else {
  207. asyncRequest := needle.NewAsyncRequest(n, false)
  208. asyncRequest.ActualSize = needle.GetActualSize(0, v.Version())
  209. v.asyncRequestAppend(asyncRequest)
  210. _, size, _, err := asyncRequest.WaitComplete()
  211. return Size(size), err
  212. }
  213. }
  214. func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
  215. glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  216. nv, ok := v.nm.Get(n.Id)
  217. // fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  218. if ok && nv.Size.IsValid() {
  219. size := nv.Size
  220. n.Data = nil
  221. n.AppendAtNs = uint64(time.Now().UnixNano())
  222. offset, _, _, err := n.Append(v.DataBackend, v.Version())
  223. if err != nil {
  224. return size, err
  225. }
  226. v.lastAppendAtNs = n.AppendAtNs
  227. if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
  228. return size, err
  229. }
  230. return size, err
  231. }
  232. return 0, nil
  233. }
  234. // read fills in Needle content by looking up n.Id from NeedleMapper
  235. func (v *Volume) readNeedle(n *needle.Needle, readOption *ReadOption) (int, error) {
  236. v.dataFileAccessLock.RLock()
  237. defer v.dataFileAccessLock.RUnlock()
  238. nv, ok := v.nm.Get(n.Id)
  239. if !ok || nv.Offset.IsZero() {
  240. return -1, ErrorNotFound
  241. }
  242. readSize := nv.Size
  243. if readSize.IsDeleted() {
  244. if readOption != nil && readOption.ReadDeleted && readSize != TombstoneFileSize {
  245. glog.V(3).Infof("reading deleted %s", n.String())
  246. readSize = -readSize
  247. } else {
  248. return -1, ErrorDeleted
  249. }
  250. }
  251. if readSize == 0 {
  252. return 0, nil
  253. }
  254. err := n.ReadData(v.DataBackend, nv.Offset.ToAcutalOffset(), readSize, v.Version())
  255. if err == needle.ErrorSizeMismatch && OffsetSize == 4 {
  256. err = n.ReadData(v.DataBackend, nv.Offset.ToAcutalOffset()+int64(MaxPossibleVolumeSize), readSize, v.Version())
  257. }
  258. if err != nil {
  259. return 0, err
  260. }
  261. bytesRead := len(n.Data)
  262. if !n.HasTtl() {
  263. return bytesRead, nil
  264. }
  265. ttlMinutes := n.Ttl.Minutes()
  266. if ttlMinutes == 0 {
  267. return bytesRead, nil
  268. }
  269. if !n.HasLastModifiedDate() {
  270. return bytesRead, nil
  271. }
  272. if uint64(time.Now().Unix()) < n.LastModified+uint64(ttlMinutes*60) {
  273. return bytesRead, nil
  274. }
  275. return -1, ErrorNotFound
  276. }
  277. func (v *Volume) startWorker() {
  278. go func() {
  279. chanClosed := false
  280. for {
  281. // chan closed. go thread will exit
  282. if chanClosed {
  283. break
  284. }
  285. currentRequests := make([]*needle.AsyncRequest, 0, 128)
  286. currentBytesToWrite := int64(0)
  287. for {
  288. request, ok := <-v.asyncRequestsChan
  289. // volume may be closed
  290. if !ok {
  291. chanClosed = true
  292. break
  293. }
  294. if MaxPossibleVolumeSize < v.ContentSize()+uint64(currentBytesToWrite+request.ActualSize) {
  295. request.Complete(0, 0, false,
  296. fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.ContentSize()))
  297. break
  298. }
  299. currentRequests = append(currentRequests, request)
  300. currentBytesToWrite += request.ActualSize
  301. // submit at most 4M bytes or 128 requests at one time to decrease request delay.
  302. // it also need to break if there is no data in channel to avoid io hang.
  303. if currentBytesToWrite >= 4*1024*1024 || len(currentRequests) >= 128 || len(v.asyncRequestsChan) == 0 {
  304. break
  305. }
  306. }
  307. if len(currentRequests) == 0 {
  308. continue
  309. }
  310. v.dataFileAccessLock.Lock()
  311. end, _, e := v.DataBackend.GetStat()
  312. if e != nil {
  313. for i := 0; i < len(currentRequests); i++ {
  314. currentRequests[i].Complete(0, 0, false,
  315. fmt.Errorf("cannot read current volume position: %v", e))
  316. }
  317. v.dataFileAccessLock.Unlock()
  318. continue
  319. }
  320. for i := 0; i < len(currentRequests); i++ {
  321. if currentRequests[i].IsWriteRequest {
  322. offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N)
  323. currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
  324. } else {
  325. size, err := v.doDeleteRequest(currentRequests[i].N)
  326. currentRequests[i].UpdateResult(0, uint64(size), false, err)
  327. }
  328. }
  329. // if sync error, data is not reliable, we should mark the completed request as fail and rollback
  330. if err := v.DataBackend.Sync(); err != nil {
  331. // todo: this may generate dirty data or cause data inconsistent, may be weed need to panic?
  332. if te := v.DataBackend.Truncate(end); te != nil {
  333. glog.V(0).Infof("Failed to truncate %s back to %d with error: %v", v.DataBackend.Name(), end, te)
  334. }
  335. for i := 0; i < len(currentRequests); i++ {
  336. if currentRequests[i].IsSucceed() {
  337. currentRequests[i].UpdateResult(0, 0, false, err)
  338. }
  339. }
  340. }
  341. for i := 0; i < len(currentRequests); i++ {
  342. currentRequests[i].Submit()
  343. }
  344. v.dataFileAccessLock.Unlock()
  345. }
  346. }()
  347. }
  348. type VolumeFileScanner interface {
  349. VisitSuperBlock(super_block.SuperBlock) error
  350. ReadNeedleBody() bool
  351. VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error
  352. }
  353. func ScanVolumeFile(dirname string, collection string, id needle.VolumeId,
  354. needleMapKind NeedleMapType,
  355. volumeFileScanner VolumeFileScanner) (err error) {
  356. var v *Volume
  357. if v, err = loadVolumeWithoutIndex(dirname, collection, id, needleMapKind); err != nil {
  358. return fmt.Errorf("failed to load volume %d: %v", id, err)
  359. }
  360. if err = volumeFileScanner.VisitSuperBlock(v.SuperBlock); err != nil {
  361. return fmt.Errorf("failed to process volume %d super block: %v", id, err)
  362. }
  363. defer v.Close()
  364. version := v.Version()
  365. offset := int64(v.SuperBlock.BlockSize())
  366. return ScanVolumeFileFrom(version, v.DataBackend, offset, volumeFileScanner)
  367. }
  368. func ScanVolumeFileFrom(version needle.Version, datBackend backend.BackendStorageFile, offset int64, volumeFileScanner VolumeFileScanner) (err error) {
  369. n, nh, rest, e := needle.ReadNeedleHeader(datBackend, version, offset)
  370. if e != nil {
  371. if e == io.EOF {
  372. return nil
  373. }
  374. return fmt.Errorf("cannot read %s at offset %d: %v", datBackend.Name(), offset, e)
  375. }
  376. for n != nil {
  377. var needleBody []byte
  378. if volumeFileScanner.ReadNeedleBody() {
  379. // println("needle", n.Id.String(), "offset", offset, "size", n.Size, "rest", rest)
  380. if needleBody, err = n.ReadNeedleBody(datBackend, version, offset+NeedleHeaderSize, rest); err != nil {
  381. glog.V(0).Infof("cannot read needle head [%d, %d) body [%d, %d) body length %d: %v", offset, offset+NeedleHeaderSize, offset+NeedleHeaderSize, offset+NeedleHeaderSize+rest, rest, err)
  382. // err = fmt.Errorf("cannot read needle body: %v", err)
  383. // return
  384. }
  385. }
  386. err := volumeFileScanner.VisitNeedle(n, offset, nh, needleBody)
  387. if err == io.EOF {
  388. return nil
  389. }
  390. if err != nil {
  391. glog.V(0).Infof("visit needle error: %v", err)
  392. return fmt.Errorf("visit needle error: %v", err)
  393. }
  394. offset += NeedleHeaderSize + rest
  395. glog.V(4).Infof("==> new entry offset %d", offset)
  396. if n, nh, rest, err = needle.ReadNeedleHeader(datBackend, version, offset); err != nil {
  397. if err == io.EOF {
  398. return nil
  399. }
  400. return fmt.Errorf("cannot read needle header at offset %d: %v", offset, err)
  401. }
  402. glog.V(4).Infof("new entry needle size:%d rest:%d", n.Size, rest)
  403. }
  404. return nil
  405. }