Files
LeafWeb/Web/Services/PiscalQueueManager.cs
T

105 lines
2.7 KiB
C#

using System;
using System.Linq;
using System.Threading;
using LeafWeb.Core.DAL;
using LeafWeb.Core.Entities;
using LeafWeb.Core.Remote;
using NLog;
namespace LeafWeb.Web.Services
{
public class PiscalQueueManager : IDisposable
{
private readonly DataService _dataService;
private readonly PiscalService _piscalService;
public PiscalQueueManager(DataService dataService, PiscalService piscalService)
{
_dataService = dataService;
_piscalService = piscalService;
}
public PiscalQueueManager() : this(new DataService(), new PiscalService()) {}
private static readonly object Lock = new object();
public void ProcessQueue()
{
var logger = LogManager.GetCurrentClassLogger();
if (Monitor.TryEnter(Lock))
{
logger.Trace("Process entered");
ProcessRunning(logger);
ProcessQueue(logger);
logger.Trace("Process completed");
Monitor.Exit(Lock);
}
else
{
logger.Trace("Process locked, queue already processing");
}
}
private void ProcessQueue(ILogger logger)
{
var runningLeafInputFiles = _dataService.GetLeafInputFiles(LeafInputStatusType.Running).ToList();
if (runningLeafInputFiles.Any())
return;
var queuedFile =
_dataService
.GetLeafInputFiles(LeafInputStatusType.Queued)
.OrderBy(l => l.Id)
.FirstOrDefault();
if (queuedFile == null)
return;
logger.Info("LeafInputFile: {0}, Start", queuedFile.Id);
_piscalService.RunLeafInputFile(queuedFile);
_dataService.SetLeafInputFileStatus(queuedFile, LeafInputStatusType.Running);
}
private void ProcessRunning(ILogger logger)
{
var runningLeafInputFiles = _dataService.GetLeafInputFiles(LeafInputStatusType.Running).ToList();
foreach (var file in runningLeafInputFiles)
{
var status = _piscalService.GetLeafInputFileStatus(file);
switch (status)
{
case PiscalStatus.Running:
logger.Debug("LeafInputFile: {0}, {1}", file.Id, status);
// continue running
break;
case PiscalStatus.Success:
logger.Info("LeafInputFile: {0}, {1}", file.Id, status);
// collect the leaf output
var leafOutputFiles = _piscalService.RetrieveLeafOutputFile(file).ToList();
foreach (var outputFile in leafOutputFiles)
{
_dataService.AddLeafOutputFile(outputFile);
}
logger.Info("LeafInputFile: {0}, output files: {1}", file.Id,
string.Join(", ", leafOutputFiles.Select(o => o.Filename)));
_dataService.SetLeafInputFileStatus(file, LeafInputStatusType.Complete);
break;
case PiscalStatus.Error:
logger.Error("LeafInputFile: {0}", file.Id);
_dataService.SetLeafInputFileStatus(file, LeafInputStatusType.Error);
break;
}
}
}
public void Dispose()
{
_dataService.Dispose();
}
}
}