volume_write.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. v.dataFileAccessLock.Lock()
  100. defer v.dataFileAccessLock.Unlock()
  101. return v.doWriteRequest(n, checkCookie)
  102. }
  103. func (v *Volume) writeNeedle2(n *needle.Needle, checkCookie bool, fsync bool) (offset uint64, size Size, isUnchanged bool, err error) {
  104. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  105. if n.Ttl == needle.EMPTY_TTL && v.Ttl != needle.EMPTY_TTL {
  106. n.SetHasTtl()
  107. n.Ttl = v.Ttl
  108. }
  109. if !fsync {
  110. return v.syncWrite(n, checkCookie)
  111. } else {
  112. asyncRequest := needle.NewAsyncRequest(n, true)
  113. // using len(n.Data) here instead of n.Size before n.Size is populated in n.Append()
  114. asyncRequest.ActualSize = needle.GetActualSize(Size(len(n.Data)), v.Version())
  115. v.asyncRequestAppend(asyncRequest)
  116. offset, _, isUnchanged, err = asyncRequest.WaitComplete()
  117. return
  118. }
  119. }
  120. func (v *Volume) doWriteRequest(n *needle.Needle, checkCookie bool) (offset uint64, size Size, isUnchanged bool, err error) {
  121. // glog.V(4).Infof("writing needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  122. if v.isFileUnchanged(n) {
  123. size = Size(n.DataSize)
  124. isUnchanged = true
  125. return
  126. }
  127. // check whether existing needle cookie matches
  128. nv, ok := v.nm.Get(n.Id)
  129. if ok {
  130. existingNeedle, _, _, existingNeedleReadErr := needle.ReadNeedleHeader(v.DataBackend, v.Version(), nv.Offset.ToActualOffset())
  131. if existingNeedleReadErr != nil {
  132. err = fmt.Errorf("reading existing needle: %v", existingNeedleReadErr)
  133. return
  134. }
  135. if n.Cookie == 0 && !checkCookie {
  136. // this is from batch deletion, and read back again when tailing a remote volume
  137. // which only happens when checkCookie == false and fsync == false
  138. n.Cookie = existingNeedle.Cookie
  139. }
  140. if existingNeedle.Cookie != n.Cookie {
  141. glog.V(0).Infof("write cookie mismatch: existing %s, new %s",
  142. needle.NewFileIdFromNeedle(v.Id, existingNeedle), needle.NewFileIdFromNeedle(v.Id, n))
  143. err = fmt.Errorf("mismatching cookie %x", n.Cookie)
  144. return
  145. }
  146. }
  147. // append to dat file
  148. n.UpdateAppendAtNs(v.lastAppendAtNs)
  149. offset, size, _, err = n.Append(v.DataBackend, v.Version())
  150. v.checkReadWriteError(err)
  151. if err != nil {
  152. return
  153. }
  154. v.lastAppendAtNs = n.AppendAtNs
  155. // add to needle map
  156. if !ok || uint64(nv.Offset.ToActualOffset()) < offset {
  157. if err = v.nm.Put(n.Id, ToOffset(int64(offset)), n.Size); err != nil {
  158. glog.V(4).Infof("failed to save in needle map %d: %v", n.Id, err)
  159. }
  160. }
  161. if v.lastModifiedTsSeconds < n.LastModified {
  162. v.lastModifiedTsSeconds = n.LastModified
  163. }
  164. return
  165. }
  166. func (v *Volume) syncDelete(n *needle.Needle) (Size, error) {
  167. // glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  168. v.dataFileAccessLock.Lock()
  169. defer v.dataFileAccessLock.Unlock()
  170. if v.nm == nil {
  171. return 0, nil
  172. }
  173. return v.doDeleteRequest(n)
  174. }
  175. func (v *Volume) deleteNeedle2(n *needle.Needle) (Size, error) {
  176. // todo: delete info is always appended no fsync, it may need fsync in future
  177. fsync := false
  178. if !fsync {
  179. return v.syncDelete(n)
  180. } else {
  181. asyncRequest := needle.NewAsyncRequest(n, false)
  182. asyncRequest.ActualSize = needle.GetActualSize(0, v.Version())
  183. v.asyncRequestAppend(asyncRequest)
  184. _, size, _, err := asyncRequest.WaitComplete()
  185. return Size(size), err
  186. }
  187. }
  188. func (v *Volume) doDeleteRequest(n *needle.Needle) (Size, error) {
  189. glog.V(4).Infof("delete needle %s", needle.NewFileIdFromNeedle(v.Id, n).String())
  190. nv, ok := v.nm.Get(n.Id)
  191. // fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  192. if ok && nv.Size.IsValid() {
  193. var offset uint64
  194. var err error
  195. size := nv.Size
  196. if !v.hasRemoteFile {
  197. n.Data = nil
  198. n.UpdateAppendAtNs(v.lastAppendAtNs)
  199. offset, _, _, err = n.Append(v.DataBackend, v.Version())
  200. v.checkReadWriteError(err)
  201. if err != nil {
  202. return size, err
  203. }
  204. }
  205. v.lastAppendAtNs = n.AppendAtNs
  206. if err = v.nm.Delete(n.Id, ToOffset(int64(offset))); err != nil {
  207. return size, err
  208. }
  209. return size, err
  210. }
  211. return 0, nil
  212. }
  213. func (v *Volume) startWorker() {
  214. go func() {
  215. chanClosed := false
  216. for {
  217. // chan closed. go thread will exit
  218. if chanClosed {
  219. break
  220. }
  221. currentRequests := make([]*needle.AsyncRequest, 0, 128)
  222. currentBytesToWrite := int64(0)
  223. for {
  224. request, ok := <-v.asyncRequestsChan
  225. // volume may be closed
  226. if !ok {
  227. chanClosed = true
  228. break
  229. }
  230. if MaxPossibleVolumeSize < v.ContentSize()+uint64(currentBytesToWrite+request.ActualSize) {
  231. request.Complete(0, 0, false,
  232. fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.ContentSize()))
  233. break
  234. }
  235. currentRequests = append(currentRequests, request)
  236. currentBytesToWrite += request.ActualSize
  237. // submit at most 4M bytes or 128 requests at one time to decrease request delay.
  238. // it also need to break if there is no data in channel to avoid io hang.
  239. if currentBytesToWrite >= 4*1024*1024 || len(currentRequests) >= 128 || len(v.asyncRequestsChan) == 0 {
  240. break
  241. }
  242. }
  243. if len(currentRequests) == 0 {
  244. continue
  245. }
  246. v.dataFileAccessLock.Lock()
  247. end, _, e := v.DataBackend.GetStat()
  248. if e != nil {
  249. for i := 0; i < len(currentRequests); i++ {
  250. currentRequests[i].Complete(0, 0, false,
  251. fmt.Errorf("cannot read current volume position: %v", e))
  252. }
  253. v.dataFileAccessLock.Unlock()
  254. continue
  255. }
  256. for i := 0; i < len(currentRequests); i++ {
  257. if currentRequests[i].IsWriteRequest {
  258. offset, size, isUnchanged, err := v.doWriteRequest(currentRequests[i].N, true)
  259. currentRequests[i].UpdateResult(offset, uint64(size), isUnchanged, err)
  260. } else {
  261. size, err := v.doDeleteRequest(currentRequests[i].N)
  262. currentRequests[i].UpdateResult(0, uint64(size), false, err)
  263. }
  264. }
  265. // if sync error, data is not reliable, we should mark the completed request as fail and rollback
  266. if err := v.DataBackend.Sync(); err != nil {
  267. // todo: this may generate dirty data or cause data inconsistent, may be weed need to panic?
  268. if te := v.DataBackend.Truncate(end); te != nil {
  269. glog.V(0).Infof("Failed to truncate %s back to %d with error: %v", v.DataBackend.Name(), end, te)
  270. }
  271. for i := 0; i < len(currentRequests); i++ {
  272. if currentRequests[i].IsSucceed() {
  273. currentRequests[i].UpdateResult(0, 0, false, err)
  274. }
  275. }
  276. }
  277. for i := 0; i < len(currentRequests); i++ {
  278. currentRequests[i].Submit()
  279. }
  280. v.dataFileAccessLock.Unlock()
  281. }
  282. }()
  283. }
  284. func (v *Volume) WriteNeedleBlob(needleId NeedleId, needleBlob []byte, size Size) error {
  285. v.dataFileAccessLock.Lock()
  286. defer v.dataFileAccessLock.Unlock()
  287. if MaxPossibleVolumeSize < v.nm.ContentSize()+uint64(len(needleBlob)) {
  288. return fmt.Errorf("volume size limit %d exceeded! current size is %d", MaxPossibleVolumeSize, v.nm.ContentSize())
  289. }
  290. appendAtNs := needle.GetAppendAtNs(v.lastAppendAtNs)
  291. offset, err := needle.WriteNeedleBlob(v.DataBackend, needleBlob, size, appendAtNs, v.Version())
  292. v.checkReadWriteError(err)
  293. if err != nil {
  294. return err
  295. }
  296. v.lastAppendAtNs = appendAtNs
  297. // add to needle map
  298. if err = v.nm.Put(needleId, ToOffset(int64(offset)), size); err != nil {
  299. glog.V(4).Infof("failed to put in needle map %d: %v", needleId, err)
  300. }
  301. return err
  302. }