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.

741 lines
17 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package autofile
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. cmn "github.com/tendermint/tendermint/libs/common"
  17. )
  18. const (
  19. groupCheckDuration = 5000 * time.Millisecond
  20. defaultHeadSizeLimit = 10 * 1024 * 1024 // 10MB
  21. defaultTotalSizeLimit = 1 * 1024 * 1024 * 1024 // 1GB
  22. maxFilesToRemove = 4 // needs to be greater than 1
  23. )
  24. /*
  25. You can open a Group to keep restrictions on an AutoFile, like
  26. the maximum size of each chunk, and/or the total amount of bytes
  27. stored in the group.
  28. The first file to be written in the Group.Dir is the head file.
  29. Dir/
  30. - <HeadPath>
  31. Once the Head file reaches the size limit, it will be rotated.
  32. Dir/
  33. - <HeadPath>.000 // First rolled file
  34. - <HeadPath> // New head path, starts empty.
  35. // The implicit index is 001.
  36. As more files are written, the index numbers grow...
  37. Dir/
  38. - <HeadPath>.000 // First rolled file
  39. - <HeadPath>.001 // Second rolled file
  40. - ...
  41. - <HeadPath> // New head path
  42. The Group can also be used to binary-search for some line,
  43. assuming that marker lines are written occasionally.
  44. */
  45. type Group struct {
  46. cmn.BaseService
  47. ID string
  48. Head *AutoFile // The head AutoFile to write to
  49. headBuf *bufio.Writer
  50. Dir string // Directory that contains .Head
  51. ticker *time.Ticker
  52. mtx sync.Mutex
  53. headSizeLimit int64
  54. totalSizeLimit int64
  55. minIndex int // Includes head
  56. maxIndex int // Includes head, where Head will move to
  57. // TODO: When we start deleting files, we need to start tracking GroupReaders
  58. // and their dependencies.
  59. }
  60. // OpenGroup creates a new Group with head at headPath. It returns an error if
  61. // it fails to open head file.
  62. func OpenGroup(headPath string) (g *Group, err error) {
  63. dir := path.Dir(headPath)
  64. head, err := OpenAutoFile(headPath)
  65. if err != nil {
  66. return nil, err
  67. }
  68. g = &Group{
  69. ID: "group:" + head.ID,
  70. Head: head,
  71. headBuf: bufio.NewWriterSize(head, 4096*10),
  72. Dir: dir,
  73. headSizeLimit: defaultHeadSizeLimit,
  74. totalSizeLimit: defaultTotalSizeLimit,
  75. minIndex: 0,
  76. maxIndex: 0,
  77. }
  78. g.BaseService = *cmn.NewBaseService(nil, "Group", g)
  79. gInfo := g.readGroupInfo()
  80. g.minIndex = gInfo.MinIndex
  81. g.maxIndex = gInfo.MaxIndex
  82. return
  83. }
  84. // OnStart implements Service by starting the goroutine that checks file and
  85. // group limits.
  86. func (g *Group) OnStart() error {
  87. g.ticker = time.NewTicker(groupCheckDuration)
  88. go g.processTicks()
  89. return nil
  90. }
  91. // OnStop implements Service by stopping the goroutine described above.
  92. // NOTE: g.Head must be closed separately using Close.
  93. func (g *Group) OnStop() {
  94. g.ticker.Stop()
  95. g.Flush() // flush any uncommitted data
  96. }
  97. // Close closes the head file. The group must be stopped by this moment.
  98. func (g *Group) Close() {
  99. g.Flush() // flush any uncommitted data
  100. g.mtx.Lock()
  101. _ = g.Head.closeFile()
  102. g.mtx.Unlock()
  103. }
  104. // SetHeadSizeLimit allows you to overwrite default head size limit - 10MB.
  105. func (g *Group) SetHeadSizeLimit(limit int64) {
  106. g.mtx.Lock()
  107. g.headSizeLimit = limit
  108. g.mtx.Unlock()
  109. }
  110. // HeadSizeLimit returns the current head size limit.
  111. func (g *Group) HeadSizeLimit() int64 {
  112. g.mtx.Lock()
  113. defer g.mtx.Unlock()
  114. return g.headSizeLimit
  115. }
  116. // SetTotalSizeLimit allows you to overwrite default total size limit of the
  117. // group - 1GB.
  118. func (g *Group) SetTotalSizeLimit(limit int64) {
  119. g.mtx.Lock()
  120. g.totalSizeLimit = limit
  121. g.mtx.Unlock()
  122. }
  123. // TotalSizeLimit returns total size limit of the group.
  124. func (g *Group) TotalSizeLimit() int64 {
  125. g.mtx.Lock()
  126. defer g.mtx.Unlock()
  127. return g.totalSizeLimit
  128. }
  129. // MaxIndex returns index of the last file in the group.
  130. func (g *Group) MaxIndex() int {
  131. g.mtx.Lock()
  132. defer g.mtx.Unlock()
  133. return g.maxIndex
  134. }
  135. // MinIndex returns index of the first file in the group.
  136. func (g *Group) MinIndex() int {
  137. g.mtx.Lock()
  138. defer g.mtx.Unlock()
  139. return g.minIndex
  140. }
  141. // Write writes the contents of p into the current head of the group. It
  142. // returns the number of bytes written. If nn < len(p), it also returns an
  143. // error explaining why the write is short.
  144. // NOTE: Writes are buffered so they don't write synchronously
  145. // TODO: Make it halt if space is unavailable
  146. func (g *Group) Write(p []byte) (nn int, err error) {
  147. g.mtx.Lock()
  148. defer g.mtx.Unlock()
  149. return g.headBuf.Write(p)
  150. }
  151. // WriteLine writes line into the current head of the group. It also appends "\n".
  152. // NOTE: Writes are buffered so they don't write synchronously
  153. // TODO: Make it halt if space is unavailable
  154. func (g *Group) WriteLine(line string) error {
  155. g.mtx.Lock()
  156. defer g.mtx.Unlock()
  157. _, err := g.headBuf.Write([]byte(line + "\n"))
  158. return err
  159. }
  160. // Flush writes any buffered data to the underlying file and commits the
  161. // current content of the file to stable storage.
  162. func (g *Group) Flush() error {
  163. g.mtx.Lock()
  164. defer g.mtx.Unlock()
  165. err := g.headBuf.Flush()
  166. if err == nil {
  167. err = g.Head.Sync()
  168. }
  169. return err
  170. }
  171. func (g *Group) processTicks() {
  172. select {
  173. case <-g.ticker.C:
  174. g.checkHeadSizeLimit()
  175. g.checkTotalSizeLimit()
  176. case <-g.Quit():
  177. return
  178. }
  179. }
  180. // NOTE: this function is called manually in tests.
  181. func (g *Group) checkHeadSizeLimit() {
  182. limit := g.HeadSizeLimit()
  183. if limit == 0 {
  184. return
  185. }
  186. size, err := g.Head.Size()
  187. if err != nil {
  188. panic(err)
  189. }
  190. if size >= limit {
  191. g.RotateFile()
  192. }
  193. }
  194. func (g *Group) checkTotalSizeLimit() {
  195. limit := g.TotalSizeLimit()
  196. if limit == 0 {
  197. return
  198. }
  199. gInfo := g.readGroupInfo()
  200. totalSize := gInfo.TotalSize
  201. for i := 0; i < maxFilesToRemove; i++ {
  202. index := gInfo.MinIndex + i
  203. if totalSize < limit {
  204. return
  205. }
  206. if index == gInfo.MaxIndex {
  207. // Special degenerate case, just do nothing.
  208. log.Println("WARNING: Group's head " + g.Head.Path + "may grow without bound")
  209. return
  210. }
  211. pathToRemove := filePathForIndex(g.Head.Path, index, gInfo.MaxIndex)
  212. fileInfo, err := os.Stat(pathToRemove)
  213. if err != nil {
  214. log.Println("WARNING: Failed to fetch info for file @" + pathToRemove)
  215. continue
  216. }
  217. err = os.Remove(pathToRemove)
  218. if err != nil {
  219. log.Println(err)
  220. return
  221. }
  222. totalSize -= fileInfo.Size()
  223. }
  224. }
  225. // RotateFile causes group to close the current head and assign it some index.
  226. // Note it does not create a new head.
  227. func (g *Group) RotateFile() {
  228. g.mtx.Lock()
  229. defer g.mtx.Unlock()
  230. headPath := g.Head.Path
  231. if err := g.Head.closeFile(); err != nil {
  232. panic(err)
  233. }
  234. indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1)
  235. if err := os.Rename(headPath, indexPath); err != nil {
  236. panic(err)
  237. }
  238. g.maxIndex++
  239. }
  240. // NewReader returns a new group reader.
  241. // CONTRACT: Caller must close the returned GroupReader.
  242. func (g *Group) NewReader(index int) (*GroupReader, error) {
  243. r := newGroupReader(g)
  244. err := r.SetIndex(index)
  245. if err != nil {
  246. return nil, err
  247. }
  248. return r, nil
  249. }
  250. // Returns -1 if line comes after, 0 if found, 1 if line comes before.
  251. type SearchFunc func(line string) (int, error)
  252. // Searches for the right file in Group, then returns a GroupReader to start
  253. // streaming lines.
  254. // Returns true if an exact match was found, otherwise returns the next greater
  255. // line that starts with prefix.
  256. // CONTRACT: Caller must close the returned GroupReader
  257. func (g *Group) Search(prefix string, cmp SearchFunc) (*GroupReader, bool, error) {
  258. g.mtx.Lock()
  259. minIndex, maxIndex := g.minIndex, g.maxIndex
  260. g.mtx.Unlock()
  261. // Now minIndex/maxIndex may change meanwhile,
  262. // but it shouldn't be a big deal
  263. // (maybe we'll want to limit scanUntil though)
  264. for {
  265. curIndex := (minIndex + maxIndex + 1) / 2
  266. // Base case, when there's only 1 choice left.
  267. if minIndex == maxIndex {
  268. r, err := g.NewReader(maxIndex)
  269. if err != nil {
  270. return nil, false, err
  271. }
  272. match, err := scanUntil(r, prefix, cmp)
  273. if err != nil {
  274. r.Close()
  275. return nil, false, err
  276. }
  277. return r, match, err
  278. }
  279. // Read starting roughly at the middle file,
  280. // until we find line that has prefix.
  281. r, err := g.NewReader(curIndex)
  282. if err != nil {
  283. return nil, false, err
  284. }
  285. foundIndex, line, err := scanNext(r, prefix)
  286. r.Close()
  287. if err != nil {
  288. return nil, false, err
  289. }
  290. // Compare this line to our search query.
  291. val, err := cmp(line)
  292. if err != nil {
  293. return nil, false, err
  294. }
  295. if val < 0 {
  296. // Line will come later
  297. minIndex = foundIndex
  298. } else if val == 0 {
  299. // Stroke of luck, found the line
  300. r, err := g.NewReader(foundIndex)
  301. if err != nil {
  302. return nil, false, err
  303. }
  304. match, err := scanUntil(r, prefix, cmp)
  305. if !match {
  306. panic("Expected match to be true")
  307. }
  308. if err != nil {
  309. r.Close()
  310. return nil, false, err
  311. }
  312. return r, true, err
  313. } else {
  314. // We passed it
  315. maxIndex = curIndex - 1
  316. }
  317. }
  318. }
  319. // Scans and returns the first line that starts with 'prefix'
  320. // Consumes line and returns it.
  321. func scanNext(r *GroupReader, prefix string) (int, string, error) {
  322. for {
  323. line, err := r.ReadLine()
  324. if err != nil {
  325. return 0, "", err
  326. }
  327. if !strings.HasPrefix(line, prefix) {
  328. continue
  329. }
  330. index := r.CurIndex()
  331. return index, line, nil
  332. }
  333. }
  334. // Returns true iff an exact match was found.
  335. // Pushes line, does not consume it.
  336. func scanUntil(r *GroupReader, prefix string, cmp SearchFunc) (bool, error) {
  337. for {
  338. line, err := r.ReadLine()
  339. if err != nil {
  340. return false, err
  341. }
  342. if !strings.HasPrefix(line, prefix) {
  343. continue
  344. }
  345. val, err := cmp(line)
  346. if err != nil {
  347. return false, err
  348. }
  349. if val < 0 {
  350. continue
  351. } else if val == 0 {
  352. r.PushLine(line)
  353. return true, nil
  354. } else {
  355. r.PushLine(line)
  356. return false, nil
  357. }
  358. }
  359. }
  360. // Searches backwards for the last line in Group with prefix.
  361. // Scans each file forward until the end to find the last match.
  362. func (g *Group) FindLast(prefix string) (match string, found bool, err error) {
  363. g.mtx.Lock()
  364. minIndex, maxIndex := g.minIndex, g.maxIndex
  365. g.mtx.Unlock()
  366. r, err := g.NewReader(maxIndex)
  367. if err != nil {
  368. return "", false, err
  369. }
  370. defer r.Close()
  371. // Open files from the back and read
  372. GROUP_LOOP:
  373. for i := maxIndex; i >= minIndex; i-- {
  374. err := r.SetIndex(i)
  375. if err != nil {
  376. return "", false, err
  377. }
  378. // Scan each line and test whether line matches
  379. for {
  380. line, err := r.ReadLine()
  381. if err == io.EOF {
  382. if found {
  383. return match, found, nil
  384. }
  385. continue GROUP_LOOP
  386. } else if err != nil {
  387. return "", false, err
  388. }
  389. if strings.HasPrefix(line, prefix) {
  390. match = line
  391. found = true
  392. }
  393. if r.CurIndex() > i {
  394. if found {
  395. return match, found, nil
  396. }
  397. continue GROUP_LOOP
  398. }
  399. }
  400. }
  401. return
  402. }
  403. // GroupInfo holds information about the group.
  404. type GroupInfo struct {
  405. MinIndex int // index of the first file in the group, including head
  406. MaxIndex int // index of the last file in the group, including head
  407. TotalSize int64 // total size of the group
  408. HeadSize int64 // size of the head
  409. }
  410. // Returns info after scanning all files in g.Head's dir.
  411. func (g *Group) ReadGroupInfo() GroupInfo {
  412. g.mtx.Lock()
  413. defer g.mtx.Unlock()
  414. return g.readGroupInfo()
  415. }
  416. // Index includes the head.
  417. // CONTRACT: caller should have called g.mtx.Lock
  418. func (g *Group) readGroupInfo() GroupInfo {
  419. groupDir := filepath.Dir(g.Head.Path)
  420. headBase := filepath.Base(g.Head.Path)
  421. var minIndex, maxIndex int = -1, -1
  422. var totalSize, headSize int64 = 0, 0
  423. dir, err := os.Open(groupDir)
  424. if err != nil {
  425. panic(err)
  426. }
  427. defer dir.Close()
  428. fiz, err := dir.Readdir(0)
  429. if err != nil {
  430. panic(err)
  431. }
  432. // For each file in the directory, filter by pattern
  433. for _, fileInfo := range fiz {
  434. if fileInfo.Name() == headBase {
  435. fileSize := fileInfo.Size()
  436. totalSize += fileSize
  437. headSize = fileSize
  438. continue
  439. } else if strings.HasPrefix(fileInfo.Name(), headBase) {
  440. fileSize := fileInfo.Size()
  441. totalSize += fileSize
  442. indexedFilePattern := regexp.MustCompile(`^.+\.([0-9]{3,})$`)
  443. submatch := indexedFilePattern.FindSubmatch([]byte(fileInfo.Name()))
  444. if len(submatch) != 0 {
  445. // Matches
  446. fileIndex, err := strconv.Atoi(string(submatch[1]))
  447. if err != nil {
  448. panic(err)
  449. }
  450. if maxIndex < fileIndex {
  451. maxIndex = fileIndex
  452. }
  453. if minIndex == -1 || fileIndex < minIndex {
  454. minIndex = fileIndex
  455. }
  456. }
  457. }
  458. }
  459. // Now account for the head.
  460. if minIndex == -1 {
  461. // If there were no numbered files,
  462. // then the head is index 0.
  463. minIndex, maxIndex = 0, 0
  464. } else {
  465. // Otherwise, the head file is 1 greater
  466. maxIndex++
  467. }
  468. return GroupInfo{minIndex, maxIndex, totalSize, headSize}
  469. }
  470. func filePathForIndex(headPath string, index int, maxIndex int) string {
  471. if index == maxIndex {
  472. return headPath
  473. }
  474. return fmt.Sprintf("%v.%03d", headPath, index)
  475. }
  476. //--------------------------------------------------------------------------------
  477. // GroupReader provides an interface for reading from a Group.
  478. type GroupReader struct {
  479. *Group
  480. mtx sync.Mutex
  481. curIndex int
  482. curFile *os.File
  483. curReader *bufio.Reader
  484. curLine []byte
  485. }
  486. func newGroupReader(g *Group) *GroupReader {
  487. return &GroupReader{
  488. Group: g,
  489. curIndex: 0,
  490. curFile: nil,
  491. curReader: nil,
  492. curLine: nil,
  493. }
  494. }
  495. // Close closes the GroupReader by closing the cursor file.
  496. func (gr *GroupReader) Close() error {
  497. gr.mtx.Lock()
  498. defer gr.mtx.Unlock()
  499. if gr.curReader != nil {
  500. err := gr.curFile.Close()
  501. gr.curIndex = 0
  502. gr.curReader = nil
  503. gr.curFile = nil
  504. gr.curLine = nil
  505. return err
  506. }
  507. return nil
  508. }
  509. // Read implements io.Reader, reading bytes from the current Reader
  510. // incrementing index until enough bytes are read.
  511. func (gr *GroupReader) Read(p []byte) (n int, err error) {
  512. lenP := len(p)
  513. if lenP == 0 {
  514. return 0, errors.New("given empty slice")
  515. }
  516. gr.mtx.Lock()
  517. defer gr.mtx.Unlock()
  518. // Open file if not open yet
  519. if gr.curReader == nil {
  520. if err = gr.openFile(gr.curIndex); err != nil {
  521. return 0, err
  522. }
  523. }
  524. // Iterate over files until enough bytes are read
  525. var nn int
  526. for {
  527. nn, err = gr.curReader.Read(p[n:])
  528. n += nn
  529. if err == io.EOF {
  530. if n >= lenP {
  531. return n, nil
  532. }
  533. // Open the next file
  534. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  535. return n, err1
  536. }
  537. } else if err != nil {
  538. return n, err
  539. } else if nn == 0 { // empty file
  540. return n, err
  541. }
  542. }
  543. }
  544. // ReadLine reads a line (without delimiter).
  545. // just return io.EOF if no new lines found.
  546. func (gr *GroupReader) ReadLine() (string, error) {
  547. gr.mtx.Lock()
  548. defer gr.mtx.Unlock()
  549. // From PushLine
  550. if gr.curLine != nil {
  551. line := string(gr.curLine)
  552. gr.curLine = nil
  553. return line, nil
  554. }
  555. // Open file if not open yet
  556. if gr.curReader == nil {
  557. err := gr.openFile(gr.curIndex)
  558. if err != nil {
  559. return "", err
  560. }
  561. }
  562. // Iterate over files until line is found
  563. var linePrefix string
  564. for {
  565. bytesRead, err := gr.curReader.ReadBytes('\n')
  566. if err == io.EOF {
  567. // Open the next file
  568. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  569. return "", err1
  570. }
  571. if len(bytesRead) > 0 && bytesRead[len(bytesRead)-1] == byte('\n') {
  572. return linePrefix + string(bytesRead[:len(bytesRead)-1]), nil
  573. }
  574. linePrefix += string(bytesRead)
  575. continue
  576. } else if err != nil {
  577. return "", err
  578. }
  579. return linePrefix + string(bytesRead[:len(bytesRead)-1]), nil
  580. }
  581. }
  582. // IF index > gr.Group.maxIndex, returns io.EOF
  583. // CONTRACT: caller should hold gr.mtx
  584. func (gr *GroupReader) openFile(index int) error {
  585. // Lock on Group to ensure that head doesn't move in the meanwhile.
  586. gr.Group.mtx.Lock()
  587. defer gr.Group.mtx.Unlock()
  588. if index > gr.Group.maxIndex {
  589. return io.EOF
  590. }
  591. curFilePath := filePathForIndex(gr.Head.Path, index, gr.Group.maxIndex)
  592. curFile, err := os.Open(curFilePath)
  593. if err != nil {
  594. return err
  595. }
  596. curReader := bufio.NewReader(curFile)
  597. // Update gr.cur*
  598. if gr.curFile != nil {
  599. gr.curFile.Close() // TODO return error?
  600. }
  601. gr.curIndex = index
  602. gr.curFile = curFile
  603. gr.curReader = curReader
  604. gr.curLine = nil
  605. return nil
  606. }
  607. // PushLine makes the given line the current one, so the next time somebody
  608. // calls ReadLine, this line will be returned.
  609. // panics if called twice without calling ReadLine.
  610. func (gr *GroupReader) PushLine(line string) {
  611. gr.mtx.Lock()
  612. defer gr.mtx.Unlock()
  613. if gr.curLine == nil {
  614. gr.curLine = []byte(line)
  615. } else {
  616. panic("PushLine failed, already have line")
  617. }
  618. }
  619. // CurIndex returns cursor's file index.
  620. func (gr *GroupReader) CurIndex() int {
  621. gr.mtx.Lock()
  622. defer gr.mtx.Unlock()
  623. return gr.curIndex
  624. }
  625. // SetIndex sets the cursor's file index to index by opening a file at this
  626. // position.
  627. func (gr *GroupReader) SetIndex(index int) error {
  628. gr.mtx.Lock()
  629. defer gr.mtx.Unlock()
  630. return gr.openFile(index)
  631. }
  632. //--------------------------------------------------------------------------------
  633. // A simple SearchFunc that assumes that the marker is of form
  634. // <prefix><number>.
  635. // For example, if prefix is '#HEIGHT:', the markers of expected to be of the form:
  636. //
  637. // #HEIGHT:1
  638. // ...
  639. // #HEIGHT:2
  640. // ...
  641. func MakeSimpleSearchFunc(prefix string, target int) SearchFunc {
  642. return func(line string) (int, error) {
  643. if !strings.HasPrefix(line, prefix) {
  644. return -1, fmt.Errorf("Marker line did not have prefix: %v", prefix)
  645. }
  646. i, err := strconv.Atoi(line[len(prefix):])
  647. if err != nil {
  648. return -1, fmt.Errorf("Failed to parse marker line: %v", err.Error())
  649. }
  650. if target < i {
  651. return 1, nil
  652. } else if target == i {
  653. return 0, nil
  654. } else {
  655. return -1, nil
  656. }
  657. }
  658. }