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.

350 lines
10 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
5 years ago
4 years ago
  1. package storage
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "github.com/seaweedfs/seaweedfs/weed/glog"
  7. "github.com/seaweedfs/seaweedfs/weed/storage/backend"
  8. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  9. . "github.com/seaweedfs/seaweedfs/weed/storage/types"
  10. "os"
  11. )
  12. var ErrorNotFound = errors.New("not found")
  13. var ErrorDeleted = errors.New("already deleted")
  14. var ErrorSizeMismatch = errors.New("size mismatch")
  15. func (v *Volume) checkReadWriteError(err error) {
  16. if err == nil {
  17. if v.lastIoError != nil {
  18. v.lastIoError = nil
  19. }
  20. return
  21. }
  22. if err.Error() == "input/output error" {
  23. v.lastIoError = err
  24. }
  25. }
  26. // isFileUnchanged checks whether this needle to write is same as last one.
  27. // It requires serialized access in the same volume.
  28. func (v *Volume) isFileUnchanged(n *needle.Needle) bool {
  29. if v.Ttl.String() != "" {
  30. return false
  31. }
  32. nv, ok := v.nm.Get(n.Id)
  33. if ok && !nv.Offset.IsZero() && nv.Size.IsValid() {
  34. oldNeedle := new(needle.Needle)
  35. err := oldNeedle.ReadData(v.DataBackend, nv.Offset.ToActualOffset(), nv.Size, v.Version())
  36. if err != nil {
  37. glog.V(0).Infof("Failed to check updated file at offset %d size %d: %v", nv.Offset.ToActualOffset(), nv.Size, err)
  38. return false
  39. }
  40. if oldNeedle.Cookie == n.Cookie && oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {
  41. n.DataSize = oldNeedle.DataSize
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. var ErrVolumeNotEmpty = fmt.Errorf("volume not empty")
  48. // Destroy removes everything related to this volume
  49. func (v *Volume) Destroy(onlyEmpty bool) (err error) {
  50. v.dataFileAccessLock.Lock()
  51. defer v.dataFileAccessLock.Unlock()
  52. if onlyEmpty {
  53. isEmpty, e := v.doIsEmpty()
  54. if e != nil {
  55. err = fmt.Errorf("failed to read isEmpty %v", e)
  56. return
  57. }
  58. if !isEmpty {
  59. err = ErrVolumeNotEmpty
  60. return
  61. }
  62. }
  63. if v.isCompacting || v.isCommitCompacting {
  64. err = fmt.Errorf("volume %d is compacting", v.Id)
  65. return
  66. }
  67. close(v.asyncRequestsChan)
  68. storageName, storageKey := v.RemoteStorageNameKey()
  69. if v.HasRemoteFile() && storageName != "" && storageKey != "" {
  70. if backendStorage, found := backend.BackendStorages[storageName]; found {
  71. backendStorage.DeleteFile(storageKey)
  72. }
  73. }
  74. v.doClose()
  75. removeVolumeFiles(v.DataFileName())
  76. removeVolumeFiles(v.IndexFileName())
  77. return
  78. }
  79. func removeVolumeFiles(filename string) {
  80. // basic
  81. os.Remove(filename + ".dat")
  82. os.Remove(filename + ".idx")
  83. os.Remove(filename + ".vif")
  84. // sorted index file
  85. os.Remove(filename + ".sdx")
  86. // compaction
  87. os.Remove(filename + ".cpd")
  88. os.Remove(filename + ".cpx")
  89. // level db index file
  90. os.RemoveAll(filename + ".ldb")
  91. // marker for damaged or incomplete volume
  92. os.Remove(filename + ".note")
  93. }
  94. func (v *Volume) asyncRequestAppend(request *needle.AsyncRequest) {
  95. v.asyncRequestsChan <- request
  96. }
  97. func (v *Volume) syncWrite(n *needle.Needle, checkCookie bool) (offset uint64, size Size, isUnchanged bool, err error) {
  98. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  99. actualSize := needle.GetActualSize(Size(len(n.Data)), v.Version())
  100. v.dataFileAccessLock.Lock()
  101. defer v.dataFileAccessLock.Unlock()
  102. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(actualSize) {
  103. err = fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  104. return
  105. }
  106. return v.doWriteRequest(n, checkCookie)
  107. }
  108. func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, 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, checkCookie)
  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, checkCookie bool) (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.ToActualOffset())
  136. if existingNeedleReadErr != nil {
  137. err = fmt.Errorf("reading existing needle: %v", existingNeedleReadErr)
  138. return
  139. }
  140. if n.Cookie == 0 && !checkCookie {
  141. // this is from batch deletion, and read back again when tailing a remote volume
  142. // which only happens when checkCookie == false and fsync == false
  143. n.Cookie = existingNeedle.Cookie
  144. }
  145. if existingNeedle.Cookie != n.Cookie {
  146. glog.V(0).Infof("write cookie mismatch: existing %s, new %s",
  147. needle.NewFileIdFromNeedle(v.Id, existingNeedle), needle.NewFileIdFromNeedle(v.Id, n))
  148. err = fmt.Errorf("mismatching cookie %x", n.Cookie)
  149. return
  150. }
  151. }
  152. // append to dat file
  153. n.UpdateAppendAtNs(v.lastAppendAtNs)
  154. offset, size, _, err = n.Append(v.DataBackend, v.Version())
  155. v.checkReadWriteError(err)
  156. if err != nil {
  157. return
  158. }
  159. v.lastAppendAtNs = n.AppendAtNs
  160. // add to needle map
  161. if !ok || uint64(nv.Offset.ToActualOffset()) < offset {
  162. if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
  163. glog.V(4).Infof("failed to save in needle map %d: %v", n.Id, err)
  164. }
  165. }
  166. if v.lastModifiedTsSeconds < n.LastModified {
  167. v.lastModifiedTsSeconds = n.LastModified
  168. }
  169. return
  170. }
  171. func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
  172. // glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  173. actualSize := needle.GetActualSize(0, v.Version())
  174. v.dataFileAccessLock.Lock()
  175. defer v.dataFileAccessLock.Unlock()
  176. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(actualSize) {
  177. err := fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  178. return 0, err
  179. }
  180. return v.doDeleteRequest(n)
  181. }
  182. func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
  183. // todo: delete info is always appended no fsync, it may need fsync in future
  184. fsync := false
  185. if !fsync {
  186. return v.syncDelete(n)
  187. } else {
  188. asyncRequest := needle.NewAsyncRequest(n, false)
  189. asyncRequest.ActualSize = needle.GetActualSize(0, v.Version())
  190. v.asyncRequestAppend(asyncRequest)
  191. _, size, _, err := asyncRequest.WaitComplete()
  192. return Size(size), err
  193. }
  194. }
  195. func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
  196. glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  197. nv, ok := v.nm.Get(n.Id)
  198. // fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  199. if ok && nv.Size.IsValid() {
  200. var offset uint64
  201. var err error
  202. size := nv.Size
  203. if !v.hasRemoteFile {
  204. n.Data = nil
  205. n.UpdateAppendAtNs(v.lastAppendAtNs)
  206. offset, _, _, err = n.Append(v.DataBackend, v.Version())
  207. v.checkReadWriteError(err)
  208. if err != nil {
  209. return size, err
  210. }
  211. }
  212. v.lastAppendAtNs = n.AppendAtNs
  213. if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
  214. return size, err
  215. }
  216. return size, err
  217. }
  218. return 0, nil
  219. }
  220. func (v *Volume) startWorker() {
  221. go func() {
  222. chanClosed := false
  223. for {
  224. // chan closed. go thread will exit
  225. if chanClosed {
  226. break
  227. }
  228. currentRequests := make([]*needle.AsyncRequest, 0, 128)
  229. currentBytesToWrite := int64(0)
  230. for {
  231. request, ok := <-v.asyncRequestsChan
  232. // volume may be closed
  233. if !ok {
  234. chanClosed = true
  235. break
  236. }
  237. if MaxPossibleVolumeSize < v.ContentSize()+uint64(currentBytesToWrite+request.ActualSize) {
  238. request.Complete(0, 0, false,
  239. fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.ContentSize()))
  240. break
  241. }
  242. currentRequests = append(currentRequests, request)
  243. currentBytesToWrite += request.ActualSize
  244. // submit at most 4M bytes or 128 requests at one time to decrease request delay.
  245. // it also need to break if there is no data in channel to avoid io hang.
  246. if currentBytesToWrite >= 4*1024*1024 || len(currentRequests) >= 128 || len(v.asyncRequestsChan) == 0 {
  247. break
  248. }
  249. }
  250. if len(currentRequests) == 0 {
  251. continue
  252. }
  253. v.dataFileAccessLock.Lock()
  254. end, _, e := v.DataBackend.GetStat()
  255. if e != nil {
  256. for i := 0; i < len(currentRequests); i++ {
  257. currentRequests[i].Complete(0, 0, false,
  258. fmt.Errorf("cannot read current volume position: %v", e))
  259. }
  260. v.dataFileAccessLock.Unlock()
  261. continue
  262. }
  263. for i := 0; i < len(currentRequests); i++ {
  264. if currentRequests[i].IsWriteRequest {
  265. offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N, true)
  266. currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
  267. } else {
  268. size, err := v.doDeleteRequest(currentRequests[i].N)
  269. currentRequests[i].UpdateResult(0, uint64(size), false, err)
  270. }
  271. }
  272. // if sync error, data is not reliable, we should mark the completed request as fail and rollback
  273. if err := v.DataBackend.Sync(); err != nil {
  274. // todo: this may generate dirty data or cause data inconsistent, may be weed need to panic?
  275. if te := v.DataBackend.Truncate(end); te != nil {
  276. glog.V(0).Infof("Failed to truncate %s back to %d with error: %v", v.DataBackend.Name(), end, te)
  277. }
  278. for i := 0; i < len(currentRequests); i++ {
  279. if currentRequests[i].IsSucceed() {
  280. currentRequests[i].UpdateResult(0, 0, false, err)
  281. }
  282. }
  283. }
  284. for i := 0; i < len(currentRequests); i++ {
  285. currentRequests[i].Submit()
  286. }
  287. v.dataFileAccessLock.Unlock()
  288. }
  289. }()
  290. }
  291. func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size) error {
  292. v.dataFileAccessLock.Lock()
  293. defer v.dataFileAccessLock.Unlock()
  294. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(len(needleBlob)) {
  295. return fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  296. }
  297. appendAtNs := needle.GetAppendAtNs(v.lastAppendAtNs)
  298. offset, err := needle.WriteNeedleBlob(v.DataBackend, needleBlob, size, appendAtNs, v.Version())
  299. v.checkReadWriteError(err)
  300. if err != nil {
  301. return err
  302. }
  303. v.lastAppendAtNs = appendAtNs
  304. // add to needle map
  305. if err = v.nm.Put(needleId, ToOffset(int64(offset)), size); err != nil {
  306. glog.V(4).Infof("failed to put in needle map %d: %v", needleId, err)
  307. }
  308. return err
  309. }