volume_write.go 9.8 KB

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