diff --git a/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/FaultInjectingMiddleware.cs b/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/FaultInjectingMiddleware.cs index 25cecf94a8a..a7843a8a841 100644 --- a/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/FaultInjectingMiddleware.cs +++ b/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/FaultInjectingMiddleware.cs @@ -67,13 +67,10 @@ private async Task SendUpstreamRequest(HttpRequest request, st using (var upstreamRequest = new HttpRequestMessage(new HttpMethod(request.Method), upstreamUri)) { - if (request.ContentLength > 0) + upstreamRequest.Content = new StreamContent(request.Body); + foreach (var header in request.Headers.Where(h => Utils.ContentRequestHeaders.Contains(h.Key))) { - upstreamRequest.Content = new StreamContent(request.Body); - foreach (var header in request.Headers.Where(h => Utils.ContentRequestHeaders.Contains(h.Key))) - { - upstreamRequest.Content.Headers.Add(header.Key, values: header.Value); - } + upstreamRequest.Content.Headers.Add(header.Key, values: header.Value); } foreach (var header in request.Headers.Where(h => !Utils.ExcludedRequestHeaders.Contains(h.Key) && !Utils.ContentRequestHeaders.Contains(h.Key))) @@ -125,7 +122,42 @@ private async Task BufferContentAsync(HttpContent content, Cancell private async Task ProxyResponse(HttpContext context, string upstreamUri, string fault, CancellationToken cancellationToken) { + switch (fault) + { + case "nq": + // No request body, then wait indefinitely + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return; + case "nqc": + // No request body, then close (TCP FIN) + Close(context); + return; + case "nqa": + // No request body, then abort (TCP RST) + Abort(context); + return; + case "pq": + // Partial request (50% of body), then wait indefinitely + await ReadPartialRequest(context.Request, cancellationToken); + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return; + case "pqc": + // Partial request (50% of body), then close (TCP FIN) + await ReadPartialRequest(context.Request, cancellationToken); + Close(context); + return; + case "pqa": + // Partial request (50% of body), then abort (TCP RST) + await ReadPartialRequest(context.Request, cancellationToken); + Abort(context); + return; + default: + // Fall through and read full request body + break; + } + UpstreamResponse upstreamResponse = await SendUpstreamRequest(context.Request, upstreamUri, cancellationToken); + switch (fault) { case "f": @@ -139,12 +171,12 @@ private async Task ProxyResponse(HttpContext context, string upstreamUri, string return; case "pc": // Partial Response (full headers, 50% of body), then close (TCP FIN) - await SendDownstreamResponse(context.Response,upstreamResponse, upstreamResponse.ContentLength / 2, cancellationToken); + await SendDownstreamResponse(context.Response, upstreamResponse, upstreamResponse.ContentLength / 2, cancellationToken); Close(context); return; case "pa": // Partial Response (full headers, 50% of body), then abort (TCP RST) - await SendDownstreamResponse(context.Response,upstreamResponse, upstreamResponse.ContentLength / 2, cancellationToken); + await SendDownstreamResponse(context.Response, upstreamResponse, upstreamResponse.ContentLength / 2, cancellationToken); Abort(context); return; case "pn": @@ -169,6 +201,36 @@ private async Task ProxyResponse(HttpContext context, string upstreamUri, string } } + private static async Task ReadPartialRequest(HttpRequest request, CancellationToken cancellationToken) + { + var contentLength = request.ContentLength + ?? throw new InvalidOperationException("Partial request options require content-length request headers"); + var bytesToRead = contentLength / 2; + long totalBytesRead = 0; + var buffer = ArrayPool.Shared.Rent(81920); + try + { + while (true) + { + var bytesRead = await request.Body.ReadAsync( + buffer, + 0, + (int)Math.Min(buffer.Length, bytesToRead - totalBytesRead), + cancellationToken + ); + totalBytesRead += bytesRead; + if (totalBytesRead >= bytesToRead || bytesRead == 0) + { + break; + } + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + private async Task SendDownstreamResponse(HttpResponse response, UpstreamResponse upstreamResponse, long contentBytes, CancellationToken cancellationToken) { response.StatusCode = upstreamResponse.StatusCode; diff --git a/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/Utils.cs b/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/Utils.cs index a53e05720b7..4743c98038c 100644 --- a/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/Utils.cs +++ b/tools/http-fault-injector/Azure.Sdk.Tools.HttpFaultInjector/Utils.cs @@ -7,14 +7,20 @@ public static class Utils { public static readonly IDictionary FaultModes = new Dictionary() { - { "f", "Full response" }, - { "p", "Partial Response (full headers, 50% of body), then wait indefinitely" }, - {"pc", "Partial Response (full headers, 50% of body), then close (TCP FIN)" }, - {"pa", "Partial Response (full headers, 50% of body), then abort (TCP RST)" }, - {"pn", "Partial Response (full headers, 50% of body), then finish normally" }, - {"n", "No response, then wait indefinitely"}, - {"nc", "No response, then close (TCP FIN)" }, - {"na", "No response, then abort (TCP RST)" } + { "f", "Full response" }, + { "p", "Partial Response (full headers, 50% of body), then wait indefinitely" }, + { "pc", "Partial Response (full headers, 50% of body), then close (TCP FIN)" }, + { "pa", "Partial Response (full headers, 50% of body), then abort (TCP RST)" }, + { "pn", "Partial Response (full headers, 50% of body), then finish normally" }, + { "n", "No response, then wait indefinitely"}, + { "nc", "No response, then close (TCP FIN)" }, + { "na", "No response, then abort (TCP RST)" }, + { "pq", "Partial request (50% of body), then wait indefinitely"}, + {"pqc", "Partial request (50% of body), then close (TCP FIN)"}, + {"pqa", "Partial request (50% of body), then abort (TCP RST)"}, + { "nq", "No request body, then wait indefinitely"}, + {"nqc", "No request body, then close (TCP FIN)"}, + {"nqa", "No request body, then abort (TCP RST)"}, }; public static readonly string[] ExcludedRequestHeaders = new string[] { diff --git a/tools/http-fault-injector/Dockerfile b/tools/http-fault-injector/Dockerfile index e7abeae2caa..80451e0a294 100644 --- a/tools/http-fault-injector/Dockerfile +++ b/tools/http-fault-injector/Dockerfile @@ -13,6 +13,8 @@ RUN dotnet dev-certs https EXPOSE 7777 EXPOSE 7778 +ENV ASPNETCORE_URLS=http://+:7777;https://+:7778 + ENTRYPOINT [ "/root/.dotnet/tools/http-fault-injector" ] diff --git a/tools/http-fault-injector/sample-clients/net/http-client/Program.cs b/tools/http-fault-injector/sample-clients/net/http-client/Program.cs index a188da216bf..ca59aaaeb52 100644 --- a/tools/http-fault-injector/sample-clients/net/http-client/Program.cs +++ b/tools/http-fault-injector/sample-clients/net/http-client/Program.cs @@ -1,5 +1,7 @@ -using System; +using System; +using System.IO; using System.Net.Http; +using System.Text; using System.Threading; using System.Threading.Tasks; @@ -9,11 +11,34 @@ class Program { static async Task Main(string[] args) { - var httpClient = new HttpClient(new FaultInjectionClientHandler(new Uri("http://localhost:7777"))); + var directClient = new HttpClient(); + var faultInjectionClient = new HttpClient(new FaultInjectionClientHandler(new Uri("http://localhost:7777"))) + { + // Short timeout for testing no response + Timeout = TimeSpan.FromSeconds(10) + }; + + Console.WriteLine("Sending request directly..."); + await Test(directClient); + + Console.WriteLine("Sending request through fault injector..."); + await Test(faultInjectionClient); + } + + private static async Task Test(HttpClient client) + { + var baseUrl = "http://localhost:5000"; + + var uploadStream = new LoggingStream(new MemoryStream(Encoding.UTF8.GetBytes(new string('a', 10 * 1024 * 1024)))); + + var response = await client.PutAsync(baseUrl + "/upload", new StreamContent(uploadStream)); - Console.WriteLine("Sending request..."); - var response = await httpClient.GetAsync("https://www.example.org"); - Console.WriteLine(response.StatusCode); + var content = await response.Content.ReadAsStringAsync(); + var shortContent = (content.Length <= 40 ? content : content.Substring(0, 40) + "..."); + + Console.WriteLine($"Status: {response.StatusCode}"); + Console.WriteLine($"Content: {shortContent}"); + Console.WriteLine($"Length: {content.Length}"); } class FaultInjectionClientHandler : HttpClientHandler @@ -52,5 +77,58 @@ protected override Task SendAsync(HttpRequestMessage reques return base.SendAsync(request, cancellationToken); } } + + class LoggingStream : Stream + { + private readonly Stream _stream; + private long _totalBytesRead; + + public LoggingStream(Stream stream) + { + _stream = stream; + } + + public override bool CanRead => _stream.CanRead; + + public override bool CanSeek => _stream.CanSeek; + + public override bool CanWrite => _stream.CanWrite; + + public override long Length => _stream.Length; + + public override long Position + { + get => _stream.Position; + set => _stream.Position = value; + } + + public override void Flush() + { + _stream.Flush(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + var bytesRead = _stream.Read(buffer, offset, count); + _totalBytesRead += bytesRead; + Console.WriteLine($"Read(buffer: byte[{buffer.Length}], offset: {offset}, count: {count}) => {bytesRead} (total {_totalBytesRead})"); + return bytesRead; + } + + public override long Seek(long offset, SeekOrigin origin) + { + return _stream.Seek(offset, origin); + } + + public override void SetLength(long value) + { + _stream.SetLength(value); + } + + public override void Write(byte[] buffer, int offset, int count) + { + _stream.Write(buffer, offset, count); + } + } } } diff --git a/tools/http-fault-injector/sample-servers/net/.gitignore b/tools/http-fault-injector/sample-servers/net/.gitignore new file mode 100644 index 00000000000..7e36f8bbf87 --- /dev/null +++ b/tools/http-fault-injector/sample-servers/net/.gitignore @@ -0,0 +1,353 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +## Customizations +!*.pfx diff --git a/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.csproj b/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.csproj new file mode 100644 index 00000000000..f35c1950ca8 --- /dev/null +++ b/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.csproj @@ -0,0 +1,14 @@ + + + + Exe + net6.0 + + + + + PreserveNewest + + + + diff --git a/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.sln b/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.sln new file mode 100644 index 00000000000..92322d842ab --- /dev/null +++ b/tools/http-fault-injector/sample-servers/net/http-server/Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.30320.12 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample", "Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample.csproj", "{C6B75C5B-AE40-40BD-B8BF-7F7CD5A53B22}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C6B75C5B-AE40-40BD-B8BF-7F7CD5A53B22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C6B75C5B-AE40-40BD-B8BF-7F7CD5A53B22}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C6B75C5B-AE40-40BD-B8BF-7F7CD5A53B22}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C6B75C5B-AE40-40BD-B8BF-7F7CD5A53B22}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {232A0BD3-B2E9-45A9-BAF3-03BE780F2AE9} + EndGlobalSection +EndGlobal diff --git a/tools/http-fault-injector/sample-servers/net/http-server/Program.cs b/tools/http-fault-injector/sample-servers/net/http-server/Program.cs new file mode 100644 index 00000000000..399ff6b51a6 --- /dev/null +++ b/tools/http-fault-injector/sample-servers/net/http-server/Program.cs @@ -0,0 +1,81 @@ +using System; +using System.Buffers; +using System.Net; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; + +namespace Azure.Sdk.Tools.HttpFaultInjector.HttpServerSample +{ + public class Program + { + public static void Main(string[] args) + { + new WebHostBuilder() + .UseKestrel(options => + { + options.Listen(IPAddress.Any, 5000); + options.Listen(IPAddress.Any, 5001, listenOptions => + { + listenOptions.UseHttps("testCert.pfx", "testPassword"); + }); + }) + .Configure(app => app.Run(async context => + { + Console.WriteLine($"Request: {context.Request.Path}"); + + if (!bool.TryParse(context.Request.Query["chunked"], out var chunked)) + { + chunked = false; + } + + string response; + if (context.Request.Path == "/download") + { + if (!int.TryParse(context.Request.Query["length"], out var length)) + { + length = 1024; + } + response = new string('a', length); + } + else if (context.Request.Path == "/upload") + { + var totalBytes = 0; + var buffer = ArrayPool.Shared.Rent(8192); + try + { + int bytesRead; + while ((bytesRead = await context.Request.Body.ReadAsync(buffer, 0, buffer.Length)) > 0) + { + totalBytes += bytesRead; + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + + response = totalBytes.ToString(); + } + else + { + response = "Hello World!"; + } + + var shortResponse = (response.Length <= 40 ? response : response.Substring(0, 40) + "..."); + + Console.WriteLine($"Response: {response.Substring(0, Math.Min(40, response.Length))}"); + Console.WriteLine($"ResponseLength: {response.Length}"); + + if (!chunked) + { + context.Response.ContentLength = response.Length; + } + + await context.Response.WriteAsync(response); + })) + .Build() + .Run(); + } + } +} diff --git a/tools/http-fault-injector/sample-servers/net/http-server/testCert.pfx b/tools/http-fault-injector/sample-servers/net/http-server/testCert.pfx new file mode 100644 index 00000000000..0dbc7caceb1 Binary files /dev/null and b/tools/http-fault-injector/sample-servers/net/http-server/testCert.pfx differ