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.

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