volume_write.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 v.nm == nil {
  177. return 0, nil
  178. }
  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. return v.doDeleteRequest(n)
  184. }
  185. func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
  186. // todo: delete info is always appended no fsync, it may need fsync in future
  187. fsync := false
  188. if !fsync {
  189. return v.syncDelete(n)
  190. } else {
  191. asyncRequest := needle.NewAsyncRequest(n, false)
  192. asyncRequest.ActualSize = needle.GetActualSize(0, v.Version())
  193. v.asyncRequestAppend(asyncRequest)
  194. _, size, _, err := asyncRequest.WaitComplete()
  195. return Size(size), err
  196. }
  197. }
  198. func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
  199. glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  200. nv, ok := v.nm.Get(n.Id)
  201. // fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  202. if ok && nv.Size.IsValid() {
  203. var offset uint64
  204. var err error
  205. size := nv.Size
  206. if !v.hasRemoteFile {
  207. n.Data = nil
  208. n.UpdateAppendAtNs(v.lastAppendAtNs)
  209. offset, _, _, err = n.Append(v.DataBackend, v.Version())
  210. v.checkReadWriteError(err)
  211. if err != nil {
  212. return size, err
  213. }
  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. func (v *Volume) startWorker() {
  224. go func() {
  225. chanClosed := false
  226. for {
  227. // chan closed. go thread will exit
  228. if chanClosed {
  229. break
  230. }
  231. currentRequests := make([]*needle.AsyncRequest, 0, 128)
  232. currentBytesToWrite := int64(0)
  233. for {
  234. request, ok := <-v.asyncRequestsChan
  235. // volume may be closed
  236. if !ok {
  237. chanClosed = true
  238. break
  239. }
  240. if MaxPossibleVolumeSize < v.ContentSize()+uint64(currentBytesToWrite+request.ActualSize) {
  241. request.Complete(0, 0, false,
  242. fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.ContentSize()))
  243. break
  244. }
  245. currentRequests = append(currentRequests, request)
  246. currentBytesToWrite += request.ActualSize
  247. // submit at most 4M bytes or 128 requests at one time to decrease request delay.
  248. // it also need to break if there is no data in channel to avoid io hang.
  249. if currentBytesToWrite >= 4*1024*1024 || len(currentRequests) >= 128 || len(v.asyncRequestsChan) == 0 {
  250. break
  251. }
  252. }
  253. if len(currentRequests) == 0 {
  254. continue
  255. }
  256. v.dataFileAccessLock.Lock()
  257. end, _, e := v.DataBackend.GetStat()
  258. if e != nil {
  259. for i := 0; i < len(currentRequests); i++ {
  260. currentRequests[i].Complete(0, 0, false,
  261. fmt.Errorf("cannot read current volume position: %v", e))
  262. }
  263. v.dataFileAccessLock.Unlock()
  264. continue
  265. }
  266. for i := 0; i < len(currentRequests); i++ {
  267. if currentRequests[i].IsWriteRequest {
  268. offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N, true)
  269. currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
  270. } else {
  271. size, err := v.doDeleteRequest(currentRequests[i].N)
  272. currentRequests[i].UpdateResult(0, uint64(size), false, err)
  273. }
  274. }
  275. // if sync error, data is not reliable, we should mark the completed request as fail and rollback
  276. if err := v.DataBackend.Sync(); err != nil {
  277. // todo: this may generate dirty data or cause data inconsistent, may be weed need to panic?
  278. if te := v.DataBackend.Truncate(end); te != nil {
  279. glog.V(0).Infof("Failed to truncate %s back to %d with error: %v", v.DataBackend.Name(), end, te)
  280. }
  281. for i := 0; i < len(currentRequests); i++ {
  282. if currentRequests[i].IsSucceed() {
  283. currentRequests[i].UpdateResult(0, 0, false, err)
  284. }
  285. }
  286. }
  287. for i := 0; i < len(currentRequests); i++ {
  288. currentRequests[i].Submit()
  289. }
  290. v.dataFileAccessLock.Unlock()
  291. }
  292. }()
  293. }
  294. func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size) error {
  295. v.dataFileAccessLock.Lock()
  296. defer v.dataFileAccessLock.Unlock()
  297. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(len(needleBlob)) {
  298. return fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  299. }
  300. appendAtNs := needle.GetAppendAtNs(v.lastAppendAtNs)
  301. offset, err := needle.WriteNeedleBlob(v.DataBackend, needleBlob, size, appendAtNs, v.Version())
  302. v.checkReadWriteError(err)
  303. if err != nil {
  304. return err
  305. }
  306. v.lastAppendAtNs = appendAtNs
  307. // add to needle map
  308. if err = v.nm.Put(needleId, ToOffset(int64(offset)), size); err != nil {
  309. glog.V(4).Infof("failed to put in needle map %d: %v", needleId, err)
  310. }
  311. return err
  312. }