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.

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