├── .appveyor.yml ├── .gitattributes ├── .gitignore ├── .travis.yml ├── Common.sln ├── License.txt ├── README.md ├── config ├── versions-dev.props ├── versions-master.props └── versions.props ├── nuget.config ├── open_source_licenses.txt ├── src ├── Steeltoe.Common.Autofac │ ├── Configuration │ │ └── ConfigurationContainerBuilderExtensions.cs │ ├── Logging │ │ ├── DefaultLoggerLevelConfigureOptions.cs │ │ ├── LoggerFilterConfigureOptions.cs │ │ └── LoggingContainerBuilderExtensions.cs │ ├── Options │ │ └── OptionsContainerBuilderExtensions.cs │ └── Steeltoe.Common.Autofac.csproj ├── Steeltoe.Common.Http │ ├── Discovery │ │ ├── DiscoveryHttpClientBuilderExtensions.cs │ │ ├── DiscoveryHttpClientHandler.cs │ │ ├── DiscoveryHttpClientHandlerBase.cs │ │ └── DiscoveryHttpMessageHandler.cs │ ├── HttpClientExtensions.cs │ ├── HttpClientHelper.cs │ ├── LoadBalancer │ │ ├── LoadBalancerDelegatingHandler.cs │ │ ├── LoadBalancerHttpClientBuilderExtensions.cs │ │ └── LoadBalancerHttpClientHandler.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SerializationHelper.cs │ └── Steeltoe.Common.Http.csproj ├── Steeltoe.Common.Net │ ├── IMPR.cs │ ├── MPR.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── Steeltoe.Common.Net.csproj │ └── WindowsNetworkFileShare.cs ├── Steeltoe.Common.Security │ ├── CertificateOptions.cs │ ├── ICertificateOptions.cs │ ├── PemCertificateProvider.cs │ ├── PemCertificateSource.cs │ ├── PemConfigurationExtensions.cs │ ├── PemConfigureCertificateOptions.cs │ └── Steeltoe.Common.Security.csproj └── Steeltoe.Common │ ├── Configuration │ ├── ConfigurationValuesHelper.cs │ ├── IConfigurationBuilderExtensions.cs │ └── PropertyPlaceHolderHelper.cs │ ├── Diagnostics │ ├── DiagnosticHelpers.cs │ ├── DiagnosticObserver.cs │ ├── DiagnosticsManager.cs │ ├── IDiagnosticObserver.cs │ ├── IDiagnosticsManager.cs │ └── IPolledDiagnosticSource.cs │ ├── Discovery │ ├── ConfigurationServiceInstance.cs │ ├── ConfigurationServiceInstanceProvider.cs │ ├── ConfigurationServiceInstanceProviderServiceCollectionExtensions.cs │ ├── DiscoveryOptions.cs │ ├── IDiscoveryClient.cs │ ├── IDiscoveryClientOptions.cs │ ├── IDiscoveryLifecycle.cs │ ├── IDiscoveryRegistrationOptions.cs │ ├── IServiceInstance.cs │ ├── IServiceInstanceProvider.cs │ ├── IServiceInstanceProviderExtensions.cs │ ├── IServiceRegistry.cs │ └── SerializableIServiceInstance.cs │ ├── HealthChecks │ ├── HealthCheckResult.cs │ ├── HealthStatus.cs │ └── IHealthContributor.cs │ ├── LoadBalancer │ ├── ILoadBalancer.cs │ ├── RandomLoadBalancer.cs │ └── RoundRobinLoadBalancer.cs │ ├── Net │ ├── HostInfo.cs │ ├── INetOptions.cs │ └── InetUtils.cs │ ├── Options │ └── AbstractOptions.cs │ ├── Platform.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Reflection │ └── ReflectionHelpers.cs │ ├── Steeltoe.Common.csproj │ └── Tasks │ └── IApplicationTask.cs ├── stylecop.json ├── targetframework.props ├── test ├── Steeltoe.Common.Autofac.Test │ ├── Configuration │ │ └── ConfigurationContainerBuilderExtensionsTest.cs │ ├── Logging │ │ └── LoggingContainerBuilderExtensionsTest.cs │ ├── Options │ │ └── OptionsContainerBuilderExtensionsTest.cs │ ├── Steeltoe.Common.Autofac.Test.csproj │ └── xunit.runner.json ├── Steeltoe.Common.Http.Test │ ├── Discovery │ │ ├── DiscoveryHttpClientHandlerBaseTest.cs │ │ └── TestDiscoveryClient.cs │ ├── HttpClientExtensionsTest.cs │ ├── HttpClientHelperTest.cs │ ├── LoadBalancer │ │ ├── BrokenLoadBalancer.cs │ │ ├── FakeLoadBalancer.cs │ │ ├── LoadBalancerDelegatingHandlerTest.cs │ │ └── LoadBalancerHttpClientBuilderExtensionsTest.cs │ ├── SerializationHelperTest.cs │ ├── SerializationTestObject.cs │ ├── Steeltoe.Common.Http.Test.csproj │ ├── TestInnerDelegatingHandler.cs │ ├── TestInnerDelegatingHandlerBrokenServer.cs │ ├── TestServiceInstance.cs │ └── xunit.runner.json ├── Steeltoe.Common.Net.Test │ ├── FakeMPR.cs │ ├── Steeltoe.Common.Net.Test.csproj │ └── WindowsNetworkFileShareTest.cs ├── Steeltoe.Common.Security.Test │ ├── PemConfigurationExtensionsTest.cs │ ├── PemConfigureCertificateOptionsTest.cs │ ├── Steeltoe.Common.Security.Test.csproj │ ├── instance.crt │ ├── instance.key │ └── xunit.runner.json └── Steeltoe.Common.Test │ ├── Configuration │ ├── ConfigurationValuesHelperTest.cs │ ├── IConfigurationBuilderExtensionsTest.cs │ └── PropertyPlaceholderHelperTest.cs │ ├── Discovery │ ├── ConfigurationServiceInstanceProviderServiceCollectionExtensionsTest.cs │ ├── ConfigurationServiceInstanceProviderTest.cs │ └── DiscoveryOptionsTest.cs │ ├── LoadBalancer │ └── RoundRobinLoadBalancerTest.cs │ ├── Net │ └── InetUtilsTest.cs │ ├── Options │ ├── AbstractOptionsTest.cs │ └── TestOptions.cs │ ├── PlatformTest.cs │ ├── Steeltoe.Common.Test.csproj │ ├── TestHelpers.cs │ ├── TestOptionsMonitor.cs │ └── xunit.runner.json └── versions.props /.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: '2.2.0-{branch}-{build}' 2 | init: 3 | - git config --global core.autocrlf true 4 | image: Visual Studio 2017 5 | skip_tags: true 6 | branches: 7 | only: 8 | - master 9 | - dev 10 | - /^update[0-9]{2}x/ 11 | install: 12 | - git clone https://github.com/SteeltoeOSS/steeltoe-ci.git -v 13 | - ps: steeltoe-ci\scripts\appveyor_install.ps1 14 | test_script: 15 | - ps: steeltoe-ci\scripts\appveyor_tests.ps1 16 | build_script: 17 | - ps: steeltoe-ci\scripts\appveyor_build.ps1 18 | - ps: steeltoe-ci\scripts\sign-packages.ps1 19 | artifacts: 20 | - path: 'localfeed\*.nupkg' 21 | environment: 22 | DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 23 | DOTNET_CLI_TELEMETRY_OPTOUT: 1 24 | PackageReferencesToUpdate: SteeltoeCommonVersion 25 | github_access_token: 26 | secure: ko4J3M/czguVI9AbVdkv5qZuj3Wuzts5nkz/6cypneFkQGWJXDs8Akg7xOEMu8qU 27 | SignClientUser: 28 | secure: Tt9mySuspn9dHJOLKMoGxrNJvJbpBrWK44UI9Qc9+eNilYdoukHZ3jUF06pl2r60 29 | SignClientSecret: 30 | secure: ZmCTr+SyfQtewSNsiB8OMISmQJp8RfjRSK0Dvg60iTQ= 31 | deploy: 32 | - provider: NuGet 33 | skip_symbols: false 34 | artifact: /.*\.nupkg/ 35 | server: https://www.myget.org/F/steeltoedev/api/v2/package 36 | symbol_server: https://www.myget.org/F/steeltoedev/symbols/api/v2/package 37 | api_key: 38 | secure: 246ApObnMYYvzDo9Ki72CxxuKfuoqYbrbUK2HLevGIGHXYY6f0OkAdE3EWCwNJ7g 39 | on: 40 | branch: dev 41 | appveyor_repo_tag: false 42 | - provider: NuGet 43 | skip_symbols: false 44 | artifact: /.*\.nupkg/ 45 | server: https://www.myget.org/F/steeltoemaster/api/v2/package 46 | symbol_server: https://www.myget.org/F/steeltoemaster/symbols/api/v2/package 47 | api_key: 48 | secure: 246ApObnMYYvzDo9Ki72CxxuKfuoqYbrbUK2HLevGIGHXYY6f0OkAdE3EWCwNJ7g 49 | on: 50 | branch: master 51 | appveyor_repo_tag: false 52 | - provider: NuGet 53 | skip_symbols: true 54 | artifact: /.*\.nupkg/ 55 | server: https://www.myget.org/F/steeltoestaging/api/v2/package 56 | symbol_server: https://www.myget.org/F/steeltoestaging/symbols/api/v2/package 57 | api_key: 58 | secure: 246ApObnMYYvzDo9Ki72CxxuKfuoqYbrbUK2HLevGIGHXYY6f0OkAdE3EWCwNJ7g 59 | on: 60 | branch: /^update[0-9]{2}x/ 61 | appveyor_repo_tag: false 62 | after_deploy: 63 | - git config --global credential.helper store 64 | - ps: Add-Content "$env:USERPROFILE\.git-credentials" "https://$($env:github_access_token):x-oauth-basic@github.com`n" 65 | - git config --global user.email "steeltoe@pivotal.io" 66 | - git config --global user.name "SteeltoeCI" 67 | - ps: steeltoe-ci\scripts\update_downstream_props.ps1 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.doc diff=astextplain 2 | *.DOC diff=astextplain 3 | *.docx diff=astextplain 4 | *.DOCX diff=astextplain 5 | *.dot diff=astextplain 6 | *.DOT diff=astextplain 7 | *.pdf diff=astextplain 8 | *.PDF diff=astextplain 9 | *.rtf diff=astextplain 10 | *.RTF diff=astextplain 11 | 12 | *.jpg binary 13 | *.png binary 14 | *.gif binary 15 | 16 | *.cs text=auto diff=csharp 17 | *.vb text=auto 18 | *.resx text=auto 19 | *.c text=auto 20 | *.cpp text=auto 21 | *.cxx text=auto 22 | *.h text=auto 23 | *.hxx text=auto 24 | *.py text=auto 25 | *.rb text=auto 26 | *.java text=auto 27 | *.html text=auto 28 | *.htm text=auto 29 | *.css text=auto 30 | *.scss text=auto 31 | *.sass text=auto 32 | *.less text=auto 33 | *.js text=auto 34 | *.lisp text=auto 35 | *.clj text=auto 36 | *.sql text=auto 37 | *.php text=auto 38 | *.lua text=auto 39 | *.m text=auto 40 | *.asm text=auto 41 | *.erl text=auto 42 | *.fs text=auto 43 | *.fsx text=auto 44 | *.hs text=auto 45 | 46 | *.csproj text=auto 47 | *.vbproj text=auto 48 | *.fsproj text=auto 49 | *.dbproj text=auto 50 | *.sln text=auto eol=crlf 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studo 2015 cache/options directory 26 | .vs/ 27 | 28 | # MSTest test Results 29 | [Tt]est[Rr]esult*/ 30 | [Bb]uild[Ll]og.* 31 | 32 | # NUNIT 33 | *.VisualState.xml 34 | TestResult.xml 35 | 36 | # Build Results of an ATL Project 37 | [Dd]ebugPS/ 38 | [Rr]eleasePS/ 39 | dlldata.c 40 | 41 | *_i.c 42 | *_p.c 43 | *_i.h 44 | *.ilk 45 | *.meta 46 | *.obj 47 | *.pch 48 | *.pdb 49 | *.pgc 50 | *.pgd 51 | *.rsp 52 | *.sbr 53 | *.tlb 54 | *.tli 55 | *.tlh 56 | *.tmp 57 | *.tmp_proj 58 | *.log 59 | *.vspscc 60 | *.vssscc 61 | .builds 62 | *.pidb 63 | *.svclog 64 | *.scc 65 | 66 | # Chutzpah Test files 67 | _Chutzpah* 68 | 69 | # Visual C++ cache files 70 | ipch/ 71 | *.aps 72 | *.ncb 73 | *.opensdf 74 | *.sdf 75 | *.cachefile 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | *.vspx 81 | 82 | # TFS 2012 Local Workspace 83 | $tf/ 84 | 85 | # Guidance Automation Toolkit 86 | *.gpState 87 | 88 | # ReSharper is a .NET coding add-in 89 | _ReSharper*/ 90 | *.[Rr]e[Ss]harper 91 | *.DotSettings.user 92 | 93 | # JustCode is a .NET coding addin-in 94 | .JustCode 95 | 96 | # TeamCity is a build add-in 97 | _TeamCity* 98 | 99 | # DotCover is a Code Coverage Tool 100 | *.dotCover 101 | 102 | # NCrunch 103 | _NCrunch_* 104 | .*crunch*.local.xml 105 | 106 | # MightyMoose 107 | *.mm.* 108 | AutoTest.Net/ 109 | 110 | # Web workbench (sass) 111 | .sass-cache/ 112 | 113 | # Installshield output folder 114 | [Ee]xpress/ 115 | 116 | # DocProject is a documentation generator add-in 117 | DocProject/buildhelp/ 118 | DocProject/Help/*.HxT 119 | DocProject/Help/*.HxC 120 | DocProject/Help/*.hhc 121 | DocProject/Help/*.hhk 122 | DocProject/Help/*.hhp 123 | DocProject/Help/Html2 124 | DocProject/Help/html 125 | 126 | # Click-Once directory 127 | publish/ 128 | 129 | # Publish Web Output 130 | *.[Pp]ublish.xml 131 | *.azurePubxml 132 | # TODO: Comment the next line if you want to checkin your web deploy settings 133 | # but database connection strings (with potential passwords) will be unencrypted 134 | *.pubxml 135 | *.publishproj 136 | 137 | # NuGet Packages 138 | *.nupkg 139 | # The packages folder can be ignored because of Package Restore 140 | **/packages/* 141 | # except build/, which is used as an MSBuild target. 142 | !**/packages/build/ 143 | # Uncomment if necessary however generally it will be regenerated when needed 144 | #!**/packages/repositories.config 145 | 146 | # Windows Azure Build Output 147 | csx/ 148 | *.build.csdef 149 | 150 | # Windows Store app package directory 151 | AppPackages/ 152 | 153 | # Others 154 | *.[Cc]ache 155 | ClientBin/ 156 | ~$* 157 | *~ 158 | *.dbmdl 159 | *.dbproj.schemaview 160 | *.pfx 161 | *.publishsettings 162 | node_modules/ 163 | bower_components/ 164 | 165 | # RIA/Silverlight projects 166 | Generated_Code/ 167 | 168 | # Backup & report files from converting an old project file 169 | # to a newer Visual Studio version. Backup files are not needed, 170 | # because we have git ;-) 171 | _UpgradeReport_Files/ 172 | Backup*/ 173 | UpgradeLog*.XML 174 | UpgradeLog*.htm 175 | 176 | # SQL Server files 177 | *.mdf 178 | *.ldf 179 | 180 | # Business Intelligence projects 181 | *.rdl.data 182 | *.bim.layout 183 | *.bim_*.settings 184 | 185 | # Microsoft Fakes 186 | FakesAssemblies/ 187 | 188 | # Node.js Tools for Visual Studio 189 | .ntvs_analysis.dat 190 | 191 | # Visual Studio 6 build log 192 | *.plg 193 | 194 | # Visual Studio 6 workspace options file 195 | *.opt 196 | 197 | # DNX-based projects have a project.lock.json file. This should not be checked-in during development 198 | project.lock.json 199 | .vscode 200 | .idea 201 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | dist: trusty 3 | env: 4 | TestFrameworkVersion: netcoreapp2.1 5 | STEELTOE_VERSION: 2.2.0 6 | global: 7 | - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true 8 | - DOTNET_CLI_TELEMETRY_OPTOUT: 1 9 | mono: none 10 | dotnet: 2.1.403 11 | os: 12 | - linux 13 | - osx 14 | osx_image: xcode8.3 15 | branches: 16 | only: 17 | - master 18 | - dev 19 | - /^update[0-9]{2}x/ 20 | script: 21 | - ./steeltoe-ci/scripts/travis_install.sh 22 | - ./steeltoe-ci/scripts/travis_build.sh 23 | - ./steeltoe-ci/scripts/travis_test.sh 24 | before_install: 25 | - git clone https://github.com/SteeltoeOSS/steeltoe-ci.git -v 26 | - if [ "$TRAVIS_OS_NAME" = "osx" ]; then ulimit -n 1024; fi 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Steeltoe Common Packages 2 | 3 | > NOTICE: This repository has been relocated as a sub-directory under the [Steeltoe](https://github.com/SteeltoeOSS/steeltoe) repository. All issues and future development will be done under that repository. 4 | 5 | This repository contains several packages that are common to other Steeltoe components. 6 | 7 | Windows Master (Stable): [![AppVeyor Master](https://ci.appveyor.com/api/projects/status/3omrdvukuvv12gig/branch/master?svg=true)](https://ci.appveyor.com/project/steeltoe/common/branch/master) 8 | 9 | Windows Dev (Less Stable): [![AppVeyor Dev](https://ci.appveyor.com/api/projects/status/3omrdvukuvv12gig/branch/dev?svg=true)](https://ci.appveyor.com/project/steeltoe/common/branch/dev) 10 | 11 | Linux/OS X Master (Stable): [![Travis Master](https://travis-ci.org/SteeltoeOSS/Common.svg?branch=master)](https://travis-ci.org/SteeltoeOSS/Common) 12 | 13 | Linux/OS X Dev (Less Stable): [![Travis Dev](https://travis-ci.org/SteeltoeOSS/Common.svg?branch=dev)](https://travis-ci.org/SteeltoeOSS/Common) 14 | 15 | ## Nuget Feeds 16 | 17 | All new development is done on the dev branch. More stable versions of the packages can be found on the master branch. The latest prebuilt packages from each branch can be found on one of two MyGet feeds. Released version can be found on nuget.org. 18 | 19 | - [Development feed (Less Stable)](https://www.myget.org/gallery/steeltoedev) 20 | - [Master feed (Stable)](https://www.myget.org/gallery/steeltoemaster) 21 | - [Release or Release Candidate feed](https://www.nuget.org/) 22 | 23 | ## Building Pre-requisites 24 | 25 | To build and run the unit tests: 26 | 27 | 1. .NET Core SDK 2.0.3 or greater 28 | 1. .NET Core Runtime 2.0.3 29 | 30 | ## Building Packages & Running Tests - Windows 31 | 32 | To build the packages on windows: 33 | 34 | 1. git clone ... 35 | 1. cd `` 36 | 1. cd src\ `` (e.g. cd src\Steeltoe.Common) 37 | 1. dotnet restore 38 | 1. dotnet pack --configuration `` 39 | 40 | The resulting artifacts can be found in the bin folder under the corresponding project. (e.g. src\Steeltoe.Common\bin) 41 | 42 | To run the unit tests: 43 | 44 | 1. git clone ... 45 | 1. cd `` 46 | 1. cd test\ `` (e.g. cd test\Steeltoe.Common.Test) 47 | 1. dotnet restore 48 | 1. dotnet xunit -verbose 49 | 50 | ## Building Packages & Running Tests - Linux/OSX 51 | 52 | To build the packages on Linux/OSX: 53 | 54 | 1. git clone ... 55 | 1. cd `` 56 | 1. cd src/ `` (e.g.. cd src/Steeltoe.Common) 57 | 1. dotnet restore 58 | 1. dotnet pack --configuration `` 59 | 60 | The resulting artifacts can be found in the bin folder under the corresponding project. (e.g. src/Steeltoe.Common/bin 61 | 62 | To run the unit tests 63 | 64 | 1. git clone ... 65 | 1. cd `` 66 | 1. cd test\ `` (e.g. cd test/Steeltoe.Common.Test) 67 | 1. dotnet restore 68 | 1. dotnet xunit -verbose -framework netcoreapp2.0 -------------------------------------------------------------------------------- /config/versions-dev.props: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SteeltoeOSS/Common/a378d53f4ebeaa2667a0c1d16f2a21886c52c835/config/versions-dev.props -------------------------------------------------------------------------------- /config/versions-master.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(STEELTOE_VERSION) 4 | $(STEELTOE_DASH_VERSION_SUFFIX) 5 | 2.0.0 6 | 2.0.0 7 | 2.1.0 8 | 2.1.0 9 | 2.1.0 10 | 4.6.1 11 | 4.4.1 12 | 1.0.2 13 | 4.3.3 14 | 3.2.1 15 | 4.4.0 16 | 11.0.2 17 | 15.7.2 18 | 2.3.1 19 | 2.3.1 20 | 1.8.4 21 | 1.0.0-beta2-18618-05 22 | 23 | -------------------------------------------------------------------------------- /config/versions.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(STEELTOE_VERSION) 4 | $(STEELTOE_DASH_VERSION_SUFFIX) 5 | 2.0.0 6 | 2.0.0 7 | 2.1.0 8 | 2.1.0 9 | 2.1.0 10 | 4.6.1 11 | 4.4.1 12 | 1.0.2 13 | 4.3.3 14 | 3.2.1 15 | 4.4.0 16 | 11.0.2 17 | 15.7.2 18 | 2.3.1 19 | 2.3.1 20 | 1.8.4 21 | 1.0.0-beta2-18618-05 22 | 23 | -------------------------------------------------------------------------------- /nuget.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Configuration/ConfigurationContainerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using System; 18 | 19 | namespace Steeltoe.Common.Configuration.Autofac 20 | { 21 | /// 22 | /// Extension methods for registering IConfiguration with the Autofac container 23 | /// 24 | public static class ConfigurationContainerBuilderExtensions 25 | { 26 | /// 27 | /// Register IConfiguration and IConfgurationRoot with the Autofac container 28 | /// 29 | /// the container builder to register with 30 | /// the configuration instance to add to the container 31 | public static void RegisterConfiguration(this ContainerBuilder container, IConfiguration configuration) 32 | { 33 | if (container == null) 34 | { 35 | throw new ArgumentNullException(nameof(container)); 36 | } 37 | 38 | if (configuration == null) 39 | { 40 | throw new ArgumentNullException(nameof(configuration)); 41 | } 42 | 43 | container.RegisterInstance(configuration).As().SingleInstance(); 44 | container.RegisterInstance(configuration).As().SingleInstance(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Logging/DefaultLoggerLevelConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using Microsoft.Extensions.Options; 17 | 18 | namespace Steeltoe.Common.Logging.Autofac 19 | { 20 | /// 21 | /// Default logger level configuration when using the Autofac container 22 | /// 23 | public class DefaultLoggerLevelConfigureOptions : ConfigureOptions 24 | { 25 | /// 26 | /// Initializes a new instance of the class. 27 | /// 28 | /// default log level to configure 29 | public DefaultLoggerLevelConfigureOptions(LogLevel level) 30 | : base(options => options.MinLevel = level) 31 | { 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Logging/LoggerFilterConfigureOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.Logging; 17 | using Microsoft.Extensions.Options; 18 | using System; 19 | 20 | namespace Steeltoe.Common.Logging.Autofac 21 | { 22 | public class LoggerFilterConfigureOptions : IConfigureOptions 23 | { 24 | private readonly IConfiguration configuration; 25 | 26 | public LoggerFilterConfigureOptions(IConfiguration configuration) 27 | { 28 | this.configuration = configuration; 29 | } 30 | 31 | public void Configure(LoggerFilterOptions options) 32 | { 33 | LoadDefaultConfigValues(options); 34 | } 35 | 36 | private static bool TryGetSwitch(string value, out LogLevel level) 37 | { 38 | if (string.IsNullOrEmpty(value)) 39 | { 40 | level = LogLevel.None; 41 | return false; 42 | } 43 | else if (Enum.TryParse(value, true, out level)) 44 | { 45 | return true; 46 | } 47 | else 48 | { 49 | throw new InvalidOperationException($"Configuration value '{value}' is not supported."); 50 | } 51 | } 52 | 53 | private void LoadDefaultConfigValues(LoggerFilterOptions options) 54 | { 55 | if (configuration == null) 56 | { 57 | return; 58 | } 59 | 60 | foreach (var configurationSection in configuration.GetChildren()) 61 | { 62 | if (configurationSection.Key == "LogLevel") 63 | { 64 | // Load global category defaults 65 | LoadRules(options, configurationSection, null); 66 | } 67 | else 68 | { 69 | var logLevelSection = configurationSection.GetSection("LogLevel"); 70 | if (logLevelSection != null) 71 | { 72 | // Load logger specific rules 73 | var logger = configurationSection.Key; 74 | LoadRules(options, logLevelSection, logger); 75 | } 76 | } 77 | } 78 | } 79 | 80 | private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) 81 | { 82 | foreach (var section in configurationSection.AsEnumerable(true)) 83 | { 84 | LogLevel level; 85 | if (TryGetSwitch(section.Value, out level)) 86 | { 87 | var category = section.Key; 88 | if (category == "Default") 89 | { 90 | category = null; 91 | } 92 | 93 | var newRule = new LoggerFilterRule(logger, category, level, null); 94 | options.Rules.Add(newRule); 95 | } 96 | } 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Logging/LoggingContainerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using Microsoft.Extensions.Logging; 18 | using Microsoft.Extensions.Logging.Console; 19 | using Microsoft.Extensions.Options; 20 | using System; 21 | 22 | namespace Steeltoe.Common.Logging.Autofac 23 | { 24 | public static class LoggingContainerBuilderExtensions 25 | { 26 | public static void RegisterLogging(this ContainerBuilder container, IConfiguration configuration) 27 | { 28 | if (container == null) 29 | { 30 | throw new ArgumentNullException(nameof(container)); 31 | } 32 | 33 | if (configuration == null) 34 | { 35 | throw new ArgumentNullException(nameof(configuration)); 36 | } 37 | 38 | container.RegisterType().As().SingleInstance(); 39 | container.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>)).SingleInstance(); 40 | container.RegisterInstance(new DefaultLoggerLevelConfigureOptions(LogLevel.Information)).As>().SingleInstance(); 41 | 42 | var config = configuration.GetSection("Logging"); 43 | container.RegisterInstance(new LoggerFilterConfigureOptions(config)).As>().SingleInstance(); 44 | container.RegisterInstance(new ConfigurationChangeTokenSource(config)).As>().SingleInstance(); 45 | } 46 | 47 | public static void RegisterConsoleLogging(this ContainerBuilder container) 48 | { 49 | if (container == null) 50 | { 51 | throw new ArgumentNullException(nameof(container)); 52 | } 53 | 54 | container.RegisterType().As(); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Options/OptionsContainerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using Microsoft.Extensions.Options; 18 | using System; 19 | 20 | namespace Steeltoe.Common.Options.Autofac 21 | { 22 | public static class OptionsContainerBuilderExtensions 23 | { 24 | public static void RegisterOptions(this ContainerBuilder container) 25 | { 26 | if (container == null) 27 | { 28 | throw new ArgumentNullException(nameof(container)); 29 | } 30 | 31 | container.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptions<>)).SingleInstance(); 32 | container.RegisterGeneric(typeof(OptionsMonitor<>)).As(typeof(IOptionsMonitor<>)).SingleInstance(); 33 | container.RegisterGeneric(typeof(OptionsCache<>)).As(typeof(IOptionsMonitorCache<>)).SingleInstance(); 34 | container.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptionsSnapshot<>)).InstancePerRequest(); 35 | container.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>)).InstancePerDependency(); 36 | } 37 | 38 | public static void RegisterOption(this ContainerBuilder container, IConfiguration config) 39 | where TOption : class 40 | => container.RegisterOption(Microsoft.Extensions.Options.Options.DefaultName, config); 41 | 42 | public static void RegisterOption(this ContainerBuilder container, string name, IConfiguration config) 43 | where TOption : class 44 | { 45 | if (container == null) 46 | { 47 | throw new ArgumentNullException(nameof(container)); 48 | } 49 | 50 | if (config == null) 51 | { 52 | throw new ArgumentNullException(nameof(config)); 53 | } 54 | 55 | container.RegisterInstance(new ConfigurationChangeTokenSource(name, config)).As>().SingleInstance(); 56 | container.RegisterInstance(new NamedConfigureFromConfigurationOptions(name, config)).As>().SingleInstance(); 57 | } 58 | 59 | public static void RegisterPostConfigure(this ContainerBuilder container, Action configureOptions) 60 | where TOptions : class 61 | => container.RegisterPostConfigure(Microsoft.Extensions.Options.Options.DefaultName, configureOptions); 62 | 63 | public static void RegisterPostConfigure(this ContainerBuilder container, string name, Action configureOptions) 64 | where TOptions : class 65 | { 66 | if (container == null) 67 | { 68 | throw new ArgumentNullException(nameof(container)); 69 | } 70 | 71 | if (configureOptions == null) 72 | { 73 | throw new ArgumentNullException(nameof(configureOptions)); 74 | } 75 | 76 | container.RegisterInstance(new PostConfigureOptions(name, configureOptions)).As>().SingleInstance(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Autofac/Steeltoe.Common.Autofac.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Steeltoe Common Library for Autofac 5 | $(SteeltoeVersion) 6 | $(VersionSuffix) 7 | Pivotal;dtillman 8 | netstandard2.0 9 | Steeltoe.Common.Autofac 10 | Steeltoe.Common.Autofac 11 | NET Core;NET Framework;Autofac 12 | https://steeltoe.io/images/transparent.png 13 | https://steeltoe.io 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | true 16 | true 17 | snupkg 18 | 19 | 20 | bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Autofac.xml 21 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | All 31 | 32 | 33 | 34 | 35 | stylecop.json 36 | Always 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.DependencyInjection; 16 | using System; 17 | using System.Net.Http; 18 | 19 | namespace Steeltoe.Common.Http.Discovery 20 | { 21 | /// 22 | /// Extension method for configuring in message handler pipelines 23 | /// 24 | public static class DiscoveryHttpClientBuilderExtensions 25 | { 26 | /// 27 | /// Adds a for performing service discovery 28 | /// 29 | /// The . 30 | /// An that can be used to configure the client. 31 | public static IHttpClientBuilder AddServiceDiscovery(this IHttpClientBuilder builder) 32 | { 33 | if (builder == null) 34 | { 35 | throw new ArgumentNullException(nameof(builder)); 36 | } 37 | 38 | builder.AddHttpMessageHandler(); 39 | return builder; 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using System; 17 | using System.Net.Http; 18 | using System.Threading; 19 | using System.Threading.Tasks; 20 | 21 | namespace Steeltoe.Common.Discovery 22 | { 23 | /// 24 | /// An implementation that performs Service Discovery 25 | /// 26 | public class DiscoveryHttpClientHandler : HttpClientHandler 27 | { 28 | private readonly ILogger _logger; 29 | private DiscoveryHttpClientHandlerBase _discoveryBase; 30 | 31 | /// 32 | /// Initializes a new instance of the class. 33 | /// 34 | /// Service discovery client to use - provided by calling services.AddDiscoveryClient(Configuration) 35 | /// ILogger for capturing logs from Discovery operations 36 | public DiscoveryHttpClientHandler(IDiscoveryClient discoveryClient, ILogger logger = null) 37 | { 38 | _discoveryBase = new DiscoveryHttpClientHandlerBase(discoveryClient, logger); 39 | _logger = logger; 40 | } 41 | 42 | /// 43 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 44 | { 45 | var current = request.RequestUri; 46 | try 47 | { 48 | request.RequestUri = await _discoveryBase.LookupServiceAsync(current); 49 | return await base.SendAsync(request, cancellationToken); 50 | } 51 | catch (Exception e) 52 | { 53 | _logger?.LogDebug(e, "Exception during SendAsync()"); 54 | throw; 55 | } 56 | finally 57 | { 58 | request.RequestUri = current; 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Discovery/DiscoveryHttpClientHandlerBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using Steeltoe.Common.LoadBalancer; 17 | using System; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Discovery 21 | { 22 | public class DiscoveryHttpClientHandlerBase 23 | { 24 | protected IDiscoveryClient _client; 25 | protected ILoadBalancer _loadBalancer; 26 | protected ILogger _logger; 27 | 28 | public DiscoveryHttpClientHandlerBase(IDiscoveryClient client, ILogger logger = null, ILoadBalancer loadBalancer = null) 29 | { 30 | _client = client ?? throw new ArgumentNullException(nameof(client)); 31 | _loadBalancer = loadBalancer ?? new RandomLoadBalancer(client); 32 | _logger = logger; 33 | } 34 | 35 | public virtual Uri LookupService(Uri current) 36 | { 37 | _logger?.LogDebug("LookupService({0})", current.ToString()); 38 | if (!current.IsDefaultPort) 39 | { 40 | return current; 41 | } 42 | 43 | return Task.Run(async () => await _loadBalancer.ResolveServiceInstanceAsync(current)).Result; 44 | } 45 | 46 | public virtual async Task LookupServiceAsync(Uri current) 47 | { 48 | _logger?.LogDebug("LookupService({0})", current.ToString()); 49 | if (!current.IsDefaultPort) 50 | { 51 | return current; 52 | } 53 | 54 | return await _loadBalancer.ResolveServiceInstanceAsync(current); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Discovery/DiscoveryHttpMessageHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using Steeltoe.Common.Discovery; 17 | using System; 18 | using System.Net.Http; 19 | using System.Threading; 20 | using System.Threading.Tasks; 21 | 22 | namespace Steeltoe.Common.Http.Discovery 23 | { 24 | /// 25 | /// A implementation that performs Service Discovery 26 | /// 27 | public class DiscoveryHttpMessageHandler : DelegatingHandler 28 | { 29 | private readonly ILogger _logger; 30 | private DiscoveryHttpClientHandlerBase _discoveryBase; 31 | 32 | /// 33 | /// Initializes a new instance of the class. 34 | /// 35 | /// Service discovery client to use - provided by calling services.AddDiscoveryClient(Configuration) 36 | /// ILogger for capturing logs from Discovery operations 37 | public DiscoveryHttpMessageHandler(IDiscoveryClient discoveryClient, ILogger logger = null) 38 | { 39 | _discoveryBase = new DiscoveryHttpClientHandlerBase(discoveryClient, logger); 40 | _logger = logger; 41 | } 42 | 43 | /// 44 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 45 | { 46 | var current = request.RequestUri; 47 | try 48 | { 49 | request.RequestUri = await _discoveryBase.LookupServiceAsync(current); 50 | return await base.SendAsync(request, cancellationToken); 51 | } 52 | catch (Exception e) 53 | { 54 | _logger?.LogDebug(e, "Exception during SendAsync()"); 55 | throw; 56 | } 57 | finally 58 | { 59 | request.RequestUri = current; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/LoadBalancer/LoadBalancerDelegatingHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.DependencyInjection; 16 | using Microsoft.Extensions.Logging; 17 | using Steeltoe.Common.LoadBalancer; 18 | using System; 19 | using System.Net.Http; 20 | using System.Threading; 21 | using System.Threading.Tasks; 22 | 23 | namespace Steeltoe.Common.Http.LoadBalancer 24 | { 25 | /// 26 | /// Same as except is a , for use with HttpClientFactory 27 | /// 28 | public class LoadBalancerDelegatingHandler : DelegatingHandler 29 | { 30 | private readonly ILoadBalancer _loadBalancer; 31 | private readonly ILogger _logger; 32 | 33 | /// 34 | /// Initializes a new instance of the class. 35 | /// For use with 36 | /// 37 | /// Load balancer to use 38 | /// For logging 39 | public LoadBalancerDelegatingHandler(ILoadBalancer loadBalancer, ILogger logger = null) 40 | { 41 | _loadBalancer = loadBalancer ?? throw new ArgumentNullException(nameof(loadBalancer)); 42 | _logger = logger; 43 | } 44 | 45 | /// 46 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 47 | { 48 | // record the original request 49 | var originalUri = request.RequestUri; 50 | Uri resolvedUri = null; 51 | DateTime startTime = default(DateTime); 52 | DateTime endTime = default(DateTime); 53 | 54 | try 55 | { 56 | // look up a service instance and update the request 57 | resolvedUri = await _loadBalancer.ResolveServiceInstanceAsync(request.RequestUri); 58 | request.RequestUri = resolvedUri; 59 | 60 | // allow other handlers to operate and the request to continue 61 | startTime = DateTime.UtcNow; 62 | var response = await base.SendAsync(request, cancellationToken); 63 | endTime = DateTime.UtcNow; 64 | 65 | // track stats 66 | await _loadBalancer.UpdateStatsAsync(originalUri, resolvedUri, endTime - startTime, null); 67 | return response; 68 | } 69 | catch (Exception exception) 70 | { 71 | if (endTime == default(DateTime)) 72 | { 73 | endTime = DateTime.UtcNow; 74 | } 75 | 76 | _logger?.LogDebug(exception, "Exception during SendAsync()"); 77 | if (resolvedUri != null) 78 | { 79 | await _loadBalancer.UpdateStatsAsync(originalUri, resolvedUri, endTime - startTime, exception); 80 | } 81 | else 82 | { 83 | _logger?.LogWarning("resolvedUri was null. This might be an issue with your service discovery provider."); 84 | } 85 | 86 | throw; 87 | } 88 | finally 89 | { 90 | request.RequestUri = originalUri; 91 | } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/LoadBalancer/LoadBalancerHttpClientBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Caching.Distributed; 16 | using Microsoft.Extensions.DependencyInjection.Extensions; 17 | using Microsoft.Extensions.Logging; 18 | using Steeltoe.Common.Discovery; 19 | using Steeltoe.Common.Http.LoadBalancer; 20 | using Steeltoe.Common.LoadBalancer; 21 | using System; 22 | using System.Net.Http; 23 | 24 | namespace Microsoft.Extensions.DependencyInjection 25 | { 26 | public static class LoadBalancerHttpClientBuilderExtensions 27 | { 28 | /// 29 | /// Adds a that performs random load balancing 30 | /// 31 | /// The . 32 | /// Requires an or in the DI container so the load balancer can sent traffic to more than one address 33 | /// An that can be used to configure the client. 34 | public static IHttpClientBuilder AddRandomLoadBalancer(this IHttpClientBuilder httpClientBuilder) 35 | { 36 | if (httpClientBuilder == null) 37 | { 38 | throw new ArgumentNullException(nameof(httpClientBuilder)); 39 | } 40 | 41 | httpClientBuilder.Services.TryAddSingleton(typeof(RandomLoadBalancer)); 42 | return httpClientBuilder.AddLoadBalancer(); 43 | } 44 | 45 | /// 46 | /// Adds a that performs round robin load balancing, optionally backed by an 47 | /// 48 | /// The . 49 | /// 50 | /// Requires an or in the DI container so the load balancer can sent traffic to more than one address 51 | /// Also requires an in the DI Container for consistent round robin balancing across multiple client instances 52 | /// 53 | /// An that can be used to configure the client. 54 | public static IHttpClientBuilder AddRoundRobinLoadBalancer(this IHttpClientBuilder httpClientBuilder) 55 | { 56 | if (httpClientBuilder == null) 57 | { 58 | throw new ArgumentNullException(nameof(httpClientBuilder)); 59 | } 60 | 61 | httpClientBuilder.Services.TryAddSingleton(typeof(RoundRobinLoadBalancer)); 62 | return httpClientBuilder.AddLoadBalancer(); 63 | } 64 | 65 | /// 66 | /// Adds an with specified load balancer 67 | /// Does NOT add the specified load balancer to the container. Please add your load balancer separately. 68 | /// 69 | /// The . 70 | /// The type of to use 71 | /// An that can be used to configure the client. 72 | public static IHttpClientBuilder AddLoadBalancer(this IHttpClientBuilder httpClientBuilder) 73 | where T : ILoadBalancer 74 | { 75 | if (httpClientBuilder == null) 76 | { 77 | throw new ArgumentNullException(nameof(httpClientBuilder)); 78 | } 79 | 80 | httpClientBuilder.Services.TryAddTransient(); 81 | httpClientBuilder.AddHttpMessageHandler((services) => new LoadBalancerDelegatingHandler(services.GetRequiredService(), services.GetService())); 82 | return httpClientBuilder; 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/LoadBalancer/LoadBalancerHttpClientHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using Steeltoe.Common.LoadBalancer; 17 | using System; 18 | using System.Net.Http; 19 | using System.Threading; 20 | using System.Threading.Tasks; 21 | 22 | namespace Steeltoe.Common.Http.LoadBalancer 23 | { 24 | /// 25 | /// Same as except is an , for non-HttpClientFactory use 26 | /// 27 | public class LoadBalancerHttpClientHandler : HttpClientHandler 28 | { 29 | private readonly ILoadBalancer _loadBalancer; 30 | private readonly ILogger _logger; 31 | 32 | /// 33 | /// Initializes a new instance of the class. 34 | /// For use with without 35 | /// 36 | /// Load balancer to use 37 | /// For logging 38 | public LoadBalancerHttpClientHandler(ILoadBalancer loadBalancer, ILogger logger = null) 39 | { 40 | _loadBalancer = loadBalancer ?? throw new ArgumentNullException(nameof(loadBalancer)); 41 | _logger = logger; 42 | } 43 | 44 | /// 45 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 46 | { 47 | // record the original request 48 | var originalUri = request.RequestUri; 49 | Uri resolvedUri = null; 50 | DateTime startTime = default(DateTime); 51 | DateTime endTime = default(DateTime); 52 | 53 | try 54 | { 55 | // look up a service instance and update the request 56 | resolvedUri = await _loadBalancer.ResolveServiceInstanceAsync(request.RequestUri); 57 | request.RequestUri = resolvedUri; 58 | 59 | // allow other handlers to operate and the request to continue 60 | startTime = DateTime.UtcNow; 61 | var response = await base.SendAsync(request, cancellationToken); 62 | endTime = DateTime.UtcNow; 63 | 64 | // track stats 65 | await _loadBalancer.UpdateStatsAsync(originalUri, resolvedUri, endTime - startTime, null); 66 | return response; 67 | } 68 | catch (Exception exception) 69 | { 70 | if (endTime == default(DateTime)) 71 | { 72 | endTime = DateTime.UtcNow; 73 | } 74 | 75 | _logger?.LogDebug(exception, "Exception during SendAsync()"); 76 | if (resolvedUri != null) 77 | { 78 | await _loadBalancer.UpdateStatsAsync(originalUri, resolvedUri, endTime - startTime, exception); 79 | } 80 | else 81 | { 82 | _logger?.LogWarning("resolvedUri was null. This might be an issue with your service discovery provider."); 83 | } 84 | 85 | throw; 86 | } 87 | finally 88 | { 89 | request.RequestUri = originalUri; 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Runtime.CompilerServices; 16 | 17 | [assembly: InternalsVisibleTo("Steeltoe.Common.Http.Test")] 18 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/SerializationHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using Newtonsoft.Json; 17 | using System; 18 | using System.IO; 19 | 20 | namespace Steeltoe.Common.Http 21 | { 22 | public static class SerializationHelper 23 | { 24 | public static T Deserialize(Stream stream, ILogger logger = null) 25 | { 26 | if (stream == null) 27 | { 28 | throw new ArgumentNullException(nameof(stream)); 29 | } 30 | 31 | try 32 | { 33 | using (JsonReader reader = new JsonTextReader(new StreamReader(stream))) 34 | { 35 | JsonSerializer serializer = new JsonSerializer(); 36 | return (T)serializer.Deserialize(reader, typeof(T)); 37 | } 38 | } 39 | catch (Exception e) 40 | { 41 | logger?.LogError("Serialization exception: {0}", e); 42 | } 43 | 44 | return default(T); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Http/Steeltoe.Common.Http.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Steeltoe Common Library 5 | $(SteeltoeVersion) 6 | $(VersionSuffix) 7 | Pivotal;dtillman 8 | netstandard2.0 9 | Steeltoe.Common.Http 10 | Steeltoe.Common.Http 11 | NET Core;NET Framework 12 | https://steeltoe.io/images/transparent.png 13 | https://steeltoe.io 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | true 16 | true 17 | snupkg 18 | 19 | 20 | bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Http.xml 21 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | All 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | stylecop.json 44 | Always 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Net/MPR.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Runtime.InteropServices; 17 | using System.Text; 18 | using static Steeltoe.Common.Net.WindowsNetworkFileShare; 19 | 20 | namespace Steeltoe.Common.Net 21 | { 22 | internal class MPR : IMPR 23 | { 24 | public MPR() 25 | { 26 | if (!Platform.IsWindows) 27 | { 28 | throw new PlatformNotSupportedException("Sorry, this functionality only works on Windows"); 29 | } 30 | } 31 | 32 | public int AddConnection(NetResource netResource, string password, string username, int flags) 33 | { 34 | return WNetAddConnection2(netResource, password, username, flags); 35 | } 36 | 37 | public int UseConnection(IntPtr hwndOwner, NetResource netResource, string password, string username, int flags, string lpAccessName, string lpBufferSize, string lpResult) 38 | { 39 | return WNetUseConnection(hwndOwner, netResource, password, username, flags, lpAccessName, lpBufferSize, lpResult); 40 | } 41 | 42 | public int CancelConnection(string name, int flags, bool force) 43 | { 44 | return WNetCancelConnection2(name, flags, force); 45 | } 46 | 47 | public int GetLastError(out int error, out StringBuilder errorBuf, int errorBufSize, out StringBuilder nameBuf, int nameBufSize) 48 | { 49 | return WNetGetLastError(out error, out errorBuf, errorBufSize, out nameBuf, nameBufSize); 50 | } 51 | 52 | [DllImport("mpr.dll")] 53 | private static extern int WNetAddConnection2( 54 | NetResource netResource, 55 | string password, 56 | string username, 57 | int flags); 58 | 59 | [DllImport("mpr.dll")] 60 | private static extern int WNetCancelConnection2( 61 | string name, 62 | int flags, 63 | bool force); 64 | 65 | [DllImport("mpr.dll")] 66 | private static extern int WNetUseConnection( 67 | IntPtr hwndOwner, 68 | NetResource netResource, 69 | string password, 70 | string username, 71 | int flags, 72 | string lpAccessName, 73 | string lpBufferSize, 74 | string lpResult); 75 | 76 | [DllImport("mpr.dll", CharSet = CharSet.Auto)] 77 | private static extern int WNetGetLastError( 78 | out int error, 79 | out StringBuilder errorBuf, 80 | int errorBufSize, 81 | out StringBuilder nameBuf, 82 | int nameBufSize); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Net/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Runtime.CompilerServices; 16 | 17 | [assembly: InternalsVisibleTo("Steeltoe.Common.Net.Test")] 18 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Net/Steeltoe.Common.Net.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Steeltoe Common Library 5 | $(SteeltoeVersion) 6 | $(VersionSuffix) 7 | Pivotal;dtillman 8 | netstandard2.0 9 | Steeltoe.Common.Net 10 | Steeltoe.Common.Net 11 | NET Core;NET Framework 12 | https://steeltoe.io/images/transparent.png 13 | https://steeltoe.io 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | true 16 | true 17 | snupkg 18 | 19 | 20 | bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Net.xml 21 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | All 35 | 36 | 37 | 38 | 39 | stylecop.json 40 | Always 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/CertificateOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Security.Cryptography.X509Certificates; 16 | 17 | namespace Steeltoe.Common.Security 18 | { 19 | public class CertificateOptions : ICertificateOptions 20 | { 21 | public string Name { get; set; } 22 | 23 | public X509Certificate2 Certificate { get; set; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/ICertificateOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Security.Cryptography.X509Certificates; 16 | 17 | namespace Steeltoe.Common.Security 18 | { 19 | public interface ICertificateOptions 20 | { 21 | string Name { get; } 22 | 23 | X509Certificate2 Certificate { get; } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/PemCertificateProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System; 17 | using System.Collections.Generic; 18 | 19 | namespace Steeltoe.Common.Security 20 | { 21 | public class PemCertificateProvider : ConfigurationProvider 22 | { 23 | private IConfigurationRoot _certFileProvider; 24 | private IConfigurationRoot _keyFileProvider; 25 | 26 | public PemCertificateProvider(IConfigurationRoot certFileProvider, IConfigurationRoot keyFileProvider) 27 | { 28 | _certFileProvider = certFileProvider; 29 | _keyFileProvider = keyFileProvider; 30 | _certFileProvider.GetReloadToken().RegisterChangeCallback(NotifyCertChanged, null); 31 | _keyFileProvider.GetReloadToken().RegisterChangeCallback(NotifyKeyChanged, null); 32 | } 33 | 34 | public override void Load() 35 | { 36 | } 37 | 38 | public override void Set(string key, string value) 39 | { 40 | throw new InvalidOperationException(); 41 | } 42 | 43 | public override bool TryGet(string key, out string value) 44 | { 45 | value = _certFileProvider[key]; 46 | if (!string.IsNullOrEmpty(value)) 47 | { 48 | return true; 49 | } 50 | 51 | value = _keyFileProvider[key]; 52 | if (!string.IsNullOrEmpty(value)) 53 | { 54 | return true; 55 | } 56 | 57 | return false; 58 | } 59 | 60 | public override IEnumerable GetChildKeys(IEnumerable earlierKeys, string parentPath) 61 | { 62 | return base.GetChildKeys(earlierKeys, parentPath); 63 | } 64 | 65 | private void NotifyCertChanged(object state) 66 | { 67 | OnReload(); 68 | _certFileProvider.GetReloadToken().RegisterChangeCallback(NotifyCertChanged, null); 69 | } 70 | 71 | private void NotifyKeyChanged(object state) 72 | { 73 | OnReload(); 74 | _keyFileProvider.GetReloadToken().RegisterChangeCallback(NotifyKeyChanged, null); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/PemCertificateSource.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System.IO; 17 | 18 | namespace Steeltoe.Common.Security 19 | { 20 | public class PemCertificateSource : IConfigurationSource 21 | { 22 | private string _certFilePath; 23 | private string _keyFilePath; 24 | 25 | public PemCertificateSource(string certFilePath, string keyFilePath) 26 | { 27 | _certFilePath = Path.GetFullPath(certFilePath); 28 | _keyFilePath = Path.GetFullPath(keyFilePath); 29 | } 30 | 31 | public IConfigurationProvider Build(IConfigurationBuilder builder) 32 | { 33 | var certSource = new FileSource("certificate") 34 | { 35 | FileProvider = null, 36 | Path = Path.GetFileName(_certFilePath), 37 | Optional = false, 38 | ReloadOnChange = true, 39 | ReloadDelay = 1000 40 | }; 41 | 42 | var keySource = new FileSource("privateKey") 43 | { 44 | FileProvider = null, 45 | Path = Path.GetFileName(_keyFilePath), 46 | Optional = false, 47 | ReloadOnChange = true, 48 | ReloadDelay = 1000, 49 | }; 50 | 51 | var certProvider = new ConfigurationBuilder() 52 | .SetBasePath(Path.GetDirectoryName(_certFilePath)) 53 | .Add(certSource) 54 | .Build(); 55 | 56 | var keyProvider = new ConfigurationBuilder() 57 | .SetBasePath(Path.GetDirectoryName(_keyFilePath)) 58 | .Add(keySource) 59 | .Build(); 60 | 61 | return new PemCertificateProvider(certProvider, keyProvider); 62 | } 63 | } 64 | 65 | #pragma warning disable SA1402 // File may only contain a single class 66 | internal class FileSource : FileConfigurationSource 67 | { 68 | internal string Key { get; } 69 | 70 | public FileSource(string key) 71 | : base() 72 | { 73 | Key = key; 74 | } 75 | 76 | public override IConfigurationProvider Build(IConfigurationBuilder builder) 77 | { 78 | EnsureDefaults(builder); 79 | return new FileProvider(this); 80 | } 81 | } 82 | 83 | internal class FileProvider : FileConfigurationProvider 84 | { 85 | public FileProvider(FileConfigurationSource source) 86 | : base(source) 87 | { 88 | } 89 | 90 | public override void Load(Stream stream) 91 | { 92 | var source = Source as FileSource; 93 | string key = source.Key; 94 | using (var reader = new StreamReader(stream)) 95 | { 96 | string value = reader.ReadToEnd(); 97 | Data[key] = value; 98 | } 99 | } 100 | } 101 | #pragma warning restore SA1402 // File may only contain a single class 102 | } 103 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/PemConfigurationExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.FileProviders; 17 | using System; 18 | 19 | namespace Steeltoe.Common.Security 20 | { 21 | public static class PemConfigurationExtensions 22 | { 23 | public static IConfigurationBuilder AddPemFiles(this IConfigurationBuilder builder, string certFilePath, string keyFilePath) 24 | { 25 | if (builder == null) 26 | { 27 | throw new ArgumentNullException(nameof(builder)); 28 | } 29 | 30 | if (string.IsNullOrEmpty(certFilePath)) 31 | { 32 | throw new ArgumentException(nameof(certFilePath)); 33 | } 34 | 35 | if (string.IsNullOrEmpty(keyFilePath)) 36 | { 37 | throw new ArgumentException(nameof(keyFilePath)); 38 | } 39 | 40 | builder.Add(new PemCertificateSource(certFilePath, keyFilePath)); 41 | return builder; 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/PemConfigureCertificateOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.Logging; 17 | using Microsoft.Extensions.Options; 18 | using Org.BouncyCastle.Crypto; 19 | using Org.BouncyCastle.OpenSsl; 20 | using Org.BouncyCastle.Pkcs; 21 | using Org.BouncyCastle.Security; 22 | using Org.BouncyCastle.X509; 23 | using System; 24 | using System.IO; 25 | using System.Text; 26 | using MS = System.Security.Cryptography.X509Certificates; 27 | 28 | namespace Steeltoe.Common.Security 29 | { 30 | public class PemConfigureCertificateOptions : IConfigureNamedOptions 31 | { 32 | private IConfiguration _config; 33 | private ILogger _logger; 34 | 35 | public PemConfigureCertificateOptions(IConfiguration config, ILogger logger = null) 36 | { 37 | if (config == null) 38 | { 39 | throw new ArgumentNullException(nameof(config)); 40 | } 41 | 42 | _config = config; 43 | _logger = logger; 44 | } 45 | 46 | public void Configure(string name, CertificateOptions options) 47 | { 48 | if (options == null) 49 | { 50 | throw new ArgumentNullException(nameof(options)); 51 | } 52 | 53 | options.Name = name; 54 | 55 | var pemCert = _config["certificate"]; 56 | var pemKey = _config["privateKey"]; 57 | 58 | if (string.IsNullOrEmpty(pemCert) || string.IsNullOrEmpty(pemKey)) 59 | { 60 | return; 61 | } 62 | 63 | var certBytes = Encoding.Default.GetBytes(pemCert); 64 | var keyBytes = Encoding.Default.GetBytes(pemKey); 65 | 66 | X509Certificate cert = ReadCertificate(certBytes); 67 | AsymmetricCipherKeyPair keys = ReadKeys(keyBytes); 68 | 69 | var pfxBytes = CreatePfxContainer(cert, keys); 70 | options.Certificate = new MS.X509Certificate2(pfxBytes); 71 | } 72 | 73 | public void Configure(CertificateOptions options) 74 | { 75 | Configure(Options.DefaultName, options); 76 | } 77 | 78 | internal byte[] CreatePfxContainer(X509Certificate cert, AsymmetricCipherKeyPair keys) 79 | { 80 | var certEntry = new X509CertificateEntry(cert); 81 | 82 | var pkcs12Store = new Pkcs12StoreBuilder() 83 | .SetUseDerEncoding(true) 84 | .Build(); 85 | var keyEntry = new AsymmetricKeyEntry(keys.Private); 86 | pkcs12Store.SetKeyEntry("ServerInstance", keyEntry, new X509CertificateEntry[] { certEntry }); 87 | 88 | using (MemoryStream stream = new MemoryStream()) 89 | { 90 | pkcs12Store.Save(stream, null, new SecureRandom()); 91 | var bytes = stream.ToArray(); 92 | return Pkcs12Utilities.ConvertToDefiniteLength(bytes); 93 | } 94 | } 95 | 96 | internal AsymmetricCipherKeyPair ReadKeys(byte[] keyBytes) 97 | { 98 | try 99 | { 100 | using (var reader = new StreamReader(new MemoryStream(keyBytes))) 101 | { 102 | return new PemReader(reader).ReadObject() as AsymmetricCipherKeyPair; 103 | } 104 | } 105 | catch (Exception e) 106 | { 107 | _logger?.LogError(e, "Unable to read PEM encoded keys"); 108 | } 109 | 110 | return null; 111 | } 112 | 113 | internal X509Certificate ReadCertificate(byte[] certBytes) 114 | { 115 | try 116 | { 117 | using (var reader = new StreamReader(new MemoryStream(certBytes))) 118 | { 119 | return new PemReader(reader).ReadObject() as X509Certificate; 120 | } 121 | } 122 | catch (Exception e) 123 | { 124 | _logger?.LogError(e, "Unable to read PEM encoded certificate"); 125 | } 126 | 127 | return null; 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/Steeltoe.Common.Security/Steeltoe.Common.Security.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Steeltoe Common Security Library 5 | $(SteeltoeVersion) 6 | $(VersionSuffix) 7 | Pivotal;dtillman 8 | netstandard2.0 9 | Steeltoe.Common.Security 10 | Steeltoe.Common.Security 11 | NET Core;NET Framework 12 | https://steeltoe.io/images/transparent.png 13 | https://steeltoe.io 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | true 16 | true 17 | snupkg 18 | 19 | 20 | bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.Security.xml 21 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | All 35 | 36 | 37 | 38 | 39 | 40 | stylecop.json 41 | Always 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Configuration/ConfigurationValuesHelper.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System; 17 | 18 | namespace Steeltoe.Common.Configuration 19 | { 20 | public static class ConfigurationValuesHelper 21 | { 22 | public static string GetSetting(string key, IConfiguration primary, IConfiguration secondary, IConfiguration resolve, string def) 23 | { 24 | // First check for key in primary 25 | var setting = GetString(key, primary, resolve, null); 26 | if (!string.IsNullOrEmpty(setting)) 27 | { 28 | return setting; 29 | } 30 | 31 | // Next check for key in secondary 32 | setting = GetString(key, secondary, resolve, null); 33 | if (!string.IsNullOrEmpty(setting)) 34 | { 35 | return setting; 36 | } 37 | 38 | return def; 39 | } 40 | 41 | public static int GetInt(string key, IConfiguration config, IConfiguration resolve, int def) 42 | { 43 | var val = GetString(key, config, resolve, null); 44 | if (!string.IsNullOrEmpty(val)) 45 | { 46 | int result; 47 | if (int.TryParse(val, out result)) 48 | { 49 | return result; 50 | } 51 | } 52 | 53 | return def; 54 | } 55 | 56 | public static double GetDouble(string key, IConfiguration config, IConfiguration resolve, double def) 57 | { 58 | var val = GetString(key, config, resolve, null); 59 | if (!string.IsNullOrEmpty(val)) 60 | { 61 | double result; 62 | if (double.TryParse(val, out result)) 63 | { 64 | return result; 65 | } 66 | } 67 | 68 | return def; 69 | } 70 | 71 | public static bool GetBoolean(string key, IConfiguration config, IConfiguration resolve, bool def) 72 | { 73 | var val = GetString(key, config, resolve, null); 74 | if (!string.IsNullOrEmpty(val)) 75 | { 76 | bool result; 77 | if (bool.TryParse(val, out result)) 78 | { 79 | return result; 80 | } 81 | } 82 | 83 | return def; 84 | } 85 | 86 | public static string GetString(string key, IConfiguration config, IConfiguration resolve, string def) 87 | { 88 | if (string.IsNullOrEmpty(key)) 89 | { 90 | throw new ArgumentException(nameof(key)); 91 | } 92 | 93 | if (config == null) 94 | { 95 | throw new ArgumentNullException(nameof(config)); 96 | } 97 | 98 | var val = config[key]; 99 | if (!string.IsNullOrEmpty(val)) 100 | { 101 | return PropertyPlaceholderHelper.ResolvePlaceholders(val, resolve); 102 | } 103 | 104 | return def; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Configuration/IConfigurationBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.Logging; 17 | using System; 18 | 19 | namespace Steeltoe.Common.Configuration 20 | { 21 | public static class IConfigurationBuilderExtensions 22 | { 23 | /// 24 | /// Finds all placeholders of the form ${some:config:reference?default_if_not_present}, 25 | /// resolves them from other values in the configuration, adds resolved values to your configuration. 26 | /// 27 | /// The which contains properties to be resolved 28 | /// Replace unresolved placeholders with empty strings, so the application does not see them 29 | /// Optional logger 30 | /// with additional provider which contains resolved placeholders 31 | public static IConfigurationBuilder AddResolvedPlaceholders(this IConfigurationBuilder configurationBuilder, bool useEmptyStringIfNotFound = true, ILogger logger = null) 32 | { 33 | if (configurationBuilder == null) 34 | { 35 | throw new ArgumentNullException(nameof(configurationBuilder)); 36 | } 37 | 38 | return configurationBuilder.AddInMemoryCollection(PropertyPlaceholderHelper.GetResolvedConfigurationPlaceholders(configurationBuilder.Build(), logger, useEmptyStringIfNotFound)); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Diagnostics/DiagnosticHelpers.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Reflection; 18 | using System.Text; 19 | 20 | namespace Steeltoe.Common.Diagnostics 21 | { 22 | public static class DiagnosticHelpers 23 | { 24 | // TODO: Fix perf of this code 25 | public static T GetProperty(object o, string name) 26 | { 27 | var property = o.GetType().GetProperty(name, BindingFlags.Instance | BindingFlags.Public); 28 | if (property == null) 29 | { 30 | return default(T); 31 | } 32 | 33 | return (T)property.GetValue(o); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Diagnostics/DiagnosticObserver.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Logging; 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Diagnostics; 19 | using System.Text; 20 | 21 | namespace Steeltoe.Common.Diagnostics 22 | { 23 | public abstract class DiagnosticObserver : IDiagnosticObserver 24 | { 25 | public string ListenerName { get; } 26 | 27 | public string ObserverName { get; } 28 | 29 | protected ILogger Logger { get; } 30 | 31 | protected IDisposable Subscription { get; set; } 32 | 33 | protected DiagnosticObserver(string name, string listenerName, ILogger logger = null) 34 | { 35 | if (string.IsNullOrEmpty(name)) 36 | { 37 | throw new ArgumentException(nameof(name)); 38 | } 39 | 40 | if (string.IsNullOrEmpty(listenerName)) 41 | { 42 | throw new ArgumentException(nameof(listenerName)); 43 | } 44 | 45 | ObserverName = name; 46 | ListenerName = listenerName; 47 | Logger = logger; 48 | } 49 | 50 | public void Dispose() 51 | { 52 | if (Subscription != null) 53 | { 54 | Subscription.Dispose(); 55 | } 56 | 57 | Subscription = null; 58 | Logger?.LogInformation("DiagnosticObserver {observer} Disposed", ObserverName); 59 | } 60 | 61 | public void Subscribe(DiagnosticListener listener) 62 | { 63 | if (ListenerName == listener.Name) 64 | { 65 | if (Subscription != null) 66 | { 67 | Dispose(); 68 | } 69 | 70 | Subscription = listener.Subscribe(this); 71 | Logger?.LogInformation("DiagnosticObserver {observer} Subscribed to {listener}", ObserverName, listener.Name); 72 | } 73 | } 74 | 75 | public virtual void OnCompleted() 76 | { 77 | } 78 | 79 | public virtual void OnError(Exception error) 80 | { 81 | } 82 | 83 | public virtual void OnNext(KeyValuePair @event) 84 | { 85 | try 86 | { 87 | ProcessEvent(@event.Key, @event.Value); 88 | } 89 | catch (Exception e) 90 | { 91 | Logger?.LogError(e, "ProcessEvent exception: {Id}", @event.Key); 92 | } 93 | } 94 | 95 | public abstract void ProcessEvent(string @event, object arg); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Diagnostics/IDiagnosticObserver.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Diagnostics; 18 | using System.Text; 19 | 20 | namespace Steeltoe.Common.Diagnostics 21 | { 22 | public interface IDiagnosticObserver : IObserver> 23 | { 24 | string ObserverName { get; } 25 | 26 | string ListenerName { get; } 27 | 28 | void Subscribe(DiagnosticListener listener); 29 | 30 | void Dispose(); 31 | 32 | void ProcessEvent(string @event, object value); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Diagnostics/IDiagnosticsManager.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Diagnostics 16 | { 17 | public interface IDiagnosticsManager 18 | { 19 | void Start(); 20 | 21 | void Stop(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Diagnostics/IPolledDiagnosticSource.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | using System.Text; 18 | 19 | namespace Steeltoe.Common.Diagnostics 20 | { 21 | public interface IPolledDiagnosticSource 22 | { 23 | void Poll(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/ConfigurationServiceInstance.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace Steeltoe.Common.Discovery 19 | { 20 | public class ConfigurationServiceInstance : IServiceInstance 21 | { 22 | public string ServiceId { get; set; } 23 | 24 | public string Host { get; set; } 25 | 26 | public int Port { get; set; } 27 | 28 | public bool IsSecure { get; set; } 29 | 30 | public Uri Uri => new Uri((IsSecure ? Uri.UriSchemeHttps : Uri.UriSchemeHttp) + Uri.SchemeDelimiter + Host + ':' + Port); 31 | 32 | public IDictionary Metadata { get; set; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/ConfigurationServiceInstanceProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Options; 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | 20 | namespace Steeltoe.Common.Discovery 21 | { 22 | public class ConfigurationServiceInstanceProvider : IServiceInstanceProvider 23 | { 24 | private readonly IOptionsMonitor> _serviceInstances; 25 | 26 | public ConfigurationServiceInstanceProvider(IOptionsMonitor> serviceInstances) 27 | { 28 | _serviceInstances = serviceInstances; 29 | } 30 | 31 | public string Description => "A service instance provider that returns services from app configuration"; 32 | 33 | public IList Services => _serviceInstances.CurrentValue.Select(si => si.ServiceId).Distinct().ToList(); 34 | 35 | public IList GetInstances(string serviceId) 36 | { 37 | return new List(_serviceInstances.CurrentValue.Where(si => si.ServiceId.Equals(serviceId, StringComparison.InvariantCultureIgnoreCase))); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/ConfigurationServiceInstanceProviderServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Steeltoe.Common.Discovery; 17 | using System; 18 | using System.Collections.Generic; 19 | 20 | namespace Microsoft.Extensions.DependencyInjection 21 | { 22 | public static class ConfigurationServiceInstanceProviderServiceCollectionExtensions 23 | { 24 | /// 25 | /// Adds an IConfiguration-based to the 26 | /// 27 | /// Your 28 | /// Application configuration 29 | /// Lifetime of the 30 | /// IServiceCollection for chaining 31 | public static IServiceCollection AddConfigurationDiscoveryClient(this IServiceCollection services, IConfiguration configuration, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton) 32 | { 33 | if (services == null) 34 | { 35 | throw new ArgumentNullException(nameof(services)); 36 | } 37 | 38 | if (configuration == null) 39 | { 40 | throw new ArgumentNullException(nameof(configuration)); 41 | } 42 | 43 | services.Add(new ServiceDescriptor(typeof(IServiceInstanceProvider), typeof(ConfigurationServiceInstanceProvider), serviceLifetime)); 44 | services.AddOptions(); 45 | services.Configure>(configuration.GetSection("discovery:services")); 46 | return services; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/DiscoveryOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System; 17 | 18 | namespace Steeltoe.Common.Discovery 19 | { 20 | public enum DiscoveryClientType 21 | { 22 | EUREKA, UNKNOWN 23 | } 24 | 25 | public class DiscoveryOptions 26 | { 27 | protected string _type; 28 | protected IDiscoveryClientOptions _clientOptions; 29 | protected IDiscoveryRegistrationOptions _registrationOptions; 30 | 31 | public DiscoveryOptions(IConfiguration config) 32 | : this() 33 | { 34 | if (config == null) 35 | { 36 | throw new ArgumentNullException(nameof(config)); 37 | } 38 | 39 | Configure(config); 40 | } 41 | 42 | public DiscoveryOptions() 43 | { 44 | ClientType = DiscoveryClientType.UNKNOWN; 45 | } 46 | 47 | public string Type 48 | { 49 | get 50 | { 51 | return _type; 52 | } 53 | } 54 | 55 | public DiscoveryClientType ClientType 56 | { 57 | get 58 | { 59 | if (string.IsNullOrEmpty(_type)) 60 | { 61 | return DiscoveryClientType.UNKNOWN; 62 | } 63 | 64 | return (DiscoveryClientType)System.Enum.Parse(typeof(DiscoveryClientType), _type); 65 | } 66 | 67 | set 68 | { 69 | _type = System.Enum.GetName(typeof(DiscoveryClientType), value); 70 | } 71 | } 72 | 73 | public IDiscoveryClientOptions ClientOptions 74 | { 75 | get 76 | { 77 | return _clientOptions; 78 | } 79 | 80 | set 81 | { 82 | _clientOptions = value; 83 | } 84 | } 85 | 86 | public IDiscoveryRegistrationOptions RegistrationOptions 87 | { 88 | get 89 | { 90 | return _registrationOptions; 91 | } 92 | 93 | set 94 | { 95 | _registrationOptions = value; 96 | } 97 | } 98 | 99 | public virtual void Configure(IConfiguration config) 100 | { 101 | ClientType = DiscoveryClientType.UNKNOWN; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IDiscoveryClient.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Threading.Tasks; 16 | 17 | namespace Steeltoe.Common.Discovery 18 | { 19 | public interface IDiscoveryClient : IServiceInstanceProvider 20 | { 21 | /// 22 | /// ServiceInstance with information used to register the local service 23 | /// 24 | /// The IServiceInstance 25 | IServiceInstance GetLocalServiceInstance(); 26 | 27 | Task ShutdownAsync(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IDiscoveryClientOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Discovery 16 | { 17 | public interface IDiscoveryClientOptions 18 | { 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IDiscoveryLifecycle.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Threading; 16 | 17 | namespace Steeltoe.Common.Discovery 18 | { 19 | public interface IDiscoveryLifecycle 20 | { 21 | CancellationToken ApplicationStopping { get; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IDiscoveryRegistrationOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Discovery 16 | { 17 | public interface IDiscoveryRegistrationOptions 18 | { 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IServiceInstance.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace Steeltoe.Common.Discovery 19 | { 20 | public interface IServiceInstance 21 | { 22 | /// 23 | /// Gets the service id as register by the DiscoveryClient 24 | /// 25 | string ServiceId { get; } 26 | 27 | /// 28 | /// Gets the hostname of the registered ServiceInstance 29 | /// 30 | string Host { get; } 31 | 32 | /// 33 | /// Gets the port of the registered ServiceInstance 34 | /// 35 | int Port { get; } 36 | 37 | /// 38 | /// Gets a value indicating whether if the port of the registered ServiceInstance is https or not 39 | /// 40 | bool IsSecure { get; } 41 | 42 | /// 43 | /// Gets the service uri address 44 | /// 45 | Uri Uri { get; } 46 | 47 | /// 48 | /// Gets the key value pair metadata associated with the service instance 49 | /// 50 | IDictionary Metadata { get; } 51 | 52 | // TODO: Steeltoe 3.0, add for compat with spring cloud 53 | // string InstanceId { get; } 54 | 55 | // string Scheme { get; } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IServiceInstanceProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | 17 | namespace Steeltoe.Common.Discovery 18 | { 19 | public interface IServiceInstanceProvider 20 | { 21 | /// 22 | /// Gets a human readable description of the implementation 23 | /// 24 | string Description { get; } 25 | 26 | /// 27 | /// Gets all known service Ids 28 | /// 29 | IList Services { get; } 30 | 31 | /// 32 | /// Get all ServiceInstances associated with a particular serviceId 33 | /// 34 | /// the serviceId to lookup 35 | /// List of service instances 36 | IList GetInstances(string serviceId); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IServiceInstanceProviderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Caching.Distributed; 16 | using System.Collections.Generic; 17 | using System.IO; 18 | using System.Linq; 19 | using System.Runtime.Serialization.Formatters.Binary; 20 | using System.Threading.Tasks; 21 | 22 | namespace Steeltoe.Common.Discovery 23 | { 24 | public static class IServiceInstanceProviderExtensions 25 | { 26 | public static async Task> GetInstancesWithCacheAsync(this IServiceInstanceProvider serviceInstanceProvider, string serviceId, IDistributedCache distributedCache = null, string serviceInstancesKeyPrefix = "ServiceInstances-") 27 | { 28 | // if distributed cache was provided, just make the call back to the provider 29 | if (distributedCache != null) 30 | { 31 | // check the cache for existing service instances 32 | var instanceData = await distributedCache.GetAsync(serviceInstancesKeyPrefix + serviceId); 33 | if (instanceData != null && instanceData.Length > 0) 34 | { 35 | return DeserializeFromCache>(instanceData).ToList(); 36 | } 37 | } 38 | 39 | // cache not found or instances not found, call out to the provider 40 | var instances = serviceInstanceProvider.GetInstances(serviceId); 41 | if (distributedCache != null) 42 | { 43 | await distributedCache.SetAsync(serviceInstancesKeyPrefix + serviceId, SerializeForCache(MapToSerializable(instances))); 44 | } 45 | 46 | return instances; 47 | } 48 | 49 | private static List MapToSerializable(IList instances) 50 | { 51 | var inst = instances.Select(i => new SerializableIServiceInstance(i)); 52 | return inst.ToList(); 53 | } 54 | 55 | private static byte[] SerializeForCache(object data) 56 | { 57 | using (var stream = new MemoryStream()) 58 | { 59 | new BinaryFormatter().Serialize(stream, data); 60 | return stream.ToArray(); 61 | } 62 | } 63 | 64 | private static T DeserializeFromCache(byte[] data) 65 | where T : class 66 | { 67 | using (var stream = new MemoryStream(data)) 68 | { 69 | return new BinaryFormatter().Deserialize(stream) as T; 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/IServiceRegistry.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | 17 | namespace Steeltoe.Common.Discovery 18 | { 19 | /// 20 | /// Represents a Service registry (e.g. Consul, etc.) 21 | /// 22 | /// a type representing a service instance 23 | public interface IServiceRegistry : IDisposable 24 | where T : IServiceInstance 25 | { 26 | /// 27 | /// Register a service instance in the service registry 28 | /// 29 | /// the service instance to register 30 | void Register(T registration); 31 | 32 | /// 33 | /// Deregister a service instance in the service registry 34 | /// 35 | /// the service instance to register 36 | void Deregister(T registration); 37 | 38 | /// 39 | /// Update the registration in the service registry with the provided status 40 | /// 41 | /// the registration to update 42 | /// the status 43 | void SetStatus(T registration, string status); 44 | 45 | /// 46 | /// Return the current status of the service registry registration 47 | /// 48 | /// the status 49 | /// the service registration to obtain status for 50 | /// the returned status 51 | S GetStatus(T registration) 52 | where S : class; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Discovery/SerializableIServiceInstance.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace Steeltoe.Common.Discovery 19 | { 20 | [Serializable] 21 | public class SerializableIServiceInstance : IServiceInstance 22 | { 23 | public SerializableIServiceInstance(IServiceInstance instance) 24 | { 25 | ServiceId = instance.ServiceId; 26 | Host = instance.Host; 27 | Port = instance.Port; 28 | IsSecure = instance.IsSecure; 29 | Uri = instance.Uri; 30 | Metadata = instance.Metadata; 31 | } 32 | 33 | public string ServiceId { get; set; } 34 | 35 | public string Host { get; set; } 36 | 37 | public int Port { get; set; } 38 | 39 | public bool IsSecure { get; set; } 40 | 41 | public Uri Uri { get; set; } 42 | 43 | public IDictionary Metadata { get; set; } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/HealthChecks/HealthCheckResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | 17 | namespace Steeltoe.Common.HealthChecks 18 | { 19 | /// 20 | /// The result of a health check 21 | /// 22 | public class HealthCheckResult 23 | { 24 | /// 25 | /// Gets or sets the status of the check 26 | /// 27 | /// Used by HealthMiddleware to determine HTTP Status code 28 | public HealthStatus Status { get; set; } = HealthStatus.UNKNOWN; 29 | 30 | /// 31 | /// Gets or sets a description of the health check result 32 | /// 33 | /// Currently only used on check failures 34 | public string Description { get; set; } 35 | 36 | /// 37 | /// Gets or sets details of the checked item 38 | /// 39 | /// For parity with Spring Boot, repeat status [with a call to .ToString()] here 40 | public Dictionary Details { get; set; } = new Dictionary(); 41 | } 42 | } -------------------------------------------------------------------------------- /src/Steeltoe.Common/HealthChecks/HealthStatus.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.HealthChecks 16 | { 17 | public enum HealthStatus 18 | { 19 | UNKNOWN, 20 | UP, 21 | WARNING, 22 | OUT_OF_SERVICE, 23 | DOWN, 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/HealthChecks/IHealthContributor.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.HealthChecks 16 | { 17 | /// 18 | /// Implement this interface and add to DI to be included in health checks 19 | /// 20 | public interface IHealthContributor 21 | { 22 | /// 23 | /// Gets an identifier for the type of check being performed 24 | /// 25 | string Id { get; } 26 | 27 | /// 28 | /// Check the health of a resource 29 | /// 30 | /// The result of checking the health of a resource 31 | HealthCheckResult Health(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/LoadBalancer/ILoadBalancer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Threading.Tasks; 17 | 18 | namespace Steeltoe.Common.LoadBalancer 19 | { 20 | public interface ILoadBalancer 21 | { 22 | /// 23 | /// Evaluates a Uri for a host name that can be resolved into a service instance 24 | /// 25 | /// A Uri containing a service name that can be resolved into one or more service instances 26 | /// The original Uri, with serviceName replaced by the host:port of a service instance 27 | Task ResolveServiceInstanceAsync(Uri request); 28 | 29 | /// 30 | /// A mechanism for tracking statistics for service instances 31 | /// 32 | /// The original request Uri 33 | /// The Uri resolved by the load balancer 34 | /// The amount of time taken for a remote call to complete 35 | /// Any exception called during calls to a resolved service instance 36 | /// A task 37 | Task UpdateStatsAsync(Uri originalUri, Uri resolvedUri, TimeSpan responseTime, Exception exception); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/LoadBalancer/RandomLoadBalancer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Caching.Distributed; 16 | using Microsoft.Extensions.Logging; 17 | using Steeltoe.Common.Discovery; 18 | using System; 19 | using System.Threading.Tasks; 20 | 21 | namespace Steeltoe.Common.LoadBalancer 22 | { 23 | public class RandomLoadBalancer : ILoadBalancer 24 | { 25 | private static readonly Random _random = new Random(); 26 | private readonly IServiceInstanceProvider _serviceInstanceProvider; 27 | private readonly IDistributedCache _distributedCache; 28 | private readonly ILogger _logger; 29 | 30 | /// 31 | /// Initializes a new instance of the class. 32 | /// Returns random service instances, with option caching of service lookups 33 | /// 34 | /// Provider of service instance information 35 | /// For caching service instance data 36 | /// For logging 37 | public RandomLoadBalancer(IServiceInstanceProvider serviceInstanceProvider, IDistributedCache distributedCache = null, ILogger logger = null) 38 | { 39 | _serviceInstanceProvider = serviceInstanceProvider ?? throw new ArgumentNullException(nameof(serviceInstanceProvider)); 40 | _distributedCache = distributedCache; 41 | _logger = logger; 42 | } 43 | 44 | public virtual async Task ResolveServiceInstanceAsync(Uri request) 45 | { 46 | _logger?.LogTrace("ResolveServiceInstance {serviceInstance}", request.Host); 47 | var availableServiceInstances = await _serviceInstanceProvider.GetInstancesWithCacheAsync(request.Host, _distributedCache); 48 | if (availableServiceInstances.Count > 0) 49 | { 50 | var resolvedUri = availableServiceInstances[_random.Next(availableServiceInstances.Count)].Uri; 51 | _logger?.LogDebug("Resolved {url} to {service}", request.Host, resolvedUri.Host); 52 | return new Uri(resolvedUri, request.PathAndQuery); 53 | } 54 | else 55 | { 56 | _logger?.LogWarning("Attempted to resolve service for {url} but found 0 instances", request.Host); 57 | return request; 58 | } 59 | } 60 | 61 | public virtual Task UpdateStatsAsync(Uri originalUri, Uri resolvedUri, TimeSpan responseTime, Exception exception) 62 | { 63 | return Task.CompletedTask; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/LoadBalancer/RoundRobinLoadBalancer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Caching.Distributed; 16 | using Microsoft.Extensions.Logging; 17 | using Steeltoe.Common.Discovery; 18 | using System; 19 | using System.Collections.Concurrent; 20 | using System.Linq; 21 | using System.Threading.Tasks; 22 | 23 | namespace Steeltoe.Common.LoadBalancer 24 | { 25 | public class RoundRobinLoadBalancer : ILoadBalancer 26 | { 27 | public string IndexKeyPrefix = "LoadBalancerIndex-"; 28 | internal readonly IServiceInstanceProvider ServiceInstanceProvider; 29 | internal readonly IDistributedCache _distributedCache; 30 | internal readonly ConcurrentDictionary NextIndexForService = new ConcurrentDictionary(); 31 | private readonly ILogger _logger; 32 | 33 | public RoundRobinLoadBalancer(IServiceInstanceProvider serviceInstanceProvider, IDistributedCache distributedCache = null, ILogger logger = null) 34 | { 35 | ServiceInstanceProvider = serviceInstanceProvider ?? throw new ArgumentNullException(nameof(serviceInstanceProvider)); 36 | _distributedCache = distributedCache; 37 | _logger = logger; 38 | _logger?.LogDebug("Distributed cache was provided to load balancer: {DistributedCacheIsNull}", _distributedCache == null); 39 | } 40 | 41 | public virtual async Task ResolveServiceInstanceAsync(Uri request) 42 | { 43 | var serviceName = request.Host; 44 | _logger?.LogTrace("ResolveServiceInstance {serviceName}", serviceName); 45 | string cacheKey = IndexKeyPrefix + serviceName; 46 | 47 | // get instances for this service 48 | var availableServiceInstances = await ServiceInstanceProvider.GetInstancesWithCacheAsync(serviceName, _distributedCache); 49 | if (!availableServiceInstances.Any()) 50 | { 51 | _logger?.LogError("No service instances available for {serviceName}", serviceName); 52 | return request; 53 | } 54 | 55 | // get next instance, or wrap back to first instance if we reach the end of the list 56 | IServiceInstance serviceInstance = null; 57 | var nextInstanceIndex = await GetOrInitNextIndex(cacheKey, 0); 58 | if (nextInstanceIndex >= availableServiceInstances.Count) 59 | { 60 | nextInstanceIndex = 0; 61 | } 62 | 63 | serviceInstance = availableServiceInstances[nextInstanceIndex]; 64 | await SetNextIndex(cacheKey, nextInstanceIndex); 65 | return new Uri(serviceInstance.Uri, request.PathAndQuery); 66 | } 67 | 68 | public virtual Task UpdateStatsAsync(Uri originalUri, Uri resolvedUri, TimeSpan responseTime, Exception exception) 69 | { 70 | return Task.CompletedTask; 71 | } 72 | 73 | private async Task GetOrInitNextIndex(string cacheKey, int initValue) 74 | { 75 | int index = initValue; 76 | if (_distributedCache != null) 77 | { 78 | var cacheEntry = await _distributedCache.GetAsync(cacheKey); 79 | if (cacheEntry != null && cacheEntry.Length > 0) 80 | { 81 | index = BitConverter.ToInt16(cacheEntry, 0); 82 | } 83 | } 84 | else 85 | { 86 | index = NextIndexForService.GetOrAdd(cacheKey, initValue); 87 | } 88 | 89 | return index; 90 | } 91 | 92 | private async Task SetNextIndex(string cacheKey, int currentValue) 93 | { 94 | if (_distributedCache != null) 95 | { 96 | await _distributedCache.SetAsync(cacheKey, BitConverter.GetBytes(currentValue + 1)); 97 | } 98 | else 99 | { 100 | NextIndexForService[cacheKey] = currentValue + 1; 101 | } 102 | } 103 | } 104 | } -------------------------------------------------------------------------------- /src/Steeltoe.Common/Net/HostInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Net 16 | { 17 | public class HostInfo 18 | { 19 | public string Hostname { get; set; } 20 | 21 | public string IpAddress { get; set; } 22 | 23 | public bool Override { get; set; } 24 | 25 | public HostInfo() 26 | { 27 | } 28 | 29 | public HostInfo(string hostname) 30 | { 31 | Hostname = hostname; 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Net/INetOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Collections.Generic; 17 | 18 | namespace Steeltoe.Common.Net 19 | { 20 | public class InetOptions 21 | { 22 | public const string PREFIX = "spring:cloud:inet"; 23 | 24 | public string DefaultHostname { get; set; } = "localhost"; 25 | 26 | public string DefaultIpAddress { get; set; } = "127.0.0.1"; 27 | 28 | public string IgnoredInterfaces { get; set; } 29 | 30 | public bool UseOnlySiteLocalInterfaces { get; set; } = false; 31 | 32 | public string PreferredNetworks { get; set; } 33 | 34 | internal IEnumerable GetIgnoredInterfaces() 35 | { 36 | if (string.IsNullOrEmpty(IgnoredInterfaces)) 37 | { 38 | return new List(); 39 | } 40 | 41 | return IgnoredInterfaces.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 42 | } 43 | 44 | internal IEnumerable GetPreferredNetworks() 45 | { 46 | if (string.IsNullOrEmpty(PreferredNetworks)) 47 | { 48 | return null; 49 | } 50 | 51 | return PreferredNetworks.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Options/AbstractOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System; 17 | 18 | namespace Steeltoe.Common.Options 19 | { 20 | public abstract class AbstractOptions 21 | { 22 | public AbstractOptions() 23 | { 24 | } 25 | 26 | public AbstractOptions(IConfigurationRoot root, string sectionPrefix = null) 27 | { 28 | if (root == null) 29 | { 30 | throw new ArgumentNullException(nameof(root)); 31 | } 32 | 33 | if (!string.IsNullOrEmpty(sectionPrefix)) 34 | { 35 | var section = root.GetSection(sectionPrefix); 36 | section.Bind(this); 37 | } 38 | else 39 | { 40 | root.Bind(this); 41 | } 42 | } 43 | 44 | public AbstractOptions(IConfiguration config) 45 | { 46 | if (config == null) 47 | { 48 | throw new ArgumentNullException(nameof(config)); 49 | } 50 | 51 | config.Bind(this); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Platform.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Runtime.InteropServices; 17 | 18 | namespace Steeltoe.Common 19 | { 20 | public static class Platform 21 | { 22 | public const string NET_FRAMEWORK = ".NET Framework"; 23 | public const string NET_CORE = ".NET Core"; 24 | public const string VCAP_APPLICATION = "VCAP_APPLICATION"; 25 | 26 | public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(NET_FRAMEWORK); 27 | 28 | public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(NET_CORE); 29 | 30 | public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); 31 | 32 | public static bool IsCloudFoundry => Environment.GetEnvironmentVariable(VCAP_APPLICATION) != null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Runtime.CompilerServices; 16 | 17 | [assembly: InternalsVisibleTo("Steeltoe.Common.Test")] 18 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Steeltoe.Common.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Steeltoe Common Library 5 | $(SteeltoeVersion) 6 | $(VersionSuffix) 7 | Pivotal;dtillman 8 | netstandard2.0 9 | Steeltoe.Common 10 | Steeltoe.Common 11 | NET Core;NET Framework 12 | https://steeltoe.io/images/transparent.png 13 | https://steeltoe.io 14 | https://www.apache.org/licenses/LICENSE-2.0 15 | true 16 | true 17 | snupkg 18 | 19 | 20 | bin\$(Configuration)\$(TargetFramework)\Steeltoe.Common.xml 21 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | All 32 | 33 | 34 | 35 | 36 | 37 | stylecop.json 38 | Always 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/Steeltoe.Common/Tasks/IApplicationTask.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Tasks 16 | { 17 | /// 18 | /// A runnable task bundled with the assembly that can be executed as one off 19 | /// 20 | public interface IApplicationTask 21 | { 22 | /// 23 | /// Gets globally unique name for task 24 | /// 25 | string Name { get; } 26 | 27 | /// 28 | /// Action which to run 29 | /// 30 | void Run(); 31 | } 32 | } -------------------------------------------------------------------------------- /stylecop.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", 3 | "settings": { 4 | "documentationRules": { 5 | "copyrightText": "Copyright {copyrightYear} the original author or authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttps://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.", 6 | "xmlHeader": false, 7 | "variables": { 8 | "copyrightYear": "2017" 9 | }, 10 | "documentExposedElements": false, 11 | "documentInternalElements": false, 12 | "documentPrivateElements": false 13 | }, 14 | "indentation": { 15 | "useTabs": false, 16 | "indentationSize": 4 17 | }, 18 | "namingRules": { 19 | }, 20 | "orderingRules": { 21 | "usingDirectivesPlacement": "outsideNamespace", 22 | "systemUsingDirectivesFirst": false 23 | }, 24 | "readabilityRules": { 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /targetframework.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | $(NuGetPackageRoot)microsoft.targetingpack.netframework.v4.6.1/1.0.1/lib/net461/ 4 | https://dotnet.myget.org/F/dotnet-core/api/v3/index.json 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Autofac.Test/Configuration/ConfigurationContainerBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using System; 18 | using Xunit; 19 | 20 | namespace Steeltoe.Common.Configuration.Autofac.Test 21 | { 22 | public class ConfigurationContainerBuilderExtensionsTest 23 | { 24 | [Fact] 25 | public void RegisterConfiguration_ThrowsNulls() 26 | { 27 | ContainerBuilder container = null; 28 | Assert.Throws(() => container.RegisterConfiguration(null)); 29 | ContainerBuilder container2 = new ContainerBuilder(); 30 | Assert.Throws(() => container2.RegisterConfiguration(null)); 31 | } 32 | 33 | [Fact] 34 | public void RegisterConfiguration_Registers() 35 | { 36 | ContainerBuilder container = new ContainerBuilder(); 37 | IConfiguration config = new ConfigurationBuilder().Build(); 38 | container.RegisterConfiguration(config); 39 | 40 | var built = container.Build(); 41 | Assert.True(built.IsRegistered()); 42 | Assert.True(built.IsRegistered()); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Autofac.Test/Logging/LoggingContainerBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using Microsoft.Extensions.Logging; 18 | using Steeltoe.Common.Logging.Autofac; 19 | using Steeltoe.Common.Options.Autofac; 20 | using System; 21 | using Xunit; 22 | 23 | namespace Steeltoe.Common.Autofac.Test.Logging 24 | { 25 | public class LoggingContainerBuilderExtensionsTest 26 | { 27 | [Fact] 28 | public void RegisterLogging_ThrowsNulls() 29 | { 30 | ContainerBuilder container = null; 31 | Assert.Throws(() => container.RegisterLogging(null)); 32 | ContainerBuilder container2 = new ContainerBuilder(); 33 | Assert.Throws(() => container2.RegisterLogging(null)); 34 | } 35 | 36 | [Fact] 37 | public void RegisterLogging_Registers() 38 | { 39 | ContainerBuilder container = new ContainerBuilder(); 40 | IConfiguration config = new ConfigurationBuilder().Build(); 41 | 42 | container.RegisterOptions(); 43 | container.RegisterLogging(config); 44 | container.RegisterConsoleLogging(); 45 | 46 | var built = container.Build(); 47 | var fac = built.Resolve(); 48 | Assert.NotNull(fac); 49 | var logger = built.Resolve>(); 50 | Assert.NotNull(logger); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Autofac.Test/Options/OptionsContainerBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Autofac; 16 | using Microsoft.Extensions.Configuration; 17 | using Microsoft.Extensions.Options; 18 | using System; 19 | using System.Collections.Generic; 20 | using Xunit; 21 | 22 | namespace Steeltoe.Common.Options.Autofac.Test 23 | { 24 | public class OptionsContainerBuilderExtensionsTest 25 | { 26 | [Fact] 27 | public void RegisterOptions_ThrowsNulls() 28 | { 29 | ContainerBuilder container = null; 30 | Assert.Throws(() => container.RegisterOptions()); 31 | } 32 | 33 | [Fact] 34 | public void RegisterOption_ThrowsNulls() 35 | { 36 | ContainerBuilder container = null; 37 | Assert.Throws(() => container.RegisterOption(null)); 38 | ContainerBuilder container2 = new ContainerBuilder(); 39 | Assert.Throws(() => container2.RegisterOption(null)); 40 | } 41 | 42 | [Fact] 43 | public void RegisterOption_Registers_AndBindsConfiguration() 44 | { 45 | ContainerBuilder container = new ContainerBuilder(); 46 | var dict = new Dictionary() 47 | { 48 | { "f1", "foobar" } 49 | }; 50 | 51 | IConfiguration config = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); 52 | container.RegisterOptions(); 53 | 54 | container.RegisterOption(config); 55 | var built = container.Build(); 56 | 57 | var service = built.Resolve>(); 58 | Assert.NotNull(service); 59 | Assert.NotNull(service.Value); 60 | Assert.Equal("foobar", service.Value.F1); 61 | } 62 | 63 | [Fact] 64 | public void RegisterPostConfigure_Registers_RunsPostAction() 65 | { 66 | ContainerBuilder container = new ContainerBuilder(); 67 | var dict = new Dictionary() 68 | { 69 | { "f1", "foobar" } 70 | }; 71 | 72 | IConfiguration config = new ConfigurationBuilder().AddInMemoryCollection(dict).Build(); 73 | container.RegisterOptions(); 74 | 75 | container.RegisterOption(config); 76 | container.RegisterPostConfigure((opt) => 77 | { 78 | opt.F1 = "changed"; 79 | }); 80 | 81 | var built = container.Build(); 82 | 83 | var service = built.Resolve>(); 84 | Assert.NotNull(service); 85 | Assert.NotNull(service.Value); 86 | Assert.Equal("changed", service.Value.F1); 87 | } 88 | 89 | private class MyOption 90 | { 91 | public string F1 { get; set; } 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Autofac.Test/Steeltoe.Common.Autofac.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | netcoreapp2.0;netcoreapp2.1;net461 7 | 8 | 9 | 10 | $(NuGetPackageRoot)microsoft.targetingpack.netframework.v4.6.1/1.0.1/lib/net461/ 11 | https://dotnet.myget.org/F/dotnet-core/api/v3/index.json 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | 23 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | All 37 | 38 | 39 | 40 | 41 | 42 | stylecop.json 43 | Always 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Autofac.Test/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "maxParallelThreads": 1, 3 | "parallelizeTestCollections": false 4 | } -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/Discovery/DiscoveryHttpClientHandlerBaseTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.Discovery; 16 | using System; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Http.Test 20 | { 21 | public class DiscoveryHttpClientHandlerBaseTest 22 | { 23 | [Fact] 24 | public void Constructor_ThrowsIfClientNull() 25 | { 26 | // Arrange 27 | IDiscoveryClient client = null; 28 | 29 | // Act and Assert 30 | var ex = Assert.Throws(() => new DiscoveryHttpClientHandlerBase(client)); 31 | Assert.Contains(nameof(client), ex.Message); 32 | } 33 | 34 | [Fact] 35 | public void LookupService_NonDefaultPort_ReturnsOriginalURI() 36 | { 37 | // Arrange 38 | IDiscoveryClient client = new TestDiscoveryClient(); 39 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 40 | Uri uri = new Uri("https://foo:8080/test"); 41 | 42 | // Act and Assert 43 | var result = handler.LookupService(uri); 44 | Assert.Equal(uri, result); 45 | } 46 | 47 | [Fact] 48 | public void LookupService_DoesntFindService_ReturnsOriginalURI() 49 | { 50 | // Arrange 51 | IDiscoveryClient client = new TestDiscoveryClient(); 52 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 53 | Uri uri = new Uri("https://foo/test"); 54 | 55 | // Act and Assert 56 | var result = handler.LookupService(uri); 57 | Assert.Equal(uri, result); 58 | } 59 | 60 | [Fact] 61 | public void LookupService_FindsService_ReturnsURI() 62 | { 63 | // Arrange 64 | IDiscoveryClient client = new TestDiscoveryClient(new TestServiceInstance(new Uri("https://foundit:5555"))); 65 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 66 | Uri uri = new Uri("https://foo/test/bar/foo?test=1&test2=2"); 67 | 68 | // Act and Assert 69 | var result = handler.LookupService(uri); 70 | Assert.Equal(new Uri("https://foundit:5555/test/bar/foo?test=1&test2=2"), result); 71 | } 72 | 73 | [Fact] 74 | public async void LookupServiceAsync_NonDefaultPort_ReturnsOriginalURI() 75 | { 76 | // Arrange 77 | IDiscoveryClient client = new TestDiscoveryClient(); 78 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 79 | Uri uri = new Uri("https://foo:8080/test"); 80 | 81 | // Act and Assert 82 | var result = await handler.LookupServiceAsync(uri); 83 | Assert.Equal(uri, result); 84 | } 85 | 86 | [Fact] 87 | public async void LookupServiceAsync_DoesntFindService_ReturnsOriginalURI() 88 | { 89 | // Arrange 90 | IDiscoveryClient client = new TestDiscoveryClient(); 91 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 92 | Uri uri = new Uri("https://foo/test"); 93 | 94 | // Act and Assert 95 | var result = await handler.LookupServiceAsync(uri); 96 | Assert.Equal(uri, result); 97 | } 98 | 99 | [Fact] 100 | public async void LookupServiceAsync_FindsService_ReturnsURI() 101 | { 102 | // Arrange 103 | IDiscoveryClient client = new TestDiscoveryClient(new TestServiceInstance(new Uri("https://foundit:5555"))); 104 | DiscoveryHttpClientHandlerBase handler = new DiscoveryHttpClientHandlerBase(client); 105 | Uri uri = new Uri("https://foo/test/bar/foo?test=1&test2=2"); 106 | 107 | // Act and Assert 108 | var result = await handler.LookupServiceAsync(uri); 109 | Assert.Equal(new Uri("https://foundit:5555/test/bar/foo?test=1&test2=2"), result); 110 | } 111 | } 112 | } -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/Discovery/TestDiscoveryClient.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.Discovery; 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Http.Test 21 | { 22 | internal class TestDiscoveryClient : IDiscoveryClient 23 | { 24 | private IServiceInstance _instance; 25 | 26 | public TestDiscoveryClient(IServiceInstance instance = null) 27 | { 28 | _instance = instance; 29 | } 30 | 31 | public string Description 32 | { 33 | get 34 | { 35 | throw new NotImplementedException(); 36 | } 37 | } 38 | 39 | public IList Services 40 | { 41 | get 42 | { 43 | throw new NotImplementedException(); 44 | } 45 | } 46 | 47 | public IList GetInstances(string serviceId) 48 | { 49 | if (_instance != null) 50 | { 51 | return new List() { _instance }; 52 | } 53 | 54 | return new List(); 55 | } 56 | 57 | public IServiceInstance GetLocalServiceInstance() 58 | { 59 | throw new NotImplementedException(); 60 | } 61 | 62 | public Task ShutdownAsync() 63 | { 64 | throw new NotImplementedException(); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/LoadBalancer/BrokenLoadBalancer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.LoadBalancer; 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Http.LoadBalancer.Test 21 | { 22 | internal class BrokenLoadBalancer : ILoadBalancer 23 | { 24 | internal List> Stats = new List>(); 25 | 26 | /// 27 | /// Initializes a new instance of the class. 28 | /// Throws exceptions when you try to resolve services 29 | /// 30 | public BrokenLoadBalancer() 31 | { 32 | } 33 | 34 | public Task ResolveServiceInstanceAsync(Uri request) 35 | { 36 | throw new Exception("(╯°□°)╯︵ ┻━┻"); 37 | } 38 | 39 | public Task UpdateStatsAsync(Uri originalUri, Uri resolvedUri, TimeSpan responseTime, Exception exception) 40 | { 41 | Stats.Add(new Tuple(originalUri, resolvedUri, responseTime, exception)); 42 | return Task.CompletedTask; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/LoadBalancer/FakeLoadBalancer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.LoadBalancer; 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Http.LoadBalancer.Test 21 | { 22 | /// 23 | /// A bad fake load balancer that only resolves requests for "replaceme" as "someresolvedhost" 24 | /// 25 | internal class FakeLoadBalancer : ILoadBalancer 26 | { 27 | internal List> Stats = new List>(); 28 | 29 | /// 30 | /// Initializes a new instance of the class. 31 | /// Only capable of resolving requests for "replaceme" as "someresolvedhost" 32 | /// 33 | public FakeLoadBalancer() 34 | { 35 | } 36 | 37 | public Task ResolveServiceInstanceAsync(Uri request) 38 | { 39 | return Task.FromResult(new Uri(request.AbsoluteUri.Replace("replaceme", "someresolvedhost"))); 40 | } 41 | 42 | public Task UpdateStatsAsync(Uri originalUri, Uri resolvedUri, TimeSpan responseTime, Exception exception) 43 | { 44 | Stats.Add(new Tuple(originalUri, resolvedUri, responseTime, exception)); 45 | return Task.CompletedTask; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/LoadBalancer/LoadBalancerDelegatingHandlerTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.Http.Test; 16 | using System; 17 | using System.Linq; 18 | using System.Net; 19 | using System.Net.Http; 20 | using System.Threading; 21 | using Xunit; 22 | 23 | namespace Steeltoe.Common.Http.LoadBalancer.Test 24 | { 25 | public class LoadBalancerDelegatingHandlerTest 26 | { 27 | [Fact] 28 | public void Throws_If_LoadBalancerNull() 29 | { 30 | var exception = Assert.Throws(() => new LoadBalancerDelegatingHandler(null)); 31 | Assert.Equal("loadBalancer", exception.ParamName); 32 | } 33 | 34 | [Fact] 35 | public async void ResolvesUri_TracksStats_WithProvidedLoadBalancer() 36 | { 37 | // arrange 38 | var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://replaceme/api"); 39 | var loadBalancer = new FakeLoadBalancer(); 40 | var handler = new LoadBalancerDelegatingHandler(loadBalancer) { InnerHandler = new TestInnerDelegatingHandler() }; 41 | var invoker = new HttpMessageInvoker(handler); 42 | 43 | // act 44 | var result = await invoker.SendAsync(httpRequestMessage, default(CancellationToken)); 45 | 46 | // assert 47 | Assert.Equal("https://someresolvedhost/api", result.Headers.GetValues("requestUri").First()); 48 | Assert.Single(loadBalancer.Stats); 49 | } 50 | 51 | [Fact] 52 | public async void DoesntTrackStats_WhenResolutionFails_WithProvidedLoadBalancer() 53 | { 54 | // arrange 55 | var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://replaceme/api"); 56 | var loadBalancer = new BrokenLoadBalancer(); 57 | var handler = new LoadBalancerDelegatingHandler(loadBalancer) { InnerHandler = new TestInnerDelegatingHandler() }; 58 | var invoker = new HttpMessageInvoker(handler); 59 | 60 | // act 61 | var result = await Assert.ThrowsAsync(async () => await invoker.SendAsync(httpRequestMessage, default(CancellationToken))); 62 | 63 | // assert 64 | Assert.Empty(loadBalancer.Stats); 65 | } 66 | 67 | [Fact] 68 | public async void TracksStats_WhenRequestsGoWrong_WithProvidedLoadBalancer() 69 | { 70 | // arrange 71 | var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://replaceme/api"); 72 | var loadBalancer = new FakeLoadBalancer(); 73 | var handler = new LoadBalancerDelegatingHandler(loadBalancer) { InnerHandler = new TestInnerDelegatingHandlerBrokenServer() }; 74 | var invoker = new HttpMessageInvoker(handler); 75 | 76 | // act 77 | var result = await invoker.SendAsync(httpRequestMessage, default(CancellationToken)); 78 | 79 | // assert 80 | Assert.Single(loadBalancer.Stats); 81 | Assert.Equal(HttpStatusCode.InternalServerError, result.StatusCode); 82 | Assert.Equal("https://someresolvedhost/api", result.Headers.GetValues("requestUri").First()); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/SerializationHelperTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.IO; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Http.Test 20 | { 21 | public class SerializationHelperTest 22 | { 23 | [Fact] 24 | public void Deserialize_ThrowsNulls() 25 | { 26 | Assert.Throws(() => SerializationHelper.Deserialize(null, null)); 27 | } 28 | 29 | [Fact] 30 | public void Deserialize_ReturnsNullOnException() 31 | { 32 | MemoryStream s = new MemoryStream(); 33 | var result = SerializationHelper.Deserialize(s); 34 | Assert.Null(result); 35 | } 36 | 37 | [Fact] 38 | public void Deserialize_ReturnsValid() 39 | { 40 | var memStream = new MemoryStream(); 41 | var textWriter = new StreamWriter(memStream); 42 | textWriter.Write("{\"f1\":100,\"f2\":200}"); 43 | textWriter.Flush(); 44 | memStream.Seek(0, SeekOrigin.Begin); 45 | 46 | var result = SerializationHelper.Deserialize(memStream); 47 | Assert.NotNull(result); 48 | Assert.Equal(100, result.F1); 49 | Assert.Equal(200, result.F2); 50 | } 51 | 52 | private class Test 53 | { 54 | public int F1 = 0; 55 | public long F2 = 0; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/SerializationTestObject.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | namespace Steeltoe.Common.Http.Test 16 | { 17 | public class SerializationTestObject 18 | { 19 | public string Name { get; set; } 20 | 21 | public string Value { get; set; } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/Steeltoe.Common.Http.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | netcoreapp2.0;netcoreapp2.1;net461 7 | 8 | 9 | 10 | 11 | 12 | 13 | PreserveNewest 14 | 15 | 16 | 17 | 18 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | All 35 | 36 | 37 | 38 | 39 | 40 | stylecop.json 41 | Always 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/TestInnerDelegatingHandler.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Net; 16 | using System.Net.Http; 17 | using System.Threading; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Http.Test 21 | { 22 | public class TestInnerDelegatingHandler : DelegatingHandler 23 | { 24 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 25 | { 26 | var responseMessage = new HttpResponseMessage(HttpStatusCode.OK); 27 | responseMessage.Headers.Add("requestUri", request.RequestUri.AbsoluteUri); 28 | return Task.Factory.StartNew(() => responseMessage, cancellationToken); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/TestInnerDelegatingHandlerBrokenServer.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Net; 16 | using System.Net.Http; 17 | using System.Threading; 18 | using System.Threading.Tasks; 19 | 20 | namespace Steeltoe.Common.Http.Test 21 | { 22 | public class TestInnerDelegatingHandlerBrokenServer : DelegatingHandler 23 | { 24 | protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 25 | { 26 | var responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError); 27 | responseMessage.Headers.Add("requestUri", request.RequestUri.AbsoluteUri); 28 | return Task.Factory.StartNew(() => responseMessage, cancellationToken); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/TestServiceInstance.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Steeltoe.Common.Discovery; 16 | using System; 17 | using System.Collections.Generic; 18 | 19 | namespace Steeltoe.Common.Http.Test 20 | { 21 | internal class TestServiceInstance : IServiceInstance 22 | { 23 | private Uri _uri; 24 | 25 | public TestServiceInstance(Uri uri) 26 | { 27 | _uri = uri; 28 | } 29 | 30 | public string Host 31 | { 32 | get 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | } 37 | 38 | public bool IsSecure 39 | { 40 | get 41 | { 42 | throw new NotImplementedException(); 43 | } 44 | } 45 | 46 | public IDictionary Metadata 47 | { 48 | get 49 | { 50 | throw new NotImplementedException(); 51 | } 52 | } 53 | 54 | public int Port 55 | { 56 | get 57 | { 58 | throw new NotImplementedException(); 59 | } 60 | } 61 | 62 | public string ServiceId 63 | { 64 | get 65 | { 66 | throw new NotImplementedException(); 67 | } 68 | } 69 | 70 | public Uri Uri 71 | { 72 | get 73 | { 74 | return _uri; 75 | } 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Http.Test/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "maxParallelThreads": 1, 3 | "parallelizeTestCollections": false 4 | } -------------------------------------------------------------------------------- /test/Steeltoe.Common.Net.Test/FakeMPR.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Text; 17 | 18 | namespace Steeltoe.Common.Net.Test 19 | { 20 | internal class FakeMPR : IMPR 21 | { 22 | internal string _username; 23 | internal string _password; 24 | internal string _networkpath; 25 | internal bool _shouldConnect; 26 | 27 | public FakeMPR(bool shouldConnect = true) 28 | { 29 | _shouldConnect = shouldConnect; 30 | } 31 | 32 | public int AddConnection(WindowsNetworkFileShare.NetResource netResource, string password, string username, int flags) 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | 37 | public int CancelConnection(string name, int flags, bool force) 38 | { 39 | throw new NotImplementedException(); 40 | } 41 | 42 | public int GetLastError(out int error, out StringBuilder errorBuf, int errorBufSize, out StringBuilder nameBuf, int nameBufSize) 43 | { 44 | throw new NotImplementedException(); 45 | } 46 | 47 | public int UseConnection(IntPtr hwndOwner, WindowsNetworkFileShare.NetResource netResource, string password, string username, int flags, string lpAccessName, string lpBufferSize, string lpResult) 48 | { 49 | _networkpath = netResource.RemoteName; 50 | _username = username; 51 | _password = password; 52 | if (_shouldConnect) 53 | { 54 | return 0; 55 | } 56 | else 57 | { 58 | // throw "bad device" error 59 | return 1200; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Net.Test/Steeltoe.Common.Net.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | netcoreapp2.0;netcoreapp2.1;net461 7 | 8 | 9 | 10 | 11 | 12 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | PreserveNewest 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | All 30 | 31 | 32 | 33 | 34 | 35 | stylecop.json 36 | Always 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Net.Test/WindowsNetworkFileShareTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using System.Net; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Net.Test 20 | { 21 | public class WindowsNetworkFileShareTest 22 | { 23 | [Fact] 24 | public void GetErrorForKnownNumber_ReturnsKnownError() 25 | { 26 | Assert.Equal("Error: Access Denied", WindowsNetworkFileShare.GetErrorForNumber(5)); 27 | Assert.Equal("Error: No Network", WindowsNetworkFileShare.GetErrorForNumber(1222)); 28 | } 29 | 30 | [Fact] 31 | public void GetErrorForUnknownNumber_ReturnsUnKnownError() 32 | { 33 | Assert.Equal("Error: Unknown, 9999", WindowsNetworkFileShare.GetErrorForNumber(9999)); 34 | } 35 | 36 | [Fact] 37 | public void WindowsNetworkFileShare_Constructor_SetsValuesOn_ConnectSuccess() 38 | { 39 | // arrange 40 | var fakeMPR = new FakeMPR(); 41 | 42 | // act 43 | _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password"), fakeMPR); 44 | 45 | // assert 46 | Assert.Equal("user", fakeMPR._username); 47 | Assert.Equal("password", fakeMPR._password); 48 | Assert.Equal(@"\\server\path", fakeMPR._networkpath); 49 | } 50 | 51 | [Fact] 52 | public void WindowsNetworkFileShare_Constructor_ConcatsUserAndDomain() 53 | { 54 | // arrange 55 | var fakeMPR = new FakeMPR(); 56 | 57 | // act 58 | _ = new WindowsNetworkFileShare(@"\\server\path", new NetworkCredential("user", "password", "domain"), fakeMPR); 59 | 60 | // assert 61 | Assert.Equal(@"domain\user", fakeMPR._username); 62 | Assert.Equal("password", fakeMPR._password); 63 | Assert.Equal(@"\\server\path", fakeMPR._networkpath); 64 | } 65 | 66 | [Fact] 67 | public void WindowsNetworkFileShare_Constructor_ThrowsOn_ConnectFail() 68 | { 69 | // arrange 70 | var fakeMPR = new FakeMPR(false); 71 | 72 | // act 73 | var exception = Assert.Throws(() => new WindowsNetworkFileShare("doesn't-matter", new NetworkCredential("user", "password"), fakeMPR)); 74 | 75 | // assert 76 | Assert.Equal("Error connecting to remote share - Code: 1200, Error: Bad Device", exception.Message); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/PemConfigurationExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.DependencyInjection; 17 | using Microsoft.Extensions.Options; 18 | using System; 19 | using System.IO; 20 | using System.Threading; 21 | using Xunit; 22 | 23 | namespace Steeltoe.Common.Security.Test 24 | { 25 | public class PemConfigurationExtensionsTest 26 | { 27 | [Fact] 28 | public void AddPemFiles_ThrowsOnNulls() 29 | { 30 | Assert.Throws(() => PemConfigurationExtensions.AddPemFiles(null, null, null)); 31 | Assert.Throws(() => PemConfigurationExtensions.AddPemFiles(new ConfigurationBuilder(), null, null)); 32 | Assert.Throws(() => PemConfigurationExtensions.AddPemFiles(new ConfigurationBuilder(), "foobar", null)); 33 | } 34 | 35 | [Fact] 36 | public void AddPemFiles_ReadsFiles() 37 | { 38 | var config = new ConfigurationBuilder() 39 | .AddPemFiles("instance.crt", "instance.key") 40 | .Build(); 41 | Assert.NotNull(config["certificate"]); 42 | Assert.NotNull(config["privateKey"]); 43 | } 44 | 45 | [Fact] 46 | public void AddPemFiles_ReloadsOnChange() 47 | { 48 | var tempFile1 = CreateTempFile("cert"); 49 | var tempFile2 = CreateTempFile("key"); 50 | 51 | var config = new ConfigurationBuilder() 52 | .AddPemFiles(tempFile1, tempFile2) 53 | .Build(); 54 | 55 | Assert.Equal("cert", config["certificate"]); 56 | Assert.Equal("key", config["privateKey"]); 57 | 58 | File.WriteAllText(tempFile1, "cert2"); 59 | Thread.Sleep(2000); 60 | Assert.Equal("cert2", config["certificate"]); 61 | Assert.Equal("key", config["privateKey"]); 62 | } 63 | 64 | [Fact] 65 | public void AddPemFiles_NotifiesOnChange() 66 | { 67 | var tempFile1 = CreateTempFile("cert"); 68 | var tempFile2 = CreateTempFile("key"); 69 | 70 | var config = new ConfigurationBuilder() 71 | .AddPemFiles(tempFile1, tempFile2) 72 | .Build(); 73 | 74 | bool changeCalled = false; 75 | var token = config.GetReloadToken(); 76 | token.RegisterChangeCallback((o) => changeCalled = true, "state"); 77 | Assert.Equal("cert", config["certificate"]); 78 | Assert.Equal("key", config["privateKey"]); 79 | 80 | File.WriteAllText(tempFile1, "barfoo"); 81 | Thread.Sleep(2000); 82 | Assert.Equal("barfoo", config["certificate"]); 83 | Assert.Equal("key", config["privateKey"]); 84 | Assert.True(changeCalled); 85 | 86 | token = config.GetReloadToken(); 87 | token.RegisterChangeCallback((o) => changeCalled = true, "state"); 88 | 89 | changeCalled = false; 90 | File.WriteAllText(tempFile2, "barbar"); 91 | Thread.Sleep(2000); 92 | Assert.Equal("barfoo", config["certificate"]); 93 | Assert.Equal("barbar", config["privateKey"]); 94 | Assert.True(changeCalled); 95 | } 96 | 97 | private static string CreateTempFile(string contents) 98 | { 99 | var tempFile = Path.GetTempFileName(); 100 | File.WriteAllText(tempFile, contents); 101 | return tempFile; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/PemConfigureCertificateOptionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.Options; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Security.Test 20 | { 21 | public class PemConfigureCertificateOptionsTest 22 | { 23 | [Fact] 24 | public void AddPemFiles_ReadsFiles_CreatesCertificate() 25 | { 26 | var config = new ConfigurationBuilder() 27 | .AddPemFiles("instance.crt", "instance.key") 28 | .Build(); 29 | Assert.NotNull(config["certificate"]); 30 | Assert.NotNull(config["privateKey"]); 31 | var pemConfig = new PemConfigureCertificateOptions(config); 32 | CertificateOptions opts = new CertificateOptions(); 33 | pemConfig.Configure(opts); 34 | Assert.NotNull(opts.Certificate); 35 | Assert.Equal(Options.DefaultName, opts.Name); 36 | Assert.True(opts.Certificate.HasPrivateKey); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/Steeltoe.Common.Security.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | netcoreapp2.0;netcoreapp2.1;net461 7 | 8 | 9 | 10 | 11 | 12 | Always 13 | 14 | 15 | Always 16 | 17 | 18 | PreserveNewest 19 | 20 | 21 | 22 | 23 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | All 40 | 41 | 42 | 43 | 44 | 45 | stylecop.json 46 | Always 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/instance.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIEBzCCAu+gAwIBAgIQSrLsvLyESbpjMDWmkPr+0TANBgkqhkiG9w0BAQsFADAy 3 | MTAwLgYDVQQDEydEaWVnbyBJbnN0YW5jZSBJZGVudGl0eSBJbnRlcm1lZGlhdGUg 4 | Q0EwHhcNMTkwMjI0MjAxMzAwWhcNMTkwMjI1MjAxMzAwWjCByDGBnjA4BgNVBAsT 5 | MW9yZ2FuaXphdGlvbjozOTBjYmI3Zi0wMWYyLTQ2MGUtOTViMi1jNjhmOGQ0YTk0 6 | YjgwMQYDVQQLEypzcGFjZTpjYzY4MmUyNi0yMTU1LTQ2NDktYjk0OC00ZjBkMDJm 7 | ODg3ZGEwLwYDVQQLEyhhcHA6M2ZlYzJmYjktNmIzYi00Yzc1LTkxYTktY2YwNDRi 8 | ZWIxOGU3MSUwIwYDVQQDExxjZmMyYmM0ZC1lODMxLTQ1ODgtNzY0My01NDQ0MIIB 9 | IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt2O/qEPoA0jQFrI23NRIzd3E 10 | FhsNwuTpZ4DoSVIZJQsjG0gjzoj0/YZHp6sbNRlWTHz1eXJ714+0rkYvpYjOp3jo 11 | EOJhsrx3Hs9eN0yDz+YqB+J3DSYt+t+nrae7wDBUAMFZXjqhrDhuFgANjsxF3Xtl 12 | 1REgcRIdW9LGydAEAGlyMKAGBmQf9zofYCR+4Sw96KhQXBOTJiI+9p9pw3ndptfB 13 | hYCBdiifcHi6+e3nsOidqjrDP4PA6OfVMCxvzDkJLU2Bq1cjqHFomNB5Tc5AshyA 14 | lvDOi2+xVWBX7Z0+UujlWBYMeQl+FSz4N1cPYQ3SSNCDadkZHx/0f+qvRGX5eQID 15 | AQABo4GBMH8wDgYDVR0PAQH/BAQDAgOoMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggr 16 | BgEFBQcDATAfBgNVHSMEGDAWgBTBVXXc35U/Jlb+VYWm3AsyiodCETAtBgNVHREE 17 | JjAkghxjZmMyYmM0ZC1lODMxLTQ1ODgtNzY0My01NDQ0hwQK/0ilMA0GCSqGSIb3 18 | DQEBCwUAA4IBAQAYBwmgU99XJ/bFrkWYXKpb4PZClxbFk8eTGWuFQiREDtum13lU 19 | uxsWGWETLewJ7xEQzoEhWTbhOu8Kc0qILc+/dgoE+ENl59quwpFiWJNAu8gJYLga 20 | 8JYaPL2RnCwx+7MBuAWkhNoX9fBWCrNo5NcJpyuaFJZPUCpmspDjQNf53ez/lnoV 21 | 8hgCdTcBRFJgmbInSHIyy//k9Tv+6wisdZUsQf7y6O5HByKNNwSFbaEfKrSY38gb 22 | 5lc9GBFsHxGgwJhy8y0y9ccMCHCMsEfKIJZPgJvyqjQqR3Y2AZiQCCexTi50f+lW 23 | ul0sbc6nZtCbml31604CjeVYA4jBCV3i6+T6 24 | -----END CERTIFICATE----- 25 | -----BEGIN CERTIFICATE----- 26 | MIIDTTCCAjWgAwIBAgIUYnMnLAdY1eziifHiE6IDh958SnwwDQYJKoZIhvcNAQEL 27 | BQAwKjEoMCYGA1UEAxMfRGllZ28gSW5zdGFuY2UgSWRlbnRpdHkgUm9vdCBDQTAe 28 | Fw0xODExMTIyMDE3MzVaFw0yMDExMTEyMDE3MzVaMDIxMDAuBgNVBAMTJ0RpZWdv 29 | IEluc3RhbmNlIElkZW50aXR5IEludGVybWVkaWF0ZSBDQTCCASIwDQYJKoZIhvcN 30 | AQEBBQADggEPADCCAQoCggEBAKzttSjhIkimTDKEwCRWFeez/S/bFP23QIjHz+Y5 31 | dl7sdX8YXwdfWbqciS2EhJ6s1QCHwMToqLb6czRtzUz1TLdyMs9wuz9XzzgJHdNj 32 | yIb9B5aSbRudhTzGIAkY6HtjSA9lSD7gn66YBt/G5b+YHeZtFzc+Ao+Su5zJZ8AD 33 | 7pWm0LP/q2Mahu+Pp3yx6dhkWV4MPDNJH6YBscQEZf08Hhew86b5adxGHmpR6ckU 34 | CpZUGHNOtE386eY6MgoN273cEj0UL7BH+YHGEeKGVrft7QYd5T/k9YC+Z7vmE9kw 35 | Ak5420Z7D3bg06y4qlguYHhqbxrlFW7HHjjrryc0Wfc7VRMCAwEAAaNjMGEwHQYD 36 | VR0OBBYEFMFVddzflT8mVv5VhabcCzKKh0IRMA4GA1UdDwEB/wQEAwICBDAfBgNV 37 | HSMEGDAWgBTFkeVheTtTImn4MXKxnOhKSBHcMzAPBgNVHRMBAf8EBTADAQH/MA0G 38 | CSqGSIb3DQEBCwUAA4IBAQBigPJqRSy13SP+vT9/dWGADoqTZSVE/JDvX4vbKuyg 39 | mOmV4hA3RbDa0vVBzDaMXLMjA4H/RFMCA3j99bec0RZXQT0sCnaYbFIU5msUEiP7 40 | 11TY8advyq5GnZaGTXaEGGkmbWTsPKlLulnawtPdEtUQwZxYnh1nc6O0LqmbniwK 41 | zuHG478KmH8r779c6KCiwkA9K6OmMpT6wxJW0N88/tQ6EnJ2VSCGaJDhB+XbwJam 42 | s+pAhGCIOOuCD3fPYlz0QQ2UN/QwRAKDV1QTzGqYBesdZTRZtnDp1q/lZd7ETt8U 43 | iF9yZCtnfUN5lTLNs7ZCxy/3/I/tW90ssLVPY/+tfX/8 44 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/instance.key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEpAIBAAKCAQEAt2O/qEPoA0jQFrI23NRIzd3EFhsNwuTpZ4DoSVIZJQsjG0gj 3 | zoj0/YZHp6sbNRlWTHz1eXJ714+0rkYvpYjOp3joEOJhsrx3Hs9eN0yDz+YqB+J3 4 | DSYt+t+nrae7wDBUAMFZXjqhrDhuFgANjsxF3Xtl1REgcRIdW9LGydAEAGlyMKAG 5 | BmQf9zofYCR+4Sw96KhQXBOTJiI+9p9pw3ndptfBhYCBdiifcHi6+e3nsOidqjrD 6 | P4PA6OfVMCxvzDkJLU2Bq1cjqHFomNB5Tc5AshyAlvDOi2+xVWBX7Z0+UujlWBYM 7 | eQl+FSz4N1cPYQ3SSNCDadkZHx/0f+qvRGX5eQIDAQABAoIBAQCK2Bh4+sCkC/KP 8 | 3GmxE3/zbR1SZzUqA0m7NVuod2HWK/Jua1XAvuxNLeb+SIuWzhIKYukvA8BDWee/ 9 | sh/MwiFDpkR81AiH3CyLxRBd6a46LtZPlePwrqFNORuoXD/HqE9RKxHQR6+zxh2C 10 | xpN9M6cJoq1cfVUEhmR36sLadIUzEVmGKVUhUv56kdrbwd3AEGrKkcWBl8N8ukCd 11 | 1qV4IU7REwPjZBbfXSequ5goSKzzMG9MbKXLAj51btkCnMtLzfHfY3sSyfQIYO62 12 | 7KJouNvdg3omNlygBsAuj4hM5nlg9uzuJQLrNEwnqOZXVGvkTXurZ+CrAN13Q5qf 13 | Xj4VyF0BAoGBAMkv+XKxH3Ck6KHsFENR3A2jb6UuvXHW77wzrN+pvXWPBZ0DhmxL 14 | PII/9clBnH4+EzINei4uhs0f0OL8+d0tqoOT0Qz6vOzhFKY/2/Cjk1ifff9uI1i3 15 | BpLjfPJyywy4HiVqjrTuDZjpp4Fj5v8jrI5Eg6Z5Xg4q3+qeAHR22ahpAoGBAOla 16 | c3r048V30LQf45Cg79uZaOtNNxCZwzcX0DZWqih0buwKfCEufhQ2ctpBbi9NeOt3 17 | 9KEe2z5PT3B+uNzPBzkUGQ/6A/+aK9JVBEtNWqJI1nR6qMXB5t+d9iQrbIf56NHA 18 | 1o3e1sAtXOvkVgh0o/ojwR//N+VMzQaDdlIvbiaRAoGBAJETukK9fRmCoYqaLeZ5 19 | skBXedvYv53Gy6uga+oBgfCzCO43q4iOHH0kWD4fxRS3+KmgVFnXDTf/2GbG2/tl 20 | wc8OGbLNYM1EZdqYtCZsHoXKxVYbevuvR9tGlkRTCR8L6hk7JNtNyppY64R/oQSd 21 | GgKhX3n9jRiUTFHoTBWv2rb5AoGAbUTNjmXdwjm4oJ/OD4tMxaewWX5uqndV0hZ0 22 | iP1L8GWVCzJdrav3nb9hSJIa5kuAs8IX6tpoD2VT7XlpVvwahb/DfJe2B5pJqtPk 23 | jt5J8nPo9+H35aJGWa+98nHjAEklnBKQZR5TsOmM+WiSYKM9pYPYiwMXSWgNGV+1 24 | qAZNrgECgYBoka0S/7jQt9TwQSRAagdmyBIo26JDQ6igqLB/lBrKgYAbqcTRmy2X 25 | bQZH1aCB/3B/NmIsqlzGOl/Uz3V6hW9Ae9X7BrXU4ug7SRH5BSff/eBY2j9YCR3e 26 | z9elUvEYUa59oaBtEJGXCOxjsypdjaR25LnW7/wVI3iBAiw6fAqlsw== 27 | -----END RSA PRIVATE KEY----- -------------------------------------------------------------------------------- /test/Steeltoe.Common.Security.Test/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "maxParallelThreads": 1, 3 | "parallelizeTestCollections": false 4 | } -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Configuration/IConfigurationBuilderExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.Configuration.Memory; 17 | using System; 18 | using System.Collections.Generic; 19 | using Xunit; 20 | 21 | namespace Steeltoe.Common.Configuration.Test 22 | { 23 | public class IConfigurationBuilderExtensionsTest 24 | { 25 | private Dictionary configEntries = new Dictionary() 26 | { 27 | { "foo", "${bazoo}" }, 28 | { "bar", "${baz}" }, 29 | { "baz", "bar" } 30 | }; 31 | 32 | [Fact] 33 | public void AddResolvedPlaceholders_ThrowsIfConfigBuilderNull() 34 | { 35 | // Arrange 36 | IConfigurationBuilder configurationBuilder = null; 37 | 38 | // Act and Assert 39 | var ex = Assert.Throws(() => IConfigurationBuilderExtensions.AddResolvedPlaceholders(configurationBuilder)); 40 | Assert.Contains(nameof(configurationBuilder), ex.Message); 41 | } 42 | 43 | [Fact] 44 | public void AddResolvedPlaceholders_AddsInMemorySourceToSourcesList() 45 | { 46 | // Arrange 47 | var configurationBuilder = new ConfigurationBuilder(); 48 | 49 | // Act and Assert 50 | configurationBuilder.AddResolvedPlaceholders(); 51 | 52 | MemoryConfigurationSource typedSource = null; 53 | foreach (var source in configurationBuilder.Sources) 54 | { 55 | typedSource = source as MemoryConfigurationSource; 56 | if (typedSource != null) 57 | { 58 | break; 59 | } 60 | } 61 | 62 | Assert.NotNull(typedSource); 63 | } 64 | 65 | [Fact] 66 | public void AddResolvedPlaceholders_OverridesResolvedValues() 67 | { 68 | // Arrange 69 | var configurationBuilder = new ConfigurationBuilder(); 70 | configurationBuilder.AddInMemoryCollection(configEntries); 71 | 72 | // Act 73 | configurationBuilder.AddResolvedPlaceholders(); 74 | var config = configurationBuilder.Build(); 75 | 76 | // Assert 77 | Assert.Equal("bar", config["bar"]); 78 | } 79 | 80 | [Fact] 81 | public void AddResolvedPlaceholders_BlanksUnResolvedValues() 82 | { 83 | // Arrange 84 | var configurationBuilder = new ConfigurationBuilder(); 85 | configurationBuilder.AddInMemoryCollection(configEntries); 86 | 87 | // Act 88 | configurationBuilder.AddResolvedPlaceholders(); 89 | var config = configurationBuilder.Build(); 90 | 91 | // Assert 92 | Assert.Equal(string.Empty, config["foo"]); 93 | } 94 | 95 | [Fact] 96 | public void AddResolvedPlaceholders_CanIgnoreUnResolvedValues() 97 | { 98 | // Arrange 99 | var configurationBuilder = new ConfigurationBuilder(); 100 | configurationBuilder.AddInMemoryCollection(configEntries); 101 | 102 | // Act 103 | configurationBuilder.AddResolvedPlaceholders(false); 104 | var config = configurationBuilder.Build(); 105 | 106 | // Assert 107 | Assert.Equal("${bazoo}", config["foo"]); 108 | } 109 | 110 | [Fact] 111 | public void AddResolvedPlaceholders_BlanksResolvedEmptyValues() 112 | { 113 | // Arrange 114 | var configurationBuilder = new ConfigurationBuilder(); 115 | configurationBuilder.AddInMemoryCollection(configEntries); 116 | 117 | // Act 118 | configurationBuilder.AddResolvedPlaceholders(); 119 | var config = configurationBuilder.Build(); 120 | 121 | // Assert 122 | Assert.Equal(string.Empty, config["foo"]); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Discovery/ConfigurationServiceInstanceProviderServiceCollectionExtensionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Microsoft.Extensions.DependencyInjection; 17 | using System.IO; 18 | using Xunit; 19 | 20 | namespace Steeltoe.Common.Discovery.Test 21 | { 22 | public class ConfigurationServiceInstanceProviderServiceCollectionExtensionsTest 23 | { 24 | [Fact] 25 | public void AddConfigurationDiscoveryClient_AddsClientWithOptions() 26 | { 27 | // arrange 28 | var appsettings = @" 29 | { 30 | 'discovery': { 31 | 'services': [ 32 | { 'serviceId': 'fruitService', 'host': 'fruitball', 'port': 443, 'isSecure': true }, 33 | { 'serviceId': 'fruitService', 'host': 'fruitballer', 'port': 8081 }, 34 | { 'serviceId': 'vegetableService', 'host': 'vegemite', 'port': 443, 'isSecure': true }, 35 | { 'serviceId': 'vegetableService', 'host': 'carrot', 'port': 8081 }, 36 | ] 37 | } 38 | }"; 39 | var path = TestHelpers.CreateTempFile(appsettings); 40 | string directory = Path.GetDirectoryName(path); 41 | string fileName = Path.GetFileName(path); 42 | var cbuilder = new ConfigurationBuilder(); 43 | cbuilder.SetBasePath(directory); 44 | cbuilder.AddJsonFile(fileName); 45 | var services = new ServiceCollection(); 46 | 47 | // act 48 | services.AddConfigurationDiscoveryClient(cbuilder.Build()); 49 | var serviceProvider = services.BuildServiceProvider(); 50 | 51 | // by getting the provider, we're confirming that the options are also available in the container 52 | var serviceInstanceProvider = serviceProvider.GetRequiredService(typeof(IServiceInstanceProvider)) as IServiceInstanceProvider; 53 | 54 | // assert 55 | Assert.NotNull(serviceInstanceProvider); 56 | Assert.IsType(serviceInstanceProvider); 57 | Assert.Equal(2, serviceInstanceProvider.Services.Count); 58 | Assert.Equal(2, serviceInstanceProvider.GetInstances("fruitService").Count); 59 | Assert.Equal(2, serviceInstanceProvider.GetInstances("vegetableService").Count); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Discovery/ConfigurationServiceInstanceProviderTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using System.Linq; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Discovery.Test 20 | { 21 | public class ConfigurationServiceInstanceProviderTest 22 | { 23 | [Fact] 24 | public void Returns_ConfiguredServices() 25 | { 26 | // arrange 27 | var services = new List 28 | { 29 | new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitball", Port = 443, IsSecure = true }, 30 | new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitballer", Port = 8081 }, 31 | new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitballerz", Port = 8082 }, 32 | new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "vegemite", Port = 443, IsSecure = true }, 33 | new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "carrot", Port = 8081 }, 34 | new ConfigurationServiceInstance { ServiceId = "vegetableService", Host = "beet", Port = 8082 }, 35 | }; 36 | var serviceOptions = new TestOptionsMonitor>(services); 37 | 38 | // act 39 | var provider = new ConfigurationServiceInstanceProvider(serviceOptions); 40 | 41 | // assert 42 | Assert.Equal(3, provider.GetInstances("fruitService").Count); 43 | Assert.Equal(3, provider.GetInstances("vegetableService").Count); 44 | Assert.Equal(2, provider.Services.Count); 45 | } 46 | 47 | [Fact] 48 | public void ReceivesUpdatesTo_ConfiguredServices() 49 | { 50 | // arrange 51 | var services = new List 52 | { 53 | new ConfigurationServiceInstance { ServiceId = "fruitService", Host = "fruitball", Port = 443, IsSecure = true }, 54 | }; 55 | var serviceOptions = new TestOptionsMonitor>(services); 56 | var provider = new ConfigurationServiceInstanceProvider(serviceOptions); 57 | Assert.Single(provider.GetInstances("fruitService")); 58 | Assert.Equal("fruitball", provider.GetInstances("fruitService").First().Host); 59 | 60 | // act 61 | services.First().Host = "updatedValue"; 62 | 63 | // assert 64 | Assert.Equal("updatedValue", provider.GetInstances("fruitService").First().Host); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Discovery/DiscoveryOptionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using System; 17 | using Xunit; 18 | 19 | namespace Steeltoe.Common.Discovery.Test 20 | { 21 | public class DiscoveryOptionsTest 22 | { 23 | [Fact] 24 | public void Constructor_Initializes_ClientType_Unknown() 25 | { 26 | var option = new DiscoveryOptions(); 27 | Assert.Equal(DiscoveryClientType.UNKNOWN, option.ClientType); 28 | } 29 | 30 | [Fact] 31 | public void Constructor_ThrowsIfConfigNull() 32 | { 33 | // Arrange 34 | IConfiguration config = null; 35 | 36 | // Act and Assert 37 | var ex = Assert.Throws(() => new DiscoveryOptions(config)); 38 | Assert.Contains(nameof(config), ex.Message); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Options/AbstractOptionsTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Steeltoe.Common.Options; 17 | using System; 18 | using System.Collections.Generic; 19 | using Xunit; 20 | 21 | namespace Steeltoe.Common.Test.Options 22 | { 23 | public class AbstractOptionsTest 24 | { 25 | [Fact] 26 | public void Constructors_ThrowsOnNulls() 27 | { 28 | IConfigurationRoot root = null; 29 | IConfiguration config = null; 30 | 31 | Assert.Throws(() => new TestOptions(root, "foobar")); 32 | Assert.Throws(() => new TestOptions(config)); 33 | } 34 | 35 | [Fact] 36 | public void Constructors_BindsValues() 37 | { 38 | var builder = new ConfigurationBuilder(); 39 | builder.AddInMemoryCollection(new Dictionary() 40 | { 41 | { "foo", "bar" } 42 | }); 43 | 44 | IConfigurationRoot root = builder.Build(); 45 | IConfiguration config = root; 46 | 47 | var opt1 = new TestOptions(root); 48 | Assert.Equal("bar", opt1.Foo); 49 | 50 | var opt2 = new TestOptions(config); 51 | Assert.Equal("bar", opt2.Foo); 52 | 53 | var builder2 = new ConfigurationBuilder(); 54 | builder2.AddInMemoryCollection(new Dictionary() 55 | { 56 | { "prefix:foo", "bar" } 57 | }); 58 | IConfigurationRoot root2 = builder2.Build(); 59 | var opt3 = new TestOptions(root2, "prefix"); 60 | Assert.Equal("bar", opt3.Foo); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Options/TestOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Configuration; 16 | using Steeltoe.Common.Options; 17 | 18 | namespace Steeltoe.Common.Test.Options 19 | { 20 | internal class TestOptions : AbstractOptions 21 | { 22 | public TestOptions(IConfigurationRoot root, string prefix) 23 | : base(root, prefix) 24 | { 25 | } 26 | 27 | public TestOptions(IConfiguration config) 28 | : base(config) 29 | { 30 | } 31 | 32 | public string Foo { get; set; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/PlatformTest.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | using Xunit; 17 | 18 | namespace Steeltoe.Common.Test 19 | { 20 | public class PlatformTest 21 | { 22 | [Fact] 23 | public void IsCloudFoundry_ReturnsExpected() 24 | { 25 | Assert.False(Platform.IsCloudFoundry); 26 | Environment.SetEnvironmentVariable("VCAP_APPLICATION", "somevalue"); 27 | Assert.True(Platform.IsCloudFoundry); 28 | Environment.SetEnvironmentVariable("VCAP_APPLICATION", null); 29 | Assert.False(Platform.IsCloudFoundry); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/Steeltoe.Common.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | netcoreapp2.0;netcoreapp2.1;net461 7 | 8 | 9 | 10 | 11 | 12 | 13 | PreserveNewest 14 | 15 | 16 | 17 | 18 | SA1101;SA1124;SA1201;SA1309;SA1310;SA1401;SA1600;SA1652;1591 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | All 35 | 36 | 37 | 38 | 39 | 40 | stylecop.json 41 | Always 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/TestHelpers.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.IO; 16 | 17 | namespace Steeltoe.Common 18 | { 19 | public class TestHelpers 20 | { 21 | public static string CreateTempFile(string contents) 22 | { 23 | var tempFile = Path.GetTempFileName(); 24 | File.WriteAllText(tempFile, contents); 25 | return tempFile; 26 | } 27 | 28 | public static Stream StringToStream(string str) 29 | { 30 | var memStream = new MemoryStream(); 31 | var textWriter = new StreamWriter(memStream); 32 | textWriter.Write(str); 33 | textWriter.Flush(); 34 | memStream.Seek(0, SeekOrigin.Begin); 35 | 36 | return memStream; 37 | } 38 | 39 | public static string StreamToString(Stream stream) 40 | { 41 | stream.Seek(0, SeekOrigin.Begin); 42 | var reader = new StreamReader(stream); 43 | 44 | return reader.ReadToEnd(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/TestOptionsMonitor.cs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 the original author or authors. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // https://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Microsoft.Extensions.Options; 16 | using System; 17 | 18 | namespace Steeltoe.Common 19 | { 20 | public class TestOptionsMonitor : IOptionsMonitor 21 | { 22 | public TestOptionsMonitor(T currentValue) 23 | { 24 | CurrentValue = currentValue; 25 | } 26 | 27 | public T Get(string name) 28 | { 29 | return CurrentValue; 30 | } 31 | 32 | public IDisposable OnChange(Action listener) 33 | { 34 | throw new NotImplementedException(); 35 | } 36 | 37 | public T CurrentValue { get; } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /test/Steeltoe.Common.Test/xunit.runner.json: -------------------------------------------------------------------------------- 1 | { 2 | "maxParallelThreads": 1, 3 | "parallelizeTestCollections": false 4 | } -------------------------------------------------------------------------------- /versions.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | --------------------------------------------------------------------------------