Skip to content

[Fixes #11183] Race condition in RouteBase.EnsureLoggers #11218

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 14, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions src/Http/Routing/src/RouteBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@

using System;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.Internal;
using Microsoft.AspNetCore.Routing.Logging;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;

namespace Microsoft.AspNetCore.Routing
{
public abstract class RouteBase : IRouter, INamedRouter
{
private readonly object _loggersLock = new object();

private TemplateMatcher _matcher;
private TemplateBinder _binder;
private ILogger _logger;
Expand Down Expand Up @@ -259,11 +258,25 @@ private void EnsureBinder(HttpContext context)

private void EnsureLoggers(HttpContext context)
{
// We check first using the _logger to see if the loggers have been initialized to avoid taking
// the lock on the most common case.
if (_logger == null)
{
var factory = context.RequestServices.GetRequiredService<ILoggerFactory>();
_logger = factory.CreateLogger(typeof(RouteBase).FullName);
_constraintLogger = factory.CreateLogger(typeof(RouteConstraintMatcher).FullName);
// We need to lock here to ensure that _constraintLogger and _logger get initialized atomically.
lock (_loggersLock)
{
if (_logger != null)
{
// Multiple threads might have tried to accquire the lock at the same time. Technically
// there is nothing wrong if things get reinitialized by a second thread, but its easy
// to prevent by just rechecking and returning here.
return;
}

var factory = context.RequestServices.GetRequiredService<ILoggerFactory>();
_constraintLogger = factory.CreateLogger(typeof(RouteConstraintMatcher).FullName);
_logger = factory.CreateLogger(typeof(RouteBase).FullName);
}
}
}

Expand Down