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. . "github.com/tendermint/tmlibs/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. 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. func OpenGroup(headPath string) (g *Group, err error) {
  61. dir := path.Dir(headPath)
  62. head, err := OpenAutoFile(headPath)
  63. if err != nil {
  64. return nil, err
  65. }
  66. g = &Group{
  67. ID: "group:" + head.ID,
  68. Head: head,
  69. headBuf: bufio.NewWriterSize(head, 4096*10),
  70. Dir: dir,
  71. ticker: time.NewTicker(groupCheckDuration),
  72. headSizeLimit: defaultHeadSizeLimit,
  73. totalSizeLimit: defaultTotalSizeLimit,
  74. minIndex: 0,
  75. maxIndex: 0,
  76. }
  77. g.BaseService = *NewBaseService(nil, "Group", g)
  78. gInfo := g.readGroupInfo()
  79. g.minIndex = gInfo.MinIndex
  80. g.maxIndex = gInfo.MaxIndex
  81. return
  82. }
  83. func (g *Group) OnStart() error {
  84. g.BaseService.OnStart()
  85. go g.processTicks()
  86. return nil
  87. }
  88. // NOTE: g.Head must be closed separately
  89. func (g *Group) OnStop() {
  90. g.BaseService.OnStop()
  91. g.ticker.Stop()
  92. }
  93. // SetHeadSizeLimit allows you to overwrite default head size limit - 10MB.
  94. func (g *Group) SetHeadSizeLimit(limit int64) {
  95. g.mtx.Lock()
  96. g.headSizeLimit = limit
  97. g.mtx.Unlock()
  98. }
  99. // HeadSizeLimit returns the current head size limit.
  100. func (g *Group) HeadSizeLimit() int64 {
  101. g.mtx.Lock()
  102. defer g.mtx.Unlock()
  103. return g.headSizeLimit
  104. }
  105. // SetTotalSizeLimit allows you to overwrite default total size limit of the
  106. // group - 1GB.
  107. func (g *Group) SetTotalSizeLimit(limit int64) {
  108. g.mtx.Lock()
  109. g.totalSizeLimit = limit
  110. g.mtx.Unlock()
  111. }
  112. // TotalSizeLimit returns total size limit of the group.
  113. func (g *Group) TotalSizeLimit() int64 {
  114. g.mtx.Lock()
  115. defer g.mtx.Unlock()
  116. return g.totalSizeLimit
  117. }
  118. // MaxIndex returns index of the last file in the group.
  119. func (g *Group) MaxIndex() int {
  120. g.mtx.Lock()
  121. defer g.mtx.Unlock()
  122. return g.maxIndex
  123. }
  124. // MinIndex returns index of the first file in the group.
  125. func (g *Group) MinIndex() int {
  126. g.mtx.Lock()
  127. defer g.mtx.Unlock()
  128. return g.minIndex
  129. }
  130. // Write writes the contents of p into the current head of the group. It
  131. // returns the number of bytes written. If nn < len(p), it also returns an
  132. // error explaining why the write is short.
  133. // NOTE: Writes are buffered so they don't write synchronously
  134. // TODO: Make it halt if space is unavailable
  135. func (g *Group) Write(p []byte) (nn int, err error) {
  136. g.mtx.Lock()
  137. defer g.mtx.Unlock()
  138. return g.headBuf.Write(p)
  139. }
  140. // WriteLine writes line into the current head of the group. It also appends "\n".
  141. // NOTE: Writes are buffered so they don't write synchronously
  142. // TODO: Make it halt if space is unavailable
  143. func (g *Group) WriteLine(line string) error {
  144. g.mtx.Lock()
  145. defer g.mtx.Unlock()
  146. _, err := g.headBuf.Write([]byte(line + "\n"))
  147. return err
  148. }
  149. // Flush writes any buffered data to the underlying file and commits the
  150. // current content of the file to stable storage.
  151. func (g *Group) Flush() error {
  152. g.mtx.Lock()
  153. defer g.mtx.Unlock()
  154. err := g.headBuf.Flush()
  155. if err == nil {
  156. err = g.Head.Sync()
  157. }
  158. return err
  159. }
  160. func (g *Group) processTicks() {
  161. for {
  162. _, ok := <-g.ticker.C
  163. if !ok {
  164. return // Done.
  165. }
  166. g.checkHeadSizeLimit()
  167. g.checkTotalSizeLimit()
  168. }
  169. }
  170. // NOTE: for testing
  171. func (g *Group) stopTicker() {
  172. g.ticker.Stop()
  173. }
  174. // NOTE: this function is called manually in tests.
  175. func (g *Group) checkHeadSizeLimit() {
  176. limit := g.HeadSizeLimit()
  177. if limit == 0 {
  178. return
  179. }
  180. size, err := g.Head.Size()
  181. if err != nil {
  182. panic(err)
  183. }
  184. if size >= limit {
  185. g.RotateFile()
  186. }
  187. }
  188. func (g *Group) checkTotalSizeLimit() {
  189. limit := g.TotalSizeLimit()
  190. if limit == 0 {
  191. return
  192. }
  193. gInfo := g.readGroupInfo()
  194. totalSize := gInfo.TotalSize
  195. for i := 0; i < maxFilesToRemove; i++ {
  196. index := gInfo.MinIndex + i
  197. if totalSize < limit {
  198. return
  199. }
  200. if index == gInfo.MaxIndex {
  201. // Special degenerate case, just do nothing.
  202. log.Println("WARNING: Group's head " + g.Head.Path + "may grow without bound")
  203. return
  204. }
  205. pathToRemove := filePathForIndex(g.Head.Path, index, gInfo.MaxIndex)
  206. fileInfo, err := os.Stat(pathToRemove)
  207. if err != nil {
  208. log.Println("WARNING: Failed to fetch info for file @" + pathToRemove)
  209. continue
  210. }
  211. err = os.Remove(pathToRemove)
  212. if err != nil {
  213. log.Println(err)
  214. return
  215. }
  216. totalSize -= fileInfo.Size()
  217. }
  218. }
  219. // RotateFile causes group to close the current head and assign it some index.
  220. // Note it does not create a new head.
  221. func (g *Group) RotateFile() {
  222. g.mtx.Lock()
  223. defer g.mtx.Unlock()
  224. headPath := g.Head.Path
  225. if err := g.Head.closeFile(); err != nil {
  226. panic(err)
  227. }
  228. indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1)
  229. if err := os.Rename(headPath, indexPath); err != nil {
  230. panic(err)
  231. }
  232. g.maxIndex += 1
  233. }
  234. // NewReader returns a new group reader.
  235. // CONTRACT: Caller must close the returned GroupReader.
  236. func (g *Group) NewReader(index int) (*GroupReader, error) {
  237. r := newGroupReader(g)
  238. err := r.SetIndex(index)
  239. if err != nil {
  240. return nil, err
  241. } else {
  242. return r, nil
  243. }
  244. }
  245. // Returns -1 if line comes after, 0 if found, 1 if line comes before.
  246. type SearchFunc func(line string) (int, error)
  247. // Searches for the right file in Group, then returns a GroupReader to start
  248. // streaming lines.
  249. // Returns true if an exact match was found, otherwise returns the next greater
  250. // line that starts with prefix.
  251. // CONTRACT: Caller must close the returned GroupReader
  252. func (g *Group) Search(prefix string, cmp SearchFunc) (*GroupReader, bool, error) {
  253. g.mtx.Lock()
  254. minIndex, maxIndex := g.minIndex, g.maxIndex
  255. g.mtx.Unlock()
  256. // Now minIndex/maxIndex may change meanwhile,
  257. // but it shouldn't be a big deal
  258. // (maybe we'll want to limit scanUntil though)
  259. for {
  260. curIndex := (minIndex + maxIndex + 1) / 2
  261. // Base case, when there's only 1 choice left.
  262. if minIndex == maxIndex {
  263. r, err := g.NewReader(maxIndex)
  264. if err != nil {
  265. return nil, false, err
  266. }
  267. match, err := scanUntil(r, prefix, cmp)
  268. if err != nil {
  269. r.Close()
  270. return nil, false, err
  271. } else {
  272. return r, match, err
  273. }
  274. }
  275. // Read starting roughly at the middle file,
  276. // until we find line that has prefix.
  277. r, err := g.NewReader(curIndex)
  278. if err != nil {
  279. return nil, false, err
  280. }
  281. foundIndex, line, err := scanNext(r, prefix)
  282. r.Close()
  283. if err != nil {
  284. return nil, false, err
  285. }
  286. // Compare this line to our search query.
  287. val, err := cmp(line)
  288. if err != nil {
  289. return nil, false, err
  290. }
  291. if val < 0 {
  292. // Line will come later
  293. minIndex = foundIndex
  294. } else if val == 0 {
  295. // Stroke of luck, found the line
  296. r, err := g.NewReader(foundIndex)
  297. if err != nil {
  298. return nil, false, err
  299. }
  300. match, err := scanUntil(r, prefix, cmp)
  301. if !match {
  302. panic("Expected match to be true")
  303. }
  304. if err != nil {
  305. r.Close()
  306. return nil, false, err
  307. } else {
  308. return r, true, err
  309. }
  310. } else {
  311. // We passed it
  312. maxIndex = curIndex - 1
  313. }
  314. }
  315. }
  316. // Scans and returns the first line that starts with 'prefix'
  317. // Consumes line and returns it.
  318. func scanNext(r *GroupReader, prefix string) (int, string, error) {
  319. for {
  320. line, err := r.ReadLine()
  321. if err != nil {
  322. return 0, "", err
  323. }
  324. if !strings.HasPrefix(line, prefix) {
  325. continue
  326. }
  327. index := r.CurIndex()
  328. return index, line, nil
  329. }
  330. }
  331. // Returns true iff an exact match was found.
  332. // Pushes line, does not consume it.
  333. func scanUntil(r *GroupReader, prefix string, cmp SearchFunc) (bool, error) {
  334. for {
  335. line, err := r.ReadLine()
  336. if err != nil {
  337. return false, err
  338. }
  339. if !strings.HasPrefix(line, prefix) {
  340. continue
  341. }
  342. val, err := cmp(line)
  343. if err != nil {
  344. return false, err
  345. }
  346. if val < 0 {
  347. continue
  348. } else if val == 0 {
  349. r.PushLine(line)
  350. return true, nil
  351. } else {
  352. r.PushLine(line)
  353. return false, nil
  354. }
  355. }
  356. }
  357. // Searches backwards for the last line in Group with prefix.
  358. // Scans each file forward until the end to find the last match.
  359. func (g *Group) FindLast(prefix string) (match string, found bool, err error) {
  360. g.mtx.Lock()
  361. minIndex, maxIndex := g.minIndex, g.maxIndex
  362. g.mtx.Unlock()
  363. r, err := g.NewReader(maxIndex)
  364. if err != nil {
  365. return "", false, err
  366. }
  367. defer r.Close()
  368. // Open files from the back and read
  369. GROUP_LOOP:
  370. for i := maxIndex; i >= minIndex; i-- {
  371. err := r.SetIndex(i)
  372. if err != nil {
  373. return "", false, err
  374. }
  375. // Scan each line and test whether line matches
  376. for {
  377. line, err := r.ReadLine()
  378. if err == io.EOF {
  379. if found {
  380. return match, found, nil
  381. } else {
  382. continue GROUP_LOOP
  383. }
  384. } else if err != nil {
  385. return "", false, err
  386. }
  387. if strings.HasPrefix(line, prefix) {
  388. match = line
  389. found = true
  390. }
  391. if r.CurIndex() > i {
  392. if found {
  393. return match, found, nil
  394. } else {
  395. continue GROUP_LOOP
  396. }
  397. }
  398. }
  399. }
  400. return
  401. }
  402. // GroupInfo holds information about the group.
  403. type GroupInfo struct {
  404. MinIndex int // index of the first file in the group, including head
  405. MaxIndex int // index of the last file in the group, including head
  406. TotalSize int64 // total size of the group
  407. HeadSize int64 // size of the head
  408. }
  409. // Returns info after scanning all files in g.Head's dir.
  410. func (g *Group) ReadGroupInfo() GroupInfo {
  411. g.mtx.Lock()
  412. defer g.mtx.Unlock()
  413. return g.readGroupInfo()
  414. }
  415. // Index includes the head.
  416. // CONTRACT: caller should have called g.mtx.Lock
  417. func (g *Group) readGroupInfo() GroupInfo {
  418. groupDir := filepath.Dir(g.Head.Path)
  419. headBase := filepath.Base(g.Head.Path)
  420. var minIndex, maxIndex int = -1, -1
  421. var totalSize, headSize int64 = 0, 0
  422. dir, err := os.Open(groupDir)
  423. if err != nil {
  424. panic(err)
  425. }
  426. defer dir.Close()
  427. fiz, err := dir.Readdir(0)
  428. if err != nil {
  429. panic(err)
  430. }
  431. // For each file in the directory, filter by pattern
  432. for _, fileInfo := range fiz {
  433. if fileInfo.Name() == headBase {
  434. fileSize := fileInfo.Size()
  435. totalSize += fileSize
  436. headSize = fileSize
  437. continue
  438. } else if strings.HasPrefix(fileInfo.Name(), headBase) {
  439. fileSize := fileInfo.Size()
  440. totalSize += fileSize
  441. indexedFilePattern := regexp.MustCompile(`^.+\.([0-9]{3,})$`)
  442. submatch := indexedFilePattern.FindSubmatch([]byte(fileInfo.Name()))
  443. if len(submatch) != 0 {
  444. // Matches
  445. fileIndex, err := strconv.Atoi(string(submatch[1]))
  446. if err != nil {
  447. panic(err)
  448. }
  449. if maxIndex < fileIndex {
  450. maxIndex = fileIndex
  451. }
  452. if minIndex == -1 || fileIndex < minIndex {
  453. minIndex = fileIndex
  454. }
  455. }
  456. }
  457. }
  458. // Now account for the head.
  459. if minIndex == -1 {
  460. // If there were no numbered files,
  461. // then the head is index 0.
  462. minIndex, maxIndex = 0, 0
  463. } else {
  464. // Otherwise, the head file is 1 greater
  465. maxIndex += 1
  466. }
  467. return GroupInfo{minIndex, maxIndex, totalSize, headSize}
  468. }
  469. func filePathForIndex(headPath string, index int, maxIndex int) string {
  470. if index == maxIndex {
  471. return headPath
  472. } else {
  473. return fmt.Sprintf("%v.%03d", headPath, index)
  474. }
  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. } else {
  507. return nil
  508. }
  509. }
  510. // Read implements io.Reader, reading bytes from the current Reader
  511. // incrementing index until enough bytes are read.
  512. func (gr *GroupReader) Read(p []byte) (n int, err error) {
  513. lenP := len(p)
  514. if lenP == 0 {
  515. return 0, errors.New("given empty slice")
  516. }
  517. gr.mtx.Lock()
  518. defer gr.mtx.Unlock()
  519. // Open file if not open yet
  520. if gr.curReader == nil {
  521. if err = gr.openFile(gr.curIndex); err != nil {
  522. return 0, err
  523. }
  524. }
  525. // Iterate over files until enough bytes are read
  526. var nn int
  527. for {
  528. nn, err = gr.curReader.Read(p[n:])
  529. n += nn
  530. if err == io.EOF {
  531. if n >= lenP {
  532. return n, nil
  533. } else { // Open the next file
  534. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  535. return n, err1
  536. }
  537. }
  538. } else if err != nil {
  539. return n, err
  540. } else if nn == 0 { // empty file
  541. return n, err
  542. }
  543. }
  544. }
  545. // ReadLine reads a line (without delimiter).
  546. // just return io.EOF if no new lines found.
  547. func (gr *GroupReader) ReadLine() (string, error) {
  548. gr.mtx.Lock()
  549. defer gr.mtx.Unlock()
  550. // From PushLine
  551. if gr.curLine != nil {
  552. line := string(gr.curLine)
  553. gr.curLine = nil
  554. return line, nil
  555. }
  556. // Open file if not open yet
  557. if gr.curReader == nil {
  558. err := gr.openFile(gr.curIndex)
  559. if err != nil {
  560. return "", err
  561. }
  562. }
  563. // Iterate over files until line is found
  564. var linePrefix string
  565. for {
  566. bytesRead, err := gr.curReader.ReadBytes('\n')
  567. if err == io.EOF {
  568. // Open the next file
  569. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  570. return "", err1
  571. }
  572. if len(bytesRead) > 0 && bytesRead[len(bytesRead)-1] == byte('\n') {
  573. return linePrefix + string(bytesRead[:len(bytesRead)-1]), nil
  574. } else {
  575. linePrefix += string(bytesRead)
  576. continue
  577. }
  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, errors.New(Fmt("Marker line did not have prefix: %v", prefix))
  647. }
  648. i, err := strconv.Atoi(line[len(prefix):])
  649. if err != nil {
  650. return -1, errors.New(Fmt("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. }