Testing halfway backend pdf conversion

This commit is contained in:
Rick Falkvinge
2017-10-01 13:54:04 +02:00
parent d0d2f48f56
commit 204865c890
6 changed files with 307 additions and 214 deletions
@@ -6,6 +6,8 @@ using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Swarmops.Logic;
using Swarmops.Logic.Security;
using Swarmops.Logic.Support;
using Swarmops.Utility.BotCode;
using WebSocketSharp;
using WebSocketSharp.Server;
@@ -45,6 +47,10 @@ namespace Swarmops.Backend.SocketServices
case "Metapackage":
BackendLoop.ProcessMetapackage(SocketMessage.FromXml((string) json["XmlData"]));
break;
case "ConvertPdf":
// Convert with high quality -- done on backend with lower priority than the immediate frontend conversion
PdfProcessor.Rerasterize(Document.FromIdentity((int) json["documentId"]), PdfProcessor.PdfProcessorOptions.HighQuality);
break;
default:
// do nothing;
break;
+5
View File
@@ -424,6 +424,11 @@ namespace Swarmops.Frontend.Socket
_backendSocket.Send(json.ToString());
}
public static void SendMessageUpstream(JObject message)
{
_backendSocket.Send(message.ToString());
}
private static Dictionary<FrontendMalfunctions,bool> _activeAlarms;
+198
View File
@@ -1,13 +1,19 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Swarmops.Frontend.Socket;
using Swarmops.Logic;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Security;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using WebSocketSharp;
using WebSocketSharp.Server;
@@ -47,6 +53,18 @@ namespace Swarmops.Frontend.Socket
// TODO: Request heartbeat from backend
// Sessions.Broadcast("{\"messageType\":\"Heartbeat\"}");
break;
case "ConvertPdf":
JArray pdfFilesArray = (JArray) json["PdfFiles"];
List<string> pdfFilesList = new List<string>();
foreach (string pdfFileString in pdfFilesArray)
{
pdfFilesList.Add(pdfFileString);
}
string[] pdfFiles = pdfFilesList.ToArray();
ConvertPdf (pdfFiles, (string) json["Guid"], Person.FromIdentity((int) json["PersonId"]));
break;
default:
// do nothing;
break;
@@ -54,6 +72,7 @@ namespace Swarmops.Frontend.Socket
}
private void ProcessMetapackage(string xmlData)
{
Console.WriteLine("Decoding XML: " + xmlData);
@@ -108,8 +127,187 @@ namespace Swarmops.Frontend.Socket
// Sessions.Broadcast("{\"messageType\":\"EditorCount\"," + String.Format("\"editorCount\":\"{0}\"", Sessions.ActiveIDs.ToArray().Length) + '}');
}
private void ConvertPdf(string[] pdfFiles, string guid, Person person)
{
List<string> failedConversionFileNames = new List<string>();
using (StreamWriter debugWriter = new StreamWriter("/tmp/PdfConversionDebug-" + guid + ".txt"))
{
try
{
debugWriter.WriteLine("ConvertPdf started");
int fileCount = pdfFiles.Length;
int successCount = 0;
int failCount = 0;
Process process = null;
Document lastDocument = null;
for (int fileIndex = 0; fileIndex < fileCount; fileIndex++)
{
// Set progress to indicate we're at file 'index' of 'fileCount'
int progress = fileIndex * 99 / fileCount; // 99 at most -- 100 indicates complete
int progressMax = (fileIndex + 1) * 99 / fileCount - 1;
int progressFileStep = 99 / fileCount;
int currentFilePageCount = 0;
int currentFilePageStep = 0;
string relativeFileName = pdfFiles[fileIndex];
debugWriter.WriteLine("------------------------------------");
debugWriter.WriteLine("{3:D2}%, Converting PDF file {0} of {1}; {2}", fileIndex + 1, fileCount,
relativeFileName, progress);
// Use qpdf to determine the number of pages in the PDF
string pageCountFileName = "/tmp/pagecount-" + guid + ".txt";
process = Process.Start("bash",
"-c \"qpdf --show-npages " + Document.StorageRoot + relativeFileName + " > " + pageCountFileName + "\"");
process.WaitForExit();
if (process.ExitCode != 0)
{
// Bad PDF file
failCount++;
failedConversionFileNames.Add(
((string[])GuidCache.Get("PdfClientNames-" + guid))[fileIndex].Replace("'", "")
.Replace("\"", "")); // caution; we're displaying user input, guard against XSS
continue;
}
// Read the resulting page count from the file we piped
using (StreamReader pageCountReader = new StreamReader(pageCountFileName))
{
string pageCountString = pageCountReader.ReadToEnd().Trim();
debugWriter.WriteLine("{0:D2}%, page count is '{1}'", progress, pageCountString);
currentFilePageCount = Int32.Parse(pageCountString);
debugWriter.WriteLine("{0:D2}%, parsed to int as {1}", progress, currentFilePageCount);
currentFilePageStep = progressFileStep / currentFilePageCount;
}
File.Delete(pageCountFileName);
// Begin the conversion
debugWriter.WriteLine("{0:D2}%, deleted page count file, starting conversion process", progress);
// Density 75 means 75dpi means conversion
// Hires 600dpi conversion is also made, but from backend after this conversion
process = Process.Start("bash",
"-c \"convert -density 75 -background white -flatten " + Document.StorageRoot + relativeFileName +
" " +
Document.StorageRoot + relativeFileName +
"-%04d.png > /tmp/PdfConversionOutput-" + guid + "\"");
int pageCounter = 0; // the first produced page will be zero
int currentPageBaseProgress = progressFileStep * fileIndex + currentFilePageStep * pageCounter;
int quarterSecondWaiting = 0;
string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
string lastPageFileName = testPageFileName;
while (pageCounter < currentFilePageCount)
{
while (!File.Exists(Document.StorageRoot + testPageFileName))
{
// Wait for file to appear
quarterSecondWaiting++;
progress = currentPageBaseProgress +
Math.Min(quarterSecondWaiting, 50) * currentFilePageStep / 2 / 50; // advance to 1/2 page over 5s while waiting
debugWriter.WriteLine("{0:D2}%, {2:O}, waiting for page #{1} to appear", progress, pageCounter + 1, DateTime.UtcNow);
debugWriter.Flush();
GuidCache.Set("Pdf-" + guid + "-Progress", progress);
process.WaitForExit(250); // this is a more elaborate version of thread.sleep that prevents Apache recycling
if (process.HasExited)
{
debugWriter.WriteLine("{0:D2}%, PROCESS HAS EXITED out of order with conversion", progress);
break;
}
}
currentPageBaseProgress = progressFileStep * fileIndex + currentFilePageStep * (pageCounter + 1);
progress = currentPageBaseProgress;
quarterSecondWaiting = 0;
if (progress > 99)
{
progress = 99; // can't reach 100 before finished
}
debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter + 1);
GuidCache.Set("Pdf-" + guid + "-Progress", progress);
// If the page# file that has appeared is 1+, then the preceding file is ready
if (pageCounter > 0)
{
long fileLength = new FileInfo(Document.StorageRoot + lastPageFileName).Length;
debugWriter.WriteLine("{0:D2}%, saving page #{1}, bytecount {2}", progress, pageCounter, fileLength);
Document.Create(lastPageFileName,
"(BackendConvertedFile) " + pageCounter.ToString(CultureInfo.InvariantCulture),
fileLength, guid, null, person);
// Prepare to save the next file
lastPageFileName = testPageFileName;
}
// Increase the page counter and the file we're looking for
pageCounter++;
testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
}
// We've seen the last page being written -- wait for process to exit
debugWriter.WriteLine("{0:D2}%, waiting for process exit", progress);
process.WaitForExit();
// Save the last page
long fileLengthLastPage = new FileInfo(Document.StorageRoot + lastPageFileName).Length;
debugWriter.WriteLine("{0:D2}%, saving last page #{1}, bytecount {2}", progress, pageCounter, fileLengthLastPage);
lastDocument = Document.Create(lastPageFileName,
"(BackendConvertedFile) " + pageCounter.ToString(CultureInfo.InvariantCulture),
fileLengthLastPage, guid, null, person);
}
// TODO: notify backend to rerasterize doc at 600dpi
}
catch (Exception e)
{
debugWriter.WriteLine("Exception thrown: " + e.ToString());
throw;
}
finally
{
debugWriter.WriteLine("Thread exiting");
GuidCache.Set("Pdf-" + guid + "-Progress", 100);
// only here may the caller fetch the results
}
}
}
public Authority Authority { get { return this._authority; } }
private Authority _authority = null;
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ namespace Swarmops.Logic.Support
}
}
protected static string StorageRoot
public static string StorageRoot
{
get
{
+75 -209
View File
@@ -11,10 +11,12 @@ using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using Newtonsoft.Json.Linq;
using Swarmops.Logic.Cache;
using Swarmops.Logic.Structure;
using Swarmops.Logic.Support;
using Swarmops.Logic.Swarm;
using WebSocketSharp;
namespace Swarmops.Frontend.Automation
{
@@ -22,17 +24,7 @@ namespace Swarmops.Frontend.Automation
{
private readonly JavaScriptSerializer js = new JavaScriptSerializer();
public static string StorageRoot
{
get
{
if (Debugger.IsAttached)
{
return @"C:\Windows\Temp\Swarmops-Debug\"; // Windows debugging environment
}
return "/var/lib/swarmops/upload/"; // production location on Debian installation
}
}
public static string StorageRoot = Document.StorageRoot;
private bool WeAreInDebugEnvironment
{
@@ -261,6 +253,7 @@ namespace Swarmops.Frontend.Automation
int pageCounter = 0;
Process process = null;
bool pdfGeneratedHere = false;
if (WeAreInDebugEnvironment)
{
@@ -281,9 +274,59 @@ namespace Swarmops.Frontend.Automation
statuses.Add(errorStatus);
// -1 for length means the file was NOT saved, and that it could not be parsed.
return;
continue; // with next file
}
pdfGeneratedHere = true;
}
else // live environment, not debug
{
// Use qpdf to determine the number of pages in the PDF
string pageCountFileName = "/tmp/pagecount-" + guid + ".txt";
process = Process.Start("bash",
"-c \"qpdf --show-npages " + StorageRoot + relativeFileName + " > " + pageCountFileName + "\"");
process.WaitForExit();
int pdfPageCount = 0;
if (process.ExitCode != 0)
{
// Bad PDF file
FilesStatus errorStatus = new FilesStatus(fullName, -1); //file.ContentLength);
errorStatus.error = "ERR_BAD_PDF";
errorStatus.url = string.Empty;
errorStatus.delete_url = string.Empty;
errorStatus.thumbnail_url = string.Empty;
statuses.Add(errorStatus);
// -1 for length means the file was NOT saved, and that it could not be parsed.
continue;
}
// Read the resulting page count from the file we piped
using (StreamReader pageCountReader = new StreamReader(pageCountFileName))
{
string pageCountString = pageCountReader.ReadToEnd().Trim();
pdfPageCount = Int32.Parse(pageCountString);
}
File.Delete(pageCountFileName);
// TODO: If page count less than something, convert immediately
FilesStatus requiresConversion = new FilesStatus(fullName, -1);
requiresConversion.requiresPdfConversion = true;
statuses.Add(requiresConversion);
pdfsForConversion.Add(relativeFileName);
pdfClientNames.Add(file.FileName);
}
if (pdfGeneratedHere) // as opposed to deferred to backend for large files
{
string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
while (File.Exists(StorageRoot + testPageFileName))
@@ -298,15 +341,6 @@ namespace Swarmops.Frontend.Automation
testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
}
}
else
{
FilesStatus requiresConversion = new FilesStatus(fullName, -1);
requiresConversion.requiresPdfConversion = true;
statuses.Add(requiresConversion);
pdfsForConversion.Add(relativeFileName);
pdfClientNames.Add(file.FileName);
}
}
else
{
@@ -318,34 +352,37 @@ namespace Swarmops.Frontend.Automation
statuses.Add(new FilesStatus(fullName, file.ContentLength));
}
GuidCache.Set("PdfsForConversion-" + guid, pdfsForConversion.ToArray());
GuidCache.Set("PdfClientNames-" + guid, pdfClientNames.ToArray());
}
[WebMethod]
public static AjaxCallResult BeginPdfConversion(string guid)
{
AuthenticationData authData = GetAuthenticationDataAndCulture();
ProcessThreadArguments args = new ProcessThreadArguments
if (pdfsForConversion.Count > 0)
{
CurrentUser = authData.CurrentUser,
Organization = authData.CurrentOrganization,
Guid = guid
};
// Backend conversion of long files required
Thread initThread = new Thread(ConvertPdfThread);
initThread.Start(args);
using (
WebSocket socket =
new WebSocket("ws://localhost:" + SystemSettings.WebsocketPortFrontend + "/Front?Auth=" +
Uri.EscapeDataString(this.CurrentAuthority.ToEncryptedXml())))
{
socket.Connect();
return new AjaxCallResult {Success = true};
JObject data = new JObject();
data ["ServerRequest"] = "ConvertPdf";
data["PdfFiles"] = JArray.FromObject(pdfsForConversion.ToArray());
data["Guid"] = (string) guid;
data["PersonId"] = CurrentUser.Identity;
socket.Send(data.ToString());
socket.Ping(); // wait a little little while for send to work
socket.Close();
}
}
}
[WebMethod]
public static AjaxConversionCallResult GetPdfConversionResult (string guid)
{
return (AjaxConversionCallResult) GuidCache.Get("PdfConversionResult-" + guid);
}
public class AjaxConversionCallResult: AjaxCallResult
{
public int SuccessCount { get; set; }
@@ -356,177 +393,6 @@ namespace Swarmops.Frontend.Automation
private static void ConvertPdfThread(object args)
{
ProcessThreadArguments argsProper = (ProcessThreadArguments) args;
List<string> failedConversionFileNames = new List<string>();
using (StreamWriter debugWriter = new StreamWriter("/tmp/PdfConversionDebug-" + argsProper.Guid + ".txt"))
{
try
{
debugWriter.WriteLine("ConvertPdfThread started");
string[] relativeFileNames = (string[]) GuidCache.Get("PdfsForConversion-" + argsProper.Guid);
string[] clientFileNames = (string[]) GuidCache.Get("PdfClientNames-" + argsProper.Guid);
GuidCache.Delete("PdfsForConversion-" + argsProper.Guid);
GuidCache.Delete("PdfsClientNames-" + argsProper.Guid);
int fileCount = relativeFileNames.Length;
int successCount = 0;
int failCount = 0;
Process process = null;
for (int fileIndex = 0; fileIndex < fileCount; fileIndex++)
{
// Set progress to indicate we're at file 'index' of 'fileCount'
int progress = fileIndex*99/fileCount; // 99 at most -- 100 indicates complete
int progressMax = (fileIndex + 1)*99/fileCount - 1;
int progressFileStep = 99/fileCount;
int currentFilePageCount = 0;
int currentFilePageStep = 0;
string relativeFileName = relativeFileNames[fileIndex];
debugWriter.WriteLine("------------------------------------");
debugWriter.WriteLine("{3:D2}%, Converting PDF file {0} of {1}; {2}", fileIndex + 1, fileCount,
relativeFileName, progress);
// Use qpdf to determine the number of pages in the PDF
string pageCountFileName = "/tmp/pagecount-" + argsProper.Guid + ".txt";
process = Process.Start("bash",
"-c \"qpdf --show-npages " + StorageRoot + relativeFileName + " > " + pageCountFileName + "\"");
process.WaitForExit();
if (process.ExitCode != 0)
{
// Bad PDF file
failCount ++;
failedConversionFileNames.Add(
((string[]) GuidCache.Get("PdfClientNames-" + argsProper.Guid))[fileIndex].Replace("'", "")
.Replace("\"", "")); // caution; we're displaying user input, guard against XSS
continue;
}
// Read the resulting page count from the file we piped
using (StreamReader pageCountReader = new StreamReader(pageCountFileName))
{
string pageCountString = pageCountReader.ReadToEnd().Trim();
debugWriter.WriteLine("{0:D2}%, page count is '{1}'", progress, pageCountString);
currentFilePageCount = Int32.Parse(pageCountString);
debugWriter.WriteLine("{0:D2}%, parsed to int as {1}", progress, currentFilePageCount);
currentFilePageStep = progressFileStep/currentFilePageCount;
}
File.Delete(pageCountFileName);
// Begin the conversion
debugWriter.WriteLine("{0:D2}%, deleted page count file, starting conversion process", progress);
process = Process.Start("bash",
"-c \"convert -density 600 -background white -flatten " + StorageRoot + relativeFileName +
" " +
StorageRoot + relativeFileName +
"-%04d.png > /tmp/PdfConversionOutput-" + argsProper.Guid + "\""); // Density 600 means 600dpi means production-grade conversion
process.PriorityClass = ProcessPriorityClass.Idle; // play real nice now
int pageCounter = 0; // the first produced page will be zero
int currentPageBaseProgress = progressFileStep*fileIndex + currentFilePageStep*pageCounter;
int quarterSecondWaiting = 0;
string testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
string lastPageFileName = testPageFileName;
while (pageCounter < currentFilePageCount)
{
while (!File.Exists(StorageRoot + testPageFileName))
{
// Wait for file to appear
quarterSecondWaiting++;
progress = currentPageBaseProgress +
Math.Min(quarterSecondWaiting, 50)*currentFilePageStep/2/50; // advance to 1/2 page over 5s while waiting
debugWriter.WriteLine("{0:D2}%, {2:O}, waiting for page #{1} to appear", progress, pageCounter+1, DateTime.UtcNow);
debugWriter.Flush();
GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress);
process.WaitForExit(250); // this is a more elaborate version of thread.sleep that prevents Apache recycling
if (process.HasExited)
{
debugWriter.WriteLine("{0:D2}%, PROCESS HAS EXITED out of order with conversion", progress);
break;
}
}
currentPageBaseProgress = progressFileStep*fileIndex + currentFilePageStep*(pageCounter+1);
progress = currentPageBaseProgress;
quarterSecondWaiting = 0;
if (progress > 99)
{
progress = 99; // can't reach 100 before finished
}
debugWriter.WriteLine("{0:D2}%, found page #{1}", progress, pageCounter+1);
GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", progress);
// If the page# file that has appeared is 1+, then the preceding file is ready
if (pageCounter > 0)
{
long fileLength = new FileInfo(StorageRoot + lastPageFileName).Length;
debugWriter.WriteLine("{0:D2}%, saving page #{1}, bytecount {2}", progress, pageCounter, fileLength);
Document.Create(lastPageFileName,
clientFileNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture),
fileLength, argsProper.Guid, null, argsProper.CurrentUser);
// Prepare to save the next file
lastPageFileName = testPageFileName;
}
// Increase the page counter and the file we're looking for
pageCounter++;
testPageFileName = String.Format("{0}-{1:D4}.png", relativeFileName, pageCounter);
debugWriter.WriteLine("{0:D2}%, testPageFileName set to {1}", progress, testPageFileName);
}
// We've seen the last page being written -- wait for process to exit
debugWriter.WriteLine("{0:D2}%, waiting for process exit", progress);
process.WaitForExit();
// Save the last page
long fileLengthLastPage = new FileInfo(StorageRoot + lastPageFileName).Length;
debugWriter.WriteLine("{0:D2}%, saving last page #{1}, bytecount {2}", progress, pageCounter, fileLengthLastPage);
Document.Create(lastPageFileName,
clientFileNames[fileIndex] + " " + pageCounter.ToString(CultureInfo.InvariantCulture),
fileLengthLastPage, argsProper.Guid, null, argsProper.CurrentUser);
}
}
catch (Exception e)
{
debugWriter.WriteLine("Exception thrown: " + e.ToString());
throw;
}
finally
{
debugWriter.WriteLine("Thread exiting");
GuidCache.Set("Pdf-" + argsProper.Guid + "-Progress", 100);
// only here may the caller fetch the results
}
}
}
+22 -4
View File
@@ -2,8 +2,10 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Swarmops.Logic.Support;
@@ -12,7 +14,13 @@ namespace Swarmops.Utility.BotCode
{
public class PdfProcessor
{
private static readonly string StorageRoot = "/var/lib/swarmops/upload/";
private static readonly string StorageRoot = Document.StorageRoot;
public enum PdfProcessorOptions
{
None = 0,
HighQuality = 0x0001
};
public static void RerasterizeAll()
{
@@ -99,7 +107,7 @@ namespace Swarmops.Utility.BotCode
}
}
public static void Rerasterize(Document document)
public static void Rerasterize(Document document, PdfProcessorOptions options = PdfProcessorOptions.None)
{
if (document.Description.Length < 32)
{
@@ -122,14 +130,24 @@ namespace Swarmops.Utility.BotCode
throw new InvalidOperationException("Document is an orphan");
}
int density = 75;
string suffix = string.Empty;
if (((int) options & (int) PdfProcessorOptions.HighQuality) > 0)
{
density = 600;
suffix = "-hires"; // hires conversion uses different filename
}
string firstPart = document.ServerFileName.Substring(0, 64);
Console.Write("Regenerating document...");
Process process = Process.Start("bash",
"-c \"convert -density 600 -background white -flatten " + StorageRoot + firstPart + " " +
"-c \"convert -density " + density.ToString(CultureInfo.InvariantCulture) + " -background white -flatten " + StorageRoot + firstPart + " " +
StorageRoot + firstPart +
"-%04d.png\""); // Density 600 means 600dpi means production-grade conversion
"-%04d" + suffix + ".png\"");
process.WaitForExit();