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.

363 lines
9.2 KiB

12 years ago
12 years ago
12 years ago
  1. package storage
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "log"
  7. "os"
  8. "path"
  9. "sync"
  10. )
  11. const (
  12. SuperBlockSize = 8
  13. )
  14. type SuperBlock struct {
  15. Version Version
  16. ReplicaType ReplicationType
  17. }
  18. func (s *SuperBlock) Bytes() []byte {
  19. header := make([]byte, SuperBlockSize)
  20. header[0] = byte(s.Version)
  21. header[1] = s.ReplicaType.Byte()
  22. return header
  23. }
  24. type Volume struct {
  25. Id VolumeId
  26. dir string
  27. dataFile *os.File
  28. nm NeedleMapper
  29. readOnly bool
  30. SuperBlock
  31. accessLock sync.Mutex
  32. }
  33. func NewVolume(dirname string, id VolumeId, replicationType ReplicationType) (v *Volume, e error) {
  34. v = &Volume{dir: dirname, Id: id}
  35. v.SuperBlock = SuperBlock{ReplicaType: replicationType}
  36. e = v.load(true)
  37. return
  38. }
  39. func LoadVolumeOnly(dirname string, id VolumeId) (v *Volume, e error) {
  40. v = &Volume{dir: dirname, Id: id}
  41. v.SuperBlock = SuperBlock{ReplicaType: CopyNil}
  42. e = v.load(false)
  43. return
  44. }
  45. func (v *Volume) load(alsoLoadIndex bool) error {
  46. var e error
  47. fileName := path.Join(v.dir, v.Id.String())
  48. v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
  49. if e != nil {
  50. if !os.IsPermission(e) {
  51. return fmt.Errorf("cannot create Volume Data %s.dat: %s", fileName, e)
  52. }
  53. if v.dataFile, e = os.Open(fileName + ".dat"); e != nil {
  54. return fmt.Errorf("cannot open Volume Data %s.dat: %s", fileName, e)
  55. }
  56. log.Printf("opening " + fileName + ".dat in READONLY mode")
  57. v.readOnly = true
  58. }
  59. if v.ReplicaType == CopyNil {
  60. e = v.readSuperBlock()
  61. } else {
  62. e = v.maybeWriteSuperBlock()
  63. }
  64. if e == nil && alsoLoadIndex {
  65. var indexFile *os.File
  66. if v.readOnly {
  67. if indexFile, e = os.Open(fileName + ".idx"); e != nil && !os.IsNotExist(e) {
  68. return fmt.Errorf("cannot open index file %s.idx: %s", fileName, e)
  69. }
  70. if indexFile != nil {
  71. log.Printf("converting %s.idx to %s.cdb", fileName, fileName)
  72. if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
  73. log.Printf("error converting %s.idx to %s.cdb: %s", fileName, fileName)
  74. } else {
  75. indexFile.Close()
  76. os.Remove(indexFile.Name())
  77. indexFile = nil
  78. }
  79. }
  80. v.nm, e = OpenCdbMap(fileName + ".cdb")
  81. return e
  82. } else {
  83. indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644)
  84. if e != nil {
  85. return fmt.Errorf("cannot create Volume Data %s.dat: %s", fileName, e)
  86. }
  87. }
  88. v.nm, e = LoadNeedleMap(indexFile)
  89. }
  90. return e
  91. }
  92. func (v *Volume) Version() Version {
  93. return v.SuperBlock.Version
  94. }
  95. func (v *Volume) Size() int64 {
  96. v.accessLock.Lock()
  97. defer v.accessLock.Unlock()
  98. stat, e := v.dataFile.Stat()
  99. if e == nil {
  100. return stat.Size()
  101. }
  102. fmt.Printf("Failed to read file size %s %s\n", v.dataFile.Name(), e.Error())
  103. return -1
  104. }
  105. func (v *Volume) Close() {
  106. v.accessLock.Lock()
  107. defer v.accessLock.Unlock()
  108. v.nm.Close()
  109. _ = v.dataFile.Close()
  110. }
  111. func (v *Volume) maybeWriteSuperBlock() error {
  112. stat, e := v.dataFile.Stat()
  113. if e != nil {
  114. fmt.Printf("failed to stat datafile %s: %s", v.dataFile, e)
  115. return e
  116. }
  117. if stat.Size() == 0 {
  118. v.SuperBlock.Version = CurrentVersion
  119. _, e = v.dataFile.Write(v.SuperBlock.Bytes())
  120. if e != nil && os.IsPermission(e) {
  121. //read-only, but zero length - recreate it!
  122. if v.dataFile, e = os.Create(v.dataFile.Name()); e == nil {
  123. if _, e = v.dataFile.Write(v.SuperBlock.Bytes()); e == nil {
  124. v.readOnly = false
  125. }
  126. }
  127. }
  128. }
  129. return e
  130. }
  131. func (v *Volume) readSuperBlock() (err error) {
  132. if _, err = v.dataFile.Seek(0, 0); err != nil {
  133. return fmt.Errorf("cannot seek to the beginning of %s: %s", v.dataFile, err)
  134. }
  135. header := make([]byte, SuperBlockSize)
  136. if _, e := v.dataFile.Read(header); e != nil {
  137. return fmt.Errorf("cannot read superblock: %s", e)
  138. }
  139. v.SuperBlock, err = ParseSuperBlock(header)
  140. return err
  141. }
  142. func ParseSuperBlock(header []byte) (superBlock SuperBlock, err error) {
  143. superBlock.Version = Version(header[0])
  144. if superBlock.ReplicaType, err = NewReplicationTypeFromByte(header[1]); err != nil {
  145. err = fmt.Errorf("cannot read replica type: %s", err)
  146. }
  147. return
  148. }
  149. func (v *Volume) NeedToReplicate() bool {
  150. return v.ReplicaType.GetCopyCount() > 1
  151. }
  152. func (v *Volume) write(n *Needle) (size uint32, err error) {
  153. if v.readOnly {
  154. err = fmt.Errorf("%s is read-only", v.dataFile)
  155. return
  156. }
  157. v.accessLock.Lock()
  158. defer v.accessLock.Unlock()
  159. var offset int64
  160. if offset, err = v.dataFile.Seek(0, 2); err != nil {
  161. return
  162. }
  163. //ensure file writing starting from aligned positions
  164. if offset%NeedlePaddingSize != 0 {
  165. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  166. if offset, err = v.dataFile.Seek(offset, 0); err != nil {
  167. return
  168. }
  169. }
  170. if size, err = n.Append(v.dataFile, v.Version()); err != nil {
  171. if e := v.dataFile.Truncate(offset); e != nil {
  172. err = fmt.Errorf("%s\ncannot truncate %s: %s", err, v.dataFile, e)
  173. }
  174. return
  175. }
  176. nv, ok := v.nm.Get(n.Id)
  177. if !ok || int64(nv.Offset)*NeedlePaddingSize < offset {
  178. _, err = v.nm.Put(n.Id, uint32(offset/NeedlePaddingSize), n.Size)
  179. }
  180. return
  181. }
  182. func (v *Volume) delete(n *Needle) (uint32, error) {
  183. if v.readOnly {
  184. return 0, fmt.Errorf("%s is read-only", v.dataFile)
  185. }
  186. v.accessLock.Lock()
  187. defer v.accessLock.Unlock()
  188. nv, ok := v.nm.Get(n.Id)
  189. //fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
  190. if ok {
  191. var err error
  192. if err = v.nm.Delete(n.Id); err != nil {
  193. return nv.Size, err
  194. }
  195. if _, err = v.dataFile.Seek(int64(nv.Offset*NeedlePaddingSize), 0); err != nil {
  196. return nv.Size, err
  197. }
  198. _, err = n.Append(v.dataFile, v.Version())
  199. return nv.Size, err
  200. }
  201. return 0, nil
  202. }
  203. func (v *Volume) read(n *Needle) (int, error) {
  204. v.accessLock.Lock()
  205. defer v.accessLock.Unlock()
  206. nv, ok := v.nm.Get(n.Id)
  207. if ok && nv.Offset > 0 {
  208. if _, err := v.dataFile.Seek(int64(nv.Offset)*NeedlePaddingSize, 0); err != nil {
  209. return -1, err
  210. }
  211. return n.Read(v.dataFile, nv.Size, v.Version())
  212. }
  213. return -1, errors.New("Not Found")
  214. }
  215. func (v *Volume) garbageLevel() float64 {
  216. return float64(v.nm.DeletedSize()) / float64(v.ContentSize())
  217. }
  218. func (v *Volume) compact() error {
  219. v.accessLock.Lock()
  220. defer v.accessLock.Unlock()
  221. filePath := path.Join(v.dir, v.Id.String())
  222. return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx")
  223. }
  224. func (v *Volume) commitCompact() error {
  225. v.accessLock.Lock()
  226. defer v.accessLock.Unlock()
  227. _ = v.dataFile.Close()
  228. var e error
  229. if e = os.Rename(path.Join(v.dir, v.Id.String()+".cpd"), path.Join(v.dir, v.Id.String()+".dat")); e != nil {
  230. return e
  231. }
  232. if e = os.Rename(path.Join(v.dir, v.Id.String()+".cpx"), path.Join(v.dir, v.Id.String()+".idx")); e != nil {
  233. return e
  234. }
  235. if e = v.load(true); e != nil {
  236. return e
  237. }
  238. return nil
  239. }
  240. func (v *Volume) freeze() error {
  241. if v.readOnly {
  242. return nil
  243. }
  244. nm, ok := v.nm.(*NeedleMap)
  245. if !ok {
  246. return nil
  247. }
  248. v.accessLock.Lock()
  249. defer v.accessLock.Unlock()
  250. bn, _ := nakeFilename(v.dataFile.Name())
  251. cdbFn := bn + ".cdb"
  252. log.Printf("converting %s to %s", nm.indexFile.Name(), cdbFn)
  253. err := DumpNeedleMapToCdb(cdbFn, nm)
  254. if err != nil {
  255. return err
  256. }
  257. if v.nm, err = OpenCdbMap(cdbFn); err != nil {
  258. return err
  259. }
  260. nm.indexFile.Close()
  261. os.Remove(nm.indexFile.Name())
  262. v.readOnly = true
  263. return nil
  264. }
  265. func ScanVolumeFile(dirname string, id VolumeId,
  266. visitSuperBlock func(SuperBlock) error,
  267. visitNeedle func(n *Needle, offset uint32) error) (err error) {
  268. var v *Volume
  269. if v, err = LoadVolumeOnly(dirname, id); err != nil {
  270. return
  271. }
  272. if err = visitSuperBlock(v.SuperBlock); err != nil {
  273. return
  274. }
  275. version := v.Version()
  276. offset := uint32(SuperBlockSize)
  277. n, rest, e := ReadNeedleHeader(v.dataFile, version)
  278. if e != nil {
  279. err = fmt.Errorf("cannot read needle header: %s", e)
  280. return
  281. }
  282. for n != nil {
  283. if err = n.ReadNeedleBody(v.dataFile, version, rest); err != nil {
  284. err = fmt.Errorf("cannot read needle body: %s", err)
  285. return
  286. }
  287. if err = visitNeedle(n, offset); err != nil {
  288. return
  289. }
  290. offset += NeedleHeaderSize + rest
  291. if n, rest, err = ReadNeedleHeader(v.dataFile, version); err != nil {
  292. if err == io.EOF {
  293. return nil
  294. }
  295. return fmt.Errorf("cannot read needle header: %s", err)
  296. }
  297. }
  298. return
  299. }
  300. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err error) {
  301. var (
  302. dst, idx *os.File
  303. )
  304. if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644); err != nil {
  305. return
  306. }
  307. defer dst.Close()
  308. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE, 0644); err != nil {
  309. return
  310. }
  311. defer idx.Close()
  312. nm := NewNeedleMap(idx)
  313. new_offset := uint32(SuperBlockSize)
  314. err = ScanVolumeFile(v.dir, v.Id, func(superBlock SuperBlock) error {
  315. _, err = dst.Write(superBlock.Bytes())
  316. return err
  317. }, func(n *Needle, offset uint32) error {
  318. nv, ok := v.nm.Get(n.Id)
  319. //log.Println("file size is", n.Size, "rest", rest)
  320. if ok && nv.Offset*NeedlePaddingSize == offset {
  321. if nv.Size > 0 {
  322. if _, err = nm.Put(n.Id, new_offset/NeedlePaddingSize, n.Size); err != nil {
  323. return fmt.Errorf("cannot put needle: %s", err)
  324. }
  325. if _, err = n.Append(dst, v.Version()); err != nil {
  326. return fmt.Errorf("cannot append needle: %s", err)
  327. }
  328. new_offset += n.DiskSize()
  329. //log.Println("saving key", n.Id, "volume offset", old_offset, "=>", new_offset, "data_size", n.Size, "rest", rest)
  330. }
  331. }
  332. return nil
  333. })
  334. return
  335. }
  336. func (v *Volume) ContentSize() uint64 {
  337. return v.nm.ContentSize()
  338. }