├── .dockerignore ├── .gitignore ├── ConfigMapFileProviderSample.sln ├── LICENSE ├── README.md ├── media └── article-preview.png └── src └── ConfigMapFileProviderSample ├── ConfigMapFileProvider.cs ├── ConfigMapFileProviderChangeToken.cs ├── ConfigMapFileProviderSample.csproj ├── Controllers └── ValuesController.cs ├── Dockerfile ├── Program.cs ├── Startup.cs ├── appsettings.Development.json ├── appsettings.json ├── configmap.yaml └── deployment.yaml /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.vs 6 | **/.vscode 7 | **/*.*proj.user 8 | **/azds.yaml 9 | **/charts 10 | **/bin 11 | **/obj 12 | **/Dockerfile 13 | **/Dockerfile.develop 14 | **/docker-compose.yml 15 | **/docker-compose.*.yml 16 | **/*.dbmdl 17 | **/*.jfm 18 | **/secrets.dev.yaml 19 | **/values.dev.yaml 20 | **/.toolstarget -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /ConfigMapFileProviderSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29215.179 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConfigMapFileProviderSample", "src\ConfigMapFileProviderSample\ConfigMapFileProviderSample.csproj", "{1343A1BF-33E0-49D5-AADB-A323867697AE}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {1343A1BF-33E0-49D5-AADB-A323867697AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {1343A1BF-33E0-49D5-AADB-A323867697AE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {1343A1BF-33E0-49D5-AADB-A323867697AE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {1343A1BF-33E0-49D5-AADB-A323867697AE}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {AB82D515-15E8-4AAE-A7B7-0CDC78DB7234} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Francisco Beltrao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .NET Configuration in Kubernetes config maps with auto reload 2 | 3 | ![Log level configuration in config map](media/article-preview.png) 4 | 5 | Kubernetes config maps allows the injection of configuration into an application. The contents of a config map can be injected as environment variables or mounted files. 6 | 7 | For instance, imagine you want to configure the log level in a separated file that will be mounted into your application. 8 | 9 | The following config map limits the verbosity to errors: 10 | 11 | ```yaml 12 | apiVersion: v1 13 | kind: ConfigMap 14 | metadata: 15 | name: demo-config 16 | data: 17 | appsettings.json: |- 18 | { 19 | "Logging": { 20 | "LogLevel": { 21 | "Default": "Error", 22 | "System": "Error", 23 | "Microsoft": "Error" 24 | } 25 | } 26 | } 27 | ``` 28 | 29 | The file below deploys an application, mounting the contents of the config map into the /app/config folder. 30 | 31 | ```yaml 32 | apiVersion: apps/v1 33 | kind: Deployment 34 | metadata: 35 | name: demo-deployment 36 | labels: 37 | app: config-demo-app 38 | spec: 39 | replicas: 1 40 | selector: 41 | matchLabels: 42 | app: config-demo-app 43 | template: 44 | metadata: 45 | labels: 46 | app: config-demo-app 47 | spec: 48 | containers: 49 | - name: configmapfileprovidersample 50 | image: fbeltrao/configmapfileprovidersample:1.0 51 | ports: 52 | - containerPort: 80 53 | volumeMounts: 54 | - name: config-volume 55 | mountPath: /app/config 56 | volumes: 57 | - name: config-volume 58 | configMap: 59 | name: demo-config 60 | ``` 61 | 62 | In order to read configurations from the provided path (`config/appsettings.json`) the following code changes are required: 63 | 64 | ```c# 65 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 66 | WebHost.CreateDefaultBuilder(args) 67 | .ConfigureAppConfiguration(c => 68 | { 69 | c.AddJsonFile("config/appsettings.json", optional: true, reloadOnChange: true); 70 | }) 71 | .UseStartup(); 72 | ``` 73 | 74 | 75 | Deploy the application: 76 | ```bash 77 | kubectl apply -f configmap.yaml 78 | kubectl apply -f deployment.yaml 79 | ``` 80 | 81 | We can peek into the running pod in Kubernetes, looking at the files stored in the container: 82 | 83 | ```bash 84 | kubectl exec -it -- bash 85 | root@demo-deployment-844f6c6546-x786b:/app# cd config/ 86 | root@demo-deployment-844f6c6546-x786b:/app/config# ls -la 87 | 88 | rwxrwxrwx 3 root root 4096 Sep 14 09:01 . 89 | drwxr-xr-x 1 root root 4096 Sep 14 08:47 .. 90 | drwxr-xr-x 2 root root 4096 Sep 14 09:01 ..2019_09_14_09_01_16.386067924 91 | lrwxrwxrwx 1 root root 31 Sep 14 09:01 ..data -> ..2019_09_14_09_01_16.386067924 92 | lrwxrwxrwx 1 root root 53 Sep 14 08:47 appsettings.json -> ..data/appsettings.json 93 | ``` 94 | 95 | As you can see, the config map content is mounted using a [symlink](https://en.wikipedia.org/wiki/Symbolic_link). 96 | 97 | Let's change the log verbosity to `debug`, making the following changes to the config map: 98 | 99 | ```yaml 100 | apiVersion: v1 101 | kind: ConfigMap 102 | metadata: 103 | name: demo-config 104 | data: 105 | appsettings.json: |- 106 | { 107 | "Logging": { 108 | "LogLevel": { 109 | "Default": "Debug", 110 | "System": "Error", 111 | "Microsoft": "Error" 112 | } 113 | } 114 | } 115 | ``` 116 | and redeploying it 117 | 118 | ```bash 119 | kubectl apply -f configmap.yaml 120 | ``` 121 | 122 | Eventually the changes will be applied to the mounted file inside the container, as you can see below: 123 | 124 | ```bash 125 | root@demo-deployment-844f6c6546-gzc6j:/app/config# ls -la 126 | total 12 127 | drwxrwxrwx 3 root root 4096 Sep 14 09:05 . 128 | drwxr-xr-x 1 root root 4096 Sep 14 08:47 .. 129 | drwxr-xr-x 2 root root 4096 Sep 14 09:05 ..2019_09_14_09_05_02.797339427 130 | lrwxrwxrwx 1 root root 31 Sep 14 09:05 ..data -> ..2019_09_14_09_05_02.797339427 131 | lrwxrwxrwx 1 root root 53 Sep 14 08:47 appsettings.json -> ..data/appsettings.json 132 | ``` 133 | 134 | Notice that the appsettings.json last modified date does not change, only the referenced file actually gets updated. 135 | 136 | Unfortunately, the build-in reload on changes in .NET core file provider does not work. The config map does not trigger the configuration reload as one would expect. 137 | 138 | Based on my investigation, it seems that the .NET core change discovery relies on the file last modified date. Since the file we are monitoring did not change (the symlink reference did), no changes are detected. 139 | 140 | ## Working on a solution 141 | 142 | This problem is tracked [here](https://github.com/aspnet/Extensions/issues/1175). Until a fix is available we can take advantage of the extensible configuration system in .NET Core and implement a file based configuration provider that detect changes based on file contents. 143 | 144 | The setup looks like this: 145 | ```c# 146 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 147 | WebHost.CreateDefaultBuilder(args) 148 | .ConfigureAppConfiguration(c => 149 | { 150 | c.AddJsonFile(ConfigMapFileProvider.FromRelativePath("config"), 151 | "appsettings.json", 152 | optional: true, 153 | reloadOnChange: true); 154 | }) 155 | .UseStartup(); 156 | ``` 157 | 158 | The provided implementation detect changes based on the hash of the content. Check the sample project files for more details. 159 | 160 | Disclaimer: this is a quick implementation, not tested in different environments/configurations. Use at your own risk. 161 | 162 | ### Testing the sample application 163 | 164 | Clone this repository then deploy the application: 165 | ```bash 166 | kubectl apply -f configmap.yaml 167 | kubectl apply -f deployment.yaml 168 | ``` 169 | 170 | In a separated console window stream the container log: 171 | ```bash 172 | kubectl logs -l app=config-demo-app -f 173 | ``` 174 | 175 | Open a tunnel to the application with kubectl port-forward 176 | ```bash 177 | kubectl port-forward 60000:80 178 | ``` 179 | 180 | Verify that the log is in error level, by opening a browser and navigating to `http://localhost:60000/api/values`. Look at the pod logs. You should see the following lines: 181 | ```log 182 | fail: ConfigMapFileProviderSample.Controllers.ValuesController[0] 183 | ERR log 184 | crit: ConfigMapFileProviderSample.Controllers.ValuesController[0] 185 | CRI log 186 | ``` 187 | 188 | Change the config map: 189 | Replace `"Default": "Error"` to `"Default": "Debug"` in the configmap.yaml file, then redeploy the config map. 190 | ```bash 191 | kubectl apply -f configmap.yaml 192 | ``` 193 | 194 | Verify that the log level changes to Debug (it can take a couple of minutes until the file change is detected) by issuing new requests to `http://localhost:60000/api/values`. The logs will change to this: 195 | ```log 196 | dbug: ConfigMapFileProviderSample.Controllers.ValuesController[0] 197 | DBG log 198 | info: ConfigMapFileProviderSample.Controllers.ValuesController[0] 199 | INF log 200 | warn: ConfigMapFileProviderSample.Controllers.ValuesController[0] 201 | WRN log 202 | fail: ConfigMapFileProviderSample.Controllers.ValuesController[0] 203 | ERR log 204 | crit: ConfigMapFileProviderSample.Controllers.ValuesController[0] 205 | CRI log 206 | ``` -------------------------------------------------------------------------------- /media/article-preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fbeltrao/ConfigMapFileProvider/216dfa1a42d40dc8c5aaead0ee69561b94eba1ad/media/article-preview.png -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/ConfigMapFileProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.FileProviders; 2 | using Microsoft.Extensions.FileProviders.Internal; 3 | using Microsoft.Extensions.FileProviders.Physical; 4 | using Microsoft.Extensions.Primitives; 5 | using System.Collections.Concurrent; 6 | using System.IO; 7 | using System.Reflection; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace ConfigMapFileProviderSample 12 | { 13 | /// 14 | /// Simple implementation using config maps as source 15 | /// Config maps volumes in Linux/Kubernetes are implemented as symlink files. 16 | /// Once reloaded their Last modified date does not change. This implementation uses a check sum to verify 17 | /// 18 | public class ConfigMapFileProvider : IFileProvider 19 | { 20 | ConcurrentDictionary watchers; 21 | 22 | public static IFileProvider FromRelativePath(string subPath) 23 | { 24 | var executableLocation = Assembly.GetEntryAssembly().Location; 25 | var executablePath = Path.GetDirectoryName(executableLocation); 26 | var configPath = Path.Combine(executablePath, subPath); 27 | if (Directory.Exists(configPath)) 28 | { 29 | return new ConfigMapFileProvider(configPath); 30 | } 31 | 32 | return null; 33 | } 34 | 35 | public ConfigMapFileProvider(string rootPath) 36 | { 37 | if (string.IsNullOrWhiteSpace(rootPath)) 38 | { 39 | throw new System.ArgumentException("Invalid root path", nameof(rootPath)); 40 | } 41 | 42 | RootPath = rootPath; 43 | watchers = new ConcurrentDictionary(); 44 | } 45 | 46 | public string RootPath { get; } 47 | 48 | public IDirectoryContents GetDirectoryContents(string subpath) 49 | { 50 | return new PhysicalDirectoryContents(Path.Combine(RootPath, subpath)); 51 | } 52 | 53 | public IFileInfo GetFileInfo(string subpath) 54 | { 55 | var fi = new FileInfo(Path.Combine(RootPath, subpath)); 56 | return new PhysicalFileInfo(fi); 57 | } 58 | 59 | public IChangeToken Watch(string filter) 60 | { 61 | var watcher = watchers.AddOrUpdate(filter, 62 | addValueFactory: (f) => 63 | { 64 | return new ConfigMapFileProviderChangeToken(RootPath, filter); 65 | }, 66 | updateValueFactory: (f, e) => 67 | { 68 | e.Dispose(); 69 | return new ConfigMapFileProviderChangeToken(RootPath, filter); 70 | }); 71 | 72 | watcher.EnsureStarted(); 73 | return watcher; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/ConfigMapFileProviderChangeToken.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Primitives; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Security.Cryptography; 6 | using System.Threading; 7 | using Timer = System.Threading.Timer; 8 | 9 | namespace ConfigMapFileProviderSample 10 | { 11 | public sealed class ConfigMapFileProviderChangeToken : IChangeToken, IDisposable 12 | { 13 | class CallbackRegistration : IDisposable 14 | { 15 | Action callback; 16 | object state; 17 | Action unregister; 18 | 19 | 20 | public CallbackRegistration(Action callback, object state, Action unregister) 21 | { 22 | this.callback = callback; 23 | this.state = state; 24 | this.unregister = unregister; 25 | } 26 | 27 | public void Notify() 28 | { 29 | var localState = this.state; 30 | var localCallback = this.callback; 31 | if (localCallback != null) 32 | { 33 | localCallback.Invoke(localState); 34 | } 35 | } 36 | 37 | 38 | public void Dispose() 39 | { 40 | var localUnregister = Interlocked.Exchange(ref unregister, null); 41 | if (localUnregister != null) 42 | { 43 | localUnregister(this); 44 | this.callback = null; 45 | this.state = null; 46 | } 47 | } 48 | } 49 | 50 | List registeredCallbacks; 51 | private readonly string rootPath; 52 | private string filter; 53 | private readonly int detectChangeIntervalMs; 54 | private Timer timer; 55 | private bool hasChanged; 56 | private string lastChecksum; 57 | object timerLock = new object(); 58 | 59 | public ConfigMapFileProviderChangeToken(string rootPath, string filter, int detectChangeIntervalMs = 30_000) 60 | { 61 | Console.WriteLine($"new {nameof(ConfigMapFileProviderChangeToken)} for {filter}"); 62 | registeredCallbacks = new List(); 63 | this.rootPath = rootPath; 64 | this.filter = filter; 65 | this.detectChangeIntervalMs = detectChangeIntervalMs; 66 | } 67 | 68 | internal void EnsureStarted() 69 | { 70 | lock (timerLock) 71 | { 72 | if (timer == null) 73 | { 74 | var fullPath = Path.Combine(rootPath, filter); 75 | if (File.Exists(fullPath)) 76 | { 77 | this.timer = new Timer(CheckForChanges); 78 | this.timer.Change(0, detectChangeIntervalMs); 79 | } 80 | } 81 | } 82 | } 83 | 84 | private void CheckForChanges(object state) 85 | { 86 | var fullPath = Path.Combine(rootPath, filter); 87 | 88 | Console.WriteLine($"Checking for changes in {fullPath}"); 89 | 90 | var newCheckSum = GetFileChecksum(fullPath); 91 | var newHasChangesValue = false; 92 | if (this.lastChecksum != null && this.lastChecksum != newCheckSum) 93 | { 94 | Console.WriteLine($"File {fullPath} was modified!"); 95 | 96 | // changed 97 | NotifyChanges(); 98 | 99 | newHasChangesValue = true; 100 | } 101 | 102 | this.hasChanged = newHasChangesValue; 103 | 104 | this.lastChecksum = newCheckSum; 105 | 106 | } 107 | 108 | private void NotifyChanges() 109 | { 110 | var localRegisteredCallbacks = registeredCallbacks; 111 | if (localRegisteredCallbacks != null) 112 | { 113 | var count = localRegisteredCallbacks.Count; 114 | for (int i = 0; i < count; i++) 115 | { 116 | localRegisteredCallbacks[i].Notify(); 117 | } 118 | } 119 | } 120 | 121 | string GetFileChecksum(string filename) 122 | { 123 | using (var md5 = MD5.Create()) 124 | { 125 | using (var stream = File.OpenRead(filename)) 126 | { 127 | return BitConverter.ToString(md5.ComputeHash(stream)); 128 | } 129 | } 130 | } 131 | 132 | public bool HasChanged => this.hasChanged; 133 | 134 | public bool ActiveChangeCallbacks => true; 135 | 136 | public IDisposable RegisterChangeCallback(Action callback, object state) 137 | { 138 | var localRegisteredCallbacks = registeredCallbacks; 139 | if (localRegisteredCallbacks == null) 140 | throw new ObjectDisposedException(nameof(registeredCallbacks)); 141 | 142 | var cbRegistration = new CallbackRegistration(callback, state, (cb) => localRegisteredCallbacks.Remove(cb)); 143 | localRegisteredCallbacks.Add(cbRegistration); 144 | 145 | return cbRegistration; 146 | } 147 | 148 | public void Dispose() 149 | { 150 | Interlocked.Exchange(ref registeredCallbacks, null); 151 | 152 | Timer localTimer = null; 153 | lock (timerLock) 154 | { 155 | localTimer = Interlocked.Exchange(ref timer, null); 156 | } 157 | 158 | if (localTimer != null) 159 | { 160 | localTimer.Dispose(); 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/ConfigMapFileProviderSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp2.2 5 | InProcess 6 | Linux 7 | ..\.. 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace ConfigMapFileProviderSample.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | [ApiController] 12 | public class ValuesController : ControllerBase 13 | { 14 | private readonly ILogger logger; 15 | 16 | public ValuesController(ILogger logger) 17 | { 18 | this.logger = logger; 19 | } 20 | 21 | // GET api/values 22 | [HttpGet] 23 | public ActionResult> Get() 24 | { 25 | logger.LogDebug("DBG log"); 26 | logger.LogInformation("INF log"); 27 | logger.LogWarning("WRN log"); 28 | logger.LogError("ERR log"); 29 | logger.LogCritical("CRI log"); 30 | return new string[] { "value1", "value2" }; 31 | } 32 | 33 | // GET api/values/5 34 | [HttpGet("{id}")] 35 | public ActionResult Get(int id) 36 | { 37 | return "value"; 38 | } 39 | 40 | // POST api/values 41 | [HttpPost] 42 | public void Post([FromBody] string value) 43 | { 44 | } 45 | 46 | // PUT api/values/5 47 | [HttpPut("{id}")] 48 | public void Put(int id, [FromBody] string value) 49 | { 50 | } 51 | 52 | // DELETE api/values/5 53 | [HttpDelete("{id}")] 54 | public void Delete(int id) 55 | { 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-stretch-slim AS base 2 | WORKDIR /app 3 | EXPOSE 80 4 | 5 | FROM mcr.microsoft.com/dotnet/core/sdk:2.2-stretch AS build 6 | WORKDIR /src 7 | COPY ["src/ConfigMapFileProviderSample/ConfigMapFileProviderSample.csproj", "src/ConfigMapFileProviderSample/"] 8 | RUN dotnet restore "src/ConfigMapFileProviderSample/ConfigMapFileProviderSample.csproj" 9 | COPY . . 10 | WORKDIR "/src/src/ConfigMapFileProviderSample" 11 | RUN dotnet build "ConfigMapFileProviderSample.csproj" -c Release -o /app 12 | 13 | FROM build AS publish 14 | RUN dotnet publish "ConfigMapFileProviderSample.csproj" -c Release -o /app 15 | 16 | FROM base AS final 17 | WORKDIR /app 18 | COPY --from=publish /app . 19 | ENTRYPOINT ["dotnet", "ConfigMapFileProviderSample.dll"] -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.AspNetCore; 8 | using Microsoft.AspNetCore.Hosting; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.FileProviders; 11 | using Microsoft.Extensions.Logging; 12 | 13 | namespace ConfigMapFileProviderSample 14 | { 15 | public class Program 16 | { 17 | public static void Main(string[] args) 18 | { 19 | CreateWebHostBuilder(args).Build().Run(); 20 | } 21 | 22 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 23 | WebHost.CreateDefaultBuilder(args) 24 | .ConfigureAppConfiguration(c => 25 | { 26 | c.AddJsonFile(ConfigMapFileProvider.FromRelativePath("config"), 27 | "appsettings.json", 28 | optional: true, 29 | reloadOnChange: true); 30 | }) 31 | .UseStartup(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace ConfigMapFileProviderSample 14 | { 15 | 16 | public class Startup 17 | { 18 | public Startup(IConfiguration configuration) 19 | { 20 | Configuration = configuration; 21 | } 22 | 23 | public IConfiguration Configuration { get; } 24 | 25 | // This method gets called by the runtime. Use this method to add services to the container. 26 | public void ConfigureServices(IServiceCollection services) 27 | { 28 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 29 | } 30 | 31 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 32 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 33 | { 34 | if (env.IsDevelopment()) 35 | { 36 | app.UseDeveloperExceptionPage(); 37 | } 38 | 39 | app.UseMvc(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/configmap.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ConfigMap 3 | metadata: 4 | name: demo-config 5 | data: 6 | appsettings.json: |- 7 | { 8 | "Logging": { 9 | "LogLevel": { 10 | "Default": "Error", 11 | "System": "Error", 12 | "Microsoft": "Error" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/ConfigMapFileProviderSample/deployment.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: demo-deployment 5 | labels: 6 | app: config-demo-app 7 | spec: 8 | replicas: 1 9 | selector: 10 | matchLabels: 11 | app: config-demo-app 12 | template: 13 | metadata: 14 | labels: 15 | app: config-demo-app 16 | spec: 17 | containers: 18 | - name: configmapfileprovidersample 19 | imagePullPolicy: Always 20 | image: fbeltrao/configmapfileprovidersample:1.0 21 | ports: 22 | - containerPort: 80 23 | volumeMounts: 24 | - name: config-volume 25 | mountPath: /app/config 26 | volumes: 27 | - name: config-volume 28 | configMap: 29 | name: demo-config --------------------------------------------------------------------------------