diff --git a/NzbDrone.Api/AutomapperBootstraper.cs b/NzbDrone.Api/AutomapperBootstraper.cs new file mode 100644 index 000000000..17bff19ad --- /dev/null +++ b/NzbDrone.Api/AutomapperBootstraper.cs @@ -0,0 +1,45 @@ +using System; +using AutoMapper; +using NzbDrone.Api.QualityProfiles; +using NzbDrone.Api.QualityType; +using NzbDrone.Api.Resolvers; +using NzbDrone.Api.Series; +using NzbDrone.Core.Repository.Quality; + +namespace NzbDrone.Api +{ + public static class AutomapperBootstraper + { + + public static void InitializeAutomapper() + { + //QualityProfiles + Mapper.CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.QualityProfileId)) + .ForMember(dest => dest.Qualities, + opt => opt.ResolveUsing().FromMember(src => src.Allowed)); + + Mapper.CreateMap() + .ForMember(dest => dest.QualityProfileId, opt => opt.MapFrom(src => src.Id)) + .ForMember(dest => dest.Allowed, + opt => opt.ResolveUsing().FromMember(src => src.Qualities)); + + Mapper.CreateMap() + .ForMember(dest => dest.Allowed, opt => opt.Ignore()); + + //QualityTypes + Mapper.CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.QualityTypeId)); + + Mapper.CreateMap() + .ForMember(dest => dest.QualityTypeId, opt => opt.MapFrom(src => src.Id)); + + //Series + Mapper.CreateMap() + .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.SeriesId)) + .ForMember(dest => dest.CustomStartDate, opt => opt.ResolveUsing().FromMember(src => src.CustomStartDate)) + .ForMember(dest => dest.BacklogSetting, opt => opt.MapFrom(src => (Int32)src.BacklogSetting)) + .ForMember(dest => dest.NextAiring, opt => opt.ResolveUsing()); + } + } +} \ No newline at end of file diff --git a/NzbDrone.Api/Bootstrapper.cs b/NzbDrone.Api/Bootstrapper.cs deleted file mode 100644 index dc07f319e..000000000 --- a/NzbDrone.Api/Bootstrapper.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Linq; -using AutoMapper; -using Autofac; -using NLog; -using Nancy.Bootstrapper; -using Nancy.Bootstrappers.Autofac; -using Nancy.Conventions; -using Nancy.Diagnostics; -using NzbDrone.Api.ErrorManagment; -using NzbDrone.Api.Extentions; -using NzbDrone.Api.QualityProfiles; -using NzbDrone.Api.QualityType; -using NzbDrone.Api.Resolvers; -using NzbDrone.Api.Series; -using NzbDrone.Core; -using NzbDrone.Core.Helpers; -using NzbDrone.Core.Repository.Quality; -using ErrorPipeline = NzbDrone.Api.ErrorManagment.ErrorPipeline; - -namespace NzbDrone.Api -{ - - public class Bootstrapper : AutofacNancyBootstrapper - { - private readonly Logger _logger; - - public Bootstrapper() - { - _logger = LogManager.GetCurrentClassLogger(); - } - - protected override Nancy.IRootPathProvider RootPathProvider - { - get - { - return new RootPathProvider(); - } - } - - protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) - { - InitializeAutomapper(); - } - - public static void InitializeAutomapper() - { - //QualityProfiles - Mapper.CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.QualityProfileId)) - .ForMember(dest => dest.Qualities, - opt => opt.ResolveUsing().FromMember(src => src.Allowed)); - - Mapper.CreateMap() - .ForMember(dest => dest.QualityProfileId, opt => opt.MapFrom(src => src.Id)) - .ForMember(dest => dest.Allowed, - opt => opt.ResolveUsing().FromMember(src => src.Qualities)); - - Mapper.CreateMap() - .ForMember(dest => dest.Allowed, opt => opt.Ignore()); - - //QualityTypes - Mapper.CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.QualityTypeId)); - - Mapper.CreateMap() - .ForMember(dest => dest.QualityTypeId, opt => opt.MapFrom(src => src.Id)); - - //Series - Mapper.CreateMap() - .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.SeriesId)) - .ForMember(dest => dest.CustomStartDate, opt => opt.ResolveUsing().FromMember(src => src.CustomStartDate)) - .ForMember(dest => dest.BacklogSetting, opt => opt.MapFrom(src => (Int32)src.BacklogSetting)) - .ForMember(dest => dest.NextAiring, opt => opt.ResolveUsing()); - } - - protected override ILifetimeScope GetApplicationContainer() - { - _logger.Info("Starting NzbDrone API"); - - - var builder = new ContainerBuilder(); - - builder.RegisterCoreServices(); - - builder.RegisterAssemblyTypes(typeof(Bootstrapper).Assembly) - .AsImplementedInterfaces() - .SingleInstance(); - - builder.RegisterType().AsSelf().SingleInstance(); - - - var container = builder.Build(); - - ApplicationPipelines.OnError.AddItemToEndOfPipeline(container.Resolve().HandleException); - - - return container; - } - - protected override NancyInternalConfiguration InternalConfiguration - { - get - { - var internalConfig = NancyInternalConfiguration.Default; - - internalConfig.StatusCodeHandlers.Add(typeof(ErrorHandler)); - internalConfig.Serializers.Add(typeof(NancyJsonSerializer)); - - - return internalConfig; - } - } - - - protected override DiagnosticsConfiguration DiagnosticsConfiguration - { - get { return new DiagnosticsConfiguration { Password = @"password" }; } - } - - - protected override void ConfigureConventions(Nancy.Conventions.NancyConventions nancyConventions) - { - base.ConfigureConventions(nancyConventions); - Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("static", @"NzbDrone.Backbone",new string[]{".css",".js",".html",".htm",".jpg",".jpeg",".icon",".gif",".png",".woff",".ttf"})); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Api/ContainerExtentions.cs b/NzbDrone.Api/ContainerExtentions.cs new file mode 100644 index 000000000..f75c23271 --- /dev/null +++ b/NzbDrone.Api/ContainerExtentions.cs @@ -0,0 +1,23 @@ +using System.Linq; +using System.Reflection; +using Autofac; + +namespace NzbDrone.Api +{ + public static class ContainerExtensions + { + public static void RegisterApiServices(this ContainerBuilder containerBuilder) + { + var apiAssembly = Assembly.Load("NzbDrone.Api"); + + + containerBuilder.RegisterAssemblyTypes(apiAssembly) + .AsImplementedInterfaces() + .SingleInstance(); + + containerBuilder.RegisterAssemblyTypes(apiAssembly) + .AsSelf() + .SingleInstance(); + } + } +} \ No newline at end of file diff --git a/NzbDrone.Api/ErrorManagment/ApiException.cs b/NzbDrone.Api/ErrorManagement/ApiException.cs similarity index 93% rename from NzbDrone.Api/ErrorManagment/ApiException.cs rename to NzbDrone.Api/ErrorManagement/ApiException.cs index 547d02255..84f859724 100644 --- a/NzbDrone.Api/ErrorManagment/ApiException.cs +++ b/NzbDrone.Api/ErrorManagement/ApiException.cs @@ -4,9 +4,8 @@ using Nancy; using Nancy.Responses; using Newtonsoft.Json; using NzbDrone.Api.Extentions; -using NzbDrone.Api.QualityType; -namespace NzbDrone.Api.ErrorManagment +namespace NzbDrone.Api.ErrorManagement { public abstract class ApiException : Exception { diff --git a/NzbDrone.Api/ErrorManagment/ErrorHandler.cs b/NzbDrone.Api/ErrorManagement/ErrorHandler.cs similarity index 93% rename from NzbDrone.Api/ErrorManagment/ErrorHandler.cs rename to NzbDrone.Api/ErrorManagement/ErrorHandler.cs index 5f455f4a4..e3f82c3e3 100644 --- a/NzbDrone.Api/ErrorManagment/ErrorHandler.cs +++ b/NzbDrone.Api/ErrorManagement/ErrorHandler.cs @@ -2,9 +2,8 @@ using Nancy; using Nancy.ErrorHandling; using NzbDrone.Api.Extentions; -using NzbDrone.Api.QualityType; -namespace NzbDrone.Api.ErrorManagment +namespace NzbDrone.Api.ErrorManagement { public class ErrorHandler : IStatusCodeHandler { diff --git a/NzbDrone.Api/ErrorManagment/ErrorModel.cs b/NzbDrone.Api/ErrorManagement/ErrorModel.cs similarity index 90% rename from NzbDrone.Api/ErrorManagment/ErrorModel.cs rename to NzbDrone.Api/ErrorManagement/ErrorModel.cs index 81f83a0bf..6bc2296a6 100644 --- a/NzbDrone.Api/ErrorManagment/ErrorModel.cs +++ b/NzbDrone.Api/ErrorManagement/ErrorModel.cs @@ -1,6 +1,6 @@ using System.Linq; -namespace NzbDrone.Api.ErrorManagment +namespace NzbDrone.Api.ErrorManagement { public class ErrorModel { diff --git a/NzbDrone.Api/ErrorManagment/ErrorPipeline.cs b/NzbDrone.Api/ErrorManagement/ErrorPipeline.cs similarity index 95% rename from NzbDrone.Api/ErrorManagment/ErrorPipeline.cs rename to NzbDrone.Api/ErrorManagement/ErrorPipeline.cs index feb15e929..60cbfc7f8 100644 --- a/NzbDrone.Api/ErrorManagment/ErrorPipeline.cs +++ b/NzbDrone.Api/ErrorManagement/ErrorPipeline.cs @@ -4,7 +4,7 @@ using NLog; using Nancy; using NzbDrone.Api.Extentions; -namespace NzbDrone.Api.ErrorManagment +namespace NzbDrone.Api.ErrorManagement { public class ErrorPipeline { diff --git a/NzbDrone.Api/NancyBootstrapper.cs b/NzbDrone.Api/NancyBootstrapper.cs new file mode 100644 index 000000000..562517112 --- /dev/null +++ b/NzbDrone.Api/NancyBootstrapper.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Autofac; +using NLog; +using Nancy.Bootstrapper; +using Nancy.Bootstrappers.Autofac; +using Nancy.Conventions; +using Nancy.Diagnostics; +using NzbDrone.Api.ErrorManagement; +using NzbDrone.Api.Extentions; +using NzbDrone.Common; +using NzbDrone.Core; +using NzbDrone.Core.Lifecycle; +using NzbDrone.Core.Providers.Core; +using SignalR; + +namespace NzbDrone.Api +{ + + public class NancyBootstrapper : AutofacNancyBootstrapper + { + private readonly Logger _logger; + + public NancyBootstrapper() + { + _logger = LogManager.GetCurrentClassLogger(); + } + + protected override Nancy.IRootPathProvider RootPathProvider + { + get + { + return new RootPathProvider(); + } + } + + protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) + { + _logger.Info("Starting NzbDrone API"); + AutomapperBootstraper.InitializeAutomapper(); + SignalRBootstraper.InitializeAutomapper(container); + RegisterReporting(container); + KickoffInitilizables(container); + + ApplicationPipelines.OnError.AddItemToEndOfPipeline(container.Resolve().HandleException); + } + + private void KickoffInitilizables(ILifetimeScope container) + { + var initilizables = container.Resolve>(); + + foreach (var initializable in initilizables) + { + _logger.Debug("Initializing {0}", initializable.GetType().Name); + try + { + initializable.Init(); + + } + catch (Exception e) + { + _logger.FatalException("An error occurred while initializing " + initializable.GetType().Name, e); + throw; + } + } + } + + private void RegisterReporting(ILifetimeScope container) + { + EnvironmentProvider.UGuid = container.Resolve().UGuid; + ReportingService.RestProvider = container.Resolve(); + ReportingService.SetupExceptronDriver(); + } + + protected override ILifetimeScope GetApplicationContainer() + { + _logger.Debug("Initializing Service Container"); + + var builder = new ContainerBuilder(); + builder.RegisterCoreServices(); + builder.RegisterApiServices(); + + var container = builder.Build(); + + return container; + } + + protected override NancyInternalConfiguration InternalConfiguration + { + get + { + var internalConfig = NancyInternalConfiguration.Default; + + internalConfig.StatusCodeHandlers.Add(typeof(ErrorHandler)); + internalConfig.Serializers.Add(typeof(NancyJsonSerializer)); + + return internalConfig; + } + } + + protected override DiagnosticsConfiguration DiagnosticsConfiguration + { + get { return new DiagnosticsConfiguration { Password = @"password" }; } + } + + protected override void ConfigureConventions(NancyConventions nancyConventions) + { + base.ConfigureConventions(nancyConventions); + Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("static", @"NzbDrone.Backbone", new string[] { ".css", ".js", ".html", ".htm", ".jpg", ".jpeg", ".icon", ".gif", ".png", ".woff", ".ttf" })); + } + } + + public static class SignalRBootstraper + { + + public static void InitializeAutomapper(ILifetimeScope container) + { + GlobalHost.DependencyResolver = new AutofacSignalrDependencyResolver(container.BeginLifetimeScope("SignalR")); + } + } +} \ No newline at end of file diff --git a/NzbDrone.Api/NzbDrone.Api.csproj b/NzbDrone.Api/NzbDrone.Api.csproj index ea128cd56..43ee52e58 100644 --- a/NzbDrone.Api/NzbDrone.Api.csproj +++ b/NzbDrone.Api/NzbDrone.Api.csproj @@ -86,6 +86,14 @@ False ..\packages\NLog.2.0.0.2000\lib\net40\NLog.dll + + False + ..\packages\SignalR.Server.0.5.3\lib\net40\SignalR.dll + + + False + ..\packages\SignalR.Hosting.Common.0.5.3\lib\net40\SignalR.Hosting.Common.dll + @@ -99,6 +107,8 @@ + + @@ -112,11 +122,11 @@ - - - - - + + + + + diff --git a/NzbDrone.Api/packages.config b/NzbDrone.Api/packages.config index a3fc7c270..d85739be2 100644 --- a/NzbDrone.Api/packages.config +++ b/NzbDrone.Api/packages.config @@ -8,4 +8,6 @@ + + \ No newline at end of file diff --git a/NzbDrone.Common/ConsoleProvider.cs b/NzbDrone.Common/ConsoleProvider.cs index 094c4b9ba..7b9ce162a 100644 --- a/NzbDrone.Common/ConsoleProvider.cs +++ b/NzbDrone.Common/ConsoleProvider.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using System.IO; -using System.Threading; namespace NzbDrone.Common { diff --git a/NzbDrone.Common/HostController.cs b/NzbDrone.Common/HostController.cs new file mode 100644 index 000000000..a9cb2ead2 --- /dev/null +++ b/NzbDrone.Common/HostController.cs @@ -0,0 +1,69 @@ +using System; +using System.Linq; +using NLog; +using Nancy.Bootstrapper; +using Nancy.Hosting.Self; + +namespace NzbDrone.Common +{ + public interface IHostController + { + bool ServerStarted { get; } + string AppUrl { get; } + void StartServer(); + void RestartServer(); + void StopServer(); + } + + public class HostController : IHostController + { + private readonly ConfigFileProvider _configFileProvider; + private readonly INancyBootstrapper _bootstrapper; + private readonly Logger _logger; + private NancyHost _host; + + + public bool ServerStarted { get; private set; } + + public HostController(ConfigFileProvider configFileProvider, INancyBootstrapper bootstrapper, Logger logger) + { + _configFileProvider = configFileProvider; + _bootstrapper = bootstrapper; + _logger = logger; + } + + public void StartServer() + { + _host = new NancyHost(new Uri(AppUrl), _bootstrapper); + } + + public string AppUrl + { + get { return string.Format("http://localhost:{0}/", _configFileProvider.Port); } + } + + + public void RestartServer() + { + + _logger.Warn("Attempting to restart server."); + + if (_host != null) + { + StopServer(); + } + + StartServer(); + } + + public void StopServer() + { + if (_host == null) return; + + _logger.Info("Attempting to stop Nancy host"); + _host.Stop(); + _host = null; + _logger.Info("Host has stopped"); + } + } +} \ No newline at end of file diff --git a/NzbDrone.Common/IISProvider.cs b/NzbDrone.Common/IISProvider.cs deleted file mode 100644 index f5af69d3b..000000000 --- a/NzbDrone.Common/IISProvider.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System.Linq; -using System; -using System.Diagnostics; -using NLog; - -namespace NzbDrone.Common -{ - public class IISProvider - { - private static readonly Logger IISLogger = LogManager.GetCurrentClassLogger(); - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - private readonly ConfigFileProvider _configFileProvider; - private readonly ProcessProvider _processProvider; - private readonly EnvironmentProvider _environmentProvider; - - public int IISProcessId { get; private set; } - - public bool ServerStarted { get; private set; } - - public void StartServer() - { - Logger.Info("Preparing IISExpress Server..."); - - var startInfo = new ProcessStartInfo(); - - startInfo.FileName = _environmentProvider.GetIISExe(); - startInfo.Arguments = String.Format("/config:\"{0}\" /trace:i", _environmentProvider.GetIISConfigPath()); - startInfo.WorkingDirectory = _environmentProvider.ApplicationPath; - - startInfo.UseShellExecute = false; - startInfo.RedirectStandardOutput = true; - startInfo.RedirectStandardError = true; - startInfo.CreateNoWindow = true; - - startInfo.EnvironmentVariables[EnvironmentProvider.NZBDRONE_PATH] = _environmentProvider.ApplicationPath; - startInfo.EnvironmentVariables[EnvironmentProvider.NZBDRONE_PID] = Process.GetCurrentProcess().Id.ToString(); - - try - { - _configFileProvider.UpdateIISConfig(_environmentProvider.GetIISConfigPath()); - } - catch (Exception e) - { - Logger.ErrorException("An error has occurred while trying to update the config file.", e); - } - - var iisProcess = _processProvider.Start(startInfo); - IISProcessId = iisProcess.Id; - - iisProcess.OutputDataReceived += (OnOutputDataReceived); - iisProcess.ErrorDataReceived += (OnErrorDataReceived); - - iisProcess.BeginErrorReadLine(); - iisProcess.BeginOutputReadLine(); - - ServerStarted = true; - - iisProcess.EnableRaisingEvents = true; - iisProcess.Exited += IIS_EXITED; - } - - public IISProvider(ConfigFileProvider configFileProvider, ProcessProvider processProvider, EnvironmentProvider environmentProvider) - { - _configFileProvider = configFileProvider; - _processProvider = processProvider; - _environmentProvider = environmentProvider; - } - - public IISProvider() - { - } - - public string AppUrl - { - get { return string.Format("http://localhost:{0}/", _configFileProvider.Port); } - } - - private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e) - { - if (e == null || String.IsNullOrWhiteSpace(e.Data)) - return; - - IISLogger.Error(e.Data); - } - - public void RestartServer() - { - ServerStarted = false; - Logger.Warn("Attempting to restart server."); - StopServer(); - StartServer(); - } - - public virtual void StopServer() - { - _processProvider.Kill(IISProcessId); - - Logger.Info("Finding orphaned IIS Processes."); - foreach (var process in _processProvider.GetProcessByName("IISExpress")) - { - Logger.Info("[{0}]IIS Process found. Path:{1}", process.Id, process.StartPath); - if (DiskProvider.PathEquals(process.StartPath, _environmentProvider.GetIISExe())) - { - Logger.Info("[{0}]Process is considered orphaned.", process.Id); - _processProvider.Kill(process.Id); - } - else - { - Logger.Info("[{0}]Process has a different start-up path. skipping.", process.Id); - } - } - } - - public void IIS_EXITED(object obj, EventArgs args) - { - RestartServer(); - } - private void OnOutputDataReceived(object s, DataReceivedEventArgs e) - { - if (e == null || String.IsNullOrWhiteSpace(e.Data) || e.Data.StartsWith("Request started:") || - e.Data.StartsWith("Request ended:") || e.Data == ("IncrementMessages called")) - return; - - Console.WriteLine(e.Data); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Common/NzbDrone.Common.csproj b/NzbDrone.Common/NzbDrone.Common.csproj index d2c18537d..a534c94dc 100644 --- a/NzbDrone.Common/NzbDrone.Common.csproj +++ b/NzbDrone.Common/NzbDrone.Common.csproj @@ -65,6 +65,12 @@ False ..\packages\Exceptron.Client.1.0.7\lib\net20\Exceptron.Client.dll + + ..\packages\Nancy.0.16.1\lib\net40\Nancy.dll + + + ..\packages\Nancy.Hosting.Self.0.16.1\lib\net40\Nancy.Hosting.Self.dll + False ..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll @@ -103,6 +109,7 @@ + @@ -110,7 +117,6 @@ - diff --git a/NzbDrone.Common/StringExtention.cs b/NzbDrone.Common/StringExtention.cs index 43780d4f5..e680f3082 100644 --- a/NzbDrone.Common/StringExtention.cs +++ b/NzbDrone.Common/StringExtention.cs @@ -1,7 +1,4 @@ - -using System.IO; - -namespace NzbDrone.Common +namespace NzbDrone.Common { public static class StringExtention { diff --git a/NzbDrone.Common/SysTray/SysTrayApp.cs b/NzbDrone.Common/SysTray/SysTrayApp.cs index d50ca2f71..0b0d844dc 100644 --- a/NzbDrone.Common/SysTray/SysTrayApp.cs +++ b/NzbDrone.Common/SysTray/SysTrayApp.cs @@ -10,18 +10,18 @@ namespace NzbDrone.Common.SysTray { private readonly ConfigFileProvider _configFileProvider; private readonly ProcessProvider _processProvider; - private readonly IISProvider _iisProvider; + private readonly HostController _hostController; private readonly EnvironmentProvider _environmentProvider; private readonly NotifyIcon _trayIcon = new NotifyIcon(); private readonly ContextMenu _trayMenu = new ContextMenu(); public SysTrayApp(ConfigFileProvider configFileProvider, ProcessProvider processProvider, - IISProvider iisProvider, EnvironmentProvider environmentProvider) + HostController hostController, EnvironmentProvider environmentProvider) { _configFileProvider = configFileProvider; _processProvider = processProvider; - _iisProvider = iisProvider; + _hostController = hostController; _environmentProvider = environmentProvider; } @@ -73,7 +73,7 @@ namespace NzbDrone.Common.SysTray private void LaunchBrowser(object sender, EventArgs e) { - _processProvider.Start(_iisProvider.AppUrl); + _processProvider.Start(_hostController.AppUrl); } } } \ No newline at end of file diff --git a/NzbDrone.Common/packages.config b/NzbDrone.Common/packages.config index 45acf1e6f..979bafbd0 100644 --- a/NzbDrone.Common/packages.config +++ b/NzbDrone.Common/packages.config @@ -2,6 +2,8 @@ + + \ No newline at end of file diff --git a/NzbDrone.Core.Test/CentralDispatchFixture.cs b/NzbDrone.Core.Test/CentralDispatchFixture.cs index f36a4884a..c71abf97b 100644 --- a/NzbDrone.Core.Test/CentralDispatchFixture.cs +++ b/NzbDrone.Core.Test/CentralDispatchFixture.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Autofac; using FluentAssertions; using NCrunch.Framework; @@ -15,15 +16,20 @@ using NzbDrone.Core.Test.Framework; namespace NzbDrone.Core.Test { + [Ignore] [TestFixture] [ExclusivelyUses("REAL_LOG_FILE")] [Serial] class CentralDispatchFixture : CoreTest { - readonly IList indexers = typeof(CentralDispatch).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(IndexerBase))).Select(c => c.ToString()).ToList(); - readonly IList jobs = typeof(CentralDispatch).Assembly.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IJob))).Select(c => c.ToString()).ToList(); - readonly IList extNotifications = typeof(CentralDispatch).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(ExternalNotificationBase))).ToList(); - readonly IList metadata = typeof(CentralDispatch).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(MetadataBase))).ToList(); + static readonly Assembly NzbDroneCore = Assembly.Load("NzbDrone.Core"); + + readonly IList indexers = NzbDroneCore.GetTypes().Where(t => t.IsSubclassOf(typeof(IndexerBase))).Select(c => c.ToString()).ToList(); + readonly IList jobs = NzbDroneCore.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IJob))).Select(c => c.ToString()).ToList(); + readonly IList extNotifications = NzbDroneCore.GetTypes().Where(t => t.IsSubclassOf(typeof(ExternalNotificationBase))).ToList(); + readonly IList metadata = NzbDroneCore.GetTypes().Where(t => t.IsSubclassOf(typeof(MetadataBase))).ToList(); + + private readonly IContainer kernel; @@ -35,10 +41,6 @@ namespace NzbDrone.Core.Test } InitLogging(); - var dispatch = new CentralDispatch(); - kernel = dispatch.BuildContainer(); - - WebTimer.Stop(); } [Test] @@ -50,7 +52,7 @@ namespace NzbDrone.Core.Test [Test] public void Resolve_all_providers() { - var providers = typeof(CentralDispatch).Assembly.GetTypes().Where(t => t.Name.EndsWith("Provider")).ToList(); + var providers = NzbDroneCore.GetTypes().Where(t => t.Name.EndsWith("Provider")).ToList(); providers.Should().NotBeEmpty(); diff --git a/NzbDrone.Core.Test/Integeration/ServiceIntegerationFixture.cs b/NzbDrone.Core.Test/Integeration/ServiceIntegerationFixture.cs deleted file mode 100644 index 81d2bd62b..000000000 --- a/NzbDrone.Core.Test/Integeration/ServiceIntegerationFixture.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Linq; -using Autofac; -using FluentAssertions; -using NLog; -using NUnit.Framework; -using NzbDrone.Common; -using NzbDrone.Core.Providers; -using NzbDrone.Core.Providers.Core; -using NzbDrone.Core.Repository; -using NzbDrone.Core.Test.Framework; -using PetaPoco; - -namespace NzbDrone.Core.Test.Integeration -{ - [TestFixture(Category = "ServiceIngeneration")] - public class ServiceIntegerationFixture : SqlCeTest - { - private IContainer _container; - - [SetUp] - public void Setup() - { - WithRealDb(); - var builder = new CentralDispatch().ContainerBuilder; - - builder.Register(c => Db) - .As(); - - builder.RegisterType().AsSelf(); - builder.RegisterType().AsSelf(); - builder.RegisterType().AsSelf(); - builder.RegisterType().AsSelf(); - - _container = builder.Build(); - - - - Mocker.GetMock().SetupGet(s => s.ServiceRootUrl) - .Returns("http://services.nzbdrone.com"); - } - - [Test] - public void should_be_able_to_update_scene_mapping() - { - _container.Resolve().UpdateMappings(); - var mappings = Db.Fetch(); - - mappings.Should().NotBeEmpty(); - - mappings.Should().OnlyContain(c => !string.IsNullOrWhiteSpace(c.CleanTitle)); - mappings.Should().OnlyContain(c => !string.IsNullOrWhiteSpace(c.SceneName)); - mappings.Should().OnlyContain(c => c.SeriesId > 0); - } - - [Test] - public void should_be_able_to_get_daily_series_ids() - { - var dailySeries = _container.Resolve().GetDailySeriesIds(); - - dailySeries.Should().NotBeEmpty(); - dailySeries.Should().OnlyContain(c => c > 0); - } - } -} \ No newline at end of file diff --git a/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj b/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj index 2cc3236d4..31612613b 100644 --- a/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj +++ b/NzbDrone.Core.Test/NzbDrone.Core.Test.csproj @@ -166,7 +166,6 @@ - diff --git a/NzbDrone.Core/CentralDispatch.cs b/NzbDrone.Core/CentralDispatch.cs deleted file mode 100644 index ddae141ab..000000000 --- a/NzbDrone.Core/CentralDispatch.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using Autofac; -using NLog; -using NzbDrone.Common; -using NzbDrone.Core.Instrumentation; -using NzbDrone.Core.Providers.Core; -using SignalR; - -namespace NzbDrone.Core -{ - public class CentralDispatch - { - private readonly Logger _logger; - private readonly EnvironmentProvider _environmentProvider; - - public ContainerBuilder ContainerBuilder { get; private set; } - - public CentralDispatch() - { - _logger = LogManager.GetCurrentClassLogger(); - _environmentProvider = new EnvironmentProvider(); - - _logger.Debug("Initializing ContainerBuilder:"); - ContainerBuilder = new ContainerBuilder(); - - } - - private void RegisterReporting(IComponentContext container) - { - EnvironmentProvider.UGuid = container.Resolve().UGuid; - ReportingService.RestProvider = container.Resolve(); - ReportingService.SetupExceptronDriver(); - } - - - public void DedicateToHost() - { - try - { - var pid = _environmentProvider.NzbDroneProcessIdFromEnviroment; - - _logger.Debug("Attaching to parent process ({0}) for automatic termination.", pid); - - var hostProcess = Process.GetProcessById(Convert.ToInt32(pid)); - - hostProcess.EnableRaisingEvents = true; - hostProcess.Exited += (delegate - { - _logger.Info("Host has been terminated. Shutting down web server."); - ShutDown(); - }); - - _logger.Debug("Successfully Attached to host. Process [{0}]", hostProcess.ProcessName); - } - catch (Exception e) - { - _logger.FatalException("An error has occurred while dedicating to host.", e); - } - } - - public IContainer BuildContainer() - { - _logger.Debug("Initializing Components"); - - ContainerBuilder.RegisterCoreServices(); - - var container = ContainerBuilder.Build(); - - container.Resolve().Register(); - LogConfiguration.Reload(); - - RegisterReporting(container); - - container.Resolve().StartTimer(30); - - //SignalR - GlobalHost.DependencyResolver = new AutofacSignalrDependencyResolver(container.BeginLifetimeScope("SignalR")); - - return container; - } - - private void ShutDown() - { - _logger.Info("Shutting down application..."); - WebTimer.Stop(); - Process.GetCurrentProcess().Kill(); - } - } -} diff --git a/NzbDrone.Core/Jobs/JobController.cs b/NzbDrone.Core/Jobs/JobController.cs index d77d53d88..9ff19e266 100644 --- a/NzbDrone.Core/Jobs/JobController.cs +++ b/NzbDrone.Core/Jobs/JobController.cs @@ -4,6 +4,7 @@ using System.Diagnostics; using System.Linq; using System.Threading; using NLog; +using NzbDrone.Core.Lifecycle; using NzbDrone.Core.Model; using NzbDrone.Core.Model.Notification; using NzbDrone.Core.Providers; @@ -19,12 +20,13 @@ namespace NzbDrone.Core.Jobs bool QueueJob(string jobTypeString); } - public class JobController : IJobController + public class JobController : IJobController, IInitializable { private readonly NotificationProvider _notificationProvider; private readonly IEnumerable _jobs; private readonly IJobRepository _jobRepository; - private readonly Logger logger; + private readonly Logger _logger; + private Timer _timer; private Thread _jobThread; public Stopwatch StopWatch { get; private set; } @@ -41,10 +43,16 @@ namespace NzbDrone.Core.Jobs _notificationProvider = notificationProvider; _jobs = jobs; _jobRepository = jobRepository; - this.logger = logger; + _logger = logger; ResetThread(); } + public void Init() + { + _timer = new Timer(c => QueueScheduled()); + _timer.Change(0, 60 * 1000); + } + public List Queue { get @@ -62,7 +70,7 @@ namespace NzbDrone.Core.Jobs if (_jobThread.IsAlive) { - logger.Trace("Queue is already running. Ignoring scheduler's request."); + _logger.Trace("Queue is already running. Ignoring scheduler's request."); return; } } @@ -73,7 +81,7 @@ namespace NzbDrone.Core.Jobs pendingJobs.ForEach(jobType => QueueJob(jobType, source: JobQueueItem.JobSourceType.Scheduler)); - logger.Trace("{0} Scheduled tasks have been added to the queue", pendingJobs.Count); + _logger.Trace("{0} Scheduled tasks have been added to the queue", pendingJobs.Count); } public virtual void QueueJob(Type jobType, dynamic options = null, JobQueueItem.JobSourceType source = JobQueueItem.JobSourceType.User) @@ -85,7 +93,7 @@ namespace NzbDrone.Core.Jobs Source = source }; - logger.Debug("Attempting to queue {0}", queueItem); + _logger.Debug("Attempting to queue {0}", queueItem); lock (_executionLock) { @@ -96,17 +104,17 @@ namespace NzbDrone.Core.Jobs if (!Queue.Contains(queueItem)) { Queue.Add(queueItem); - logger.Trace("Job {0} added to the queue. current items in queue: {1}", queueItem, Queue.Count); + _logger.Trace("Job {0} added to the queue. current items in queue: {1}", queueItem, Queue.Count); } else { - logger.Info("{0} already exists in the queue. Skipping. current items in queue: {1}", queueItem, Queue.Count); + _logger.Info("{0} already exists in the queue. Skipping. current items in queue: {1}", queueItem, Queue.Count); } } if (_jobThread.IsAlive) { - logger.Trace("Queue is already running. No need to start it up."); + _logger.Trace("Queue is already running. No need to start it up."); return; } @@ -145,7 +153,7 @@ namespace NzbDrone.Core.Jobs if (Queue.Count != 0) { job = Queue.OrderBy(c => c.Source).First(); - logger.Trace("Popping {0} from the queue.", job); + _logger.Trace("Popping {0} from the queue.", job); Queue.Remove(job); } } @@ -161,7 +169,7 @@ namespace NzbDrone.Core.Jobs } catch (Exception e) { - logger.FatalException("An error has occurred while executing job.", e); + _logger.FatalException("An error has occurred while executing job.", e); } } @@ -169,16 +177,16 @@ namespace NzbDrone.Core.Jobs } catch (ThreadAbortException e) { - logger.Warn(e.Message); + _logger.Warn(e.Message); } catch (Exception e) { - logger.ErrorException("Error has occurred in queue processor thread", e); + _logger.ErrorException("Error has occurred in queue processor thread", e); } finally { StopWatch.Stop(); - logger.Trace("Finished processing jobs in the queue."); + _logger.Trace("Finished processing jobs in the queue."); } } @@ -187,7 +195,7 @@ namespace NzbDrone.Core.Jobs var jobImplementation = _jobs.SingleOrDefault(t => t.GetType() == queueItem.JobType); if (jobImplementation == null) { - logger.Error("Unable to locate implementation for '{0}'. Make sure it is properly registered.", queueItem.JobType); + _logger.Error("Unable to locate implementation for '{0}'. Make sure it is properly registered.", queueItem.JobType); return; } @@ -196,7 +204,7 @@ namespace NzbDrone.Core.Jobs { try { - logger.Debug("Starting {0}. Last execution {1}", queueItem, jobDefinition.LastExecution); + _logger.Debug("Starting {0}. Last execution {1}", queueItem, jobDefinition.LastExecution); var sw = Stopwatch.StartNew(); @@ -208,7 +216,7 @@ namespace NzbDrone.Core.Jobs jobDefinition.Success = true; sw.Stop(); - logger.Debug("Job {0} successfully completed in {1:0}.{2} seconds.", queueItem, sw.Elapsed.TotalSeconds, sw.Elapsed.Milliseconds / 100, + _logger.Debug("Job {0} successfully completed in {1:0}.{2} seconds.", queueItem, sw.Elapsed.TotalSeconds, sw.Elapsed.Milliseconds / 100, sw.Elapsed.Seconds); } catch (ThreadAbortException) @@ -217,7 +225,7 @@ namespace NzbDrone.Core.Jobs } catch (Exception e) { - logger.ErrorException("An error has occurred while executing job [" + jobImplementation.Name + "].", e); + _logger.ErrorException("An error has occurred while executing job [" + jobImplementation.Name + "].", e); _notification.Status = ProgressNotificationStatus.Failed; _notification.CurrentMessage = jobImplementation.Name + " Failed."; @@ -237,7 +245,7 @@ namespace NzbDrone.Core.Jobs { if (StopWatch.Elapsed.TotalHours > 1) { - logger.Warn("Thread job has been running for more than an hour. fuck it!"); + _logger.Warn("Thread job has been running for more than an hour. fuck it!"); ResetThread(); } } @@ -249,8 +257,10 @@ namespace NzbDrone.Core.Jobs _jobThread.Abort(); } - logger.Trace("resetting queue processor thread"); + _logger.Trace("resetting queue processor thread"); _jobThread = new Thread(ProcessQueue) { Name = "JobQueueThread" }; } + + } } \ No newline at end of file diff --git a/NzbDrone.Core/Lifecycle/AppRestartJob.cs b/NzbDrone.Core/Lifecycle/AppRestartJob.cs index 24d460358..954946b9c 100644 --- a/NzbDrone.Core/Lifecycle/AppRestartJob.cs +++ b/NzbDrone.Core/Lifecycle/AppRestartJob.cs @@ -9,13 +9,13 @@ namespace NzbDrone.Core.Lifecycle { public class AppRestartJob : IJob { - private readonly IISProvider _iisProvider; + private readonly HostController _hostController; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); - public AppRestartJob(IISProvider iisProvider) + public AppRestartJob(HostController hostController) { - _iisProvider = iisProvider; + _hostController = hostController; } public string Name @@ -33,7 +33,7 @@ namespace NzbDrone.Core.Lifecycle notification.CurrentMessage = "Restarting NzbDrone"; logger.Info("Restarting NzbDrone"); - _iisProvider.StopServer(); + _hostController.StopServer(); } } } \ No newline at end of file diff --git a/NzbDrone.Core/NzbDrone.Core.csproj b/NzbDrone.Core/NzbDrone.Core.csproj index a85883f83..1d2ff5385 100644 --- a/NzbDrone.Core/NzbDrone.Core.csproj +++ b/NzbDrone.Core/NzbDrone.Core.csproj @@ -592,7 +592,6 @@ - @@ -609,7 +608,6 @@ - diff --git a/NzbDrone.Core/WebTimer.cs b/NzbDrone.Core/WebTimer.cs deleted file mode 100644 index 5dbf8d6d2..000000000 --- a/NzbDrone.Core/WebTimer.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Web; -using System.Web.Caching; -using NLog; -using NzbDrone.Core.Jobs; - -namespace NzbDrone.Core -{ - public class WebTimer - { - private readonly JobController _jobProvider; - - private static CacheItemRemovedCallback _onCacheRemove; - private static bool _stop; - - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - - - public WebTimer(JobController jobProvider) - { - _jobProvider = jobProvider; - } - - //TODO: Fix this so the timer doesn't keep running during unit tests. - public void StartTimer(int secondInterval) - { - _onCacheRemove = DoWork; - - HttpRuntime.Cache.Insert(GetType().ToString(), secondInterval, null, - DateTime.Now.AddSeconds(secondInterval), Cache.NoSlidingExpiration, - CacheItemPriority.NotRemovable, _onCacheRemove); - } - - - public void DoWork(string k, object v, CacheItemRemovedReason r) - { - if (!_stop) - { - _jobProvider.QueueScheduled(); - StartTimer(Convert.ToInt32(v)); - } - } - - public static void Stop() - { - Logger.Info("Stopping Web Timer"); - _stop = true; - } - } -} diff --git a/NzbDrone.Services/NzbDrone.Services.Service/Global.asax.cs b/NzbDrone.Services/NzbDrone.Services.Service/Global.asax.cs index 03ab8fefa..058165e72 100644 --- a/NzbDrone.Services/NzbDrone.Services.Service/Global.asax.cs +++ b/NzbDrone.Services/NzbDrone.Services.Service/Global.asax.cs @@ -45,7 +45,6 @@ namespace NzbDrone.Services.Service ModelBinders.Binders.DefaultBinder = new JsonModelBinder(); - InitContainer(); } // ReSharper disable InconsistentNaming @@ -72,7 +71,7 @@ namespace NzbDrone.Services.Service private void InitContainer() { - logger.Info("NzbDrone Starting up."); +/*/* logger.Info("NzbDrone Starting up."); var dispatch = new CentralDispatch(); @@ -81,9 +80,9 @@ namespace NzbDrone.Services.Service MVCRegistration(dispatch.ContainerBuilder); - var container = dispatch.ContainerBuilder.Build(); + var container = dispatch.ContainerBuilder.Build();#1# - DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); + DependencyResolver.SetResolver(new AutofacDependencyResolver(container));*/ } private static void MVCRegistration(ContainerBuilder builder) diff --git a/NzbDrone.Update.Test/UpdateProviderStartFixture.cs b/NzbDrone.Update.Test/UpdateProviderStartFixture.cs index a2fb25eda..d32b3c0e1 100644 --- a/NzbDrone.Update.Test/UpdateProviderStartFixture.cs +++ b/NzbDrone.Update.Test/UpdateProviderStartFixture.cs @@ -125,7 +125,7 @@ namespace NzbDrone.Update.Test Mocker.Resolve().Start(TARGET_FOLDER); //Assert - Mocker.GetMock().Verify(c => c.StopServer(), Times.Once()); + Mocker.GetMock().Verify(c => c.StopServer(), Times.Once()); } [Test] diff --git a/NzbDrone.Update/Providers/UpdateProvider.cs b/NzbDrone.Update/Providers/UpdateProvider.cs index cd781e0ea..7ff6ff3e1 100644 --- a/NzbDrone.Update/Providers/UpdateProvider.cs +++ b/NzbDrone.Update/Providers/UpdateProvider.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; using NLog; @@ -13,17 +12,17 @@ namespace NzbDrone.Update.Providers private readonly ServiceProvider _serviceProvider; private readonly ProcessProvider _processProvider; private readonly EnvironmentProvider _environmentProvider; - private readonly IISProvider _iisProvider; + private readonly HostController _hostController; private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public UpdateProvider(DiskProvider diskProvider, ServiceProvider serviceProvider, - ProcessProvider processProvider, EnvironmentProvider environmentProvider, IISProvider iisProvider) + ProcessProvider processProvider, EnvironmentProvider environmentProvider, HostController hostController) { _diskProvider = diskProvider; _serviceProvider = serviceProvider; _processProvider = processProvider; _environmentProvider = environmentProvider; - _iisProvider = iisProvider; + _hostController = hostController; } public UpdateProvider() @@ -80,7 +79,7 @@ namespace NzbDrone.Update.Providers } logger.Info("Killing all orphan IISExpress processes"); - _iisProvider.StopServer(); + _hostController.StopServer(); logger.Info("Creating backup of existing installation"); _diskProvider.CopyDirectory(targetFolder, _environmentProvider.GetUpdateBackUpFolder()); diff --git a/NzbDrone.Web.UI.Test/NzbDrone.Web.UI.Automation.csproj b/NzbDrone.Web.UI.Test/NzbDrone.Web.UI.Automation.csproj index 5cef9f400..260bb62b3 100644 --- a/NzbDrone.Web.UI.Test/NzbDrone.Web.UI.Automation.csproj +++ b/NzbDrone.Web.UI.Test/NzbDrone.Web.UI.Automation.csproj @@ -97,10 +97,6 @@ {F2BE0FDF-6E47-4827-A420-DD4EF82407F8} NzbDrone.Common - - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD} - NzbDrone.Web - {D12F7F2F-8A3C-415F-88FA-6DD061A84869} NzbDrone diff --git a/NzbDrone.sln b/NzbDrone.sln index 863d5920e..2c7300cc1 100644 --- a/NzbDrone.sln +++ b/NzbDrone.sln @@ -11,13 +11,10 @@ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone", "NzbDrone\NzbDrone.csproj", "{D12F7F2F-8A3C-415F-88FA-6DD061A84869}" ProjectSection(ProjectDependencies) = postProject {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205} = {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205} - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD} = {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Core", "NzbDrone.Core\NzbDrone.Core.csproj", "{FF5EE3B6-913B-47CE-9CEB-11C51B4E1205}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Web", "NzbDrone.Web\NzbDrone.Web.csproj", "{43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Core.Test", "NzbDrone.Core.Test\NzbDrone.Core.Test.csproj", "{193ADD3B-792B-4173-8E4C-5A3F8F0237F0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.App.Test", "NzbDrone.App.Test\NzbDrone.App.Test.csproj", "{C0EA1A40-91AD-4EEB-BD16-2DDDEBD20AE5}" @@ -34,8 +31,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Common.Test", "Nzb EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Test.Common", "NzbDrone.Test.Common\NzbDrone.Test.Common.csproj", "{CADDFCE0-7509-4430-8364-2074E1EEFCA2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NzbDrone.Web.UI.Automation", "NzbDrone.Web.UI.Test\NzbDrone.Web.UI.Automation.csproj", "{3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceInstall", "ServiceHelpers\ServiceInstall\ServiceInstall.csproj", "{6BCE712F-846D-4846-9D1B-A66B858DA755}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServiceUninstall", "ServiceHelpers\ServiceUninstall\ServiceUninstall.csproj", "{700D0B95-95CD-43F3-B6C9-FAA0FC1358D4}" @@ -124,26 +119,6 @@ Global {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205}.Services|x64.Build.0 = Release|x64 {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205}.Services|x86.ActiveCfg = Release|x86 {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205}.Services|x86.Build.0 = Release|x86 - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|x64.ActiveCfg = Debug|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|x86.ActiveCfg = Debug|x86 - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Debug|x86.Build.0 = Debug|x86 - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|Any CPU.Build.0 = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|x64.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|x86.ActiveCfg = Release|x86 - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Release|x86.Build.0 = Release|x86 - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|Any CPU.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|Any CPU.Build.0 = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|Mixed Platforms.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|Mixed Platforms.Build.0 = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|x64.ActiveCfg = Release|Any CPU - {43BD3BBD-1531-4D8F-9C08-E1CD544AB2CD}.Services|x86.ActiveCfg = Release|Any CPU {193ADD3B-792B-4173-8E4C-5A3F8F0237F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {193ADD3B-792B-4173-8E4C-5A3F8F0237F0}.Debug|Any CPU.Build.0 = Debug|Any CPU {193ADD3B-792B-4173-8E4C-5A3F8F0237F0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -298,24 +273,6 @@ Global {CADDFCE0-7509-4430-8364-2074E1EEFCA2}.Services|Mixed Platforms.Build.0 = Release|Any CPU {CADDFCE0-7509-4430-8364-2074E1EEFCA2}.Services|x64.ActiveCfg = Release|Any CPU {CADDFCE0-7509-4430-8364-2074E1EEFCA2}.Services|x86.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|x64.ActiveCfg = Debug|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Debug|x86.ActiveCfg = Debug|x86 - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|Any CPU.Build.0 = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|Mixed Platforms.Build.0 = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|x64.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Release|x86.ActiveCfg = Release|x86 - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|Any CPU.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|Any CPU.Build.0 = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|Mixed Platforms.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|Mixed Platforms.Build.0 = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|x64.ActiveCfg = Release|Any CPU - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E}.Services|x86.ActiveCfg = Release|Any CPU {6BCE712F-846D-4846-9D1B-A66B858DA755}.Debug|Any CPU.ActiveCfg = Debug|x86 {6BCE712F-846D-4846-9D1B-A66B858DA755}.Debug|Mixed Platforms.ActiveCfg = Debug|x86 {6BCE712F-846D-4846-9D1B-A66B858DA755}.Debug|Mixed Platforms.Build.0 = Debug|x86 @@ -509,7 +466,6 @@ Global {C0EA1A40-91AD-4EEB-BD16-2DDDEBD20AE5} = {57A04B72-8088-4F75-A582-1158CF8291F7} {35388E8E-0CDB-4A84-AD16-E4B6EFDA5D97} = {57A04B72-8088-4F75-A582-1158CF8291F7} {BEC74619-DDBB-4FBA-B517-D3E20AFC9997} = {57A04B72-8088-4F75-A582-1158CF8291F7} - {3CCD64E1-84DA-4853-B7EF-98B02FD4E39E} = {57A04B72-8088-4F75-A582-1158CF8291F7} {FAFB5948-A222-4CF6-AD14-026BE7564802} = {47697CDB-27B6-4B05-B4F8-0CBE6F6EDF97} {CADDFCE0-7509-4430-8364-2074E1EEFCA2} = {47697CDB-27B6-4B05-B4F8-0CBE6F6EDF97} {6BCE712F-846D-4846-9D1B-A66B858DA755} = {F9E67978-5CD6-4A5F-827B-4249711C0B02} diff --git a/NzbDrone.sln.DotSettings b/NzbDrone.sln.DotSettings index 1bbc6428e..38ec44874 100644 --- a/NzbDrone.sln.DotSettings +++ b/NzbDrone.sln.DotSettings @@ -1,5 +1,6 @@  ERROR + DO_NOT_SHOW DO_NOT_SHOW <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb"><ExtraRule Prefix="" Suffix="" Style="AaBb" /></Policy> BOTH_SIDES diff --git a/NzbDrone/ApplicationServer.cs b/NzbDrone/ApplicationServer.cs index cc24b6229..a7dd39d57 100644 --- a/NzbDrone/ApplicationServer.cs +++ b/NzbDrone/ApplicationServer.cs @@ -14,22 +14,20 @@ namespace NzbDrone private static readonly Logger logger = LogManager.GetCurrentClassLogger(); private readonly ConfigFileProvider _configFileProvider; - private readonly DebuggerProvider _debuggerProvider; private readonly EnvironmentProvider _environmentProvider; - private readonly IISProvider _iisProvider; + private readonly HostController _hostController; private readonly ProcessProvider _processProvider; private readonly MonitoringProvider _monitoringProvider; private readonly SecurityProvider _securityProvider; private readonly DiskProvider _diskProvider; - public ApplicationServer(ConfigFileProvider configFileProvider, IISProvider iisProvider, - DebuggerProvider debuggerProvider, EnvironmentProvider environmentProvider, + public ApplicationServer(ConfigFileProvider configFileProvider, HostController hostController, + EnvironmentProvider environmentProvider, ProcessProvider processProvider, MonitoringProvider monitoringProvider, SecurityProvider securityProvider, DiskProvider diskProvider) { _configFileProvider = configFileProvider; - _iisProvider = iisProvider; - _debuggerProvider = debuggerProvider; + _hostController = hostController; _environmentProvider = environmentProvider; _processProvider = processProvider; _monitoringProvider = monitoringProvider; @@ -49,7 +47,7 @@ namespace NzbDrone public virtual void Start() { - _iisProvider.StopServer(); + _hostController.StopServer(); _securityProvider.MakeAccessible(); if(_securityProvider.IsCurrentUserAdmin()) @@ -59,17 +57,16 @@ namespace NzbDrone _diskProvider.CreateDirectory(tempFiles); } - _iisProvider.StartServer(); + _hostController.StartServer(); //Todo: verify that IIS is actually started - _debuggerProvider.Attach(); if (_environmentProvider.IsUserInteractive && _configFileProvider.LaunchBrowser) { try { - logger.Info("Starting default browser. {0}", _iisProvider.AppUrl); - _processProvider.Start(_iisProvider.AppUrl); + logger.Info("Starting default browser. {0}", _hostController.AppUrl); + _processProvider.Start(_hostController.AppUrl); } catch (Exception e) { @@ -83,7 +80,7 @@ namespace NzbDrone protected override void OnStop() { logger.Info("Attempting to stop application."); - _iisProvider.StopServer(); + _hostController.StopServer(); logger.Info("Application has finished stop routine."); } } diff --git a/NzbDrone/CentralDispatch.cs b/NzbDrone/CentralDispatch.cs index 8545ef104..32bca4775 100644 --- a/NzbDrone/CentralDispatch.cs +++ b/NzbDrone/CentralDispatch.cs @@ -1,6 +1,9 @@ using Autofac; using NLog; +using Nancy.Bootstrapper; +using NzbDrone.Api; using NzbDrone.Common; +using NzbDrone.Core.Instrumentation; using NzbDrone.Providers; namespace NzbDrone @@ -31,12 +34,15 @@ namespace NzbDrone builder.RegisterAssemblyTypes(typeof(DiskProvider).Assembly).SingleInstance(); builder.RegisterType(); + builder.RegisterModule(); + + + builder.RegisterType().As().SingleInstance(); builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); - builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); - builder.RegisterType().SingleInstance(); + builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); builder.RegisterType().SingleInstance(); diff --git a/NzbDrone/NzbDrone.Console.csproj b/NzbDrone/NzbDrone.Console.csproj index 4c3aa6bd4..f389cc73f 100644 --- a/NzbDrone/NzbDrone.Console.csproj +++ b/NzbDrone/NzbDrone.Console.csproj @@ -106,8 +106,6 @@ - - @@ -151,6 +149,10 @@ {F2BE0FDF-6E47-4827-A420-DD4EF82407F8} NzbDrone.Common + + {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205} + NzbDrone.Core + diff --git a/NzbDrone/NzbDrone.csproj b/NzbDrone/NzbDrone.csproj index e0d7bed31..21b7fbe94 100644 --- a/NzbDrone/NzbDrone.csproj +++ b/NzbDrone/NzbDrone.csproj @@ -104,8 +104,6 @@ - - @@ -149,6 +147,10 @@ {F2BE0FDF-6E47-4827-A420-DD4EF82407F8} NzbDrone.Common + + {FF5EE3B6-913B-47CE-9CEB-11C51B4E1205} + NzbDrone.Core + diff --git a/NzbDrone/ProcessAttacher.cs b/NzbDrone/ProcessAttacher.cs deleted file mode 100644 index c673ac85b..000000000 --- a/NzbDrone/ProcessAttacher.cs +++ /dev/null @@ -1,167 +0,0 @@ -/* SOURCE: http://lazy.codeplex.com/ - * File: http://lazy.codeplex.com/SourceControl/changeset/view/55373#307770 - * Author: pablito900 - * Licence: GNU General Public License version 2 (GPLv2) - */ - -#if DEBUG -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.InteropServices; -using EnvDTE80; -using Process = EnvDTE.Process; -using Thread = System.Threading.Thread; - -namespace NzbDrone -{ - [DebuggerStepThrough] - public class ProcessAttacher - { - public static void Attach() - { - DTE2 dte2; - - try - { - dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.10.0"); - } - catch (Exception e) - { - dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.11.0"); - } - - - var pa = new ProcessAttacher(dte2, "iisexpress", 10); - pa.PessimisticAttachManaged(); - - // Get an instance of the currently running Visual Studio IDE. - } - - #region private - - private readonly Dictionary _attachTypesMap; - private readonly DTE2 _dte; - private readonly string _processName; - private readonly int _waitTimeout; - - #endregion - - #region ctor - - private ProcessAttacher(DTE2 dte, string processName, int waitTimeout) - { - _processName = processName; - _waitTimeout = waitTimeout; - _dte = dte; - _attachTypesMap = new Dictionary - { - {AttachType.Managed, "Managed"} - }; - } - - #endregion - - #region private methods - - private AttachResult Attach(AttachType attachType) - { - string engine = _attachTypesMap[attachType]; - - if (IsBeingDebugged()) - { - return AttachResult.BeingDebugged; - } - - var dbg = _dte.Debugger as Debugger2; - var trans = dbg.Transports.Item("Default"); - - var eng = trans.Engines.Item(engine); - - Process2 proc = null; - - try - { - proc = dbg.GetProcesses(trans, "").Item(_processName) as Process2; - } - catch (Exception) - { - return AttachResult.NotRunning; - } - - proc.Attach2(eng); - - return AttachResult.Attached; - } - - private AttachResult PessimisticAttach(AttachType attachType) - { - var res = Attach(attachType); - - var timeout = DateTime.Now.AddSeconds(_waitTimeout); - - while (res == AttachResult.NotRunning && timeout > DateTime.Now) - { - res = Attach(attachType); - Thread.Sleep(100); - } - return res; - } - - private bool IsBeingDebugged() - { - if (_dte.Debugger.DebuggedProcesses != null) - { - foreach (Process process in _dte.Debugger.DebuggedProcesses) - { - if (process.Name.IndexOf(_processName) != -1) - { - return true; - } - } - } - - return false; - } - - #endregion - - #region public methods - - public void OptimisticAttachManaged() - { - Attach(AttachType.Managed); - } - - public void PessimisticAttachManaged() - { - PessimisticAttach(AttachType.Managed); - } - - #endregion - - #region Nested type: AttachResult - - private enum AttachResult - { - Attached, - NotRunning, - BeingDebugged - } - - #endregion - - #region Nested type: AttachType - - private enum AttachType - { - Managed, - Native, - ManagedAndNative - } - - #endregion - } -} - -#endif \ No newline at end of file diff --git a/NzbDrone/Providers/DebuggerProvider.cs b/NzbDrone/Providers/DebuggerProvider.cs deleted file mode 100644 index f95a5f43f..000000000 --- a/NzbDrone/Providers/DebuggerProvider.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Diagnostics; -using System.Threading; -using NLog; - -namespace NzbDrone.Providers -{ - [DebuggerStepThroughAttribute] - public class DebuggerProvider - { - private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); - - - public virtual void Attach() - { -#if DEBUG - if (Debugger.IsAttached) - { - Logger.Info("Trying to attach to debugger"); - - int count = 0; - - while (true) - { - try - { - ProcessAttacher.Attach(); - Logger.Info("Debugger Attached"); - return; - } - catch (Exception e) - { - count++; - if (count > 20) - { - Logger.WarnException("Unable to attach to debugger", e); - return; - } - - Thread.Sleep(100); - } - } - } -#endif - } - } -} \ No newline at end of file diff --git a/NzbDrone/Providers/MonitoringProvider.cs b/NzbDrone/Providers/MonitoringProvider.cs index ef2405665..ddb289231 100644 --- a/NzbDrone/Providers/MonitoringProvider.cs +++ b/NzbDrone/Providers/MonitoringProvider.cs @@ -5,7 +5,6 @@ using System.Runtime.Remoting; using System.Threading; using NLog; using NzbDrone.Common; -using NzbDrone.Common.Model; namespace NzbDrone.Providers { @@ -13,7 +12,7 @@ namespace NzbDrone.Providers { private static readonly Logger logger = LogManager.GetLogger("Host.MonitoringProvider"); - private readonly IISProvider _iisProvider; + private readonly HostController _hostController; private readonly ProcessProvider _processProvider; private readonly HttpProvider _httpProvider; private readonly ConfigFileProvider _configFileProvider; @@ -22,11 +21,11 @@ namespace NzbDrone.Providers private Timer _pingTimer; private Timer _processPriorityCheckTimer; - public MonitoringProvider(ProcessProvider processProvider, IISProvider iisProvider, + public MonitoringProvider(ProcessProvider processProvider, HostController hostController, HttpProvider httpProvider, ConfigFileProvider configFileProvider) { _processProvider = processProvider; - _iisProvider = iisProvider; + _hostController = hostController; _httpProvider = httpProvider; _configFileProvider = configFileProvider; } @@ -59,7 +58,7 @@ namespace NzbDrone.Providers _processProvider.SetPriority(currentProcess.Id, ProcessPriorityClass.Normal); } - var iisProcess = _processProvider.GetProcessById(_iisProvider.IISProcessId); + var iisProcess = _processProvider.GetProcessById(_processProvider.GetCurrentProcess().Id); if (iisProcess != null && iisProcess.Priority != ProcessPriorityClass.Normal && iisProcess.Priority != ProcessPriorityClass.AboveNormal) { @@ -74,13 +73,13 @@ namespace NzbDrone.Providers public virtual void PingServer(object sender) { - if (!_iisProvider.ServerStarted) return; + if (!_hostController.ServerStarted) return; try { ICredentials identity = CredentialCache.DefaultCredentials; - _httpProvider.DownloadString(_iisProvider.AppUrl, identity); //This should preload the home page, making the first load faster. - string response = _httpProvider.DownloadString(_iisProvider.AppUrl + "/health", identity); + _httpProvider.DownloadString(_hostController.AppUrl, identity); //This should preload the home page, making the first load faster. + string response = _httpProvider.DownloadString(_hostController.AppUrl + "/health", identity); if (!response.Contains("OK")) { @@ -101,14 +100,14 @@ namespace NzbDrone.Providers if (_pingFailCounter >= 10) { _pingFailCounter = 0; - _iisProvider.RestartServer(); + _hostController.RestartServer(); } } } private void ProgramExited(object sender, EventArgs e) { - _iisProvider.StopServer(); + _hostController.StopServer(); } public static void AppDomainException(Exception excepion) diff --git a/NzbDrone/Router.cs b/NzbDrone/Router.cs index e6e1f8fd4..e25c0ae3e 100644 --- a/NzbDrone/Router.cs +++ b/NzbDrone/Router.cs @@ -51,7 +51,7 @@ namespace NzbDrone case ApplicationMode.Nancy: { - var nancyHost = new NancyHost(new Uri("http://localhost:8282"), new Bootstrapper()); + var nancyHost = new NancyHost(new Uri("http://localhost:8282"), new NancyBootstrapper()); nancyHost.Start();