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.

743 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. for {
  173. select {
  174. case <-g.ticker.C:
  175. g.checkHeadSizeLimit()
  176. g.checkTotalSizeLimit()
  177. case <-g.Quit():
  178. return
  179. }
  180. }
  181. }
  182. // NOTE: this function is called manually in tests.
  183. func (g *Group) checkHeadSizeLimit() {
  184. limit := g.HeadSizeLimit()
  185. if limit == 0 {
  186. return
  187. }
  188. size, err := g.Head.Size()
  189. if err != nil {
  190. panic(err)
  191. }
  192. if size >= limit {
  193. g.RotateFile()
  194. }
  195. }
  196. func (g *Group) checkTotalSizeLimit() {
  197. limit := g.TotalSizeLimit()
  198. if limit == 0 {
  199. return
  200. }
  201. gInfo := g.readGroupInfo()
  202. totalSize := gInfo.TotalSize
  203. for i := 0; i < maxFilesToRemove; i++ {
  204. index := gInfo.MinIndex + i
  205. if totalSize < limit {
  206. return
  207. }
  208. if index == gInfo.MaxIndex {
  209. // Special degenerate case, just do nothing.
  210. log.Println("WARNING: Group's head " + g.Head.Path + "may grow without bound")
  211. return
  212. }
  213. pathToRemove := filePathForIndex(g.Head.Path, index, gInfo.MaxIndex)
  214. fileInfo, err := os.Stat(pathToRemove)
  215. if err != nil {
  216. log.Println("WARNING: Failed to fetch info for file @" + pathToRemove)
  217. continue
  218. }
  219. err = os.Remove(pathToRemove)
  220. if err != nil {
  221. log.Println(err)
  222. return
  223. }
  224. totalSize -= fileInfo.Size()
  225. }
  226. }
  227. // RotateFile causes group to close the current head and assign it some index.
  228. // Note it does not create a new head.
  229. func (g *Group) RotateFile() {
  230. g.mtx.Lock()
  231. defer g.mtx.Unlock()
  232. headPath := g.Head.Path
  233. if err := g.Head.closeFile(); err != nil {
  234. panic(err)
  235. }
  236. indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1)
  237. if err := os.Rename(headPath, indexPath); err != nil {
  238. panic(err)
  239. }
  240. g.maxIndex++
  241. }
  242. // NewReader returns a new group reader.
  243. // CONTRACT: Caller must close the returned GroupReader.
  244. func (g *Group) NewReader(index int) (*GroupReader, error) {
  245. r := newGroupReader(g)
  246. err := r.SetIndex(index)
  247. if err != nil {
  248. return nil, err
  249. }
  250. return r, nil
  251. }
  252. // Returns -1 if line comes after, 0 if found, 1 if line comes before.
  253. type SearchFunc func(line string) (int, error)
  254. // Searches for the right file in Group, then returns a GroupReader to start
  255. // streaming lines.
  256. // Returns true if an exact match was found, otherwise returns the next greater
  257. // line that starts with prefix.
  258. // CONTRACT: Caller must close the returned GroupReader
  259. func (g *Group) Search(prefix string, cmp SearchFunc) (*GroupReader, bool, error) {
  260. g.mtx.Lock()
  261. minIndex, maxIndex := g.minIndex, g.maxIndex
  262. g.mtx.Unlock()
  263. // Now minIndex/maxIndex may change meanwhile,
  264. // but it shouldn't be a big deal
  265. // (maybe we'll want to limit scanUntil though)
  266. for {
  267. curIndex := (minIndex + maxIndex + 1) / 2
  268. // Base case, when there's only 1 choice left.
  269. if minIndex == maxIndex {
  270. r, err := g.NewReader(maxIndex)
  271. if err != nil {
  272. return nil, false, err
  273. }
  274. match, err := scanUntil(r, prefix, cmp)
  275. if err != nil {
  276. r.Close()
  277. return nil, false, err
  278. }
  279. return r, match, err
  280. }
  281. // Read starting roughly at the middle file,
  282. // until we find line that has prefix.
  283. r, err := g.NewReader(curIndex)
  284. if err != nil {
  285. return nil, false, err
  286. }
  287. foundIndex, line, err := scanNext(r, prefix)
  288. r.Close()
  289. if err != nil {
  290. return nil, false, err
  291. }
  292. // Compare this line to our search query.
  293. val, err := cmp(line)
  294. if err != nil {
  295. return nil, false, err
  296. }
  297. if val < 0 {
  298. // Line will come later
  299. minIndex = foundIndex
  300. } else if val == 0 {
  301. // Stroke of luck, found the line
  302. r, err := g.NewReader(foundIndex)
  303. if err != nil {
  304. return nil, false, err
  305. }
  306. match, err := scanUntil(r, prefix, cmp)
  307. if !match {
  308. panic("Expected match to be true")
  309. }
  310. if err != nil {
  311. r.Close()
  312. return nil, false, err
  313. }
  314. return r, true, err
  315. } else {
  316. // We passed it
  317. maxIndex = curIndex - 1
  318. }
  319. }
  320. }
  321. // Scans and returns the first line that starts with 'prefix'
  322. // Consumes line and returns it.
  323. func scanNext(r *GroupReader, prefix string) (int, string, error) {
  324. for {
  325. line, err := r.ReadLine()
  326. if err != nil {
  327. return 0, "", err
  328. }
  329. if !strings.HasPrefix(line, prefix) {
  330. continue
  331. }
  332. index := r.CurIndex()
  333. return index, line, nil
  334. }
  335. }
  336. // Returns true iff an exact match was found.
  337. // Pushes line, does not consume it.
  338. func scanUntil(r *GroupReader, prefix string, cmp SearchFunc) (bool, error) {
  339. for {
  340. line, err := r.ReadLine()
  341. if err != nil {
  342. return false, err
  343. }
  344. if !strings.HasPrefix(line, prefix) {
  345. continue
  346. }
  347. val, err := cmp(line)
  348. if err != nil {
  349. return false, err
  350. }
  351. if val < 0 {
  352. continue
  353. } else if val == 0 {
  354. r.PushLine(line)
  355. return true, nil
  356. } else {
  357. r.PushLine(line)
  358. return false, nil
  359. }
  360. }
  361. }
  362. // Searches backwards for the last line in Group with prefix.
  363. // Scans each file forward until the end to find the last match.
  364. func (g *Group) FindLast(prefix string) (match string, found bool, err error) {
  365. g.mtx.Lock()
  366. minIndex, maxIndex := g.minIndex, g.maxIndex
  367. g.mtx.Unlock()
  368. r, err := g.NewReader(maxIndex)
  369. if err != nil {
  370. return "", false, err
  371. }
  372. defer r.Close()
  373. // Open files from the back and read
  374. GROUP_LOOP:
  375. for i := maxIndex; i >= minIndex; i-- {
  376. err := r.SetIndex(i)
  377. if err != nil {
  378. return "", false, err
  379. }
  380. // Scan each line and test whether line matches
  381. for {
  382. line, err := r.ReadLine()
  383. if err == io.EOF {
  384. if found {
  385. return match, found, nil
  386. }
  387. continue GROUP_LOOP
  388. } else if err != nil {
  389. return "", false, err
  390. }
  391. if strings.HasPrefix(line, prefix) {
  392. match = line
  393. found = true
  394. }
  395. if r.CurIndex() > i {
  396. if found {
  397. return match, found, nil
  398. }
  399. continue GROUP_LOOP
  400. }
  401. }
  402. }
  403. return
  404. }
  405. // GroupInfo holds information about the group.
  406. type GroupInfo struct {
  407. MinIndex int // index of the first file in the group, including head
  408. MaxIndex int // index of the last file in the group, including head
  409. TotalSize int64 // total size of the group
  410. HeadSize int64 // size of the head
  411. }
  412. // Returns info after scanning all files in g.Head's dir.
  413. func (g *Group) ReadGroupInfo() GroupInfo {
  414. g.mtx.Lock()
  415. defer g.mtx.Unlock()
  416. return g.readGroupInfo()
  417. }
  418. // Index includes the head.
  419. // CONTRACT: caller should have called g.mtx.Lock
  420. func (g *Group) readGroupInfo() GroupInfo {
  421. groupDir := filepath.Dir(g.Head.Path)
  422. headBase := filepath.Base(g.Head.Path)
  423. var minIndex, maxIndex int = -1, -1
  424. var totalSize, headSize int64 = 0, 0
  425. dir, err := os.Open(groupDir)
  426. if err != nil {
  427. panic(err)
  428. }
  429. defer dir.Close()
  430. fiz, err := dir.Readdir(0)
  431. if err != nil {
  432. panic(err)
  433. }
  434. // For each file in the directory, filter by pattern
  435. for _, fileInfo := range fiz {
  436. if fileInfo.Name() == headBase {
  437. fileSize := fileInfo.Size()
  438. totalSize += fileSize
  439. headSize = fileSize
  440. continue
  441. } else if strings.HasPrefix(fileInfo.Name(), headBase) {
  442. fileSize := fileInfo.Size()
  443. totalSize += fileSize
  444. indexedFilePattern := regexp.MustCompile(`^.+\.([0-9]{3,})$`)
  445. submatch := indexedFilePattern.FindSubmatch([]byte(fileInfo.Name()))
  446. if len(submatch) != 0 {
  447. // Matches
  448. fileIndex, err := strconv.Atoi(string(submatch[1]))
  449. if err != nil {
  450. panic(err)
  451. }
  452. if maxIndex < fileIndex {
  453. maxIndex = fileIndex
  454. }
  455. if minIndex == -1 || fileIndex < minIndex {
  456. minIndex = fileIndex
  457. }
  458. }
  459. }
  460. }
  461. // Now account for the head.
  462. if minIndex == -1 {
  463. // If there were no numbered files,
  464. // then the head is index 0.
  465. minIndex, maxIndex = 0, 0
  466. } else {
  467. // Otherwise, the head file is 1 greater
  468. maxIndex++
  469. }
  470. return GroupInfo{minIndex, maxIndex, totalSize, headSize}
  471. }
  472. func filePathForIndex(headPath string, index int, maxIndex int) string {
  473. if index == maxIndex {
  474. return headPath
  475. }
  476. return fmt.Sprintf("%v.%03d", headPath, index)
  477. }
  478. //--------------------------------------------------------------------------------
  479. // GroupReader provides an interface for reading from a Group.
  480. type GroupReader struct {
  481. *Group
  482. mtx sync.Mutex
  483. curIndex int
  484. curFile *os.File
  485. curReader *bufio.Reader
  486. curLine []byte
  487. }
  488. func newGroupReader(g *Group) *GroupReader {
  489. return &GroupReader{
  490. Group: g,
  491. curIndex: 0,
  492. curFile: nil,
  493. curReader: nil,
  494. curLine: nil,
  495. }
  496. }
  497. // Close closes the GroupReader by closing the cursor file.
  498. func (gr *GroupReader) Close() error {
  499. gr.mtx.Lock()
  500. defer gr.mtx.Unlock()
  501. if gr.curReader != nil {
  502. err := gr.curFile.Close()
  503. gr.curIndex = 0
  504. gr.curReader = nil
  505. gr.curFile = nil
  506. gr.curLine = nil
  507. return err
  508. }
  509. return nil
  510. }
  511. // Read implements io.Reader, reading bytes from the current Reader
  512. // incrementing index until enough bytes are read.
  513. func (gr *GroupReader) Read(p []byte) (n int, err error) {
  514. lenP := len(p)
  515. if lenP == 0 {
  516. return 0, errors.New("given empty slice")
  517. }
  518. gr.mtx.Lock()
  519. defer gr.mtx.Unlock()
  520. // Open file if not open yet
  521. if gr.curReader == nil {
  522. if err = gr.openFile(gr.curIndex); err != nil {
  523. return 0, err
  524. }
  525. }
  526. // Iterate over files until enough bytes are read
  527. var nn int
  528. for {
  529. nn, err = gr.curReader.Read(p[n:])
  530. n += nn
  531. if err == io.EOF {
  532. if n >= lenP {
  533. return n, nil
  534. }
  535. // Open the next file
  536. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  537. return n, err1
  538. }
  539. } else if err != nil {
  540. return n, err
  541. } else if nn == 0 { // empty file
  542. return n, err
  543. }
  544. }
  545. }
  546. // ReadLine reads a line (without delimiter).
  547. // just return io.EOF if no new lines found.
  548. func (gr *GroupReader) ReadLine() (string, error) {
  549. gr.mtx.Lock()
  550. defer gr.mtx.Unlock()
  551. // From PushLine
  552. if gr.curLine != nil {
  553. line := string(gr.curLine)
  554. gr.curLine = nil
  555. return line, nil
  556. }
  557. // Open file if not open yet
  558. if gr.curReader == nil {
  559. err := gr.openFile(gr.curIndex)
  560. if err != nil {
  561. return "", err
  562. }
  563. }
  564. // Iterate over files until line is found
  565. var linePrefix string
  566. for {
  567. bytesRead, err := gr.curReader.ReadBytes('\n')
  568. if err == io.EOF {
  569. // Open the next file
  570. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  571. return "", err1
  572. }
  573. if len(bytesRead) > 0 && bytesRead[len(bytesRead)-1] == byte('\n') {
  574. return linePrefix + string(bytesRead[:len(bytesRead)-1]), nil
  575. }
  576. linePrefix += string(bytesRead)
  577. continue
  578. } else if err != nil {
  579. return "", err
  580. }
  581. return linePrefix + string(bytesRead[:len(bytesRead)-1]), nil
  582. }
  583. }
  584. // IF index > gr.Group.maxIndex, returns io.EOF
  585. // CONTRACT: caller should hold gr.mtx
  586. func (gr *GroupReader) openFile(index int) error {
  587. // Lock on Group to ensure that head doesn't move in the meanwhile.
  588. gr.Group.mtx.Lock()
  589. defer gr.Group.mtx.Unlock()
  590. if index > gr.Group.maxIndex {
  591. return io.EOF
  592. }
  593. curFilePath := filePathForIndex(gr.Head.Path, index, gr.Group.maxIndex)
  594. curFile, err := os.Open(curFilePath)
  595. if err != nil {
  596. return err
  597. }
  598. curReader := bufio.NewReader(curFile)
  599. // Update gr.cur*
  600. if gr.curFile != nil {
  601. gr.curFile.Close() // TODO return error?
  602. }
  603. gr.curIndex = index
  604. gr.curFile = curFile
  605. gr.curReader = curReader
  606. gr.curLine = nil
  607. return nil
  608. }
  609. // PushLine makes the given line the current one, so the next time somebody
  610. // calls ReadLine, this line will be returned.
  611. // panics if called twice without calling ReadLine.
  612. func (gr *GroupReader) PushLine(line string) {
  613. gr.mtx.Lock()
  614. defer gr.mtx.Unlock()
  615. if gr.curLine == nil {
  616. gr.curLine = []byte(line)
  617. } else {
  618. panic("PushLine failed, already have line")
  619. }
  620. }
  621. // CurIndex returns cursor's file index.
  622. func (gr *GroupReader) CurIndex() int {
  623. gr.mtx.Lock()
  624. defer gr.mtx.Unlock()
  625. return gr.curIndex
  626. }
  627. // SetIndex sets the cursor's file index to index by opening a file at this
  628. // position.
  629. func (gr *GroupReader) SetIndex(index int) error {
  630. gr.mtx.Lock()
  631. defer gr.mtx.Unlock()
  632. return gr.openFile(index)
  633. }
  634. //--------------------------------------------------------------------------------
  635. // A simple SearchFunc that assumes that the marker is of form
  636. // <prefix><number>.
  637. // For example, if prefix is '#HEIGHT:', the markers of expected to be of the form:
  638. //
  639. // #HEIGHT:1
  640. // ...
  641. // #HEIGHT:2
  642. // ...
  643. func MakeSimpleSearchFunc(prefix string, target int) SearchFunc {
  644. return func(line string) (int, error) {
  645. if !strings.HasPrefix(line, prefix) {
  646. return -1, fmt.Errorf("Marker line did not have prefix: %v", prefix)
  647. }
  648. i, err := strconv.Atoi(line[len(prefix):])
  649. if err != nil {
  650. return -1, fmt.Errorf("Failed to parse marker line: %v", err.Error())
  651. }
  652. if target < i {
  653. return 1, nil
  654. } else if target == i {
  655. return 0, nil
  656. } else {
  657. return -1, nil
  658. }
  659. }
  660. }