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.

456 lines
12 KiB

12 years ago
12 years ago
11 years ago
12 years ago
11 years ago
11 years ago
11 years ago
  1. package storage
  2. import (
  3. "bytes"
  4. "code.google.com/p/weed-fs/go/glog"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path"
  10. "sync"
  11. "time"
  12. )
  13. const (
  14. SuperBlockSize = 8
  15. )
  16. type SuperBlock struct {
  17. Version Version
  18. ReplicaPlacement *ReplicaPlacement
  19. }
  20. func (s *SuperBlock) Bytes() []byte {
  21. header := make([]byte, SuperBlockSize)
  22. header[0] = byte(s.Version)
  23. header[1] = s.ReplicaPlacement.Byte()
  24. return header
  25. }
  26. type Volume struct {
  27. Id VolumeId
  28. dir string
  29. Collection string
  30. dataFile *os.File
  31. nm NeedleMapper
  32. readOnly bool
  33. SuperBlock
  34. accessLock sync.Mutex
  35. }
  36. func NewVolume(dirname string, collection string, id VolumeId, replicaPlacement *ReplicaPlacement) (v *Volume, e error) {
  37. v = &Volume{dir: dirname, Collection: collection, Id: id}
  38. v.SuperBlock = SuperBlock{ReplicaPlacement: replicaPlacement}
  39. e = v.load(true, true)
  40. return
  41. }
  42. func loadVolumeWithoutIndex(dirname string, collection string, id VolumeId) (v *Volume, e error) {
  43. v = &Volume{dir: dirname, Collection: collection, Id: id}
  44. v.SuperBlock = SuperBlock{}
  45. e = v.load(false, false)
  46. return
  47. }
  48. func (v *Volume) FileName() (fileName string) {
  49. if v.Collection == "" {
  50. fileName = path.Join(v.dir, v.Id.String())
  51. } else {
  52. fileName = path.Join(v.dir, v.Collection+"_"+v.Id.String())
  53. }
  54. return
  55. }
  56. func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool) error {
  57. var e error
  58. fileName := v.FileName()
  59. if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists {
  60. if !canRead {
  61. return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
  62. }
  63. if canWrite {
  64. v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
  65. } else {
  66. glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
  67. v.dataFile, e = os.Open(fileName + ".dat")
  68. v.readOnly = true
  69. }
  70. } else {
  71. if createDatIfMissing {
  72. v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
  73. } else {
  74. return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
  75. }
  76. }
  77. if e != nil {
  78. if !os.IsPermission(e) {
  79. return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
  80. }
  81. }
  82. if v.ReplicaPlacement == nil {
  83. e = v.readSuperBlock()
  84. } else {
  85. e = v.maybeWriteSuperBlock()
  86. }
  87. if e == nil && alsoLoadIndex {
  88. if v.readOnly {
  89. if v.ensureConvertIdxToCdb(fileName) {
  90. v.nm, e = OpenCdbMap(fileName + ".cdb")
  91. return e
  92. }
  93. }
  94. var indexFile *os.File
  95. if v.readOnly {
  96. glog.V(1).Infoln("open to read file", fileName+".idx")
  97. if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
  98. return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
  99. }
  100. } else {
  101. glog.V(1).Infoln("open to write file", fileName+".idx")
  102. if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
  103. return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
  104. }
  105. }
  106. glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
  107. if v.nm, e = LoadNeedleMap(indexFile); e != nil {
  108. glog.V(0).Infoln("loading error:", e)
  109. }
  110. }
  111. return e
  112. }
  113. func (v *Volume) Version() Version {
  114. return v.SuperBlock.Version
  115. }
  116. func (v *Volume) Size() int64 {
  117. v.accessLock.Lock()
  118. defer v.accessLock.Unlock()
  119. stat, e := v.dataFile.Stat()
  120. if e == nil {
  121. return stat.Size()
  122. }
  123. glog.V(0).Infof("Failed to read file size %s %s", v.dataFile.Name(), e.Error())
  124. return -1
  125. }
  126. func (v *Volume) Close() {
  127. v.accessLock.Lock()
  128. defer v.accessLock.Unlock()
  129. v.nm.Close()
  130. _ = v.dataFile.Close()
  131. }
  132. func (v *Volume) maybeWriteSuperBlock() error {
  133. stat, e := v.dataFile.Stat()
  134. if e != nil {
  135. glog.V(0).Infof("failed to stat datafile %s: %s", v.dataFile, e.Error())
  136. return e
  137. }
  138. if stat.Size() == 0 {
  139. v.SuperBlock.Version = CurrentVersion
  140. _, e = v.dataFile.Write(v.SuperBlock.Bytes())
  141. if e != nil && os.IsPermission(e) {
  142. //read-only, but zero length - recreate it!
  143. if v.dataFile, e = os.Create(v.dataFile.Name()); e == nil {
  144. if _, e = v.dataFile.Write(v.SuperBlock.Bytes()); e == nil {
  145. v.readOnly = false
  146. }
  147. }
  148. }
  149. }
  150. return e
  151. }
  152. func (v *Volume) readSuperBlock() (err error) {
  153. if _, err = v.dataFile.Seek(0, 0); err != nil {
  154. return fmt.Errorf("cannot seek to the beginning of %s: %s", v.dataFile.Name(), err.Error())
  155. }
  156. header := make([]byte, SuperBlockSize)
  157. if _, e := v.dataFile.Read(header); e != nil {
  158. return fmt.Errorf("cannot read superblock: %s", e.Error())
  159. }
  160. v.SuperBlock, err = ParseSuperBlock(header)
  161. return err
  162. }
  163. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  164. superBlock.Version = Version(header[0])
  165. if superBlock.ReplicaPlacement, err = NewReplicaPlacementFromByte(header[1]); err != nil {
  166. err = fmt.Errorf("cannot read replica type: %s", err.Error())
  167. }
  168. return
  169. }
  170. func (v *Volume) NeedToReplicate() bool {
  171. return v.ReplicaPlacement.GetCopyCount() > 1
  172. }
  173. func (v *Volume) isFileUnchanged(n *Needle) bool {
  174. nv, ok := v.nm.Get(n.Id)
  175. if ok && nv.Offset > 0 {
  176. if _, err := v.dataFile.Seek(int64(nv.Offset)*NeedlePaddingSize, 0); err != nil {
  177. return false
  178. }
  179. oldNeedle := new(Needle)
  180. oldNeedle.Read(v.dataFile, nv.Size, v.Version())
  181. if oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {
  182. n.Size = oldNeedle.Size
  183. return true
  184. }
  185. }
  186. return false
  187. }
  188. func (v *Volume) write(n *Needle) (size uint32, err error) {
  189. if v.readOnly {
  190. err = fmt.Errorf("%s is read-only", v.dataFile)
  191. return
  192. }
  193. v.accessLock.Lock()
  194. defer v.accessLock.Unlock()
  195. if v.isFileUnchanged(n) {
  196. size = n.Size
  197. glog.V(4).Infof("needle is unchanged!")
  198. return
  199. }
  200. var offset int64
  201. if offset, err = v.dataFile.Seek(0, 2); err != nil {
  202. return
  203. }
  204. //ensure file writing starting from aligned positions
  205. if offset%NeedlePaddingSize != 0 {
  206. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  207. if offset, err = v.dataFile.Seek(offset, 0); err != nil {
  208. glog.V(4).Infof("failed to align in datafile %s: %s", v.dataFile.Name(), err.Error())
  209. return
  210. }
  211. }
  212. if size, err = n.Append(v.dataFile, v.Version()); err != nil {
  213. if e := v.dataFile.Truncate(offset); e != nil {
  214. err = fmt.Errorf("%s\ncannot truncate %s: %s", err, v.dataFile, e.Error())
  215. }
  216. return
  217. }
  218. nv, ok := v.nm.Get(n.Id)
  219. if !ok || int64(nv.Offset)*NeedlePaddingSize < offset {
  220. if _, err = v.nm.Put(n.Id, uint32(offset/NeedlePaddingSize), n.Size); err != nil {
  221. glog.V(4).Infof("failed to save in needle map %d: %s", n.Id, err.Error())
  222. }
  223. }
  224. return
  225. }
  226. func (v *Volume) delete(n *Needle) (uint32, error) {
  227. if v.readOnly {
  228. return 0, fmt.Errorf("%s is read-only", v.dataFile)
  229. }
  230. v.accessLock.Lock()
  231. defer v.accessLock.Unlock()
  232. nv, ok := v.nm.Get(n.Id)
  233. //fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  234. if ok {
  235. size := nv.Size
  236. if err := v.nm.Delete(n.Id); err != nil {
  237. return size, err
  238. }
  239. if _, err := v.dataFile.Seek(0, 2); err != nil {
  240. return size, err
  241. }
  242. n.Data = make([]byte, 0)
  243. _, err := n.Append(v.dataFile, v.Version())
  244. return size, err
  245. }
  246. return 0, nil
  247. }
  248. func (v *Volume) read(n *Needle) (int, error) {
  249. v.accessLock.Lock()
  250. defer v.accessLock.Unlock()
  251. nv, ok := v.nm.Get(n.Id)
  252. if ok && nv.Offset > 0 {
  253. if _, err := v.dataFile.Seek(int64(nv.Offset)*NeedlePaddingSize, 0); err != nil {
  254. return -1, err
  255. }
  256. return n.Read(v.dataFile, nv.Size, v.Version())
  257. }
  258. return -1, errors.New("Not Found")
  259. }
  260. func (v *Volume) garbageLevel() float64 {
  261. return float64(v.nm.DeletedSize()) / float64(v.ContentSize())
  262. }
  263. func (v *Volume) Compact() error {
  264. v.accessLock.Lock()
  265. defer v.accessLock.Unlock()
  266. filePath := path.Join(v.dir, v.Id.String())
  267. return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx")
  268. }
  269. func (v *Volume) commitCompact() error {
  270. v.accessLock.Lock()
  271. defer v.accessLock.Unlock()
  272. _ = v.dataFile.Close()
  273. var e error
  274. if e = os.Rename(path.Join(v.dir, v.Id.String()+".cpd"), path.Join(v.dir, v.Id.String()+".dat")); e != nil {
  275. return e
  276. }
  277. if e = os.Rename(path.Join(v.dir, v.Id.String()+".cpx"), path.Join(v.dir, v.Id.String()+".idx")); e != nil {
  278. return e
  279. }
  280. if e = v.load(true, false); e != nil {
  281. return e
  282. }
  283. return nil
  284. }
  285. func (v *Volume) freeze() error {
  286. if v.readOnly {
  287. return nil
  288. }
  289. nm, ok := v.nm.(*NeedleMap)
  290. if !ok {
  291. return nil
  292. }
  293. v.accessLock.Lock()
  294. defer v.accessLock.Unlock()
  295. bn, _ := baseFilename(v.dataFile.Name())
  296. cdbFn := bn + ".cdb"
  297. glog.V(0).Infof("converting %s to %s", nm.indexFile.Name(), cdbFn)
  298. err := DumpNeedleMapToCdb(cdbFn, nm)
  299. if err != nil {
  300. return err
  301. }
  302. if v.nm, err = OpenCdbMap(cdbFn); err != nil {
  303. return err
  304. }
  305. nm.indexFile.Close()
  306. os.Remove(nm.indexFile.Name())
  307. v.readOnly = true
  308. return nil
  309. }
  310. func ScanVolumeFile(dirname string, collection string, id VolumeId,
  311. visitSuperBlock func(SuperBlock) error,
  312. visitNeedle func(n *Needle, offset int64) error) (err error) {
  313. var v *Volume
  314. if v, err = loadVolumeWithoutIndex(dirname, collection, id); err != nil {
  315. return
  316. }
  317. if err = visitSuperBlock(v.SuperBlock); err != nil {
  318. return
  319. }
  320. version := v.Version()
  321. offset := int64(SuperBlockSize)
  322. n, rest, e := ReadNeedleHeader(v.dataFile, version)
  323. if e != nil {
  324. err = fmt.Errorf("cannot read needle header: %s", e)
  325. return
  326. }
  327. for n != nil {
  328. if err = n.ReadNeedleBody(v.dataFile, version, rest); err != nil {
  329. err = fmt.Errorf("cannot read needle body: %s", err)
  330. return
  331. }
  332. if err = visitNeedle(n, offset); err != nil {
  333. return
  334. }
  335. offset += int64(NeedleHeaderSize + rest)
  336. if n, rest, err = ReadNeedleHeader(v.dataFile, version); err != nil {
  337. if err == io.EOF {
  338. return nil
  339. }
  340. return fmt.Errorf("cannot read needle header: %s", err)
  341. }
  342. }
  343. return
  344. }
  345. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err error) {
  346. var (
  347. dst, idx *os.File
  348. )
  349. if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  350. return
  351. }
  352. defer dst.Close()
  353. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  354. return
  355. }
  356. defer idx.Close()
  357. nm := NewNeedleMap(idx)
  358. new_offset := int64(SuperBlockSize)
  359. err = ScanVolumeFile(v.dir, v.Collection, v.Id, func(superBlock SuperBlock) error {
  360. _, err = dst.Write(superBlock.Bytes())
  361. return err
  362. }, func(n *Needle, offset int64) error {
  363. nv, ok := v.nm.Get(n.Id)
  364. //glog.V(0).Infoln("file size is", n.Size, "rest", rest)
  365. if ok && int64(nv.Offset)*NeedlePaddingSize == offset {
  366. if nv.Size > 0 {
  367. if _, err = nm.Put(n.Id, uint32(new_offset/NeedlePaddingSize), n.Size); err != nil {
  368. return fmt.Errorf("cannot put needle: %s", err)
  369. }
  370. if _, err = n.Append(dst, v.Version()); err != nil {
  371. return fmt.Errorf("cannot append needle: %s", err)
  372. }
  373. new_offset += n.DiskSize()
  374. //glog.V(0).Infoln("saving key", n.Id, "volume offset", old_offset, "=>", new_offset, "data_size", n.Size, "rest", rest)
  375. }
  376. }
  377. return nil
  378. })
  379. return
  380. }
  381. func (v *Volume) ContentSize() uint64 {
  382. return v.nm.ContentSize()
  383. }
  384. func checkFile(filename string) (exists, canRead, canWrite bool, modTime time.Time) {
  385. exists = true
  386. fi, err := os.Stat(filename)
  387. if os.IsNotExist(err) {
  388. exists = false
  389. return
  390. }
  391. if fi.Mode()&0400 != 0 {
  392. canRead = true
  393. }
  394. if fi.Mode()&0200 != 0 {
  395. canWrite = true
  396. }
  397. modTime = fi.ModTime()
  398. return
  399. }
  400. func (v *Volume) ensureConvertIdxToCdb(fileName string) (cdbCanRead bool) {
  401. var indexFile *os.File
  402. var e error
  403. _, cdbCanRead, cdbCanWrite, cdbModTime := checkFile(fileName + ".cdb")
  404. _, idxCanRead, _, idxModeTime := checkFile(fileName + ".idx")
  405. if cdbCanRead && cdbModTime.After(idxModeTime) {
  406. return true
  407. }
  408. if !cdbCanWrite {
  409. return false
  410. }
  411. if !idxCanRead {
  412. glog.V(0).Infoln("Can not read file", fileName+".idx!")
  413. return false
  414. }
  415. glog.V(2).Infoln("opening file", fileName+".idx")
  416. if indexFile, e = os.Open(fileName + ".idx"); e != nil {
  417. glog.V(0).Infoln("Failed to read file", fileName+".idx !")
  418. return false
  419. }
  420. defer indexFile.Close()
  421. glog.V(0).Infof("converting %s.idx to %s.cdb", fileName, fileName)
  422. if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
  423. glog.V(0).Infof("error converting %s.idx to %s.cdb: %s", fileName, fileName, e.Error())
  424. return false
  425. }
  426. return true
  427. }