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.

460 lines
12 KiB

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 Index %s.idx: %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 Index %s.idx: %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. stat, e := v.dataFile.Stat()
  118. if e == nil {
  119. return stat.Size()
  120. }
  121. glog.V(0).Infof("Failed to read file size %s %s", v.dataFile.Name(), e.Error())
  122. return -1
  123. }
  124. func (v *Volume) Close() {
  125. v.accessLock.Lock()
  126. defer v.accessLock.Unlock()
  127. v.nm.Close()
  128. _ = v.dataFile.Close()
  129. }
  130. func (v *Volume) maybeWriteSuperBlock() error {
  131. stat, e := v.dataFile.Stat()
  132. if e != nil {
  133. glog.V(0).Infof("failed to stat datafile %s: %s", v.dataFile, e.Error())
  134. return e
  135. }
  136. if stat.Size() == 0 {
  137. v.SuperBlock.Version = CurrentVersion
  138. _, e = v.dataFile.Write(v.SuperBlock.Bytes())
  139. if e != nil && os.IsPermission(e) {
  140. //read-only, but zero length - recreate it!
  141. if v.dataFile, e = os.Create(v.dataFile.Name()); e == nil {
  142. if _, e = v.dataFile.Write(v.SuperBlock.Bytes()); e == nil {
  143. v.readOnly = false
  144. }
  145. }
  146. }
  147. }
  148. return e
  149. }
  150. func (v *Volume) readSuperBlock() (err error) {
  151. if _, err = v.dataFile.Seek(0, 0); err != nil {
  152. return fmt.Errorf("cannot seek to the beginning of %s: %s", v.dataFile.Name(), err.Error())
  153. }
  154. header := make([]byte, SuperBlockSize)
  155. if _, e := v.dataFile.Read(header); e != nil {
  156. return fmt.Errorf("cannot read superblock: %s", e.Error())
  157. }
  158. v.SuperBlock, err = ParseSuperBlock(header)
  159. return err
  160. }
  161. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  162. superBlock.Version = Version(header[0])
  163. if superBlock.ReplicaPlacement, err = NewReplicaPlacementFromByte(header[1]); err != nil {
  164. err = fmt.Errorf("cannot read replica type: %s", err.Error())
  165. }
  166. return
  167. }
  168. func (v *Volume) NeedToReplicate() bool {
  169. return v.ReplicaPlacement.GetCopyCount() > 1
  170. }
  171. func (v *Volume) isFileUnchanged(n *Needle) bool {
  172. nv, ok := v.nm.Get(n.Id)
  173. if ok && nv.Offset > 0 {
  174. oldNeedle := new(Needle)
  175. oldNeedle.Read(v.dataFile, int64(nv.Offset)*NeedlePaddingSize, nv.Size, v.Version())
  176. if oldNeedle.Checksum == n.Checksum && bytes.Equal(oldNeedle.Data, n.Data) {
  177. n.Size = oldNeedle.Size
  178. return true
  179. }
  180. }
  181. return false
  182. }
  183. func (v *Volume) Destroy() (err error) {
  184. if v.readOnly {
  185. err = fmt.Errorf("%s is read-only", v.dataFile)
  186. return
  187. }
  188. v.Close()
  189. err = os.Remove(v.dataFile.Name())
  190. if err != nil {
  191. return
  192. }
  193. err = v.nm.Destroy()
  194. return
  195. }
  196. func (v *Volume) write(n *Needle) (size uint32, err error) {
  197. if v.readOnly {
  198. err = fmt.Errorf("%s is read-only", v.dataFile)
  199. return
  200. }
  201. v.accessLock.Lock()
  202. defer v.accessLock.Unlock()
  203. if v.isFileUnchanged(n) {
  204. size = n.Size
  205. glog.V(4).Infof("needle is unchanged!")
  206. return
  207. }
  208. var offset int64
  209. if offset, err = v.dataFile.Seek(0, 2); err != nil {
  210. return
  211. }
  212. //ensure file writing starting from aligned positions
  213. if offset%NeedlePaddingSize != 0 {
  214. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  215. if offset, err = v.dataFile.Seek(offset, 0); err != nil {
  216. glog.V(4).Infof("failed to align in datafile %s: %s", v.dataFile.Name(), err.Error())
  217. return
  218. }
  219. }
  220. if size, err = n.Append(v.dataFile, v.Version()); err != nil {
  221. if e := v.dataFile.Truncate(offset); e != nil {
  222. err = fmt.Errorf("%s\ncannot truncate %s: %s", err, v.dataFile, e.Error())
  223. }
  224. return
  225. }
  226. nv, ok := v.nm.Get(n.Id)
  227. if !ok || int64(nv.Offset)*NeedlePaddingSize < offset {
  228. if _, err = v.nm.Put(n.Id, uint32(offset/NeedlePaddingSize), n.Size); err != nil {
  229. glog.V(4).Infof("failed to save in needle map %d: %s", n.Id, err.Error())
  230. }
  231. }
  232. return
  233. }
  234. func (v *Volume) delete(n *Needle) (uint32, error) {
  235. if v.readOnly {
  236. return 0, fmt.Errorf("%s is read-only", v.dataFile)
  237. }
  238. v.accessLock.Lock()
  239. defer v.accessLock.Unlock()
  240. nv, ok := v.nm.Get(n.Id)
  241. //fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  242. if ok {
  243. size := nv.Size
  244. if err := v.nm.Delete(n.Id); err != nil {
  245. return size, err
  246. }
  247. if _, err := v.dataFile.Seek(0, 2); err != nil {
  248. return size, err
  249. }
  250. n.Data = make([]byte, 0)
  251. _, err := n.Append(v.dataFile, v.Version())
  252. return size, err
  253. }
  254. return 0, nil
  255. }
  256. func (v *Volume) read(n *Needle) (int, error) {
  257. nv, ok := v.nm.Get(n.Id)
  258. if ok && nv.Offset > 0 {
  259. return n.Read(v.dataFile, int64(nv.Offset)*NeedlePaddingSize, nv.Size, v.Version())
  260. }
  261. return -1, errors.New("Not Found")
  262. }
  263. func (v *Volume) garbageLevel() float64 {
  264. return float64(v.nm.DeletedSize()) / float64(v.ContentSize())
  265. }
  266. func (v *Volume) Compact() error {
  267. v.accessLock.Lock()
  268. defer v.accessLock.Unlock()
  269. filePath := v.FileName()
  270. glog.V(3).Infof("creating copies for volume %d ...", v.Id)
  271. return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx")
  272. }
  273. func (v *Volume) commitCompact() error {
  274. v.accessLock.Lock()
  275. defer v.accessLock.Unlock()
  276. _ = v.dataFile.Close()
  277. var e error
  278. if e = os.Rename(v.FileName()+".cpd", v.FileName()+".dat"); e != nil {
  279. return e
  280. }
  281. if e = os.Rename(v.FileName()+".cpx", v.FileName()+".idx"); e != nil {
  282. return e
  283. }
  284. if e = v.load(true, false); e != nil {
  285. return e
  286. }
  287. return nil
  288. }
  289. func (v *Volume) freeze() error {
  290. if v.readOnly {
  291. return nil
  292. }
  293. nm, ok := v.nm.(*NeedleMap)
  294. if !ok {
  295. return nil
  296. }
  297. v.accessLock.Lock()
  298. defer v.accessLock.Unlock()
  299. bn, _ := baseFilename(v.dataFile.Name())
  300. cdbFn := bn + ".cdb"
  301. glog.V(0).Infof("converting %s to %s", nm.indexFile.Name(), cdbFn)
  302. err := DumpNeedleMapToCdb(cdbFn, nm)
  303. if err != nil {
  304. return err
  305. }
  306. if v.nm, err = OpenCdbMap(cdbFn); err != nil {
  307. return err
  308. }
  309. nm.indexFile.Close()
  310. os.Remove(nm.indexFile.Name())
  311. v.readOnly = true
  312. return nil
  313. }
  314. func ScanVolumeFile(dirname string, collection string, id VolumeId,
  315. visitSuperBlock func(SuperBlock) error,
  316. visitNeedle func(n *Needle, offset int64) error) (err error) {
  317. var v *Volume
  318. if v, err = loadVolumeWithoutIndex(dirname, collection, id); err != nil {
  319. return errors.New("Failed to load volume:" + err.Error())
  320. }
  321. if err = visitSuperBlock(v.SuperBlock); err != nil {
  322. return errors.New("Failed to read super block:" + err.Error())
  323. }
  324. version := v.Version()
  325. offset := int64(SuperBlockSize)
  326. n, rest, e := ReadNeedleHeader(v.dataFile, version, offset)
  327. if e != nil {
  328. err = fmt.Errorf("cannot read needle header: %s", e)
  329. return
  330. }
  331. for n != nil {
  332. if err = n.ReadNeedleBody(v.dataFile, version, offset+int64(NeedleHeaderSize), rest); err != nil {
  333. err = fmt.Errorf("cannot read needle body: %s", err)
  334. return
  335. }
  336. if err = visitNeedle(n, offset); err != nil {
  337. return
  338. }
  339. offset += int64(NeedleHeaderSize) + int64(rest)
  340. if n, rest, err = ReadNeedleHeader(v.dataFile, version, offset); err != nil {
  341. if err == io.EOF {
  342. return nil
  343. }
  344. return fmt.Errorf("cannot read needle header: %s", err)
  345. }
  346. }
  347. return
  348. }
  349. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err error) {
  350. var (
  351. dst, idx *os.File
  352. )
  353. if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  354. return
  355. }
  356. defer dst.Close()
  357. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  358. return
  359. }
  360. defer idx.Close()
  361. nm := NewNeedleMap(idx)
  362. new_offset := int64(SuperBlockSize)
  363. err = ScanVolumeFile(v.dir, v.Collection, v.Id, func(superBlock SuperBlock) error {
  364. _, err = dst.Write(superBlock.Bytes())
  365. return err
  366. }, func(n *Needle, offset int64) error {
  367. nv, ok := v.nm.Get(n.Id)
  368. glog.V(3).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  369. if ok && int64(nv.Offset)*NeedlePaddingSize == offset && nv.Size > 0 {
  370. if _, err = nm.Put(n.Id, uint32(new_offset/NeedlePaddingSize), n.Size); err != nil {
  371. return fmt.Errorf("cannot put needle: %s", err)
  372. }
  373. if _, err = n.Append(dst, v.Version()); err != nil {
  374. return fmt.Errorf("cannot append needle: %s", err)
  375. }
  376. new_offset += n.DiskSize()
  377. glog.V(3).Infoln("saving key", n.Id, "volume offset", offset, "=>", new_offset, "data_size", n.Size)
  378. }
  379. return nil
  380. })
  381. return
  382. }
  383. func (v *Volume) ContentSize() uint64 {
  384. return v.nm.ContentSize()
  385. }
  386. func checkFile(filename string) (exists, canRead, canWrite bool, modTime time.Time) {
  387. exists = true
  388. fi, err := os.Stat(filename)
  389. if os.IsNotExist(err) {
  390. exists = false
  391. return
  392. }
  393. if fi.Mode()&0400 != 0 {
  394. canRead = true
  395. }
  396. if fi.Mode()&0200 != 0 {
  397. canWrite = true
  398. }
  399. modTime = fi.ModTime()
  400. return
  401. }
  402. func (v *Volume) ensureConvertIdxToCdb(fileName string) (cdbCanRead bool) {
  403. var indexFile *os.File
  404. var e error
  405. _, cdbCanRead, cdbCanWrite, cdbModTime := checkFile(fileName + ".cdb")
  406. _, idxCanRead, _, idxModeTime := checkFile(fileName + ".idx")
  407. if cdbCanRead && cdbModTime.After(idxModeTime) {
  408. return true
  409. }
  410. if !cdbCanWrite {
  411. return false
  412. }
  413. if !idxCanRead {
  414. glog.V(0).Infoln("Can not read file", fileName+".idx!")
  415. return false
  416. }
  417. glog.V(2).Infoln("opening file", fileName+".idx")
  418. if indexFile, e = os.Open(fileName + ".idx"); e != nil {
  419. glog.V(0).Infoln("Failed to read file", fileName+".idx !")
  420. return false
  421. }
  422. defer indexFile.Close()
  423. glog.V(0).Infof("converting %s.idx to %s.cdb", fileName, fileName)
  424. if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
  425. glog.V(0).Infof("error converting %s.idx to %s.cdb: %s", fileName, fileName, e.Error())
  426. return false
  427. }
  428. return true
  429. }