Datei: StressTests/StressTest/Program.cs
Last Commit (9de6a8c)
| 1 | -- File didn't exist -- |
New Commit (bbf1d57)
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Diagnostics; |
| 4 | using System.Linq; |
| 5 | using System.Threading; |
| 6 | using System.Threading.Tasks; |
| 7 | using Microsoft.Extensions.Configuration; |
| 8 | using StressTestClasses; |
| 9 | |
| 10 | namespace StressTest |
| 11 | { |
| 12 | ····/// <summary> |
| 13 | ····/// Stress test for NDO: many workers create, change, query and delete objects concurrently |
| 14 | ····/// using the async API of PersistenceManager and VirtualTable. |
| 15 | ····/// </summary> |
| 16 | ····/// <remarks> |
| 17 | ····/// Exit codes: 0 = no errors, 1 = errors, 2 = cancelled, 3 = setup failed. |
| 18 | ····/// </remarks> |
| 19 | ····class Program |
| 20 | ····{ |
| 21 | ········static readonly Dictionary<string, string> switchMappings = new Dictionary<string, string> |
| 22 | ········{ |
| 23 | ············["--provider"] = "StressTest:Provider", |
| 24 | ············["-p"] = "StressTest:Provider", |
| 25 | ············["--connection"] = "StressTest:ConnectionString", |
| 26 | ············["-c"] = "StressTest:ConnectionString", |
| 27 | ············["--threads"] = "StressTest:Threads", |
| 28 | ············["-t"] = "StressTest:Threads", |
| 29 | ············["--iterations"] = "StressTest:Iterations", |
| 30 | ············["-i"] = "StressTest:Iterations", |
| 31 | ············["--duration"] = "StressTest:DurationSeconds", |
| 32 | ············["-d"] = "StressTest:DurationSeconds", |
| 33 | ············["--lines"] = "StressTest:LinesPerOrder", |
| 34 | ············["--tags"] = "StressTest:TagCount", |
| 35 | ············["--transactionMode"] = "StressTest:TransactionMode", |
| 36 | ············["--isolationLevel"] = "StressTest:IsolationLevel", |
| 37 | ············["--sharedMapping"] = "StressTest:SharedMapping", |
| 38 | ············["--recreateSchema"] = "StressTest:RecreateSchema", |
| 39 | ············["--dropSchema"] = "StressTest:DropSchemaAfterTest", |
| 40 | ············["--stopOnFirstError"] = "StressTest:StopOnFirstError", |
| 41 | ············["--maxErrors"] = "StressTest:MaxErrorsToPrint", |
| 42 | ········}; |
| 43 | |
| 44 | ········static async Task<int> Main( string[] args ) |
| 45 | ········{ |
| 46 | ············if (args.Contains( "--help" ) || args.Contains( "-h" ) || args.Contains( "-?" )) |
| 47 | ············{ |
| 48 | ················PrintHelp(); |
| 49 | ················return 0; |
| 50 | ············} |
| 51 | |
| 52 | ············StressTestOptions options; |
| 53 | ············try |
| 54 | ············{ |
| 55 | ················options = ReadOptions( args ); |
| 56 | ················options.Validate(); |
| 57 | ············} |
| 58 | ············catch (Exception ex) |
| 59 | ············{ |
| 60 | ················Console.Error.WriteLine( "Configuration error: " + ex.Message ); |
| 61 | ················Console.Error.WriteLine( "Use --help to see the options." ); |
| 62 | ················return 3; |
| 63 | ············} |
| 64 | |
| 65 | ············Console.WriteLine( "NDO stress test" ); |
| 66 | ············Console.WriteLine( options ); |
| 67 | ············Console.WriteLine(); |
| 68 | |
| 69 | ············using var cts = new CancellationTokenSource(); |
| 70 | ············Console.CancelKeyPress += ( s, e ) => |
| 71 | ············{ |
| 72 | ················e.Cancel = true; |
| 73 | ················Console.WriteLine( "Cancelling..." ); |
| 74 | ················cts.Cancel(); |
| 75 | ············}; |
| 76 | |
| 77 | ············// Avoid the slow thread injection of the thread pool, which would limit the concurrency at the beginning |
| 78 | ············ThreadPool.GetMinThreads( out int minWorker, out int minIo ); |
| 79 | ············ThreadPool.SetMinThreads( Math.Max( minWorker, options.Threads * 2 ), Math.Max( minIo, options.Threads * 2 ) ); |
| 80 | |
| 81 | ············TestDatabase db; |
| 82 | ············int[] tagIds; |
| 83 | ············TestDatabase.RowCounts before; |
| 84 | ············try |
| 85 | ············{ |
| 86 | ················db = new TestDatabase( options ); |
| 87 | ················if (options.RecreateSchema) |
| 88 | ················{ |
| 89 | ····················Console.WriteLine( "Creating the schema..." ); |
| 90 | ····················await db.DropSchemaAsync( cts.Token ); |
| 91 | ····················await db.CreateSchemaAsync( cts.Token ); |
| 92 | ················} |
| 93 | ················tagIds = await GetOrCreateTagsAsync( db, options.TagCount, cts.Token ); |
| 94 | ················before = await db.GetRowCountsAsync( cts.Token ); |
| 95 | ················Console.WriteLine( "Rows before the test: " + before ); |
| 96 | ············} |
| 97 | ············catch (Exception ex) |
| 98 | ············{ |
| 99 | ················Console.Error.WriteLine( "Setup failed:" ); |
| 100 | ················Console.Error.WriteLine( ex ); |
| 101 | ················return 3; |
| 102 | ············} |
| 103 | |
| 104 | ············var statistics = new Statistics(); |
| 105 | ············string runId = Guid.NewGuid().ToString( "N" ).Substring( 0, 8 ); |
| 106 | ············DateTime? endTime = options.DurationSeconds > 0 ? DateTime.UtcNow.AddSeconds( options.DurationSeconds ) : (DateTime?) null; |
| 107 | |
| 108 | ············Console.WriteLine( $"Starting {options.Threads} workers (run id {runId})..." ); |
| 109 | ············var stopwatch = Stopwatch.StartNew(); |
| 110 | ············var tasks = Enumerable.Range( 0, options.Threads ).Select( workerNo => Task.Run( async () => |
| 111 | ············{ |
| 112 | ················try |
| 113 | ················{ |
| 114 | ····················await new Worker( workerNo, db, options, statistics, tagIds, runId ).RunAsync( endTime, cts.Token ); |
| 115 | ················} |
| 116 | ················catch |
| 117 | ················{ |
| 118 | ····················// StopOnFirstError: stop the other workers |
| 119 | ····················cts.Cancel(); |
| 120 | ····················throw; |
| 121 | ················} |
| 122 | ············} ) ).ToArray(); |
| 123 | |
| 124 | ············Task all = Task.WhenAll( tasks ); |
| 125 | ············while (!all.IsCompleted) |
| 126 | ············{ |
| 127 | ················await Task.WhenAny( all, Task.Delay( TimeSpan.FromSeconds( Math.Max( 1, options.ProgressIntervalSeconds ) ) ) ); |
| 128 | ················Console.WriteLine( $"[{stopwatch.Elapsed:hh\\:mm\\:ss}] iterations ok: {statistics.SuccessfulIterations}, failed: {statistics.FailedIterations}" ); |
| 129 | ············} |
| 130 | ············stopwatch.Stop(); |
| 131 | |
| 132 | ············try |
| 133 | ············{ |
| 134 | ················await all; |
| 135 | ············} |
| 136 | ············catch |
| 137 | ············{ |
| 138 | ················// The errors are reported by the statistics |
| 139 | ············} |
| 140 | |
| 141 | ············bool cancelled = cts.IsCancellationRequested && !options.StopOnFirstError; |
| 142 | |
| 143 | ············Console.WriteLine(); |
| 144 | ············Console.WriteLine( $"Elapsed: {stopwatch.Elapsed}" ); |
| 145 | ············Console.WriteLine( $"Iterations ok: {statistics.SuccessfulIterations}, failed: {statistics.FailedIterations}" ); |
| 146 | ············Console.WriteLine( $"Iterations/s: {statistics.SuccessfulIterations / stopwatch.Elapsed.TotalSeconds:F1}" ); |
| 147 | ············Console.WriteLine(); |
| 148 | ············Console.WriteLine( statistics.GetOperationReport( stopwatch.Elapsed ) ); |
| 149 | |
| 150 | ············bool consistent = true; |
| 151 | ············try |
| 152 | ············{ |
| 153 | ················var after = await db.GetRowCountsAsync(); |
| 154 | ················Console.WriteLine( "Rows after the test:··" + after ); |
| 155 | ················// Each successful iteration deletes all objects it has created. |
| 156 | ················// If iterations failed, there might be remaining objects, so the check makes no sense. |
| 157 | ················if (statistics.FailedIterations == 0 && !cancelled) |
| 158 | ················{ |
| 159 | ····················consistent = after.Customers == before.Customers |
| 160 | ························&& after.Orders == before.Orders |
| 161 | ························&& after.OrderLines == before.OrderLines |
| 162 | ························&& after.Tags == before.Tags |
| 163 | ························&& after.MappingTableEntries == before.MappingTableEntries; |
| 164 | ····················if (!consistent) |
| 165 | ························Console.WriteLine( "ERROR: The row counts after the test differ from the row counts before the test." ); |
| 166 | ················} |
| 167 | ············} |
| 168 | ············catch (Exception ex) |
| 169 | ············{ |
| 170 | ················consistent = false; |
| 171 | ················Console.WriteLine( "ERROR: Can't read the row counts after the test:" ); |
| 172 | ················Console.WriteLine( ex ); |
| 173 | ············} |
| 174 | |
| 175 | ············if (statistics.ErrorCount > 0) |
| 176 | ············{ |
| 177 | ················Console.WriteLine(); |
| 178 | ················Console.WriteLine( statistics.GetErrorReport( options.MaxErrorsToPrint ) ); |
| 179 | ············} |
| 180 | |
| 181 | ············bool success = statistics.ErrorCount == 0 && consistent && !cancelled; |
| 182 | ············if (success && options.DropSchemaAfterTest) |
| 183 | ············{ |
| 184 | ················Console.WriteLine( "Dropping the schema..." ); |
| 185 | ················await db.DropSchemaAsync(); |
| 186 | ············} |
| 187 | |
| 188 | ············Console.WriteLine(); |
| 189 | ············if (cancelled) |
| 190 | ············{ |
| 191 | ················Console.WriteLine( "CANCELLED" ); |
| 192 | ················return 2; |
| 193 | ············} |
| 194 | ············Console.WriteLine( success ? "SUCCESS" : "FAILED" ); |
| 195 | ············return success ? 0 : 1; |
| 196 | ········} |
| 197 | |
| 198 | ········static StressTestOptions ReadOptions( string[] args ) |
| 199 | ········{ |
| 200 | ············IConfiguration config = new ConfigurationBuilder() |
| 201 | ················.SetBasePath( AppContext.BaseDirectory ) |
| 202 | ················.AddJsonFile( "appsettings.json", optional: false ) |
| 203 | ················// For local connection strings, which shouldn't be committed |
| 204 | ················.AddJsonFile( "appsettings.local.json", optional: true ) |
| 205 | ················.AddEnvironmentVariables( "NDOSTRESS_" ) |
| 206 | ················.AddCommandLine( args, switchMappings ) |
| 207 | ················.Build(); |
| 208 | |
| 209 | ············var options = config.GetSection( "StressTest" ).Get<StressTestOptions>() ?? new StressTestOptions(); |
| 210 | ············if (String.IsNullOrEmpty( options.ConnectionString )) |
| 211 | ················options.ConnectionString = config.GetConnectionString( options.Provider ); |
| 212 | ············// Sqlite allows only one writer. A deferred transaction (ReadCommitted) which starts with a read can't be |
| 213 | ············// upgraded to a write transaction, while another connection writes. Sqlite fails immediately with |
| 214 | ············// "database is locked" instead of waiting. Serializable starts the transaction with BEGIN IMMEDIATE. |
| 215 | ············if (options.IsolationLevel == null && String.Equals( options.Provider, "Sqlite", StringComparison.OrdinalIgnoreCase )) |
| 216 | ················options.IsolationLevel = System.Data.IsolationLevel.Serializable; |
| 217 | ············return options; |
| 218 | ········} |
| 219 | |
| 220 | ········static async Task<int[]> GetOrCreateTagsAsync( TestDatabase db, int tagCount, CancellationToken ct ) |
| 221 | ········{ |
| 222 | ············await using (var pm = db.NewPersistenceManager()) |
| 223 | ············{ |
| 224 | ················var existing = await pm.Objects<Tag>().ToListAsync( ct ); |
| 225 | ················if (existing.Count >= tagCount) |
| 226 | ····················return existing.Select( t => (int) ((NDO.IPersistenceCapable) t).NDOObjectId.Id[0] ).ToArray(); |
| 227 | ············} |
| 228 | ············await db.CreateTagsAsync( tagCount, ct ); |
| 229 | ············return await GetOrCreateTagsAsync( db, tagCount, ct ); |
| 230 | ········} |
| 231 | |
| 232 | ········static void PrintHelp() |
| 233 | ········{ |
| 234 | ············Console.WriteLine( @"NDO stress test |
| 235 | |
| 236 | Usage: dotnet run -- [options] |
| 237 | |
| 238 | The defaults are read from appsettings.json and appsettings.local.json (optional). |
| 239 | Environment variables with the prefix NDOSTRESS_ override them, e.g. NDOSTRESS_ConnectionStrings__Postgre. |
| 240 | |
| 241 | Options: |
| 242 | ··-p, --provider <name>········ Sqlite, SqlServer, MySql, MySqlConnector, Postgre |
| 243 | ··-c, --connection <string>···· Connection string (default: ConnectionStrings:<provider>) |
| 244 | ··-t, --threads <n>············ Number of concurrent workers |
| 245 | ··-i, --iterations <n>··········Iterations per worker |
| 246 | ··-d, --duration <seconds>······Run for the given time instead of a fixed number of iterations |
| 247 | ······--lines <n>·············· Lines per order (>= 2) |
| 248 | ······--tags <n>················Number of shared tags (>= 3) |
| 249 | ······--transactionMode <mode>··Optimistic or Pessimistic |
| 250 | ······--isolationLevel <level>··ReadCommitted, Serializable, ... (default: NDO default, Sqlite: Serializable) |
| 251 | ······--sharedMapping <bool>····All PersistenceManagers share one NDOMapping object |
| 252 | ······--recreateSchema <bool>·· Drop and create the tables before the test |
| 253 | ······--dropSchema <bool>······ Drop the tables after a successful test |
| 254 | ······--stopOnFirstError <bool> Stop all workers after the first error |
| 255 | ······--maxErrors <n>·········· Number of errors printed with stack trace |
| 256 | |
| 257 | Exit codes: 0 = success, 1 = errors, 2 = cancelled, 3 = configuration or setup error" ); |
| 258 | ········} |
| 259 | ····} |
| 260 | } |
| 261 |