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.

399 lines
10 KiB

12 years ago
11 years ago
12 years ago
11 years ago
11 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.Name())
  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. glog.V(4).Infof("writing needle %s", NewFileIdFromNeedle(v.Id, n).String())
  198. if v.readOnly {
  199. err = fmt.Errorf("%s is read-only", v.dataFile.Name())
  200. return
  201. }
  202. v.accessLock.Lock()
  203. defer v.accessLock.Unlock()
  204. if v.isFileUnchanged(n) {
  205. size = n.Size
  206. glog.V(4).Infof("needle is unchanged!")
  207. return
  208. }
  209. var offset int64
  210. if offset, err = v.dataFile.Seek(0, 2); err != nil {
  211. return
  212. }
  213. //ensure file writing starting from aligned positions
  214. if offset%NeedlePaddingSize != 0 {
  215. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  216. if offset, err = v.dataFile.Seek(offset, 0); err != nil {
  217. glog.V(4).Infof("failed to align in datafile %s: %s", v.dataFile.Name(), err.Error())
  218. return
  219. }
  220. }
  221. if size, err = n.Append(v.dataFile, v.Version()); err != nil {
  222. if e := v.dataFile.Truncate(offset); e != nil {
  223. err = fmt.Errorf("%s\ncannot truncate %s: %s", err, v.dataFile.Name(), e.Error())
  224. }
  225. return
  226. }
  227. nv, ok := v.nm.Get(n.Id)
  228. if !ok || int64(nv.Offset)*NeedlePaddingSize < offset {
  229. if _, err = v.nm.Put(n.Id, uint32(offset/NeedlePaddingSize), n.Size); err != nil {
  230. glog.V(4).Infof("failed to save in needle map %d: %s", n.Id, err.Error())
  231. }
  232. }
  233. return
  234. }
  235. func (v *Volume) delete(n *Needle) (uint32, error) {
  236. glog.V(4).Infof("delete needle %s", NewFileIdFromNeedle(v.Id, n).String())
  237. if v.readOnly {
  238. return 0, fmt.Errorf("%s is read-only", v.dataFile.Name())
  239. }
  240. v.accessLock.Lock()
  241. defer v.accessLock.Unlock()
  242. nv, ok := v.nm.Get(n.Id)
  243. //fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  244. if ok {
  245. size := nv.Size
  246. if err := v.nm.Delete(n.Id); err != nil {
  247. return size, err
  248. }
  249. if _, err := v.dataFile.Seek(0, 2); err != nil {
  250. return size, err
  251. }
  252. n.Data = make([]byte, 0)
  253. _, err := n.Append(v.dataFile, v.Version())
  254. return size, err
  255. }
  256. return 0, nil
  257. }
  258. func (v *Volume) read(n *Needle) (int, error) {
  259. nv, ok := v.nm.Get(n.Id)
  260. if ok && nv.Offset > 0 {
  261. return n.Read(v.dataFile, int64(nv.Offset)*NeedlePaddingSize, nv.Size, v.Version())
  262. }
  263. return -1, errors.New("Not Found")
  264. }
  265. func (v *Volume) freeze() error {
  266. if v.readOnly {
  267. return nil
  268. }
  269. nm, ok := v.nm.(*NeedleMap)
  270. if !ok {
  271. return nil
  272. }
  273. v.accessLock.Lock()
  274. defer v.accessLock.Unlock()
  275. bn, _ := baseFilename(v.dataFile.Name())
  276. cdbFn := bn + ".cdb"
  277. glog.V(0).Infof("converting %s to %s", nm.indexFile.Name(), cdbFn)
  278. err := DumpNeedleMapToCdb(cdbFn, nm)
  279. if err != nil {
  280. return err
  281. }
  282. if v.nm, err = OpenCdbMap(cdbFn); err != nil {
  283. return err
  284. }
  285. nm.indexFile.Close()
  286. os.Remove(nm.indexFile.Name())
  287. v.readOnly = true
  288. return nil
  289. }
  290. func ScanVolumeFile(dirname string, collection string, id VolumeId,
  291. visitSuperBlock func(SuperBlock) error,
  292. readNeedleBody bool,
  293. visitNeedle func(n *Needle, offset int64) error) (err error) {
  294. var v *Volume
  295. if v, err = loadVolumeWithoutIndex(dirname, collection, id); err != nil {
  296. return errors.New("Failed to load volume:" + err.Error())
  297. }
  298. if err = visitSuperBlock(v.SuperBlock); err != nil {
  299. return errors.New("Failed to read super block:" + err.Error())
  300. }
  301. version := v.Version()
  302. offset := int64(SuperBlockSize)
  303. n, rest, e := ReadNeedleHeader(v.dataFile, version, offset)
  304. if e != nil {
  305. err = fmt.Errorf("cannot read needle header: %s", e)
  306. return
  307. }
  308. for n != nil {
  309. if readNeedleBody {
  310. if err = n.ReadNeedleBody(v.dataFile, version, offset+int64(NeedleHeaderSize), rest); err != nil {
  311. err = fmt.Errorf("cannot read needle body: %s", err)
  312. return
  313. }
  314. }
  315. if err = visitNeedle(n, offset); err != nil {
  316. return
  317. }
  318. offset += int64(NeedleHeaderSize) + int64(rest)
  319. if n, rest, err = ReadNeedleHeader(v.dataFile, version, offset); err != nil {
  320. if err == io.EOF {
  321. return nil
  322. }
  323. return fmt.Errorf("cannot read needle header: %s", err)
  324. }
  325. }
  326. return
  327. }
  328. func (v *Volume) ContentSize() uint64 {
  329. return v.nm.ContentSize()
  330. }
  331. func checkFile(filename string) (exists, canRead, canWrite bool, modTime time.Time) {
  332. exists = true
  333. fi, err := os.Stat(filename)
  334. if os.IsNotExist(err) {
  335. exists = false
  336. return
  337. }
  338. if fi.Mode()&0400 != 0 {
  339. canRead = true
  340. }
  341. if fi.Mode()&0200 != 0 {
  342. canWrite = true
  343. }
  344. modTime = fi.ModTime()
  345. return
  346. }
  347. func (v *Volume) ensureConvertIdxToCdb(fileName string) (cdbCanRead bool) {
  348. var indexFile *os.File
  349. var e error
  350. _, cdbCanRead, cdbCanWrite, cdbModTime := checkFile(fileName + ".cdb")
  351. _, idxCanRead, _, idxModeTime := checkFile(fileName + ".idx")
  352. if cdbCanRead && cdbModTime.After(idxModeTime) {
  353. return true
  354. }
  355. if !cdbCanWrite {
  356. return false
  357. }
  358. if !idxCanRead {
  359. glog.V(0).Infoln("Can not read file", fileName+".idx!")
  360. return false
  361. }
  362. glog.V(2).Infoln("opening file", fileName+".idx")
  363. if indexFile, e = os.Open(fileName + ".idx"); e != nil {
  364. glog.V(0).Infoln("Failed to read file", fileName+".idx !")
  365. return false
  366. }
  367. defer indexFile.Close()
  368. glog.V(0).Infof("converting %s.idx to %s.cdb", fileName, fileName)
  369. if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
  370. glog.V(0).Infof("error converting %s.idx to %s.cdb: %s", fileName, fileName, e.Error())
  371. return false
  372. }
  373. return true
  374. }