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.

541 lines
13 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
6 years ago
8 years ago
8 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
6 years ago
8 years ago
8 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
6 years ago
8 years ago
8 years ago
8 years ago
cs: sync WAL more frequently (#3300) As per #3043, this adds a ticker to sync the WAL every 2s while the WAL is running. * Flush WAL every 2s This adds a ticker that flushes the WAL every 2s while the WAL is running. This is related to #3043. * Fix spelling * Increase timeout to 2mins for slower build environments * Make WAL sync interval configurable * Add TODO to replace testChan with more comprehensive testBus * Remove extraneous debug statement * Remove testChan in favour of using system time As per https://github.com/tendermint/tendermint/pull/3300#discussion_r255886586, this removes the `testChan` WAL member and replaces the approach with a system time-oriented one. In this new approach, we keep track of the system time at which each flush and periodic flush successfully occurred. The naming of the various functions is also updated here to be more consistent with "flushing" as opposed to "sync'ing". * Update naming convention and ensure lock for timestamp update * Add Flush method as part of WAL interface Adds a `Flush` method as part of the WAL interface to enforce the idea that we can manually trigger a WAL flush from outside of the WAL. This is employed in the consensus state management to flush the WAL prior to signing votes/proposals, as per https://github.com/tendermint/tendermint/issues/3043#issuecomment-453853630 * Update CHANGELOG_PENDING * Remove mutex approach and replace with DI The dependency injection approach to dealing with testing concerns could allow similar effects to some kind of "testing bus"-based approach. This commit introduces an example of this, where instead of relying on (potentially fragile) timing of things between the code and the test, we inject code into the function under test that can signal the test through a channel. This allows us to avoid the `time.Sleep()`-based approach previously employed. * Update comment on WAL flushing during vote signing Co-Authored-By: thanethomson <connect@thanethomson.com> * Simplify flush interval definition Co-Authored-By: thanethomson <connect@thanethomson.com> * Expand commentary on WAL disk flushing Co-Authored-By: thanethomson <connect@thanethomson.com> * Add broken test to illustrate WAL sync test problem Removes test-related state (dependency injection code) from the WAL data structure and adds test code to illustrate the problem with using `WALGenerateNBlocks` and `wal.SearchForEndHeight` to test periodic sync'ing. * Fix test error messages * Use WAL group buffer size to check for flush A function is added to `libs/autofile/group.go#Group` in order to return the size of the buffered data (i.e. data that has not yet been flushed to disk). The test now checks that, prior to a `time.Sleep`, the group buffer has data in it. After the `time.Sleep` (during which time the periodic flush should have been called), the buffer should be empty. * Remove config root dir removal from #3291 * Add godoc for NewWAL mentioning periodic sync
6 years ago
8 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
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. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "github.com/tendermint/tendermint/libs/service"
  16. )
  17. const (
  18. defaultGroupCheckDuration = 5000 * time.Millisecond
  19. defaultHeadSizeLimit = 10 * 1024 * 1024 // 10MB
  20. defaultTotalSizeLimit = 1 * 1024 * 1024 * 1024 // 1GB
  21. maxFilesToRemove = 4 // needs to be greater than 1
  22. )
  23. /*
  24. You can open a Group to keep restrictions on an AutoFile, like
  25. the maximum size of each chunk, and/or the total amount of bytes
  26. stored in the group.
  27. The first file to be written in the Group.Dir is the head file.
  28. Dir/
  29. - <HeadPath>
  30. Once the Head file reaches the size limit, it will be rotated.
  31. Dir/
  32. - <HeadPath>.000 // First rolled file
  33. - <HeadPath> // New head path, starts empty.
  34. // The implicit index is 001.
  35. As more files are written, the index numbers grow...
  36. Dir/
  37. - <HeadPath>.000 // First rolled file
  38. - <HeadPath>.001 // Second rolled file
  39. - ...
  40. - <HeadPath> // New head path
  41. The Group can also be used to binary-search for some line,
  42. assuming that marker lines are written occasionally.
  43. */
  44. type Group struct {
  45. service.BaseService
  46. ID string
  47. Head *AutoFile // The head AutoFile to write to
  48. headBuf *bufio.Writer
  49. Dir string // Directory that contains .Head
  50. ticker *time.Ticker
  51. mtx sync.Mutex
  52. headSizeLimit int64
  53. totalSizeLimit int64
  54. groupCheckDuration time.Duration
  55. minIndex int // Includes head
  56. maxIndex int // Includes head, where Head will move to
  57. // close this when the processTicks routine is done.
  58. // this ensures we can cleanup the dir after calling Stop
  59. // and the routine won't be trying to access it anymore
  60. doneProcessTicks chan struct{}
  61. // TODO: When we start deleting files, we need to start tracking GroupReaders
  62. // and their dependencies.
  63. }
  64. // OpenGroup creates a new Group with head at headPath. It returns an error if
  65. // it fails to open head file.
  66. func OpenGroup(headPath string, groupOptions ...func(*Group)) (*Group, error) {
  67. dir, err := filepath.Abs(filepath.Dir(headPath))
  68. if err != nil {
  69. return nil, err
  70. }
  71. head, err := OpenAutoFile(headPath)
  72. if err != nil {
  73. return nil, err
  74. }
  75. g := &Group{
  76. ID: "group:" + head.ID,
  77. Head: head,
  78. headBuf: bufio.NewWriterSize(head, 4096*10),
  79. Dir: dir,
  80. headSizeLimit: defaultHeadSizeLimit,
  81. totalSizeLimit: defaultTotalSizeLimit,
  82. groupCheckDuration: defaultGroupCheckDuration,
  83. minIndex: 0,
  84. maxIndex: 0,
  85. doneProcessTicks: make(chan struct{}),
  86. }
  87. for _, option := range groupOptions {
  88. option(g)
  89. }
  90. g.BaseService = *service.NewBaseService(nil, "Group", g)
  91. gInfo := g.readGroupInfo()
  92. g.minIndex = gInfo.MinIndex
  93. g.maxIndex = gInfo.MaxIndex
  94. return g, nil
  95. }
  96. // GroupCheckDuration allows you to overwrite default groupCheckDuration.
  97. func GroupCheckDuration(duration time.Duration) func(*Group) {
  98. return func(g *Group) {
  99. g.groupCheckDuration = duration
  100. }
  101. }
  102. // GroupHeadSizeLimit allows you to overwrite default head size limit - 10MB.
  103. func GroupHeadSizeLimit(limit int64) func(*Group) {
  104. return func(g *Group) {
  105. g.headSizeLimit = limit
  106. }
  107. }
  108. // GroupTotalSizeLimit allows you to overwrite default total size limit of the group - 1GB.
  109. func GroupTotalSizeLimit(limit int64) func(*Group) {
  110. return func(g *Group) {
  111. g.totalSizeLimit = limit
  112. }
  113. }
  114. // OnStart implements service.Service by starting the goroutine that checks file
  115. // and group limits.
  116. func (g *Group) OnStart(ctx context.Context) error {
  117. g.ticker = time.NewTicker(g.groupCheckDuration)
  118. go g.processTicks()
  119. return nil
  120. }
  121. // OnStop implements service.Service by stopping the goroutine described above.
  122. // NOTE: g.Head must be closed separately using Close.
  123. func (g *Group) OnStop() {
  124. g.ticker.Stop()
  125. if err := g.FlushAndSync(); err != nil {
  126. g.Logger.Error("Error flushing to disk", "err", err)
  127. }
  128. }
  129. // Wait blocks until all internal goroutines are finished. Supposed to be
  130. // called after Stop.
  131. func (g *Group) Wait() {
  132. // wait for processTicks routine to finish
  133. <-g.doneProcessTicks
  134. }
  135. // Close closes the head file. The group must be stopped by this moment.
  136. func (g *Group) Close() {
  137. if err := g.FlushAndSync(); err != nil {
  138. g.Logger.Error("Error flushing to disk", "err", err)
  139. }
  140. g.mtx.Lock()
  141. _ = g.Head.closeFile()
  142. g.mtx.Unlock()
  143. }
  144. // HeadSizeLimit returns the current head size limit.
  145. func (g *Group) HeadSizeLimit() int64 {
  146. g.mtx.Lock()
  147. defer g.mtx.Unlock()
  148. return g.headSizeLimit
  149. }
  150. // TotalSizeLimit returns total size limit of the group.
  151. func (g *Group) TotalSizeLimit() int64 {
  152. g.mtx.Lock()
  153. defer g.mtx.Unlock()
  154. return g.totalSizeLimit
  155. }
  156. // MaxIndex returns index of the last file in the group.
  157. func (g *Group) MaxIndex() int {
  158. g.mtx.Lock()
  159. defer g.mtx.Unlock()
  160. return g.maxIndex
  161. }
  162. // MinIndex returns index of the first file in the group.
  163. func (g *Group) MinIndex() int {
  164. g.mtx.Lock()
  165. defer g.mtx.Unlock()
  166. return g.minIndex
  167. }
  168. // Write writes the contents of p into the current head of the group. It
  169. // returns the number of bytes written. If nn < len(p), it also returns an
  170. // error explaining why the write is short.
  171. // NOTE: Writes are buffered so they don't write synchronously
  172. // TODO: Make it halt if space is unavailable
  173. func (g *Group) Write(p []byte) (nn int, err error) {
  174. g.mtx.Lock()
  175. defer g.mtx.Unlock()
  176. return g.headBuf.Write(p)
  177. }
  178. // WriteLine writes line into the current head of the group. It also appends "\n".
  179. // NOTE: Writes are buffered so they don't write synchronously
  180. // TODO: Make it halt if space is unavailable
  181. func (g *Group) WriteLine(line string) error {
  182. g.mtx.Lock()
  183. defer g.mtx.Unlock()
  184. _, err := g.headBuf.Write([]byte(line + "\n"))
  185. return err
  186. }
  187. // Buffered returns the size of the currently buffered data.
  188. func (g *Group) Buffered() int {
  189. g.mtx.Lock()
  190. defer g.mtx.Unlock()
  191. return g.headBuf.Buffered()
  192. }
  193. // FlushAndSync writes any buffered data to the underlying file and commits the
  194. // current content of the file to stable storage (fsync).
  195. func (g *Group) FlushAndSync() error {
  196. g.mtx.Lock()
  197. defer g.mtx.Unlock()
  198. err := g.headBuf.Flush()
  199. if err == nil {
  200. err = g.Head.Sync()
  201. }
  202. return err
  203. }
  204. func (g *Group) processTicks() {
  205. defer close(g.doneProcessTicks)
  206. for {
  207. select {
  208. case <-g.ticker.C:
  209. g.checkHeadSizeLimit()
  210. g.checkTotalSizeLimit()
  211. case <-g.Quit():
  212. return
  213. }
  214. }
  215. }
  216. // NOTE: this function is called manually in tests.
  217. func (g *Group) checkHeadSizeLimit() {
  218. limit := g.HeadSizeLimit()
  219. if limit == 0 {
  220. return
  221. }
  222. size, err := g.Head.Size()
  223. if err != nil {
  224. g.Logger.Error("Group's head may grow without bound", "head", g.Head.Path, "err", err)
  225. return
  226. }
  227. if size >= limit {
  228. g.RotateFile()
  229. }
  230. }
  231. func (g *Group) checkTotalSizeLimit() {
  232. limit := g.TotalSizeLimit()
  233. if limit == 0 {
  234. return
  235. }
  236. gInfo := g.readGroupInfo()
  237. totalSize := gInfo.TotalSize
  238. for i := 0; i < maxFilesToRemove; i++ {
  239. index := gInfo.MinIndex + i
  240. if totalSize < limit {
  241. return
  242. }
  243. if index == gInfo.MaxIndex {
  244. // Special degenerate case, just do nothing.
  245. g.Logger.Error("Group's head may grow without bound", "head", g.Head.Path)
  246. return
  247. }
  248. pathToRemove := filePathForIndex(g.Head.Path, index, gInfo.MaxIndex)
  249. fInfo, err := os.Stat(pathToRemove)
  250. if err != nil {
  251. g.Logger.Error("Failed to fetch info for file", "file", pathToRemove)
  252. continue
  253. }
  254. err = os.Remove(pathToRemove)
  255. if err != nil {
  256. g.Logger.Error("Failed to remove path", "path", pathToRemove)
  257. return
  258. }
  259. totalSize -= fInfo.Size()
  260. }
  261. }
  262. // RotateFile causes group to close the current head and assign it some index.
  263. // Note it does not create a new head.
  264. func (g *Group) RotateFile() {
  265. g.mtx.Lock()
  266. defer g.mtx.Unlock()
  267. headPath := g.Head.Path
  268. if err := g.headBuf.Flush(); err != nil {
  269. panic(err)
  270. }
  271. if err := g.Head.Sync(); err != nil {
  272. panic(err)
  273. }
  274. if err := g.Head.closeFile(); err != nil {
  275. panic(err)
  276. }
  277. indexPath := filePathForIndex(headPath, g.maxIndex, g.maxIndex+1)
  278. if err := os.Rename(headPath, indexPath); err != nil {
  279. panic(err)
  280. }
  281. g.maxIndex++
  282. }
  283. // NewReader returns a new group reader.
  284. // CONTRACT: Caller must close the returned GroupReader.
  285. func (g *Group) NewReader(index int) (*GroupReader, error) {
  286. r := newGroupReader(g)
  287. err := r.SetIndex(index)
  288. if err != nil {
  289. return nil, err
  290. }
  291. return r, nil
  292. }
  293. // GroupInfo holds information about the group.
  294. type GroupInfo struct {
  295. MinIndex int // index of the first file in the group, including head
  296. MaxIndex int // index of the last file in the group, including head
  297. TotalSize int64 // total size of the group
  298. HeadSize int64 // size of the head
  299. }
  300. // Returns info after scanning all files in g.Head's dir.
  301. func (g *Group) ReadGroupInfo() GroupInfo {
  302. g.mtx.Lock()
  303. defer g.mtx.Unlock()
  304. return g.readGroupInfo()
  305. }
  306. // Index includes the head.
  307. // CONTRACT: caller should have called g.mtx.Lock
  308. func (g *Group) readGroupInfo() GroupInfo {
  309. groupDir := filepath.Dir(g.Head.Path)
  310. headBase := filepath.Base(g.Head.Path)
  311. var minIndex, maxIndex int = -1, -1
  312. var totalSize, headSize int64 = 0, 0
  313. dir, err := os.Open(groupDir)
  314. if err != nil {
  315. panic(err)
  316. }
  317. defer dir.Close()
  318. fiz, err := dir.Readdir(0)
  319. if err != nil {
  320. panic(err)
  321. }
  322. // For each file in the directory, filter by pattern
  323. for _, fileInfo := range fiz {
  324. if fileInfo.Name() == headBase {
  325. fileSize := fileInfo.Size()
  326. totalSize += fileSize
  327. headSize = fileSize
  328. continue
  329. } else if strings.HasPrefix(fileInfo.Name(), headBase) {
  330. fileSize := fileInfo.Size()
  331. totalSize += fileSize
  332. indexedFilePattern := regexp.MustCompile(`^.+\.([0-9]{3,})$`)
  333. submatch := indexedFilePattern.FindSubmatch([]byte(fileInfo.Name()))
  334. if len(submatch) != 0 {
  335. // Matches
  336. fileIndex, err := strconv.Atoi(string(submatch[1]))
  337. if err != nil {
  338. panic(err)
  339. }
  340. if maxIndex < fileIndex {
  341. maxIndex = fileIndex
  342. }
  343. if minIndex == -1 || fileIndex < minIndex {
  344. minIndex = fileIndex
  345. }
  346. }
  347. }
  348. }
  349. // Now account for the head.
  350. if minIndex == -1 {
  351. // If there were no numbered files,
  352. // then the head is index 0.
  353. minIndex, maxIndex = 0, 0
  354. } else {
  355. // Otherwise, the head file is 1 greater
  356. maxIndex++
  357. }
  358. return GroupInfo{minIndex, maxIndex, totalSize, headSize}
  359. }
  360. func filePathForIndex(headPath string, index int, maxIndex int) string {
  361. if index == maxIndex {
  362. return headPath
  363. }
  364. return fmt.Sprintf("%v.%03d", headPath, index)
  365. }
  366. //--------------------------------------------------------------------------------
  367. // GroupReader provides an interface for reading from a Group.
  368. type GroupReader struct {
  369. *Group
  370. mtx sync.Mutex
  371. curIndex int
  372. curFile *os.File
  373. curReader *bufio.Reader
  374. curLine []byte
  375. }
  376. func newGroupReader(g *Group) *GroupReader {
  377. return &GroupReader{
  378. Group: g,
  379. curIndex: 0,
  380. curFile: nil,
  381. curReader: nil,
  382. curLine: nil,
  383. }
  384. }
  385. // Close closes the GroupReader by closing the cursor file.
  386. func (gr *GroupReader) Close() error {
  387. gr.mtx.Lock()
  388. defer gr.mtx.Unlock()
  389. if gr.curReader != nil {
  390. err := gr.curFile.Close()
  391. gr.curIndex = 0
  392. gr.curReader = nil
  393. gr.curFile = nil
  394. gr.curLine = nil
  395. return err
  396. }
  397. return nil
  398. }
  399. // Read implements io.Reader, reading bytes from the current Reader
  400. // incrementing index until enough bytes are read.
  401. func (gr *GroupReader) Read(p []byte) (n int, err error) {
  402. lenP := len(p)
  403. if lenP == 0 {
  404. return 0, errors.New("given empty slice")
  405. }
  406. gr.mtx.Lock()
  407. defer gr.mtx.Unlock()
  408. // Open file if not open yet
  409. if gr.curReader == nil {
  410. if err = gr.openFile(gr.curIndex); err != nil {
  411. return 0, err
  412. }
  413. }
  414. // Iterate over files until enough bytes are read
  415. var nn int
  416. for {
  417. nn, err = gr.curReader.Read(p[n:])
  418. n += nn
  419. switch {
  420. case err == io.EOF:
  421. if n >= lenP {
  422. return n, nil
  423. }
  424. // Open the next file
  425. if err1 := gr.openFile(gr.curIndex + 1); err1 != nil {
  426. return n, err1
  427. }
  428. case err != nil:
  429. return n, err
  430. case nn == 0: // empty file
  431. return n, err
  432. }
  433. }
  434. }
  435. // IF index > gr.Group.maxIndex, returns io.EOF
  436. // CONTRACT: caller should hold gr.mtx
  437. func (gr *GroupReader) openFile(index int) error {
  438. // Lock on Group to ensure that head doesn't move in the meanwhile.
  439. gr.Group.mtx.Lock()
  440. defer gr.Group.mtx.Unlock()
  441. if index > gr.Group.maxIndex {
  442. return io.EOF
  443. }
  444. curFilePath := filePathForIndex(gr.Head.Path, index, gr.Group.maxIndex)
  445. curFile, err := os.OpenFile(curFilePath, os.O_RDONLY|os.O_CREATE, autoFilePerms)
  446. if err != nil {
  447. return err
  448. }
  449. curReader := bufio.NewReader(curFile)
  450. // Update gr.cur*
  451. if gr.curFile != nil {
  452. gr.curFile.Close() // TODO return error?
  453. }
  454. gr.curIndex = index
  455. gr.curFile = curFile
  456. gr.curReader = curReader
  457. gr.curLine = nil
  458. return nil
  459. }
  460. // CurIndex returns cursor's file index.
  461. func (gr *GroupReader) CurIndex() int {
  462. gr.mtx.Lock()
  463. defer gr.mtx.Unlock()
  464. return gr.curIndex
  465. }
  466. // SetIndex sets the cursor's file index to index by opening a file at this
  467. // position.
  468. func (gr *GroupReader) SetIndex(index int) error {
  469. gr.mtx.Lock()
  470. defer gr.mtx.Unlock()
  471. return gr.openFile(index)
  472. }