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 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-lokadclone
Source/Lokad.Cloud.Framework/Management/CloudProvisioning.cs
C#
bsd
12,767
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-lokadclone
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-lokadclone
Source/Lokad.Cloud.Framework/Mock/MockStorageModule.cs
C#
bsd
1,019
#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-lokadclone
Source/Lokad.Cloud.Framework/Mock/MemoryLogger.cs
C#
bsd
617
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-lokadclone
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 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-lokadclone
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.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-lokadclone
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.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-lokadclone
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.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-lokadclone
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; 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-lokadclone
Source/Lokad.Cloud.Framework/Application/ServiceInspector.cs
C#
bsd
5,776
#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-lokadclone
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 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-lokadclone
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-lokadclone
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 Lokad.Cloud.Management; using Lokad.Cloud.ServiceFabric; using Lokad.Cloud.Storage; namespace Lokad.Cloud { /// <summary>IoC argument for <see cref="CloudService"/> and other /// cloud abstractions.</summary> /// <remarks>This argument will be populated through Inversion Of Control (IoC) /// by the Lokad.Cloud framework itself. This class is placed in the /// <c>Lokad.Cloud.Framework</c> for convenience while inheriting a /// <see cref="CloudService"/>.</remarks> public class CloudInfrastructureProviders : CloudStorageProviders { /// <summary>Abstracts the Management API.</summary> public IProvisioningProvider Provisioning { get; set; } /// <summary>IoC constructor.</summary> public CloudInfrastructureProviders( IBlobStorageProvider blobStorage, IQueueStorageProvider queueStorage, ITableStorageProvider tableStorage, Storage.Shared.Logging.ILog log, IProvisioningProvider provisioning, IRuntimeFinalizer runtimeFinalizer) : base(blobStorage, queueStorage, tableStorage, runtimeFinalizer, log) { Provisioning = provisioning; } /// <summary>IoC constructor 2.</summary> public CloudInfrastructureProviders( CloudStorageProviders storageProviders, IProvisioningProvider provisioning) : base(storageProviders) { Provisioning = provisioning; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Framework/CloudInfrastructureProviders.cs
C#
bsd
1,716
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/CloudService.cs
C#
bsd
10,950
#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-lokadclone
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.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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/Scheduler.cs
C#
bsd
4,746
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/TriggerRestartException.cs
C#
bsd
1,147
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/NoRestartFloodPolicy.cs
C#
bsd
2,157
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/SingleRuntimeHost.cs
C#
bsd
7,265
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/AssemblyLoader.cs
C#
bsd
4,708
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/ServiceFabricHost.cs
C#
bsd
1,924
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/Runtime/Runtime.cs
C#
bsd
10,536
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/ScheduledServiceSettingsAttribute.cs
C#
bsd
1,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.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-lokadclone
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 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-lokadclone
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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/RuntimeFinalizer.cs
C#
bsd
1,642
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/QueueService.cs
C#
bsd
7,138
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/SynchronizationLeaseState.cs
C#
bsd
960
#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-lokadclone
Source/Lokad.Cloud.Framework/ServiceFabric/IInitializable.cs
C#
bsd
270
#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-lokadclone
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.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-lokadclone
Source/Lokad.Cloud.Framework/Storage/DelayedQueue.cs
C#
bsd
3,933
#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-lokadclone
Source/Lokad.Cloud.Framework/Storage/BlobCounter.cs
C#
bsd
3,032
#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-lokadclone
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; 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-lokadclone
Source/Lokad.Cloud.Framework/Storage/Azure/StorageModule.cs
C#
bsd
6,350
#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 { /// <summary>Maps types to storage names, and vice-versa.</summary> /// <remarks> /// Spec on queue names: http://msdn.microsoft.com/en-us/library/dd179349.aspx /// Spec on container names: http://msdn.microsoft.com/en-us/library/dd135715.aspx /// </remarks> public static class TypeMapper { public static string GetStorageName(Type type) { var name = type.FullName.ToLowerInvariant().Replace(".", "-"); // TODO: need a smarter behavior with long type name. if(name.Length > 63) { throw new ArgumentOutOfRangeException("type", "Type name is too long for auto-naming."); } return name; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Framework/TypeMapperProvider.cs
C#
bsd
839
#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-lokadclone
Source/Lokad.Cloud.Framework/Properties/AssemblyInfo.cs
C#
bsd
834
#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-lokadclone
Source/Lokad.Cloud.Framework/Services/MonitoringService.cs
C#
bsd
969
#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-lokadclone
Source/Lokad.Cloud.Framework/Services/MonitoringDataRetentionService.cs
C#
bsd
999
#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-lokadclone
Source/Lokad.Cloud.Framework/Services/GarbageCollectorService.cs
C#
bsd
1,894
#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-lokadclone
Source/Lokad.Cloud.Framework/Services/AssemblyConfigurationUpdateService.cs
C#
bsd
1,481
#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-lokadclone
Source/Lokad.Cloud.Framework/Services/DelayedQueueService.cs
C#
bsd
1,597
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-lokadclone
Source/Lokad.Cloud.Framework/Jobs/JobManager.cs
C#
bsd
1,202
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-lokadclone
Source/Lokad.Cloud.Framework/Jobs/Job.cs
C#
bsd
306
#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-lokadclone
Source/Lokad.Cloud.Framework/CloudConfigurationModule.cs
C#
bsd
2,603
#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-lokadclone
Source/Lokad.Cloud.Framework/CloudModule.cs
C#
bsd
1,477
#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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/PartitionMonitor.cs
C#
bsd
6,108
#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-lokadclone
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-lokadclone
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 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-lokadclone
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 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-lokadclone
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 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-lokadclone
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-lokadclone
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.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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/ServiceMonitor.cs
C#
bsd
6,692
#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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/ICloudDiagnosticsRepository.cs
C#
bsd
1,989
#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-lokadclone
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 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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/ExecutionProfilingMonitor.cs
C#
bsd
4,309
#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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/ServiceStatistics.cs
C#
bsd
1,035
#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-lokadclone
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-lokadclone
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 = "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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/Rsm/RsmMessageReport.cs
C#
bsd
978
#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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/Rsm/RsmIndicatorReport.cs
C#
bsd
1,117
#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-lokadclone
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; 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-lokadclone
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 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-lokadclone
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 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-lokadclone
Source/Lokad.Cloud.Framework/Diagnostics/IServiceMonitor.cs
C#
bsd
504
#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-lokadclone
Source/Lokad.Cloud.Framework/CloudEnvironment.cs
C#
bsd
4,020
#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.IO; using System.Runtime.Serialization; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared; namespace Lokad.Cloud.Storage { internal static class DataSerializerExtensions { public static Result<T, Exception> TryDeserializeAs<T>(this IDataSerializer serializer, Stream source) { var position = source.Position; try { var result = serializer.Deserialize(source, typeof(T)); if (result == null) { return Result<T, Exception>.CreateError(new SerializationException("Serializer returned null")); } if (!(result is T)) { return Result<T, Exception>.CreateError(new InvalidCastException( String.Format("Source was expected to be of type {0} but was of type {1}.", typeof (T).Name, result.GetType().Name))); } return Result<T, Exception>.CreateSuccess((T)result); } catch (Exception e) { return Result<T, Exception>.CreateError(e); } finally { source.Position = position; } } public static Result<object, Exception> TryDeserialize(this IDataSerializer serializer, Stream source, Type type) { var position = source.Position; try { var result = serializer.Deserialize(source, type); if (result == null) { return Result<object, Exception>.CreateError(new SerializationException("Serializer returned null")); } var actualType = result.GetType(); if (!type.IsAssignableFrom(actualType)) { return Result<object, Exception>.CreateError(new InvalidCastException( String.Format("Source was expected to be of type {0} but was of type {1}.", type.Name, actualType.Name))); } return Result<object, Exception>.CreateSuccess(result); } catch (Exception e) { return Result<object, Exception>.CreateError(e); } finally { source.Position = position; } } public static Result<T, Exception> TryDeserializeAs<T>(this IDataSerializer serializer, byte[] source) { using (var stream = new MemoryStream(source)) { return TryDeserializeAs<T>(serializer, stream); } } public static Result<XElement, Exception> TryUnpackXml(this IIntermediateDataSerializer serializer, Stream source) { var position = source.Position; try { var result = serializer.UnpackXml(source); if (result == null) { return Result<XElement, Exception>.CreateError(new SerializationException("Serializer returned null")); } return Result<XElement, Exception>.CreateSuccess(result); } catch (Exception e) { return Result<XElement, Exception>.CreateError(e); } finally { source.Position = position; } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/DataSerializerExtensions.cs
C#
bsd
3,868
#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.Xml.Linq; namespace Lokad.Cloud.Storage { /// <summary>Abstraction for the Blob Storage.</summary> /// <remarks> /// This provider represents a <em>logical</em> blob storage, not the actual /// Blob Storage. In particular, this provider deals with overflowing buffers /// that need to be split in smaller chunks to be uploaded. /// </remarks> public interface IBlobStorageProvider { /// <summary> /// List the names of all containers, matching the optional prefix if provided. /// </summary> IEnumerable<string> ListContainers(string containerNamePrefix = null); /// <summary>Creates a new blob container.</summary> /// <returns><c>true</c> if the container was actually created and <c>false</c> if /// the container already exists.</returns> /// <remarks>This operation is idempotent.</remarks> bool CreateContainerIfNotExist(string containerName); /// <summary>Delete a container.</summary> /// <returns><c>true</c> if the container has actually been deleted.</returns> /// <remarks>This operation is idempotent.</remarks> bool DeleteContainerIfExist(string containerName); /// <summary> /// List the blob names of all blobs matching both the provided container name and the optional blob name prefix. /// </summary> /// <remarks> /// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para> /// </remarks> IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null); /// <summary> /// List and get all blobs matching both the provided container name and the optional blob name prefix. /// </summary> /// <remarks> /// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para> /// </remarks> IEnumerable<T> ListBlobs<T>(string containerName, string blobNamePrefix = null, int skip = 0); /// <summary> /// Deletes a blob if it exists. /// </summary> /// <remarks> /// <para>This method is idempotent.</para> /// </remarks> bool DeleteBlobIfExist(string containerName, string blobName); /// <summary> /// Delete all blobs matching the provided blob name prefix. /// </summary> /// <remarks> /// <para>This method is idempotent.</para> /// </remarks> void DeleteAllBlobs(string containerName, string blobNamePrefix = null); /// <summary>Gets a blob.</summary> /// <returns> /// If there is no such blob, the returned object /// has its property HasValue set to <c>false</c>. /// </returns> Maybe<T> GetBlob<T>(string containerName, string blobName); /// <summary>Gets a blob.</summary> /// <typeparam name="T">Blob type.</typeparam> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="etag">Identifier assigned by the storage to the blob /// that can be used to distinguish be successive version of the blob /// (useful to check for blob update).</param> /// <returns> /// If there is no such blob, the returned object /// has its property HasValue set to <c>false</c>. /// </returns> Maybe<T> GetBlob<T>(string containerName, string blobName, out string etag); /// <summary>Gets a blob.</summary> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="type">The type of the blob.</param> /// <param name="etag">Identifier assigned by the storage to the blob /// that can be used to distinguish be successive version of the blob /// (useful to check for blob update).</param> /// <returns> /// If there is no such blob, the returned object /// has its property HasValue set to <c>false</c>. /// </returns> /// <remarks>This method should only be used when the caller does not know the type of the /// object stored in the blob at compile time, but it can only be determined at run time. /// In all other cases, you should use the generic overloads of the method.</remarks> Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag); /// <summary> /// Gets a blob in intermediate XML representation for inspection and recovery, /// if supported by the serialization formatter. /// </summary> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="etag">Identifier assigned by the storage to the blob /// that can be used to distinguish be successive version of the blob /// (useful to check for blob update).</param> /// <returns> /// If there is no such blob or the formatter supports no XML representation, /// the returned object has its property HasValue set to <c>false</c>. /// </returns> Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag); /// <summary> /// Gets a range of blobs. /// </summary> /// <typeparam name="T">Blob type.</typeparam> /// <param name="containerName">Name of the container.</param> /// <param name="blobNames">Names of the blobs.</param> /// <param name="etags">Etag identifiers for all returned blobs.</param> /// <returns>For each requested blob, an element in the array is returned in the same order. /// If a specific blob was not found, the corresponding <b>etags</b> array element is <c>null</c>.</returns> Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags); /// <summary>Gets a blob only if the etag has changed meantime.</summary> /// <typeparam name="T">Type of the blob.</typeparam> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="oldEtag">Old etag value. If this value is <c>null</c>, the blob will always /// be retrieved (except if the blob does not exist anymore).</param> /// <param name="newEtag">New etag value. Will be <c>null</c> if the blob no more exist, /// otherwise will be set to the current etag value of the blob.</param> /// <returns> /// If the blob has not been modified or if there is no such blob, /// then the returned object has its property HasValue set to <c>false</c>. /// </returns> Maybe<T> GetBlobIfModified<T>(string containerName, string blobName, string oldEtag, out string newEtag); /// <summary> /// Gets the current etag of the blob, or <c>null</c> if the blob does not exists. /// </summary> string GetBlobEtag(string containerName, string blobName); /// <summary>Puts a blob (overwrite if the blob already exists).</summary> /// <remarks>Creates the container if it does not exist beforehand.</remarks> void PutBlob<T>(string containerName, string blobName, T item); /// <summary>Puts a blob and optionally overwrite.</summary> /// <remarks>Creates the container if it does not exist beforehand.</remarks> /// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already /// exists but could not be overwritten.</returns> bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite); /// <summary>Puts a blob and optionally overwrite.</summary> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="item">Item to be put.</param> /// <param name="overwrite">Indicates whether existing blob should be overwritten /// if it exists.</param> /// <param name="etag">New etag (identifier used to track for blob change) if /// the blob is written, or <c>null</c> if no blob is written.</param> /// <remarks>Creates the container if it does not exist beforehand.</remarks> /// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already /// exists but could not be overwritten.</returns> bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite, out string etag); /// <summary>Puts a blob only if etag given in argument is matching blob's etag in blobStorage.</summary> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="item">Item to be put.</param> /// <param name="expectedEtag">etag that should be matched inside BlobStorage.</param> /// <remarks>Creates the container if it does not exist beforehand.</remarks> /// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already /// exists but version were not matching.</returns> bool PutBlob<T>(string containerName, string blobName, T item, string expectedEtag); /// <summary>Puts a blob and optionally overwrite.</summary> /// <param name="containerName">Name of the container.</param> /// <param name="blobName">Name of the blob.</param> /// <param name="item">Item to be put.</param> /// <param name="type">The type of the blob.</param> /// <param name="overwrite">Indicates whether existing blob should be overwritten /// if it exists.</param> /// <param name="etag">New etag (identifier used to track for blob change) if /// the blob is written, or <c>null</c> if no blob is written.</param> /// <remarks>Creates the container if it does not exist beforehand.</remarks> /// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already /// exists but could not be overwritten.</returns> /// <remarks>This method should only be used when the caller does not know the type of the /// object stored in the blob at compile time, but it can only be determined at run time. /// In all other cases, you should use the generic overloads of the method.</remarks> bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string etag); /// <summary> /// Updates a blob if it already exists. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist.</returns> Maybe<T> UpdateBlobIfExist<T>(string containerName, string blobName, Func<T, T> update); /// <summary> /// Updates a blob if it already exists. /// If the insert or update lambdas return empty, the blob will not be changed. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist or no change was applied.</returns> Maybe<T> UpdateBlobIfExistOrSkip<T>(string containerName, string blobName, Func<T, Maybe<T>> update); /// <summary> /// Updates a blob if it already exists. /// If the insert or update lambdas return empty, the blob will be deleted. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist or was deleted.</returns> Maybe<T> UpdateBlobIfExistOrDelete<T>(string containerName, string blobName, Func<T, Maybe<T>> update); /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda.</returns> T UpsertBlob<T>(string containerName, string blobName, Func<T> insert, Func<T, T> update); /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// If the insert or update lambdas return empty, the blob will not be changed. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda. If empty, then no change was applied.</returns> Maybe<T> UpsertBlobOrSkip<T>(string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update); /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// If the insert or update lambdas return empty, the blob will be deleted (if it exists). /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda. If empty, then the blob has been deleted.</returns> Maybe<T> UpsertBlobOrDelete<T>(string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update); /// <summary>Requests a new lease on the blob and returns its new lease ID</summary> Result<string> TryAcquireLease(string containerName, string blobName); /// <summary>Releases the lease of the blob if the provided lease ID matches.</summary> bool TryReleaseLease(string containerName, string blobName, string leaseId); /// <summary>Renews the lease of the blob if the provided lease ID matches.</summary> bool TryRenewLease(string containerName, string blobName, string leaseId); } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/IBlobStorageProvider.cs
C#
bsd
17,142
#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.Storage { /// <summary> /// Base class for strongly typed hierarchical references to blobs of a /// strongly typed content. /// </summary> /// <typeparam name="T">Type contained in the blob.</typeparam> /// <remarks> /// The type <c>T</c> is handy to strengthen the /// <see cref="StorageExtensions"/>. /// </remarks> [Serializable, DataContract] public abstract class BlobName<T> : UntypedBlobName { } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/BlobName.cs
C#
bsd
701
#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.Storage { /// <summary> /// Reference to a unique blob with a fixed limited lifespan. /// </summary> /// <remarks> /// Used in conjunction with the Gargage Collector service. Use as /// base class for custom temporary blobs with additional attributes, or use /// the method /// <see cref="GetNew(System.DateTimeOffset)"/> to instantiate a new instance /// directly linked to the garbage collected container. /// </remarks> /// <typeparam name="T">Type referred by the blob name.</typeparam> [Serializable, DataContract] public class TemporaryBlobName<T> : BlobName<T> { public const string DefaultContainerName = "lokad-cloud-temporary"; /// <summary> /// Returns the garbage collected container. /// </summary> public sealed override string ContainerName { get { return DefaultContainerName; } } [Rank(0), DataMember] public readonly DateTimeOffset Expiration; [Rank(1), DataMember] public readonly string Suffix; /// <summary> /// Explicit constructor. /// </summary> /// <param name="expiration"> /// Date that triggers the garbage collection. /// </param> /// <param name="suffix"> /// Static suffix (typically used to avoid overlaps between temporary blob name /// inheritor). If the provided suffix is <c>null</c>then the /// default prefix <c>GetType().FullName</c> is used instead. /// </param> protected TemporaryBlobName(DateTimeOffset expiration, string suffix) { Expiration = expiration; Suffix = suffix ?? GetType().FullName; } /// <summary> /// Gets a full name to a temporary blob. /// </summary> public static TemporaryBlobName<T> GetNew(DateTimeOffset expiration) { return new TemporaryBlobName<T>(expiration, Guid.NewGuid().ToString("N")); } /// <summary> /// Gets a full name to a temporary blob. /// </summary> public static TemporaryBlobName<T> GetNew(DateTimeOffset expiration, string prefix) { // hyphen used on purpose, not to interfere with parsing later on. return new TemporaryBlobName<T>(expiration, prefix + "-" + Guid.NewGuid().ToString("N")); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/TemporaryBlobName.cs
C#
bsd
2,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; namespace Lokad.Cloud.Storage { /// <summary>Used to specify the field position in the blob name.</summary> /// <remarks>The name (chosen as the abbreviation of "field position") /// is made compact not to make client code too verbose.</remarks> public class RankAttribute : Attribute { public readonly int Index; /// <summary>Indicates whether the default value (for value types) /// should be treated as 'null'. Not relevant for class types. /// </summary> public readonly bool TreatDefaultAsNull; /// <summary>Position v</summary> public RankAttribute(int index) { Index = index; } /// <summary>Position v, and default behavior.</summary> public RankAttribute(int index, bool treatDefaultAsNull) { Index = index; TreatDefaultAsNull = treatDefaultAsNull; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/RankAttribute.cs
C#
bsd
1,126
#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.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; namespace Lokad.Cloud.Storage { /// <summary> /// Base class for untyped hierarchical blob names. Implementations should /// not inherit <see cref="UntypedBlobName"/>c> but <see cref="BlobName{T}"/> instead. /// </summary> [Serializable, DataContract] public abstract class UntypedBlobName { class InheritanceComparer : IComparer<Type> { public int Compare(Type x, Type y) { if (x.Equals(y)) return 0; return x.IsSubclassOf(y) ? 1 : -1; } } /// <summary>Sortable pattern for date times.</summary> /// <remarks>Hyphens can be eventually used to refine further the iteration.</remarks> public const string DateFormatInBlobName = "yyyy-MM-dd-HH-mm-ss"; static readonly Dictionary<Type, Func<string, object>> Parsers = new Dictionary<Type, Func<string, object>>(); static readonly Dictionary<Type, Func<object, string>> Printers = new Dictionary<Type, Func<object, string>>(); /// <summary>Name of the container (to be used as a short-hand while /// operating with the <see cref="IBlobStorageProvider"/>).</summary> /// <remarks>Do not introduce an extra field for the property as /// it would be incorporated in the blob name. Instead, just /// return a constant string.</remarks> public abstract string ContainerName { get; } static UntypedBlobName() { // adding overrides // Guid: does not have default converter Printers.Add(typeof(Guid), o => ((Guid)o).ToString("N")); Parsers.Add(typeof(Guid), s => new Guid(s)); // DateTime: sortable ascending; // NOTE: not time zone safe, users have to deal with that temselves Printers.Add(typeof(DateTime), o => ((DateTime)o).ToString(DateFormatInBlobName, CultureInfo.InvariantCulture)); Parsers.Add(typeof(DateTime), s => DateTime.ParseExact(s, DateFormatInBlobName, CultureInfo.InvariantCulture)); // DateTimeOffset: sortable ascending; // time zone safe, but always returned with UTC/zero offset (comparisons can deal with that) Printers.Add(typeof(DateTimeOffset), o => ((DateTimeOffset)o).UtcDateTime.ToString(DateFormatInBlobName, CultureInfo.InvariantCulture)); Parsers.Add(typeof(DateTimeOffset), s => new DateTimeOffset(DateTime.SpecifyKind(DateTime.ParseExact(s, DateFormatInBlobName, CultureInfo.InvariantCulture), DateTimeKind.Utc))); } public override string ToString() { // Invoke a Static Generic Method using Reflection // because type is programmatically defined var method = typeof(UntypedBlobName).GetMethod("Print", BindingFlags.Static | BindingFlags.Public); // Binding the method info to generic arguments method = method.MakeGenericMethod(new[] { GetType() }); // Invoking the method and passing parameters // The null parameter is the object to call the method from. Since the method is static, pass null. return (string)method.Invoke(null, new object[] { this }); } static object InternalParse(string value, Type type) { var func = GetValue(Parsers, type, s => Convert.ChangeType(s, type)); return func(value); } static string InternalPrint(object value, Type type) { var func = GetValue(Printers, type, o => o.ToString()); return func(value); } /// <summary>Returns <paramref name="defaultValue"/> if the given <paramref name="key"/> /// is not present within the dictionary.</summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="self">The dictionary.</param> /// <param name="key">The key to look for.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value matching <paramref name="key"/> or <paramref name="defaultValue"/> if none is found</returns> static TValue GetValue<TKey, TValue>(IDictionary<TKey, TValue> self, TKey key, TValue defaultValue) { TValue value; if (self.TryGetValue(key, out value)) { return value; } return defaultValue; } class ConverterTypeCache<T> { static readonly MemberInfo[] Members; // either 'FieldInfo' or 'PropertyInfo' static readonly bool[] TreatDefaultAsNull; const string Delimeter = "/"; static readonly ConstructorInfo FirstCtor; static ConverterTypeCache() { // HACK: optimize this to IL code, if needed // NB: this approach could be used to generate F# style objects! Members = (typeof(T).GetFields().Select(f => (MemberInfo)f).Union(typeof(T).GetProperties())) .Where(f => f.GetCustomAttributes(typeof(RankAttribute), true).Any()) // ordering always respect inheritance .GroupBy(f => f.DeclaringType) .OrderBy(g => g.Key, new InheritanceComparer()) .Select(g => g.OrderBy(f => ((RankAttribute)f.GetCustomAttributes(typeof(RankAttribute), true).First()).Index)) .SelectMany(f => f) .ToArray(); TreatDefaultAsNull = Members.Select(m => ((RankAttribute) (m.GetCustomAttributes(typeof (RankAttribute), true).First())).TreatDefaultAsNull).ToArray(); FirstCtor = typeof(T).GetConstructors( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).First(); } public static string Print(T instance) { var sb = new StringBuilder(); for (int i = 0; i < Members.Length; i++) { var info = Members[i]; var fieldInfo = info as FieldInfo; var propInfo = info as PropertyInfo; var memberType = (null != fieldInfo) ? fieldInfo.FieldType : propInfo.PropertyType; var value = (null != fieldInfo) ? fieldInfo.GetValue(instance) : propInfo.GetValue(instance, new object[0]); if(null == value || (TreatDefaultAsNull[i] && IsDefaultValue(value, memberType))) { // Delimiter has to be appended here to avoid enumerating // too many blog (names being prefix of each other). // // For example, without delimiter, the prefix 'foo/123' whould enumerate both // foo/123/bar // foo/1234/bar // // Then, we should not append a delimiter if prefix is entirely empty // because it would not properly enumerate all blobs (semantic associated with // empty prefix). if (i > 0) sb.Append(Delimeter); break; } var s = InternalPrint(value, memberType); if (i > 0) sb.Append(Delimeter); sb.Append(s); } return sb.ToString(); } private static bool IsDefaultValue(object value, Type type) { if (type == typeof(string)) { return String.IsNullOrEmpty((string)value); } if (type.IsValueType) { return Activator.CreateInstance(type).Equals(value); } return value == null; } public static T Parse(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } var split = value.Split(new[] { Delimeter }, StringSplitOptions.RemoveEmptyEntries); // In order to support parsing blob names also to blob name supper classes // in case of inheritance, we simply ignore supplementary items in the name if (split.Length < Members.Length) { throw new ArgumentException("Number of items in the string is invalid. Are you missing something?", "value"); } var parameters = new object[Members.Length]; for (int i = 0; i < parameters.Length; i++) { var memberType = Members[i] is FieldInfo ? ((FieldInfo) Members[i]).FieldType : ((PropertyInfo) Members[i]).PropertyType; parameters[i] = InternalParse(split[i], memberType); } // Initialization through reflection (no assumption on constructors) var name = (T)FormatterServices.GetUninitializedObject(typeof (T)); for (int i = 0; i < Members.Length; i++) { if (Members[i] is FieldInfo) { ((FieldInfo)Members[i]).SetValue(name, parameters[i]); } else { ((PropertyInfo)Members[i]).SetValue(name, parameters[i], new object[0]); } } return name; } } /// <summary>Do not use directly, call <see cref="ToString"/> instead.</summary> public static string Print<T>(T instance) where T : UntypedBlobName { return ConverterTypeCache<T>.Print(instance); } /// <summary>Parse a hierarchical blob name.</summary> public static T Parse<T>(string value) where T : UntypedBlobName { return ConverterTypeCache<T>.Parse(value); } /// <summary>Returns the <see cref="ContainerName"/> value without /// having an instance at hand.</summary> public static string GetContainerName<T>() where T : UntypedBlobName { // HACK: that's a heavy way of getting the thing done return ((T)FormatterServices.GetUninitializedObject(typeof(T))).ContainerName; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/UntypedBlobName.cs
C#
bsd
11,396
#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.Text.RegularExpressions; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMethodReturnValue.Global namespace Lokad.Cloud.Storage { /// <summary>Helpers for the <see cref="IBlobStorageProvider"/>.</summary> public static class BlobStorageExtensions { /// <summary> /// List the blob names of all blobs matching the provided blob name prefix. /// </summary> /// <remarks> /// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para> /// </remarks> public static IEnumerable<T> ListBlobNames<T>(this IBlobStorageProvider provider, T blobNamePrefix) where T : UntypedBlobName { return provider.ListBlobNames(blobNamePrefix.ContainerName, blobNamePrefix.ToString()) .Select(UntypedBlobName.Parse<T>); } /// <summary> /// List and get all blobs matching the provided blob name prefix. /// </summary> /// <remarks> /// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para> /// </remarks> public static IEnumerable<T> ListBlobs<T>(this IBlobStorageProvider provider, BlobName<T> blobNamePrefix, int skip = 0) { return provider.ListBlobs<T>(blobNamePrefix.ContainerName, blobNamePrefix.ToString(), skip); } /// <summary> /// Deletes a blob if it exists. /// </summary> /// <remarks> /// <para>This method is idempotent.</para> /// </remarks> public static bool DeleteBlobIfExist<T>(this IBlobStorageProvider provider, BlobName<T> fullName) { return provider.DeleteBlobIfExist(fullName.ContainerName, fullName.ToString()); } /// <summary> /// Delete all blobs matching the provided blob name prefix. /// </summary> /// <remarks> /// <para>This method is idempotent.</para> /// </remarks> public static void DeleteAllBlobs(this IBlobStorageProvider provider, UntypedBlobName blobNamePrefix) { provider.DeleteAllBlobs(blobNamePrefix.ContainerName, blobNamePrefix.ToString()); } public static Maybe<T> GetBlob<T>(this IBlobStorageProvider provider, BlobName<T> name) { return provider.GetBlob<T>(name.ContainerName, name.ToString()); } public static Maybe<T> GetBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, out string etag) { return provider.GetBlob<T>(name.ContainerName, name.ToString(), out etag); } public static string GetBlobEtag<T>(this IBlobStorageProvider provider, BlobName<T> name) { return provider.GetBlobEtag(name.ContainerName, name.ToString()); } public static void PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item) { provider.PutBlob(name.ContainerName, name.ToString(), item); } public static bool PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item, bool overwrite) { return provider.PutBlob(name.ContainerName, name.ToString(), item, overwrite); } /// <summary>Push the blob only if etag is matching the etag of the blob in BlobStorage</summary> public static bool PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item, string etag) { return provider.PutBlob(name.ContainerName, name.ToString(), item, etag); } /// <summary> /// Updates a blob if it already exists. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist.</returns> public static Maybe<T> UpdateBlobIfExist<T>(this IBlobStorageProvider provider, BlobName<T> name, Func<T, T> update) { return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), () => Maybe<T>.Empty, t => update(t)); } /// <summary> /// Updates a blob if it already exists. /// If the insert or update lambdas return empty, the blob will not be changed. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist or no change was applied.</returns> public static Maybe<T> UpdateBlobIfExistOrSkip<T>( this IBlobStorageProvider provider, BlobName<T> name, Func<T, Maybe<T>> update) { return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), () => Maybe<T>.Empty, update); } /// <summary> /// Updates a blob if it already exists. /// If the insert or update lambdas return empty, the blob will be deleted. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para> /// </remarks> /// <returns>The value returned by the lambda, or empty if the blob did not exist or was deleted.</returns> public static Maybe<T> UpdateBlobIfExistOrDelete<T>( this IBlobStorageProvider provider, BlobName<T> name, Func<T, Maybe<T>> update) { return provider.UpdateBlobIfExistOrDelete(name.ContainerName, name.ToString(), update); } /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda.</returns> public static T UpsertBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, Func<T> insert, Func<T, T> update) { return provider.UpsertBlobOrSkip<T>(name.ContainerName, name.ToString(), () => insert(), t => update(t)).Value; } /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// If the insert or update lambdas return empty, the blob will not be changed. /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda. If empty, then no change was applied.</returns> public static Maybe<T> UpsertBlobOrSkip<T>(this IBlobStorageProvider provider, BlobName<T> name, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), insert, update); } /// <summary> /// Inserts or updates a blob depending on whether it already exists or not. /// If the insert or update lambdas return empty, the blob will be deleted (if it exists). /// </summary> /// <remarks> /// <para> /// The provided lambdas can be executed multiple times in case of /// concurrency-related retrials, so be careful with side-effects /// (like incrementing a counter in them). /// </para> /// <para> /// This method is idempotent if and only if the provided lambdas are idempotent /// and if the object returned by the insert lambda is an invariant to the update lambda /// (if the second condition is not met, it is idempotent after the first successful call). /// </para> /// </remarks> /// <returns>The value returned by the lambda. If empty, then the blob has been deleted.</returns> public static Maybe<T> UpsertBlobOrDelete<T>( this IBlobStorageProvider provider, BlobName<T> name, Func<Maybe<T>> insert, Func<T, Maybe<T>> update) { return provider.UpsertBlobOrDelete(name.ContainerName, name.ToString(), insert, update); } /// <summary>Checks that containerName is a valid DNS name, as requested by Azure</summary> public static bool IsContainerNameValid(string containerName) { return (Regex.IsMatch(containerName, @"(^([a-z]|\d))((-([a-z]|\d)|([a-z]|\d))+)$") && (3 <= containerName.Length) && (containerName.Length <= 63)); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Blobs/BlobStorageExtensions.cs
C#
bsd
10,748
#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.Data.Services.Client; using System.Linq; using Lokad.Cloud.Storage.Azure; using Lokad.Cloud.Storage.Shared; namespace Lokad.Cloud.Storage.InMemory { /// <summary>Mock in-memory TableStorage Provider.</summary> /// <remarks> /// All the methods of <see cref="MemoryTableStorageProvider"/> are thread-safe. /// </remarks> public class MemoryTableStorageProvider : ITableStorageProvider { /// <summary>In memory table storage : entries per table (designed for simplicity instead of performance)</summary> readonly Dictionary<string, List<MockTableEntry>> _tables; /// <summary>Formatter as requiered to handle FatEntities.</summary> internal IDataSerializer DataSerializer { get; set; } /// <summary>naive global lock to make methods thread-safe.</summary> readonly object _syncRoot; int _nextETag; /// <summary> /// Constructor for <see cref="MemoryTableStorageProvider"/>. /// </summary> public MemoryTableStorageProvider() { _tables = new Dictionary<string, List<MockTableEntry>>(); _syncRoot = new object(); DataSerializer = new CloudFormatter(); } /// <see cref="ITableStorageProvider.CreateTable"/> public bool CreateTable(string tableName) { lock (_syncRoot) { if (_tables.ContainsKey(tableName)) { //If the table already exists: return false. return false; } //create table return true. _tables.Add(tableName, new List<MockTableEntry>()); return true; } } /// <see cref="ITableStorageProvider.DeleteTable"/> public bool DeleteTable(string tableName) { lock (_syncRoot) { if (_tables.ContainsKey(tableName)) { //If the table exists remove it. _tables.Remove(tableName); return true; } //Can not remove an unexisting table. return false; } } /// <see cref="ITableStorageProvider.GetTables"/> public IEnumerable<string> GetTables() { lock (_syncRoot) { return _tables.Keys; } } /// <see cref="ITableStorageProvider.Get{T}(string)"/> IEnumerable<CloudEntity<T>> GetInternal<T>(string tableName, Func<MockTableEntry,bool> predicate) { lock (_syncRoot) { if (!_tables.ContainsKey(tableName)) { return new List<CloudEntity<T>>(); } return from entry in _tables[tableName] where predicate(entry) select entry.ToCloudEntity<T>(DataSerializer); } } /// <see cref="ITableStorageProvider.Get{T}(string)"/> public IEnumerable<CloudEntity<T>> Get<T>(string tableName) { return GetInternal<T>(tableName, entry => true); } /// <see cref="ITableStorageProvider.Get{T}(string,string)"/> public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey) { return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey); } /// <see cref="ITableStorageProvider.Get{T}(string,string,string,string)"/> public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey) { var isInRange = string.IsNullOrEmpty(endRowKey) ? (Func<string, bool>)(rowKey => string.Compare(startRowKey, rowKey) <= 0) : (rowKey => string.Compare(startRowKey, rowKey) <= 0 && string.Compare(rowKey, endRowKey) < 0); return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey && isInRange(entry.RowKey)) .OrderBy(entity => entity.RowKey); } /// <see cref="ITableStorageProvider.Get{T}(string,string,System.Collections.Generic.IEnumerable{string})"/> public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { var keys = new HashSet<string>(rowKeys); return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey && keys.Contains(entry.RowKey)); } /// <see cref="ITableStorageProvider.Insert{T}"/> public void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { lock (_syncRoot) { List<MockTableEntry> entries; if (!_tables.TryGetValue(tableName, out entries)) { _tables.Add(tableName, entries = new List<MockTableEntry>()); } // verify valid data BEFORE inserting them if (entities.Join(entries, u => ToId(u), ToId, (u, v) => true).Any()) { throw new DataServiceRequestException("INSERT: key conflict."); } if (entities.GroupBy(e => ToId(e)).Any(id => id.Count() != 1)) { throw new DataServiceRequestException("INSERT: duplicate keys."); } // ok, we can insert safely now foreach (var entity in entities) { var etag = (_nextETag++).ToString(); entity.ETag = etag; entries.Add(new MockTableEntry { PartitionKey = entity.PartitionKey, RowKey = entity.RowKey, ETag = etag, Value = FatEntity.Convert(entity, DataSerializer) }); } } } /// <see cref="ITableStorageProvider.Update{T}"/> public void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { lock (_syncRoot) { List<MockTableEntry> entries; if (!_tables.TryGetValue(tableName, out entries)) { throw new DataServiceRequestException("UPDATE: table not found."); } // verify valid data BEFORE updating them if (entities.GroupJoin(entries, u => ToId(u), ToId, (u, vs) => vs.Count(entry => force || u.ETag == null || entry.ETag == u.ETag)).Any(c => c != 1)) { throw new DataServiceRequestException("UPDATE: key not found or etag conflict."); } if (entities.GroupBy(e => ToId(e)).Any(id => id.Count() != 1)) { throw new DataServiceRequestException("UPDATE: duplicate keys."); } // ok, we can update safely now foreach (var entity in entities) { var etag = (_nextETag++).ToString(); entity.ETag = etag; var index = entries.FindIndex(entry => entry.PartitionKey == entity.PartitionKey && entry.RowKey == entity.RowKey); entries[index] = new MockTableEntry { PartitionKey = entity.PartitionKey, RowKey = entity.RowKey, ETag = etag, Value = FatEntity.Convert(entity, DataSerializer) }; } } } /// <see cref="ITableStorageProvider.Update{T}"/> public void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities) { lock (_syncRoot) { // deleting all existing entities foreach (var g in entities.GroupBy(e => e.PartitionKey)) { Delete<T>(tableName, g.Key, g.Select(e => e.RowKey)); } // inserting all entities Insert(tableName, entities); } } /// <see cref="ITableStorageProvider.Delete{T}"/> public void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys) { lock (_syncRoot) { List<MockTableEntry> entries; if (!_tables.TryGetValue(tableName, out entries)) { return; } var keys = new HashSet<string>(rowKeys); entries.RemoveAll(entry => entry.PartitionKey == partitionKey && keys.Contains(entry.RowKey)); } } /// <see cref="ITableStorageProvider.Delete{T}"/> public void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force) { lock (_syncRoot) { List<MockTableEntry> entries; if (!_tables.TryGetValue(tableName, out entries)) { return; } var entityList = entities.ToList(); // verify valid data BEFORE deleting them if (entityList.Join(entries, u => ToId(u), ToId, (u, v) => force || u.ETag == null || u.ETag == v.ETag).Any(c => !c)) { throw new DataServiceRequestException("DELETE: etag conflict."); } // ok, we can delete safely now entries.RemoveAll(entry => entityList.Any(entity => entity.PartitionKey == entry.PartitionKey && entity.RowKey == entry.RowKey)); } } static System.Tuple<string, string> ToId<T>(CloudEntity<T> entity) { return System.Tuple.Create(entity.PartitionKey, entity.RowKey); } static System.Tuple<string, string> ToId(MockTableEntry entry) { return System.Tuple.Create(entry.PartitionKey, entry.RowKey); } class MockTableEntry { public string PartitionKey { get; set; } public string RowKey { get; set; } public string ETag { get; set; } public FatEntity Value { get; set; } public CloudEntity<T> ToCloudEntity<T>(IDataSerializer serializer) { return FatEntity.Convert<T>(Value, serializer, ETag); } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/InMemory/MemoryTableStorageProvider.cs
C#
bsd
11,195
#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.Xml.Linq; using Lokad.Cloud.Storage.Shared; namespace Lokad.Cloud.Storage.InMemory { /// <summary>Mock in-memory Blob Storage.</summary> /// <remarks> /// All the methods of <see cref="MemoryBlobStorageProvider"/> are thread-safe. /// Note that the blob lease implementation is simplified such that leases do not time out. /// </remarks> public class MemoryBlobStorageProvider : IBlobStorageProvider { /// <summary> Containers Property.</summary> Dictionary<string, MockContainer> Containers { get { return _containers;} } readonly Dictionary<string, MockContainer> _containers; /// <summary>naive global lock to make methods thread-safe.</summary> readonly object _syncRoot; internal IDataSerializer DataSerializer { get; set; } /// <remarks></remarks> public MemoryBlobStorageProvider() { _containers = new Dictionary<string, MockContainer>(); _syncRoot = new object(); DataSerializer = new CloudFormatter(); } public IEnumerable<string> ListContainers(string prefix = null) { lock (_syncRoot) { if (String.IsNullOrEmpty(prefix)) { return Containers.Keys; } return Containers.Keys.Where(key => key.StartsWith(prefix)); } } public bool CreateContainerIfNotExist(string containerName) { lock (_syncRoot) { if (!BlobStorageExtensions.IsContainerNameValid(containerName)) { throw new NotSupportedException("the containerName is not compliant with azure constraints on container names"); } if (Containers.Keys.Contains(containerName)) { return false; } Containers.Add(containerName, new MockContainer()); return true; } } public bool DeleteContainerIfExist(string containerName) { lock (_syncRoot) { if (!Containers.Keys.Contains(containerName)) { return false; } Containers.Remove(containerName); return true; } } public IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null) { lock (_syncRoot) { if (!Containers.Keys.Contains(containerName)) { return Enumerable.Empty<string>(); } var names = Containers[containerName].BlobNames; return String.IsNullOrEmpty(blobNamePrefix) ? names : names.Where(name => name.StartsWith(blobNamePrefix)); } } 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) { lock (_syncRoot) { if (!Containers.Keys.Contains(containerName) || !Containers[containerName].BlobNames.Contains(blobName)) { return false; } Containers[containerName].RemoveBlob(blobName); return true; } } public void DeleteAllBlobs(string containerName, string blobNamePrefix = null) { 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 => o is T ? (T)o : Maybe<T>.Empty, Maybe<T>.Empty); } public Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag) { lock (_syncRoot) { if (!Containers.ContainsKey(containerName) || !Containers[containerName].BlobNames.Contains(blobName)) { etag = null; return Maybe<object>.Empty; } etag = Containers[containerName].BlobsEtag[blobName]; return Containers[containerName].GetBlob(blobName); } } public Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag) { etag = null; var formatter = DataSerializer as IIntermediateDataSerializer; if (formatter == null) { return Maybe<XElement>.Empty; } object data; lock (_syncRoot) { if (!Containers.ContainsKey(containerName) || !Containers[containerName].BlobNames.Contains(blobName)) { return Maybe<XElement>.Empty; } etag = Containers[containerName].BlobsEtag[blobName]; data = Containers[containerName].GetBlob(blobName); } using (var stream = new MemoryStream()) { formatter.Serialize(data, stream); stream.Position = 0; return formatter.UnpackXml(stream); } } public Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags) { // Copy-paste from BlobStorageProvider.cs var tempResult = blobNames.Select(blobName => { string etag; var blob = GetBlob<T>(containerName, blobName, out etag); return new System.Tuple<Maybe<T>, string>(blob, etag); }).ToArray(); 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) { lock (_syncRoot) { string currentEtag = GetBlobEtag(containerName, blobName); if (currentEtag == oldEtag) { newEtag = null; return Maybe<T>.Empty; } newEtag = currentEtag; return GetBlob<T>(containerName, blobName); } } public string GetBlobEtag(string containerName, string blobName) { lock (_syncRoot) { return (Containers.ContainsKey(containerName) && Containers[containerName].BlobNames.Contains(blobName)) ? Containers[containerName].BlobsEtag[blobName] : null; } } 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 ignored; return PutBlob(containerName, blobName, item, typeof (T), true, expectedEtag, out ignored); } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string etag) { return PutBlob(containerName, blobName, item, type, overwrite, null, out etag); } public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, string expectedEtag, out string etag) { lock(_syncRoot) { etag = null; if(Containers.ContainsKey(containerName)) { if(Containers[containerName].BlobNames.Contains(blobName)) { if(!overwrite || expectedEtag != null && expectedEtag != Containers[containerName].BlobsEtag[blobName]) { return false; } using (var stream = new MemoryStream()) { DataSerializer.Serialize(item, stream); } Containers[containerName].SetBlob(blobName, item); etag = Containers[containerName].BlobsEtag[blobName]; return true; } Containers[containerName].AddBlob(blobName, item); etag = Containers[containerName].BlobsEtag[blobName]; return true; } if (!BlobStorageExtensions.IsContainerNameValid(containerName)) { throw new NotSupportedException("the containerName is not compliant with azure constraints on container names"); } Containers.Add(containerName, new MockContainer()); using (var stream = new MemoryStream()) { DataSerializer.Serialize(item, stream); } Containers[containerName].AddBlob(blobName, item); etag = Containers[containerName].BlobsEtag[blobName]; return true; } } 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) { lock (_syncRoot) { Maybe<T> input; if (Containers.ContainsKey(containerName)) { if (Containers[containerName].BlobNames.Contains(blobName)) { var blobData = Containers[containerName].GetBlob(blobName); input = blobData == null ? Maybe<T>.Empty : (T)blobData; } else { input = Maybe<T>.Empty; } } else { Containers.Add(containerName, new MockContainer()); input = Maybe<T>.Empty; } var output = input.HasValue ? update(input.Value) : insert(); if (output.HasValue) { Containers[containerName].SetBlob(blobName, output.Value); } return output; } } 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; } class MockContainer { readonly Dictionary<string, object> _blobSet; readonly Dictionary<string, string> _blobsEtag; readonly Dictionary<string, string> _blobsLeases; public string[] BlobNames { get { return _blobSet.Keys.ToArray(); } } public Dictionary<string, string> BlobsEtag { get { return _blobsEtag; } } public Dictionary<string, string> BlobsLeases { get { return _blobsLeases; } } public MockContainer() { _blobSet = new Dictionary<string, object>(); _blobsEtag = new Dictionary<string, string>(); _blobsLeases = new Dictionary<string, string>(); } public void SetBlob(string blobName, object item) { _blobSet[blobName] = item; _blobsEtag[blobName] = Guid.NewGuid().ToString(); } public object GetBlob(string blobName) { return _blobSet[blobName]; } public void AddBlob(string blobName, object item) { _blobSet.Add(blobName, item); _blobsEtag.Add(blobName, Guid.NewGuid().ToString()); } public void RemoveBlob(string blobName) { _blobSet.Remove(blobName); _blobsEtag.Remove(blobName); _blobsLeases.Remove(blobName); } } public Result<string> TryAcquireLease(string containerName, string blobName) { lock (_syncRoot) { if (!Containers[containerName].BlobsLeases.ContainsKey(blobName)) { var leaseId = Guid.NewGuid().ToString("N"); Containers[containerName].BlobsLeases[blobName] = leaseId; return Result.CreateSuccess(leaseId); } return Result<string>.CreateError("Conflict"); } } public bool TryReleaseLease(string containerName, string blobName, string leaseId) { lock (_syncRoot) { string actualLeaseId; if (Containers[containerName].BlobsLeases.TryGetValue(blobName, out actualLeaseId) && actualLeaseId == leaseId) { Containers[containerName].BlobsLeases.Remove(blobName); return true; } return false; } } public bool TryRenewLease(string containerName, string blobName, string leaseId) { lock (_syncRoot) { string actualLeaseId; return Containers[containerName].BlobsLeases.TryGetValue(blobName, out actualLeaseId) && actualLeaseId == leaseId; } } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/InMemory/MemoryBlobStorageProvider.cs
C#
bsd
17,108
#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 Lokad.Cloud.Storage.Shared; using Tu = System.Tuple<string, object, System.Collections.Generic.List<byte[]>>; namespace Lokad.Cloud.Storage.InMemory { /// <summary>Mock in-memory Queue Storage.</summary> public class MemoryQueueStorageProvider : IQueueStorageProvider { /// <summary>Root used to synchronize accesses to <c>_inprocess</c>.</summary> private readonly object _sync = new object(); private readonly Dictionary<string, Queue<byte[]>> _queues; private readonly Dictionary<object, Tu> _inProcessMessages; private readonly HashSet<System.Tuple<string, string, string, byte[]>> _persistedMessages; internal IDataSerializer DataSerializer { get; set; } /// <summary>Default constructor.</summary> public MemoryQueueStorageProvider() { _queues = new Dictionary<string, Queue<byte[]>>(); _inProcessMessages = new Dictionary<object, Tu>(); _persistedMessages = new HashSet<System.Tuple<string, string, string, byte[]>>(); DataSerializer = new CloudFormatter(); } public IEnumerable<string> List(string prefix) { return _queues.Keys.Where(e => e.StartsWith(prefix)); } public IEnumerable<T> Get<T>(string queueName, int count, TimeSpan visibilityTimeout, int maxProcessingTrials) { lock (_sync) { var items = new List<T>(count); for (int i = 0; i < count; i++) { if (_queues.ContainsKey(queueName) && _queues[queueName].Any()) { var messageBytes = _queues[queueName].Dequeue(); object message; using (var stream = new MemoryStream(messageBytes)) { message = DataSerializer.Deserialize(stream, typeof (T)); } Tu inProcess; if (!_inProcessMessages.TryGetValue(message, out inProcess)) { inProcess = new Tu(queueName, message, new List<byte[]>()); _inProcessMessages.Add(message, inProcess); } inProcess.Item3.Add(messageBytes); items.Add((T)message); } } return items; } } public void Put<T>(string queueName, T message) { lock (_sync) { byte[] messageBytes; using (var stream = new MemoryStream()) { DataSerializer.Serialize(message, stream); messageBytes = stream.ToArray(); } if (!_queues.ContainsKey(queueName)) { _queues.Add(queueName, new Queue<byte[]>()); } _queues[queueName].Enqueue(messageBytes); } } public void PutRange<T>(string queueName, IEnumerable<T> messages) { lock (_sync) { foreach(var message in messages) { Put(queueName, message); } } } public void Clear(string queueName) { lock (_sync) { _queues[queueName].Clear(); var toDelete = _inProcessMessages.Where(pair => pair.Value.Item1 == queueName).ToList(); foreach(var pair in toDelete) { _inProcessMessages.Remove(pair.Key); } } } public bool Delete<T>(T message) { lock (_sync) { Tu inProcess; if (!_inProcessMessages.TryGetValue(message, out inProcess)) { return false; } inProcess.Item3.RemoveAt(0); if (inProcess.Item3.Count == 0) { _inProcessMessages.Remove(inProcess.Item2); } return true; } } public int DeleteRange<T>(IEnumerable<T> messages) { lock (_sync) { return messages.Where(Delete).Count(); } } public bool Abandon<T>(T message) { lock (_sync) { Tu inProcess; if (!_inProcessMessages.TryGetValue(message, out inProcess)) { return false; } // Add back to queue if (!_queues.ContainsKey(inProcess.Item1)) { _queues.Add(inProcess.Item1, new Queue<byte[]>()); } _queues[inProcess.Item1].Enqueue(inProcess.Item3[0]); // Remove from invisible queue inProcess.Item3.RemoveAt(0); if (inProcess.Item3.Count == 0) { _inProcessMessages.Remove(inProcess.Item2); } return true; } } public int AbandonRange<T>(IEnumerable<T> messages) { lock (_sync) { return messages.Count(Abandon); } } public bool ResumeLater<T>(T message) { // same as abandon as the InMemory provider applies no poison detection return Abandon(message); } public int ResumeLaterRange<T>(IEnumerable<T> messages) { // same as abandon as the InMemory provider applies no poison detection return AbandonRange(messages); } public void Persist<T>(T message, string storeName, string reason) { lock (_sync) { Tu inProcess; if (!_inProcessMessages.TryGetValue(message, out inProcess)) { return; } // persist var key = Guid.NewGuid().ToString("N"); _persistedMessages.Add(System.Tuple.Create(storeName, key, inProcess.Item1, inProcess.Item3[0])); // Remove from invisible queue inProcess.Item3.RemoveAt(0); if (inProcess.Item3.Count == 0) { _inProcessMessages.Remove(inProcess.Item2); } } } public void PersistRange<T>(IEnumerable<T> messages, string storeName, string reason) { lock (_sync) { foreach(var message in messages) { Persist(message, storeName, reason); } } } public IEnumerable<string> ListPersisted(string storeName) { lock (_sync) { return _persistedMessages .Where(x => x.Item1 == storeName) .Select(x => x.Item2) .ToArray(); } } public Maybe<PersistedMessage> GetPersisted(string storeName, string key) { var intermediateDataSerializer = DataSerializer as IIntermediateDataSerializer; var xmlProvider = intermediateDataSerializer != null ? new Maybe<IIntermediateDataSerializer>(intermediateDataSerializer) : Maybe<IIntermediateDataSerializer>.Empty; lock (_sync) { var tuple = _persistedMessages.FirstOrDefault(x => x.Item1 == storeName && x.Item2 == key); if(null != tuple) { return new PersistedMessage { QueueName = tuple.Item3, StoreName = tuple.Item1, Key = tuple.Item2, IsDataAvailable = true, DataXml = xmlProvider.Convert(s => s.UnpackXml(new MemoryStream(tuple.Item4))) }; } return Maybe<PersistedMessage>.Empty; } } public void DeletePersisted(string storeName, string key) { lock (_sync) { _persistedMessages.RemoveWhere(x => x.Item1 == storeName && x.Item2 == key); } } public void RestorePersisted(string storeName, string key) { lock (_sync) { var item = _persistedMessages.First(x => x.Item1 == storeName && x.Item2 == key); _persistedMessages.Remove(item); if (!_queues.ContainsKey(item.Item3)) { _queues.Add(item.Item3, new Queue<byte[]>()); } _queues[item.Item3].Enqueue(item.Item4); } } public bool DeleteQueue(string queueName) { lock (_sync) { if (!_queues.ContainsKey(queueName)) { return false; } _queues.Remove(queueName); var toDelete = _inProcessMessages.Where(pair => pair.Value.Item1 == queueName).ToList(); foreach (var pair in toDelete) { _inProcessMessages.Remove(pair.Key); } return true; } } public int GetApproximateCount(string queueName) { lock (_sync) { Queue<byte[]> queue; return _queues.TryGetValue(queueName, out queue) ? queue.Count : 0; } } public Maybe<TimeSpan> GetApproximateLatency(string queueName) { return Maybe<TimeSpan>.Empty; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/InMemory/MemoryQueueStorageProvider.cs
C#
bsd
10,697
#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; namespace Lokad.Cloud { /// <summary>Collects objects that absolutely need to be disposed /// before the runtime gets shut down.</summary> /// <remarks> /// There is no garanty that registered objects will actually be disposed. /// When a VM is shutdown, a small grace period (30s) is offered to clean-up /// resources before the OS itself is aborted. The runtime finalizer /// should be kept for very critical clean-ups to be performed during the /// grace period. /// /// Typically, the runtime finalizer is used to abandon in-process queue /// messages and lease on blobs. Any extra object that you register here /// is likely to negatively impact more prioritary clean-ups. Use with care. /// /// Implementations must be thread-safe. /// </remarks> public interface IRuntimeFinalizer { /// <summary>Register a object for high priority finalization if runtime is terminating.</summary> /// <remarks>The method is idempotent, once an object is registered, /// registering the object again has no effect.</remarks> void Register(IDisposable obj); /// <summary>Unregister a object from high priority finalization.</summary> /// <remarks>The method is idempotent, once an object is unregistered, /// unregistering the object again has no effect.</remarks> void Unregister(IDisposable obj); /// <summary> /// Finalize high-priority resources hold by the runtime. This method /// should only be called ONCE upon runtime finalization. /// </summary> void FinalizeRuntime(); } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/IRuntimeFinalizer.cs
C#
bsd
1,851
#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.IO; using System.Xml.Linq; using Lokad.Cloud.Storage.Shared; namespace Lokad.Cloud.Storage { /// <summary> /// Optional extension for custom formatters supporting an /// intermediate xml representation for inspection and recovery. /// </summary> /// <remarks> /// This extension can be implemented even when the serializer /// is not xml based but in a format that can be transformed /// to xml easily in a robust way (i.e. more robust than /// deserializing to a full object). Note that formatters /// should be registered in IoC as IBinaryFormatter, not by /// this extension interface. /// </remarks> public interface IIntermediateDataSerializer : IDataSerializer { /// <summary>Unpack and transform an object from a stream to xml.</summary> XElement UnpackXml(Stream source); /// <summary>Transform and repack an object from xml to a stream.</summary> void RepackXml(XElement data, Stream destination); } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/IIntermediateDataSerializer.cs
C#
bsd
1,191
#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-lokadclone
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; 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-lokadclone
Source/Lokad.Cloud.Storage/Queues/IQueueStorageProvider.cs
C#
bsd
9,981
#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-lokadclone
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-lokadclone
Source/Lokad.Cloud.Storage/Queues/MessageWrapper.cs
C#
bsd
677
#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.Threading; namespace Lokad.Cloud.Storage.Shared.Threading { // HACK: imported back from Lokad.Shared /// <summary> /// Helper class for invoking tasks with timeout. Overhead is 0,005 ms. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> public sealed class WaitFor<TResult> { readonly TimeSpan _timeout; /// <summary> /// Initializes a new instance of the <see cref="WaitFor{T}"/> class, /// using the specified timeout for all operations. /// </summary> /// <param name="timeout">The timeout.</param> public WaitFor(TimeSpan timeout) { _timeout = timeout; } /// <summary> /// Executes the specified function within the current thread, aborting it /// if it does not complete within the specified timeout interval. /// </summary> /// <param name="function">The function.</param> /// <returns>result of the function</returns> /// <remarks> /// The performance trick is that we do not interrupt the current /// running thread. Instead, we just create a watcher that will sleep /// until the originating thread terminates or until the timeout is /// elapsed. /// </remarks> /// <exception cref="ArgumentNullException">if function is null</exception> /// <exception cref="TimeoutException">if the function does not finish in time </exception> public TResult Run(Func<TResult> function) { if (function == null) throw new ArgumentNullException("function"); var sync = new object(); var isCompleted = false; WaitCallback watcher = obj => { var watchedThread = obj as Thread; lock (sync) { if (!isCompleted) { Monitor.Wait(sync, _timeout); } } // CAUTION: the call to Abort() can be blocking in rare situations // http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx // Hence, it should not be called with the 'lock' as it could deadlock // with the 'finally' block below. if (!isCompleted) { watchedThread.Abort(); } }; try { ThreadPool.QueueUserWorkItem(watcher, Thread.CurrentThread); return function(); } catch (ThreadAbortException) { // This is our own exception. Thread.ResetAbort(); throw new TimeoutException(string.Format("The operation has timed out after {0}.", _timeout)); } finally { lock (sync) { isCompleted = true; Monitor.Pulse(sync); } } } /// <summary> /// Executes the specified function within the current thread, aborting it /// if it does not complete within the specified timeout interval. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="function">The function.</param> /// <returns>result of the function</returns> /// <remarks> /// The performance trick is that we do not interrupt the current /// running thread. Instead, we just create a watcher that will sleep /// until the originating thread terminates or until the timeout is /// elapsed. /// </remarks> /// <exception cref="ArgumentNullException">if function is null</exception> /// <exception cref="TimeoutException">if the function does not finish in time </exception> public static TResult Run(TimeSpan timeout, Func<TResult> function) { return new WaitFor<TResult>(timeout).Run(function); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Threading/WaitFor.cs
C#
bsd
4,389
#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; using System.Threading; namespace Lokad.Cloud.Storage.Shared.Threading { ///<summary> /// Quick alternatives to PLinq with minimal overhead and simple implementations. ///</summary> public static class ParallelExtensions { static int ThreadCount = Environment.ProcessorCount; /// <summary>Executes the specified function in parallel over an array.</summary> /// <param name="input">Input array to processed in parallel.</param> /// <param name="func">The action to perform. Parameters and all the members should be immutable.</param> /// <remarks>Threads are recycled. Synchronization overhead is minimal.</remarks> public static TResult[] SelectInParallel<TItem, TResult>(this TItem[] input, Func<TItem, TResult> func) { return SelectInParallel(input, func, ThreadCount); } /// <summary> /// Executes the specified function in parallel over an array, using the provided number of threads. /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="input">Input array to processed in parallel.</param> /// <param name="func">The action to perform. Parameters and all the members should be immutable.</param> /// <param name="threadCount">The thread count.</param> /// <returns></returns> /// <remarks>Threads are recycled. Synchronization overhead is minimal.</remarks> public static TResult[] SelectInParallel<TItem, TResult>(this TItem[] input, Func<TItem, TResult> func, int threadCount) { if (input == null) throw new ArgumentNullException("input"); if (func == null) throw new ArgumentNullException("func"); if (threadCount < 1) throw new ArgumentOutOfRangeException("threadCount"); if (input.Length == 0) return new TResult[0]; var results = new TResult[input.Length]; if (threadCount == 1 || input.Length == 1) { for (int i = 0; i < input.Length; i++) { try { results[i] = func(input[i]); } catch (Exception ex) { WrapAndThrow(ex); } } return results; } // perf: no more threads than items in collection var actualThreadCount = Math.Min(threadCount, input.Length); // perf: start by syncless process, then finish with light index-based sync // to adjust varying execution time of the various threads. var threshold = Math.Max(0, input.Length - (int)Math.Sqrt(input.Length) - 2 * actualThreadCount); var workingIndex = threshold - 1; var sync = new object(); Exception exception = null; int completedCount = 0; WaitCallback worker = index => { try { // no need for lock - disjoint processing for (var i = (int)index; i < threshold; i += actualThreadCount) { results[i] = func(input[i]); } // joint processing int j; while ((j = Interlocked.Increment(ref workingIndex)) < input.Length) { results[j] = func(input[j]); } var r = Interlocked.Increment(ref completedCount); // perf: only the terminating thread actually acquires a lock. if (r == actualThreadCount && (int)index != 0) { lock (sync) Monitor.Pulse(sync); } } catch (Exception ex) { exception = ex; lock (sync) Monitor.Pulse(sync); } }; for (int i = 1; i < actualThreadCount; i++) { ThreadPool.QueueUserWorkItem(worker, i); } worker((object)0); // perf: recycle current thread // waiting until completion or failure while (completedCount < actualThreadCount && exception == null) { // CAUTION: limit on wait time is needed because if threads // have terminated // - AFTER the test of the 'while' loop, and // - BEFORE the inner 'lock' // then, there is no one left to call for 'Pulse'. lock (sync) Monitor.Wait(sync, TimeSpan.FromMilliseconds(10)); } if (exception != null) { WrapAndThrow(exception); } return results; } [DebuggerNonUserCode] static void WrapAndThrow(Exception exception) { throw new Exception("Exception caught in SelectInParallel", exception); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Threading/ParallelExtensions.cs
C#
bsd
5,625
// Imported from Lokad.Shared, 2011-02-08 using System; namespace Lokad.Cloud.Storage { /// <summary> /// Helper class that allows to pass out method call results without using exceptions /// </summary> /// <typeparam name="T">type of the associated data</typeparam> public class Result<T> : IEquatable<Result<T>> { readonly bool _isSuccess; readonly T _value; readonly string _error; Result(bool isSuccess, T value, string error) { _isSuccess = isSuccess; _value = value; _error = error; } /// <summary> /// Creates the success result. /// </summary> /// <param name="value">The value.</param> /// <returns>result encapsulating the success value</returns> /// <exception cref="ArgumentNullException">if value is a null reference type</exception> public static Result<T> CreateSuccess(T value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<T>(true, value, default(string)); } /// <summary> /// Creates the error result. /// </summary> /// <param name="error">The error.</param> /// <returns>result encapsulating the error value</returns> /// <exception cref="ArgumentNullException">if error is null</exception> public static Result<T> CreateError(string error) { if (null == error) throw new ArgumentNullException("error"); return new Result<T>(false, default(T), error); } /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Result{T}"/>. /// </summary> /// <param name="value">The item.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">if <paramref name="value"/> is a reference type that is null</exception> public static implicit operator Result<T>(T value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<T>(true, value, null); } /// <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> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Result<T>)) return false; return Equals((Result<T>) 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> public override int GetHashCode() { unchecked { int result = _isSuccess.GetHashCode(); result = (result*397) ^ _value.GetHashCode(); result = (result*397) ^ (_error != null ? _error.GetHashCode() : 0); return result; } } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(Result<T> other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._isSuccess.Equals(_isSuccess) && Equals(other._value, _value) && Equals(other._error, _error); } /// <summary> /// Gets a value indicating whether this result is valid. /// </summary> /// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value> public bool IsSuccess { get { return _isSuccess; } } /// <summary> /// item associated with this result /// </summary> public T Value { get { if (!_isSuccess) throw new InvalidOperationException("Dont access result on error. " + _error); return _value; } } /// <summary> /// Error message associated with this failure /// </summary> public string Error { get { if (_isSuccess) throw new InvalidOperationException("Dont access error on valid result."); return _error; } } /// <summary> /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Result{T}"/>. /// </summary> /// <param name="error">The error.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">If value is a null reference type</exception> public static implicit operator Result<T>(string error) { if (null == error) throw new ArgumentNullException("error"); return CreateError(error); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (!_isSuccess) return "<Error: '" + _error + "'>"; return "<Value: '" + _value + "'>"; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Monads/Result.1.cs
C#
bsd
6,824
// Imported from Lokad.Shared, 2011-02-08 using System; namespace Lokad.Cloud.Storage { /// <summary> /// Improved version of the Result[T], that could serve as a basis for it. /// </summary> /// <typeparam name="TValue">The type of the value.</typeparam> /// <typeparam name="TError">The type of the error.</typeparam> /// <remarks>It is to be moved up-stream if found useful in other projects.</remarks> public class Result<TValue, TError> : IEquatable<Result<TValue, TError>> { readonly bool _isSuccess; readonly TValue _value; readonly TError _error; Result(bool isSuccess, TValue value, TError error) { _isSuccess = isSuccess; _value = value; _error = error; } /// <summary> /// Creates the success result. /// </summary> /// <param name="value">The value.</param> /// <returns>result encapsulating the success value</returns> /// <exception cref="ArgumentNullException">if value is a null reference type</exception> public static Result<TValue, TError> CreateSuccess(TValue value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<TValue, TError>(true, value, default(TError)); } /// <summary> /// Creates the error result. /// </summary> /// <param name="error">The error.</param> /// <returns>result encapsulating the error value</returns> /// <exception cref="ArgumentNullException">if error is a null reference type</exception> public static Result<TValue, TError> CreateError(TError error) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == error) throw new ArgumentNullException("error"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Result<TValue, TError>(false, default(TValue), error); } /// <summary> /// item associated with this result /// </summary> public TValue Value { get { if (!_isSuccess) throw new InvalidOperationException("Dont access result on error. " + _error); return _value; } } /// <summary> /// Error message associated with this failure /// </summary> public TError Error { get { if (_isSuccess) throw new InvalidOperationException("Dont access error on valid result."); return _error; } } /// <summary> /// Gets a value indicating whether this result is valid. /// </summary> /// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value> public bool IsSuccess { get { return _isSuccess; } } /// <summary> /// Performs an implicit conversion from <typeparamref name="TValue"/> to <see cref="Result{TValue,TError}"/>. /// </summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">If value is a null reference type</exception> public static implicit operator Result<TValue, TError>(TValue value) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == value) throw new ArgumentNullException("value"); // ReSharper restore CompareNonConstrainedGenericWithNull return CreateSuccess(value); } /// <summary> /// Performs an implicit conversion from <typeparamref name="TError"/> to <see cref="Result{TValue,TError}"/>. /// </summary> /// <param name="error">The error.</param> /// <returns>The result of the conversion.</returns> /// <exception cref="ArgumentNullException">If value is a null reference type</exception> public static implicit operator Result<TValue, TError>(TError error) { // ReSharper disable CompareNonConstrainedGenericWithNull if (null == error) throw new ArgumentNullException("error"); // ReSharper restore CompareNonConstrainedGenericWithNull return CreateError(error); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(Result<TValue, TError> other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._isSuccess.Equals(_isSuccess) && Equals(other._value, _value) && Equals(other._error, _error); } /// <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> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (Result<TValue, TError>)) return false; return Equals((Result<TValue, TError>) 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> public override int GetHashCode() { unchecked { int result = _isSuccess.GetHashCode(); // ReSharper disable CompareNonConstrainedGenericWithNull result = (result*397) ^ (_value != null ? _value.GetHashCode() : 1); result = (result*397) ^ (_error != null ? _error.GetHashCode() : 0); // ReSharper restore CompareNonConstrainedGenericWithNull return result; } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (!_isSuccess) return "<Error: '" + _error + "'>"; return "<Value: '" + _value + "'>"; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Monads/Result.2.cs
C#
bsd
7,583
// Imported from Lokad.Shared, 2011-02-08 using System; namespace Lokad.Cloud.Storage { /// <summary> Helper class for creating <see cref="Result{T}"/> instances </summary> public static class Result { /// <summary> Creates success result </summary> /// <typeparam name="TValue">The type of the result.</typeparam> /// <param name="value">The item.</param> /// <returns>new result instance</returns> /// <seealso cref="Result{T}.CreateSuccess"/> public static Result<TValue> CreateSuccess<TValue>(TValue value) { return Result<TValue>.CreateSuccess(value); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Monads/Result.cs
C#
bsd
675
// Imported from Lokad.Shared, 2011-02-08 using System; namespace Lokad.Cloud.Storage { /// <summary> /// Helper class that indicates nullable value in a good-citizenship code /// </summary> /// <typeparam name="T">underlying type</typeparam> [Serializable] public class Maybe<T> : IEquatable<Maybe<T>> { readonly T _value; readonly bool _hasValue; Maybe(T item, bool hasValue) { _value = item; _hasValue = hasValue; } internal Maybe(T value) : this(value, true) { // ReSharper disable CompareNonConstrainedGenericWithNull if (value == null) { throw new ArgumentNullException("value"); } // ReSharper restore CompareNonConstrainedGenericWithNull } /// <summary> /// Default empty instance. /// </summary> public static readonly Maybe<T> Empty = new Maybe<T>(default(T), false); /// <summary> /// Gets the underlying value. /// </summary> /// <value>The value.</value> public T Value { get { if (!_hasValue) { throw new InvalidOperationException("Dont access value when Maybe is empty."); } return _value; } } /// <summary> /// Gets a value indicating whether this instance has value. /// </summary> /// <value><c>true</c> if this instance has value; otherwise, <c>false</c>.</value> public bool HasValue { get { return _hasValue; } } /// <summary> /// Retrieves value from this instance, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public T GetValue(Func<T> defaultValue) { return _hasValue ? _value : defaultValue(); } /// <summary> /// Retrieves value from this instance, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public T GetValue(T defaultValue) { return _hasValue ? _value : defaultValue; } /// <summary> /// Retrieves value from this instance, using a <paramref name="defaultValue"/> /// factory, if it is absent /// </summary> /// <param name="defaultValue">The default value to provide.</param> /// <returns>maybe value</returns> public Maybe<T> GetValue(Func<Maybe<T>> defaultValue) { return _hasValue ? this : defaultValue(); } /// <summary> /// Retrieves value from this instance, using a <paramref name="defaultValue"/> /// if it is absent /// </summary> /// <param name="defaultValue">The default value to provide.</param> /// <returns>maybe value</returns> public Maybe<T> GetValue(Maybe<T> defaultValue) { return _hasValue ? this : defaultValue; } /// <summary> /// Applies the specified action to the value, if it is present. /// </summary> /// <param name="action">The action.</param> /// <returns>same instance for inlining</returns> public Maybe<T> Apply(Action<T> action) { if (_hasValue) { action(_value); } return this; } /// <summary> /// Executes the specified action, if the value is absent /// </summary> /// <param name="action">The action.</param> /// <returns>same instance for inlining</returns> public Maybe<T> Handle(Action action) { if (!_hasValue) { action(); } return this; } /// <summary> /// Converts this instance to <see cref="Maybe{T}"/>, /// while applying <paramref name="converter"/> if there is a value. /// </summary> /// <typeparam name="TTarget">The type of the target.</typeparam> /// <param name="converter">The converter.</param> /// <returns></returns> public Maybe<TTarget> Convert<TTarget>(Func<T, TTarget> converter) { return _hasValue ? converter(_value) : Maybe<TTarget>.Empty; } /// <summary> /// Retrieves converted value, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <typeparam name="TTarget">type of the conversion target</typeparam> /// <param name="converter">The converter.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public TTarget Convert<TTarget>(Func<T, TTarget> converter, Func<TTarget> defaultValue) { return _hasValue ? converter(_value) : defaultValue(); } /// <summary> /// Retrieves converted value, using a /// <paramref name="defaultValue"/> if it is absent. /// </summary> /// <typeparam name="TTarget">type of the conversion target</typeparam> /// <param name="converter">The converter.</param> /// <param name="defaultValue">The default value.</param> /// <returns>value</returns> public TTarget Convert<TTarget>(Func<T, TTarget> converter, TTarget defaultValue) { return _hasValue ? converter(_value) : defaultValue; } /// <summary> /// Determines whether the specified <see cref="Maybe{T}"/> is equal to the current <see cref="Maybe{T}"/>. /// </summary> /// <param name="maybe">The <see cref="Maybe{T}"/> to compare with.</param> /// <returns>true if the objects are equal</returns> public bool Equals(Maybe<T> maybe) { if (ReferenceEquals(null, maybe)) return false; if (ReferenceEquals(this, maybe)) return true; if (_hasValue != maybe._hasValue) return false; if (!_hasValue) return true; return _value.Equals(maybe._value); } /// <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> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; var maybe = obj as Maybe<T>; if (maybe == null) return false; return Equals(maybe); } /// <summary> /// Serves as a hash function for this instance. /// </summary> /// <returns> /// A hash code for the current <see cref="Maybe{T}"/>. /// </returns> public override int GetHashCode() { unchecked { // ReSharper disable CompareNonConstrainedGenericWithNull return ((_value != null ? _value.GetHashCode() : 0)*397) ^ _hasValue.GetHashCode(); // ReSharper restore CompareNonConstrainedGenericWithNull } } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(Maybe<T> left, Maybe<T> right) { return Equals(left, right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(Maybe<T> left, Maybe<T> right) { return !Equals(left, right); } /// <summary> /// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Maybe{T}"/>. /// </summary> /// <param name="item">The item.</param> /// <returns>The result of the conversion.</returns> public static implicit operator Maybe<T>(T item) { // ReSharper disable CompareNonConstrainedGenericWithNull if (item == null) throw new ArgumentNullException("item"); // ReSharper restore CompareNonConstrainedGenericWithNull return new Maybe<T>(item); } /// <summary> /// Performs an explicit conversion from <see cref="Maybe{T}"/> to <typeparamref name="T"/>. /// </summary> /// <param name="item">The item.</param> /// <returns>The result of the conversion.</returns> public static explicit operator T(Maybe<T> item) { if (item == null) throw new ArgumentNullException("item"); if (!item.HasValue) throw new ArgumentException("May be must have value"); return item.Value; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { if (_hasValue) { return "<" + _value + ">"; } return "<Empty>"; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Monads/Maybe.1.cs
C#
bsd
10,559
#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-lokadclone
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 namespace Lokad.Cloud.Storage.Shared.Logging { /// <remarks></remarks> public interface ILogProvider { /// <remarks></remarks> ILog Get(string key); } }
zyyin2005-lokadclone
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.Logging { /// <summary> <see cref="ILog"/> that does not do anything.</summary> [Serializable] public sealed class NullLog : ILog { /// <summary> /// Singleton instance of the <see cref="NullLog"/>. /// </summary> public static readonly ILog Instance = new NullLog(); /// <summary> /// Singleton instance of the <see cref="NullLogProvider"/>. /// </summary> public static readonly ILogProvider Provider = new NullLogProvider(); NullLog() { } void ILog.Log(LogLevel level, object message) { } void ILog.Log(LogLevel level, Exception ex, object message) { } bool ILog.IsEnabled(LogLevel level) { return false; } } /// <summary>Returns the <see cref="ILog"/> that does not do anything.</summary> public sealed class NullLogProvider : ILogProvider { /// <remarks></remarks> public ILog Get(string key) { return NullLog.Instance; } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Logging/NullLog.cs
C#
bsd
1,349
#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.Globalization; namespace Lokad.Cloud.Storage.Shared.Logging { /// <summary> /// Helper extensions for any class that implements <see cref="ILog"/> /// </summary> public static class ILogExtensions { static readonly CultureInfo _culture = CultureInfo.InvariantCulture; /// <summary> /// Determines whether the specified log is recording debug messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording debug messages; otherwise, <c>false</c>. /// </returns> public static bool IsDebugEnabled(this ILog log) { return log.IsEnabled(LogLevel.Debug); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Debug(this ILog log, object message) { log.Log(LogLevel.Debug, message); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void DebugFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Debug, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Debug(this ILog log, Exception ex, object message) { log.Log(LogLevel.Debug, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Debug"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void DebugFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Debug, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording info messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording info messages; otherwise, <c>false</c>. /// </returns> public static bool IsInfoEnabled(this ILog log) { return log.IsEnabled(LogLevel.Info); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Info(this ILog log, object message) { log.Log(LogLevel.Info, message); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void InfoFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Info, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Info(this ILog log, Exception ex, object message) { log.Log(LogLevel.Info, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Info"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void InfoFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Info, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording warning messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording warning messages; otherwise, <c>false</c>. /// </returns> public static bool IsWarnEnabled(this ILog log) { return log.IsEnabled(LogLevel.Warn); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Warn(this ILog log, object message) { log.Log(LogLevel.Warn, message); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void WarnFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Warn, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Warn(this ILog log, Exception ex, object message) { log.Log(LogLevel.Warn, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Warn"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void WarnFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Warn, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording error messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording error messages; otherwise, <c>false</c>. /// </returns> public static bool IsErrorEnabled(this ILog log) { return log.IsEnabled(LogLevel.Error); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Error(this ILog log, object message) { log.Log(LogLevel.Error, message); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void ErrorFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Error, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Error(this ILog log, Exception ex, object message) { log.Log(LogLevel.Error, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Error"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void ErrorFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Error, ex, string.Format(_culture, format, args)); } /// <summary> /// Determines whether the specified log is recording Fatal messages. /// </summary> /// <param name="log">The log.</param> /// <returns> /// <c>true</c> if the specified log is recording datal messages; otherwise, <c>false</c>. /// </returns> public static bool IsFatalEnabled(this ILog log) { return log.IsEnabled(LogLevel.Fatal); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="message">Message</param> public static void Fatal(this ILog log, object message) { log.Log(LogLevel.Fatal, message); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void FatalFormat(this ILog log, string format, params object[] args) { log.Log(LogLevel.Fatal, string.Format(_culture, format, args)); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="message">Message</param> public static void Fatal(this ILog log, Exception ex, object message) { log.Log(LogLevel.Fatal, ex, message); } /// <summary> /// Writes message with <see cref="LogLevel.Fatal"/> level and /// appends the specified <see cref="Exception"/> /// </summary> /// <param name="log">Log instance being extended</param> /// <param name="ex">Exception to add to the message</param> /// <param name="format">Format string as in /// <see cref="string.Format(string,object[])"/></param> /// <param name="args">Arguments</param> public static void FatalFormat(this ILog log, Exception ex, string format, params object[] args) { log.Log(LogLevel.Fatal, ex, string.Format(_culture, format, args)); } } }
zyyin2005-lokadclone
Source/Lokad.Cloud.Storage/Shared/Logging/ILogExtensions.cs
C#
bsd
13,428
#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-lokadclone
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 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-lokadclone
Source/Lokad.Cloud.Storage/Shared/FormatUtil.cs
C#
bsd
3,951
#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-lokadclone
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; 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-lokadclone
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; 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-lokadclone
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; namespace Lokad.Cloud.Storage.Shared.Policies { interface IRetryState { bool CanRetry(Exception ex); } }
zyyin2005-lokadclone
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; 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-lokadclone
Source/Lokad.Cloud.Storage/Shared/Policies/RetryPolicy.cs
C#
bsd
953