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.

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