Skip to content
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

global mutex for XML serialization & deserialization #1264

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions src/chocolatey/chocolatey.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
<Compile Include="infrastructure.app\services\FileTypeDetectorService.cs" />
<Compile Include="infrastructure.app\services\IFileTypeDetectorService.cs" />
<Compile Include="infrastructure.app\utility\ArgumentsUtility.cs" />
<Compile Include="infrastructure\guards\SingleGlobalMutex.cs" />
<Compile Include="infrastructure\logging\TraceLog.cs" />
<Compile Include="infrastructure\registration\SecurityProtocol.cs" />
<Compile Include="infrastructure\results\PowerShellExecutionResults.cs" />
Expand Down
78 changes: 78 additions & 0 deletions src/chocolatey/infrastructure/guards/SingleGlobalMutex.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright © 2017 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace chocolatey.infrastructure.guards
ferventcoder marked this conversation as resolved.
Show resolved Hide resolved
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;

class SingleGlobalMutex : IDisposable
ferventcoder marked this conversation as resolved.
Show resolved Hide resolved
{
public bool hasHandle = false;
Mutex mutex;
ferventcoder marked this conversation as resolved.
Show resolved Hide resolved

private void InitMutex()
{
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
mutex = new Mutex(false, mutexId);

var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
}

public SingleGlobalMutex(int timeOut)
{
InitMutex();
try
{
if (timeOut < 0)
hasHandle = mutex.WaitOne(Timeout.Infinite, false);
else
hasHandle = mutex.WaitOne(timeOut, false);
ferventcoder marked this conversation as resolved.
Show resolved Hide resolved

if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
}
catch (AbandonedMutexException)
{
hasHandle = true;
}
}


public void Dispose()
{
if (mutex != null)
{
if (hasHandle)
mutex.ReleaseMutex();
ferventcoder marked this conversation as resolved.
Show resolved Hide resolved
mutex.Dispose();
}
}
}


}
186 changes: 96 additions & 90 deletions src/chocolatey/infrastructure/services/XmlService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ namespace chocolatey.infrastructure.services
using cryptography;
using filesystem;
using tolerance;
using chocolatey.infrastructure.guards;

/// <summary>
/// XML interaction
Expand All @@ -41,110 +42,115 @@ public XmlService(IFileSystem fileSystem, IHashProvider hashProvider)

public XmlType deserialize<XmlType>(string xmlFilePath)
{
return FaultTolerance.try_catch_with_logging_exception(
() =>
{
var xmlSerializer = new XmlSerializer(typeof(XmlType));
using (var fileStream = _fileSystem.open_file_readonly(xmlFilePath))
using (var fileReader = new StreamReader(fileStream))
using (var xmlReader = XmlReader.Create(fileReader))
{
if (!xmlSerializer.CanDeserialize(xmlReader))
{
this.Log().Warn("Cannot deserialize response of type {0}", typeof(XmlType));
return default(XmlType);
}
using (new SingleGlobalMutex(1000))
{
return FaultTolerance.try_catch_with_logging_exception(
() =>
{
var xmlSerializer = new XmlSerializer(typeof(XmlType));
using (var fileStream = _fileSystem.open_file_readonly(xmlFilePath))
using (var fileReader = new StreamReader(fileStream))
using (var xmlReader = XmlReader.Create(fileReader))
{
if (!xmlSerializer.CanDeserialize(xmlReader))
{
this.Log().Warn("Cannot deserialize response of type {0}", typeof(XmlType));
return default(XmlType);
}

try
{
return (XmlType)xmlSerializer.Deserialize(xmlReader);
}
catch(InvalidOperationException ex)
{
// Check if its just a malformed document.
if (ex.Message.Contains("There is an error in XML document"))
{
// If so, check for a backup file and try an parse that.
if (_fileSystem.file_exists(xmlFilePath + ".backup"))
{
using (var backupStream = _fileSystem.open_file_readonly(xmlFilePath + ".backup"))
using (var backupReader = new StreamReader(backupStream))
using (var backupXmlReader = XmlReader.Create(backupReader))
{
var validConfig = (XmlType)xmlSerializer.Deserialize(backupXmlReader);
try
{
return (XmlType)xmlSerializer.Deserialize(xmlReader);
}
catch (InvalidOperationException ex)
{
// Check if its just a malformed document.
if (ex.Message.Contains("There is an error in XML document"))
{
// If so, check for a backup file and try an parse that.
if (_fileSystem.file_exists(xmlFilePath + ".backup"))
{
using (var backupStream = _fileSystem.open_file_readonly(xmlFilePath + ".backup"))
using (var backupReader = new StreamReader(backupStream))
using (var backupXmlReader = XmlReader.Create(backupReader))
{
var validConfig = (XmlType)xmlSerializer.Deserialize(backupXmlReader);

// If there's no errors and it's valid, go ahead and replace the bad file with the backup.
if(validConfig != null)
{
_fileSystem.copy_file(xmlFilePath + ".backup", xmlFilePath, overwriteExisting: true);
}
// If there's no errors and it's valid, go ahead and replace the bad file with the backup.
if (validConfig != null)
{
_fileSystem.copy_file(xmlFilePath + ".backup", xmlFilePath, overwriteExisting: true);
}

return validConfig;
}
}
}

throw;
}
}
},
"Error deserializing response of type {0}".format_with(typeof(XmlType)),
throwError: true);
return validConfig;
}
}
}

throw;
}
}
},
"Error deserializing response of type {0}".format_with(typeof(XmlType)),
throwError: true);
}
}

public void serialize<XmlType>(XmlType xmlType, string xmlFilePath)
{
serialize(xmlType,xmlFilePath, isSilent: false);
}

public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent)
{
_fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(xmlFilePath));
public void serialize<XmlType>(XmlType xmlType, string xmlFilePath, bool isSilent)
{
_fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(xmlFilePath));
using (new SingleGlobalMutex(1000))
{
FaultTolerance.try_catch_with_logging_exception(
() =>
{
var xmlSerializer = new XmlSerializer(typeof(XmlType));

FaultTolerance.try_catch_with_logging_exception(
() =>
{
var xmlSerializer = new XmlSerializer(typeof(XmlType));
// Write the updated file to memory
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)))
{
xmlSerializer.Serialize(streamWriter, xmlType);
streamWriter.Flush();

// Write the updated file to memory
using(var memoryStream = new MemoryStream())
using(var streamWriter = new StreamWriter(memoryStream, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)))
{
xmlSerializer.Serialize(streamWriter, xmlType);
streamWriter.Flush();
memoryStream.Position = 0;

memoryStream.Position = 0;

// Grab the hash of both files and compare them.
var originalFileHash = _hashProvider.hash_file(xmlFilePath);
if (!originalFileHash.is_equal_to(_hashProvider.hash_stream(memoryStream)))
{
// If there wasn't a file there in the first place, just write the new one out directly.
if(string.IsNullOrEmpty(originalFileHash))
{
using(var updateFileStream = _fileSystem.create_file(xmlFilePath))
{
memoryStream.Position = 0;
memoryStream.CopyTo(updateFileStream);
// Grab the hash of both files and compare them.
var originalFileHash = _hashProvider.hash_file(xmlFilePath);
if (!originalFileHash.is_equal_to(_hashProvider.hash_stream(memoryStream)))
{
// If there wasn't a file there in the first place, just write the new one out directly.
if (string.IsNullOrEmpty(originalFileHash))
{
using (var updateFileStream = _fileSystem.create_file(xmlFilePath))
{
memoryStream.Position = 0;
memoryStream.CopyTo(updateFileStream);

return;
}
}
return;
}
}

// Otherwise, create an update file, and resiliently move it into place.
var tempUpdateFile = xmlFilePath + ".update";
using(var updateFileStream = _fileSystem.create_file(tempUpdateFile))
{
memoryStream.Position = 0;
memoryStream.CopyTo(updateFileStream);
}
_fileSystem.replace_file(tempUpdateFile, xmlFilePath, xmlFilePath + ".backup");
}
}
},
"Error serializing type {0}".format_with(typeof(XmlType)),
throwError: true,
isSilent: isSilent);
}
// Otherwise, create an update file, and resiliently move it into place.
var tempUpdateFile = xmlFilePath + ".update";
using (var updateFileStream = _fileSystem.create_file(tempUpdateFile))
{
memoryStream.Position = 0;
memoryStream.CopyTo(updateFileStream);
}
_fileSystem.replace_file(tempUpdateFile, xmlFilePath, xmlFilePath + ".backup");
}
}
},
"Error serializing type {0}".format_with(typeof(XmlType)),
throwError: true,
isSilent: isSilent);
}
}
}
}