Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persitence Plugin for exporting storage changes #21

Merged
merged 15 commits into from
Dec 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions StatesDumper/PersistActions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace Neo.Plugins
{
[Flags]
internal enum PersistActions : byte
{
StorageChanges = 0b00000001
}
}
48 changes: 48 additions & 0 deletions StatesDumper/Settings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.Extensions.Configuration;
using System;
using System.Reflection;

namespace Neo.Plugins
{
internal class Settings
{
/// <summary>
/// Amount of storages states (heights) to be dump in a given json file
/// </summary>
public uint BlockCacheSize { get; }
/// <summary>
/// Height to begin storage dump
/// </summary>
public uint HeightToBegin { get; }
/// <summary>
/// Height to begin real-time syncing and dumping on, consequently, dumping every block into a single files
/// </summary>
public uint HeightToStartRealTimeSyncing { get; }
/// <summary>
/// Persisting actions
/// </summary>
public PersistActions PersistAction { get; }

public static Settings Default { get; }

static Settings()
{
Default = new Settings(Assembly.GetExecutingAssembly().GetConfiguration());
}

public Settings(IConfigurationSection section)
{
/// Geting settings for storage changes state dumper
this.BlockCacheSize = GetValueOrDefault(section.GetSection("BlockCacheSize"), 1000u, p => uint.Parse(p));
this.HeightToBegin = GetValueOrDefault(section.GetSection("HeightToBegin"), 0u, p => uint.Parse(p));
this.HeightToStartRealTimeSyncing = GetValueOrDefault(section.GetSection("HeightToStartRealTimeSyncing"), 2883000u, p => uint.Parse(p));
this.PersistAction = GetValueOrDefault(section.GetSection("PersistAction"), PersistActions.StorageChanges, p => (PersistActions)Enum.Parse(typeof(PersistActions), p));
}

public T GetValueOrDefault<T>(IConfigurationSection section, T defaultValue, Func<string, T> selector)
{
if (section.Value == null) return defaultValue;
return selector(section.Value);
}
}
}
75 changes: 74 additions & 1 deletion StatesDumper/StatesDumper.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
using Neo.IO;
using Neo.IO.Caching;
using Neo.IO.Json;
using Neo.Ledger;
using Neo.Persistence;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Neo.Plugins
{
public class StatesDumper : Plugin
public class StatesDumper : Plugin, IPersistencePlugin
{
private readonly JArray bs_cache = new JArray();

private static void Dump<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> states)
where TKey : ISerializable
where TValue : ISerializable
Expand Down Expand Up @@ -63,5 +67,74 @@ private bool OnHelp(string[] args)
Console.Write($"{Name} Commands:\n" + "\tdump storage <key>\n");
return true;
}

public void OnPersist(Snapshot snapshot)
{
if (Settings.Default.PersistAction.HasFlag(PersistActions.StorageChanges))
OnPersistStorage(snapshot);
}

private void OnPersistStorage(Snapshot snapshot)
{
uint blockIndex = snapshot.Height;
if (blockIndex >= Settings.Default.HeightToBegin)
{
string dirPath = "./Storage";
Directory.CreateDirectory(dirPath);
string path = $"{HandlePaths(dirPath, blockIndex)}/dump-block-{blockIndex.ToString()}.json";

JArray array = new JArray();

foreach (DataCache<StorageKey, StorageItem>.Trackable trackable in snapshot.Storages.GetChangeSet())
{
JObject state = new JObject();

switch (trackable.State)
{

case TrackState.Added:
state["state"] = "Added";
state["key"] = trackable.Key.ToArray().ToHexString();
state["value"] = trackable.Item.ToArray().ToHexString();
// Here we have a new trackable.Key and trackable.Item
break;
case TrackState.Changed:
state["state"] = "Changed";
state["key"] = trackable.Key.ToArray().ToHexString();
state["value"] = trackable.Item.ToArray().ToHexString();
break;
case TrackState.Deleted:
state["state"] = "Deleted";
state["key"] = trackable.Key.ToArray().ToHexString();
break;
}
array.Add(state);
}

JObject bs_item = new JObject();
bs_item["block"] = blockIndex;
bs_item["size"] = array.Count;
bs_item["storage"] = array;
bs_cache.Add(bs_item);

if ((blockIndex % Settings.Default.BlockCacheSize == 0) || (blockIndex > Settings.Default.HeightToStartRealTimeSyncing))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this prevent data loss?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the only way to prevent data loss is to save the data every time the block is persisted.

Copy link
Member Author

@vncoelho vncoelho Nov 28, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If BlockCacheSize==1 there will be no data loss.

In our case, we chose it BlockCacheSize==1000 (it is a little faster instead of persisting every block when syncing for the first time) and dumped with ImportPlugin chain.acc.

The chance of data loss is lower when Importing.
That is why there is an additional variable that is HeightToStartRealTimeSyncing which, implicitly, forces BlockCacheSize to 1.

There could be a tool that prints it every block and later deletes the files and merge then.
We currently do it in bash scripts: https://github.com/NeoResearch/neo-tests/blob/master/simple-rpc-node/merge_Storage.sh

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the difference between BlockCacheSize=1 and BlockCacheSize=1000? Is it related to performance?

Copy link
Member Author

@vncoelho vncoelho Nov 30, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The performance was not good when persisting files on every block (in particular, during import), then we created this possible cache.
What do you think, @igormcoelho?

Copy link
Contributor

@igormcoelho igormcoelho Dec 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, reducing disk writes is fundamental for performance... we experimented with BlockCacheSize=1 and it was very slow during block import... the bigger the Cache the better. We found that 1000 was a good compromise between delaying disk writes and still having block offloading to disk at every few seconds (during block import only, after that behavior should go to 1 again, which is enough for every 15 seconds).

{
File.WriteAllText(path, bs_cache.ToString());
bs_cache.Clear();
}
}
}

private static string HandlePaths(string dirPath, uint blockIndex)
{
//Default Parameter
uint storagePerFolder = 100000;
uint folder = (((blockIndex - 1) / storagePerFolder) + 1) * storagePerFolder;
if (blockIndex == 0)
folder = 0;
string dirPathWithBlock = $"{dirPath}/BlockStorage_{folder}";
Directory.CreateDirectory(dirPathWithBlock);
return dirPathWithBlock;
}
}
}
7 changes: 7 additions & 0 deletions StatesDumper/StatesDumper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@
<RootNamespace>Neo.Plugins</RootNamespace>
</PropertyGroup>

<ItemGroup>
<None Update="StatesDumper\config.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Neo" Version="2.9.2" />
</ItemGroup>
Expand Down
8 changes: 8 additions & 0 deletions StatesDumper/StatesDumper/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"PluginConfiguration": {
"PersistAction": "StorageChanges",
"BlockCacheSize": 1000,
"HeightToBegin": 0,
"HeightToRealTimeSyncing": 2883000
}
}