Prevent exponential growth in ~/.influx_history #5460
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR addresses issue #5436
Please note that Influx is using the Liner library for the ReadHistory / AppendHistory / WriteHistory functions.
THE PROBLEM:
When the influx console is started, ReadHistory reads the entire buffer from ~/.influx_history into memory, for up to 1000 lines.
Each time a command is entered into the console, AppendHistory is called. This appends to the history buffer we have in memory which has a limit of 1000 entries as well. So far, so good.
Now things start to get hairy. WriteHistory is called each time a command is entered. Not only does this function ignore the HistoryLimit, but it appends the history buffer in memory to the file. Additionally, when exit() is issued, WriteHistory writes that entire buffer to ~/.influx_history again. You can see how this will cause the file to quickly grow exponentially...
REPRODUCTION
If you want to reproduce the growth yourself:
PROPOSED SOLUTION:
On the liner library example page, it looks like they open the historyFile with os.Open (read-only), and then attempt to recreate the file each time using os.Create() before WriteHistory is called. If the file already exists, os.Create() will truncate it. This prevents the growth problem by using WriteHistory as intended.
I modified the file open function for the ReadHistory call and also closed the handle immediately after finished. I didn't see a need to use defer since the handle to the file won't be reused elsewhere.
I've created a function called saveHistory that calls WriteHistory after clearing the ~/.influx_history file. I added historyFilePath to the CommandLine struct to make this easier. I removed historyFile from the struct since it's no longer used. I replaced the calls to WriteHistory with my saveHistory function.