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.

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