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.

433 lines
13 KiB

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