code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Cloud.Storage.Shared.Logging { /// <remarks></remarks> public enum LogLevel { /// <summary> Message is intended for debugging </summary> Debug, /// <summary> Informatory message </summary> Info, /// <summary> The message is about potential problem in the system </summary> Warn, /// <summary> Some error has occured </summary> Error, /// <summary> Message is associated with the critical problem </summary> Fatal, /// <summary> /// Highest possible level /// </summary> Max = int.MaxValue, /// <summary> Smallest logging level</summary> Min = int.MinValue } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Logging/LogLevel.cs
C#
bsd
907
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Logging { /// <summary> /// Basic logging abstraction. /// </summary> public interface ILog { /// <summary> Writes the message to the logger </summary> /// <param name="level">The importance level</param> /// <param name="message">The actual message</param> void Log(LogLevel level, object message); /// <summary> /// Writes the exception and associated information /// to the logger /// </summary> /// <param name="level">The importance level</param> /// <param name="ex">The actual exception</param> /// <param name="message">Information related to the exception</param> void Log(LogLevel level, Exception ex, object message); /// <summary> /// Determines whether the messages of specified level are being logged down /// </summary> /// <param name="level">The level.</param> /// <returns> /// <c>true</c> if the specified level is logged; otherwise, <c>false</c>. /// </returns> bool IsEnabled(LogLevel level); } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Logging/ILog.cs
C#
bsd
1,351
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion namespace Lokad.Cloud.Storage.Shared.Logging { /// <remarks></remarks> public interface ILogProvider { /// <remarks></remarks> ILog Get(string key); } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Logging/ILogProvider.cs
C#
bsd
356
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { sealed class RetryStateWithCount : IRetryState { int _errorCount; readonly Action<Exception, int> _onRetry; readonly Predicate<int> _canRetry; public RetryStateWithCount(int retryCount, Action<Exception, int> onRetry) { _onRetry = onRetry; _canRetry = i => _errorCount <= retryCount; } public bool CanRetry(Exception ex) { _errorCount += 1; bool result = _canRetry(_errorCount); if (result) { _onRetry(ex, _errorCount - 1); } return result; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/RetryStateWithCount.cs
C#
bsd
900
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { interface IRetryState { bool CanRetry(Exception ex); } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/IRetryState.cs
C#
bsd
311
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> Fluent API for defining <see cref="Policies.ActionPolicy"/> /// that allows to handle exceptions. </summary> public static class ExceptionHandlerSyntax { /* Development notes * ================= * If a stateful policy is returned by the syntax, * it must be wrapped with the sync lock */ static void DoNothing2(Exception ex, int count) { } /// <summary> /// Builds <see cref="Policies.ActionPolicy"/> that will retry exception handling /// for a couple of times before giving up. /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="retryCount">The retry count.</param> /// <returns>reusable instance of policy</returns> public static ActionPolicy Retry(this Syntax<ExceptionHandler> syntax, int retryCount) { if(null == syntax) throw new ArgumentNullException("syntax"); Func<IRetryState> state = () => new RetryStateWithCount(retryCount, DoNothing2); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } /// <summary> /// Builds <see cref="Policies.ActionPolicy"/> that will retry exception handling /// for a couple of times before giving up. /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetry">The action to perform on retry (i.e.: write to log). /// First parameter is the exception and second one is its number in sequence. </param> /// <returns>reusable policy instance </returns> public static ActionPolicy Retry(this Syntax<ExceptionHandler> syntax, int retryCount, Action<Exception, int> onRetry) { if(null == syntax) throw new ArgumentNullException("syntax"); if(retryCount <= 0) throw new ArgumentOutOfRangeException("retryCount"); Func<IRetryState> state = () => new RetryStateWithCount(retryCount, onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } /// <summary> Builds <see cref="Policies.ActionPolicy"/> that will keep retrying forever </summary> /// <param name="syntax">The syntax to extend.</param> /// <param name="onRetry">The action to perform when the exception could be retried.</param> /// <returns> reusable instance of policy</returns> public static ActionPolicy RetryForever(this Syntax<ExceptionHandler> syntax, Action<Exception> onRetry) { if(null == syntax) throw new ArgumentNullException("syntax"); if(null == onRetry) throw new ArgumentNullException("onRetry"); var state = new RetryState(onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, () => state)); } /// <summary> <para>Builds the policy that will keep retrying as long as /// the exception could be handled by the <paramref name="syntax"/> being /// built and <paramref name="sleepDurations"/> is providing the sleep intervals. /// </para> /// </summary> /// <param name="syntax">The syntax.</param> /// <param name="sleepDurations">The sleep durations.</param> /// <param name="onRetry">The action to perform on retry (i.e.: write to log). /// First parameter is the exception and second one is the planned sleep duration. </param> /// <returns>new policy instance</returns> public static ActionPolicy WaitAndRetry(this Syntax<ExceptionHandler> syntax, IEnumerable<TimeSpan> sleepDurations, Action<Exception, TimeSpan> onRetry) { if(null == syntax) throw new ArgumentNullException("syntax"); if(null == onRetry) throw new ArgumentNullException("onRetry"); if(null == sleepDurations) throw new ArgumentNullException("sleepDurations"); Func<IRetryState> state = () => new RetryStateWithSleep(sleepDurations, onRetry); return new ActionPolicy(action => RetryPolicy.Implementation(action, syntax.Target, state)); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/ExceptionHandlerSyntax.cs
C#
bsd
4,660
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { sealed class RetryState : IRetryState { readonly Action<Exception> _onRetry; public RetryState(Action<Exception> onRetry) { _onRetry = onRetry; } bool IRetryState.CanRetry(Exception ex) { _onRetry(ex); return true; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/RetryState.cs
C#
bsd
572
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System.ComponentModel; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> /// Helper class for creating fluent APIs, that hides unused signatures. /// </summary> public abstract class Syntax { /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] public override string ToString() { return base.ToString(); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { return base.Equals(obj); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Creates the syntax for the specified target /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="inner">The inner.</param> /// <returns>new syntax instance</returns> public static Syntax<TTarget> For<TTarget>(TTarget inner) { return new Syntax<TTarget>(inner); } } /// <summary> /// Helper class for creating fluent APIs, that hides unused signatures. /// </summary> public sealed class Syntax<TTarget> : Syntax { readonly TTarget _inner; /// <summary> /// Initializes a new instance of the <see cref="Syntax{T}"/> class. /// </summary> /// <param name="inner">The underlying instance.</param> public Syntax(TTarget inner) { _inner = inner; } /// <summary> /// Gets the underlying object. /// </summary> /// <value>The underlying object.</value> [EditorBrowsable(EditorBrowsableState.Advanced)] public TTarget Target { get { return _inner; } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/Syntax.cs
C#
bsd
3,288
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> This delegate represents <em>catch</em> block.</summary> /// <param name="ex">Exception to handle.</param> /// <returns><em>true</em> if we can handle exception.</returns> public delegate bool ExceptionHandler(Exception ex); }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/ExceptionHandler.cs
C#
bsd
491
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Collections.Generic; using System.Threading; namespace Lokad.Cloud.Storage.Shared.Policies { sealed class RetryStateWithSleep : IRetryState { readonly IEnumerator<TimeSpan> _enumerator; readonly Action<Exception, TimeSpan> _onRetry; public RetryStateWithSleep(IEnumerable<TimeSpan> sleepDurations, Action<Exception, TimeSpan> onRetry) { _onRetry = onRetry; _enumerator = sleepDurations.GetEnumerator(); } public bool CanRetry(Exception ex) { if (_enumerator.MoveNext()) { var current = _enumerator.Current; _onRetry(ex, current); Thread.Sleep(current); return true; } return false; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/RetryStateWithSleep.cs
C#
bsd
1,024
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared.Policies { static class RetryPolicy { internal static void Implementation(Action action, ExceptionHandler canRetry, Func<IRetryState> stateBuilder) { var state = stateBuilder(); while (true) { try { action(); return; } catch (Exception ex) { if (!canRetry(ex)) { throw; } if (!state.CanRetry(ex)) { throw; } } } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/RetryPolicy.cs
C#
bsd
953
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.Diagnostics; namespace Lokad.Cloud.Storage.Shared.Policies { /// <summary> /// Policy that could be applied to delegates to /// augment their behavior (i.e. to retry on problems) /// </summary> [Serializable] public class ActionPolicy { readonly Action<Action> _policy; /// <summary> /// Initializes a new instance of the <see cref="ActionPolicy"/> class. /// </summary> /// <param name="policy">The policy.</param> public ActionPolicy(Action<Action> policy) { if (policy == null) throw new ArgumentNullException("policy"); _policy = policy; } /// <summary> /// Performs the specified action within the policy. /// </summary> /// <param name="action">The action to perform.</param> [DebuggerNonUserCode] public void Do(Action action) { _policy(action); } /// <summary> /// Performs the specified action within the policy and returns the result /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="action">The action to perform.</param> /// <returns>result returned by <paramref name="action"/></returns> [DebuggerNonUserCode] public TResult Get<TResult>(Func<TResult> action) { var result = default(TResult); _policy(() => { result = action(); }); return result; } /// <summary> /// Action policy that does not do anything /// </summary> public static readonly ActionPolicy Null = new ActionPolicy(action => action()); /// <summary> Starts building <see cref="ActionPolicy"/> /// that can handle exceptions, as determined by /// <paramref name="handler"/> </summary> /// <param name="handler">The exception handler.</param> /// <returns>syntax</returns> public static Syntax<ExceptionHandler> With(ExceptionHandler handler) { if (handler == null) throw new ArgumentNullException("handler"); return Syntax.For(handler); } /// <summary> Starts building <see cref="ActionPolicy"/> /// that can handle exceptions, as determined by /// <paramref name="doWeHandle"/> function</summary> /// <param name="doWeHandle"> function that returns <em>true</em> if we can hande the specified exception.</param> /// <returns>syntax</returns> public static Syntax<ExceptionHandler> From(Func<Exception, bool> doWeHandle) { if (doWeHandle == null) throw new ArgumentNullException("doWeHandle"); ExceptionHandler handler = exception => doWeHandle(exception); return Syntax.For(handler); } /// <summary> Starts building simple <see cref="ActionPolicy"/> /// that can handle <typeparamref name="TException"/> </summary> /// <typeparam name="TException">The type of the exception to handle.</typeparam> /// <returns>syntax</returns> public static Syntax<ExceptionHandler> Handle<TException>() where TException : Exception { return Syntax.For<ExceptionHandler>(ex => ex is TException); } /// <summary> Starts building simple <see cref="ActionPolicy"/> /// that can handle <typeparamref name="TEx1"/> or <typeparamref name="TEx1"/> /// </summary> /// <typeparam name="TEx1">The type of the exception to handle.</typeparam> /// <typeparam name="TEx2">The type of the exception to handle.</typeparam> /// <returns>syntax</returns> public static Syntax<ExceptionHandler> Handle<TEx1, TEx2>() where TEx1 : Exception where TEx2 : Exception { return Syntax.For<ExceptionHandler>(ex => (ex is TEx1) || (ex is TEx2)); } /// <summary> Starts building simple <see cref="ActionPolicy"/> /// that can handle <typeparamref name="TEx1"/> or <typeparamref name="TEx1"/> /// </summary> /// <typeparam name="TEx1">The first type of the exception to handle.</typeparam> /// <typeparam name="TEx2">The second of the exception to handle.</typeparam> /// <typeparam name="TEx3">The third of the exception to handle.</typeparam> /// <returns>syntax</returns> public static Syntax<ExceptionHandler> Handle<TEx1, TEx2, TEx3>() where TEx1 : Exception where TEx2 : Exception where TEx3 : Exception { return Syntax.For<ExceptionHandler>(ex => (ex is TEx1) || (ex is TEx2) || (ex is TEx3)); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/Policies/ActionPolicy.cs
C#
bsd
5,063
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; using System.IO; namespace Lokad.Cloud.Storage.Shared { /// <summary> /// Generic data serializer interface. /// </summary> public interface IDataSerializer { /// <summary>Serializes the object to the specified stream.</summary> /// <param name="instance">The instance.</param> /// <param name="destinationStream">The destination stream.</param> void Serialize(object instance, Stream destinationStream); /// <summary>Deserializes the object from specified source stream.</summary> /// <param name="sourceStream">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> object Deserialize(Stream sourceStream, Type type); } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/IDataSerializer.cs
C#
bsd
1,011
#region (c)2009-2011 Lokad - New BSD license // Company: http://www.lokad.com // This code is released under the terms of the new BSD licence #endregion using System; namespace Lokad.Cloud.Storage.Shared { /// <summary>Pretty format utils.</summary> public static class FormatUtil { static readonly string[] ByteOrders = new[] { "EB", "PB", "TB", "GB", "MB", "KB", "Bytes" }; static readonly long MaxScale; static FormatUtil() { MaxScale = (long)Math.Pow(1024, ByteOrders.Length - 1); } /// <summary> /// Formats the size in bytes to a pretty string. /// </summary> /// <param name="sizeInBytes">The size in bytes.</param> /// <returns></returns> public static string SizeInBytes(long sizeInBytes) { var max = MaxScale; foreach (var order in ByteOrders) { if (sizeInBytes > max) return string.Format("{0:##.##} {1}", decimal.Divide(sizeInBytes, max), order); max /= 1024; } return "0 Bytes"; } static string PositiveTimeSpan(TimeSpan timeSpan) { const int second = 1; const int minute = 60 * second; const int hour = 60 * minute; const int day = 24 * hour; const int month = 30 * day; double delta = timeSpan.TotalSeconds; if (delta < 1) return timeSpan.Milliseconds + " ms"; if (delta < 1 * minute) return timeSpan.Seconds == 1 ? "one second" : timeSpan.Seconds + " seconds"; if (delta < 2 * minute) return "a minute"; if (delta < 50 * minute) return timeSpan.Minutes + " minutes"; if (delta < 70 * minute) return "an hour"; if (delta < 2 * hour) return (int)timeSpan.TotalMinutes + " minutes"; if (delta < 24 * hour) return timeSpan.Hours + " hours"; if (delta < 48 * hour) return (int)timeSpan.TotalHours + " hours"; if (delta < 30 * day) return timeSpan.Days + " days"; if (delta < 12 * month) { var months = (int)Math.Floor(timeSpan.Days / 30.0); return months <= 1 ? "one month" : months + " months"; } var years = (int)Math.Floor(timeSpan.Days / 365.0); return years <= 1 ? "one year" : years + " years"; } /// <summary> /// Displays time passed since (or remaining before) some event expressed in UTC, displaying it as '<em>5 days ago</em>'. /// </summary> /// <param name="dateInUtc">The date in UTC.</param> /// <returns>formatted event</returns> public static string TimeOffsetUtc(DateTime dateInUtc) { var now = DateTime.UtcNow; var offset = now - dateInUtc; return TimeSpan(offset); } /// <summary> /// Displays time passed since some event expressed, displaying it as '<em>5 days ago</em>'. /// </summary> /// <param name="localTime">The local time.</param> /// <returns></returns> public static string TimeOffset(DateTime localTime) { var now = DateTime.Now; var offset = now - localTime; return TimeSpan(offset); } /// <summary> /// Formats time span nicely /// </summary> /// <param name="offset">The offset.</param> /// <returns>formatted string</returns> public static string TimeSpan(TimeSpan offset) { if (offset > System.TimeSpan.Zero) { return PositiveTimeSpan(offset) + " ago"; } return PositiveTimeSpan(-offset) + " from now"; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Shared/FormatUtil.cs
C#
bsd
3,951
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global namespace Lokad.Cloud.Storage { /// <summary>Helper extensions methods for storage providers.</summary> public static class QueueStorageExtensions { /// <summary>Gets messages from a queue with a visibility timeout of 2 hours and a maximum of 50 processing trials.</summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="queueName">Identifier of the queue to be pulled.</param> /// <param name="count">Maximal number of messages to be retrieved.</param> /// <returns>Enumeration of messages, possibly empty.</returns> public static IEnumerable<T> Get<T>(this IQueueStorageProvider provider, string queueName, int count) { return provider.Get<T>(queueName, count, new TimeSpan(2, 0, 0), 5); } /// <summary>Gets messages from a queue with a visibility timeout of 2 hours.</summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="queueName">Identifier of the queue to be pulled.</param> /// <param name="count">Maximal number of messages to be retrieved.</param> /// <param name="maxProcessingTrials"> /// Maximum number of message processing trials, before the message is considered as /// being poisonous, removed from the queue and persisted to the 'failing-messages' store. /// </param> /// <returns>Enumeration of messages, possibly empty.</returns> public static IEnumerable<T> Get<T>(this IQueueStorageProvider provider, string queueName, int count, int maxProcessingTrials) { return provider.Get<T>(queueName, count, new TimeSpan(2, 0, 0), maxProcessingTrials); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Queues/QueueStorageExtensions.cs
C#
bsd
2,063
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Storage { /// <summary> /// The purpose of the <see cref="MessageEnvelope"/> is to provide /// additional metadata for a message. /// </summary> [DataContract] internal sealed class MessageEnvelope { [DataMember] public int DequeueCount { get; set; } [DataMember] public byte[] RawMessage { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Queues/MessageEnvelope.cs
C#
bsd
595
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Runtime.Serialization; namespace Lokad.Cloud.Storage { /// <summary>The purpose of the <see cref="MessageWrapper"/> is to gracefully /// handle messages that are too large of the queue storage (or messages that /// happen to be already stored in the Blob Storage).</summary> [DataContract] internal sealed class MessageWrapper { [DataMember] public string ContainerName { get; set; } [DataMember] public string BlobName { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Queues/MessageWrapper.cs
C#
bsd
677
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Xml.Linq; namespace Lokad.Cloud.Storage { /// <summary>Abstraction of the Queue Storage.</summary> /// <remarks> /// This provider represents a <em>logical</em> queue, not the actual /// Queue Storage. In particular, the provider implementation deals /// with overflowing messages (that is to say messages larger than 8kb) /// on its own. /// </remarks> public interface IQueueStorageProvider { /// <summary>Gets the list of queues whose name start with the specified prefix.</summary> /// <param name="prefix">If <c>null</c> or empty, returns all queues.</param> IEnumerable<string> List(string prefix); /// <summary>Gets messages from a queue.</summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="queueName">Identifier of the queue to be pulled.</param> /// <param name="count">Maximal number of messages to be retrieved.</param> /// <param name="visibilityTimeout"> /// The visibility timeout, indicating when the not yet deleted message should /// become visible in the queue again. /// </param> /// <param name="maxProcessingTrials"> /// Maximum number of message processing trials, before the message is considered as /// being poisonous, removed from the queue and persisted to the 'failing-messages' store. /// </param> /// <returns>Enumeration of messages, possibly empty.</returns> IEnumerable<T> Get<T>(string queueName, int count, TimeSpan visibilityTimeout, int maxProcessingTrials); /// <summary>Put a message on a queue.</summary> void Put<T>(string queueName, T message); /// <summary>Put messages on a queue.</summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="queueName">Identifier of the queue where messages are put.</param> /// <param name="messages">Messages to be put.</param> /// <remarks>If the queue does not exist, it gets created.</remarks> void PutRange<T>(string queueName, IEnumerable<T> messages); /// <summary>Clear all the messages from the specified queue.</summary> void Clear(string queueName); /// <summary>Deletes a message being processed from the queue.</summary> /// <returns><c>True</c> if the message has been deleted.</returns> /// <remarks>Message must have first been retrieved through <see cref="Get{T}"/>.</remarks> bool Delete<T>(T message); /// <summary>Deletes messages being processed from the queue.</summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="messages">Messages to be removed.</param> /// <returns>The number of messages actually deleted.</returns> /// <remarks>Messages must have first been retrieved through <see cref="Get{T}"/>.</remarks> int DeleteRange<T>(IEnumerable<T> messages); /// <summary> /// Abandon a message being processed and put it visibly back on the queue. /// </summary> /// <typeparam name="T">Type of the message.</typeparam> /// <param name="message">Message to be abandoned.</param> /// <returns><c>True</c> if the original message has been deleted.</returns> /// <remarks>Message must have first been retrieved through <see cref="Get{T}"/>.</remarks> bool Abandon<T>(T message); /// <summary> /// Abandon a set of messages being processed and put them visibly back on the queue. /// </summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="messages">Messages to be abandoned.</param> /// <returns>The number of original messages actually deleted.</returns> /// <remarks>Messages must have first been retrieved through <see cref="Get{T}"/>.</remarks> int AbandonRange<T>(IEnumerable<T> messages); /// <summary> /// Resume a message being processed later and put it visibly back on the queue, without decreasing the poison detection dequeue count. /// </summary> /// <typeparam name="T">Type of the message.</typeparam> /// <param name="message">Message to be resumed later.</param> /// <returns><c>True</c> if the original message has been deleted.</returns> /// <remarks>Message must have first been retrieved through <see cref="Get{T}"/>.</remarks> bool ResumeLater<T>(T message); /// <summary> /// Resume a set of messages being processed latern and put them visibly back on the queue, without decreasing the poison detection dequeue count. /// </summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="messages">Messages to be resumed later.</param> /// <returns>The number of original messages actually deleted.</returns> /// <remarks>Messages must have first been retrieved through <see cref="Get{T}"/>.</remarks> int ResumeLaterRange<T>(IEnumerable<T> messages); /// <summary> /// Persist a message being processed to a store and remove it from the queue. /// </summary> /// <typeparam name="T">Type of the message.</typeparam> /// <param name="message">Message to be persisted.</param> /// <param name="storeName">Name of the message persistence store.</param> /// <param name="reason">Optional reason text on why the message has been taken out of the queue.</param> void Persist<T>(T message, string storeName, string reason); /// <summary> /// Persist a set of messages being processed to a store and remove them from the queue. /// </summary> /// <typeparam name="T">Type of the messages.</typeparam> /// <param name="messages">Messages to be persisted.</param> /// <param name="storeName">Name of the message persistence store.</param> /// <param name="reason">Optional reason text on why the messages have been taken out of the queue.</param> void PersistRange<T>(IEnumerable<T> messages, string storeName, string reason); /// <summary> /// Enumerate the keys of all persisted messages of the provided store. /// </summary> /// <param name="storeName">Name of the message persistence store.</param> IEnumerable<string> ListPersisted(string storeName); /// <summary> /// Get details of a persisted message for inspection and recovery. /// </summary> /// <param name="storeName">Name of the message persistence store.</param> /// <param name="key">Unique key of the persisted message as returned by ListPersisted.</param> Maybe<PersistedMessage> GetPersisted(string storeName, string key); /// <summary> /// Delete a persisted message. /// </summary> /// <param name="storeName">Name of the message persistence store.</param> /// <param name="key">Unique key of the persisted message as returned by ListPersisted.</param> void DeletePersisted(string storeName, string key); /// <summary> /// Put a persisted message back to the queue and delete it. /// </summary> /// <param name="storeName">Name of the message persistence store.</param> /// <param name="key">Unique key of the persisted message as returned by ListPersisted.</param> void RestorePersisted(string storeName, string key); /// <summary>Deletes a queue.</summary> /// <returns><c>true</c> if the queue name has been actually deleted.</returns> bool DeleteQueue(string queueName); /// <summary>Gets the approximate number of items in this queue.</summary> int GetApproximateCount(string queueName); /// <summary>Gets the approximate age of the top message of this queue.</summary> Maybe<TimeSpan> GetApproximateLatency(string queueName); } /// <summary> /// Persisted message details for inspection and recovery. /// </summary> public class PersistedMessage { /// <summary>Identifier of the originating message queue.</summary> public string QueueName { get; internal set; } /// <summary>Name of the message persistence store.</summary> public string StoreName { get; internal set; } /// <summary>Unique key of the persisted message as returned by ListPersisted.</summary> public string Key { get; internal set; } /// <summary>Time when the message was inserted into the message queue.</summary> public DateTimeOffset InsertionTime { get; internal set; } /// <summary>Time when the message was persisted and removed from the message queue.</summary> public DateTimeOffset PersistenceTime { get; internal set; } /// <summary>The number of times the message has been dequeued.</summary> public int DequeueCount { get; internal set; } /// <summary>Optional reason text why the message was persisted.</summary> public string Reason { get; internal set; } /// <summary>XML representation of the message, if possible and supported by the serializer</summary> public Maybe<XElement> DataXml { get; internal set; } /// <summary>True if the raw message data is available and can be restored.</summary> /// <remarks>Can be true even if DataXML is not available.</remarks> public bool IsDataAvailable { get; internal set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Queues/IQueueStorageProvider.cs
C#
bsd
9,981
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Threading; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Policies; using Lokad.Cloud.Storage.Shared.Threading; using Microsoft.WindowsAzure.StorageClient; using Microsoft.WindowsAzure.StorageClient.Protocol; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.Storage.Azure { /// <summary>Provides access to the Blob Storage.</summary> /// <remarks> /// All the methods of <see cref="BlobStorageProvider"/> are thread-safe. /// </remarks> public class BlobStorageProvider : IBlobStorageProvider { /// <summary>Custom meta-data used as a work-around of an issue of the StorageClient.</summary> /// <remarks>[vermorel 2010-11] The StorageClient for odds reasons do not enable the /// retrieval of the Content-MD5 property when performing a GET on blobs. In order to validate /// the integrity during the entire roundtrip, we need to apply a suplementary header /// used to perform the MD5 check.</remarks> private const string MetadataMD5Key = "LokadContentMD5"; readonly CloudBlobClient _blobStorage; readonly IDataSerializer _serializer; readonly ActionPolicy _azureServerPolicy; readonly ActionPolicy _networkPolicy; readonly ILog _log; // Instrumentation readonly ExecutionCounter _countPutBlob; readonly ExecutionCounter _countGetBlob; readonly ExecutionCounter _countGetBlobIfModified; readonly ExecutionCounter _countUpsertBlobOrSkip; readonly ExecutionCounter _countDeleteBlob; /// <summary>IoC constructor.</summary> public BlobStorageProvider(CloudBlobClient blobStorage, IDataSerializer serializer, ILog log = null) { _blobStorage = blobStorage; _serializer = serializer; _log = log; _azureServerPolicy = AzurePolicies.TransientServerErrorBackOff; _networkPolicy = AzurePolicies.NetworkCorruption; // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countPutBlob = new ExecutionCounter("BlobStorageProvider.PutBlob", 0, 0), _countGetBlob = new ExecutionCounter("BlobStorageProvider.GetBlob", 0, 0), _countGetBlobIfModified = new ExecutionCounter("BlobStorageProvider.GetBlobIfModified", 0, 0), _countUpsertBlobOrSkip = new ExecutionCounter("BlobStorageProvider.UpdateBlob", 0, 0), _countDeleteBlob = new ExecutionCounter("BlobStorageProvider.DeleteBlob", 0, 0), }); } public IEnumerable<string> ListContainers(string containerNamePrefix = null) { var enumerator = String.IsNullOrEmpty(containerNamePrefix) ? _blobStorage.ListContainers().GetEnumerator() : _blobStorage.ListContainers(containerNamePrefix).GetEnumerator(); // TODO: Parallelize while (true) { if (!_azureServerPolicy.Get(enumerator.MoveNext)) { yield break; } // removing /container/ from the blob name (dev storage: /account/container/) yield return enumerator.Current.Name; } } public bool CreateContainerIfNotExist(string containerName) { //workaround since Azure is presently returning OutOfRange exception when using a wrong name. if (!BlobStorageExtensions.IsContainerNameValid(containerName)) throw new NotSupportedException("containerName is not compliant with azure constraints on container naming"); var container = _blobStorage.GetContainerReference(containerName); try { _azureServerPolicy.Do(container.Create); return true; } catch(StorageClientException ex) { if(ex.ErrorCode == StorageErrorCode.ContainerAlreadyExists || ex.ErrorCode == StorageErrorCode.ResourceAlreadyExists) { return false; } throw; } } public bool DeleteContainerIfExist(string containerName) { var container = _blobStorage.GetContainerReference(containerName); try { _azureServerPolicy.Do(container.Delete); return true; } catch(StorageClientException ex) { if(ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } throw; } } public IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null) { // Enumerated blobs do not have a "name" property, // thus the name must be extracted from their URI // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/c5e36676-8d07-46cc-b803-72621a0898b0/?prof=required if (blobNamePrefix == null) { blobNamePrefix = string.Empty; } var container = _blobStorage.GetContainerReference(containerName); var options = new BlobRequestOptions { UseFlatBlobListing = true }; // if no prefix is provided, then enumerate the whole container IEnumerator<IListBlobItem> enumerator; if (string.IsNullOrEmpty(blobNamePrefix)) { enumerator = container.ListBlobs(options).GetEnumerator(); } else { // 'CloudBlobDirectory' must be used for prefixed enumeration var directory = container.GetDirectoryReference(blobNamePrefix); // HACK: [vermorel] very ugly override, but otherwise an "/" separator gets forcibly added typeof(CloudBlobDirectory).GetField("prefix", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(directory, blobNamePrefix); enumerator = directory.ListBlobs(options).GetEnumerator(); } // TODO: Parallelize while (true) { try { if (!_azureServerPolicy.Get(enumerator.MoveNext)) { yield break; } } catch (StorageClientException ex) { // if the container does not exist, empty enumeration if (ex.ErrorCode == StorageErrorCode.ContainerNotFound) { yield break; } throw; } // removing /container/ from the blob name (dev storage: /account/container/) yield return Uri.UnescapeDataString(enumerator.Current.Uri.AbsolutePath.Substring(container.Uri.LocalPath.Length + 1)); } } public IEnumerable<T> ListBlobs<T>(string containerName, string blobNamePrefix = null, int skip = 0) { var names = ListBlobNames(containerName, blobNamePrefix); if (skip > 0) { names = names.Skip(skip); } return names.Select(name => GetBlob<T>(containerName, name)) .Where(blob => blob.HasValue) .Select(blob => blob.Value); } public bool DeleteBlobIfExist(string containerName, string blobName) { var timestamp = _countDeleteBlob.Open(); var container = _blobStorage.GetContainerReference(containerName); try { var blob = container.GetBlockBlobReference(blobName); _azureServerPolicy.Do(blob.Delete); _countDeleteBlob.Close(timestamp); return true; } catch (StorageClientException ex) // no such container, return false { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } throw; } } public void DeleteAllBlobs(string containerName, string blobNamePrefix = null) { // TODO: Parallelize foreach (var blobName in ListBlobNames(containerName, blobNamePrefix)) { DeleteBlobIfExist(containerName, blobName); } } public Maybe<T> GetBlob<T>(string containerName, string blobName) { string ignoredEtag; return GetBlob<T>(containerName, blobName, out ignoredEtag); } public Maybe<T> GetBlob<T>(string containerName, string blobName, out string etag) { return GetBlob(containerName, blobName, typeof(T), out etag) .Convert(o => (T)o, Maybe<T>.Empty); } public Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag) { var timestamp = _countGetBlob.Open(); var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); using (var stream = new MemoryStream()) { etag = null; // if no such container, return empty try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream); VerifyContentHash(blob, stream, containerName, blobName); })); etag = blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<object>.Empty; } throw; } stream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserialize(stream, type); _countGetBlob.Close(timestamp); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for GeBlob but failed to deserialize. Blob {0} in container {1}.", blobName, containerName); } return deserialized.IsSuccess ? new Maybe<object>(deserialized.Value) : Maybe<object>.Empty; } } public Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag) { etag = null; var formatter = _serializer as IIntermediateDataSerializer; if (formatter == null) { return Maybe<XElement>.Empty; } var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); using (var stream = new MemoryStream()) { // if no such container, return empty try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream); VerifyContentHash(blob, stream, containerName, blobName); })); etag = blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<XElement>.Empty; } throw; } stream.Seek(0, SeekOrigin.Begin); var unpacked = formatter.TryUnpackXml(stream); return unpacked.IsSuccess ? unpacked.Value : Maybe<XElement>.Empty; } } /// <summary>As many parallel requests than there are blob names.</summary> public Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags) { var tempResult = blobNames.SelectInParallel(blobName => { string etag; var blob = GetBlob<T>(containerName, blobName, out etag); return new Tuple<Maybe<T>, string>(blob, etag); }, blobNames.Length); etags = new string[blobNames.Length]; var result = new Maybe<T>[blobNames.Length]; for (int i = 0; i < tempResult.Length; i++) { result[i] = tempResult[i].Item1; etags[i] = tempResult[i].Item2; } return result; } public Maybe<T> GetBlobIfModified<T>(string containerName, string blobName, string oldEtag, out string newEtag) { // 'oldEtag' is null, then behavior always match simple 'GetBlob'. if (null == oldEtag) { return GetBlob<T>(containerName, blobName, out newEtag); } var timestamp = _countGetBlobIfModified.Open(); newEtag = null; var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); try { var options = new BlobRequestOptions { AccessCondition = AccessCondition.IfNoneMatch(oldEtag) }; using (var stream = new MemoryStream()) { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(stream, options); VerifyContentHash(blob, stream, containerName, blobName); })); newEtag = blob.Properties.ETag; stream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserializeAs<T>(stream); _countGetBlobIfModified.Close(timestamp); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for GetBlobIfModified but failed to deserialize. Blob {0} in container {1}.", blobName, containerName); } return deserialized.IsSuccess ? deserialized.Value : Maybe<T>.Empty; } } catch (StorageClientException ex) { // call fails because blob has not been modified (usual case) if (ex.ErrorCode == StorageErrorCode.ConditionFailed || // HACK: BUG in StorageClient 1.0 // see http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/4817cafa-12d8-4979-b6a7-7bda053e6b21 ex.Message == @"The condition specified using HTTP conditional header(s) is not met.") { return Maybe<T>.Empty; } // call fails due to misc problems if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return Maybe<T>.Empty; } throw; } } public string GetBlobEtag(string containerName, string blobName) { var container = _blobStorage.GetContainerReference(containerName); try { var blob = container.GetBlockBlobReference(blobName); _azureServerPolicy.Do(blob.FetchAttributes); return blob.Properties.ETag; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return null; } throw; } } public void PutBlob<T>(string containerName, string blobName, T item) { PutBlob(containerName, blobName, item, true); } public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite) { string ignored; return PutBlob(containerName, blobName, item, overwrite, out ignored); } public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite, out string etag) { return PutBlob(containerName, blobName, item, typeof(T), overwrite, out etag); } public bool PutBlob<T>(string containerName, string blobName, T item, string expectedEtag) { string outEtag; return PutBlob(containerName, blobName, item, typeof (T), true, expectedEtag, out outEtag); } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, string expectedEtag, out string outEtag) { var timestamp = _countPutBlob.Open(); using (var stream = new MemoryStream()) { _serializer.Serialize(item, stream); var container = _blobStorage.GetContainerReference(containerName); Func<Maybe<string>> doUpload = () => { var blob = container.GetBlockBlobReference(blobName); // single remote call var result = UploadBlobContent(blob, stream, overwrite, expectedEtag); return result; }; try { var result = doUpload(); if (!result.HasValue) { outEtag = null; return false; } outEtag = result.Value; _countPutBlob.Close(timestamp); return true; } catch (StorageClientException ex) { // if the container does not exist, it gets created if (ex.ErrorCode == StorageErrorCode.ContainerNotFound) { // caution: the container might have been freshly deleted // (multiple retries are needed in such a situation) var tentativeEtag = Maybe<string>.Empty; AzurePolicies.SlowInstantiation.Do(() => { _azureServerPolicy.Get(container.CreateIfNotExist); tentativeEtag = doUpload(); }); if (!tentativeEtag.HasValue) { outEtag = null; return false; } outEtag = tentativeEtag.Value; _countPutBlob.Close(timestamp); return true; } if (ex.ErrorCode == StorageErrorCode.BlobAlreadyExists && !overwrite) { // See http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/fff78a35-3242-4186-8aee-90d27fbfbfd4 // and http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/86b9f184-c329-4c30-928f-2991f31e904b/ outEtag = null; return false; } var result = doUpload(); if (!result.HasValue) { outEtag = null; return false; } outEtag = result.Value; _countPutBlob.Close(timestamp); return true; } } } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string outEtag) { return PutBlob(containerName, blobName, item, type, overwrite, null, out outEtag); } /// <param name="overwrite">If <c>false</c>, then no write happens if the blob already exists.</param> /// <param name="expectedEtag">When specified, no writing occurs unless the blob etag /// matches the one specified as argument.</param> /// <returns>The ETag of the written blob, if it was written.</returns> Maybe<string> UploadBlobContent(CloudBlob blob, Stream stream, bool overwrite, string expectedEtag) { BlobRequestOptions options; if (!overwrite) // no overwrite authorized, blob must NOT exists { options = new BlobRequestOptions { AccessCondition = AccessCondition.IfNotModifiedSince(DateTime.MinValue) }; } else // overwrite is OK { options = string.IsNullOrEmpty(expectedEtag) ? // case with no etag constraint new BlobRequestOptions { AccessCondition = AccessCondition.None } : // case with etag constraint new BlobRequestOptions { AccessCondition = AccessCondition.IfMatch(expectedEtag) }; } ApplyContentHash(blob, stream); try { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { stream.Seek(0, SeekOrigin.Begin); blob.UploadFromStream(stream, options); })); } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ConditionFailed) { return Maybe<string>.Empty; } throw; } return blob.Properties.ETag; } public Maybe<T> UpdateBlobIfExist<T>( string containerName, string blobName, Func<T, T> update) { return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, t => update(t)); } public Maybe<T> UpdateBlobIfExistOrSkip<T>( string containerName, string blobName, Func<T, Maybe<T>> update) { return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update); } public Maybe<T> UpdateBlobIfExistOrDelete<T>( string containerName, string blobName, Func<T, Maybe<T>> update) { var result = UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update); if (!result.HasValue) { DeleteBlobIfExist(containerName, blobName); } return result; } public T UpsertBlob<T>(string containerName, string blobName, Func<T> insert, Func<T, T> update) { return UpsertBlobOrSkip<T>(containerName, blobName, () => insert(), t => update(t)).Value; } public Maybe<T> UpsertBlobOrSkip<T>( string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { var timestamp = _countUpsertBlobOrSkip.Open(); var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); Maybe<T> output; TimeSpan retryInterval; var retryPolicy = AzurePolicies.OptimisticConcurrency(); for (int retryCount = 0; retryPolicy(retryCount, null, out retryInterval); retryCount++) { // 1. DOWNLOAD EXISTING INPUT BLOB, IF IT EXISTS Maybe<T> input; bool inputBlobExists = false; string inputETag = null; try { using (var readStream = new MemoryStream()) { _azureServerPolicy.Do(() => _networkPolicy.Do(() => { readStream.Seek(0, SeekOrigin.Begin); blob.DownloadToStream(readStream); VerifyContentHash(blob, readStream, containerName, blobName); })); inputETag = blob.Properties.ETag; inputBlobExists = !String.IsNullOrEmpty(inputETag); readStream.Seek(0, SeekOrigin.Begin); var deserialized = _serializer.TryDeserializeAs<T>(readStream); if (!deserialized.IsSuccess && _log != null) { _log.WarnFormat(deserialized.Error, "Cloud Storage: A blob was retrieved for Upsert but failed to deserialize. An Insert will be performed instead, overwriting the corrupt blob {0} in container {1}.", blobName, containerName); } input = deserialized.IsSuccess ? deserialized.Value : Maybe<T>.Empty; } } catch (StorageClientException ex) { // creating the container when missing if (ex.ErrorCode == StorageErrorCode.ContainerNotFound || ex.ErrorCode == StorageErrorCode.BlobNotFound || ex.ErrorCode == StorageErrorCode.ResourceNotFound) { input = Maybe<T>.Empty; // caution: the container might have been freshly deleted // (multiple retries are needed in such a situation) AzurePolicies.SlowInstantiation.Do(() => _azureServerPolicy.Get(container.CreateIfNotExist)); } else { throw; } } // 2. APPLY UPADTE OR INSERT (DEPENDING ON INPUT) output = input.HasValue ? update(input.Value) : insert(); // 3. IF EMPTY OUTPUT THEN WE CAN SKIP THE WHOLE OPERATION if (!output.HasValue) { _countUpsertBlobOrSkip.Close(timestamp); return output; } // 4. TRY TO INSERT OR UPDATE BLOB using (var writeStream = new MemoryStream()) { _serializer.Serialize(output.Value, writeStream); writeStream.Seek(0, SeekOrigin.Begin); // Semantics: // Insert: Blob must not exist -> do not overwrite // Update: Blob must exists -> overwrite and verify matching ETag bool succeeded = inputBlobExists ? UploadBlobContent(blob, writeStream, true, inputETag).HasValue : UploadBlobContent(blob, writeStream, false, null).HasValue; if (succeeded) { _countUpsertBlobOrSkip.Close(timestamp); return output; } } // 5. WAIT UNTIL NEXT TRIAL (retry policy) if (retryInterval > TimeSpan.Zero) { Thread.Sleep(retryInterval); } } throw new TimeoutException("Failed to resolve optimistic concurrency errors within a limited number of retrials"); } public Maybe<T> UpsertBlobOrDelete<T>( string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { var result = UpsertBlobOrSkip(containerName, blobName, insert, update); if (!result.HasValue) { DeleteBlobIfExist(containerName, blobName); } return result; } private static string ComputeContentHash(Stream source) { byte[] hash; source.Seek(0, SeekOrigin.Begin); using (var md5 = MD5.Create()) { hash = md5.ComputeHash(source); } source.Seek(0, SeekOrigin.Begin); return Convert.ToBase64String(hash); } /// <summary> /// Apply a content hash to the blob to verify upload and roundtrip consistency. /// </summary> private static void ApplyContentHash(CloudBlob blob, Stream stream) { var hash = ComputeContentHash(stream); // HACK: [Vermorel 2010-11] StorageClient does not apply MD5 on smaller blobs. // Reflector indicates that the behavior threshold is at 32MB // so manually disable hasing for larger blobs if (stream.Length < 0x2000000L) { blob.Properties.ContentMD5 = hash; } // HACK: [vermorel 2010-11] StorageClient does not provide a way to retrieve // MD5 so we add our own MD5 check which let perform our own validation when // downloading the blob (full roundtrip validation). blob.Metadata[MetadataMD5Key] = hash; } /// <summary> /// Throws a DataCorruptionException if the content hash is available but doesn't match. /// </summary> private static void VerifyContentHash(CloudBlob blob, Stream stream, string containerName, string blobName) { var expectedHash = blob.Metadata[MetadataMD5Key]; if (string.IsNullOrEmpty(expectedHash)) { return; } if (expectedHash != ComputeContentHash(stream)) { throw new DataCorruptionException( string.Format("MD5 mismatch on blob retrieval {0}/{1}.", containerName, blobName)); } } public Result<string> TryAcquireLease(string containerName, string blobName) { var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); var credentials = _blobStorage.Credentials; var uri = new Uri(credentials.TransformUri(blob.Uri.ToString())); var request = BlobRequest.Lease(uri, 90, LeaseAction.Acquire, null); credentials.SignRequest(request); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { var statusCode = ((HttpWebResponse) we.Response).StatusCode; switch (statusCode) { case HttpStatusCode.Conflict: case HttpStatusCode.RequestTimeout: case HttpStatusCode.InternalServerError: return Result<string>.CreateError(statusCode.ToString()); default: throw; } } try { return response.StatusCode == HttpStatusCode.Created ? Result<string>.CreateSuccess(response.Headers["x-ms-lease-id"]) : Result<string>.CreateError(response.StatusCode.ToString()); } finally { response.Close(); } } public bool TryReleaseLease(string containerName, string blobName, string leaseId) { return TryLeaseAction(containerName, blobName, LeaseAction.Release, leaseId); } public bool TryRenewLease(string containerName, string blobName, string leaseId) { return TryLeaseAction(containerName, blobName, LeaseAction.Renew, leaseId); } private bool TryLeaseAction(string containerName, string blobName, LeaseAction action, string leaseId = null) { var container = _blobStorage.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(blobName); var credentials = _blobStorage.Credentials; var uri = new Uri(credentials.TransformUri(blob.Uri.ToString())); var request = BlobRequest.Lease(uri, 90, action, leaseId); credentials.SignRequest(request); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException we) { var statusCode = ((HttpWebResponse) we.Response).StatusCode; switch(statusCode) { case HttpStatusCode.Conflict: case HttpStatusCode.RequestTimeout: case HttpStatusCode.InternalServerError: return false; default: throw; } } try { var expectedCode = action == LeaseAction.Break ? HttpStatusCode.Accepted : HttpStatusCode.OK; return response.StatusCode == expectedCode; } finally { response.Close(); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/BlobStorageProvider.cs
C#
bsd
36,425
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Logging; using Lokad.Cloud.Storage.Shared.Policies; using Lokad.Diagnostics; using Lokad.Cloud.Storage.Shared; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>Provides access to the Queue Storage (plus the Blob Storage when /// messages are overflowing).</summary> /// <remarks> /// <para> /// Overflowing messages are stored in blob storage and normally deleted as with /// their originating correspondence in queue storage. /// </para> /// <para>All the methods of <see cref="QueueStorageProvider"/> are thread-safe.</para> /// </remarks> public class QueueStorageProvider : IQueueStorageProvider, IDisposable { internal const string OverflowingMessagesContainerName = "lokad-cloud-overflowing-messages"; internal const string PoisonedMessagePersistenceStoreName = "failing-messages"; /// <summary>Root used to synchronize accesses to <c>_inprocess</c>. /// Caution: do not hold the lock while performing operations on the cloud /// storage.</summary> readonly object _sync = new object(); readonly CloudQueueClient _queueStorage; readonly IBlobStorageProvider _blobStorage; readonly IDataSerializer _serializer; readonly IRuntimeFinalizer _runtimeFinalizer; readonly ActionPolicy _azureServerPolicy; readonly ILog _log; // Instrumentation readonly ExecutionCounter _countGetMessage; readonly ExecutionCounter _countPutMessage; readonly ExecutionCounter _countDeleteMessage; readonly ExecutionCounter _countAbandonMessage; readonly ExecutionCounter _countPersistMessage; readonly ExecutionCounter _countWrapMessage; readonly ExecutionCounter _countUnwrapMessage; // messages currently being processed (boolean property indicates if the message is overflowing) /// <summary>Mapping object --> Queue Message Id. Use to delete messages afterward.</summary> readonly Dictionary<object, InProcessMessage> _inProcessMessages; /// <summary>IoC constructor.</summary> /// <param name="blobStorage">Not null.</param> /// <param name="queueStorage">Not null.</param> /// <param name="serializer">Not null.</param> /// <param name="runtimeFinalizer">May be null (handy for strict O/C mapper /// scenario).</param> /// <param name="log">Optional log</param> public QueueStorageProvider( CloudQueueClient queueStorage, IBlobStorageProvider blobStorage, IDataSerializer serializer, IRuntimeFinalizer runtimeFinalizer, ILog log = null) { _queueStorage = queueStorage; _blobStorage = blobStorage; _serializer = serializer; _runtimeFinalizer = runtimeFinalizer; _log = log; // finalizer can be null in a strict O/C mapper scenario if(null != _runtimeFinalizer) { // self-registration for finalization _runtimeFinalizer.Register(this); } _azureServerPolicy = AzurePolicies.TransientServerErrorBackOff; _inProcessMessages = new Dictionary<object, InProcessMessage>(20); // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countGetMessage = new ExecutionCounter("QueueStorageProvider.Get", 0, 0), _countPutMessage = new ExecutionCounter("QueueStorageProvider.PutSingle", 0, 0), _countDeleteMessage = new ExecutionCounter("QueueStorageProvider.DeleteSingle", 0, 0), _countAbandonMessage = new ExecutionCounter("QueueStorageProvider.AbandonSingle", 0, 0), _countPersistMessage = new ExecutionCounter("QueueStorageProvider.PersistSingle", 0, 0), _countWrapMessage = new ExecutionCounter("QueueStorageProvider.WrapSingle", 0, 0), _countUnwrapMessage = new ExecutionCounter("QueueStorageProvider.UnwrapSingle", 0, 0), }); } /// <summary> /// Disposing the provider will cause an abandon on all currently messages currently /// in-process. At the end of the life-cycle of the provider, normally there is no /// message in-process. /// </summary> public void Dispose() { AbandonRange(_inProcessMessages.Keys.ToArray()); } public IEnumerable<string> List(string prefix) { return _queueStorage.ListQueues(prefix).Select(queue => queue.Name); } public IEnumerable<T> Get<T>(string queueName, int count, TimeSpan visibilityTimeout, int maxProcessingTrials) { var timestamp = _countGetMessage.Open(); var queue = _queueStorage.GetQueueReference(queueName); // 1. GET RAW MESSAGES IEnumerable<CloudQueueMessage> rawMessages; try { rawMessages = _azureServerPolicy.Get(() => queue.GetMessages(count, visibilityTimeout)); } catch (StorageClientException ex) { // if the queue does not exist return an empty collection. if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return new T[0]; } throw; } // 2. SKIP EMPTY QUEUE if (null == rawMessages) { _countGetMessage.Close(timestamp); return new T[0]; } // 3. DESERIALIZE MESSAGE OR MESSAGE WRAPPER, CHECK-OUT var messages = new List<T>(count); var wrappedMessages = new List<MessageWrapper>(); lock (_sync) { foreach (var rawMessage in rawMessages) { // 3.1. DESERIALIZE MESSAGE, CHECK-OUT, COLLECT WRAPPED MESSAGES TO BE UNWRAPPED LATER var data = rawMessage.AsBytes; var stream = new MemoryStream(data); try { var dequeueCount = rawMessage.DequeueCount; // 3.1.1 UNPACK ENVELOPE IF PACKED, UPDATE POISONING INDICATOR var messageAsEnvelope = _serializer.TryDeserializeAs<MessageEnvelope>(stream); if (messageAsEnvelope.IsSuccess) { stream.Dispose(); dequeueCount += messageAsEnvelope.Value.DequeueCount; data = messageAsEnvelope.Value.RawMessage; stream = new MemoryStream(data); } // 3.1.2 PERSIST POISONED MESSAGE, SKIP if (dequeueCount > maxProcessingTrials) { // we want to persist the unpacked message (no envelope) but still need to drop // the original message, that's why we pass the original rawMessage but the unpacked data PersistRawMessage(rawMessage, data, queueName, PoisonedMessagePersistenceStoreName, String.Format("Message was dequeued {0} times but failed processing each time.", dequeueCount - 1)); if (_log != null) { _log.WarnFormat("Cloud Storage: A message of type {0} in queue {1} failed to process repeatedly and has been quarantined.", typeof(T).Name, queueName); } continue; } // 3.1.3 DESERIALIZE MESSAGE IF POSSIBLE var messageAsT = _serializer.TryDeserializeAs<T>(stream); if (messageAsT.IsSuccess) { messages.Add(messageAsT.Value); CheckOutMessage(messageAsT.Value, rawMessage, data, queueName, false, dequeueCount); continue; } // 3.1.4 DESERIALIZE WRAPPER IF POSSIBLE var messageAsWrapper = _serializer.TryDeserializeAs<MessageWrapper>(stream); if (messageAsWrapper.IsSuccess) { // we don't retrieve messages while holding the lock wrappedMessages.Add(messageAsWrapper.Value); CheckOutMessage(messageAsWrapper.Value, rawMessage, data, queueName, true, dequeueCount); continue; } // 3.1.5 PERSIST FAILED MESSAGE, SKIP // we want to persist the unpacked message (no envelope) but still need to drop // the original message, that's why we pass the original rawMessage but the unpacked data PersistRawMessage(rawMessage, data, queueName, PoisonedMessagePersistenceStoreName, String.Format("Message failed to deserialize:\r\nAs {0}:\r\n{1}\r\n\r\nAs MessageEnvelope:\r\n{2}\r\n\r\nAs MessageWrapper:\r\n{3}", typeof (T).FullName, messageAsT.Error, messageAsEnvelope.IsSuccess ? "unwrapped" : messageAsEnvelope.Error.ToString(), messageAsWrapper.Error)); if (_log != null) { _log.WarnFormat(messageAsT.Error, "Cloud Storage: A message in queue {0} failed to deserialize to type {1} and has been quarantined.", queueName, typeof(T).Name); } } finally { stream.Dispose(); } } } // 4. UNWRAP WRAPPED MESSAGES foreach (var mw in wrappedMessages) { var unwrapTimestamp = _countUnwrapMessage.Open(); string ignored; var blobContent = _blobStorage.GetBlob(mw.ContainerName, mw.BlobName, typeof(T), out ignored); // blob may not exists in (rare) case of failure just before queue deletion // but after container deletion (or also timeout deletion). if (!blobContent.HasValue) { CloudQueueMessage rawMessage; lock (_sync) { rawMessage = _inProcessMessages[mw].RawMessages[0]; CheckInMessage(mw); } DeleteRawMessage(rawMessage, queue); // skipping the message if it can't be unwrapped continue; } T innerMessage = (T)blobContent.Value; // substitution: message wrapper replaced by actual item in '_inprocess' list CheckOutRelink(mw, innerMessage); messages.Add(innerMessage); _countUnwrapMessage.Close(unwrapTimestamp); } _countGetMessage.Close(timestamp); // 5. RETURN LIST OF MESSAGES return messages; } public void Put<T>(string queueName, T message) { PutRange(queueName, new[] { message }); } public void PutRange<T>(string queueName, IEnumerable<T> messages) { var queue = _queueStorage.GetQueueReference(queueName); foreach (var message in messages) { var timestamp = _countPutMessage.Open(); using (var stream = new MemoryStream()) { _serializer.Serialize(message, stream); // Caution: MaxMessageSize is not related to the number of bytes // but the number of characters when Base64-encoded: CloudQueueMessage queueMessage; if (stream.Length >= (CloudQueueMessage.MaxMessageSize - 1) / 4 * 3) { queueMessage = new CloudQueueMessage(PutOverflowingMessageAndWrap(queueName, message)); } else { try { queueMessage = new CloudQueueMessage(stream.ToArray()); } catch (ArgumentException) { queueMessage = new CloudQueueMessage(PutOverflowingMessageAndWrap(queueName, message)); } } PutRawMessage(queueMessage, queue); } _countPutMessage.Close(timestamp); } } byte[] PutOverflowingMessageAndWrap<T>(string queueName, T message) { var timestamp = _countWrapMessage.Open(); var blobRef = OverflowingMessageBlobName<T>.GetNew(queueName); // HACK: In this case serialization is performed another time (internally) _blobStorage.PutBlob(blobRef, message); var mw = new MessageWrapper { ContainerName = blobRef.ContainerName, BlobName = blobRef.ToString() }; using (var stream = new MemoryStream()) { _serializer.Serialize(mw, stream); var serializerWrapper = stream.ToArray(); _countWrapMessage.Close(timestamp); return serializerWrapper; } } void DeleteOverflowingMessages(string queueName) { _blobStorage.DeleteAllBlobs(OverflowingMessagesContainerName, queueName); } public void Clear(string queueName) { try { // caution: call 'DeleteOverflowingMessages' first (BASE). DeleteOverflowingMessages(queueName); var queue = _queueStorage.GetQueueReference(queueName); _azureServerPolicy.Do(queue.Clear); } catch (StorageClientException ex) { // if the queue does not exist do nothing if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return; } throw; } } public bool Delete<T>(T message) { return DeleteRange(new[] { message }) > 0; } public int DeleteRange<T>(IEnumerable<T> messages) { int deletionCount = 0; foreach (var message in messages) { var timestamp = _countDeleteMessage.Open(); // 1. GET RAW MESSAGE & QUEUE, OR SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage rawMessage; string queueName; bool isOverflowing; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { continue; } rawMessage = inProcMsg.RawMessages[0]; isOverflowing = inProcMsg.IsOverflowing; queueName = inProcMsg.QueueName; data = inProcMsg.Data; } var queue = _queueStorage.GetQueueReference(queueName); // 2. DELETING THE OVERFLOW BLOB, IF WRAPPED if (isOverflowing) { var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(data); if (messageWrapper.IsSuccess) { _blobStorage.DeleteBlobIfExist(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName); } else if (_log != null) { _log.WarnFormat(messageWrapper.Error, "Cloud Storage: The overflowing part of a corrupt message in queue {0} could not be identified and may have not been deleted while deleting the message itself.", queueName); } } // 3. DELETE THE MESSAGE FROM THE QUEUE if(DeleteRawMessage(rawMessage, queue)) { deletionCount++; } // 4. REMOVE THE RAW MESSAGE CheckInMessage(message); _countDeleteMessage.Close(timestamp); } return deletionCount; } public bool Abandon<T>(T message) { return AbandonRange(new[] { message }) > 0; } public int AbandonRange<T>(IEnumerable<T> messages) { int abandonCount = 0; foreach (var message in messages) { var timestamp = _countAbandonMessage.Open(); // 1. GET RAW MESSAGE & QUEUE, OR SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage oldRawMessage; string queueName; int dequeueCount; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { continue; } queueName = inProcMsg.QueueName; dequeueCount = inProcMsg.DequeueCount; oldRawMessage = inProcMsg.RawMessages[0]; data = inProcMsg.Data; } var queue = _queueStorage.GetQueueReference(queueName); // 2. CLONE THE MESSAGE AND PUT IT TO THE QUEUE // we always use an envelope here since the dequeue count // is always >0, which we should continue to track in order // to make poison detection possible at all. var envelope = new MessageEnvelope { DequeueCount = dequeueCount, RawMessage = data }; CloudQueueMessage newRawMessage = null; using (var stream = new MemoryStream()) { _serializer.Serialize(envelope, stream); if (stream.Length < (CloudQueueMessage.MaxMessageSize - 1)/4*3) { try { newRawMessage = new CloudQueueMessage(stream.ToArray()); } catch (ArgumentException) { } } if (newRawMessage == null) { envelope.RawMessage = PutOverflowingMessageAndWrap(queueName, message); using (var wrappedStream = new MemoryStream()) { _serializer.Serialize(envelope, wrappedStream); newRawMessage = new CloudQueueMessage(wrappedStream.ToArray()); } } } PutRawMessage(newRawMessage, queue); // 3. DELETE THE OLD MESSAGE FROM THE QUEUE if(DeleteRawMessage(oldRawMessage, queue)) { abandonCount++; } // 4. REMOVE THE RAW MESSAGE CheckInMessage(message); _countAbandonMessage.Close(timestamp); } return abandonCount; } public bool ResumeLater<T>(T message) { string queueName; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcMsg; if (!_inProcessMessages.TryGetValue(message, out inProcMsg)) { return false; } queueName = inProcMsg.QueueName; } Put(queueName, message); return Delete(message); } public int ResumeLaterRange<T>(IEnumerable<T> messages) { return messages.Count(ResumeLater); } public void Persist<T>(T message, string storeName, string reason) { PersistRange(new[] { message }, storeName, reason); } public void PersistRange<T>(IEnumerable<T> messages, string storeName, string reason) { foreach (var message in messages) { // 1. GET MESSAGE FROM CHECK-OUT, SKIP IF NOT AVAILABLE/ALREADY DELETED CloudQueueMessage rawMessage; string queueName; byte[] data; lock (_sync) { // ignoring message if already deleted InProcessMessage inProcessMessage; if (!_inProcessMessages.TryGetValue(message, out inProcessMessage)) { continue; } queueName = inProcessMessage.QueueName; rawMessage = inProcessMessage.RawMessages[0]; data = inProcessMessage.Data; } // 2. PERSIST MESSAGE AND DELETE FROM QUEUE PersistRawMessage(rawMessage, data, queueName, storeName, reason); // 3. REMOVE MESSAGE FROM CHECK-OUT CheckInMessage(message); } } public IEnumerable<string> ListPersisted(string storeName) { var blobPrefix = PersistedMessageBlobName.GetPrefix(storeName); return _blobStorage.ListBlobNames(blobPrefix).Select(blobReference => blobReference.Key); } public Maybe<PersistedMessage> GetPersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if (!blob.HasValue) { return Maybe<PersistedMessage>.Empty; } var persistedMessage = blob.Value; var data = persistedMessage.Data; var dataXml = Maybe<XElement>.Empty; // 2. IF WRAPPED, UNWRAP; UNPACK XML IF SUPPORTED bool dataForRestorationAvailable; var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(data); if (messageWrapper.IsSuccess) { string ignored; dataXml = _blobStorage.GetBlobXml(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName, out ignored); // We consider data to be available only if we can access its blob's data // Simplification: we assume that if we can get the data as xml, then we can also get its binary data dataForRestorationAvailable = dataXml.HasValue; } else { var intermediateSerializer = _serializer as IIntermediateDataSerializer; if (intermediateSerializer != null) { using (var stream = new MemoryStream(data)) { var unpacked = intermediateSerializer.TryUnpackXml(stream); dataXml = unpacked.IsSuccess ? unpacked.Value : Maybe<XElement>.Empty; } } // The message is not wrapped (or unwrapping it failed). // No matter whether we can get the xml, we do have access to the binary data dataForRestorationAvailable = true; } // 3. RETURN return new PersistedMessage { QueueName = persistedMessage.QueueName, StoreName = storeName, Key = key, InsertionTime = persistedMessage.InsertionTime, PersistenceTime = persistedMessage.PersistenceTime, DequeueCount = persistedMessage.DequeueCount, Reason = persistedMessage.Reason, DataXml = dataXml, IsDataAvailable = dataForRestorationAvailable, }; } public void DeletePersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if (!blob.HasValue) { return; } var persistedMessage = blob.Value; // 2. IF WRAPPED, UNWRAP AND DELETE BLOB var messageWrapper = _serializer.TryDeserializeAs<MessageWrapper>(persistedMessage.Data); if (messageWrapper.IsSuccess) { _blobStorage.DeleteBlobIfExist(messageWrapper.Value.ContainerName, messageWrapper.Value.BlobName); } // 3. DELETE PERSISTED MESSAGE _blobStorage.DeleteBlobIfExist(blobReference); } public void RestorePersisted(string storeName, string key) { // 1. GET PERSISTED MESSAGE BLOB var blobReference = new PersistedMessageBlobName(storeName, key); var blob = _blobStorage.GetBlob(blobReference); if(!blob.HasValue) { return; } var persistedMessage = blob.Value; // 2. PUT MESSAGE TO QUEUE var queue = _queueStorage.GetQueueReference(persistedMessage.QueueName); var rawMessage = new CloudQueueMessage(persistedMessage.Data); PutRawMessage(rawMessage, queue); // 3. DELETE PERSISTED MESSAGE _blobStorage.DeleteBlobIfExist(blobReference); } void PersistRawMessage(CloudQueueMessage message, byte[] data, string queueName, string storeName, string reason) { var timestamp = _countPersistMessage.Open(); var queue = _queueStorage.GetQueueReference(queueName); // 1. PERSIST MESSAGE TO BLOB var blobReference = PersistedMessageBlobName.GetNew(storeName); var persistedMessage = new PersistedMessageData { QueueName = queueName, InsertionTime = message.InsertionTime.Value, PersistenceTime = DateTimeOffset.UtcNow, DequeueCount = message.DequeueCount, Reason = reason, Data = data, }; _blobStorage.PutBlob(blobReference, persistedMessage); // 2. DELETE MESSAGE FROM QUEUE DeleteRawMessage(message, queue); _countPersistMessage.Close(timestamp); } bool DeleteRawMessage(CloudQueueMessage message, CloudQueue queue) { try { _azureServerPolicy.Do(() => queue.DeleteMessage(message)); return true; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound) { return false; } var info = ex.ExtendedErrorInformation; if (info == null) { throw; } if (info.ErrorCode == QueueErrorCodeStrings.PopReceiptMismatch) { if (_log != null) { _log.WarnFormat("Cloud Storage: A message to be deleted in queue {0} was already remotely deleted or the invisibility timeout has elapsed.", queue.Name); } return false; } if (info.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return false; } throw; } } void PutRawMessage(CloudQueueMessage message, CloudQueue queue) { try { _azureServerPolicy.Do(() => queue.AddMessage(message)); } catch (StorageClientException ex) { // HACK: not storage status error code yet if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { // It usually takes time before the queue gets available // (the queue might also have been freshly deleted). AzurePolicies.SlowInstantiation.Do(() => { queue.Create(); queue.AddMessage(message); }); } else { throw; } } } void CheckOutMessage(object message, CloudQueueMessage rawMessage, byte[] data, string queueName, bool isOverflowing, int dequeueCount) { lock (_sync) { // If T is a value type, _inprocess could already contain the message // (not the same exact instance, but an instance that is value-equal to this one) InProcessMessage inProcessMessage; if (!_inProcessMessages.TryGetValue(message, out inProcessMessage)) { inProcessMessage = new InProcessMessage { QueueName = queueName, RawMessages = new List<CloudQueueMessage> {rawMessage}, Data = data, IsOverflowing = isOverflowing, DequeueCount = dequeueCount }; _inProcessMessages.Add(message, inProcessMessage); } else { inProcessMessage.RawMessages.Add(rawMessage); } } } void CheckOutRelink(object originalMessage, object newMessage) { lock (_sync) { var inProcessMessage = _inProcessMessages[originalMessage]; _inProcessMessages.Remove(originalMessage); _inProcessMessages.Add(newMessage, inProcessMessage); } } void CheckInMessage(object message) { lock (_sync) { var inProcessMessage = _inProcessMessages[message]; inProcessMessage.RawMessages.RemoveAt(0); if (0 == inProcessMessage.RawMessages.Count) { _inProcessMessages.Remove(message); } } } /// <summary> /// Deletes a queue. /// </summary> /// <returns><c>true</c> if the queue name has been actually deleted.</returns> /// <remarks> /// This implementation takes care of deleting overflowing blobs as /// well. /// </remarks> public bool DeleteQueue(string queueName) { try { // Caution: call to 'DeleteOverflowingMessages' comes first (BASE). DeleteOverflowingMessages(queueName); var queue = _queueStorage.GetQueueReference(queueName); _azureServerPolicy.Do(queue.Delete); return true; } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return false; } throw; } } /// <summary> /// Gets the approximate number of items in this queue. /// </summary> public int GetApproximateCount(string queueName) { try { var queue = _queueStorage.GetQueueReference(queueName); return _azureServerPolicy.Get(queue.RetrieveApproximateMessageCount); } catch (StorageClientException ex) { // if the queue does not exist, return 0 (no queue) if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return 0; } throw; } } /// <summary> /// Gets the approximate age of the top message of this queue. /// </summary> public Maybe<TimeSpan> GetApproximateLatency(string queueName) { var queue = _queueStorage.GetQueueReference(queueName); CloudQueueMessage rawMessage; try { rawMessage = _azureServerPolicy.Get(queue.PeekMessage); } catch (StorageClientException ex) { if (ex.ErrorCode == StorageErrorCode.ResourceNotFound || ex.ExtendedErrorInformation.ErrorCode == QueueErrorCodeStrings.QueueNotFound) { return Maybe<TimeSpan>.Empty; } throw; } if(rawMessage == null || !rawMessage.InsertionTime.HasValue) { return Maybe<TimeSpan>.Empty; } var latency = DateTimeOffset.UtcNow - rawMessage.InsertionTime.Value; // don't return negative values when clocks are slightly out of sync return latency > TimeSpan.Zero ? latency : TimeSpan.Zero; } } /// <summary>Represents a set of value-identical messages that are being processed by workers, /// i.e. were hidden from the queue because of calls to Get{T}.</summary> internal class InProcessMessage { /// <summary>Name of the queue where messages are originating from.</summary> public string QueueName { get; set; } /// <summary> /// The multiple, different raw <see cref="CloudQueueMessage" /> /// objects as returned from the queue storage. /// </summary> public List<CloudQueueMessage> RawMessages { get; set; } /// <summary> /// The unpacked message data. Can still be a message wrapper, but never an envelope. /// </summary> public byte[] Data { get; set; } /// <summary> /// A flag indicating whether the original message was bigger than the max /// allowed size and was therefore wrapped in <see cref="MessageWrapper" />. /// </summary> public bool IsOverflowing { get; set; } /// <summary> /// The number of times this message has already been dequeued, /// so we can track it safely even when abandoning it later /// </summary> public int DequeueCount { get; set; } } internal class OverflowingMessageBlobName<T> : BlobName<T> { public override string ContainerName { get { return QueueStorageProvider.OverflowingMessagesContainerName; } } /// <summary>Indicates the name of the queue where the message has been originally pushed.</summary> [Rank(0)] public string QueueName; /// <summary>Message identifiers as specified by the queue storage itself.</summary> [Rank(1)] public Guid MessageId; OverflowingMessageBlobName(string queueName, Guid guid) { QueueName = queueName; MessageId = guid; } /// <summary>Used to iterate over all the overflowing messages /// associated to a queue.</summary> public static OverflowingMessageBlobName<T> GetNew(string queueName) { return new OverflowingMessageBlobName<T>(queueName, Guid.NewGuid()); } } [DataContract] internal class PersistedMessageData { [DataMember(Order = 1)] public string QueueName { get; set; } [DataMember(Order = 2)] public DateTimeOffset InsertionTime { get; set; } [DataMember(Order = 3)] public DateTimeOffset PersistenceTime { get; set; } [DataMember(Order = 4)] public int DequeueCount { get; set; } [DataMember(Order = 5, IsRequired = false)] public string Reason { get; set; } [DataMember(Order = 6)] public byte[] Data { get; set; } } internal class PersistedMessageBlobName : BlobName<PersistedMessageData> { public override string ContainerName { get { return "lokad-cloud-persisted-messages"; } } /// <summary>Indicates the name of the swap out store where the message is persisted.</summary> [Rank(0)] public string StoreName; [Rank(1)] public string Key; public PersistedMessageBlobName(string storeName, string key) { StoreName = storeName; Key = key; } public static PersistedMessageBlobName GetNew(string storeName, string key) { return new PersistedMessageBlobName(storeName, key); } public static PersistedMessageBlobName GetNew(string storeName) { return new PersistedMessageBlobName(storeName, Guid.NewGuid().ToString("N")); } public static PersistedMessageBlobName GetPrefix(string storeName) { return new PersistedMessageBlobName(storeName, null); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/QueueStorageProvider.cs
C#
bsd
40,416
#region Copyright (c) Lokad 2010-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Data.Services.Client; using System.Diagnostics; using System.Linq; using System.Text; using System.Web; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Cloud.Storage.Shared.Policies; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>Implementation based on the Table Storage of Windows Azure.</summary> public class TableStorageProvider : ITableStorageProvider { // HACK: those tokens will probably be provided as constants in the StorageClient library const int MaxEntityTransactionCount = 100; // HACK: Lowering the maximal payload, to avoid corner cases #117 (ContentLengthExceeded) // [vermorel] 128kB is purely arbitrary, only taken as a reasonable safety margin const int MaxEntityTransactionPayload = 4 * 1024 * 1024 - 128 * 1024; // 4 MB - 128kB const string ContinuationNextRowKeyToken = "x-ms-continuation-NextRowKey"; const string ContinuationNextPartitionKeyToken = "x-ms-continuation-NextPartitionKey"; const string NextRowKeyToken = "NextRowKey"; const string NextPartitionKeyToken = "NextPartitionKey"; readonly CloudTableClient _tableStorage; readonly IDataSerializer _serializer; readonly ActionPolicy _storagePolicy; // Instrumentation readonly ExecutionCounter _countQuery; readonly ExecutionCounter _countInsert; readonly ExecutionCounter _countUpdate; readonly ExecutionCounter _countDelete; /// <summary>IoC constructor.</summary> public TableStorageProvider(CloudTableClient tableStorage, IDataSerializer serializer) { _tableStorage = tableStorage; _serializer = serializer; _storagePolicy = AzurePolicies.TransientTableErrorBackOff; // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countQuery = new ExecutionCounter("TableStorageProvider.QuerySegment", 0, 0), _countInsert = new ExecutionCounter("TableStorageProvider.InsertSlice", 0, 0), _countUpdate = new ExecutionCounter("TableStorageProvider.UpdateSlice", 0, 0), _countDelete = new ExecutionCounter("TableStorageProvider.DeleteSlice", 0, 0), }); } public bool CreateTable(string tableName) { var flag = false; AzurePolicies.SlowInstantiation.Do(() => flag = _tableStorage.CreateTableIfNotExist(tableName)); return flag; } public bool DeleteTable(string tableName) { var flag = false; AzurePolicies.SlowInstantiation.Do(() => flag = _tableStorage.DeleteTableIfExist(tableName)); return flag; } public IEnumerable<string> GetTables() { return _tableStorage.ListTables(); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName) { if(null == tableName) throw new ArgumentNullException("tableName"); var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, Maybe<string>.Empty); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if (partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char in partitionKey."); var filter = string.Format("(PartitionKey eq '{0}')", HttpUtility.UrlEncode(partitionKey)); var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, filter); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if (partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char."); if(startRowKey != null && startRowKey.Contains("'")) throw new ArgumentOutOfRangeException("startRowKey", "Incorrect char."); if(endRowKey != null && endRowKey.Contains("'")) throw new ArgumentOutOfRangeException("endRowKey", "Incorrect char."); var filter = string.Format("(PartitionKey eq '{0}')", HttpUtility.UrlEncode(partitionKey)); // optional starting range constraint if (!string.IsNullOrEmpty(startRowKey)) { // ge = GreaterThanOrEqual (inclusive) filter += string.Format(" and (RowKey ge '{0}')", HttpUtility.UrlEncode(startRowKey)); } if (!string.IsNullOrEmpty(endRowKey)) { // lt = LessThan (exclusive) filter += string.Format(" and (RowKey lt '{0}')", HttpUtility.UrlEncode(endRowKey)); } var context = _tableStorage.GetDataServiceContext(); return GetInternal<T>(context, tableName, filter); } public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { if(null == tableName) throw new ArgumentNullException("tableName"); if(null == partitionKey) throw new ArgumentNullException("partitionKey"); if(partitionKey.Contains("'")) throw new ArgumentOutOfRangeException("partitionKey", "Incorrect char."); var context = _tableStorage.GetDataServiceContext(); foreach (var slice in Slice(rowKeys, MaxEntityTransactionCount)) { // work-around the limitation of ADO.NET that does not provide a native way // of query a set of specified entities directly. var builder = new StringBuilder(); builder.Append(string.Format("(PartitionKey eq '{0}') and (", HttpUtility.UrlEncode(partitionKey))); for (int i = 0; i < slice.Length; i++) { // in order to avoid SQL-injection-like problems if (slice[i].Contains("'")) throw new ArgumentOutOfRangeException("rowKeys", "Incorrect char."); builder.Append(string.Format("(RowKey eq '{0}')", HttpUtility.UrlEncode(slice[i]))); if (i < slice.Length - 1) { builder.Append(" or "); } } builder.Append(")"); foreach(var entity in GetInternal<T>(context, tableName, builder.ToString())) { yield return entity; } } } private IEnumerable<CloudEntity<T>> GetInternal<T>(TableServiceContext context, string tableName, Maybe<string> filter) { string continuationRowKey = null; string continuationPartitionKey = null; var timestamp = _countQuery.Open(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; do { var query = context.CreateQuery<FatEntity>(tableName); if (filter.HasValue) { query = query.AddQueryOption("$filter", filter.Value); } if (null != continuationRowKey) { query = query.AddQueryOption(NextRowKeyToken, continuationRowKey) .AddQueryOption(NextPartitionKeyToken, continuationPartitionKey); } QueryOperationResponse response = null; FatEntity[] fatEntities = null; _storagePolicy.Do(() => { try { response = query.Execute() as QueryOperationResponse; fatEntities = ((IEnumerable<FatEntity>)response).ToArray(); } catch (DataServiceQueryException ex) { // if the table does not exist, there is nothing to return var errorCode = AzurePolicies.GetErrorCode(ex); if (TableErrorCodeStrings.TableNotFound == errorCode || StorageErrorCodeStrings.ResourceNotFound == errorCode) { fatEntities = new FatEntity[0]; return; } throw; } }); _countQuery.Close(timestamp); foreach (var fatEntity in fatEntities) { var etag = context.Entities.First(e => e.Entity == fatEntity).ETag; context.Detach(fatEntity); yield return FatEntity.Convert<T>(fatEntity, _serializer, etag); } Debug.Assert(context.Entities.Count == 0); if (null != response && response.Headers.ContainsKey(ContinuationNextRowKeyToken)) { continuationRowKey = response.Headers[ContinuationNextRowKeyToken]; continuationPartitionKey = response.Headers[ContinuationNextPartitionKeyToken]; timestamp = _countQuery.Open(); } else { continuationRowKey = null; continuationPartitionKey = null; } } while (null != continuationRowKey); } public void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { InsertInternal(tableName, g); } } void InsertInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { var context = _tableStorage.GetDataServiceContext(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; var fatEntities = entities.Select(e => Tuple.Create(FatEntity.Convert(e, _serializer), e)); var noBatchMode = false; foreach (var slice in SliceEntities(fatEntities, e => e.Item1.GetPayload())) { var timestamp = _countInsert.Open(); var cloudEntityOfFatEntity = new Dictionary<object, CloudEntity<T>>(); foreach (var fatEntity in slice) { context.AddObject(tableName, fatEntity.Item1); cloudEntityOfFatEntity.Add(fatEntity.Item1, fatEntity.Item2); } _storagePolicy.Do(() => { try { // HACK: nested try/catch try { context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); } // special casing the need for table instantiation catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == TableErrorCodeStrings.TableNotFound || errorCode == StorageErrorCodeStrings.ResourceNotFound) { AzurePolicies.SlowInstantiation.Do(() => { try { _tableStorage.CreateTableIfNotExist(tableName); } // HACK: incorrect behavior of the StorageClient (2010-09) // Fails to behave properly in multi-threaded situations catch (StorageClientException cex) { if (cex.ExtendedErrorInformation == null || cex.ExtendedErrorInformation.ErrorCode != TableErrorCodeStrings.TableAlreadyExists) { throw; } } context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); }); } else { throw; } } } catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } // HACK: undocumented code returned by the Table Storage else if (errorCode == "ContentLengthExceeded") { context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } catch (DataServiceQueryException ex) { // HACK: code dupplicated var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } }); _countInsert.Close(timestamp); } } public void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { UpdateInternal(tableName, g, force); } } void UpdateInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { var context = _tableStorage.GetDataServiceContext(); context.MergeOption = MergeOption.AppendOnly; context.ResolveType = ResolveFatEntityType; var fatEntities = entities.Select(e => Tuple.Create(FatEntity.Convert(e, _serializer), e)); var noBatchMode = false; foreach (var slice in SliceEntities(fatEntities, e => e.Item1.GetPayload())) { var timestamp = _countUpdate.Open(); var cloudEntityOfFatEntity = new Dictionary<object, CloudEntity<T>>(); foreach (var fatEntity in slice) { // entities should be updated in a single round-trip context.AttachTo(tableName, fatEntity.Item1, MapETag(fatEntity.Item2.ETag, force)); context.UpdateObject(fatEntity.Item1); cloudEntityOfFatEntity.Add(fatEntity.Item1, fatEntity.Item2); } _storagePolicy.Do(() => { try { context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); } catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else if (errorCode == TableErrorCodeStrings.TableNotFound) { AzurePolicies.SlowInstantiation.Do(() => { try { _tableStorage.CreateTableIfNotExist(tableName); } // HACK: incorrect behavior of the StorageClient (2010-09) // Fails to behave properly in multi-threaded situations catch (StorageClientException cex) { if (cex.ExtendedErrorInformation.ErrorCode != TableErrorCodeStrings.TableAlreadyExists) { throw; } } context.SaveChanges(noBatchMode ? SaveChangesOptions.None : SaveChangesOptions.Batch); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); }); } else { throw; } } catch (DataServiceQueryException ex) { // HACK: code dupplicated var errorCode = AzurePolicies.GetErrorCode(ex); if (errorCode == StorageErrorCodeStrings.OperationTimedOut) { // if batch does not work, then split into elementary requests // PERF: it would be better to split the request in two and retry context.SaveChanges(); ReadETagsAndDetach(context, (entity, etag) => cloudEntityOfFatEntity[entity].ETag = etag); noBatchMode = true; } else { throw; } } }); _countUpdate.Close(timestamp); } } public void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { UpsertInternal(tableName, g); } } // HACK: no 'upsert' (update or insert) available at the time // http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/4b902237-7cfb-4d48-941b-4802864fc274 /// <remarks>Upsert is making several storage calls to emulate the /// missing semantic from the Table Storage.</remarks> void UpsertInternal<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { // checking for entities that already exist var partitionKey = entities.First().PartitionKey; var existingKeys = new HashSet<string>( Get<T>(tableName, partitionKey, entities.Select(e => e.RowKey)).Select(e => e.RowKey)); // inserting or updating depending on the presence of the keys Insert(tableName, entities.Where(e => !existingKeys.Contains(e.RowKey))); Update(tableName, entities.Where(e => existingKeys.Contains(e.RowKey)), true); } /// <summary>Slice entities according the payload limitation of /// the transaction group, plus the maximal number of entities to /// be embedded into a single transaction.</summary> static IEnumerable<T[]> SliceEntities<T>(IEnumerable<T> entities, Func<T, int> getPayload) { var accumulator = new List<T>(100); var payload = 0; foreach (var entity in entities) { var entityPayLoad = getPayload(entity); if (accumulator.Count >= MaxEntityTransactionCount || payload + entityPayLoad >= MaxEntityTransactionPayload) { yield return accumulator.ToArray(); accumulator.Clear(); payload = 0; } accumulator.Add(entity); payload += entityPayLoad; } if (accumulator.Count > 0) { yield return accumulator.ToArray(); } } public void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { DeleteInternal<T>(tableName, partitionKey, rowKeys.Select(k => Tuple.Create(k, "*")), true); } public void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { foreach (var g in entities.GroupBy(e => e.PartitionKey)) { DeleteInternal<T>(tableName, g.Key, g.Select(e => Tuple.Create(e.RowKey, MapETag(e.ETag, force))), force); } } void DeleteInternal<T>(string tableName, string partitionKey, IEnumerable<Tuple<string,string>> rowKeysAndETags, bool force) { var context = _tableStorage.GetDataServiceContext(); // CAUTION: make sure to get rid of potential duplicate in rowkeys. // (otherwise insertion in 'context' is likely to fail) foreach (var s in Slice(rowKeysAndETags // Similar effect than 'Distinct' based on 'RowKey' .ToLookup(p => p.Item1, p => p).Select(g => g.First()), MaxEntityTransactionCount)) { var timestamp = _countDelete.Open(); var slice = s; DeletionStart: // 'slice' might have been refreshed if some entities were already deleted foreach (var rowKeyAndETag in slice) { // Deleting entities in 1 roundtrip // http://blog.smarx.com/posts/deleting-entities-from-windows-azure-without-querying-first var mock = new FatEntity { PartitionKey = partitionKey, RowKey = rowKeyAndETag.Item1 }; context.AttachTo(tableName, mock, rowKeyAndETag.Item2); context.DeleteObject(mock); } try // HACK: [vermorel] if a single entity is missing, then the whole batch operation is aborded { try // HACK: nested try/catch to handle the special case where the table is missing { _storagePolicy.Do(() => context.SaveChanges(SaveChangesOptions.Batch)); } catch (DataServiceRequestException ex) { // if the table is missing, no need to go on with the deletion var errorCode = AzurePolicies.GetErrorCode(ex); if (TableErrorCodeStrings.TableNotFound == errorCode) { _countDelete.Close(timestamp); return; } throw; } } // if some entities exist catch (DataServiceRequestException ex) { var errorCode = AzurePolicies.GetErrorCode(ex); // HACK: Table Storage both implement a bizarre non-idempotent semantic // but in addition, it throws a non-documented exception as well. if (errorCode != "ResourceNotFound") { throw; } slice = Get<T>(tableName, partitionKey, slice.Select(p => p.Item1)) .Select(e => Tuple.Create(e.RowKey, MapETag(e.ETag, force))).ToArray(); // entities with same name will be added again context = _tableStorage.GetDataServiceContext(); // HACK: [vermorel] yes, gotos are horrid, but other solutions are worst here. goto DeletionStart; } _countDelete.Close(timestamp); } } static Type ResolveFatEntityType(string name) { return typeof (FatEntity); } static string MapETag(string etag, bool force) { return force || string.IsNullOrEmpty(etag) ? "*" : etag; } static void ReadETagsAndDetach(DataServiceContext context, Action<object, string> write) { foreach (var entity in context.Entities) { write(entity.Entity, entity.ETag); context.Detach(entity.Entity); } } /// <summary> /// Performs lazy splitting of the provided collection into collections of <paramref name="sliceLength"/> /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <param name="source">The source.</param> /// <param name="sliceLength">Maximum length of the slice.</param> /// <returns>lazy enumerator of the collection of arrays</returns> public static IEnumerable<TItem[]> Slice<TItem>(IEnumerable<TItem> source, int sliceLength) { if (source == null) throw new ArgumentNullException("source"); if (sliceLength <= 0) throw new ArgumentOutOfRangeException("sliceLength", "value must be greater than 0"); var list = new List<TItem>(sliceLength); foreach (var item in source) { list.Add(item); if (sliceLength == list.Count) { yield return list.ToArray(); list.Clear(); } } if (list.Count > 0) yield return list.ToArray(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/TableStorageProvider.cs
C#
bsd
30,326
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Storage.Azure { /// <summary> /// Exception indicating that received data has been detected to be corrupt or altered. /// </summary> [Serializable] public class DataCorruptionException : Exception { public DataCorruptionException() { } public DataCorruptionException(string message) : base(message) { } public DataCorruptionException(string message, Exception inner) : base(message, inner) { } protected DataCorruptionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/DataCorruptionException.cs
C#
bsd
812
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Linq; using System.Data.Services.Client; using System.Net; using System.Text.RegularExpressions; using System.Threading; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Diagnostics; using Microsoft.WindowsAzure.StorageClient; using Lokad.Cloud.Storage.Shared.Policies; namespace Lokad.Cloud.Storage.Azure { /// <summary> /// Azure retry policies for corner-situation and server errors. /// </summary> public static class AzurePolicies { /// <summary> /// Retry policy to temporarily back off in case of transient Azure server /// errors, system overload or in case the denial of service detection system /// thinks we're a too heavy user. Blocks the thread while backing off to /// prevent further requests for a while (per thread). /// </summary> public static Shared.Policies.ActionPolicy TransientServerErrorBackOff { get; private set; } /// <summary>Similar to <see cref="TransientServerErrorBackOff"/>, yet /// the Table Storage comes with its own set or exceptions/.</summary> public static Shared.Policies.ActionPolicy TransientTableErrorBackOff { get; private set; } /// <summary> /// Very patient retry policy to deal with container, queue or table instantiation /// that happens just after a deletion. /// </summary> public static Shared.Policies.ActionPolicy SlowInstantiation { get; private set; } /// <summary> /// Limited retry related to MD5 validation failure. /// </summary> public static Shared.Policies.ActionPolicy NetworkCorruption { get; private set; } /// <summary> /// Retry policy for optimistic concurrency retrials. The exception parameter is ignored, it can be null. /// </summary> public static ShouldRetry OptimisticConcurrency() { var random = new Random(); return delegate(int currentRetryCount, Exception lastException, out TimeSpan retryInterval) { retryInterval = TimeSpan.FromMilliseconds(random.Next(Math.Min(10000, 10 + currentRetryCount * currentRetryCount * 10))); return currentRetryCount <= 30; }; } // Instrumentation static readonly ExecutionCounter CountOnTransientServerError; static readonly ExecutionCounter CountOnTransientTableError; static readonly ExecutionCounter CountOnSlowInstantiation; static readonly ExecutionCounter CountOnNetworkCorruption; /// <summary> /// Static Constructor /// </summary> static AzurePolicies() { // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { CountOnTransientServerError = new ExecutionCounter("Policies.ServerErrorRetryWait", 0, 0), CountOnTransientTableError = new ExecutionCounter("Policies.TableErrorRetryWait", 0, 0), CountOnSlowInstantiation = new ExecutionCounter("Policies.SlowInstantiationRetryWait", 0, 0), CountOnNetworkCorruption = new ExecutionCounter("Policies.NetworkCorruption", 0, 0) }); // Initialize Policies TransientServerErrorBackOff = Shared.Policies.ActionPolicy.With(TransientServerErrorExceptionFilter) .Retry(30, OnTransientServerErrorRetry); TransientTableErrorBackOff = Shared.Policies.ActionPolicy.With(TransientTableErrorExceptionFilter) .Retry(30, OnTransientTableErrorRetry); SlowInstantiation = Shared.Policies.ActionPolicy.With(SlowInstantiationExceptionFilter) .Retry(30, OnSlowInstantiationRetry); NetworkCorruption = Shared.Policies.ActionPolicy.With(NetworkCorruptionExceptionFilter) .Retry(2, OnNetworkCorruption); } static void OnTransientServerErrorRetry(Exception exception, int count) { // NOTE: we can't log here, since logging would fail as well var timestamp = CountOnTransientServerError.Open(); // quadratic backoff, capped at 5 minutes var c = count + 1; Thread.Sleep(TimeSpan.FromSeconds(Math.Min(300, c*c))); CountOnTransientServerError.Close(timestamp); } static void OnTransientTableErrorRetry(Exception exception, int count) { // NOTE: we can't log here, since logging would fail as well var timestamp = CountOnTransientTableError.Open(); // quadratic backoff, capped at 5 minutes var c = count + 1; Thread.Sleep(TimeSpan.FromSeconds(Math.Min(300, c * c))); CountOnTransientTableError.Close(timestamp); } static void OnSlowInstantiationRetry(Exception exception, int count) { var timestamp = CountOnSlowInstantiation.Open(); // linear backoff Thread.Sleep(TimeSpan.FromMilliseconds(100 * count)); CountOnSlowInstantiation.Close(timestamp); } static void OnNetworkCorruption(Exception exception, int count) { var timestamp = CountOnNetworkCorruption.Open(); // no backoff, retry immediately CountOnNetworkCorruption.Close(timestamp); } static bool IsErrorCodeMatch(StorageException exception, params StorageErrorCode[] codes) { return exception != null && codes.Contains(exception.ErrorCode); } static bool IsErrorStringMatch(StorageException exception, params string[] errorStrings) { return exception != null && exception.ExtendedErrorInformation != null && errorStrings.Contains(exception.ExtendedErrorInformation.ErrorCode); } static bool IsErrorStringMatch(string exceptionErrorString, params string[] errorStrings) { return errorStrings.Contains(exceptionErrorString); } static bool TransientServerErrorExceptionFilter(Exception exception) { var serverException = exception as StorageServerException; if (serverException != null) { if (IsErrorCodeMatch(serverException, StorageErrorCode.ServiceInternalError, StorageErrorCode.ServiceTimeout)) { return true; } if (IsErrorStringMatch(serverException, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut)) { return true; } return false; } // HACK: StorageClient does not catch internal errors very well. // Hence we end up here manually catching exception that should have been correctly // typed by the StorageClient: // System.Net.InternalException is internal, but uncaught on some race conditions. // We therefore assume this is a transient error and retry. var exceptionType = exception.GetType(); if (exceptionType.FullName == "System.Net.InternalException") { return true; } return false; } static bool TransientTableErrorExceptionFilter(Exception exception) { var dataServiceRequestException = exception as DataServiceRequestException; if (dataServiceRequestException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceRequestException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } var dataServiceQueryException = exception as DataServiceQueryException; if (dataServiceQueryException != null) { if (IsErrorStringMatch(GetErrorCode(dataServiceQueryException), StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, StorageErrorCodeStrings.OperationTimedOut, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } // HACK: StorageClient does not catch internal errors very well. // Hence we end up here manually catching exception that should have been correctly // typed by the StorageClient: // The remote server returned an error: (500) Internal Server Error. var webException = exception as WebException; if (null != webException && (webException.Status == WebExceptionStatus.ProtocolError || webException.Status == WebExceptionStatus.ConnectionClosed)) { return true; } // System.Net.InternalException is internal, but uncaught on some race conditions. // We therefore assume this is a transient error and retry. var exceptionType = exception.GetType(); if (exceptionType.FullName == "System.Net.InternalException") { return true; } return false; } static bool SlowInstantiationExceptionFilter(Exception exception) { var storageException = exception as StorageClientException; // Blob Storage or Queue Storage exceptions // Table Storage may throw exception of type 'StorageClientException' if (storageException != null) { // 'client' exceptions reflect server-side problems (delayed instantiation) if (IsErrorCodeMatch(storageException, StorageErrorCode.ResourceNotFound, StorageErrorCode.ContainerNotFound)) { return true; } if (IsErrorStringMatch(storageException, QueueErrorCodeStrings.QueueNotFound, QueueErrorCodeStrings.QueueBeingDeleted, StorageErrorCodeStrings.InternalError, StorageErrorCodeStrings.ServerBusy, TableErrorCodeStrings.TableServerOutOfMemory, TableErrorCodeStrings.TableNotFound, TableErrorCodeStrings.TableBeingDeleted)) { return true; } } // Table Storage may also throw exception of type 'DataServiceQueryException'. var dataServiceException = exception as DataServiceQueryException; if (null != dataServiceException) { if (IsErrorStringMatch(GetErrorCode(dataServiceException), TableErrorCodeStrings.TableBeingDeleted, TableErrorCodeStrings.TableNotFound, TableErrorCodeStrings.TableServerOutOfMemory)) { return true; } } return false; } static bool NetworkCorruptionExceptionFilter(Exception exception) { // Upload MD5 mismatch var clientException = exception as StorageClientException; if (clientException != null && clientException.ErrorCode == StorageErrorCode.BadRequest && clientException.ExtendedErrorInformation != null && clientException.ExtendedErrorInformation.ErrorCode == StorageErrorCodeStrings.InvalidHeaderValue && clientException.ExtendedErrorInformation.AdditionalDetails["HeaderName"] == "Content-MD5") { // network transport corruption (automatic), try again return true; } // Download MD5 mismatch if (exception is DataCorruptionException) { // network transport corruption (manual), try again return true; } return false; } public static string GetErrorCode(DataServiceRequestException ex) { var r = new Regex(@"<code>(\w+)</code>", RegexOptions.IgnoreCase); var match = r.Match(ex.InnerException.Message); return match.Groups[1].Value; } // HACK: just dupplicating the other overload of 'GetErrorCode' public static string GetErrorCode(DataServiceQueryException ex) { var r = new Regex(@"<code>(\w+)</code>", RegexOptions.IgnoreCase); var match = r.Match(ex.InnerException.Message); return match.Groups[1].Value; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/AzurePolicies.cs
C#
bsd
13,683
#region Copyright (c) Lokad 2010-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using Lokad.Cloud.Storage.Shared; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>This entity is basically a workaround the 64KB limitation /// for entity properties. 15 properties represents a total storage /// capability of 960KB (entity limit is at 1024KB).</summary> /// <remarks>This class is basically a hack against the Table Storage /// to work-around the 64KB limitation for properties.</remarks> public class FatEntity : TableServiceEntity { /// <summary> /// Maximal entity size is 1MB. Out of that, we keep only /// 960kb (1MB - 64kb as a safety margin). Then, it should be taken /// into account that byte[] are Base64 encoded which represent /// a penalty overhead of 4/3 - hence the reduced capacity. /// </summary> public const int MaxByteCapacity = (960 * 1024 * 3) / 4; // ReSharper disable InconsistentNaming // ReSharper disable MemberCanBePrivate.Global public byte[] P0 { get; set; } public byte[] P1 { get; set; } public byte[] P2 { get; set; } public byte[] P3 { get; set; } public byte[] P4 { get; set; } public byte[] P5 { get; set; } public byte[] P6 { get; set; } public byte[] P7 { get; set; } public byte[] P8 { get; set; } public byte[] P9 { get; set; } public byte[] P10 { get; set; } public byte[] P11 { get; set; } public byte[] P12 { get; set; } public byte[] P13 { get; set; } public byte[] P14 { get; set; } IEnumerable<byte[]> GetProperties() { if (null != P0) yield return P0; if (null != P1) yield return P1; if (null != P2) yield return P2; if (null != P3) yield return P3; if (null != P4) yield return P4; if (null != P5) yield return P5; if (null != P6) yield return P6; if (null != P7) yield return P7; if (null != P8) yield return P8; if (null != P9) yield return P9; if (null != P10) yield return P10; if (null != P11) yield return P11; if (null != P12) yield return P12; if (null != P13) yield return P13; if (null != P14) yield return P14; } public byte[] GetData() { var arrays = GetProperties().ToArray(); var buffer = new byte[arrays.Sum(a => a.Length)]; var i = 0; foreach (var array in arrays) { Buffer.BlockCopy(array, 0, buffer, i, array.Length); i += array.Length; } return buffer; } public void SetData(byte[] data) { if(null == data) throw new ArgumentNullException("data"); if(data.Length >= MaxByteCapacity) throw new ArgumentOutOfRangeException("data"); var setters = new Action<byte[]>[] { b => P0 = b, b => P1 = b, b => P2 = b, b => P3 = b, b => P4 = b, b => P5 = b, b => P6 = b, b => P7 = b, b => P8 = b, b => P9 = b, b => P10 = b, b => P11 = b, b => P12 = b, b => P13 = b, b => P14 = b, }; for (int i = 0; i < 15; i++) { if (i * 64 * 1024 < data.Length) { var start = i * 64 * 1024; var length = Math.Min(64 * 1024, data.Length - start); var buffer = new byte[length]; Buffer.BlockCopy(data, start, buffer, 0, buffer.Length); setters[i](buffer); } else { setters[i](null); // discarding potential leftover } } } /// <summary>Returns an upper bound approximation of the payload associated to /// the entity once serialized as XML Atom (used for communication with the /// Table Storage).</summary> public int GetPayload() { // measurements indicates overhead is closer to 1300 chars, but we take a bit of margin const int envelopOverhead = 1500; // Caution: there is a loss when converting byte[] to Base64 representation var binCharCount = (GetProperties().Sum(a => a.Length) * 4 + 3) / 3; var partitionKeyCount = PartitionKey.Length; var rowKeyCount = RowKey.Length; // timestamp is already accounted for in the envelop overhead. return binCharCount + partitionKeyCount + rowKeyCount + envelopOverhead; } /// <summary>Converts a <c>FatEntity</c> toward a <c>CloudEntity</c>.</summary> public static CloudEntity<T> Convert<T>(FatEntity fatEntity, IDataSerializer serializer, string etag) { using (var stream = new MemoryStream(fatEntity.GetData()) { Position = 0 }) { var val = (T)serializer.Deserialize(stream, typeof(T)); return new CloudEntity<T> { PartitionKey = fatEntity.PartitionKey, RowKey = fatEntity.RowKey, Timestamp = fatEntity.Timestamp, ETag = etag, Value = val }; } } /// <summary>Converts a <c>CloudEntity</c> toward a <c>FatEntity</c>.</summary> public static FatEntity Convert<T>(CloudEntity<T> cloudEntity, IDataSerializer serializer) { var fatEntity = new FatEntity { PartitionKey = cloudEntity.PartitionKey, RowKey = cloudEntity.RowKey, Timestamp = cloudEntity.Timestamp }; using (var stream = new MemoryStream()) { serializer.Serialize(cloudEntity.Value, stream); fatEntity.SetData(stream.ToArray()); return fatEntity; } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Storage/Azure/FatEntity.cs
C#
bsd
6,799
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Runtime; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.ServiceFabric.Runtime; namespace Lokad.Cloud.Services { /// <summary> /// Checks for updated assemblies or configuration and restarts the runtime if needed. /// </summary> [ScheduledServiceSettings( AutoStart = true, TriggerInterval = 60, // 1 execution every 1 minute Description = "Checks for and applies assembly and configuration updates.", ProcessingTimeoutSeconds = 5 * 60, // timeout after 5 minutes SchedulePerWorker = true)] public class AssemblyConfigurationUpdateService : ScheduledService { readonly AssemblyLoader _assemblyLoader; public AssemblyConfigurationUpdateService(RuntimeProviders runtimeProviders) { // NOTE: we can't use the BlobStorage as provided by the base class // as this is not available at constructur time, but we want to reset // the status as soon as possible to avoid missing any changes _assemblyLoader = new AssemblyLoader(runtimeProviders); _assemblyLoader.ResetUpdateStatus(); } protected override void StartOnSchedule() { _assemblyLoader.CheckUpdate(false); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Services/AssemblyConfigurationUpdateService.cs
C#
bsd
1,481
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Services { /// <summary> /// Garbage collects temporary items stored in the <see cref="CloudService.TemporaryContainer"/>. /// </summary> /// <remarks> /// The container <see cref="CloudService.TemporaryContainer"/> is handy to /// store non-persistent data, typically state information concerning ongoing /// processing. /// </remarks> [ScheduledServiceSettings( AutoStart = true, Description = "Garbage collects temporary items.", TriggerInterval = 60)] // 1 execution every 1min public class GarbageCollectorService : ScheduledService { static TimeSpan MaxExecutionTime { get { return TimeSpan.FromMinutes(10); } } protected override void StartOnSchedule() { const string containerName = TemporaryBlobName<object>.DefaultContainerName; var executionExpiration = DateTimeOffset.UtcNow.Add(MaxExecutionTime); // lazy enumeration over the overflowing messages foreach (var blobName in BlobStorage.ListBlobNames(containerName)) { // HACK: targeted object is irrelevant var parsedName = UntypedBlobName.Parse<TemporaryBlobName<object>>(blobName); if (DateTimeOffset.UtcNow <= parsedName.Expiration) { // overflowing messages are iterated in date-increasing order // as soon a non-expired overflowing message is encountered // just stop the process. break; } // if the overflowing message is expired, delete it BlobStorage.DeleteBlobIfExist(containerName, blobName); // don't freeze the worker with this service if (DateTimeOffset.UtcNow > executionExpiration) { break; } } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Services/GarbageCollectorService.cs
C#
bsd
1,894
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Diagnostics; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Services { /// <summary> /// Collects and persists monitoring statistics. /// </summary> [ScheduledServiceSettings( AutoStart = true, TriggerInterval = 2 * 60, // 1 execution every 2min SchedulePerWorker = true, Description = "Collects and persists monitoring statistics.")] public class MonitoringService : ScheduledService { readonly DiagnosticsAcquisition _diagnosticsAcquisition; public MonitoringService(DiagnosticsAcquisition diagnosticsAcquisition) { _diagnosticsAcquisition = diagnosticsAcquisition; } /// <summary>Called by the framework.</summary> protected override void StartOnSchedule() { _diagnosticsAcquisition.CollectStatistics(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Services/MonitoringService.cs
C#
bsd
969
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.Shared.Logging; // HACK: the delayed queue service does not provide a scalable iteration pattern. // (single instance iterating over the delayed message) namespace Lokad.Cloud.Services { /// <summary>Routinely checks for expired delayed messages that needs to /// be put in queue for immediate consumption.</summary> [ScheduledServiceSettings( AutoStart = true, Description = "Checks for expired delayed messages to be put in regular queue.", TriggerInterval = 15)] // 15s public class DelayedQueueService : ScheduledService { protected override void StartOnSchedule() { // lazy enumeration over the delayed messages foreach (var parsedName in BlobStorage.ListBlobNames(new DelayedMessageName())) { if (DateTimeOffset.UtcNow <= parsedName.TriggerTime) { // delayed messages are iterated in date-increasing order // as soon a non-expired delayed message is encountered // just stop the process. break; } var dm = BlobStorage.GetBlob(parsedName); if (!dm.HasValue) { Log.WarnFormat("Deserialization failed for delayed message {0}, message was dropped.", parsedName.Identifier); continue; } QueueStorage.Put(dm.Value.QueueName, dm.Value.InnerMessage); BlobStorage.DeleteBlobIfExist(parsedName); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Services/DelayedQueueService.cs
C#
bsd
1,597
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Diagnostics; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Services { /// <summary> /// Removes monitoring statistics after a retention period of 24 segments each. /// </summary> [ScheduledServiceSettings( AutoStart = true, TriggerInterval = 6 * 60 * 60, // 1 execution every 6 hours Description = "Removes old monitoring statistics.")] public class MonitoringDataRetentionService : ScheduledService { readonly DiagnosticsAcquisition _diagnosticsAcquisition; public MonitoringDataRetentionService(DiagnosticsAcquisition diagnosticsAcquisition) { _diagnosticsAcquisition = diagnosticsAcquisition; } /// <summary>Called by the framework.</summary> protected override void StartOnSchedule() { _diagnosticsAcquisition.RemoveStatisticsBefore(24); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Services/MonitoringDataRetentionService.cs
C#
bsd
999
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security; using System.Xml.XPath; using Lokad.Cloud.Storage; // TODO: clean-up the 'Storage.Shared.Logging.' type prefix once Lokad.Shared is removed. namespace Lokad.Cloud.Diagnostics { /// <summary> /// Log entry (when retrieving logs with the <see cref="CloudLogger"/>). /// </summary> public class LogEntry { public DateTime DateTimeUtc { get; set; } public string Level { get; set; } public string Message { get; set; } public string Error { get; set; } public string Source { get; set; } } /// <summary> /// Logger built on top of the Blob Storage. /// </summary> /// <remarks> /// <para> /// Logs are formatted in XML with /// <code> /// &lt;log&gt; /// &lt;message&gt; {0} &lt;/message&gt; /// &lt;error&gt; {1} &lt;/error&gt; /// &lt;/log&gt; /// </code> /// Also, the logger is relying on date prefix in order to facilitate large /// scale enumeration of the logs. Yet, in order to facilitate fast enumeration /// of recent logs, a prefix inversion trick is used. /// </para> /// <para> /// We put entries to different containers depending on the log level. This helps /// reading only interesting entries and easily skipping those below the threshold. /// An entry is put to one container matching the level only, not to all containers /// with the matching or a lower level. This is a tradeoff to avoid optimizing /// for read spead at the cost of write speed, because we assume more frequent /// writes than reads and, more importantly, writes to happen in time-critical /// code paths while reading is almost never time-critical. /// </para> /// </remarks> public class CloudLogger : Storage.Shared.Logging.ILog { private const string ContainerNamePrefix = "lokad-cloud-logs"; private const int DeleteBatchSize = 50; private readonly IBlobStorageProvider _blobStorage; private readonly string _source; /// <summary>Minimal log level (inclusive), below this level, /// notifications are ignored.</summary> public Storage.Shared.Logging.LogLevel LogLevelThreshold { get; set; } public CloudLogger(IBlobStorageProvider blobStorage, string source) { _blobStorage = blobStorage; _source = source; LogLevelThreshold = Storage.Shared.Logging.LogLevel.Min; } public bool IsEnabled(Storage.Shared.Logging.LogLevel level) { return level >= LogLevelThreshold; } public void Log(Storage.Shared.Logging.LogLevel level, object message) { Log(level, null, message); } public void Log(Storage.Shared.Logging.LogLevel level, Exception ex, object message) { if (!IsEnabled(level)) { return; } var now = DateTime.UtcNow; var logEntry = new LogEntry { DateTimeUtc = now, Level = level.ToString(), Message = message.ToString(), Error = ex != null ? ex.ToString() : string.Empty, Source = _source ?? string.Empty }; var blobContent = FormatLogEntry(logEntry); var blobName = string.Format("{0}/{1}/", FormatDateTimeNamePrefix(logEntry.DateTimeUtc), logEntry.Level); var blobContainer = LevelToContainer(level); var attempt = 0; while (!_blobStorage.PutBlob(blobContainer, blobName + attempt, blobContent, false)) { attempt++; } } /// <summary> /// Lazily enuerate all logs of the specified level, ordered with the newest entry first. /// </summary> public IEnumerable<LogEntry> GetLogsOfLevel(Storage.Shared.Logging.LogLevel level, int skip = 0) { return _blobStorage .ListBlobs<string>(LevelToContainer(level), skip: skip) .Select(ParseLogEntry); } /// <summary> /// Lazily enuerate all logs of the specified level or higher, ordered with the newest entry first. /// </summary> public IEnumerable<LogEntry> GetLogsOfLevelOrHigher(Storage.Shared.Logging.LogLevel levelThreshold, int skip = 0) { // We need to sort by date (desc), but want to do it lazily based on // the guarantee that the enumerators themselves are ordered alike. // To do that we always select the newest value, move next, and repeat. var enumerators = Enum.GetValues(typeof(Storage.Shared.Logging.LogLevel)).OfType<Storage.Shared.Logging.LogLevel>() .Where(l => l >= levelThreshold && l < Storage.Shared.Logging.LogLevel.Max && l > Storage.Shared.Logging.LogLevel.Min) .Select(level => { var containerName = LevelToContainer(level); return _blobStorage.ListBlobNames(containerName, string.Empty) .Select(blobName => System.Tuple.Create(containerName, blobName)) .GetEnumerator(); }) .ToList(); for (var i = enumerators.Count - 1; i >= 0; i--) { if (!enumerators[i].MoveNext()) { enumerators.RemoveAt(i); } } // Skip for (var i = skip; i > 0 && enumerators.Count > 0; i--) { var max = enumerators.Aggregate((left, right) => string.Compare(left.Current.Item2, right.Current.Item2) < 0 ? left : right); if (!max.MoveNext()) { enumerators.Remove(max); } } // actual iterator while (enumerators.Count > 0) { var max = enumerators.Aggregate((left, right) => string.Compare(left.Current.Item2, right.Current.Item2) < 0 ? left : right); var blob = _blobStorage.GetBlob<string>(max.Current.Item1, max.Current.Item2); if (blob.HasValue) { yield return ParseLogEntry(blob.Value); } if (!max.MoveNext()) { enumerators.Remove(max); } } } /// <summary>Lazily enumerates over the entire logs.</summary> /// <returns></returns> public IEnumerable<LogEntry> GetLogs(int skip = 0) { return GetLogsOfLevelOrHigher(Storage.Shared.Logging.LogLevel.Min, skip); } /// <summary> /// Deletes all logs of all levels. /// </summary> public void DeleteAllLogs() { foreach (var level in Enum.GetValues(typeof(Storage.Shared.Logging.LogLevel)).OfType<Storage.Shared.Logging.LogLevel>() .Where(l => l < Storage.Shared.Logging.LogLevel.Max && l > Storage.Shared.Logging.LogLevel.Min)) { _blobStorage.DeleteContainerIfExist(LevelToContainer(level)); } } /// <summary> /// Deletes all the logs older than the provided date. /// </summary> public void DeleteOldLogs(DateTime olderThanUtc) { foreach (var level in Enum.GetValues(typeof(Storage.Shared.Logging.LogLevel)).OfType<Storage.Shared.Logging.LogLevel>() .Where(l => l < Storage.Shared.Logging.LogLevel.Max && l > Storage.Shared.Logging.LogLevel.Min)) { DeleteOldLogsOfLevel(level, olderThanUtc); } } /// <summary> /// Deletes all the logs of a level and older than the provided date. /// </summary> public void DeleteOldLogsOfLevel(Storage.Shared.Logging.LogLevel level, DateTime olderThanUtc) { // Algorithm: // Iterate over the logs, queuing deletions up to 50 items at a time, // then restart; continue until no deletions are queued var deleteQueue = new List<string>(DeleteBatchSize); var blobContainer = LevelToContainer(level); do { deleteQueue.Clear(); foreach (var blobName in _blobStorage.ListBlobNames(blobContainer, string.Empty)) { var dateTime = ParseDateTimeFromName(blobName); if (dateTime < olderThanUtc) deleteQueue.Add(blobName); if (deleteQueue.Count == DeleteBatchSize) break; } foreach (var blobName in deleteQueue) { _blobStorage.DeleteBlobIfExist(blobContainer, blobName); } } while (deleteQueue.Count > 0); } private static string LevelToContainer(Storage.Shared.Logging.LogLevel level) { return ContainerNamePrefix + "-" + level.ToString().ToLower(); } private static string FormatLogEntry(LogEntry logEntry) { return string.Format( @" <log> <level>{0}</level> <timestamp>{1}</timestamp> <message>{2}</message> <error>{3}</error> <source>{4}</source> </log> ", logEntry.Level, logEntry.DateTimeUtc.ToString("o", CultureInfo.InvariantCulture), SecurityElement.Escape(logEntry.Message), SecurityElement.Escape(logEntry.Error), SecurityElement.Escape(logEntry.Source)); } private static LogEntry ParseLogEntry(string blobContent) { using (var stream = new StringReader(blobContent)) { var xpath = new XPathDocument(stream); var nav = xpath.CreateNavigator(); return new LogEntry { Level = nav.SelectSingleNode("/log/level").InnerXml, DateTimeUtc = DateTime.ParseExact(nav.SelectSingleNode("/log/timestamp").InnerXml, "o", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(), Message = nav.SelectSingleNode("/log/message").InnerXml, Error = nav.SelectSingleNode("/log/error").InnerXml, Source = nav.SelectSingleNode("/log/source").InnerXml, }; } } /// <summary>Time prefix with inversion in order to enumerate /// starting from the most recent.</summary> /// <remarks>This method is the symmetric of <see cref="ParseDateTimeFromName"/>.</remarks> public static string FormatDateTimeNamePrefix(DateTime dateTimeUtc) { // yyyy/MM/dd/hh/mm/ss/fff return string.Format("{0}/{1}/{2}/{3}/{4}/{5}/{6}", (10000 - dateTimeUtc.Year).ToString(CultureInfo.InvariantCulture), (12 - dateTimeUtc.Month).ToString("00"), (31 - dateTimeUtc.Day).ToString("00"), (24 - dateTimeUtc.Hour).ToString("00"), (60 - dateTimeUtc.Minute).ToString("00"), (60 - dateTimeUtc.Second).ToString("00"), (999 - dateTimeUtc.Millisecond).ToString("000")); } /// <summary>Convert a prefix with inversion into a <c>DateTime</c>.</summary> /// <remarks>This method is the symmetric of <see cref="FormatDateTimeNamePrefix"/>.</remarks> public static DateTime ParseDateTimeFromName(string nameOrPrefix) { // prefix is always 23 char long var tokens = nameOrPrefix.Substring(0, 23).Split('/'); if (tokens.Length != 7) throw new ArgumentException("Incorrect prefix.", "nameOrPrefix"); var year = 10000 - int.Parse(tokens[0], CultureInfo.InvariantCulture); var month = 12 - int.Parse(tokens[1], CultureInfo.InvariantCulture); var day = 31 - int.Parse(tokens[2], CultureInfo.InvariantCulture); var hour = 24 - int.Parse(tokens[3], CultureInfo.InvariantCulture); var minute = 60 - int.Parse(tokens[4], CultureInfo.InvariantCulture); var second = 60 - int.Parse(tokens[5], CultureInfo.InvariantCulture); var millisecond = 999 - int.Parse(tokens[6], CultureInfo.InvariantCulture); return new DateTime(year, month, day, hour, minute, second, millisecond, DateTimeKind.Utc); } } ///<summary>Log provider for the cloud logger.</summary> public class CloudLogProvider : Storage.Shared.Logging.ILogProvider { readonly IBlobStorageProvider _provider; /// <summary>IoC constructor.</summary> public CloudLogProvider(IBlobStorageProvider provider) { _provider = provider; } /// <remarks></remarks> public Storage.Shared.Logging.ILog Get(string key) { return new CloudLogger(_provider, key); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/CloudLogger.cs
C#
bsd
11,650
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Diagnostics Repository /// </summary> public interface ICloudDiagnosticsRepository { /// <summary>Get the statistics of all execution profiles.</summary> IEnumerable<ExecutionProfilingStatistics> GetExecutionProfilingStatistics(string timeSegment); /// <summary>Update the statistics of an execution profile.</summary> void UpdateExecutionProfilingStatistics(string timeSegment, string contextName, Func<Maybe<ExecutionProfilingStatistics>, ExecutionProfilingStatistics> updater); /// <summary>Remove old statistics of execution profiles.</summary> void RemoveExecutionProfilingStatistics(string timeSegmentPrefix, string timeSegmentBefore); /// <summary>Get the statistics of all cloud partitions.</summary> IEnumerable<PartitionStatistics> GetAllPartitionStatistics(string timeSegment); /// <summary>Update the statistics of a cloud partition.</summary> void UpdatePartitionStatistics(string timeSegment, string partitionName, Func<Maybe<PartitionStatistics>, PartitionStatistics> updater); /// <summary>Remove old statistics of cloud partitions.</summary> void RemovePartitionStatistics(string timeSegmentPrefix, string timeSegmentBefore); /// <summary>Get the statistics of all cloud services.</summary> IEnumerable<ServiceStatistics> GetAllServiceStatistics(string timeSegment); /// <summary>Update the statistics of a cloud service.</summary> void UpdateServiceStatistics(string timeSegment, string serviceName, Func<Maybe<ServiceStatistics>, ServiceStatistics> updater); /// <summary>Remove old statistics of cloud services.</summary> void RemoveServiceStatistics(string timeSegmentPrefix, string timeSegmentBefore); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ICloudDiagnosticsRepository.cs
C#
bsd
1,989
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Diagnostics; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Partition and Worker Monitoring Data Provider /// </summary> internal class PartitionMonitor { readonly ICloudDiagnosticsRepository _repository; readonly string _partitionKey; readonly string _instanceId; /// <summary> /// Creates an instance of the <see cref="PartitionMonitor"/> class. /// </summary> public PartitionMonitor(ICloudDiagnosticsRepository repository) { _repository = repository; _partitionKey = CloudEnvironment.PartitionKey; _instanceId = CloudEnvironment.AzureCurrentInstanceId.GetValue("N/A"); } public void UpdateStatistics() { var process = Process.GetCurrentProcess(); var timestamp = DateTimeOffset.UtcNow; Update(TimeSegments.Day(timestamp), process); Update(TimeSegments.Month(timestamp), process); } /// <summary> /// Remove statistics older than the provided time stamp. /// </summary> public void RemoveStatisticsBefore(DateTimeOffset before) { _repository.RemovePartitionStatistics(TimeSegments.DayPrefix, TimeSegments.Day(before)); _repository.RemovePartitionStatistics(TimeSegments.MonthPrefix, TimeSegments.Month(before)); } /// <summary> /// Remove statistics older than the provided number of periods (0 removes all but the current period). /// </summary> public void RemoveStatisticsBefore(int numberOfPeriods) { var now = DateTimeOffset.UtcNow; _repository.RemovePartitionStatistics( TimeSegments.DayPrefix, TimeSegments.Day(now.AddDays(-numberOfPeriods))); _repository.RemovePartitionStatistics( TimeSegments.MonthPrefix, TimeSegments.Month(now.AddMonths(-numberOfPeriods))); } void Update(string timeSegment, Process process) { _repository.UpdatePartitionStatistics( timeSegment, _partitionKey, s => { var now = DateTimeOffset.UtcNow; if (!s.HasValue) { return new PartitionStatistics { // WORKER DETAILS PartitionKey = _partitionKey, InstanceId = _instanceId, OperatingSystem = Environment.OSVersion.ToString(), Runtime = Environment.Version.ToString(), ProcessorCount = Environment.ProcessorCount, // WORKER AVAILABILITY StartTime = process.StartTime, StartCount = 0, LastUpdate = now, ActiveTime = new TimeSpan(), LifetimeActiveTime = now - process.StartTime, // THREADS & HANDLES HandleCount = process.HandleCount, ThreadCount = process.Threads.Count, // CPU PROCESSING TotalProcessorTime = new TimeSpan(), UserProcessorTime = new TimeSpan(), LifetimeTotalProcessorTime = process.TotalProcessorTime, LifetimeUserProcessorTime = process.UserProcessorTime, // MEMORY CONSUMPTION MemorySystemNonPagedSize = process.NonpagedSystemMemorySize64, MemorySystemPagedSize = process.PagedSystemMemorySize64, MemoryVirtualPeakSize = process.PeakVirtualMemorySize64, MemoryWorkingSet = process.WorkingSet64, MemoryWorkingSetPeak = process.PeakWorkingSet64, MemoryPrivateSize = process.PrivateMemorySize64, MemoryPagedSize = process.PagedMemorySize64, MemoryPagedPeakSize = process.PeakPagedMemorySize64, }; } var stats = s.Value; // WORKER DETAILS stats.InstanceId = _instanceId; stats.OperatingSystem = Environment.OSVersion.ToString(); stats.Runtime = Environment.Version.ToString(); stats.ProcessorCount = Environment.ProcessorCount; // WORKER AVAILABILITY var wasRestarted = false; if (process.StartTime > stats.StartTime) { wasRestarted = true; stats.StartCount++; stats.StartTime = process.StartTime; } stats.LastUpdate = now; if (stats.LifetimeActiveTime.Ticks == 0) { // Upgrade old data structures stats.ActiveTime = new TimeSpan(); } else if (wasRestarted) { stats.ActiveTime += now - process.StartTime; } else { stats.ActiveTime += (now - process.StartTime) - stats.LifetimeActiveTime; } stats.LifetimeActiveTime = now - process.StartTime; // THREADS & HANDLES stats.HandleCount = process.HandleCount; stats.ThreadCount = process.Threads.Count; // CPU PROCESSING if (stats.LifetimeTotalProcessorTime.Ticks == 0) { // Upgrade old data structures stats.TotalProcessorTime = new TimeSpan(); stats.UserProcessorTime = new TimeSpan(); } else if(wasRestarted) { stats.TotalProcessorTime += process.TotalProcessorTime; stats.UserProcessorTime += process.UserProcessorTime; } else { stats.TotalProcessorTime += process.TotalProcessorTime - stats.LifetimeTotalProcessorTime; stats.UserProcessorTime += process.UserProcessorTime - stats.LifetimeUserProcessorTime; } stats.LifetimeTotalProcessorTime = process.TotalProcessorTime; stats.LifetimeUserProcessorTime = process.UserProcessorTime; // MEMORY CONSUMPTION stats.MemorySystemNonPagedSize = process.NonpagedSystemMemorySize64; stats.MemorySystemPagedSize = process.PagedSystemMemorySize64; stats.MemoryVirtualPeakSize = process.PeakVirtualMemorySize64; stats.MemoryWorkingSet = process.WorkingSet64; stats.MemoryWorkingSetPeak = process.PeakWorkingSet64; stats.MemoryPrivateSize = process.PrivateMemorySize64; stats.MemoryPagedSize = process.PagedMemorySize64; stats.MemoryPagedPeakSize = process.PeakPagedMemorySize64; return stats; }); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/PartitionMonitor.cs
C#
bsd
6,108
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Service Monitoring Instrumentation /// </summary> public interface IServiceMonitor { /// <summary> /// Monitor starting a server, dispose once its stopped. /// </summary> IDisposable Monitor(CloudService service); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/IServiceMonitor.cs
C#
bsd
504
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; namespace Lokad.Cloud.Diagnostics { public enum TimeSegmentPeriod { Day, Month } /// <remarks> /// Generated time segments are strictly ordered ascending by time and date /// when compared as string. /// </remarks> static class TimeSegments { public const string DayPrefix = "day"; public const string MonthPrefix = "month"; public static string Day(DateTimeOffset timestamp) { return For(TimeSegmentPeriod.Day, timestamp); } public static string Month(DateTimeOffset timestamp) { return For(TimeSegmentPeriod.Month, timestamp); } public static string For(TimeSegmentPeriod period, DateTimeOffset timestamp) { var utcDate = timestamp.UtcDateTime; return String.Format(GetPeriodFormatString(period), utcDate); } static string GetPeriodFormatString(TimeSegmentPeriod period) { switch (period) { case TimeSegmentPeriod.Day: return "day-{0:yyyyMMdd}"; case TimeSegmentPeriod.Month: return "month-{0:yyyyMM}"; default: throw new ArgumentOutOfRangeException("period"); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/TimeSegments.cs
C#
bsd
1,278
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; using Lokad.Cloud.Diagnostics.Persistence; using Lokad.Cloud.Storage; using Microsoft.WindowsAzure; namespace Lokad.Cloud.Diagnostics { /// <summary>Cloud Diagnostics IoC Module.</summary> public class DiagnosticsModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(CloudLogger); builder.Register(CloudLogger).As<Storage.Shared.Logging.ILog>().PreserveExistingDefaults(); builder.Register(CloudLogProvider).As<Storage.Shared.Logging.ILogProvider>().PreserveExistingDefaults(); // Cloud Monitoring builder.RegisterType<BlobDiagnosticsRepository>().As<ICloudDiagnosticsRepository>().PreserveExistingDefaults(); builder.RegisterType<ServiceMonitor>().As<IServiceMonitor>(); builder.RegisterType<DiagnosticsAcquisition>() .PropertiesAutowired(true) .InstancePerDependency(); } static CloudLogger CloudLogger(IComponentContext c) { return new CloudLogger(BlobStorageForDiagnostics(c), string.Empty); } static CloudLogProvider CloudLogProvider(IComponentContext c) { return new CloudLogProvider(BlobStorageForDiagnostics(c)); } static IBlobStorageProvider BlobStorageForDiagnostics(IComponentContext c) { // No log is provided here (WithLog method) since the providers // used for logging obviously can't log themselves (cyclic dependency) return CloudStorage .ForAzureAccount(c.Resolve<CloudStorageAccount>()) .WithDataSerializer(new CloudFormatter()) .BuildBlobStorage(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/DiagnosticsModule.cs
C#
bsd
1,993
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Text; namespace Lokad.Cloud.Diagnostics.Rsm { /// <remarks></remarks> [DataContract(Name = "rsm", Namespace = "http://schemas.lokad.com/monitoring/1.0/")] public class RsmReport { /// <remarks></remarks> [DataMember(Name = "messages", IsRequired = false)] public IList<MonitoringMessageReport> Messages { get; set; } /// <remarks></remarks> [DataMember(Name = "indicators", IsRequired = false)] public IList<MonitoringIndicatorReport> Indicators { get; set; } /// <remarks></remarks> public RsmReport() { Messages = new List<MonitoringMessageReport>(); Indicators = new List<MonitoringIndicatorReport>(); } /// <summary>Returns the XML ready to be returned by the endpoint.</summary> public override string ToString() { var serializer = new DataContractSerializer(typeof(RsmReport)); using (var stream = new MemoryStream()) { serializer.WriteObject(stream, this); stream.Position = 0; var enc = new UTF8Encoding(); return enc.GetString(stream.ToArray()); } } /// <summary>Helper methods to concatenate the tags.</summary> public static string GetTags(params string[] tags) { var builder = new StringBuilder(); for (int i = 0; i < tags.Length; i++) { if (string.IsNullOrEmpty(tags[i])) continue; builder.Append(tags[i]); if (i < tags.Length - 1) builder.Append(" "); } return builder.ToString(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Rsm/RsmReport.cs
C#
bsd
2,022
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Diagnostics.Rsm { [Serializable] [DataContract(Name = "indicator", Namespace = "http://schemas.lokad.com/monitoring/1.0/")] public class MonitoringIndicatorReport { [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "started", IsRequired = false)] public DateTime Started { get; set; } [DataMember(Name = "updated", IsRequired = false)] public DateTime Updated { get; set; } [DataMember(Name = "instance", IsRequired = false)] public string Instance { get; set; } [DataMember(Name = "value")] public string Value { get; set; } [DataMember(Name = "tags", IsRequired = false)] public string Tags { get; set; } [DataMember(Name = "link", IsRequired = false)] public string Link { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Rsm/RsmIndicatorReport.cs
C#
bsd
1,117
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Diagnostics.Rsm { [Serializable] [DataContract(Name = "message", Namespace = "http://schemas.lokad.com/monitoring/1.0/")] public class MonitoringMessageReport { [DataMember(Name = "id")] public string Id { get; set; } [DataMember(Name = "updated")] public DateTime Updated { get; set; } [DataMember(Name = "title")] public string Title { get; set; } [DataMember(Name = "summary", IsRequired = false)] public string Summary { get; set; } [DataMember(Name = "tags", IsRequired = false)] public string Tags { get; set; } [DataMember(Name = "link", IsRequired = false)] public string Link { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Rsm/RsmMessageReport.cs
C#
bsd
978
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; using Lokad.Diagnostics.Persist; namespace Lokad.Cloud.Diagnostics { [Serializable] [DataContract] public class ExecutionProfilingStatistics { [DataMember] public string Name { get; set; } [DataMember] public ExecutionData[] Statistics { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ExecutionProfilingStatistics.cs
C#
bsd
491
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Service Monitoring Data Provider /// </summary> internal class ServiceMonitor : IServiceMonitor { static List<ServiceStatisticUpdate> _updates = new List<ServiceStatisticUpdate>(); static readonly object _updatesSync = new object(); readonly ICloudDiagnosticsRepository _repository; /// <summary> /// Creates an instance of the <see cref="ServiceMonitor"/> class. /// </summary> public ServiceMonitor(ICloudDiagnosticsRepository repository) { _repository = repository; } public void UpdateStatistics() { List<ServiceStatisticUpdate> updates; lock(_updatesSync) { updates = _updates; _updates = new List<ServiceStatisticUpdate>(); } var aggregates = updates .GroupBy(x => new {x.TimeSegment, x.ServiceName}) .Select(x => x.Aggregate((a, b) => new ServiceStatisticUpdate { ServiceName = x.Key.ServiceName, TimeSegment = x.Key.TimeSegment, TotalCpuTime = a.TotalCpuTime + b.TotalCpuTime, UserCpuTime = a.UserCpuTime + b.UserCpuTime, AbsoluteTime = a.AbsoluteTime + b.AbsoluteTime, MaxAbsoluteTime = a.MaxAbsoluteTime > b.MaxAbsoluteTime ? a.MaxAbsoluteTime : b.MaxAbsoluteTime, TimeStamp = a.TimeStamp > b.TimeStamp ? a.TimeStamp : b.TimeStamp, Count = a.Count + b.Count })); foreach(var aggregate in aggregates) { Update(aggregate); } } /// <summary> /// Remove statistics older than the provided time stamp. /// </summary> public void RemoveStatisticsBefore(DateTimeOffset before) { _repository.RemoveServiceStatistics(TimeSegments.DayPrefix, TimeSegments.Day(before)); _repository.RemoveServiceStatistics(TimeSegments.MonthPrefix, TimeSegments.Month(before)); } /// <summary> /// Remove statistics older than the provided number of periods (0 removes all but the current period). /// </summary> public void RemoveStatisticsBefore(int numberOfPeriods) { var now = DateTimeOffset.UtcNow; _repository.RemoveServiceStatistics( TimeSegments.DayPrefix, TimeSegments.Day(now.AddDays(-numberOfPeriods))); _repository.RemoveServiceStatistics( TimeSegments.MonthPrefix, TimeSegments.Month(now.AddMonths(-numberOfPeriods))); } public IDisposable Monitor(CloudService service) { var handle = OnStart(service); return new DisposableAction(() => OnStop(handle)); } RunningServiceHandle OnStart(CloudService service) { var process = Process.GetCurrentProcess(); var handle = new RunningServiceHandle { Service = service, TotalProcessorTime = process.TotalProcessorTime, UserProcessorTime = process.UserProcessorTime, StartDate = DateTimeOffset.UtcNow }; return handle; } void OnStop(RunningServiceHandle handle) { var timestamp = DateTimeOffset.UtcNow; var process = Process.GetCurrentProcess(); var serviceName = handle.Service.Name; var totalCpuTime = process.TotalProcessorTime - handle.TotalProcessorTime; var userCpuTime = process.UserProcessorTime - handle.UserProcessorTime; var absoluteTime = timestamp - handle.StartDate; lock (_updatesSync) { _updates.Add(new ServiceStatisticUpdate { TimeSegment = TimeSegments.Day(timestamp), ServiceName = serviceName, TimeStamp = timestamp, TotalCpuTime = totalCpuTime, UserCpuTime = userCpuTime, AbsoluteTime = absoluteTime, MaxAbsoluteTime = absoluteTime, Count = 1 }); _updates.Add(new ServiceStatisticUpdate { TimeSegment = TimeSegments.Month(timestamp), ServiceName = serviceName, TimeStamp = timestamp, TotalCpuTime = totalCpuTime, UserCpuTime = userCpuTime, AbsoluteTime = absoluteTime, MaxAbsoluteTime = absoluteTime, Count = 1 }); } } void Update(ServiceStatisticUpdate update) { _repository.UpdateServiceStatistics( update.TimeSegment, update.ServiceName, s => { if (!s.HasValue) { var now = DateTimeOffset.UtcNow; return new ServiceStatistics { Name = update.ServiceName, FirstStartTime = now, LastUpdate = now, TotalProcessorTime = update.TotalCpuTime, UserProcessorTime = update.UserCpuTime, AbsoluteTime = update.AbsoluteTime, MaxAbsoluteTime = update.AbsoluteTime, Count = 1 }; } var stats = s.Value; stats.TotalProcessorTime += update.TotalCpuTime; stats.UserProcessorTime += update.UserCpuTime; stats.AbsoluteTime += update.AbsoluteTime; if (stats.MaxAbsoluteTime < update.AbsoluteTime) { stats.MaxAbsoluteTime = update.AbsoluteTime; } stats.LastUpdate = update.TimeStamp; stats.Count += update.Count; return stats; }); } private class RunningServiceHandle { public CloudService Service { get; set; } public TimeSpan TotalProcessorTime { get; set; } public TimeSpan UserProcessorTime { get; set; } public DateTimeOffset StartDate { get; set; } } private class ServiceStatisticUpdate { public string ServiceName { get; set; } public string TimeSegment { get; set; } public DateTimeOffset TimeStamp { get; set; } public TimeSpan TotalCpuTime { get; set; } public TimeSpan UserCpuTime { get; set; } public TimeSpan AbsoluteTime { get; set; } public TimeSpan MaxAbsoluteTime { get; set; } public long Count { get; set; } } } // HACK: 'DisposableAction' ported from Lokad.Shared /// <summary>Class that allows action to be executed, when it is disposed.</summary> [Serializable] public sealed class DisposableAction : IDisposable { readonly Action _action; /// <summary> /// Initializes a new instance of the <see cref="DisposableAction"/> class. /// </summary> /// <param name="action">The action.</param> public DisposableAction(Action action) { _action = action; } /// <summary> /// Executes the action /// </summary> public void Dispose() { _action(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ServiceMonitor.cs
C#
bsd
6,692
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Storage; namespace Lokad.Cloud.Diagnostics.Persistence { internal class ServiceStatisticsName : BlobName<ServiceStatistics> { public override string ContainerName { get { return "lokad-cloud-diag-service"; } } [Rank(0)] public readonly string TimeSegment; [Rank(1)] public readonly string ServiceName; public ServiceStatisticsName(string timeSegment, string serviceName) { TimeSegment = timeSegment; ServiceName = serviceName; } public static ServiceStatisticsName New(string timeSegment, string serviceName) { return new ServiceStatisticsName(timeSegment, serviceName); } public static ServiceStatisticsName GetPrefix() { return new ServiceStatisticsName(null, null); } public static ServiceStatisticsName GetPrefix(string timeSegment) { return new ServiceStatisticsName(timeSegment, null); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Persistence/ServiceStatisticsName.cs
C#
bsd
1,249
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Runtime; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Diagnostics.Persistence { /// <summary> /// Diagnostics Cloud Data Repository to Blob Storage /// </summary> /// <remarks> /// In order for retention to work correctly, time segments need to be strictly /// ordered ascending by time and date when compared as string. /// </remarks> public class BlobDiagnosticsRepository : ICloudDiagnosticsRepository { readonly IBlobStorageProvider _blobs; /// <summary> /// Creates an Instance of the <see cref="BlobDiagnosticsRepository"/> class. /// </summary> public BlobDiagnosticsRepository(RuntimeProviders runtimeProviders) { _blobs = runtimeProviders.BlobStorage; } void Upsert<T>(BlobName<T> name, Func<Maybe<T>, T> updater) { _blobs.UpsertBlob( name, () => updater(Maybe<T>.Empty), t => updater(t)); } void RemoveWhile<TName>(TName prefix, Func<TName, string> segmentProvider, string timeSegmentBefore) where TName : UntypedBlobName { // since the blobs are strictly ordered we can stop once we reach the condition. var matchingBlobs = _blobs .ListBlobNames(prefix) .TakeWhile(blobName => String.Compare(segmentProvider(blobName), timeSegmentBefore, StringComparison.Ordinal) < 0); foreach (var blob in matchingBlobs) { _blobs.DeleteBlobIfExist(blob.ContainerName, blob.ToString()); } } /// <summary> /// Get the statistics of all execution profiles. /// </summary> public IEnumerable<ExecutionProfilingStatistics> GetExecutionProfilingStatistics(string timeSegment) { return _blobs.ListBlobs(ExecutionProfilingStatisticsName.GetPrefix(timeSegment)); } /// <summary> /// Get the statistics of all cloud partitions. /// </summary> public IEnumerable<PartitionStatistics> GetAllPartitionStatistics(string timeSegment) { return _blobs.ListBlobs(PartitionStatisticsName.GetPrefix(timeSegment)); } /// <summary> /// Get the statistics of all cloud services. /// </summary> public IEnumerable<ServiceStatistics> GetAllServiceStatistics(string timeSegment) { return _blobs.ListBlobs(ServiceStatisticsName.GetPrefix(timeSegment)); } /// <summary> /// Upsert the statistics of an execution profile. /// </summary> public void UpdateExecutionProfilingStatistics(string timeSegment, string contextName, Func<Maybe<ExecutionProfilingStatistics>, ExecutionProfilingStatistics> updater) { Upsert(ExecutionProfilingStatisticsName.New(timeSegment, contextName), updater); } /// <summary> /// Upsert the statistics of a cloud partition. /// </summary> public void UpdatePartitionStatistics(string timeSegment, string partitionName, Func<Maybe<PartitionStatistics>, PartitionStatistics> updater) { Upsert(PartitionStatisticsName.New(timeSegment, partitionName), updater); } /// <summary> /// Upsert the statistics of a cloud service. /// </summary> public void UpdateServiceStatistics(string timeSegment, string serviceName, Func<Maybe<ServiceStatistics>, ServiceStatistics> updater) { Upsert(ServiceStatisticsName.New(timeSegment, serviceName), updater); } /// <summary> /// Remove old statistics of execution profiles. /// </summary> public void RemoveExecutionProfilingStatistics(string timeSegmentPrefix, string timeSegmentBefore) { RemoveWhile( ExecutionProfilingStatisticsName.GetPrefix(timeSegmentPrefix), blobRef => blobRef.TimeSegment, timeSegmentBefore); } /// <summary> /// Remove old statistics of cloud partitions. /// </summary> public void RemovePartitionStatistics(string timeSegmentPrefix, string timeSegmentBefore) { RemoveWhile( PartitionStatisticsName.GetPrefix(timeSegmentPrefix), blobRef => blobRef.TimeSegment, timeSegmentBefore); } /// <summary> /// Remove old statistics of cloud services. /// </summary> public void RemoveServiceStatistics(string timeSegmentPrefix, string timeSegmentBefore) { RemoveWhile( ServiceStatisticsName.GetPrefix(timeSegmentPrefix), blobRef => blobRef.TimeSegment, timeSegmentBefore); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Persistence/BlobDiagnosticsRepository.cs
C#
bsd
5,231
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Storage; namespace Lokad.Cloud.Diagnostics.Persistence { internal class PartitionStatisticsName : BlobName<PartitionStatistics> { public override string ContainerName { get { return "lokad-cloud-diag-partition"; } } [Rank(0)] public readonly string TimeSegment; [Rank(1)] public readonly string PartitionKey; public PartitionStatisticsName(string timeSegment, string partitionKey) { TimeSegment = timeSegment; PartitionKey = partitionKey; } public static PartitionStatisticsName New(string timeSegment, string partitionKey) { return new PartitionStatisticsName(timeSegment, partitionKey); } public static PartitionStatisticsName GetPrefix() { return new PartitionStatisticsName(null, null); } public static PartitionStatisticsName GetPrefix(string timeSegment) { return new PartitionStatisticsName(timeSegment, null); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Persistence/PartitionStatisticsName.cs
C#
bsd
1,275
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Storage; namespace Lokad.Cloud.Diagnostics.Persistence { internal class ExecutionProfilingStatisticsName : BlobName<ExecutionProfilingStatistics> { public override string ContainerName { get { return "lokad-cloud-diag-profile"; } } [Rank(0)] public readonly string TimeSegment; [Rank(1)] public readonly string ContextName; public ExecutionProfilingStatisticsName(string timeSegment, string contextName) { TimeSegment = timeSegment; ContextName = contextName; } public static ExecutionProfilingStatisticsName New(string timeSegment, string contextName) { return new ExecutionProfilingStatisticsName(timeSegment, contextName); } public static ExecutionProfilingStatisticsName GetPrefix() { return new ExecutionProfilingStatisticsName(null, null); } public static ExecutionProfilingStatisticsName GetPrefix(string timeSegment) { return new ExecutionProfilingStatisticsName(timeSegment, null); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/Persistence/ExecutionProfilingStatisticsName.cs
C#
bsd
1,348
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Diagnostics.Persist; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Generic Execution Profile Monitoring Data Provider /// </summary> /// <remarks> /// Implement <see cref="ICloudDiagnosticsSource"/> /// to provide data from non-default counter sources. /// </remarks> internal class ExecutionProfilingMonitor { readonly ICloudDiagnosticsRepository _repository; /// <summary> /// Creates an instance of the <see cref="ExecutionProfilingMonitor"/> class. /// </summary> public ExecutionProfilingMonitor(ICloudDiagnosticsRepository repository) { _repository = repository; } /// <remarks> /// Base implementation collects default counters of this worker /// </remarks> public void UpdateDefaultStatistics() { var counters = ExecutionCounters.Default; var data = counters.ToList().ToArray().ToPersistence(); counters.ResetAll(); Update("Default", data); } /// <summary> /// Update the statistics data with a set of additional new data items /// </summary> public void Update(string contextName, IEnumerable<ExecutionData> additionalData) { var dataList = additionalData.ToList(); if(dataList.Count == 0) { return; } var timestamp = DateTimeOffset.UtcNow; Update(TimeSegments.Day(timestamp), contextName, dataList); Update(TimeSegments.Month(timestamp), contextName, dataList); } /// <summary> /// Remove statistics older than the provided time stamp. /// </summary> public void RemoveStatisticsBefore(DateTimeOffset before) { _repository.RemoveExecutionProfilingStatistics(TimeSegments.DayPrefix, TimeSegments.Day(before)); _repository.RemoveExecutionProfilingStatistics(TimeSegments.MonthPrefix, TimeSegments.Month(before)); } /// <summary> /// Remove statistics older than the provided number of periods (0 removes all but the current period). /// </summary> public void RemoveStatisticsBefore(int numberOfPeriods) { var now = DateTimeOffset.UtcNow; _repository.RemoveExecutionProfilingStatistics( TimeSegments.DayPrefix, TimeSegments.Day(now.AddDays(-numberOfPeriods))); _repository.RemoveExecutionProfilingStatistics( TimeSegments.MonthPrefix, TimeSegments.Month(now.AddMonths(-numberOfPeriods))); } /// <summary> /// Update the statistics data with a set of additional new data items /// </summary> public void Update(string timeSegment, string contextName, IEnumerable<ExecutionData> additionalData) { _repository.UpdateExecutionProfilingStatistics( timeSegment, contextName, s => { if (!s.HasValue) { return new ExecutionProfilingStatistics() { Name = contextName, Statistics = additionalData.ToArray() }; } var stats = s.Value; stats.Statistics = Aggregate(stats.Statistics.Concat(additionalData)).ToArray(); return stats; }); } /// <summary> /// Aggregation Helper /// </summary> private ExecutionData[] Aggregate(IEnumerable<ExecutionData> data) { return data .GroupBy( p => p.Name, (name, items) => new ExecutionData { Name = name, OpenCount = items.Sum(c => c.OpenCount), CloseCount = items.Sum(c => c.CloseCount), Counters = TotalCounters(items), RunningTime = items.Sum(c => c.RunningTime) }) .OrderBy(e => e.Name) .ToArray(); } static long[] TotalCounters(IEnumerable<ExecutionData> data) { if (data.Count() == 0) { return new long[0]; } var length = data.First().Counters.Length; var counters = new long[length]; foreach (var stat in data) { if (stat.Counters.Length != length) { // name/version collision return new long[] { -1, -1, -1 }; } for (int i = 0; i < length; i++) { counters[i] += stat.Counters[i]; } } return counters; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ExecutionProfilingMonitor.cs
C#
bsd
4,309
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using Lokad.Diagnostics.Persist; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Facade to collect internal and external diagnostics statistics (pull or push) /// </summary> public class DiagnosticsAcquisition { readonly ExecutionProfilingMonitor _executionProfiling; readonly PartitionMonitor _partitionMonitor; readonly ServiceMonitor _serviceMonitor; /// <remarks>IoC Injected, but optional</remarks> public ICloudDiagnosticsSource DiagnosticsSource { get; set; } public DiagnosticsAcquisition(ICloudDiagnosticsRepository repository) { _executionProfiling = new ExecutionProfilingMonitor(repository); _partitionMonitor = new PartitionMonitor(repository); _serviceMonitor = new ServiceMonitor(repository); } /// <summary> /// Collect (pull) internal and external diagnostics statistics and persists /// them in the diagnostics repository. /// </summary> public void CollectStatistics() { _executionProfiling.UpdateDefaultStatistics(); _partitionMonitor.UpdateStatistics(); _serviceMonitor.UpdateStatistics(); if (DiagnosticsSource != null) { DiagnosticsSource.GetIncrementalStatistics(_executionProfiling.Update); } } /// <summary> /// Remove all statistics older than the provided time stamp from the /// persistent diagnostics repository. /// </summary> public void RemoveStatisticsBefore(DateTimeOffset before) { _executionProfiling.RemoveStatisticsBefore(before); _partitionMonitor.RemoveStatisticsBefore(before); _serviceMonitor.RemoveStatisticsBefore(before); } /// <summary> /// Remove all statistics older than the provided number of periods from the /// persistent diagnostics repository (0 removes all but the current period). /// </summary> public void RemoveStatisticsBefore(int numberOfPeriods) { _executionProfiling.RemoveStatisticsBefore(numberOfPeriods); _partitionMonitor.RemoveStatisticsBefore(numberOfPeriods); _serviceMonitor.RemoveStatisticsBefore(numberOfPeriods); } /// <summary> /// Push incremental statistics for external execution profiles. /// </summary> public void PushExecutionProfilingStatistics(string context, IEnumerable<ExecutionData> additionalData) { _executionProfiling.Update(context, additionalData); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/DiagnosticsAcquisition.cs
C#
bsd
2,564
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Service Monitoring Statistics /// </summary> [Serializable] [DataContract] public class ServiceStatistics { [DataMember] public string Name { get; set; } [DataMember] public DateTimeOffset FirstStartTime { get; set; } [DataMember] public DateTimeOffset LastUpdate { get; set; } [DataMember] public TimeSpan TotalProcessorTime { get; set; } [DataMember] public TimeSpan UserProcessorTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan AbsoluteTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan MaxAbsoluteTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public long Count { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ServiceStatistics.cs
C#
bsd
1,035
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using Lokad.Diagnostics.Persist; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Extension interface for custom or external diagnostics providers. /// </summary> /// <remarks> /// If a diagnostics source is registered in IoC as member of /// ICloudDiagnosticsSource, it will be queried by the diagnostics /// infrastructure in regular intervals. /// </remarks> public interface ICloudDiagnosticsSource { void GetIncrementalStatistics(Action<string, IEnumerable<ExecutionData>> pushExecutionProfiles); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/ICloudDiagnosticsSource.cs
C#
bsd
743
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Diagnostics { /// <summary> /// Cloud Partition and Worker Monitoring Statistics /// </summary> /// <remarks> /// Properties prefixed with Lifetime refer to the lifetime of the partition's /// process. Is a process restarted, the lifetime value will be reset to zero. /// These additional values are needed internally in order to compute the /// actual non-lifetime values. /// </remarks> [Serializable] [DataContract] public class PartitionStatistics { // WORKER DETAILS [DataMember] public string PartitionKey { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public string InstanceId { get; set; } [DataMember] public string OperatingSystem { get; set; } [DataMember] public string Runtime { get; set; } [DataMember] public int ProcessorCount { get; set; } // WORKER AVAILABILITY [DataMember] public DateTimeOffset StartTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public int StartCount { get; set; } [DataMember] public DateTimeOffset LastUpdate { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan ActiveTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan LifetimeActiveTime { get; set; } // THREADS & HANDLES [DataMember] public int HandleCount { get; set; } [DataMember] public int ThreadCount { get; set; } // CPU PROCESSING [DataMember] public TimeSpan TotalProcessorTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan LifetimeTotalProcessorTime { get; set; } [DataMember] public TimeSpan UserProcessorTime { get; set; } [DataMember(IsRequired = false, EmitDefaultValue = true)] public TimeSpan LifetimeUserProcessorTime { get; set; } // MEMORY CONSUMPTION [DataMember] public long MemorySystemNonPagedSize { get; set; } [DataMember] public long MemorySystemPagedSize { get; set; } [DataMember] public long MemoryVirtualPeakSize { get; set; } [DataMember] public long MemoryWorkingSet { get; set; } [DataMember] public long MemoryWorkingSetPeak { get; set; } [DataMember] public long MemoryPrivateSize { get; set; } [DataMember] public long MemoryPagedSize { get; set; } [DataMember] public long MemoryPagedPeakSize { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Diagnostics/PartitionStatistics.cs
C#
bsd
2,650
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; namespace Lokad.Cloud { /// <summary> /// IoC configuration module for Azure storage and management credentials. /// Recommended to be loaded either manually or in the appconfig. /// </summary> /// <remarks> /// When only using the storage (O/C mapping) toolkit standalone it is easier /// to let the <see cref="Standalone"/> factory create the storage providers on demand. /// </remarks> /// <seealso cref="CloudModule"/> /// <seealso cref="Standalone"/> public sealed class CloudConfigurationModule : Module { /// <summary>Azure storage connection string.</summary> public string DataConnectionString { get; set; } /// <summary>Azure subscription Id (optional).</summary> public string SelfManagementSubscriptionId { get; set; } /// <summary>Azure management certificate thumbprint (optional).</summary> public string SelfManagementCertificateThumbprint { get; set; } public CloudConfigurationModule() { } public CloudConfigurationModule(ICloudConfigurationSettings externalSettings) { ApplySettings(externalSettings); } protected override void Load(ContainerBuilder builder) { if (string.IsNullOrEmpty(DataConnectionString)) { var config = RoleConfigurationSettings.LoadFromRoleEnvironment(); if (config.HasValue) { ApplySettings(config.Value); } } // Only register storage components if the storage credentials are OK // This will cause exceptions to be thrown quite soon, but this way // the roles' OnStart() method returns correctly, allowing the web role // to display a warning to the user (the worker is recycled indefinitely // as Run() throws almost immediately) if (string.IsNullOrEmpty(DataConnectionString)) { return; } builder.RegisterInstance(new RoleConfigurationSettings { DataConnectionString = DataConnectionString, SelfManagementSubscriptionId = SelfManagementSubscriptionId, SelfManagementCertificateThumbprint = SelfManagementCertificateThumbprint }).As<ICloudConfigurationSettings>(); } void ApplySettings(ICloudConfigurationSettings settings) { DataConnectionString = settings.DataConnectionString; SelfManagementSubscriptionId = settings.SelfManagementSubscriptionId; SelfManagementCertificateThumbprint = settings.SelfManagementCertificateThumbprint; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/CloudConfigurationModule.cs
C#
bsd
2,603
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Linq; using System.Runtime.Serialization; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.ServiceFabric { /// <summary>Configuration state of the <seealso cref="ScheduledService"/>.</summary> [Serializable, DataContract] public class ScheduledServiceState { /// <summary>Indicates the frequency this service must be called.</summary> [DataMember] public TimeSpan TriggerInterval { get; set; } /// <summary>Date of the last execution.</summary> [DataMember] public DateTimeOffset LastExecuted { get; set; } /// <summary> /// Lease state info to support synchronized exclusive execution of this /// service (applies only to cloud scoped service, not per worker scheduled /// ones). If <c>null</c> then the service is not currently leased by any /// worker. /// </summary> [DataMember(IsRequired = false, EmitDefaultValue = false)] public SynchronizationLeaseState Lease { get; set; } /// <summary> /// Indicates whether this service is currently running /// (apply only to globally scoped services, not per worker ones) /// .</summary> [Obsolete("Use the Lease mechanism instead.")] [DataMember(IsRequired = false, EmitDefaultValue = false)] public bool IsBusy { get; set; } // TODO: #130, uncomment or remove //[Obsolete("Scheduling scope is fixed at compilation time and thus not a state of the service.")] [DataMember(IsRequired = false, EmitDefaultValue = false)] public bool SchedulePerWorker { get; set; } } /// <summary>Strong typed blob name for <see cref="ScheduledServiceState"/>.</summary> public class ScheduledServiceStateName : BlobName<ScheduledServiceState> { public override string ContainerName { get { return ScheduledService.ScheduleStateContainer; } } /// <summary>Name of the service being refered to.</summary> [Rank(0)] public readonly string ServiceName; /// <summary>Instantiate the reference associated to the specified service.</summary> public ScheduledServiceStateName(string serviceName) { ServiceName = serviceName; } /// <summary>Helper for service states enumeration.</summary> public static ScheduledServiceStateName GetPrefix() { return new ScheduledServiceStateName(null); } } /// <summary>This cloud service is automatically called by the framework /// on scheduled basis. Scheduling options are provided through the /// <see cref="ScheduledServiceSettingsAttribute"/>.</summary> /// <remarks>A empty constructor is needed for instantiation through reflection.</remarks> public abstract class ScheduledService : CloudService, IDisposable { internal const string ScheduleStateContainer = "lokad-cloud-schedule-state"; readonly bool _scheduledPerWorker; readonly string _workerKey; readonly TimeSpan _leaseTimeout; readonly TimeSpan _defaultTriggerPeriod; DateTimeOffset _workerScopeLastExecuted; bool _isLeaseOwner; /// <summary>Default Constructor</summary> protected ScheduledService() { // runtime fixed settings _leaseTimeout = ExecutionTimeout + TimeSpan.FromMinutes(5); _workerKey = CloudEnvironment.PartitionKey; // default setting _scheduledPerWorker = false; _defaultTriggerPeriod = TimeSpan.FromHours(1); // overwrite settings with config in the attribute - if available var settings = GetType().GetCustomAttributes(typeof(ScheduledServiceSettingsAttribute), true) .FirstOrDefault() as ScheduledServiceSettingsAttribute; if (settings != null) { _scheduledPerWorker = settings.SchedulePerWorker; if (settings.TriggerInterval > 0) { _defaultTriggerPeriod = TimeSpan.FromSeconds(settings.TriggerInterval); } } } public override void Initialize() { base.Initialize(); // Auto-register the service for finalization: // 1) Registration should not be made within the constructor // because providers are not ready at this phase. // 2) Hasty finalization is needed only for cloud-scoped scheduled // scheduled services (because they have a lease). if (!_scheduledPerWorker) { Providers.RuntimeFinalizer.Register(this); } } /// <seealso cref="CloudService.StartImpl"/> protected sealed override ServiceExecutionFeedback StartImpl() { var stateReference = new ScheduledServiceStateName(Name); // 1. SIMPLE WORKER-SCOPED SCHEDULING CASE if (_scheduledPerWorker) { var blobState = RuntimeProviders.BlobStorage.GetBlob(stateReference); if (!blobState.HasValue) { // even though we will never change it from here, a state blob // still needs to exist so it can be configured by the console var newState = GetDefaultState(); RuntimeProviders.BlobStorage.PutBlob(stateReference, newState); blobState = newState; } var state = blobState.Value; var now = DateTimeOffset.UtcNow; if (now.Subtract(state.TriggerInterval) >= _workerScopeLastExecuted) { _workerScopeLastExecuted = now; StartOnSchedule(); return ServiceExecutionFeedback.DoneForNow; } return ServiceExecutionFeedback.Skipped; } // 2. CHECK WHETHER WE SHOULD EXECUTE NOW, ACQUIRE LEASE IF SO // checking if the last update is not too recent, and eventually // update this value if it's old enough. When the update fails, // it simply means that another worker is already on its ways // to execute the service. var resultIfChanged = RuntimeProviders.BlobStorage.UpsertBlobOrSkip( stateReference, () => { // create new state and lease, and execute var now = DateTimeOffset.UtcNow; var newState = GetDefaultState(); newState.LastExecuted = now; newState.Lease = CreateLease(now); return newState; }, state => { var now = DateTimeOffset.UtcNow; if (now.Subtract(state.TriggerInterval) < state.LastExecuted) { // was recently executed somewhere; skip return Maybe<ScheduledServiceState>.Empty; } if (state.Lease != null) { if (state.Lease.Timeout > now) { // update needed but blocked by lease; skip return Maybe<ScheduledServiceState>.Empty; } Log.WarnFormat( "ScheduledService {0}: Expired lease owned by {1} was reset after blocking for {2} minutes.", Name, state.Lease.Owner, (int) (now - state.Lease.Acquired).TotalMinutes); } // create lease and execute state.LastExecuted = now; state.Lease = CreateLease(now); return state; }); // 3. IF WE SHOULD NOT EXECUTE NOW, SKIP if (!resultIfChanged.HasValue) { return ServiceExecutionFeedback.Skipped; } _isLeaseOwner = true; // flag used for eventual runtime shutdown try { // 4. ACTUAL EXECUTION StartOnSchedule(); return ServiceExecutionFeedback.DoneForNow; } finally { // 5. RELEASE THE LEASE SurrenderLease(); _isLeaseOwner = false; } } /// <summary>The lease can be surrender in two situations: /// 1- the service completes normally, and we surrender the lease accordingly. /// 2- the runtime is being shutdown, and we can't hold the lease any further. /// </summary> void SurrenderLease() { // we need a full update here (instead of just uploading the cached blob) // to ensure we do not overwrite changes made in the console in the meantime // (e.g. changed trigger interval), and to resolve the edge case when // a lease has been forcefully removed from the console and another service // has taken a lease in the meantime. RuntimeProviders.BlobStorage.UpdateBlobIfExistOrSkip( new ScheduledServiceStateName(Name), state => { if (state.Lease == null || state.Lease.Owner != _workerKey) { // skip return Maybe<ScheduledServiceState>.Empty; } // remove lease state.Lease = null; return state; }); } /// <summary>Don't call this method. Disposing the scheduled service /// should only be done by the <see cref="IRuntimeFinalizer"/> when /// the environment is being forcibly shut down.</summary> public void Dispose() { if(_isLeaseOwner) { SurrenderLease(); _isLeaseOwner = false; } } /// <summary> /// Prepares this service's default state based on its settings attribute. /// In case no attribute is found then Maybe.Empty is returned. /// </summary> private ScheduledServiceState GetDefaultState() { return new ScheduledServiceState { LastExecuted = DateTimeOffset.MinValue, TriggerInterval = _defaultTriggerPeriod, SchedulePerWorker = _scheduledPerWorker }; } /// <summary>Prepares a new lease.</summary> private SynchronizationLeaseState CreateLease(DateTimeOffset now) { return new SynchronizationLeaseState { Acquired = now, Timeout = now + _leaseTimeout, Owner = _workerKey }; } /// <summary>Called by the framework.</summary> /// <remarks>We suggest not performing any heavy processing here. In case /// of heavy processing, put a message and use <see cref="QueueService{T}"/> /// instead.</remarks> protected abstract void StartOnSchedule(); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/ScheduledService.cs
C#
bsd
12,165
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; namespace Lokad.Cloud.ServiceFabric { /// <summary>Shared settings for all <see cref="CloudService"/>s.</summary> [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class CloudServiceSettingsAttribute : Attribute { /// <summary>Indicates whether the service is be started by default /// when the cloud app is deployed.</summary> public bool AutoStart { get; set; } /// <summary>Define the relative priority of this service compared to the /// other services.</summary> public double Priority { get; set; } /// <summary>Gets a description of the service (for administration purposes).</summary> public string Description { get; set; } /// <summary>Execution time-out for the <c>StartImpl</c> methods of /// <see cref="CloudService"/> inheritors. When processing messages it is /// recommended to keep the timeout below 2 hours, or 7200 seconds.</summary> public int ProcessingTimeoutSeconds { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/CloudServiceSettingsAttribute.cs
C#
bsd
1,165
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.ServiceFabric { /// <summary>Synchronization Lease.</summary> [DataContract] public class SynchronizationLeaseState { /// <summary> /// Point of time when the lease was originally acquired. This value is not /// updated when a lease is renewed. /// </summary> [DataMember] public DateTimeOffset Acquired { get; set; } /// <summary> /// Point of them when the lease will time out and can thus be taken over and /// acquired by a new owner. /// </summary> [DataMember] public DateTimeOffset Timeout { get; set; } /// <summary>Reference of the owner of this lease.</summary> [DataMember(IsRequired = false, EmitDefaultValue = false)] public string Owner { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/SynchronizationLeaseState.cs
C#
bsd
960
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion namespace Lokad.Cloud.ServiceFabric { /// <summary>Schedule settings for the execution of a <see cref="ScheduledService"/>.</summary> /// <remarks>The implementation is kept very simple for now. Complete scheduling, /// specifying specific hours or days will be added later on.</remarks> public sealed class ScheduledServiceSettingsAttribute : CloudServiceSettingsAttribute { /// <summary>Indicates the interval between the scheduled executions /// (expressed in seconds).</summary> /// <remarks><c>TimeSpan</c> cannot be used here, because it's not compatible /// with the attribute usage.</remarks> public double TriggerInterval { get; set; } /// <summary> /// Indicates whether the service is scheduled globally among all cloud /// workers (default, <c>false</c>), or whether it should be scheduled /// separately per worker. If scheduled per worker, the service will /// effectively run the number of cloud worker instances times the normal /// rate, and can run on multiple workers at the same time. /// </summary> public bool SchedulePerWorker { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/ScheduledServiceSettingsAttribute.cs
C#
bsd
1,270
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion namespace Lokad.Cloud.ServiceFabric { public interface IInitializable { void Initialize(); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/IInitializable.cs
C#
bsd
270
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Jobs; using Lokad.Cloud.Runtime; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Storage.Shared.Threading; namespace Lokad.Cloud.ServiceFabric { /// <summary>Status flag for <see cref="CloudService"/>s.</summary> /// <remarks>Starting / stopping services isn't a synchronous operation, /// it can take a little while before all the workers notice an update /// on the service state.</remarks> [Serializable] public enum CloudServiceState { /// <summary> /// Indicates that the service should be running.</summary> Started = 0, /// <summary> /// Indicates that the service should be stopped. /// </summary> Stopped = 1 } /// <summary>Strong-typed blob name for cloud service state.</summary> public class CloudServiceStateName : BlobName<CloudServiceState> { public override string ContainerName { get { return CloudService.ServiceStateContainer; } } /// <summary>Name of the service being refered to.</summary> [Rank(0)] public readonly string ServiceName; /// <summary>Instantiate a new blob name associated to the specified service.</summary> public CloudServiceStateName(string serviceName) { ServiceName = serviceName; } /// <summary>Let you iterate over the state of each cloud service.</summary> public static CloudServiceStateName GetPrefix() { return new CloudServiceStateName(null); } } /// <summary>Base class for cloud services.</summary> /// <remarks>Do not inherit directly from <see cref="CloudService"/>, inherit from /// <see cref="QueueService{T}"/> or <see cref="ScheduledService"/> instead.</remarks> public abstract class CloudService : IInitializable { /// <summary>Name of the container associated to temporary items. Each blob /// is prefixed with his lifetime expiration date.</summary> internal const string TemporaryContainer = "lokad-cloud-temporary"; internal const string ServiceStateContainer = "lokad-cloud-services-state"; internal const string DelayedMessageContainer = "lokad-cloud-messages"; /// <summary>Timeout set at 1h58.</summary> /// <remarks>The timeout provided by Windows Azure for message consumption /// on queue is set at 2h. Yet, in order to avoid race condition between /// message silent re-inclusion in queue and message deletion, the timeout here /// is default at 1h58.</remarks> protected readonly TimeSpan ExecutionTimeout; /// <summary>Indicates the state of the service, as retrieved during the last check.</summary> CloudServiceState _state; readonly CloudServiceState _defaultState; /// <summary>Indicates the last time the service has checked its execution status.</summary> DateTimeOffset _lastStateCheck = DateTimeOffset.MinValue; /// <summary>Indicates the frequency where the service is actually checking for its state.</summary> static TimeSpan StateCheckInterval { get { return TimeSpan.FromMinutes(1); } } /// <summary>Name of the service (used for reporting purposes).</summary> /// <remarks>Default implementation returns <c>Type.FullName</c>.</remarks> public virtual string Name { get { return GetType().FullName; } } /// <summary>Providers used by the cloud service to access the storage.</summary> public CloudInfrastructureProviders Providers { get; set; } public RuntimeProviders RuntimeProviders { get; set; } // Short-hands are only provided for the most frequently used providers. // (ex: IRuntimeFinalizer is typically NOT a frequently used provider) /// <summary>Short-hand for <c>Providers.BlobStorage</c>.</summary> public IBlobStorageProvider BlobStorage { get { return Providers.BlobStorage; } } /// <summary>Short-hand for <c>Providers.QueueStorage</c>.</summary> public IQueueStorageProvider QueueStorage { get { return Providers.QueueStorage; } } /// <summary>Short-hand for <c>Providers.TableStorage</c>.</summary> public ITableStorageProvider TableStorage { get { return Providers.TableStorage; } } /// <summary>Short-hand for <c>Providers.Log</c>.</summary> public Storage.Shared.Logging.ILog Log { get { return RuntimeProviders.Log; } } public JobManager Jobs { get; set; } /// <summary> /// Default constructor /// </summary> protected CloudService() { // default setting _defaultState = CloudServiceState.Started; _state = _defaultState; ExecutionTimeout = new TimeSpan(1, 58, 0); // overwrite settings with config in the attribute - if available var settings = GetType().GetCustomAttributes(typeof(CloudServiceSettingsAttribute), true) .FirstOrDefault() as CloudServiceSettingsAttribute; if (null == settings) { return; } _defaultState = settings.AutoStart ? CloudServiceState.Started : CloudServiceState.Stopped; _state = _defaultState; if (settings.ProcessingTimeoutSeconds > 0) { ExecutionTimeout = TimeSpan.FromSeconds(settings.ProcessingTimeoutSeconds); } } public virtual void Initialize() { } /// <summary> /// Wrapper method for the <see cref="StartImpl"/> method. Checks that the /// service status before executing the inner start. /// </summary> /// <returns> /// See <seealso cref="StartImpl"/> for the semantic of the return value. /// </returns> /// <remarks> /// If the execution does not complete within /// <see cref="ExecutionTimeout"/>, then a <see cref="TimeoutException"/> is /// thrown. /// </remarks> public ServiceExecutionFeedback Start() { var now = DateTimeOffset.UtcNow; // checking service state at regular interval if(now.Subtract(_lastStateCheck) > StateCheckInterval) { var stateBlobName = new CloudServiceStateName(Name); var state = RuntimeProviders.BlobStorage.GetBlob(stateBlobName); // no state can be retrieved, update blob storage if(!state.HasValue) { state = _defaultState; RuntimeProviders.BlobStorage.PutBlob(stateBlobName, state.Value); } _state = state.Value; _lastStateCheck = now; } // no execution if the service is stopped if(CloudServiceState.Stopped == _state) { return ServiceExecutionFeedback.Skipped; } var waitFor = new WaitFor<ServiceExecutionFeedback>(ExecutionTimeout); return waitFor.Run(StartImpl); } /// <summary> /// Called when the service is launched. /// </summary> /// <returns> /// Feedback with details whether the service did actually perform any /// operation, and whether it knows or assumes to have more work available for /// immediate execution. This value is used by the framework to adjust the /// scheduling behavior for the respective services. /// </returns> /// <remarks> /// This method is expected to be implemented by the framework services not by /// the app services. /// </remarks> protected abstract ServiceExecutionFeedback StartImpl(); /// <summary>Put a message into the queue implicitly associated to the type <c>T</c>.</summary> public void Put<T>(T message) { PutRange(new[]{message}); } /// <summary>Put a message into the queue identified by <c>queueName</c>.</summary> public void Put<T>(T message, string queueName) { PutRange(new[] { message }, queueName); } /// <summary>Put messages into the queue implicitly associated to the type <c>T</c>.</summary> public void PutRange<T>(IEnumerable<T> messages) { PutRange(messages, TypeMapper.GetStorageName(typeof(T))); } /// <summary>Put messages into the queue identified by <c>queueName</c>.</summary> public void PutRange<T>(IEnumerable<T> messages, string queueName) { QueueStorage.PutRange(queueName, messages); } /// <summary>Put a message into the queue implicitly associated to the type <c>T</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutWithDelay<T>(T message, DateTimeOffset triggerTime) { new DelayedQueue(BlobStorage).PutWithDelay(message, triggerTime); } /// <summary>Put a message into the queue identified by <c>queueName</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutWithDelay<T>(T message, DateTimeOffset triggerTime, string queueName) { new DelayedQueue(BlobStorage).PutWithDelay(message, triggerTime, queueName); } /// <summary>Put messages into the queue implicitly associated to the type <c>T</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutRangeWithDelay<T>(IEnumerable<T> messages, DateTimeOffset triggerTime) { new DelayedQueue(BlobStorage).PutRangeWithDelay(messages, triggerTime); } /// <summary>Put messages into the queue identified by <c>queueName</c> at the /// time specified by the <c>triggerTime</c>.</summary> /// <remarks>This method acts as a delayed put operation, the message not being put /// before the <c>triggerTime</c> is reached.</remarks> public void PutRangeWithDelay<T>(IEnumerable<T> messages, DateTimeOffset triggerTime, string queueName) { new DelayedQueue(BlobStorage).PutRangeWithDelay(messages, triggerTime, queueName); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/CloudService.cs
C#
bsd
10,950
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion namespace Lokad.Cloud.ServiceFabric { /// <summary> /// The execution result of a scheduled action, providing information that /// might be considered for further scheduling. /// </summary> public enum ServiceExecutionFeedback { /// <summary> /// No information available or the service is not interested in providing /// any details. /// </summary> DontCare = 0, /// <summary> /// The service knows or assumes that there is more work available. /// </summary> WorkAvailable, /// <summary> /// The service did some work, but knows or assumes that there is no more work /// available. /// </summary> DoneForNow, /// <summary> /// The service skipped without doing any work (and expects the same for /// successive calls). /// </summary> Skipped, /// <summary> /// The service failed with a fatal error. /// </summary> Failed } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/ServiceExecutionFeedback.cs
C#
bsd
1,073
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; namespace Lokad.Cloud.ServiceFabric { /// <summary>Strongly-type queue service (inheritors are instantiated by /// reflection on the cloud).</summary> /// <typeparam name="T">Message type</typeparam> /// <remarks> /// <para>The implementation is not constrained by the 8kb limit for <c>T</c> instances. /// If the instances are larger, the framework will wrap them into the cloud storage.</para> /// <para>Whenever possible, we suggest to design the service logic to be idempotent /// in order to make the service reliable and ultimately consistent.</para> /// <para>A empty constructor is needed for instantiation through reflection.</para> /// </remarks> public abstract class QueueService<T> : CloudService { readonly string _queueName; readonly string _serviceName; readonly int _batchSize; readonly TimeSpan _visibilityTimeout; readonly int _maxProcessingTrials; /// <summary>Name of the queue associated to the service.</summary> public override string Name { get { return _serviceName; } } /// <summary>Default constructor</summary> protected QueueService() { var settings = GetType().GetCustomAttributes(typeof(QueueServiceSettingsAttribute), true) .FirstOrDefault() as QueueServiceSettingsAttribute; // default settings _batchSize = 1; _maxProcessingTrials = 5; if (null != settings) // settings are provided through custom attribute { _queueName = settings.QueueName ?? TypeMapper.GetStorageName(typeof (T)); _serviceName = settings.ServiceName ?? GetType().FullName; if (settings.BatchSize > 0) { // need to be at least 1 _batchSize = settings.BatchSize; } if (settings.MaxProcessingTrials > 0) { _maxProcessingTrials = settings.MaxProcessingTrials; } } else { _queueName = TypeMapper.GetStorageName(typeof (T)); _serviceName = GetType().FullName; } // 1.25 * execution timeout, but limited to 2h max _visibilityTimeout = TimeSpan.FromSeconds(Math.Max(1, Math.Min(7200, (1.25*ExecutionTimeout.TotalSeconds)))); } /// <summary>Do not try to override this method, use <see cref="StartRange"/> /// instead.</summary> protected sealed override ServiceExecutionFeedback StartImpl() { var messages = QueueStorage.Get<T>(_queueName, _batchSize, _visibilityTimeout, _maxProcessingTrials); var count = messages.Count(); if (count > 0) { StartRange(messages); } // Messages might have already been deleted by the 'Start' method. // It's OK, 'Delete' is idempotent. DeleteRange(messages); return count > 0 ? ServiceExecutionFeedback.WorkAvailable : ServiceExecutionFeedback.Skipped; } /// <summary>Method called first by the <c>Lokad.Cloud</c> framework when messages are /// available for processing. Default implementation is naively calling <see cref="Start"/>. /// </summary> /// <param name="messages">Messages to be processed.</param> /// <remarks> /// We suggest to make messages deleted asap through the <see cref="DeleteRange"/> /// method. Otherwise, messages will be automatically deleted when the method /// returns (except if an exception is thrown obviously). /// </remarks> protected virtual void StartRange(IEnumerable<T> messages) { foreach (var message in messages) { Start(message); } } /// <summary>Method called by <see cref="StartRange"/>, passing the message.</summary> /// <remarks> /// This method is a syntactic sugar for <see cref="QueueService{T}"/> inheritors /// dealing only with 1 message at a time. /// </remarks> protected virtual void Start(T message) { throw new NotSupportedException("Start or StartRange method must overridden by inheritor."); } /// <summary>Get more messages from the underlying queue.</summary> /// <param name="count">Maximal number of messages to be retrieved.</param> /// <returns>Retrieved messages (enumeration might be empty).</returns> /// <remarks>It is suggested to <see cref="DeleteRange"/> messages first /// before asking for more.</remarks> public IEnumerable<T> GetMore(int count) { return QueueStorage.Get<T>(_queueName, count, _visibilityTimeout, _maxProcessingTrials); } /// <summary>Get more message from an arbitrary queue.</summary> /// <param name="count">Number of message to be retrieved.</param> /// <param name="queueName">Name of the queue.</param> /// <returns>Retrieved message (enumeration might be empty).</returns> public IEnumerable<T> GetMore(int count, string queueName) { return QueueStorage.Get<T>(queueName, count, _visibilityTimeout, _maxProcessingTrials); } /// <summary> /// Delete message retrieved either through <see cref="StartRange"/> /// or through <see cref="GetMore(int)"/>. /// </summary> public void Delete(T message) { QueueStorage.Delete(message); } /// <summary> /// Delete messages retrieved either through <see cref="StartRange"/> /// or through <see cref="GetMore(int)"/>. /// </summary> public void DeleteRange(IEnumerable<T> messages) { QueueStorage.DeleteRange(messages); } /// <summary> /// Abandon a messages retrieved either through <see cref="StartRange"/> /// or through <see cref="GetMore(int)"/> and put it visibly back on the queue. /// </summary> public void Abandon(T message) { QueueStorage.Abandon(message); } /// <summary> /// Abandon a set of messages retrieved either through <see cref="StartRange"/> /// or through <see cref="GetMore(int)"/> and put them visibly back on the queue. /// </summary> public void AbandonRange(IEnumerable<T> messages) { QueueStorage.AbandonRange(messages); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/QueueService.cs
C#
bsd
7,138
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.Application; using Lokad.Cloud.Runtime; using Lokad.Cloud.Storage; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <remarks> /// Since the assemblies are loaded in the current <c>AppDomain</c>, this class /// should be a natural candidate for a singleton design pattern. Yet, keeping /// it as a plain class facilitates the IoC instantiation. /// </remarks> public class AssemblyLoader { /// <summary>Name of the container used to store the assembly package.</summary> public const string ContainerName = "lokad-cloud-assemblies"; /// <summary>Name of the blob used to store the assembly package.</summary> public const string PackageBlobName = "default"; /// <summary>Name of the blob used to store the optional dependency injection configuration.</summary> public const string ConfigurationBlobName = "config"; /// <summary>Frequency for checking for update concerning the assembly package.</summary> public static TimeSpan UpdateCheckFrequency { get { return TimeSpan.FromMinutes(1); } } readonly IBlobStorageProvider _provider; /// <summary>Etag of the assembly package. This property is set when /// assemblies are loaded. It can be used to monitor the availability of /// a new package.</summary> string _lastPackageEtag; string _lastConfigurationEtag; DateTimeOffset _lastPackageCheck; /// <summary>Build a new package loader.</summary> public AssemblyLoader(RuntimeProviders runtimeProviders) { _provider = runtimeProviders.BlobStorage; } /// <summary>Loads the assembly package.</summary> /// <remarks>This method is expected to be called only once. Call <see cref="CheckUpdate"/> /// afterward.</remarks> public void LoadPackage() { var buffer = _provider.GetBlob<byte[]>(ContainerName, PackageBlobName, out _lastPackageEtag); _lastPackageCheck = DateTimeOffset.UtcNow; // if no assemblies have been loaded yet, just skip the loading if (!buffer.HasValue) { return; } var reader = new CloudApplicationPackageReader(); var package = reader.ReadPackage(buffer.Value, false); package.LoadAssemblies(); } public Maybe<byte[]> LoadConfiguration() { return _provider.GetBlob<byte[]>(ContainerName, ConfigurationBlobName, out _lastConfigurationEtag); } /// <summary> /// Reset the update status to the currently available version, /// such that <see cref="CheckUpdate"/> does not cause an update to happen. /// </summary> public void ResetUpdateStatus() { _lastPackageEtag = _provider.GetBlobEtag(ContainerName, PackageBlobName); _lastConfigurationEtag = _provider.GetBlobEtag(ContainerName, ConfigurationBlobName); _lastPackageCheck = DateTimeOffset.UtcNow; } /// <summary>Check for the availability of a new assembly package /// and throw a <see cref="TriggerRestartException"/> if a new package /// is available.</summary> /// <param name="delayCheck">If <c>true</c> then the actual update /// check if performed not more than the frequency specified by /// <see cref="UpdateCheckFrequency"/>.</param> public void CheckUpdate(bool delayCheck) { var now = DateTimeOffset.UtcNow; // limiting the frequency where the actual update check is performed. if (delayCheck && now.Subtract(_lastPackageCheck) <= UpdateCheckFrequency) { return; } var newPackageEtag = _provider.GetBlobEtag(ContainerName, PackageBlobName); var newConfigurationEtag = _provider.GetBlobEtag(ContainerName, ConfigurationBlobName); if (!string.Equals(_lastPackageEtag, newPackageEtag)) { throw new TriggerRestartException("Assemblies update has been detected."); } if (!string.Equals(_lastConfigurationEtag, newConfigurationEtag)) { throw new TriggerRestartException("Configuration update has been detected."); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/AssemblyLoader.cs
C#
bsd
4,708
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; // IDEA: the message of the exception could be logged in to the cloud logs. // (issue: how to avoid N identical messages to be logged through all workers) namespace Lokad.Cloud.ServiceFabric.Runtime { ///<summary>Throw this exception in order to force a worker restart.</summary> [Serializable] public class TriggerRestartException : ApplicationException { /// <summary>Empty constructor.</summary> public TriggerRestartException() { } /// <summary>Constructor with message.</summary> public TriggerRestartException(string message) : base(message) { } /// <summary>Constructor with message and inner exception.</summary> public TriggerRestartException(string message, Exception inner) : base(message, inner) { } /// <summary>Deserialization constructor.</summary> public TriggerRestartException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/TriggerRestartException.cs
C#
bsd
1,147
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.IO; using System.Reflection; using System.Security; using System.Threading; using Autofac; using Autofac.Builder; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <summary> /// AppDomain-isolated host for a single runtime instance. /// </summary> internal class IsolatedSingleRuntimeHost { /// <summary>Refer to the callee instance (isolated). This property is not null /// only for the caller instance (non-isolated).</summary> volatile SingleRuntimeHost _isolatedInstance; /// <summary> /// Run the hosted runtime, blocking the calling thread. /// </summary> /// <returns>True if the worker stopped as planned (e.g. due to updated assemblies)</returns> public bool Run() { var settings = RoleConfigurationSettings.LoadFromRoleEnvironment(); // The trick is to load this same assembly in another domain, then // instantiate this same class and invoke Run var domain = AppDomain.CreateDomain("WorkerDomain", null, AppDomain.CurrentDomain.SetupInformation); bool restartForAssemblyUpdate; try { _isolatedInstance = (SingleRuntimeHost)domain.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, typeof(SingleRuntimeHost).FullName); // This never throws, unless something went wrong with IoC setup and that's fine // because it is not possible to execute the worker restartForAssemblyUpdate = _isolatedInstance.Run(settings); } finally { _isolatedInstance = null; // If this throws, it's because something went wrong when unloading the AppDomain // The exception correctly pulls down the entire worker process so that no AppDomains are // left in memory AppDomain.Unload(domain); } return restartForAssemblyUpdate; } /// <summary> /// Immediately stop the runtime host and wait until it has exited (or a timeout expired). /// </summary> public void Stop() { var instance = _isolatedInstance; if (null != instance) { _isolatedInstance.Stop(); } } } /// <summary> /// Host for a single runtime instance. /// </summary> internal class SingleRuntimeHost : MarshalByRefObject, IDisposable { /// <summary>Current hosted runtime instance.</summary> volatile Runtime _runtime; /// <summary> /// Manual-reset wait handle, signaled once the host stopped running. /// </summary> readonly EventWaitHandle _stoppedWaitHandle = new ManualResetEvent(false); /// <summary> /// Run the hosted runtime, blocking the calling thread. /// </summary> /// <returns>True if the worker stopped as planned (e.g. due to updated assemblies)</returns> public bool Run(Maybe<ICloudConfigurationSettings> externalRoleConfiguration) { _stoppedWaitHandle.Reset(); // Runtime IoC Setup var runtimeBuilder = new ContainerBuilder(); runtimeBuilder.RegisterModule(new CloudModule()); runtimeBuilder.RegisterModule(externalRoleConfiguration.Convert(s => new CloudConfigurationModule(s), () => new CloudConfigurationModule())); runtimeBuilder.RegisterType<Runtime>().InstancePerDependency(); // Run using (var runtimeContainer = runtimeBuilder.Build()) { var log = runtimeContainer.Resolve<Storage.Shared.Logging.ILog>(); _runtime = null; try { _runtime = runtimeContainer.Resolve<Runtime>(); _runtime.RuntimeContainer = runtimeContainer; // runtime endlessly keeps pinging queues for pending work _runtime.Execute(); log.DebugFormat("Runtime Host: Runtime has stopped cleanly on worker {0}.", CloudEnvironment.PartitionKey); } catch (TypeLoadException typeLoadException) { log.ErrorFormat(typeLoadException, "Runtime Host: Type {0} could not be loaded. The Runtime Host will be restarted.", typeLoadException.TypeName); } catch (FileLoadException fileLoadException) { // Tentatively: referenced assembly is missing log.Fatal(fileLoadException, "Runtime Host: Could not load assembly probably due to a missing reference assembly. The Runtime Host will be restarted."); } catch (SecurityException securityException) { // Tentatively: assembly cannot be loaded due to security config log.FatalFormat(securityException, "Runtime Host: Could not load assembly {0} probably due to security configuration. The Runtime Host will be restarted.", securityException.FailedAssemblyInfo); } catch (TriggerRestartException) { log.DebugFormat("Runtime Host: Triggered to stop execution on worker {0}. The Role Instance will be recycled and the Runtime Host restarted.", CloudEnvironment.PartitionKey); return true; } catch (Exception ex) { // Generic exception log.ErrorFormat(ex, "Runtime Host: An unhandled {0} exception occurred on worker {1}. The Runtime Host will be restarted.", ex.GetType().Name, CloudEnvironment.PartitionKey); } finally { _stoppedWaitHandle.Set(); _runtime = null; } return false; } } /// <summary> /// Immediately stop the runtime host and wait until it has exited (or a timeout expired). /// </summary> public void Stop() { var runtime = _runtime; if (null != runtime) { runtime.Stop(); // note: we DO have to wait until the shut down has finished, // or the Azure Fabric will tear us apart early! _stoppedWaitHandle.WaitOne(TimeSpan.FromSeconds(25)); } } public void Dispose() { _stoppedWaitHandle.Close(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/SingleRuntimeHost.cs
C#
bsd
7,265
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Autofac; using Autofac.Builder; using Autofac.Configuration; using Lokad.Cloud.Diagnostics; using Lokad.Cloud.Runtime; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <summary>Organize the executions of the services.</summary> internal class Runtime { readonly RuntimeProviders _runtimeProviders; readonly IRuntimeFinalizer _runtimeFinalizer; readonly Storage.Shared.Logging.ILog _log; readonly IServiceMonitor _monitoring; readonly DiagnosticsAcquisition _diagnostics; readonly ICloudConfigurationSettings _settings; /// <summary>Main thread used to schedule services in <see cref="Execute()"/>.</summary> Thread _executeThread; volatile bool _isStopRequested; Scheduler _scheduler; IRuntimeFinalizer _applicationFinalizer; /// <summary>Container used to populate cloud service properties.</summary> public IContainer RuntimeContainer { get; set; } /// <summary>IoC constructor.</summary> public Runtime(RuntimeProviders runtimeProviders, ICloudConfigurationSettings settings, ICloudDiagnosticsRepository diagnosticsRepository) { _runtimeProviders = runtimeProviders; _runtimeFinalizer = runtimeProviders.RuntimeFinalizer; _log = runtimeProviders.Log; _settings = settings; _monitoring = new ServiceMonitor(diagnosticsRepository); _diagnostics = new DiagnosticsAcquisition(diagnosticsRepository); } /// <summary>Called once by the service fabric. Call is not supposed to return /// until stop is requested, or an uncaught exception is thrown.</summary> public void Execute() { _log.DebugFormat("Runtime: started on worker {0}.", CloudEnvironment.PartitionKey); // hook on the current thread to force shut down _executeThread = Thread.CurrentThread; _scheduler = new Scheduler(LoadServices<CloudService>, RunService); try { foreach (var action in _scheduler.Schedule()) { if (_isStopRequested) { break; } action(); } } catch (ThreadInterruptedException) { _log.WarnFormat("Runtime: execution was interrupted on worker {0} in service {1}. The Runtime will be restarted.", CloudEnvironment.PartitionKey, GetNameOfServiceInExecution()); } catch (ThreadAbortException) { Thread.ResetAbort(); _log.DebugFormat("Runtime: execution was aborted on worker {0} in service {1}. The Runtime is stopping.", CloudEnvironment.PartitionKey, GetNameOfServiceInExecution()); } catch (TimeoutException) { _log.WarnFormat("Runtime: execution timed out on worker {0} in service {1}. The Runtime will be restarted.", CloudEnvironment.PartitionKey, GetNameOfServiceInExecution()); } catch (TriggerRestartException) { // Supposed to be handled by the runtime host (i.e. SingleRuntimeHost) throw; } catch (Exception ex) { _log.ErrorFormat(ex, "Runtime: An unhandled {0} exception occurred on worker {1} in service {2}. The Runtime will be restarted.", ex.GetType().Name, CloudEnvironment.PartitionKey, GetNameOfServiceInExecution()); } finally { _log.DebugFormat("Runtime: stopping on worker {0}.", CloudEnvironment.PartitionKey); if (_runtimeFinalizer != null) { _runtimeFinalizer.FinalizeRuntime(); } if (_applicationFinalizer != null) { _applicationFinalizer.FinalizeRuntime(); } TryDumpDiagnostics(); _log.DebugFormat("Runtime: stopped on worker {0}.", CloudEnvironment.PartitionKey); } } /// <summary>The name of the service that is being executed, if any, <c>null</c> otherwise.</summary> private string GetNameOfServiceInExecution() { var scheduler = _scheduler; CloudService service; if (scheduler == null || (service = scheduler.CurrentlyScheduledService) == null) { return "unknown"; } return service.Name; } /// <summary>Stops all services at once.</summary> /// <remarks>Called once by the service fabric when environment is about to /// be shut down.</remarks> public void Stop() { _isStopRequested = true; _log.DebugFormat("Runtime: Stop() on worker {0}.", CloudEnvironment.PartitionKey); if (_executeThread != null) { _executeThread.Abort(); return; } if (_scheduler != null) { _scheduler.AbortWaitingSchedule(); } } /// <summary> /// Load and get all initialized service instances using the provided IoC container. /// </summary> IEnumerable<T> LoadServices<T>() { var applicationBuilder = new ContainerBuilder(); applicationBuilder.RegisterModule(new CloudModule()); applicationBuilder.RegisterInstance(_settings); // Load Application Assemblies into the AppDomain var loader = new AssemblyLoader(_runtimeProviders); loader.LoadPackage(); // Load Application IoC Configuration and apply it to the builder var config = loader.LoadConfiguration(); if (config.HasValue) { ApplyConfiguration(config.Value, applicationBuilder); } // Look for all cloud services currently loaded in the AppDomain var serviceTypes = AppDomain.CurrentDomain.GetAssemblies() .Select(a => a.GetExportedTypes()).SelectMany(x => x) .Where(t => t.IsSubclassOf(typeof (T)) && !t.IsAbstract && !t.IsGenericType) .ToList(); // Register the cloud services in the IoC Builder so we can support dependencies foreach (var type in serviceTypes) { applicationBuilder.RegisterType(type) .OnActivating(e => { e.Context.InjectUnsetProperties(e.Instance); var initializable = e.Instance as IInitializable; if (initializable != null) { initializable.Initialize(); } }) .InstancePerDependency() .ExternallyOwned(); // ExternallyOwned: to prevent the container from disposing the // cloud services - we manage their lifetime on our own using // e.g. RuntimeFinalizer } var applicationContainer = applicationBuilder.Build(); _applicationFinalizer = applicationContainer.ResolveOptional<IRuntimeFinalizer>(); // Give the application a chance to override external diagnostics sources applicationContainer.InjectProperties(_diagnostics); // Instanciate and return all the cloud services return serviceTypes.Select(type => (T)applicationContainer.Resolve(type)); } /// <summary> /// Run a scheduled service /// </summary> ServiceExecutionFeedback RunService(CloudService service) { ServiceExecutionFeedback feedback; using (_monitoring.Monitor(service)) { feedback = service.Start(); } return feedback; } /// <summary> /// Try to dump diagnostics, but suppress any exceptions if it fails /// </summary> void TryDumpDiagnostics() { try { _diagnostics.CollectStatistics(); } catch (ThreadAbortException) { Thread.ResetAbort(); _log.WarnFormat("Runtime: skipped acquiring statistics on worker {0}", CloudEnvironment.PartitionKey); } catch(Exception e) { _log.WarnFormat(e, "Runtime: failed to acquire statistics on worker {0}: {1}", CloudEnvironment.PartitionKey, e.Message); // might fail when shutting down on exception // logging is likely to fail as well in this case // Suppress exception, can't do anything (will be recycled anyway) } } /// <summary> /// Apply the configuration provided in text as raw bytes to the provided IoC /// container. /// </summary> static void ApplyConfiguration(byte[] config, ContainerBuilder applicationBuilder) { // HACK: need to copy settings locally first // HACK: hard-code string for local storage name const string fileName = "lokad.cloud.clientapp.config"; const string resourceName = "LokadCloudStorage"; var pathToFile = Path.Combine( CloudEnvironment.GetLocalStoragePath(resourceName), fileName); File.WriteAllBytes(pathToFile, config); applicationBuilder.RegisterModule(new ConfigurationSettingsReader("autofac", pathToFile)); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/Runtime.cs
C#
bsd
10,536
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Linq; using Microsoft.WindowsAzure.ServiceRuntime; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <summary> /// Entry point, hosting the service fabric with one or more /// continuously running isolated runtimes. /// </summary> public class ServiceFabricHost { readonly NoRestartFloodPolicy _restartPolicy; volatile IsolatedSingleRuntimeHost _primaryRuntimeHost; public ServiceFabricHost() { _restartPolicy = new NoRestartFloodPolicy(); } /// <summary> /// Start up the runtime. This step is required before calling Run. /// </summary> public void StartRuntime() { RoleEnvironment.Changing += OnRoleEnvironmentChanging; } /// <summary>Shutdown the runtime.</summary> public void ShutdownRuntime() { RoleEnvironment.Changing -= OnRoleEnvironmentChanging; _restartPolicy.IsStopRequested = true; if(null != _primaryRuntimeHost) { _primaryRuntimeHost.Stop(); } } /// <summary>Runtime Main Thread.</summary> public void Run() { // restart policy cease restarts if stop is requested _restartPolicy.Do(() => { _primaryRuntimeHost = new IsolatedSingleRuntimeHost(); return _primaryRuntimeHost.Run(); }); } static void OnRoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e) { // we restart all workers if the configuration changed (e.g. the storage account) // for now. // We do not request a recycle if only the topology changed, // e.g. if some instances have been removed or added. var configChanges = e.Changes.OfType<RoleEnvironmentConfigurationSettingChange>(); if(configChanges.Any()) { RoleEnvironment.RequestRecycle(); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/ServiceFabricHost.cs
C#
bsd
1,924
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Lokad.Cloud.Storage.Shared.Diagnostics; using Lokad.Diagnostics; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <summary> /// Round robin scheduler with adaptive modifications: tasks that claim to have /// more work ready are given the chance to continue until they reach a fixed /// time limit (greedy), and the scheduling is slowed down when all available /// services skip execution consecutively. /// </summary> public class Scheduler { readonly Func<IEnumerable<CloudService>> _serviceProvider; readonly Func<CloudService, ServiceExecutionFeedback> _schedule; readonly object _sync = new object(); /// <summary>Duration to keep pinging the same cloud service if service is active.</summary> readonly TimeSpan _moreOfTheSame = TimeSpan.FromSeconds(60); /// <summary>Resting duration.</summary> readonly TimeSpan _idleSleep = TimeSpan.FromSeconds(10); CloudService _currentService; volatile bool _isRunning; // Instrumentation readonly ExecutionCounter _countIdleSleep; readonly ExecutionCounter _countBusyExecute; /// <summary> /// Creates a new instance of the Scheduler class. /// </summary> /// <param name="serviceProvider">Provider of available cloud services</param> /// <param name="schedule">Action to be invoked when a service is scheduled to run</param> public Scheduler(Func<IEnumerable<CloudService>> serviceProvider, Func<CloudService, ServiceExecutionFeedback> schedule) { _serviceProvider = serviceProvider; _schedule = schedule; // Instrumentation ExecutionCounters.Default.RegisterRange(new[] { _countIdleSleep = new ExecutionCounter("Runtime.IdleSleep", 0, 0), _countBusyExecute = new ExecutionCounter("Runtime.BusyExecute", 0, 0) }); } public CloudService CurrentlyScheduledService { get { return _currentService; } } public IEnumerable<Action> Schedule() { var services = _serviceProvider().ToArray(); var currentServiceIndex = -1; var skippedConsecutively = 0; _isRunning = true; while (_isRunning) { currentServiceIndex = (currentServiceIndex + 1) % services.Length; _currentService = services[currentServiceIndex]; var result = ServiceExecutionFeedback.DontCare; var isRunOnce = false; // 'more of the same pattern' // as long the service is active, keep triggering the same service // for at least 1min (in order to avoid a single service to monopolize CPU) var start = DateTimeOffset.UtcNow; while (DateTimeOffset.UtcNow.Subtract(start) < _moreOfTheSame && _isRunning && DemandsImmediateStart(result)) { yield return () => { var busyExecuteTimestamp = _countBusyExecute.Open(); result = _schedule(_currentService); _countBusyExecute.Close(busyExecuteTimestamp); }; isRunOnce |= WasSuccessfullyExecuted(result); } skippedConsecutively = isRunOnce ? 0 : skippedConsecutively + 1; if (skippedConsecutively >= services.Length && _isRunning) { // We are not using 'Thread.Sleep' because we want the worker // to terminate fast if 'Stop' is requested. var idleSleepTimestamp = _countIdleSleep.Open(); lock (_sync) { Monitor.Wait(_sync, _idleSleep); } _countIdleSleep.Close(idleSleepTimestamp); skippedConsecutively = 0; } } _currentService = null; } /// <summary>Waits until the current service completes, and stop the scheduling.</summary> /// <remarks>This method CANNOT be used in case the environment is stopping, /// because the termination is going to be way too slow.</remarks> public void AbortWaitingSchedule() { _isRunning = false; lock (_sync) { Monitor.Pulse(_sync); } } /// <summary> /// The service was successfully executed and it might make sense to execute /// it again immediately (greedy). /// </summary> bool DemandsImmediateStart(ServiceExecutionFeedback feedback) { return feedback == ServiceExecutionFeedback.WorkAvailable || feedback == ServiceExecutionFeedback.DontCare; } /// <summary> /// The service was actually executed (not skipped) and did not fail. /// </summary> bool WasSuccessfullyExecuted(ServiceExecutionFeedback feedback) { return feedback != ServiceExecutionFeedback.Skipped && feedback != ServiceExecutionFeedback.Failed; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/Scheduler.cs
C#
bsd
4,746
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Threading; namespace Lokad.Cloud.ServiceFabric.Runtime { /// <summary> /// Helper class to deal with pathological situations where a worker crashes at /// start-up time (typically because initialization or assembly loading goes /// wrong). Instead of performing a high-frequency restart (producing junk logs /// among other), when restart flood is detected restarts are forcefully slowed /// down. /// </summary> internal class NoRestartFloodPolicy { /// <summary> /// Minimal duration between worker restart to be considered as a regular /// situation (restart can happen from time to time). /// </summary> static TimeSpan FloodFrequencyThreshold { get { return TimeSpan.FromMinutes(1); } } /// <summary> /// Delay to be applied before the next restart when a flooding situation is /// detected. /// </summary> static TimeSpan DelayWhenFlooding { get { return TimeSpan.FromMinutes(5); } } volatile bool _isStopRequested; /// <summary>When stop is requested, policy won't go on with restarts anymore.</summary> public bool IsStopRequested { get { return _isStopRequested; } set { _isStopRequested = value; } } /// <summary> /// Endlessly restart the provided action, but avoiding restart flooding /// patterns. /// </summary> public void Do(Func<bool> workButNotFloodRestart) { // once stop is requested, we stop while (!_isStopRequested) { // The assemblyUpdated flag handles the case when a restart is caused by an asm update, "soon" after another restart // In such case, the worker would be reported as unhealthy virtually forever if no more restarts occur var lastRestart = DateTimeOffset.UtcNow; var assemblyUpdated = workButNotFloodRestart(); if (!assemblyUpdated && DateTimeOffset.UtcNow.Subtract(lastRestart) < FloodFrequencyThreshold) { // Unhealthy Thread.Sleep(DelayWhenFlooding); } } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/NoRestartFloodPolicy.cs
C#
bsd
2,157
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion namespace Lokad.Cloud.ServiceFabric { /// <summary>Default settings for the <see cref="QueueService{T}"/>. Once the queue /// service is deployed, settings are stored in the <c>lokad-cloud-queues</c> blob /// container.</summary> public sealed class QueueServiceSettingsAttribute : CloudServiceSettingsAttribute { /// <summary>Name of the queue attached to the <see cref="QueueService{T}"/>.</summary> /// <remarks>If this value is <c>null</c> or empty, a default queue name is chosen based /// on the type <c>T</c>.</remarks> public string QueueName { get; set; } /// <summary>Name of the services as it will appear in administration console. This is also its identifier</summary> /// <remarks>If this value is <c>null</c> or empty, a default service name is chosen based /// on the class type.</remarks> public string ServiceName { get; set; } /// <summary>Suggested size for batch retrieval of messages.</summary> /// <remarks>The maximal value is 1000. We suggest to retrieve small messages /// in batch to reduce network overhead.</remarks> public int BatchSize { get; set; } /// <summary> /// Maximum number of times a message is tried to process before it is considered as /// being poisonous, removed from the queue and persisted to the 'failing-messages' store. /// </summary> public int MaxProcessingTrials { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/QueueServiceSettingsAttribute.cs
C#
bsd
1,553
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; namespace Lokad.Cloud.ServiceFabric { /// <summary>High-priority runtime finalizer. Attempts to finalize key cloud resources /// when the runtime is forcibly shut down.</summary> public class RuntimeFinalizer : IRuntimeFinalizer { /// <summary>Locking object used to ensure the thread safety of instance.</summary> readonly object _sync; /// <summary>Collections of objects to be disposed on runtime finalization.</summary> readonly HashSet<IDisposable> _disposables; bool _isRuntimeFinalized; public void Register(IDisposable obj) { lock(_sync) { if(_isRuntimeFinalized) { throw new InvalidOperationException("Runtime already finalized."); } _disposables.Add(obj); } } public void Unregister(IDisposable obj) { lock (_sync) { if (_isRuntimeFinalized) { throw new InvalidOperationException("Runtime already finalized."); } _disposables.Remove(obj); } } public void FinalizeRuntime() { lock (_sync) { if (!_isRuntimeFinalized) { _isRuntimeFinalized = true; foreach (var disposable in _disposables) { disposable.Dispose(); } } // ignore multiple calls to finalization } } /// <summary>IoC constructor.</summary> public RuntimeFinalizer() { _sync = new object(); _disposables = new HashSet<IDisposable>(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/ServiceFabric/RuntimeFinalizer.cs
C#
bsd
1,642
using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Jobs { [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/jobs/1.1"), Serializable] public class Job { [DataMember(IsRequired = true)] public string JobId { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Jobs/Job.cs
C#
bsd
306
using System; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.Jobs { /// <summary>NOT IMPLEMENTED YET.</summary> public class JobManager { private readonly Storage.Shared.Logging.ILog _log; public JobManager(Storage.Shared.Logging.ILog log) { _log = log; } public Job CreateNew() { return new Job { JobId = string.Format("j{0:yyyyMMddHHnnss}{1:N}", DateTime.UtcNow, Guid.NewGuid()) }; } public Job StartNew() { var job = CreateNew(); Start(job); return job; } public void Start(Job job) { // TODO: Implementation _log.DebugFormat("Job {0} started", job.JobId); } public void Succeed(Job job) { // TODO: Implementation _log.DebugFormat("Job {0} succeeded", job.JobId); } public void Fail(Job job) { // TODO: Implementation _log.DebugFormat("Job {0} failed", job.JobId); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Jobs/JobManager.cs
C#
bsd
1,202
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; namespace Lokad.Cloud { /// <summary> /// IoC module that registers all usually required components, including /// storage providers, management & provisioning and diagnostics/logging. /// It is recommended to load this module even when only using the storage (O/C mapping) providers. /// Expects the <see cref="CloudConfigurationModule"/> (or the mock module) to be registered as well. /// </summary> /// <remarks> /// When only using the storage (O/C mapping) toolkit standalone it is easier /// to let the <see cref="Standalone"/> factory create the storage providers on demand. /// </remarks> /// <seealso cref="CloudConfigurationModule"/> /// <seealso cref="Standalone"/> public sealed class CloudModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterModule(new Diagnostics.DiagnosticsModule()); builder.RegisterModule(new Management.ManagementModule()); builder.RegisterModule(new Storage.Azure.StorageModule()); builder.RegisterType<Jobs.JobManager>(); builder.RegisterType<ServiceFabric.RuntimeFinalizer>().As<IRuntimeFinalizer>().InstancePerLifetimeScope(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/CloudModule.cs
C#
bsd
1,477
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.Storage; namespace Lokad.Cloud { [Serializable] public class RoleConfigurationSettings : ICloudConfigurationSettings { public string DataConnectionString { get; set; } public string SelfManagementSubscriptionId { get; set; } public string SelfManagementCertificateThumbprint { get; set; } public static Maybe<ICloudConfigurationSettings> LoadFromRoleEnvironment() { if (!CloudEnvironment.IsAvailable) { return Maybe<ICloudConfigurationSettings>.Empty; } var setting = new RoleConfigurationSettings(); ApplySettingFromRole("DataConnectionString", v => setting.DataConnectionString = v); ApplySettingFromRole("SelfManagementSubscriptionId", v => setting.SelfManagementSubscriptionId = v); ApplySettingFromRole("SelfManagementCertificateThumbprint", v => setting.SelfManagementCertificateThumbprint = v); return setting; } static void ApplySettingFromRole(string setting, Action<string> setter) { CloudEnvironment.GetConfigurationSetting(setting).Apply(setter); } } /// <summary> /// Settings used among others by the <see cref="Lokad.Cloud.Storage.Azure.StorageModule" />. /// </summary> public interface ICloudConfigurationSettings { /// <summary> /// Gets the data connection string. /// </summary> /// <value>The data connection string.</value> string DataConnectionString { get; } /// <summary> /// Gets the Azure subscription Id to be used for self management (optional, can be null). /// </summary> string SelfManagementSubscriptionId { get; } /// <summary> /// Gets the Azure certificate thumbpring to be used for self management (optional, can be null). /// </summary> string SelfManagementCertificateThumbprint { get; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/RoleConfigurationSettings.cs
C#
bsd
1,955
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using Lokad.Cloud.Storage; using Microsoft.WindowsAzure.ServiceRuntime; namespace Lokad.Cloud { /// <summary> /// Cloud Environment Helper /// </summary> /// <remarks> /// Providing functionality of Azure <see cref="RoleEnvironment"/>, /// but more neutral and resilient to missing runtime. /// </remarks> public static class CloudEnvironment { readonly static bool _runtimeAvailable; static CloudEnvironment() { try { _runtimeAvailable = RoleEnvironment.IsAvailable; } catch (TypeInitializationException) { _runtimeAvailable = false; } } /// <summary> /// Indicates whether the instance is running in the Cloud environment. /// </summary> public static bool IsAvailable { get { return _runtimeAvailable; } } /// <summary> /// Cloud Worker Key /// </summary> public static string PartitionKey { get { return System.Net.Dns.GetHostName(); } } /// <summary> /// ID of the Cloud Worker Instances /// </summary> public static Maybe<string> AzureCurrentInstanceId { get { return _runtimeAvailable ? RoleEnvironment.CurrentRoleInstance.Id : Maybe<string>.Empty; } } public static Maybe<string> AzureDeploymentId { get { return _runtimeAvailable ? RoleEnvironment.DeploymentId : Maybe<string>.Empty; } } public static Maybe<int> AzureWorkerInstanceCount { get { if(!_runtimeAvailable) { return Maybe<int>.Empty; } Role workerRole; if(!RoleEnvironment.Roles.TryGetValue("Lokad.Cloud.WorkerRole", out workerRole)) { return Maybe<int>.Empty; } return workerRole.Instances.Count; } } /// <summary> /// Retrieves the root path of a named local resource. /// </summary> public static string GetLocalStoragePath(string resourceName) { if (IsAvailable) { return RoleEnvironment.GetLocalResource(resourceName).RootPath; } var dir = Path.Combine(Path.GetTempPath(), resourceName); Directory.CreateDirectory(dir); return dir; } public static Maybe<X509Certificate2> GetCertificate(string thumbprint) { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); var certs = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false); if(certs.Count != 1) { return Maybe<X509Certificate2>.Empty; } return certs[0]; } finally { store.Close(); } } ///<summary> /// Retreives the configuration setting from the <see cref="RoleEnvironment"/>. ///</summary> ///<param name="configurationSettingName">Name of the configuration setting</param> ///<returns>configuration value, or an empty result, if the environment is not present, or the value is null or empty</returns> public static Maybe<string> GetConfigurationSetting(string configurationSettingName) { if (!_runtimeAvailable) { return Maybe<string>.Empty; } try { var value = RoleEnvironment.GetConfigurationSettingValue(configurationSettingName); if (!String.IsNullOrEmpty(value)) { value = value.Trim(); } if (String.IsNullOrEmpty(value)) { value = null; } return value; } catch (RoleEnvironmentException) { return Maybe<string>.Empty; // setting was removed from the csdef, skip // (logging is usually not available at that stage) } } public static bool HasSecureEndpoint() { if (!_runtimeAvailable) { return false; } return RoleEnvironment.CurrentRoleInstance.InstanceEndpoints.ContainsKey("HttpsIn"); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/CloudEnvironment.cs
C#
bsd
4,020
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Diagnostics; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Runtime { public static class CloudStorageExtensions { public static RuntimeProviders BuildRuntimeProviders(this CloudStorage.CloudStorageBuilder builder) { var formatter = new CloudFormatter(); var diagnosticsStorage = builder .WithLog(null) .WithDataSerializer(formatter) .BuildBlobStorage(); var providers = builder .WithLog(new CloudLogger(diagnosticsStorage, string.Empty)) .WithDataSerializer(formatter) .BuildStorageProviders(); return new RuntimeProviders( providers.BlobStorage, providers.QueueStorage, providers.TableStorage, providers.RuntimeFinalizer, providers.Log); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Runtime/CloudStorageExtensions.cs
C#
bsd
1,113
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Storage; namespace Lokad.Cloud.Runtime { /// <remarks> /// The purpose of having a separate class mirroring CloudStorageProviders /// just for runtime classes is to make it easier to distinct them and avoid /// mixing them up (also simplifying IoC on the way), since they have a different /// purpose and are likely configured slightly different. E.g. Runtime Providers /// have a fixed data serializer, while the application can choose it's serializer /// for it's own application code. /// </remarks> public class RuntimeProviders { /// <summary>Abstracts the Blob Storage.</summary> public IBlobStorageProvider BlobStorage { get; private set; } /// <summary>Abstracts the Queue Storage.</summary> public IQueueStorageProvider QueueStorage { get; private set; } /// <summary>Abstracts the Table Storage.</summary> public ITableStorageProvider TableStorage { get; private set; } /// <summary>Abstracts the finalizer (used for fast resource release /// in case of runtime shutdown).</summary> public IRuntimeFinalizer RuntimeFinalizer { get; private set; } public Storage.Shared.Logging.ILog Log { get; private set; } /// <summary>IoC constructor.</summary> public RuntimeProviders( IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage, ITableStorageProvider tableStorage, IRuntimeFinalizer runtimeFinalizer, Storage.Shared.Logging.ILog log) { BlobStorage = blobStorage; QueueStorage = queueStorage; TableStorage = tableStorage; RuntimeFinalizer = runtimeFinalizer; Log = log; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Runtime/RuntimeProviders.cs
C#
bsd
1,992
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Lokad.Cloud.Framework")] [assembly: AssemblyDescription("")] [assembly: AssemblyCopyright("Copyright © Lokad 2009")] [assembly: AssemblyTrademark("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("165bae5a-30f1-4b0c-bbb5-cb087ab4b88a")] [assembly: InternalsVisibleTo("Lokad.Cloud.Framework.Test")]
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Properties/AssemblyInfo.cs
C#
bsd
834
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; using Autofac.Configuration; namespace Lokad.Cloud { /// <summary> /// Provider factory for standalone use of the cloud storage toolkit (O/C mapping) /// (if not hosted as worker services in the ServiceFabric). /// </summary> public static class Standalone { /// <summary> /// Create standalone infrastructure providers using the specified settings. /// </summary> public static CloudInfrastructureProviders CreateProviders(ICloudConfigurationSettings settings) { var builder = new ContainerBuilder(); builder.RegisterModule(new CloudModule()); builder.RegisterModule(new CloudConfigurationModule(settings)); using (var container = builder.Build()) { return container.Resolve<CloudInfrastructureProviders>(); } } /// <summary> /// Create standalone infrastructure providers using the specified settings. /// </summary> public static CloudInfrastructureProviders CreateProviders(string dataConnectionString) { return CreateProviders(new RoleConfigurationSettings { DataConnectionString = dataConnectionString }); } /// <summary> /// Create standalone infrastructure providers using an IoC module configuration /// in the local config file in the specified config section. /// </summary> public static CloudInfrastructureProviders CreateProvidersFromConfiguration(string configurationSectionName) { var builder = new ContainerBuilder(); builder.RegisterModule(new CloudModule()); builder.RegisterModule(new ConfigurationSettingsReader(configurationSectionName)); using (var container = builder.Build()) { return container.Resolve<CloudInfrastructureProviders>(); } } /// <summary> /// Create standalone mock infrastructure providers. /// </summary> /// <returns></returns> public static CloudInfrastructureProviders CreateMockProviders() { var builder = new ContainerBuilder(); builder.RegisterModule(new CloudModule()); builder.RegisterModule(new Mock.MockStorageModule()); using (var container = builder.Build()) { return container.Resolve<CloudInfrastructureProviders>(); } } /// <summary> /// Create standalone infrastructure providers bound to the local development storage. /// </summary> public static CloudInfrastructureProviders CreateDevelopmentStorageProviders() { return CreateProviders("UseDevelopmentStorage=true"); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Standalone.cs
C#
bsd
2,663
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Runtime.Serialization; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Storage { /// <summary>Used as a wrapper for delayed messages (stored in the /// blob storage waiting to be pushed into a queue).</summary> /// <seealso cref="DelayedQueue.PutWithDelay{T}(T,System.DateTime)"/> /// <remarks> /// Due to genericity, this message is not tagged with <c>DataContract</c>. /// </remarks> [Serializable] class DelayedMessage { /// <summary>Name of the queue where the inner message will be put /// once the delay is expired.</summary> public string QueueName { get; set; } /// <summary>Inner message.</summary> public object InnerMessage { get; set; } /// <summary>Full constructor.</summary> public DelayedMessage(string queueName, object innerMessage) { QueueName = queueName; InnerMessage = innerMessage; } } [Serializable, DataContract] class DelayedMessageName : BlobName<DelayedMessage> { public override string ContainerName { get { return CloudService.DelayedMessageContainer; } } [Rank(0, true), DataMember] public readonly DateTimeOffset TriggerTime; [Rank(1, true), DataMember] public readonly Guid Identifier; /// <summary>Empty constructor, used for prefixing.</summary> public DelayedMessageName() { } public DelayedMessageName(DateTimeOffset triggerTime, Guid identifier) { TriggerTime = triggerTime; Identifier = identifier; } } /// <summary>Allows to put messages in a queue, delaying them as needed.</summary> /// <remarks>A <see cref="IBlobStorageProvider"/> is used for storing messages that /// must be enqueued with a delay.</remarks> public class DelayedQueue { readonly IBlobStorageProvider _provider; /// <summary>Initializes a new instance of the <see cref="DelayedQueue"/> class.</summary> /// <param name="provider">The blob storage provider.</param> public DelayedQueue(IBlobStorageProvider provider) { if(null == provider) throw new ArgumentNullException("provider"); _provider = provider; } /// <summary>Put a message into the queue implicitly associated to the type <c>T</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutWithDelay<T>(T message, DateTimeOffset triggerTime) { PutWithDelay(message, triggerTime, TypeMapper.GetStorageName(typeof(T))); } /// <summary>Put a message into the queue identified by <c>queueName</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutWithDelay<T>(T message, DateTimeOffset triggerTime, string queueName) { PutRangeWithDelay(new[] { message }, triggerTime, queueName); } /// <summary>Put messages into the queue implicitly associated to the type <c>T</c> at the /// time specified by the <c>triggerTime</c>.</summary> public void PutRangeWithDelay<T>(IEnumerable<T> messages, DateTimeOffset triggerTime) { PutRangeWithDelay(messages, triggerTime, TypeMapper.GetStorageName(typeof(T))); } /// <summary>Put messages into the queue identified by <c>queueName</c> at the /// time specified by the <c>triggerTime</c>.</summary> /// <remarks>This method acts as a delayed put operation, the message not being put /// before the <c>triggerTime</c> is reached.</remarks> public void PutRangeWithDelay<T>(IEnumerable<T> messages, DateTimeOffset triggerTime, string queueName) { foreach(var message in messages) { var blobRef = new DelayedMessageName(triggerTime, Guid.NewGuid()); var envelope = new DelayedMessage(queueName, message); _provider.PutBlob(blobRef, envelope); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Storage/DelayedQueue.cs
C#
bsd
3,933
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Core; using Autofac.Core.Registration; namespace Lokad.Cloud.Storage { /// <summary> /// Verifies that storage credentials are correct and allow access to blob and queue storage. /// </summary> public class StorageCredentialsVerifier { private readonly IBlobStorageProvider _storage; /// <summary> /// Initializes a new instance of the <see cref="T:StorageCredentialsVerifier" /> class. /// </summary> /// <param name="container">The IoC container.</param> public StorageCredentialsVerifier(IContainer container) { try { _storage = container.Resolve<IBlobStorageProvider>(); } catch(ComponentNotRegisteredException) { } catch(DependencyResolutionException) { } } /// <summary> /// Verifies the storage credentials. /// </summary> /// <returns><c>true</c> if the credentials are correct, <c>false</c> otherwise.</returns> public bool VerifyCredentials() { if(_storage == null) return false; try { var containers = _storage.ListContainers(); // It is necssary to enumerate in order to actually send the request foreach (var c in containers) { } return true; } catch { return false; } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Storage/StorageCredentialsVerifier.cs
C#
bsd
1,428
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; namespace Lokad.Cloud.Storage { /// <summary>Simple non-sharded counter shared among several workers.</summary> /// <remarks>The content of the counter is stored in a single blob value. Present design /// starts to be slow when about 50 workers are trying to modify the same counter. /// Caution : this counter is not idempotent, so using it in services could lead to incorrect behaviour.</remarks> public class BlobCounter { readonly IBlobStorageProvider _provider; readonly string _containerName; readonly string _blobName; /// <summary>Constant value provided for the cloud enumeration pattern /// over a queue.</summary> /// <remarks>The constant value is <c>2^48</c>, expected to be sufficiently /// large to avoid any arithmetic overflow with <c>long</c> values.</remarks> public const long Aleph = 1L << 48; /// <summary>Container that is storing the counter.</summary> public string ContainerName { get { return _containerName; } } /// <summary>Blob that is storing the counter.</summary> public string BlobName { get { return _blobName; } } /// <summary>Shorthand constructor.</summary> public BlobCounter(IBlobStorageProvider provider, BlobName<decimal> fullName) : this(provider, fullName.ContainerName, fullName.ToString()) { } /// <summary>Full constructor.</summary> public BlobCounter(IBlobStorageProvider provider, string containerName, string blobName) { if(null == provider) throw new ArgumentNullException("provider"); if(null == containerName) throw new ArgumentNullException("containerName"); if(null == blobName) throw new ArgumentNullException("blobName"); _provider = provider; _containerName = containerName; _blobName = blobName; } /// <summary>Returns the value of the counter (or zero if there is no value to /// be returned).</summary> public decimal GetValue() { var value = _provider.GetBlob<decimal>(_containerName, _blobName); return value.HasValue ? value.Value : 0m; } /// <summary>Atomic increment the counter value.</summary> /// <remarks>If the counter does not exist before hand, it gets created with the provided increment value.</remarks> public decimal Increment(decimal increment) { return _provider.UpsertBlob(_containerName, _blobName, () => increment, x => x + increment); } /// <summary>Reset the counter at the given value.</summary> public void Reset(decimal value) { _provider.PutBlob(_containerName, _blobName, value); } /// <summary>Deletes the counter.</summary> /// <returns><c>true</c> if the counter has actually been deleted by the call, /// and <c>false</c> otherwise.</returns> public bool Delete() { return _provider.DeleteBlobIfExist(_containerName, _blobName); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Storage/BlobCounter.cs
C#
bsd
3,032
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Net; using Autofac; using Autofac.Builder; using Lokad.Cloud.Storage.Shared; using Lokad.Cloud.Management; using Lokad.Cloud.Runtime; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; namespace Lokad.Cloud.Storage.Azure { /// <summary>IoC module that registers /// <see cref="BlobStorageProvider"/>, <see cref="QueueStorageProvider"/> and /// <see cref="TableStorageProvider"/> from the <see cref="ICloudConfigurationSettings"/>.</summary> public sealed class StorageModule : Module { static StorageModule() { } protected override void Load(ContainerBuilder builder) { builder.RegisterType<CloudFormatter>().As<IDataSerializer>().PreserveExistingDefaults(); builder.Register(StorageAccountFromSettings); builder.Register(QueueClient); builder.Register(BlobClient); builder.Register(TableClient); builder.Register(BlobStorageProvider); builder.Register(QueueStorageProvider); builder.Register(TableStorageProvider); builder.Register(RuntimeProviders); builder.Register(CloudStorageProviders); builder.Register(CloudInfrastructureProviders); } private static CloudStorageAccount StorageAccountFromSettings(IComponentContext c) { var settings = c.Resolve<ICloudConfigurationSettings>(); CloudStorageAccount account; if (CloudStorageAccount.TryParse(settings.DataConnectionString, out account)) { // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx ServicePointManager.FindServicePoint(account.BlobEndpoint).UseNagleAlgorithm = false; ServicePointManager.FindServicePoint(account.TableEndpoint).UseNagleAlgorithm = false; ServicePointManager.FindServicePoint(account.QueueEndpoint).UseNagleAlgorithm = false; return account; } throw new InvalidOperationException("Failed to get valid connection string"); } static RuntimeProviders RuntimeProviders(IComponentContext c) { return CloudStorage .ForAzureAccount(c.Resolve<CloudStorageAccount>()) .BuildRuntimeProviders(); } static CloudInfrastructureProviders CloudInfrastructureProviders(IComponentContext c) { return new CloudInfrastructureProviders( c.Resolve<CloudStorageProviders>(), c.ResolveOptional<IProvisioningProvider>()); } static CloudStorageProviders CloudStorageProviders(IComponentContext c) { return new CloudStorageProviders( c.Resolve<IBlobStorageProvider>(), c.Resolve<IQueueStorageProvider>(), c.Resolve<ITableStorageProvider>(), c.ResolveOptional<IRuntimeFinalizer>(), c.ResolveOptional<Storage.Shared.Logging.ILog>()); } static ITableStorageProvider TableStorageProvider(IComponentContext c) { IDataSerializer formatter; if (!c.TryResolve(out formatter)) { formatter = new CloudFormatter(); } return new TableStorageProvider( c.Resolve<CloudTableClient>(), formatter); } static IQueueStorageProvider QueueStorageProvider(IComponentContext c) { IDataSerializer formatter; if (!c.TryResolve(out formatter)) { formatter = new CloudFormatter(); } return new QueueStorageProvider( c.Resolve<CloudQueueClient>(), c.Resolve<IBlobStorageProvider>(), formatter, // RuntimeFinalizer is a dependency (as the name suggest) on the worker runtime // This dependency is typically not available in a pure O/C mapper scenario. // In such case, we just pass a dummy finalizer (that won't be used any c.ResolveOptional<IRuntimeFinalizer>(), c.ResolveOptional<Storage.Shared.Logging.ILog>()); } static IBlobStorageProvider BlobStorageProvider(IComponentContext c) { IDataSerializer formatter; if (!c.TryResolve(out formatter)) { formatter = new CloudFormatter(); } return new BlobStorageProvider( c.Resolve<CloudBlobClient>(), formatter, c.ResolveOptional<Storage.Shared.Logging.ILog>()); } static CloudTableClient TableClient(IComponentContext c) { var account = c.Resolve<CloudStorageAccount>(); var storage = account.CreateCloudTableClient(); storage.RetryPolicy = BuildDefaultRetry(); return storage; } static CloudBlobClient BlobClient(IComponentContext c) { var account = c.Resolve<CloudStorageAccount>(); var storage = account.CreateCloudBlobClient(); storage.RetryPolicy = BuildDefaultRetry(); return storage; } static CloudQueueClient QueueClient(IComponentContext c) { var account = c.Resolve<CloudStorageAccount>(); var queueService = account.CreateCloudQueueClient(); queueService.RetryPolicy = BuildDefaultRetry(); return queueService; } static RetryPolicy BuildDefaultRetry() { // [abdullin]: in short this gives us MinBackOff + 2^(10)*Rand.(~0.5.Seconds()) // at the last retry. Reflect the method for more details var deltaBackoff = TimeSpan.FromSeconds(0.5); return RetryPolicies.RetryExponential(10, deltaBackoff); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Storage/Azure/StorageModule.cs
C#
bsd
6,350
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; namespace Lokad.Cloud.Mock { public class MemoryLogger : Storage.Shared.Logging.ILog { public bool IsEnabled(Storage.Shared.Logging.LogLevel level) { return false; } public void Log(Storage.Shared.Logging.LogLevel level, Exception ex, object message) { //do nothing } public void Log(Storage.Shared.Logging.LogLevel level, object message) { Log(level, null, message); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Mock/MemoryLogger.cs
C#
bsd
617
using Lokad.Cloud.Management; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Mock { public class MemoryProvisioning : IProvisioningProvider { public bool IsAvailable { get { return false; } } public void SetWorkerInstanceCount(int count) { } public Maybe<int> GetWorkerInstanceCount() { return Maybe<int>.Empty; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Mock/MemoryProvisioning.cs
C#
bsd
375
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; using Lokad.Cloud.Diagnostics; using Lokad.Cloud.Management; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.InMemory; namespace Lokad.Cloud.Mock { /// <remarks></remarks> public sealed class MockStorageModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(c => new MemoryBlobStorageProvider()).As<IBlobStorageProvider>(); builder.Register(c => new MemoryQueueStorageProvider()).As<IQueueStorageProvider>(); builder.Register(c => new MemoryTableStorageProvider()).As<ITableStorageProvider>(); builder.Register(c => new MemoryLogger()).As<Storage.Shared.Logging.ILog>(); builder.Register(c => new MemoryMonitor()).As<IServiceMonitor>(); builder.Register(c => new MemoryProvisioning()).As<IProvisioningProvider>(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Mock/MockStorageModule.cs
C#
bsd
1,019
using System; using Lokad.Cloud.Diagnostics; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Mock { public class MemoryMonitor : IServiceMonitor { public IDisposable Monitor(CloudService service) { return new DisposableAction(() => { }); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Mock/MemoryMonitor.cs
C#
bsd
281
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using Lokad.Cloud.Runtime; using Lokad.Cloud.Storage; using Lokad.Cloud.ServiceFabric.Runtime; namespace Lokad.Cloud.Application { public class CloudApplicationInspector { public const string ContainerName = "lokad-cloud-assemblies"; public const string ApplicationDefinitionBlobName = "definition"; private readonly IBlobStorageProvider _blobs; public CloudApplicationInspector(RuntimeProviders runtimeProviders) { _blobs = runtimeProviders.BlobStorage; } public Maybe<CloudApplicationDefinition> Inspect() { var definitionBlob = _blobs.GetBlob<CloudApplicationDefinition>(ContainerName, ApplicationDefinitionBlobName); Maybe<byte[]> packageBlob; string packageETag; if (definitionBlob.HasValue) { packageBlob = _blobs.GetBlobIfModified<byte[]>(AssemblyLoader.ContainerName, AssemblyLoader.PackageBlobName, definitionBlob.Value.PackageETag, out packageETag); if (!packageBlob.HasValue || definitionBlob.Value.PackageETag == packageETag) { return definitionBlob.Value; } } else { packageBlob = _blobs.GetBlob<byte[]>(AssemblyLoader.ContainerName, AssemblyLoader.PackageBlobName, out packageETag); } if (!packageBlob.HasValue) { return Maybe<CloudApplicationDefinition>.Empty; } var definition = Analyze(packageBlob.Value, packageETag); _blobs.PutBlob(ContainerName, ApplicationDefinitionBlobName, definition); return definition; } private static CloudApplicationDefinition Analyze(byte[] packageData, string etag) { var reader = new CloudApplicationPackageReader(); var package = reader.ReadPackage(packageData, true); var inspectionResult = ServiceInspector.Inspect(packageData); return new CloudApplicationDefinition { PackageETag = etag, Timestamp = DateTimeOffset.UtcNow, Assemblies = package.Assemblies.ToArray(), QueueServices = inspectionResult.QueueServices.ToArray(), ScheduledServices = inspectionResult.ScheduledServices.ToArray(), CloudServices = inspectionResult.CloudServices.ToArray() }; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/CloudApplicationInspector.cs
C#
bsd
2,767
#region Copyright (c) Lokad 2009 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Reflection; namespace Lokad.Cloud.Application { /// <summary>Resolves assemblies by caching assemblies that were loaded.</summary> public sealed class AssemblyResolver { /// <summary> /// Holds the loaded assemblies. /// </summary> private readonly Dictionary<string, Assembly> _assemblyCache; /// <summary> /// Initializes an instance of the <see cref="AssemblyResolver" /> class. /// </summary> public AssemblyResolver() { _assemblyCache = new Dictionary<string, Assembly>(); } /// <summary> /// Installs the assembly resolver by hooking up to the /// <see cref="AppDomain.AssemblyResolve" /> event. /// </summary> public void Attach() { AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoad; } /// <summary> /// Uninstalls the assembly resolver. /// </summary> public void Detach() { AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolve; AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoad; _assemblyCache.Clear(); } /// <summary> /// Resolves an assembly not found by the system using the assembly cache. /// </summary> private Assembly AssemblyResolve(object sender, ResolveEventArgs args) { var isFullName = args.Name.IndexOf("Version=") != -1; // extract the simple name out of a qualified assembly name var nameOf = new Func<string, string>(qn => qn.Substring(0, qn.IndexOf(","))); // first try to find an already loaded assembly var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var assembly in assemblies) { if (isFullName) { if (assembly.FullName == args.Name || nameOf(assembly.FullName) == nameOf(args.Name)) { // return assembly from AppDomain return assembly; } } else if (assembly.GetName(false).Name == args.Name) { // return assembly from AppDomain return assembly; } } // TODO: missing optimistic assembly resolution when it comes from the cache. // find assembly in cache if (isFullName) { if (_assemblyCache.ContainsKey(args.Name)) { // return assembly from cache return _assemblyCache[args.Name]; } } else { foreach (var assembly in _assemblyCache.Values) { if (assembly.GetName(false).Name == args.Name) { // return assembly from cache return assembly; } } } return null; } /// <summary> /// Occurs when an assembly is loaded. The loaded assembly is added /// to the assembly cache. /// </summary> private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { // store assembly in cache _assemblyCache[args.LoadedAssembly.FullName] = args.LoadedAssembly; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/AssemblyResolver.cs
C#
bsd
3,928
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Application { [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/application/1.1"), Serializable] public class CloudApplicationDefinition { [DataMember(IsRequired = true)] public string PackageETag { get; set; } [DataMember(IsRequired = true)] public DateTimeOffset Timestamp { get; set; } [DataMember(IsRequired = true)] public CloudApplicationAssemblyInfo[] Assemblies { get; set; } [DataMember(IsRequired = true)] public QueueServiceDefinition[] QueueServices { get; set; } [DataMember(IsRequired = true)] public ScheduledServiceDefinition[] ScheduledServices { get; set; } [DataMember(IsRequired = true)] public CloudServiceDefinition[] CloudServices { get; set; } } public interface ICloudServiceDefinition { string TypeName { get; set; } } [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/application/1.1"), Serializable] public class QueueServiceDefinition : ICloudServiceDefinition { [DataMember(IsRequired = true)] public string TypeName { get; set; } [DataMember(IsRequired = true)] public string MessageTypeName { get; set; } [DataMember(IsRequired = true)] public string QueueName { get; set; } } [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/application/1.1"), Serializable] public class ScheduledServiceDefinition : ICloudServiceDefinition { [DataMember(IsRequired = true)] public string TypeName { get; set; } } [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/application/1.1"), Serializable] public class CloudServiceDefinition : ICloudServiceDefinition { [DataMember(IsRequired = true)] public string TypeName { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/CloudApplicationDefinition.cs
C#
bsd
2,163
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Reflection; namespace Lokad.Cloud.Application { /// <summary> /// Utility to inspect assemblies in an isolated AppDomain. /// </summary> internal static class AssemblyVersionInspector { internal static AssemblyVersionInspectionResult Inspect(byte[] assemblyBytes) { var sandbox = AppDomain.CreateDomain("AssemblyInspector", null, AppDomain.CurrentDomain.SetupInformation); try { var wrapper = (Wrapper)sandbox.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, (typeof(Wrapper)).FullName, false, BindingFlags.CreateInstance, null, new object[] { assemblyBytes }, null, new object[0]); return wrapper.Result; } finally { AppDomain.Unload(sandbox); } } [Serializable] internal class AssemblyVersionInspectionResult { public Version Version { get; set; } } /// <summary> /// Wraps an assembly (to be used from within a secondary AppDomain). /// </summary> private class Wrapper : MarshalByRefObject { internal AssemblyVersionInspectionResult Result { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Wrapper"/> class. /// </summary> /// <param name="assemblyBytes">The assembly bytes.</param> public Wrapper(byte[] assemblyBytes) { Result = new AssemblyVersionInspectionResult { Version = Assembly.ReflectionOnlyLoad(assemblyBytes).GetName().Version }; } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/AssemblyVersionInspector.cs
C#
bsd
2,161
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.IO; using ICSharpCode.SharpZipLib.Zip; namespace Lokad.Cloud.Application { public class CloudApplicationPackageReader { public CloudApplicationPackage ReadPackage(byte[] data, bool fetchVersion) { using(var stream = new MemoryStream(data)) { return ReadPackage(stream, fetchVersion); } } public CloudApplicationPackage ReadPackage(Stream stream, bool fetchVersion) { var assemblyInfos = new List<CloudApplicationAssemblyInfo>(); var assemblyBytes = new Dictionary<string, byte[]>(); var symbolBytes = new Dictionary<string, byte[]>(); using (var zipStream = new ZipInputStream(stream)) { ZipEntry entry; while ((entry = zipStream.GetNextEntry()) != null) { if (!entry.IsFile || entry.Size == 0) { continue; } var extension = Path.GetExtension(entry.Name).ToLowerInvariant(); if (extension != ".dll" && extension != ".pdb") { continue; } var isValid = true; var name = Path.GetFileNameWithoutExtension(entry.Name); var data = new byte[entry.Size]; try { zipStream.Read(data, 0, data.Length); } catch (Exception) { isValid = false; } switch (extension) { case ".dll": assemblyBytes.Add(name.ToLowerInvariant(), data); assemblyInfos.Add(new CloudApplicationAssemblyInfo { AssemblyName = name, DateTime = entry.DateTime, SizeBytes = entry.Size, IsValid = isValid, Version = new Version() }); break; case ".pdb": symbolBytes.Add(name.ToLowerInvariant(), data); break; } } } foreach (var assemblyInfo in assemblyInfos) { assemblyInfo.HasSymbols = symbolBytes.ContainsKey(assemblyInfo.AssemblyName.ToLowerInvariant()); } if (fetchVersion) { foreach (var assemblyInfo in assemblyInfos) { byte[] bytes = assemblyBytes[assemblyInfo.AssemblyName.ToLowerInvariant()]; try { assemblyInfo.Version = AssemblyVersionInspector.Inspect(bytes).Version; } catch (Exception) { assemblyInfo.IsValid = false; } } } return new CloudApplicationPackage(assemblyInfos, assemblyBytes, symbolBytes); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/CloudApplicationPackageReader.cs
C#
bsd
3,690
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Runtime.Serialization; namespace Lokad.Cloud.Application { [DataContract(Namespace = "http://schemas.lokad.com/lokad-cloud/application/1.1"), Serializable] public class CloudApplicationAssemblyInfo { /// <summary>Name of the cloud assembly.</summary> [DataMember(Order = 0, IsRequired = true)] public string AssemblyName { get; set; } /// <summary>Time stamp of the cloud assembly.</summary> [DataMember(Order = 1)] public DateTime DateTime { get; set; } /// <summary>Version of the cloud assembly.</summary> [DataMember(Order = 2)] public Version Version { get; set; } /// <summary>File size of the cloud assembly, in bytes.</summary> [DataMember(Order = 3)] public long SizeBytes { get; set; } /// <summary>Assembly can be loaded successfully.</summary> [DataMember(Order = 4)] public bool IsValid { get; set; } /// <summary>Assembly symbol store (PDB file) is available.</summary> [DataMember(Order = 5)] public bool HasSymbols { get; set; } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/CloudApplicationAssemblyInfo.cs
C#
bsd
1,328
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.Reflection; namespace Lokad.Cloud.Application { public class CloudApplicationPackage { public List<CloudApplicationAssemblyInfo> Assemblies { get; set; } private readonly Dictionary<string, byte[]> _assemblyBytes; private readonly Dictionary<string, byte[]> _symbolBytes; public CloudApplicationPackage(List<CloudApplicationAssemblyInfo> assemblyInfos, Dictionary<string, byte[]> assemblyBytes, Dictionary<string, byte[]> symbolBytes) { Assemblies = assemblyInfos; _assemblyBytes = assemblyBytes; _symbolBytes = symbolBytes; } public byte[] GetAssembly(CloudApplicationAssemblyInfo assemblyInfo) { return _assemblyBytes[assemblyInfo.AssemblyName.ToLowerInvariant()]; } public byte[] GetSymbol(CloudApplicationAssemblyInfo assemblyInfo) { return _symbolBytes[assemblyInfo.AssemblyName.ToLowerInvariant()]; } public void LoadAssemblies() { var resolver = new AssemblyResolver(); resolver.Attach(); foreach (var info in Assemblies) { if (!info.IsValid) { continue; } if (info.HasSymbols) { Assembly.Load(GetAssembly(info), GetSymbol(info)); } else { Assembly.Load(GetAssembly(info)); } } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/CloudApplicationPackage.cs
C#
bsd
1,806
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Lokad.Cloud.ServiceFabric; namespace Lokad.Cloud.Application { /// <summary> /// Utility to inspect cloud services in an isolated AppDomain. /// </summary> internal static class ServiceInspector { internal static ServiceInspectionResult Inspect(byte[] packageBytes) { var sandbox = AppDomain.CreateDomain("ServiceInspector", null, AppDomain.CurrentDomain.SetupInformation); try { var wrapper = (Wrapper)sandbox.CreateInstanceAndUnwrap( Assembly.GetExecutingAssembly().FullName, (typeof(Wrapper)).FullName, false, BindingFlags.CreateInstance, null, new object[] { packageBytes }, null, new object[0]); return wrapper.Result; } finally { AppDomain.Unload(sandbox); } } [Serializable] internal class ServiceInspectionResult { public List<QueueServiceDefinition> QueueServices { get; set; } public List<ScheduledServiceDefinition> ScheduledServices { get; set; } public List<CloudServiceDefinition> CloudServices { get; set; } } /// <summary> /// Wraps an assembly (to be used from within a secondary AppDomain). /// </summary> private class Wrapper : MarshalByRefObject { internal ServiceInspectionResult Result { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Wrapper"/> class. /// </summary> /// <param name="packageBytes">The application package bytes.</param> public Wrapper(byte[] packageBytes) { var reader = new CloudApplicationPackageReader(); var package = reader.ReadPackage(packageBytes, false); package.LoadAssemblies(); var serviceTypes = AppDomain.CurrentDomain.GetAssemblies() .Select(a => a.GetExportedTypes()).SelectMany(x => x) .Where(t => t.IsSubclassOf(typeof(CloudService)) && !t.IsAbstract && !t.IsGenericType) .ToList(); var scheduledServiceTypes = serviceTypes.Where(t => t.IsSubclassOf(typeof(ScheduledService))).ToList(); var queueServiceTypes = serviceTypes.Where(t => IsSubclassOfRawGeneric(t, typeof(QueueService<>))).ToList(); var cloudServiceTypes = serviceTypes.Except(scheduledServiceTypes).Except(queueServiceTypes).ToList(); Result = new ServiceInspectionResult { ScheduledServices = scheduledServiceTypes .Select(t => new ScheduledServiceDefinition { TypeName = t.FullName }).ToList(), CloudServices = cloudServiceTypes .Select(t => new CloudServiceDefinition { TypeName = t.FullName }).ToList(), QueueServices = queueServiceTypes .Select(t => { var messageType = GetBaseClassGenericTypeParameters(t, typeof(QueueService<>))[0]; var attribute = t.GetCustomAttributes( typeof(QueueServiceSettingsAttribute), true).FirstOrDefault() as QueueServiceSettingsAttribute; var queueName = (attribute != null && !String.IsNullOrEmpty(attribute.QueueName)) ? attribute.QueueName : TypeMapper.GetStorageName(messageType); return new QueueServiceDefinition { TypeName = t.FullName, MessageTypeName = messageType.FullName, QueueName = queueName }; }).ToList() }; } static bool IsSubclassOfRawGeneric(Type type, Type baseGenericTypeDefinition) { while (type != typeof(object)) { var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (baseGenericTypeDefinition == cur) { return true; } type = type.BaseType; } return false; } static Type[] GetBaseClassGenericTypeParameters(Type type, Type baseGenericTypeDefinition) { while (type != typeof(object)) { var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (baseGenericTypeDefinition == cur) { return type.GetGenericArguments(); } type = type.BaseType; } throw new InvalidOperationException(); } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Application/ServiceInspector.cs
C#
bsd
5,776
#region Copyright (c) Lokad 2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Lokad.Cloud.Storage; namespace Lokad.Cloud.Management { /// <summary>Defines an interface to auto-scale your cloud app.</summary> /// <remarks>The implementation relies on the Management API on Windows Azure.</remarks> public interface IProvisioningProvider { /// <summary>Indicates where the provider is correctly setup.</summary> bool IsAvailable { get; } /// <summary>Defines the number of regular VM instances to get allocated /// for the cloud app.</summary> /// <param name="count"></param> void SetWorkerInstanceCount(int count); /// <summary>Indicates the number of VM instances currently allocated /// for the cloud app.</summary> /// <remarks>If <see cref="IsAvailable"/> is <c>false</c> this method /// will be returning a <c>null</c> value.</remarks> Maybe<int> GetWorkerInstanceCount(); } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/IProvisioningProvider.cs
C#
bsd
1,010
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Linq; using System.Collections.Generic; using Lokad.Cloud.Management.Api10; using Lokad.Cloud.Runtime; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Services; using Lokad.Cloud.Storage; // TODO: blobs are sequentially enumerated, performance issue // if there are more than a few dozen services namespace Lokad.Cloud.Management { /// <summary>Management facade for scheduled cloud services.</summary> public class CloudServiceScheduling : ICloudServiceSchedulingApi { readonly IBlobStorageProvider _blobProvider; /// <summary> /// Initializes a new instance of the <see cref="CloudServiceScheduling"/> class. /// </summary> public CloudServiceScheduling(RuntimeProviders runtimeProviders) { _blobProvider = runtimeProviders.BlobStorage; } /// <summary> /// Enumerate infos of all cloud service schedules. /// </summary> public List<CloudServiceSchedulingInfo> GetSchedules() { // TODO: Redesign to make it self-contained (so that we don't need to pass the name as well) return _blobProvider.ListBlobNames(ScheduledServiceStateName.GetPrefix()) .Select(name => System.Tuple.Create(name, _blobProvider.GetBlob(name))) .Where(pair => pair.Item2.HasValue) .Select(pair => { var state = pair.Item2.Value; var info = new CloudServiceSchedulingInfo { ServiceName = pair.Item1.ServiceName, TriggerInterval = state.TriggerInterval, LastExecuted = state.LastExecuted, WorkerScoped = state.SchedulePerWorker, LeasedBy = Maybe<string>.Empty, LeasedSince = Maybe<DateTimeOffset>.Empty, LeasedUntil = Maybe<DateTimeOffset>.Empty }; if (state.Lease != null) { info.LeasedBy = state.Lease.Owner; info.LeasedSince = state.Lease.Acquired; info.LeasedUntil = state.Lease.Timeout; } return info; }) .ToList(); } /// <summary> /// Gets infos of one cloud service schedule. /// </summary> public CloudServiceSchedulingInfo GetSchedule(string serviceName) { var blob = _blobProvider.GetBlob(new ScheduledServiceStateName(serviceName)); var state = blob.Value; var info = new CloudServiceSchedulingInfo { ServiceName = serviceName, TriggerInterval = state.TriggerInterval, LastExecuted = state.LastExecuted, WorkerScoped = state.SchedulePerWorker, LeasedBy = Maybe<string>.Empty, LeasedSince = Maybe<DateTimeOffset>.Empty, LeasedUntil = Maybe<DateTimeOffset>.Empty }; if (state.Lease != null) { info.LeasedBy = state.Lease.Owner; info.LeasedSince = state.Lease.Acquired; info.LeasedUntil = state.Lease.Timeout; } return info; } /// <summary> /// Enumerate the names of all scheduled cloud service. /// </summary> public List<string> GetScheduledServiceNames() { return _blobProvider.ListBlobNames(ScheduledServiceStateName.GetPrefix()) .Select(reference => reference.ServiceName).ToList(); } /// <summary> /// Enumerate the names of all scheduled user cloud service (system services are skipped). /// </summary> public List<string> GetScheduledUserServiceNames() { var systemServices = new[] { typeof(GarbageCollectorService), typeof(DelayedQueueService), typeof(MonitoringService), typeof(MonitoringDataRetentionService), typeof(AssemblyConfigurationUpdateService) } .Select(type => type.FullName) .ToList(); return GetScheduledServiceNames() .Where(service => !systemServices.Contains(service)).ToList(); } /// <summary> /// Set the trigger interval of a cloud service. /// </summary> public void SetTriggerInterval(string serviceName, TimeSpan triggerInterval) { _blobProvider.UpdateBlobIfExist( new ScheduledServiceStateName(serviceName), state => { state.TriggerInterval = triggerInterval; return state; }); } /// <summary> /// Remove the scheduling information of a cloud service /// </summary> public void ResetSchedule(string serviceName) { _blobProvider.DeleteBlobIfExist(new ScheduledServiceStateName(serviceName)); } /// <summary> /// Forcibly remove the synchronization lease of a periodic cloud service /// </summary> public void ReleaseLease(string serviceName) { _blobProvider.UpdateBlobIfExist( new ScheduledServiceStateName(serviceName), state => { state.Lease = null; return state; }); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudServiceScheduling.cs
C#
bsd
6,231
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using Autofac; using Autofac.Builder; using Lokad.Cloud.Management.Api10; namespace Lokad.Cloud.Management { /// <summary> /// IoC module for Lokad.Cloud management classes. /// </summary> public class ManagementModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<CloudConfiguration>().As<ICloudConfigurationApi>().InstancePerDependency(); builder.RegisterType<CloudAssemblies>().As<ICloudAssembliesApi>().InstancePerDependency(); builder.RegisterType<CloudServices>().As<ICloudServicesApi>().InstancePerDependency(); builder.RegisterType<CloudServiceScheduling>().As<ICloudServiceSchedulingApi>().InstancePerDependency(); builder.RegisterType<CloudStatistics>().As<ICloudStatisticsApi>().InstancePerDependency(); // in some cases (like standalone mock storage) the RoleConfigurationSettings // will not be available. That's ok, since in this case Provisioning is not // available anyway and there's no need to make Provisioning resolveable. builder.Register(c => new CloudProvisioning( c.Resolve<ICloudConfigurationSettings>(), c.Resolve<Storage.Shared.Logging.ILog>())) .As<CloudProvisioning, IProvisioningProvider, ICloudProvisioningApi>() .SingleInstance(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/ManagementModule.cs
C#
bsd
1,494
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.IO; using System.Linq; using ICSharpCode.SharpZipLib.Zip; using Lokad.Cloud.Application; using Lokad.Cloud.Management.Api10; using Lokad.Cloud.Runtime; using Lokad.Cloud.ServiceFabric.Runtime; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Management { /// <summary>Management facade for cloud assemblies.</summary> public class CloudAssemblies : ICloudAssembliesApi { readonly RuntimeProviders _runtimeProviders; /// <summary> /// Initializes a new instance of the <see cref="CloudAssemblies"/> class. /// </summary> public CloudAssemblies(RuntimeProviders runtimeProviders) { _runtimeProviders = runtimeProviders; } public Maybe<CloudApplicationDefinition> GetApplicationDefinition() { var inspector = new CloudApplicationInspector(_runtimeProviders); return inspector.Inspect(); } /// <summary> /// Enumerate infos of all configured cloud service assemblies. /// </summary> public List<CloudApplicationAssemblyInfo> GetAssemblies() { var maybe = GetApplicationDefinition(); if(maybe.HasValue) { return maybe.Value.Assemblies.ToList(); } // empty list return new List<CloudApplicationAssemblyInfo>(); } /// <summary> /// Configure a .dll assembly file as the new cloud service assembly. /// </summary> public void UploadAssemblyDll(byte[] data, string fileName) { using (var tempStream = new MemoryStream()) { using (var zip = new ZipOutputStream(tempStream)) { zip.PutNextEntry(new ZipEntry(fileName)); zip.Write(data, 0, data.Length); zip.CloseEntry(); } UploadAssemblyZipContainer(tempStream.ToArray()); } } /// <summary> /// Configure a zip container with one or more assemblies as the new cloud services. /// </summary> public void UploadAssemblyZipContainer(byte[] data) { _runtimeProviders.BlobStorage.PutBlob( AssemblyLoader.ContainerName, AssemblyLoader.PackageBlobName, data, true); } /// <summary> /// Verify whether the provided zip container is valid. /// </summary> public bool IsValidZipContainer(byte[] data) { try { using (var dataStream = new MemoryStream(data)) using (var zipStream = new ZipInputStream(dataStream)) { ZipEntry entry; while ((entry = zipStream.GetNextEntry()) != null) { var buffer = new byte[entry.Size]; zipStream.Read(buffer, 0, buffer.Length); } } return true; } catch { return false; } } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudAssemblies.cs
C#
bsd
3,494
#region Copyright (c) Lokad 2010-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.ServiceModel.Security; using System.Text; using System.Xml.Linq; using Lokad.Cloud.Management.Api10; using Lokad.Cloud.Management.Azure; using Lokad.Cloud.Management.Azure.Entities; using Lokad.Cloud.Management.Azure.InputParameters; using Lokad.Cloud.Storage; using Lokad.Cloud.Storage.Shared.Logging; namespace Lokad.Cloud.Management { /// <summary>Azure Management API Provider, Provisioning Provider.</summary> public class CloudProvisioning : IProvisioningProvider, ICloudProvisioningApi { readonly Storage.Shared.Logging.ILog _log; readonly bool _enabled; readonly Maybe<X509Certificate2> _certificate = Maybe<X509Certificate2>.Empty; readonly Maybe<string> _deploymentId = Maybe<string>.Empty; readonly Maybe<string> _subscriptionId = Maybe<string>.Empty; readonly Storage.Shared.Policies.ActionPolicy _retryPolicy; ManagementStatus _status; Maybe<HostedService> _service = Maybe<HostedService>.Empty; Maybe<Deployment> _deployment = Maybe<Deployment>.Empty; ManagementClient _client; //[ThreadStatic] IAzureServiceManagement _channel; /// <summary>IoC constructor.</summary>> public CloudProvisioning(ICloudConfigurationSettings settings, Storage.Shared.Logging.ILog log) { _log = log; _retryPolicy = AzureManagementPolicies.TransientServerErrorBackOff; // try get settings and certificate _deploymentId = CloudEnvironment.AzureDeploymentId; _subscriptionId = settings.SelfManagementSubscriptionId ?? Maybe<string>.Empty; var certificateThumbprint = settings.SelfManagementCertificateThumbprint ?? Maybe<string>.Empty; if (certificateThumbprint.HasValue) { _certificate = CloudEnvironment.GetCertificate(certificateThumbprint.Value); } // early evaluate management status for intrinsic fault states, to skip further processing if (!_deploymentId.HasValue || !_subscriptionId.HasValue || !certificateThumbprint.HasValue) { _status = ManagementStatus.ConfigurationMissing; return; } if (!_certificate.HasValue) { _status = ManagementStatus.CertificateMissing; return; } // ok, now try find service matching the deployment _enabled = true; TryFindDeployment(); } public ManagementStatus Status { get { return _status; } } public bool IsAvailable { get { return _status == ManagementStatus.Available; } } public Maybe<X509Certificate2> Certificate { get { return _certificate; } } public Maybe<string> Subscription { get { return _subscriptionId; } } public Maybe<string> DeploymentName { get { return _deployment.Convert(d => d.Name); } } public Maybe<string> DeploymentId { get { return _deployment.Convert(d => d.PrivateID); } } public Maybe<string> DeploymentLabel { get { return _deployment.Convert(d => Base64Decode(d.Label)); } } public Maybe<DeploymentSlot> DeploymentSlot { get { return _deployment.Convert(d => d.DeploymentSlot); } } public Maybe<DeploymentStatus> DeploymentStatus { get { return _deployment.Convert(d => d.Status); } } public Maybe<string> ServiceName { get { return _service.Convert(s => s.ServiceName); } } public Maybe<string> ServiceLabel { get { return _service.Convert(s => Base64Decode(s.HostedServiceProperties.Label)); } } public Maybe<int> WorkerInstanceCount { get { return _deployment.Convert(d => d.RoleInstanceList.Count(ri => ri.RoleName == "Lokad.Cloud.WorkerRole")); } } public void Update() { if (!IsAvailable) { return; } PrepareRequest(); _deployment = _retryPolicy.Get(() => _channel.GetDeployment(_subscriptionId.Value, _service.Value.ServiceName, _deployment.Value.Name)); } Maybe<int> IProvisioningProvider.GetWorkerInstanceCount() { Update(); return WorkerInstanceCount; } public void SetWorkerInstanceCount(int count) { if(count <= 0 && count > 500) { throw new ArgumentOutOfRangeException("count"); } ChangeDeploymentConfiguration( (config, inProgress) => { XAttribute instanceCount; try { // need to be careful about namespaces instanceCount = config .Descendants() .Single(d => d.Name.LocalName == "Role" && d.Attributes().Single(a => a.Name.LocalName == "name").Value == "Lokad.Cloud.WorkerRole") .Elements() .Single(e => e.Name.LocalName == "Instances") .Attributes() .Single(a => a.Name.LocalName == "count"); } catch (Exception ex) { _log.Error(ex, "Azure Self-Management: Unexpected service configuration file format."); throw; } var oldCount = instanceCount.Value; var newCount = count.ToString(); if (inProgress) { _log.InfoFormat("Azure Self-Management: Update worker instance count from {0} to {1}. Application will be delayed because a deployment update is already in progress.", oldCount, newCount); } else { _log.InfoFormat("Azure Self-Management: Update worker instance count from {0} to {1}.", oldCount, newCount); } instanceCount.Value = newCount; }); } void ChangeDeploymentConfiguration(Action<XElement, bool> updater) { PrepareRequest(); _deployment = _retryPolicy.Get(() => _channel.GetDeployment( _subscriptionId.Value, _service.Value.ServiceName, _deployment.Value.Name)); var config = Base64Decode(_deployment.Value.Configuration); var xml = XDocument.Parse(config, LoadOptions.SetBaseUri | LoadOptions.PreserveWhitespace); var inProgress = _deployment.Value.Status != Azure.Entities.DeploymentStatus.Running; updater(xml.Root, inProgress); var newConfig = xml.ToString(SaveOptions.DisableFormatting); _retryPolicy.Do(() => _channel.ChangeConfiguration( _subscriptionId.Value, _service.Value.ServiceName, _deployment.Value.Name, new ChangeConfigurationInput { Configuration = Base64Encode(newConfig) })); } void PrepareRequest() { if (!_enabled) { throw new InvalidOperationException("not enabled"); } if (_channel == null) { if (_client == null) { _client = new ManagementClient(_certificate.Value); } _channel = _client.CreateChannel(); } if (_status == ManagementStatus.Unknown) { TryFindDeployment(); } if (_status != ManagementStatus.Available) { throw new InvalidOperationException("not operational"); } } bool TryFindDeployment() { if (!_enabled || _status != ManagementStatus.Unknown) { throw new InvalidOperationException(); } if (_channel == null) { if (_client == null) { _client = new ManagementClient(_certificate.Value); } _channel = _client.CreateChannel(); } var deployments = new List<System.Tuple<Deployment, HostedService>>(); try { var hostedServices = _retryPolicy.Get(() => _channel.ListHostedServices(_subscriptionId.Value)); foreach (var hostedService in hostedServices) { var service = _retryPolicy.Get(() => _channel.GetHostedServiceWithDetails(_subscriptionId.Value, hostedService.ServiceName, true)); if (service == null || service.Deployments == null) { _log.Warn("Azure Self-Management: skipped unexpected null service or deployment list"); continue; } foreach (var deployment in service.Deployments) { deployments.Add(System.Tuple.Create(deployment, service)); } } } catch (MessageSecurityException) { _status = ManagementStatus.AuthenticationFailed; return false; } catch (Exception ex) { _log.Error(ex, "Azure Self-Management: unexpected error when listing all hosted services."); return false; } if (deployments.Count == 0) { _log.Warn("Azure Self-Management: found no hosted service deployments"); _status = ManagementStatus.DeploymentNotFound; return false; } var selfServiceAndDeployment = deployments.FirstOrDefault(pair => pair.Item1.PrivateID == _deploymentId.Value); if (null == selfServiceAndDeployment) { _log.WarnFormat("Azure Self-Management: no hosted service deployment matches {0}", _deploymentId.Value); _status = ManagementStatus.DeploymentNotFound; return false; } _status = ManagementStatus.Available; _service = selfServiceAndDeployment.Item2; _deployment = selfServiceAndDeployment.Item1; return true; } static string Base64Decode(string value) { var bytes = Convert.FromBase64String(value); return Encoding.UTF8.GetString(bytes); } static string Base64Encode(string value) { var bytes = Encoding.UTF8.GetBytes(value); return Convert.ToBase64String(bytes); } int ICloudProvisioningApi.GetWorkerInstanceCount() { if (!IsAvailable) { throw new NotSupportedException("Provisioning not supported on this environment."); } return WorkerInstanceCount.Value; } void ICloudProvisioningApi.SetWorkerInstanceCount(int count) { if (!IsAvailable) { throw new NotSupportedException("Provisioning not supported on this environment."); } SetWorkerInstanceCount(count); } } public enum ManagementStatus { Unknown = 0, Available, ConfigurationMissing, CertificateMissing, AuthenticationFailed, DeploymentNotFound, } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudProvisioning.cs
C#
bsd
12,767
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Text; using Lokad.Cloud.Management.Api10; using Lokad.Cloud.Runtime; using Lokad.Cloud.ServiceFabric.Runtime; using Lokad.Cloud.Storage; namespace Lokad.Cloud.Management { /// <summary> /// Management facade for cloud configuration. /// </summary> public class CloudConfiguration : ICloudConfigurationApi { readonly IBlobStorageProvider _blobProvider; readonly UTF8Encoding _encoding = new UTF8Encoding(); /// <summary> /// Initializes a new instance of the <see cref="CloudConfiguration"/> class. /// </summary> public CloudConfiguration(RuntimeProviders runtimeProviders) { _blobProvider = runtimeProviders.BlobStorage; } /// <summary> /// Get the cloud configuration file. /// </summary> public string GetConfigurationString() { var buffer = _blobProvider.GetBlob<byte[]>( AssemblyLoader.ContainerName, AssemblyLoader.ConfigurationBlobName); return buffer.Convert(bytes => _encoding.GetString(bytes), String.Empty); } /// <summary> /// Set or update the cloud configuration file. /// </summary> public void SetConfiguration(string configuration) { if(configuration == null) { RemoveConfiguration(); return; } configuration = configuration.Trim(); if(String.IsNullOrEmpty(configuration)) { RemoveConfiguration(); return; } _blobProvider.PutBlob( AssemblyLoader.ContainerName, AssemblyLoader.ConfigurationBlobName, _encoding.GetBytes(configuration)); } /// <summary> /// Remove the cloud configuration file. /// </summary> public void RemoveConfiguration() { _blobProvider.DeleteBlobIfExist( AssemblyLoader.ContainerName, AssemblyLoader.ConfigurationBlobName); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudConfiguration.cs
C#
bsd
2,380
#region Copyright (c) Lokad 2009-2010 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System; using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Diagnostics; using Lokad.Cloud.Management.Api10; namespace Lokad.Cloud.Management { /// <summary>Management facade for cloud configuration.</summary> public class CloudStatistics : ICloudStatisticsApi { readonly ICloudDiagnosticsRepository _repository; /// <summary> /// Initializes a new instance of the <see cref="CloudStatistics"/> class. /// </summary> public CloudStatistics(ICloudDiagnosticsRepository diagnosticsRepository) { _repository = diagnosticsRepository; } /// <summary>Get the statistics of all cloud partitions on the provided month.</summary> public List<PartitionStatistics> GetPartitionsOfMonth(DateTime? monthUtc) { return _repository.GetAllPartitionStatistics(TimeSegments.For(TimeSegmentPeriod.Month, new DateTimeOffset(monthUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } /// <summary>Get the statistics of all cloud partitions on the provided day.</summary> public List<PartitionStatistics> GetPartitionsOfDay(DateTime? dayUtc) { return _repository.GetAllPartitionStatistics(TimeSegments.For(TimeSegmentPeriod.Day, new DateTimeOffset(dayUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } /// <summary>Get the statistics of all cloud services on the provided month.</summary> public List<ServiceStatistics> GetServicesOfMonth(DateTime? monthUtc) { return _repository.GetAllServiceStatistics(TimeSegments.For(TimeSegmentPeriod.Month, new DateTimeOffset(monthUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } /// <summary>Get the statistics of all cloud services on the provided day.</summary> public List<ServiceStatistics> GetServicesOfDay(DateTime? dayUtc) { return _repository.GetAllServiceStatistics(TimeSegments.For(TimeSegmentPeriod.Day, new DateTimeOffset(dayUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } /// <summary>Get the statistics of all execution profiles on the provided month.</summary> public List<ExecutionProfilingStatistics> GetProfilesOfMonth(DateTime? monthUtc) { return _repository.GetExecutionProfilingStatistics(TimeSegments.For(TimeSegmentPeriod.Month, new DateTimeOffset(monthUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } /// <summary>Get the statistics of all execution profiles on the provided day.</summary> public List<ExecutionProfilingStatistics> GetProfilesOfDay(DateTime? dayUtc) { return _repository.GetExecutionProfilingStatistics(TimeSegments.For(TimeSegmentPeriod.Day, new DateTimeOffset(dayUtc ?? DateTime.UtcNow, TimeSpan.Zero))).ToList(); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudStatistics.cs
C#
bsd
2,820
#region Copyright (c) Lokad 2009-2011 // This code is released under the terms of the new BSD licence. // URL: http://www.lokad.com/ #endregion using System.Collections.Generic; using System.Linq; using Lokad.Cloud.Management.Api10; using Lokad.Cloud.Runtime; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Services; using Lokad.Cloud.Storage; // TODO: blobs are sequentially enumerated, performance issue // if there are more than a few dozen services namespace Lokad.Cloud.Management { /// <summary>Management facade for cloud services.</summary> public class CloudServices : ICloudServicesApi { readonly IBlobStorageProvider _blobProvider; /// <summary> /// Initializes a new instance of the <see cref="CloudServices"/> class. /// </summary> public CloudServices(RuntimeProviders runtimeProviders) { _blobProvider = runtimeProviders.BlobStorage; } /// <summary> /// Enumerate infos of all cloud services. /// </summary> public List<CloudServiceInfo> GetServices() { // TODO: Redesign to make it self-contained (so that we don't need to pass the name as well) return _blobProvider.ListBlobNames(CloudServiceStateName.GetPrefix()) .Select(name => System.Tuple.Create(name, _blobProvider.GetBlob(name))) .Where(pair => pair.Item2.HasValue) .Select(pair => new CloudServiceInfo { ServiceName = pair.Item1.ServiceName, IsStarted = pair.Item2.Value == CloudServiceState.Started }) .ToList(); } /// <summary> /// Gets info of one cloud service. /// </summary> public CloudServiceInfo GetService(string serviceName) { var blob = _blobProvider.GetBlob(new CloudServiceStateName(serviceName)); return new CloudServiceInfo { ServiceName = serviceName, IsStarted = blob.Value == CloudServiceState.Started }; } /// <summary> /// Enumerate the names of all cloud services. /// </summary> public List<string> GetServiceNames() { return _blobProvider.ListBlobNames(CloudServiceStateName.GetPrefix()) .Select(reference => reference.ServiceName).ToList(); } /// <summary> /// Enumerate the names of all user cloud services (system services are skipped). /// </summary> public List<string> GetUserServiceNames() { var systemServices = new[] { typeof(GarbageCollectorService), typeof(DelayedQueueService), typeof(MonitoringService), typeof(MonitoringDataRetentionService), typeof(AssemblyConfigurationUpdateService) } .Select(type => type.FullName) .ToList(); return GetServiceNames() .Where(service => !systemServices.Contains(service)).ToList(); } /// <summary> /// Enable a cloud service /// </summary> public void EnableService(string serviceName) { _blobProvider.PutBlob(new CloudServiceStateName(serviceName), CloudServiceState.Started); } /// <summary> /// Disable a cloud service /// </summary> public void DisableService(string serviceName) { _blobProvider.PutBlob(new CloudServiceStateName(serviceName), CloudServiceState.Stopped); } /// <summary> /// Toggle the state of a cloud service /// </summary> public void ToggleServiceState(string serviceName) { _blobProvider.UpsertBlob( new CloudServiceStateName(serviceName), () => CloudServiceState.Started, state => state == CloudServiceState.Started ? CloudServiceState.Stopped : CloudServiceState.Started); } /// <summary> /// Remove the state information of a cloud service /// </summary> public void ResetServiceState(string serviceName) { _blobProvider.DeleteBlobIfExist(new CloudServiceStateName(serviceName)); } } }
zyyin2005-lokad
Source/Lokad.Cloud.Framework/Management/CloudServices.cs
C#
bsd
4,633