2013-11-26 07:08:12 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
2013-11-26 02:46:12 +00:00
|
|
|
|
using NLog;
|
|
|
|
|
using NzbDrone.Common.Processes;
|
|
|
|
|
|
|
|
|
|
namespace NzbDrone.Host
|
|
|
|
|
{
|
|
|
|
|
public interface ISingleInstancePolicy
|
|
|
|
|
{
|
2013-11-26 07:08:12 +00:00
|
|
|
|
void PreventStartIfAlreadyRunning();
|
|
|
|
|
void KillAllOtherInstance();
|
2013-11-26 02:46:12 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public class SingleInstancePolicy : ISingleInstancePolicy
|
|
|
|
|
{
|
|
|
|
|
private readonly IProcessProvider _processProvider;
|
|
|
|
|
private readonly IBrowserService _browserService;
|
|
|
|
|
private readonly Logger _logger;
|
|
|
|
|
|
|
|
|
|
public SingleInstancePolicy(IProcessProvider processProvider, IBrowserService browserService, Logger logger)
|
|
|
|
|
{
|
|
|
|
|
_processProvider = processProvider;
|
|
|
|
|
_browserService = browserService;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
}
|
|
|
|
|
|
2013-11-26 07:08:12 +00:00
|
|
|
|
public void PreventStartIfAlreadyRunning()
|
2013-11-26 02:46:12 +00:00
|
|
|
|
{
|
|
|
|
|
if (IsAlreadyRunning())
|
|
|
|
|
{
|
|
|
|
|
_logger.Warn("Another instance of NzbDrone is already running.");
|
|
|
|
|
_browserService.LaunchWebUI();
|
|
|
|
|
throw new TerminateApplicationException("Another instance is already running");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-11-26 07:08:12 +00:00
|
|
|
|
public void KillAllOtherInstance()
|
|
|
|
|
{
|
|
|
|
|
foreach (var processId in GetOtherNzbDroneProcessIds())
|
|
|
|
|
{
|
|
|
|
|
_processProvider.Kill(processId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-11-26 02:46:12 +00:00
|
|
|
|
private bool IsAlreadyRunning()
|
2013-11-26 07:08:12 +00:00
|
|
|
|
{
|
|
|
|
|
return GetOtherNzbDroneProcessIds().Any();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private List<int> GetOtherNzbDroneProcessIds()
|
2013-11-26 02:46:12 +00:00
|
|
|
|
{
|
|
|
|
|
var currentId = _processProvider.GetCurrentProcess().Id;
|
2013-11-26 07:08:12 +00:00
|
|
|
|
var consoleIds = _processProvider.FindProcessByName(ProcessProvider.NZB_DRONE_CONSOLE_PROCESS_NAME)
|
|
|
|
|
.Select(c => c.Id);
|
|
|
|
|
var winformIds = _processProvider.FindProcessByName(ProcessProvider.NZB_DRONE_PROCESS_NAME).Select(c => c.Id);
|
2013-11-26 02:46:12 +00:00
|
|
|
|
|
2013-11-26 07:08:12 +00:00
|
|
|
|
var otherProcesses = consoleIds.Union(winformIds).Except(new[] { currentId }).ToList();
|
2013-11-26 02:46:12 +00:00
|
|
|
|
|
2013-11-26 07:08:12 +00:00
|
|
|
|
if (otherProcesses.Any())
|
|
|
|
|
{
|
|
|
|
|
_logger.Info("{0} instance(s) of NzbDrone are running", otherProcesses.Count);
|
|
|
|
|
}
|
2013-11-26 02:46:12 +00:00
|
|
|
|
|
2013-11-26 07:08:12 +00:00
|
|
|
|
return otherProcesses;
|
|
|
|
|
}
|
2013-11-26 02:46:12 +00:00
|
|
|
|
}
|
|
|
|
|
}
|