This commit is contained in:
Rahul Kumar 2016-06-01 14:05:09 -07:00
Родитель 9b9cfdf9c7
Коммит ff7a952cbb
70 изменённых файлов: 5535 добавлений и 0 удалений

29
.gitignore поставляемый
Просмотреть файл

@ -3,3 +3,32 @@
################################################################################
/packages
/Smv2Sql/bin/Release
/Smv2Sql/obj
/Smv2Sql/Smv2Sql.csproj.user
/SmvAccessor/bin/Release
/SmvAccessor/obj
/SmvAccessorDemo/obj
/SMVActionsTable/bin/Release
/SMVActionsTable/obj
/SmvCloud/bin/Release
/SmvCloud/csx/Release
/SmvCloud/obj/Release
/SmvCloud/rcf/Release/SmvCloudWorkerContent
/SmvCloudWorker/bin/Release
/SmvCloudWorker/obj
/SmvDb/bin
/SmvDb/obj/Release
/SmvInterceptor/bin/Release
/SmvInterceptor/obj
/SmvInterceptorWrapper/bin/Release
/SmvInterceptorWrapper/obj
/SmvLibrary/bin
/SmvLibrary/obj
/SmvLineCounter/bin/Release
/SmvLineCounter/obj
/SmvSdv/bin/Release
/SmvSkeleton/bin
/SmvSkeleton/obj
/SmvTest/bin/Release
/SmvTest/obj

Просмотреть файл

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="SmvCloud" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="*" schemaVersion="2014-01.2.3">
<Role name="SmvCloudWorker">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="Microsoft.WindowsAzure.Plugins. Diagnostics.ConnectionString" value="***REMOVED***"/>
</ConfigurationSettings>
</Role>
</ServiceConfiguration>

Просмотреть файл

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<ServiceConfiguration serviceName="SmvCloud" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration" osFamily="4" osVersion="*" schemaVersion="2014-01.2.3">
<Role name="SmvCloudWorker">
<Instances count="1" />
<ConfigurationSettings>
<Setting name="Microsoft.WindowsAzure.Plugins. Diagnostics.ConnectionString" value="***REMOVED***"/>
</ConfigurationSettings>
</Role>
</ServiceConfiguration>

Просмотреть файл

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="SmvCloud" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2014-01.2.3">
<WorkerRole name="SmvCloudWorker" vmsize="Small">
<Imports>
<Import moduleName="Diagnostics" />
</Imports>
<LocalResources>
<LocalStorage name="SMVExec" cleanOnRoleRecycle="true" />
<LocalStorage name="SMVWorking" cleanOnRoleRecycle="true" />
<LocalStorage name="SMVResults" cleanOnRoleRecycle="true" />
</LocalResources>
</WorkerRole>
</ServiceDefinition>

73
Backup/SmvCloud.ccproj Normal file
Просмотреть файл

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>2.3</ProductVersion>
<ProjectGuid>3bbc4fad-85a1-4451-8975-bc00eaf81e63</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmvCloud</RootNamespace>
<AssemblyName>SmvCloud</AssemblyName>
<StartDevelopmentStorage>True</StartDevelopmentStorage>
<Name>SmvCloud</Name>
<PackageEnableRemoteDebugger>False</PackageEnableRemoteDebugger>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<!-- Items for the project -->
<ItemGroup>
<ServiceDefinition Include="ServiceDefinition.csdef" />
<ServiceConfiguration Include="ServiceConfiguration.Local.cscfg" />
<ServiceConfiguration Include="ServiceConfiguration.Cloud.cscfg" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmvCloudWorker\SmvCloudWorker.csproj">
<Name>SmvCloudWorker</Name>
<Project>{00d32586-d675-4ef4-b4f3-06dc45bbf079}</Project>
<Private>True</Private>
<RoleType>Worker</RoleType>
<RoleName>SmvCloudWorker</RoleName>
<UpdateDiagnosticsConnectionStringOnPublish>True</UpdateDiagnosticsConnectionStringOnPublish>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Folder Include="SmvCloudWorkerContent\" />
</ItemGroup>
<ItemGroup>
<Content Include="SmvCloudWorkerContent\CloudConfig.cs">
<SubType>Content</SubType>
</Content>
<Content Include="SmvCloudWorkerContent\CloudConfig.xml">
<SubType>Content</SubType>
</Content>
<Content Include="SmvCloudWorkerContent\CloudConfig.xsd">
<SubType>Content</SubType>
</Content>
<Content Include="SmvCloudWorkerContent\diagnostics.wadcfg">
<SubType>Content</SubType>
</Content>
</ItemGroup>
<!-- Import the target files for this project template -->
<PropertyGroup>
<VisualStudioVersion Condition=" '$(VisualStudioVersion)' == '' ">10.0</VisualStudioVersion>
<CloudExtensionsDir Condition=" '$(CloudExtensionsDir)' == '' ">$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Windows Azure Tools\2.3\</CloudExtensionsDir>
</PropertyGroup>
<Import Project="$(CloudExtensionsDir)Microsoft.WindowsAzure.targets" />
</Project>

Просмотреть файл

@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SmvLibrary
{
[XmlRootAttribute(Namespace = "")]
public class SMVCloudConfig
{
[XmlElementAttribute("StorageConnectionString")]
public StorageConnectionStringElement StorageConnectionString;
[XmlElementAttribute("ServiceBusConnectionString")]
public ServiceBusConnectionStringElement ServiceBusConnectionString;
}
[XmlRootAttribute("StorageConnectionString", Namespace = "")]
public class StorageConnectionStringElement
{
[XmlAttributeAttribute()]
public string Value { get; set; }
}
[XmlRootAttribute("ServiceBusConnectionString", Namespace = "")]
public class ServiceBusConnectionStringElement
{
[XmlAttributeAttribute()]
public string Value { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="SMVCloudConfig"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="SMVCloudConfig">
<xs:complexType>
<xs:sequence>
<xs:element name="StorageConnectionString" type="ConnectionStringType" minOccurs="1" maxOccurs="1" />
<xs:element name="ServiceBusConnectionString" type="ConnectionStringType" minOccurs="1" maxOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="ConnectionStringType">
<xs:attribute name="value" type="xs:string" use="required" />
</xs:complexType>
</xs:schema>

Просмотреть файл

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<DiagnosticMonitorConfiguration configurationChangePollInterval="PT1M" overallQuotaInMB="4096" xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
<DiagnosticInfrastructureLogs />
<Directories>
<IISLogs container="wad-iis-logfiles" directoryQuotaInMB="1024" />
<CrashDumps container="wad-crash-dumps" />
</Directories>
<Logs bufferQuotaInMB="1024" scheduledTransferPeriod="PT1M" scheduledTransferLogLevelFilter="Error" />
<WindowsEventLog bufferQuotaInMB="1024" scheduledTransferPeriod="PT1M" scheduledTransferLogLevelFilter="Error">
<DataSource name="Application!*" />
</WindowsEventLog>
<PerformanceCounters bufferQuotaInMB="512" scheduledTransferPeriod="PT0M">
<PerformanceCounterConfiguration counterSpecifier="\Memory\Available MBytes" sampleRate="PT3M" />
<PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\ISAPI Extension Requests/sec" sampleRate="PT3M"/>
<PerformanceCounterConfiguration counterSpecifier="\Web Service(_Total)\Bytes Total/Sec" sampleRate="PT3M"/>
<PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Requests/Sec" sampleRate="PT3M"/>
<PerformanceCounterConfiguration counterSpecifier="\ASP.NET Applications(__Total__)\Errors Total/Sec" sampleRate="PT3M"/>
<PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Queued" sampleRate="PT3M"/>
<PerformanceCounterConfiguration counterSpecifier="\ASP.NET\Requests Rejected" sampleRate="PT3M"/>
</PerformanceCounters>
</DiagnosticMonitorConfiguration>

Двоичные данные
Doc/CloudSMVActionScheduler.docx Normal file

Двоичный файл не отображается.

Двоичные данные
Doc/SMVCloudWorker.docx Normal file

Двоичный файл не отображается.

Двоичные данные
Doc/SmvConfiguration.docx Normal file

Двоичный файл не отображается.

Двоичные данные
Doc/Static Module Verifier.docx Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
namespace SMVActionsTable
{
/// <summary>
/// This class is a wrapper around the actions table that provides some useful operations.
/// </summary>
public class ActionsTableDataSource
{
private CloudTable actionsTable; /// Table where each row contains information about the action.
public ActionsTableDataSource(CloudTable table)
{
actionsTable = table;
actionsTable.CreateIfNotExists();
}
/// <summary>
/// Get an entry from the table.
/// </summary>
/// <param name="partitionKey">The partition key of the entry.</param>
/// <param name="rowKey">The row key of the entry.</param>
/// <returns>The entry if it was found in the table, null otherwise.</returns>
public ActionsTableEntry GetEntry(string partitionKey, string rowKey)
{
var retrieveOperation = TableOperation.Retrieve<ActionsTableEntry>(partitionKey, rowKey);
TableResult result = actionsTable.Execute(retrieveOperation);
if(result.Result == null)
{
return null;
}
return (ActionsTableEntry)result.Result;
}
/// <summary>
/// Get all the entries with a certain status. WARNING: Does a query across all partitions, so may be very slow.
/// </summary>
/// <param name="status">The status to use in the query.</param>
/// <returns>The entries in the table which have the given status.</returns>
public IEnumerable<ActionsTableEntry> GetEntries(ActionStatus status)
{
var query = new TableQuery<ActionsTableEntry>().Where(TableQuery.GenerateFilterConditionForInt("Status",
QueryComparisons.Equal, (int)status));
var results = actionsTable.ExecuteQuery(query);
return results;
}
/// <summary>
/// Adds an entry to the table.
/// </summary>
/// <param name="entry">The entry to be added.</param>
public void AddEntry(ActionsTableEntry entry)
{
var insertOperation = TableOperation.Insert(entry);
actionsTable.Execute(insertOperation);
}
/// <summary>
/// Updates the status of an entry in the table.
/// </summary>
/// <param name="partitionKey">Partition key of the entry.</param>
/// <param name="rowKey">Row key of the entry.</param>
/// <param name="newStatus">The new status of the entry.</param>
public void UpdateStatus(string partitionKey, string rowKey, ActionStatus newStatus)
{
var retrieveOperation = TableOperation.Retrieve<ActionsTableEntry>(partitionKey, rowKey);
TableResult result = actionsTable.Execute(retrieveOperation);
if (result.Result == null)
{
throw new ArgumentException(string.Format("Could not find an entry in the table for the given partitionKey, rowKey tuple: {0}, {1}",
partitionKey, rowKey));
}
var entry = (ActionsTableEntry)result.Result;
entry.Status = (int)newStatus;
var replaceOperation = TableOperation.Replace(entry);
actionsTable.Execute(replaceOperation);
}
/// <summary>
/// Updates the SerializedAction field of an entry in the table.
/// </summary>
/// <param name="partitionKey">Partition key of the entry.</param>
/// <param name="rowKey">Row key of the entry.</param>
/// <param name="serializedAction">The new value for the serialized action field.</param>
public void UpdateAction(string partitionKey, string rowKey, byte[] serializedAction)
{
var retrieveOperation = TableOperation.Retrieve<ActionsTableEntry>(partitionKey, rowKey);
TableResult result = actionsTable.Execute(retrieveOperation);
if (result.Result == null)
{
throw new ArgumentException(string.Format("Could not find an entry in the table for the given partitionKey, rowKey tuple: {0}, {1}",
partitionKey, rowKey));
}
var entry = (ActionsTableEntry)result.Result;
entry.SerializedAction = serializedAction;
var replaceOperation = TableOperation.Replace(entry);
actionsTable.Execute(replaceOperation);
}
}
}

Просмотреть файл

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Globalization;
namespace SMVActionsTable
{
/// <summary>
/// Denotes the status of the action.
/// </summary>
public enum ActionStatus { NotStarted, InProgress, Complete, Error };
/// <summary>
/// Represents a row in the actions table. The scheduler instance GUID is used as the partition key and the rule GUID is used as the row key.
/// </summary>
public class ActionsTableEntry : TableEntity
{
/// <summary>
/// Name of the action.
/// </summary>
public string ActionName { get; set; }
/// <summary>
/// Status of the action.
/// </summary>
public int Status { get; set; }
/// <summary>
/// The serialized action.
/// </summary>
public byte[] SerializedAction { get; set; }
/// <summary>
/// Which version of SMV to use to run this action.
/// </summary>
public string Version { get; set; }
/// <summary>
/// Path to the plugin used to run this action, relative to %smv%.
/// </summary>
public string PluginPath { get; set; }
/// <summary>
/// Hash of the module required to run this action.
/// </summary>
public string ModuleHash { get; set; }
public ActionsTableEntry()
{
ActionName = "Invalid";
RowKey = "Invalid";
PartitionKey = "Invalid";
SerializedAction = null;
Version = "Invalid";
PluginPath = "Invalid";
ModuleHash = "Invalid";
Status = (int)ActionStatus.Error;
}
public ActionsTableEntry(string actionName, string actionGuid, string schedulerInstanceGuid, byte[] serializedAction,
string version, string plugin, string moduleHash)
{
ActionName = actionName;
RowKey = actionGuid;
PartitionKey = schedulerInstanceGuid;
SerializedAction = serializedAction;
Version = version;
PluginPath = plugin;
ModuleHash = moduleHash;
Status = (int)ActionStatus.NotStarted;
}
public override string ToString()
{
return "Scheduler Instance GUID: " + PartitionKey + Environment.NewLine
+ "Action Name: " + ActionName + Environment.NewLine
+ "Action Guid: " + RowKey + Environment.NewLine
+ "Status: " + Status.ToString(CultureInfo.CurrentCulture);
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
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("SMVActionsTable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SMVActionsTable")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef2ca0f4-755d-47d9-b028-a1dbd66c4e10")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6F655D35-3867-4351-8929-23B4578E5190}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SMVActionsTable</RootNamespace>
<AssemblyName>SMVActionsTable</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.WindowsAzure.ServiceRuntime, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.WindowsAzure.Storage, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ActionsTableDataSource.cs" />
<Compile Include="ActionsTableEntry.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,36 @@
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("SmvCloudWorker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SmvCloudWorker")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b6c2f531-9088-40be-ae66-6e1308bdd26a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{00D32586-D675-4EF4-B4F3-06DC45BBF079}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmvCloudWorker</RootNamespace>
<AssemblyName>SmvCloudWorker</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<RoleType>Worker</RoleType>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Data.Edm, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Data.Edm.5.6.2\lib\net40\Microsoft.Data.Edm.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Data.OData, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Data.OData.5.6.2\lib\net40\Microsoft.Data.OData.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Data.Services.Client, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Data.Services.Client.5.6.2\lib\net40\Microsoft.Data.Services.Client.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.ServiceBus, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\WindowsAzure.ServiceBus.3.2.0\lib\net45-full\Microsoft.ServiceBus.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.WindowsAzure.ConfigurationManager.2.0.3\lib\net40\Microsoft.WindowsAzure.Configuration.dll</HintPath>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Diagnostics, Version=2.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.ServiceRuntime, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.Storage, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.5.0.6\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.Services.Client" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Spatial, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\System.Spatial.5.6.2\lib\net40\System.Spatial.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WorkerRole.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmvAccessor\SmvAccessor.csproj">
<Project>{5a923bec-71fc-48e3-b076-2a2aa81ebd03}</Project>
<Name>SmvAccessor</Name>
</ProjectReference>
<ProjectReference Include="..\SMVActionsTable\SMVActionsTable.csproj">
<Project>{6f655d35-3867-4351-8929-23b4578e5190}</Project>
<Name>SMVActionsTable</Name>
</ProjectReference>
<ProjectReference Include="..\SMVLibrary\SmvLibrary.csproj">
<Project>{e03dc0df-84cc-420c-91b1-2a937e88ff31}</Project>
<Name>SmvLibrary</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,410 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO.Compression;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.Queue;
using SmvLibrary;
using SMVActionsTable;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using Microsoft.ServiceBus.Messaging;
using Microsoft.ServiceBus;
namespace SmvCloudWorker2
{
public class WorkerRole : RoleEntryPoint
{
private TopicClient outputTopic; /// Output topic to inform the clients of results.
private SMVCloudConfig cloudConfig; /// Object containing connection strings.
private bool acceptingMessages = true; /// Set to false when the worker stops accepting new messages.
private BlobRequestOptions options; /// Options for blob storage.
private CloudQueue inputQueue; /// Queue with the actions to be executed.
private CloudBlobContainer jobsContainer; /// Jobs are downloaded from here.
private CloudBlobContainer resultsContainer; /// Results are uploaded here.
private CloudBlobContainer versionsContainer; /// SMV versions are downloaded from here.
private ActionsTableDataSource tableDataSource; /// Used to interact with the actions table.
private string workingDirectory; /// The working directory for SMV.
private string resultsDirectory; /// A temporary location for the result zip files.
private string smvVersionsDirectory; /// The directory containing the SMV versions.
private string smvDirectory; /// The directory containing the current SMV version.
private CloudQueueMessage currentMessage; /// The message being currently processed.
/// Maps names of SMV versions to their locations on the file system.
private IDictionary<string, Tuple<string, DateTime>> smvVersions = new Dictionary<string, Tuple<string, DateTime>>();
private void SendMessageToTopic(BrokeredMessage msg)
{
bool done = false;
for (int retryCount = 1; !done; retryCount++)
{
done = true;
try
{
outputTopic = TopicClient.CreateFromConnectionString(cloudConfig.ServiceBusConnectionString.value, CloudConstants.ResultsTopicName);
outputTopic.Send(msg);
outputTopic.Close();
}
catch (Exception)
{
if (retryCount == CloudConstants.MaxRetries)
{
throw;
}
done = false;
System.Threading.Thread.Sleep(CloudConstants.RetryBackoffInterval);
}
}
}
public override void Run()
{
while (acceptingMessages)
{
System.Threading.Thread.Sleep(30 * 1000);
try
{
currentMessage = inputQueue.GetMessage(TimeSpan.FromHours(1));
if (currentMessage != null)
{
// Parse the message.
string[] msgParts = currentMessage.AsString.Split(',');
string schedulerInstanceGuid = msgParts[0];
string actionGuid = msgParts[1];
// Get the table entry.
ActionsTableEntry tableEntry = tableDataSource.GetEntry(schedulerInstanceGuid, actionGuid);
tableDataSource.UpdateStatus(schedulerInstanceGuid, actionGuid, ActionStatus.InProgress);
CloudBlockBlob jobBlob = jobsContainer.GetBlockBlobReference(actionGuid + ".zip");
using (var outputMsg = new BrokeredMessage())
{
outputMsg.Properties["SchedulerInstanceGuid"] = schedulerInstanceGuid;
outputMsg.Properties["ActionGuid"] = actionGuid;
outputMsg.Properties["DequeueCount"] = currentMessage.DequeueCount;
outputMsg.Properties["WaitTime"] = DateTime.Now - currentMessage.InsertionTime;
// Check if we have tried to process this message too many times.
// If so, delete it and report an error back to the client.
if (currentMessage.DequeueCount >= CloudConstants.MaxDequeueCount)
{
tableDataSource.UpdateStatus(schedulerInstanceGuid, actionGuid, ActionStatus.Error);
SendMessageToTopic(outputMsg);
inputQueue.DeleteMessage(currentMessage);
jobBlob.Delete();
continue;
}
// Switch the version of SMV if required.
if (!SetSmvVersion(tableEntry.Version))
{
Trace.TraceError("Could not set SMV version.");
tableDataSource.UpdateStatus(schedulerInstanceGuid, actionGuid, ActionStatus.Error);
SendMessageToTopic(outputMsg);
inputQueue.DeleteMessage(currentMessage);
jobBlob.Delete();
continue;
}
// Load the plugin.
if (!string.IsNullOrEmpty(tableEntry.PluginPath))
{
string pluginPath = Environment.ExpandEnvironmentVariables(tableEntry.PluginPath);
var assembly = System.Reflection.Assembly.LoadFrom(pluginPath);
string fullName = assembly.ExportedTypes.First().FullName;
Utility.plugin = (ISMVPlugin)assembly.CreateInstance(fullName);
if (Utility.plugin == null)
{
throw new Exception("Could not load plugin: " + tableEntry.PluginPath);
}
Utility.plugin.Initialize();
}
// Get the module object, if any.
if (!string.IsNullOrEmpty(tableEntry.ModuleHash))
{
SmvAccessor.ISmvAccessor accessor = Utility.GetSmvSQLAccessor();
Utility.smvModule = accessor.GetModuleByHash(tableEntry.ModuleHash);
if(Utility.smvModule == null)
{
throw new Exception("Could not load module with hash: " + tableEntry.ModuleHash);
}
}
// Download the job and extract it to the working directory.
Utility.ClearDirectory(workingDirectory);
string jobZipPath = Path.Combine(workingDirectory, "job.zip");
jobBlob.DownloadToFile(jobZipPath, FileMode.CreateNew);
ZipFile.ExtractToDirectory(jobZipPath, workingDirectory);
File.Delete(jobZipPath);
// Deserialize the action.
SMVAction action = (SMVAction)Utility.ByteArrayToObject(tableEntry.SerializedAction);
// Get ready to execute the action.
// We substitute the value of assemblyDir and workingDir with the values on this machine.
string oldWorkingDir = action.variables["workingDir"].ToLower();
string oldAssemblyDir = action.variables["assemblyDir"].ToLower();
string newAssemblyDir = Path.Combine(smvDirectory, "bin").ToLower();
workingDirectory = workingDirectory.ToLower();
var keys = new List<string>(action.variables.Keys);
foreach (var key in keys)
{
if (!string.IsNullOrEmpty(action.variables[key]))
{
if (action.variables[key].ToLower().StartsWith(oldAssemblyDir))
{
action.variables[key] = action.variables[key].ToLower().Replace(oldAssemblyDir, newAssemblyDir);
}
else if (action.variables[key].ToLower().StartsWith(oldWorkingDir))
{
action.variables[key] = action.variables[key].ToLower().Replace(oldWorkingDir, workingDirectory);
}
}
}
// NOTE: We set the Path attribute in the action to null because the action is always processed in the working directory.
var path = action.Path;
action.Path = null;
Utility.SetSmvVar("workingDir", workingDirectory);
// Execute the action.
SMVActionResult result = Utility.ExecuteAction(action);
// Change the paths back to their old values.
foreach (var key in keys)
{
if (!string.IsNullOrEmpty(action.variables[key]))
{
if (action.variables[key].ToLower().StartsWith(newAssemblyDir))
{
action.variables[key] = action.variables[key].ToLower().Replace(newAssemblyDir, oldAssemblyDir);
}
else if (action.variables[key].ToLower().StartsWith(workingDirectory))
{
action.variables[key] = action.variables[key].ToLower().Replace(workingDirectory, oldWorkingDir);
}
}
}
// Now set the path attribute again because the client needs it.
action.Path = path;
// Zip up the working directory and upload it as the result.
string resultsZipPath = Path.Combine(resultsDirectory, actionGuid + ".zip");
ZipFile.CreateFromDirectory(workingDirectory, resultsZipPath);
CloudBlockBlob resultsBlob = resultsContainer.GetBlockBlobReference(actionGuid + ".zip");
resultsBlob.UploadFromFile(resultsZipPath, FileMode.Open);
File.Delete(resultsZipPath);
// Job done!
tableDataSource.UpdateAction(schedulerInstanceGuid, actionGuid, Utility.ObjectToByteArray(action));
tableDataSource.UpdateStatus(schedulerInstanceGuid, actionGuid, ActionStatus.Complete);
SendMessageToTopic(outputMsg);
if (currentMessage != null)
{
inputQueue.DeleteMessage(currentMessage);
currentMessage = null;
}
jobBlob.DeleteIfExists();
Utility.ClearDirectory(workingDirectory);
}
}
}
catch (Exception e)
{
Trace.TraceError("Exception while processing queue item:" + e.ToString());
if (currentMessage != null)
{
inputQueue.UpdateMessage(currentMessage, TimeSpan.FromSeconds(5), MessageUpdateFields.Visibility);
}
System.Threading.Thread.Sleep(5000);
}
}
}
private bool SetSmvVersion(string version)
{
// The version string cannot be empty.
if (String.IsNullOrEmpty(version))
{
return false;
}
// First, check if the SMV version already exists in our local machine.
string smvName = "smv-" + version;
string smvFilename = smvName + ".zip";
CloudBlockBlob blob = versionsContainer.GetBlockBlobReference(smvFilename);
blob.FetchAttributes();
if (smvVersions.ContainsKey(version) && smvVersions[version].Item2 >= blob.Properties.LastModified.Value.UtcDateTime)
{
smvVersionsDirectory = smvVersions[version].Item1;
Environment.SetEnvironmentVariable("smv", smvVersionsDirectory);
return true;
}
// Download the SMV version if it's not available locally.
string zipPath = Path.Combine(smvVersionsDirectory, smvFilename);
if (File.Exists(zipPath))
{
File.Delete(zipPath);
}
blob.DownloadToFile(zipPath, FileMode.CreateNew);
// Delete the version's directory to clear it of any old files.
string dir = Path.Combine(smvVersionsDirectory, smvName);
if (Directory.Exists(dir))
{
Directory.Delete(dir, true);
}
// Now we'll unpack our version of SMV.
try
{
Directory.CreateDirectory(dir);
ZipFile.ExtractToDirectory(zipPath, dir);
File.Delete(zipPath);
}
catch (Exception e)
{
Trace.TraceError("Error unzipping smv.zip: Exception: {0}", e.ToString());
return false;
}
// We've setup a version of SMV successfully. Set smvPath and add this version to the list of avaiable SMV versions.
smvDirectory = dir;
Environment.SetEnvironmentVariable("smv", smvDirectory);
smvVersions[version] = new Tuple<string, DateTime>(smvDirectory, blob.Properties.LastModified.Value.UtcDateTime);
return true;
}
public override bool OnStart()
{
try
{
// Set the maximum number of concurrent connections .
System.Net.ServicePointManager.DefaultConnectionLimit = 12;
// Set options for blob storage.
options = new BlobRequestOptions();
options.ServerTimeout = TimeSpan.FromMinutes(10);
options.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval), CloudConstants.MaxRetries);
// Get the connection strings.
string assemblyDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string cloudConfigPath = Path.Combine(assemblyDir, CloudConstants.CloudConfigXmlFileName);
string cloudConfigContents = Utility.ReadFile(cloudConfigPath);
string schemaPath = Path.Combine(assemblyDir, CloudConstants.CloudConfigXsdFileName);
using (var c = new StringReader(cloudConfigContents))
{
if (!Utility.ValidateXmlFile(schemaPath, c))
{
Trace.TraceError("Could not load cloud config from file: " + cloudConfigPath);
return false;
}
}
var serializer = new XmlSerializer(typeof(SMVCloudConfig));
using (var reader = new StringReader(cloudConfigContents))
{
cloudConfig = (SMVCloudConfig)serializer.Deserialize(reader);
}
bool done = false;
while (!done)
{
try
{
var storageAccount = CloudStorageAccount.Parse(cloudConfig.StorageConnectionString.value);
// Setup queue storage.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
queueClient.DefaultRequestOptions = new QueueRequestOptions();
queueClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval),
CloudConstants.MaxRetries);
inputQueue = queueClient.GetQueueReference(CloudConstants.InputQueueName);
inputQueue.CreateIfNotExists();
// Setup blob storage.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
blobClient.DefaultRequestOptions = new BlobRequestOptions();
blobClient.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval),
CloudConstants.MaxRetries);
jobsContainer = blobClient.GetContainerReference(CloudConstants.InputBlobContainerName);
jobsContainer.CreateIfNotExists();
resultsContainer = blobClient.GetContainerReference(CloudConstants.OutputBlobContainerName);
resultsContainer.CreateIfNotExists();
versionsContainer = blobClient.GetContainerReference(CloudConstants.VersionsContainerName);
versionsContainer.CreateIfNotExists();
// Setup table storage.
var tableStorage = storageAccount.CreateCloudTableClient();
tableStorage.DefaultRequestOptions = new TableRequestOptions();
tableStorage.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval), CloudConstants.MaxRetries);
CloudTable table = tableStorage.GetTableReference(CloudConstants.TableName);
tableDataSource = new ActionsTableDataSource(table);
// Setup the service bus topic.
var namespaceManager = NamespaceManager.CreateFromConnectionString(cloudConfig.ServiceBusConnectionString.value);
if (!namespaceManager.TopicExists(CloudConstants.ResultsTopicName))
{
namespaceManager.CreateTopic(CloudConstants.ResultsTopicName);
}
done = true;
}
catch (Exception e)
{
Trace.TraceError("Failure trying to connect to Azure storage: " + e.ToString());
System.Threading.Thread.Sleep(5000);
}
}
// Get paths to important directories in the file system. Remove the trailing slash from the paths.
LocalResource localResource = RoleEnvironment.GetLocalResource(CloudConstants.SmvWorkingDirectoryResourceName);
workingDirectory = localResource.RootPath.Remove(localResource.RootPath.Length - 1);
localResource = RoleEnvironment.GetLocalResource(CloudConstants.SmvResultsDirectoryResourceName);
resultsDirectory = localResource.RootPath.Remove(localResource.RootPath.Length - 1);
localResource = RoleEnvironment.GetLocalResource(CloudConstants.SmvDirectoryResourceName);
smvVersionsDirectory = localResource.RootPath.Remove(localResource.RootPath.Length - 1);
}
catch (Exception e)
{
Trace.TraceError("Exception while running OnStart(): " + e.ToString());
return false;
}
Utility.result = null;
return base.OnStart();
}
public override void OnStop()
{
try
{
// Stop accepting more messages.
acceptingMessages = false;
// Make the message available to another worker.
if (currentMessage != null)
{
inputQueue.UpdateMessage(currentMessage, TimeSpan.FromSeconds(5), MessageUpdateFields.Visibility);
currentMessage = null;
}
}
catch (Exception e)
{
Trace.TraceError("An exception occurred while running OnStop(): " + e.ToString());
}
}
}
}

62
SmvCloudWorker/app.config Normal file
Просмотреть файл

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<connectionStrings>
<clear />
<add name="SmvDbConnectionString" connectionString="Data Source=.;Initial Catalog=SmvDb;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.serviceModel>
<extensions>
<!-- In this extension section we are introducing all known service bus extensions. User can remove the ones they don't need. -->
<behaviorExtensions>
<add name="connectionStatusBehavior" type="Microsoft.ServiceBus.Configuration.ConnectionStatusElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="serviceRegistrySettings" type="Microsoft.ServiceBus.Configuration.ServiceRegistrySettingsElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</behaviorExtensions>
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="tcpRelayTransport" type="Microsoft.ServiceBus.Configuration.TcpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpsRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpsRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="onewayRelayTransport" type="Microsoft.ServiceBus.Configuration.RelayedOnewayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingElementExtensions>
<bindingExtensions>
<add name="basicHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.BasicHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="webHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WebHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="ws2007HttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WS2007HttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netTcpRelayBinding" type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netOnewayRelayBinding" type="Microsoft.ServiceBus.Configuration.NetOnewayRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netEventRelayBinding" type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingExtensions>
</extensions>
</system.serviceModel>
<appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[your secret]" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Services.Client" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.0.0" newVersion="5.6.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Data.Edm" version="5.6.2" targetFramework="net45" />
<package id="Microsoft.Data.OData" version="5.6.2" targetFramework="net45" />
<package id="Microsoft.Data.Services.Client" version="5.6.2" targetFramework="net45" />
<package id="Microsoft.WindowsAzure.ConfigurationManager" version="2.0.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="5.0.6" targetFramework="net45" />
<package id="System.Spatial" version="5.6.2" targetFramework="net45" />
<package id="WindowsAzure.ServiceBus" version="3.2.0" targetFramework="net45" />
<package id="WindowsAzure.Storage" version="3.0.3.0" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

Двоичные данные
SmvInterceptorWrapper/GlobalSuppressions.cs Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,497 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;
namespace SmvInterceptorWrapper
{
class Program
{
static void Main(string[] args)
{
// Get the output dir from the Environment variable set by SMV
string smvOutDir = Environment.GetEnvironmentVariable("SMV_OUTPUT_DIR");
List<string> iargs = args.Where(x => !x.Contains("/iwrap:") && !x.Contains(".rsp") && !x.Contains("/plugin:")).ToList();
#region cl.exe
if (args.Contains("/iwrap:cl.exe"))
{
Console.WriteLine("iwrap: cl.exe called with args " + string.Join(",", args));
string[] unsupportedClExtensions = {".inf", ".mof", ".src", ".pdb" };
// check for inf and other unsupported files and skip
if (args.Where(a => unsupportedClExtensions.Any(b => a.Contains(b))).Count() > 0)
{
return;
}
// get the name of the plugin
string plugin = args.Where(x => x.Contains("/plugin:")).ToList().First().Replace("/plugin:", String.Empty);
// call slamcl
string rspContents = string.Empty;
string rspFileContent = string.Empty;
string rspFile = args.ToList().Find(x => x.Contains(".rsp") || x.StartsWith("@", StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(rspFile))
{
rspFile = rspFile.Replace("@", "");
rspContents = System.IO.File.ReadAllText(rspFile);
rspContents = rspContents.Replace("/analyze-", "");
}
// remove unsupported flags. currently we are not removing anything.
Regex[] unsupportedFlags = {//new Regex(@"\s+\/Yu[^\s]+\s{1}", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+\/Fp[^\s]+\s{1}", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+\/Yc[^\s]+\s{1}", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\/d1nodatetime)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\/d1trimfile:[^\s]*)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\/d2AllowCompatibleILVersions)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\/d2Zi\+)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\/d1nosafedelete)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"\s+(\-nosafedelete)", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"-DDBG=\d\s{1}|\/DDBG=\d\s{1}", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex(@"-DDEBUG\s{1}|\/DDEBUG\s{1}", System.Text.RegularExpressions.RegexOptions.IgnoreCase),
//new Regex("\\s+\\/Fp\"[^\"]+\"{1}", System.Text.RegularExpressions.RegexOptions.None)
};
foreach (Regex rgx in unsupportedFlags)
{
rspContents = rgx.Replace(rspContents, " ");
}
rspContents = rspContents.Replace("\r", " ");
rspContents = rspContents.Replace("\n", " ");
rspContents = rspContents.Replace("/W4", string.Empty);
rspContents = rspContents.Replace("/W3", string.Empty);
rspContents = rspContents.Replace("/W2", string.Empty);
rspContents = rspContents.Replace("/W1", string.Empty);
rspContents = rspContents.Replace("/WX", string.Empty);
rspFileContent = rspContents;
rspContents = Environment.ExpandEnvironmentVariables(" /nologo /w /Y- /analyze:only /analyze:plugin \"" + plugin +
"\" /errorReport:none" + " " + string.Join(" ", iargs)) + " " + rspContents;
// get out dir
string outDir = smvOutDir;
// Persist the RSP file
// Remove file names (*.c) from the content
Regex fileNameRegex = new Regex(@"(\w+\.c)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
rspFileContent = fileNameRegex.Replace(rspFileContent, String.Empty);
using (System.IO.StreamWriter str = new StreamWriter(Path.Combine(outDir, "sdv_cl.rsp"), false))
{
str.Write(rspFileContent);
}
// call CL.exe
ProcessStartInfo psi = new ProcessStartInfo(System.IO.Path.GetFullPath(Environment.ExpandEnvironmentVariables("%SMV_ANALYSIS_COMPILER%")),
Environment.ExpandEnvironmentVariables(rspContents));
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
if (!psi.EnvironmentVariables.ContainsKey("esp.cfgpersist.persistfile"))
{
psi.EnvironmentVariables.Add("esp.cfgpersist.persistfile", outDir + "\\$SOURCEFILE.rawcfgf");
psi.EnvironmentVariables.Add("Esp.CfgPersist.ExpandLocalStaticInitializer", "1");
psi.EnvironmentVariables.Add("ESP.BplFilesDir", outDir);
}
//Console.WriteLine("iwrap: cl.exe --> " + psi.FileName + " " + psi.Arguments);
Process p = System.Diagnostics.Process.Start(psi);
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(outDir + "\\smvcl.log", true))
{
sw.Write(p.StandardOutput.ReadToEnd());
sw.Write(p.StandardError.ReadToEnd());
}
File.AppendAllText(outDir + "\\smvcl.log", psi.Arguments);
}
#endregion
#region smv2sql.exe
else if (args.Contains("/iwrap:smv2sql.exe"))
{
// get rsp contents
string rspContents = string.Empty;
string rspFile = args.ToList().Find(x => x.Contains(".rsp") || x.StartsWith("@", StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(rspFile))
{
rspFile = rspFile.Replace("@", "");
rspContents = System.IO.File.ReadAllText(rspFile);
rspContents = rspContents.Replace("\r", " ");
rspContents = rspContents.Replace("\n", " ");
}
// get directory where build artifacts are being placed
// Note: for Link, this is not just getting the /out:<ARG>
// since Link is using inputs, and the location of the inputs
// is the real location where rawcfgf/li files are going to
// TODO: think about whether the LI files should be placed
// in the outdir
string outDir = smvOutDir;
Console.WriteLine("iwrap: smv2sql.exe --> outdir is " + outDir);
// May not be the best way to get the source dir.
File.Copy(Environment.ExpandEnvironmentVariables(@"%SMV%\bin\smv2sql.exe.config"), Path.Combine(outDir, "smv2sql.exe.config"), true);
File.Copy(Environment.ExpandEnvironmentVariables(@"%SMV%\bin\smvaccessor.dll"), Path.Combine(outDir, "smvaccessor.dll"), true);
// Don't let the Smv2Sql phase run twice.
if (File.Exists(Path.Combine(outDir, "smv2sql.log")))
{
Console.WriteLine("iwrap: link.exe --> quitting since this phase is already complete");
return;
}
// Run Smv2Sql to put the LI and BPL files into a DB.
Process smv2SqlProcess;
var psi = new ProcessStartInfo(System.IO.Path.GetFullPath(Environment.ExpandEnvironmentVariables(@"%SMV%\bin\smv2sql.exe")));
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = outDir;
psi.Arguments = outDir + " /log verbose";
Console.WriteLine("iwrap: link.exe --> " + psi.FileName + " " + psi.Arguments);
smv2SqlProcess = System.Diagnostics.Process.Start(psi);
using (StreamWriter sw = new System.IO.StreamWriter(outDir + "\\smv2sql.log", true))
{
sw.Write(smv2SqlProcess.StandardOutput.ReadToEnd());
sw.Write(smv2SqlProcess.StandardError.ReadToEnd());
}
}
#endregion
#region link.exe
else if (args.Contains("/iwrap:link.exe"))
{
Console.WriteLine("iwrap: link.exe called with args " + string.Join(" ", iargs));
Console.WriteLine("iwrap: link.exe --> " + Environment.ExpandEnvironmentVariables("slamcl_writer.exe"));
// get rsp contents
string rspContents = string.Empty;
string rspFile = args.ToList().Find(x => x.Contains(".rsp") || x.StartsWith("@", StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(rspFile))
{
rspFile = rspFile.Replace("@", "");
rspContents = System.IO.File.ReadAllText(rspFile);
rspContents = rspContents.Replace("\r", " ");
rspContents = rspContents.Replace("\n", " ");
}
// get out dir
string outDir = smvOutDir;
Console.WriteLine("iwrap: link.exe --> outdir is " + outDir);
// get rid of previous LI files, log files etc.
foreach (string liFile in Directory.GetFiles(outDir, "*.li"))
{
File.Delete(liFile);
}
if(File.Exists(Path.Combine(outDir, "smvlink.log")))
{
File.Delete(Path.Combine(outDir, "smvlink.log"));
}
//TODO: if link is called multiple times to create multiple binaries
// we will still only create 1 LI file for all the LI files that are available
// This happens in cases where a directory is used to store all the .obj
// files and then link is called multiple times with a subset of the .obj
// files to produce various binaries.
// The solution is to look at the link command in its entirety,
// and extract the obj files that are being used in it.
// we should then produce the LI for the corresponding obj.li files.
// the obj files are specified in the link rsp or command line and can
// be extracted using a regex, similar to how we extract lib files and locations.
string[] files = System.IO.Directory.GetFiles(outDir, "*.rawcfgf");
files = files.Select(x => System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileName(x))).ToArray();
files = files.Where(x => !x.Contains(".obj")).ToArray();
ProcessStartInfo psi;
Process p;
StreamWriter sw;
psi = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("slamcl_writer.exe"), "--smv *");
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = outDir;
Console.WriteLine("iwrap: link.exe --> " + psi.FileName + " " + psi.Arguments);
p = System.Diagnostics.Process.Start(psi);
using (sw = new System.IO.StreamWriter(outDir + "\\smvlink.log", true))
{
sw.Write(p.StandardOutput.ReadToEnd());
sw.Write(p.StandardError.ReadToEnd());
}
files = files.Select(x => x + ".rawcfgf.obj").ToArray();
#region BPL for compilation units
/*
* IF WE WANT TO PRODUCE BPLs for each compilation unit then we uncommend the following section
// Produce BPL files from the LI files.
Process li2BplProcess;
File.Copy(Environment.ExpandEnvironmentVariables(@"%SMV%\bin\liConversion.txt"), Path.Combine(outDir, "liConversion.txt"), true);
psi = new ProcessStartInfo(System.IO.Path.GetFullPath(Environment.ExpandEnvironmentVariables(@"%SMV%\bin\li2bpl.exe")));
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = outDir;
sw = new System.IO.StreamWriter(outDir + "\\smvli2bpl.log", true);
foreach(string file in files)
{
psi.Arguments = " -liFile " + Path.Combine(outDir, file);
Console.WriteLine("iwrap: li2bpl.exe --> " + psi.FileName + " " + psi.Arguments);
li2BplProcess = System.Diagnostics.Process.Start(psi);
sw.Write(li2BplProcess.StandardOutput.ReadToEnd());
sw.Write(li2BplProcess.StandardError.ReadToEnd());
// Rename all the BPL files, appending "compilationunit." to the name of each file.
// Can li2bpl be modified to take the name of the output bpl file as an argument?
string oldBplPath = Path.Combine(outDir, "li2c_prog.bpl");
string newBplPath = Path.Combine(outDir, "compilationunit." + file + ".bpl");
if (File.Exists(oldBplPath))
{
File.Copy(oldBplPath, newBplPath, true);
}
}
sw.Close();
*/
#endregion
Process slamLinkProcess;
// if only 1 li file then just copy that to slam.li
if (files.Length == 1)
{
File.Copy(outDir + "\\" + files.ElementAt(0) + ".li", outDir + "\\slam.li", true);
}
else
{
// many LI files, link all LIs together
psi = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("slamlink.exe "));
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = outDir;
psi.Arguments = " --lib " + string.Join(" ", files);
Console.WriteLine("iwrap: link.exe --> " + psi.FileName + " " + psi.Arguments);
slamLinkProcess = System.Diagnostics.Process.Start(psi);
using (sw = new System.IO.StreamWriter(outDir + "\\smvlink.log", true))
{
sw.Write(slamLinkProcess.StandardOutput.ReadToEnd());
sw.Write(slamLinkProcess.StandardError.ReadToEnd());
}
// copy the slam.lib.li produced by slamlink to slam.li
if (File.Exists(outDir + "\\slam.lib.li"))
{
File.Copy(outDir + "\\slam.lib.li", outDir + "\\slam.li", true);
}
}
// create copy for linking with libs
if (File.Exists(outDir + "\\slam.li"))
{
File.Copy(outDir + "\\slam.li", outDir + "\\slamout.obj.li", true);
}
else
{
Console.WriteLine("iwrap: link.exe --> No slam.li found in " + outDir);
}
// get any libs that need to be added and the corresponding rawcfgs
List<string> libs = GetLibs(string.Join(" ", iargs) + " " + rspContents + " ");
libs.RemoveAll(l => string.IsNullOrEmpty(l));
foreach (string l in libs)
{
Console.WriteLine("lib is " + l);
if (l.Equals(outDir)) continue;
try
{
string[] liFilesInLibDir = Directory.GetFiles(l, "slam.li");
foreach (string liFile in liFilesInLibDir)
{
Console.WriteLine("iwrap: Linking " + liFile + " " + outDir + "\\slam.obj.li");
File.Copy(liFile, outDir + "\\slamlib.obj.li", true);
File.Copy(outDir + "\\slamout.obj.li", outDir + "\\slamorig.obj.li");
psi = new ProcessStartInfo(Environment.ExpandEnvironmentVariables("slamlink.exe"));
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.WorkingDirectory = outDir;
psi.Arguments = " --lib slamorig.obj slamlib.obj /out:slamout.obj";
slamLinkProcess = System.Diagnostics.Process.Start(psi);
using (sw = new System.IO.StreamWriter(outDir + "\\smvlink.log", true))
{
sw.Write(slamLinkProcess.StandardOutput.ReadToEnd());
sw.Write(slamLinkProcess.StandardError.ReadToEnd());
}
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
if (File.Exists(outDir + "\\slamout.obj.li"))
{
File.Copy(outDir + "\\slamout.obj.li", outDir + "\\slam.li", true);
}
}
}
#endregion
#region lib.exe
else if (args.Contains("/iwrap:lib.exe"))
{
Console.WriteLine("iwrap: Currently unimplemented. In general link functionality should be used.");
}
#endregion
}
/// <summary>
/// Given a list of arguments, figures out what obj/lib files are
/// present, and returns the list
/// </summary>
/// <param name="args">arguments to process</param>
/// <returns>list of libraries</returns>
static List<string> GetLibs(string args)
{
// Extract all matches containing paths of lib and obj files which are enclosed by an optional space and does not have a space within
MatchCollection matchList = Regex.Matches(args, @"[\s]?([^\s""]+\.((lib)|(obj)))[\s]$?", RegexOptions.IgnoreCase);
List<string> spaceTokens = matchList.Cast<Match>()
.Select(match => match.Value.Trim().Replace(@"/implib:", string.Empty))
.Where(match => !match.StartsWith(@"/out", StringComparison.OrdinalIgnoreCase))
.Where(match => !match.StartsWith(@"\\out", StringComparison.OrdinalIgnoreCase))
.Select(match => System.IO.Path.GetDirectoryName(match.Trim())).ToList();
// Extract all matches containing paths of lib and obj files which are enclosed within quotes
matchList = Regex.Matches(args, @"""([^""]+\.(lib|obj))""", RegexOptions.IgnoreCase);
List<string> quoteTokens = matchList.Cast<Match>()
.Select(match => match.Value.Trim().Replace(@"/implib:", string.Empty))
.Where(match => !match.StartsWith(@"/out", StringComparison.OrdinalIgnoreCase))
.Where(match => !match.StartsWith(@"\\out", StringComparison.OrdinalIgnoreCase))
.Select(match => System.IO.Path.GetDirectoryName(match.Replace("\"", ""))).ToList();
return spaceTokens.Union(quoteTokens).ToList();
}
/// <summary>
/// Given arguments to compiler, gets the output folder
/// by matching on a regular expression
/// </summary>
/// <param name="args">arguments to process</param>
/// <returns>compilers output directory</returns>
static string GetOutDirCl(string args)
{
string regex = String.Format(CultureInfo.InvariantCulture, "/F{0}\"(\\S+)\"|/F{0}(\\S+)", "[a|d|m|p|R|e|o|r|i]");
Match match = Regex.Match(args, regex);
if(match.Success)
{
if (match.Groups[1].Success) return System.IO.Path.GetDirectoryName(match.Groups[1].Value);
if (match.Groups[2].Success) return System.IO.Path.GetDirectoryName(match.Groups[2].Value);
}
return Environment.GetEnvironmentVariable("OBJECT_ROOT");
}
/// <summary>
/// arguments to link are processed to figure out the
/// output directory of link
/// </summary>
/// <param name="args">arguments to process</param>
/// <returns>output directory of link</returns>
static string GetOutDirLink(string args)
{
Match match = Regex.Match(args, "/out:\"(.[^\"]+)\"|/out:(\\S+)", RegexOptions.IgnoreCase);
string retVal = string.Empty;
if (match.Success)
{
if(match.Groups[1].Success) retVal = System.IO.Path.GetDirectoryName(match.Groups[1].Value);
if (match.Groups[2].Success) retVal = System.IO.Path.GetDirectoryName(match.Groups[2].Value);
}
if (string.IsNullOrEmpty(retVal))
{
retVal = Environment.GetEnvironmentVariable("OBJECT_ROOT");
}
else
{
// check for relative path
if (!Path.IsPathRooted(retVal))
{
retVal = Path.Combine(Environment.CurrentDirectory, retVal);
}
}
return retVal;
}
/// <summary>
/// Extract build path from output
/// </summary>
/// <param name="output">Output of the build.</param>
public static string ExtractBuildPath()
{
string lines = string.Empty;
using (FileStream fs = new FileStream("smvbuild.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
lines += sr.ReadLine() + Environment.NewLine;
}
}
}
if (!String.IsNullOrEmpty(lines))
{
lines = lines.Replace("\r\n", Environment.NewLine);
Match match = Regex.Match(lines, @"\/\/iwrap: outdir is (.*?)$", RegexOptions.Multiline);
string path = String.Empty;
if (match.Success)
{
try
{
string key = match.Groups[1].Value;
path = key.Trim();
}
catch (Exception)
{
Console.WriteLine("iwrap: Could not extract build path");
}
Console.WriteLine("iwrap: Build path found - " + path);
return path;
}
else
{
Console.WriteLine("iwrap: Could not extract build path");
return string.Empty;
}
}
else
{
Console.WriteLine("iwrap: Could not extract build path");
return string.Empty;
}
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
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("SmvInterceptorWrapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SmvInterceptorWrapper")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0eb021eb-9999-4aae-ba63-34a734ee5f95")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,60 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8F9EA492-E86B-4F1C-ADC5-BF407466F448}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmvInterceptorWrapper</RootNamespace>
<AssemblyName>SmvInterceptorWrapper</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8F9EA492-E86B-4F1C-ADC5-BF407466F448}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>iwrap</RootNamespace>
<AssemblyName>iwrap</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmvLibrary
{
/// <summary>
/// Each instance of this class represents an entry in the ActionsQueue for the local and master action schedulers.
/// </summary>
public class ActionsQueueEntry
{
/// <summary>
/// The action to be executed.
/// </summary>
public SMVAction Action { get; set; }
/// <summary>
/// This delegate is called after the action is complete.
/// </summary>
public SMVActionCompleteCallBack Callback { get; set; }
/// <summary>
/// A list of results, one for this action and one for each action that was a child of this action.
/// </summary>
public List<SMVActionResult> Results { get; set; }
/// <summary>
/// Context object passed to the callback.
/// </summary>
public object Context { get; set; }
public ActionsQueueEntry(SMVAction action, SMVActionCompleteCallBack callback, object context)
{
this.Action = action;
this.Callback = callback;
this.Context = context;
this.Results = new List<SMVActionResult>();
}
}
}

29
SmvLibrary/CloudConfig.cs Normal file
Просмотреть файл

@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Xml.Serialization;
namespace SmvLibrary
{
[XmlRootAttribute(Namespace = "")]
public class SMVCloudConfig
{
[XmlElementAttribute("StorageConnectionString")]
public StorageConnectionStringElement StorageConnectionString;
[XmlElementAttribute("ServiceBusConnectionString")]
public ServiceBusConnectionStringElement ServiceBusConnectionString;
}
[XmlRootAttribute("StorageConnectionString", Namespace = "")]
public class StorageConnectionStringElement
{
[XmlAttributeAttribute()]
public string value { get; set; }
}
[XmlRootAttribute("ServiceBusConnectionString", Namespace = "")]
public class ServiceBusConnectionStringElement
{
[XmlAttributeAttribute()]
public string value { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="SMVCloudConfig"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<xs:element name="SMVCloudConfig">
<xs:complexType>
<xs:sequence>
<xs:element name="StorageConnectionString" type="ConnectionStringType" minOccurs="1" maxOccurs="1" />
<xs:element name="ServiceBusConnectionString" type="ConnectionStringType" minOccurs="1" maxOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="ConnectionStringType">
<xs:attribute name="value" type="xs:string" use="required" />
</xs:complexType>
</xs:schema>

Просмотреть файл

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmvLibrary
{
/// <summary>
/// Common constants needed by both SmvCloudWorker and CloudSmvActionScheduler.
/// </summary>
public static class CloudConstants
{
public static int MaxRetries = 6; /// Maximum number of times to try to connect to blob storage before giving up.
public const int RetryBackoffInterval = 4; /// Time to wait in seconds before retrying a request.
public const int BeginReceiveTimeoutInHours = 9; /// Timeout for the BeginReceive() call.
public const string InputBlobContainerName = "smvactions"; /// Container action data is uploaded to.
public const string OutputBlobContainerName = "smvresults"; /// Container results are downloaded from.
public const string VersionsContainerName = "smvversions"; /// Container where different versions of SMV are stored.
public const string InputQueueName = "smvactions"; /// Name of the actions queue.
public const string ResultsTopicName = "smvresults"; /// Name of the service bus topic used to deliver result messages to the client.
public const string TableName = "actionstable"; /// Name of the table used to store information about the actions.
public const string CloudConfigXmlFileName = "cloudconfig.xml"; /// Name of the XML file that contains the connection strings.
public const string CloudConfigXsdFileName = "cloudconfig.xsd"; /// Name of XML schema file for the cloud config files.
public const int MaxDequeueCount = 5; /// The maximum number of times a message can be dequeued for processing.
public const string SmvWorkingDirectoryResourceName = "SMVWorking"; /// Used to get the path to the SMV working directory.
public const string SmvResultsDirectoryResourceName = "SMVResults"; /// Used to get the path to the results directory.
public const string SmvDirectoryResourceName = "SMVExec"; /// Used to get the location to SMV.
}
}

Просмотреть файл

@ -0,0 +1,265 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Queue;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.WindowsAzure.Storage.RetryPolicies;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using SMVActionsTable;
namespace SmvLibrary
{
public class CloudSMVActionScheduler : ISMVActionScheduler
{
private bool disposed = false; /// Used for implementing IDisposable.
private string schedulerInstanceGuid; /// A unique identifier for this instance of the CloudSMVActionScheduler object.
private string storageConnectionString; /// Connection string to connect to Azure storage.
private string serviceBusConnectionString; /// Connection string to connect to Azure Service Bus.
private CloudBlobContainer inputContainer; /// Container where actions are uploaded to.
private CloudBlobContainer outputContainer; /// Container where results are downloaded from.
private ActionsTableDataSource tableDataSource; /// Data source object used to query the actions table.
private CloudQueue actionsQueue; /// Cloud queue where each message is an action to be processed by a worker.
private NamespaceManager namespaceManager; /// Namespace manager used for working with service bus entities.
private SubscriptionClient subscriptionClient; /// Subscription client used to communicate with the service bus.
private class CloudActionCompleteContext
{
public SMVAction action;
public SMVActionCompleteCallBack callback;
public object context;
public CloudActionCompleteContext(SMVAction _action, SMVActionCompleteCallBack _callback, object _context)
{
action = _action;
callback = _callback;
context = _context;
}
}
/// <summary>
/// This variable maps action GUIDs to CloudActionCompleteContext objects so we can get some information about the
/// action that completed when ActionComplete() is called.
/// </summary>
private Dictionary<string, CloudActionCompleteContext> contextDictionary = new Dictionary<string, CloudActionCompleteContext>();
public CloudSMVActionScheduler(SMVCloudConfig config)
{
// Set the instance GUID.
schedulerInstanceGuid = Guid.NewGuid().ToString();
Log.LogInfo("Scheduler Instance GUID: " + schedulerInstanceGuid);
// Check if the connection strings are set properly.
storageConnectionString = config.StorageConnectionString.value;
serviceBusConnectionString = config.ServiceBusConnectionString.value;
if (string.IsNullOrEmpty(storageConnectionString))
{
throw new Exception("Connection string \"Microsoft.WindowsAzure.Storage.ConnectionString\" is not set. Please contact rahulku@microsoft.com for a " +
"valid connection string.");
}
if (string.IsNullOrEmpty(serviceBusConnectionString))
{
throw new Exception("Connection string \"Microsoft.ServiceBus.ConnectionString\" is not set. Please contact rahulku@microsoft.com for a " +
"valid connection string.");
}
int retriesLeft = CloudConstants.MaxRetries;
while (true)
{
try
{
// Connect to cloud storage.
var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
var queueStorage = storageAccount.CreateCloudQueueClient();
var blobStorage = storageAccount.CreateCloudBlobClient();
var tableStorage = storageAccount.CreateCloudTableClient();
// Set up blob storage.
blobStorage.DefaultRequestOptions = new BlobRequestOptions();
blobStorage.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval), CloudConstants.MaxRetries);
inputContainer = blobStorage.GetContainerReference(CloudConstants.InputBlobContainerName);
inputContainer.CreateIfNotExists();
outputContainer = blobStorage.GetContainerReference(CloudConstants.OutputBlobContainerName);
outputContainer.CreateIfNotExists();
// Set up our queue.
queueStorage.DefaultRequestOptions = new QueueRequestOptions();
queueStorage.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval), CloudConstants.MaxRetries);
actionsQueue = queueStorage.GetQueueReference(CloudConstants.InputQueueName);
actionsQueue.CreateIfNotExists();
// Set up table storage.
tableStorage.DefaultRequestOptions = new TableRequestOptions();
tableStorage.DefaultRequestOptions.RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval), CloudConstants.MaxRetries);
CloudTable table = tableStorage.GetTableReference(CloudConstants.TableName);
tableDataSource = new ActionsTableDataSource(table);
// Set up the service bus subscription.
namespaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
var filter = new SqlFilter(String.Format(CultureInfo.CurrentCulture, "(SchedulerInstanceGuid = '{0}')", schedulerInstanceGuid));
if (!namespaceManager.TopicExists(CloudConstants.ResultsTopicName))
{
namespaceManager.CreateTopic(CloudConstants.ResultsTopicName);
}
var subDesc = new SubscriptionDescription(CloudConstants.ResultsTopicName, schedulerInstanceGuid);
subDesc.AutoDeleteOnIdle = TimeSpan.FromDays(7.0);
if (!namespaceManager.SubscriptionExists(CloudConstants.ResultsTopicName, schedulerInstanceGuid))
{
namespaceManager.CreateSubscription(subDesc, filter);
}
subscriptionClient = SubscriptionClient.CreateFromConnectionString(serviceBusConnectionString,
CloudConstants.ResultsTopicName, schedulerInstanceGuid);
subscriptionClient.RetryPolicy = new RetryExponential(
TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval),
TimeSpan.FromSeconds(CloudConstants.RetryBackoffInterval * CloudConstants.MaxRetries),
CloudConstants.MaxRetries);
subscriptionClient.OnMessage((msg) =>
{
try
{
ActionComplete(msg);
}
catch (Exception)
{
msg.Abandon();
}
});
// If we're here, we've successfully initialized everything and can break out of the retry loop.
break;
}
catch (Exception e)
{
// We can fix the three exceptions below by using retry logic. But there's no point retrying for other exceptions.
if ((e is TimeoutException || e is ServerBusyException || e is MessagingCommunicationException) && retriesLeft > 0)
{
retriesLeft--;
}
else
{
throw;
}
}
System.Threading.Thread.Sleep(5000);
}
}
public void AddAction(SMVAction action, SMVActionCompleteCallBack callback, object context)
{
string actionGuid = Guid.NewGuid().ToString();
// Upload action directory to blob storage.
string actionPath = Utility.GetActionDirectory(action);
string zipPath = Path.GetTempFileName();
File.Delete(zipPath);
ZipFile.CreateFromDirectory(actionPath, zipPath);
CloudBlockBlob blob = inputContainer.GetBlockBlobReference(actionGuid + ".zip");
blob.UploadFromFile(zipPath, FileMode.Open);
File.Delete(zipPath);
// Add entry to table storage.
// TODO: Due to constraints on sizes of properties in Azure table entities, serializedAction cannot be larger
// than 64kB. Fix this if this becomes an issue.
byte[] serializedAction = Utility.ObjectToByteArray(action);
string moduleHash = Utility.smvModule == null ? string.Empty : Utility.smvModule.Hash;
ActionsTableEntry entry = new ActionsTableEntry(action.name, actionGuid, schedulerInstanceGuid, serializedAction,
Utility.version, Utility.pluginPath, moduleHash);
tableDataSource.AddEntry(entry);
// Add message to queue.
Log.LogInfo("Executing: " + action.GetFullName() + " [cloud id:" + actionGuid + "]");
string messageString = schedulerInstanceGuid + "," + actionGuid;
var message = new CloudQueueMessage(messageString);
actionsQueue.AddMessage(message);
// Start listening for a message from the service bus.
contextDictionary[actionGuid] = new CloudActionCompleteContext(action, callback, context);
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = false;
options.AutoRenewTimeout = TimeSpan.FromHours(CloudConstants.BeginReceiveTimeoutInHours);
//subscriptionClient.BeginReceive(TimeSpan.FromHours(CloudConstants.BeginReceiveTimeoutInHours),
// new AsyncCallback(ActionComplete), null);
}
/// <summary>
/// Callback that is called when SubscriptionClient.BeginReceive() receives a message.
/// </summary>
/// <param name="ar"></param>
private void ActionComplete(BrokeredMessage message)
{
var actionGuid = (string)message.Properties["ActionGuid"];
var waitTime = (TimeSpan)message.Properties["WaitTime"]; // The amount of time the rule had to wait before it started being processed.
var dequeueCount = (int)message.Properties["DequeueCount"]; // The number of times the message we sent was dequeued by the workers.
message.Complete();
CloudActionCompleteContext context = contextDictionary[actionGuid];
ActionsTableEntry entry = tableDataSource.GetEntry(schedulerInstanceGuid, actionGuid);
var action = (SMVAction)Utility.ByteArrayToObject(entry.SerializedAction);
Console.WriteLine("ActionComplete for " + action.GetFullName() + " [cloud id " + actionGuid + "]");
// Populate the original action object so that the master scheduler gets the changes to the action object.
context.action.analysisProperty = action.analysisProperty;
context.action.result = action.result;
context.action.variables = action.variables;
var results = new SMVActionResult[] { context.action.result };
if(entry.Status != (int)ActionStatus.Complete)
{
Log.LogError(string.Format("Failed to complete action: {0} ({1})", actionGuid, context.action.name));
context.callback(new SMVActionResult[] { context.action.result }, context.context);
}
// Download and extract the results.
CloudBlockBlob resultsBlob = outputContainer.GetBlockBlobReference(actionGuid + ".zip");
string zipPath = Path.GetTempFileName();
File.Delete(zipPath);
resultsBlob.DownloadToFile(zipPath, FileMode.CreateNew);
resultsBlob.Delete();
string actionDirectory = Utility.GetActionDirectory(context.action);
Utility.ClearDirectory(actionDirectory);
ZipFile.ExtractToDirectory(zipPath, actionDirectory);
File.Delete(zipPath);
// Write to the cloudstats.txt file.
using (StreamWriter writer = File.AppendText(Path.Combine(actionDirectory, "cloudstats.txt")))
{
writer.WriteLine("Wait Time: " + waitTime.ToString());
writer.WriteLine("Dequeue Count: " + dequeueCount);
}
context.callback(results, context.context);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Clean up managed resources.
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

Двоичные данные
SmvLibrary/GlobalSuppressions.cs Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace SmvLibrary
{
/// <summary>
/// Delegate used by the scheduler to indicate that an action and all its children have completed.
/// </summary>
/// <param name="results">The results of all the actions that have been executed as a result of this action.</param>
/// <param name="context">Context object passed to the callback.</param>
public delegate void SMVActionCompleteCallBack(IEnumerable<SMVActionResult> results, object context);
/// <summary>
/// Defines an interface for classes that want to support scheduling SMVActions.
/// </summary>
public interface ISMVActionScheduler : IDisposable
{
/// <summary>
/// Adds an action to be scheduled. Once the action has completed, <paramref name="callback"/> will be called with
/// <paramref name="context"/> as the argument.
/// </summary>
/// <param name="action">The action to be performed.</param>
/// <param name="callback">Delegate that will be called once the action has been performed.</param>
/// <param name="context">Object passed to the delegate when the action has been performed.</param>
void AddAction(SMVAction action, SMVActionCompleteCallBack callback, object context);
}
}

58
SmvLibrary/ISMVPlugin.cs Normal file
Просмотреть файл

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmvLibrary
{
public interface ISMVPlugin
{
/// <summary>
/// Initialize the Plugin
/// </summary>
void Initialize();
/// <summary>
/// Prints help text specific to the plugin
/// </summary>
void PrintPluginHelp();
/// <summary>
/// Process custom arguments for use by the Plugin
/// </summary>
/// <param name="args">The arguments passed to smv.</param>
void ProcessPluginArgument(string[] args);
/// <summary>
/// Called before an action is run
/// </summary>
/// <param name="action">The action being run.</param>
void PreAction(SMVAction action);
/// <summary>
/// Called after an action is run
/// </summary>
/// <param name="action">The action being run.</param>
void PostAction(SMVAction action);
/// <summary>
/// Called after build, if build node is present in the SMVConfig.
/// </summary>
/// <param name="buildResult">List of build actions.</param>
void PostBuild(SMVAction[] buildActions);
/// <summary>
/// Do analysis if /analyze argument is not passed to SMV
/// </summary>
/// <param name="analysis">List of analysis actions.</param>
/// <returns>true on success, false on failure.</returns>
bool DoPluginAnalysis(SMVAction[] analysisActions);
/// <summary>
/// Called after analysis, if analysis node is present in the SMVConfig.
/// </summary>
/// <param name="analysisResult">List of result of the analysis actions.</param>
void PostAnalysis(SMVAction[] analysisActions);
}
}

Просмотреть файл

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SmvLibrary
{
public class LocalSMVActionScheduler : ISMVActionScheduler
{
private ConcurrentQueue<ActionsQueueEntry> actionsQueue = new ConcurrentQueue<ActionsQueueEntry>();
private List<Thread> executeThreads = new List<Thread>();
private bool disposed = false;
/// <summary>
/// Starts <paramref name="numberOfThreads"/> threads, each of which will start dequeueing actions from the actions
/// queue. The threads stop executing once the object is disposed of.
/// </summary>
/// <param name="numberOfThreads">The number of threads to start.</param>
public LocalSMVActionScheduler(int numberOfThreads)
{
for(int i = 0; i < numberOfThreads; i++)
{
Thread t = new Thread(new ThreadStart(Execute));
executeThreads.Add(t);
t.Start();
}
}
public void AddAction(SMVAction action, SMVActionCompleteCallBack callback, object context)
{
var entry = new ActionsQueueEntry(action, callback, context);
actionsQueue.Enqueue(entry);
}
private void Execute()
{
try
{
while(true)
{
ActionsQueueEntry entry;
while(actionsQueue.TryDequeue(out entry))
{
Log.LogInfo("Executing: " + entry.Action.GetFullName());
SMVActionResult result = Utility.ExecuteAction(entry.Action);
entry.Results.Add(result);
entry.Callback(entry.Results, entry.Context);
}
Thread.Sleep(2000);
}
}
catch(ThreadAbortException)
{
// Do nothing here, we just need this so we can call Thread.Abort() to kill the thread.
}
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Clean up managed resources.
foreach(Thread t in executeThreads)
{
t.Abort();
}
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

Просмотреть файл

@ -0,0 +1,149 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmvLibrary
{
public class MasterSMVActionScheduler : ISMVActionScheduler
{
private ConcurrentQueue<ActionsQueueEntry> actionsQueue = new ConcurrentQueue<ActionsQueueEntry>();
private IDictionary<string, ISMVActionScheduler> schedulers = new Dictionary<string, ISMVActionScheduler>();
private bool disposed = false;
private bool done = false;
private delegate void ExecuteDelegate();
/// <summary>
/// Start running a thread that handles dequeueing actions from the actionsQueue and sending them to the appropriate scheduler.
/// </summary>
public MasterSMVActionScheduler()
{
new ExecuteDelegate(this.Execute).BeginInvoke(null, null);
}
/// <summary>
/// Add a new scheduler to the list of schedulers used by the master scheduler.
/// </summary>
/// <param name="type">The type of scheduler you're adding. E.g., "local", "cloud"</param>
/// <param name="scheduler">The scheduler to be added.</param>
public void AddScheduler(string type, ISMVActionScheduler scheduler)
{
schedulers[type] = scheduler;
}
public void AddAction(SMVAction action, SMVActionCompleteCallBack callback, object context)
{
Log.LogInfo("Queuing action: " + action.GetFullName());
var entry = new ActionsQueueEntry(action, callback, context);
actionsQueue.Enqueue(entry);
}
/// <summary>
/// This function runs in its own thread, dequeueing actions from the actions queue and sending them to the
/// appropriate scheduler.
/// </summary>
private void Execute()
{
while (!done)
{
ActionsQueueEntry entry;
while (!done && actionsQueue.TryDequeue(out entry))
{
SMVAction action = entry.Action;
string schedulerType = action.executeOn;
if (!schedulers.ContainsKey(schedulerType))
{
Log.LogFatalError("Could not find scheduler of type: " + schedulerType +
" while executing action " + action.name);
}
else
{
ISMVActionScheduler scheduler = schedulers[schedulerType];
lock (Utility.lockObject)
{
Utility.result.Add(action.GetFullName(), "Skipped");
}
scheduler.AddAction(action, new SMVActionCompleteCallBack(ActionComplete), entry);
}
}
System.Threading.Thread.Sleep(2000);
}
}
/// <summary>
/// This callback function is called once an action and all its children have executed.
/// </summary>
/// <param name="results">A list of results, one for each action (the action added to the queue and its children).</param>
/// <param name="context">A context object.</param>
private void ActionComplete(IEnumerable<SMVActionResult> results, object context)
{
var entry = context as ActionsQueueEntry;
SMVAction action = entry.Action;
SMVActionCompleteCallBack callback = entry.Callback;
entry.Results.AddRange(results);
Log.LogInfo("Completed action: " + action.GetFullName());
// Add result to our global result set.
string result = "Failed";
if(action.result != null && action.result.isSuccessful)
{
result = "Success";
}
lock (Utility.lockObject)
{
Utility.result[action.GetFullName()] = result;
}
// If there was an error, simply call the callback function with whatever results we have, the callback is
// expected to handle the errors by looking at the list of results.
if (action.result == null || action.result.breakExecution)
{
entry.Callback(entry.Results, entry.Context);
}
// Otherwise, add the next action to the queue, if any.
else
{
SMVAction nextAction = Utility.GetNextAction(action);
if (nextAction != null)
{
nextAction.analysisProperty = action.analysisProperty;
nextAction.variables = new Dictionary<string, string>(entry.Action.variables);
//var newEntry = new ActionsQueueEntry(nextAction, entry.Callback, entry.Context);
//newEntry.Results = entry.Results;
//actionsQueue.Enqueue(newEntry);
this.AddAction(nextAction, entry.Callback, entry.Context);
}
else
{
entry.Callback(entry.Results, entry.Context);
}
}
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
{
// Clean up managed resources.
done = true;
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
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("SMVLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SMVLibrary")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b7dc81e0-23b7-44d6-a136-9967ac20548c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E03DC0DF-84CC-420C-91B1-2A937E88FF31}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmvLibrary</RootNamespace>
<AssemblyName>SmvLibrary</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>true</RunCodeAnalysis>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Data.Edm, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Data.Edm.5.6.2\lib\net40\Microsoft.Data.Edm.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.Data.OData, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Data.OData.5.6.2\lib\net40\Microsoft.Data.OData.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.ServiceBus, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\WindowsAzure.ServiceBus.3.2.0\lib\net45-full\Microsoft.ServiceBus.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.WindowsAzure.ServiceRuntime, Version=2.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="Microsoft.WindowsAzure.Storage, Version=4.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression.FileSystem" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Spatial, Version=5.6.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\System.Spatial.5.6.2\lib\net40\System.Spatial.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ActionsQueueEntry.cs" />
<Compile Include="CloudConfig.cs">
<DependentUpon>CloudConfig.xsd</DependentUpon>
</Compile>
<Compile Include="CloudConstants.cs" />
<Compile Include="CloudSMVActionScheduler.cs" />
<Compile Include="LocalSMVActionScheduler.cs" />
<Compile Include="MasterSMVActionScheduler.cs" />
<Compile Include="config.cs">
<DependentUpon>Config.xsd</DependentUpon>
</Compile>
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="ISMVActionScheduler.cs" />
<Compile Include="ISMVPlugin.cs" />
<Compile Include="log.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Utility.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="CloudConfig.xsd">
<SubType>Designer</SubType>
</None>
<None Include="Config.xsd">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmvAccessor\SmvAccessor.csproj">
<Project>{5a923bec-71fc-48e3-b076-2a2aa81ebd03}</Project>
<Name>SmvAccessor</Name>
</ProjectReference>
<ProjectReference Include="..\SMVActionsTable\SMVActionsTable.csproj">
<Project>{6f655d35-3867-4351-8929-23b4578e5190}</Project>
<Name>SMVActionsTable</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="CloudConfig.xml" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>copy $(ProjectDir)Config.xsd $(TargetDir)
copy $(ProjectDir)CloudConfig.xsd $(TargetDir)
copy $(ProjectDir)CloudConfig.xml $(TargetDir)</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

1047
SmvLibrary/Utility.cs Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

15
SmvLibrary/app.config Normal file
Просмотреть файл

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.7.0.0" newVersion="5.7.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.7.0.0" newVersion="5.7.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

182
SmvLibrary/config.cs Normal file
Просмотреть файл

@ -0,0 +1,182 @@
using System.Collections.Generic;
using System.Xml.Serialization;
using System;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1 and then modified
//
namespace SmvLibrary
{
[XmlRootAttribute(Namespace = "")]
[Serializable]
public class SMVConfig
{
[XmlArrayItemAttribute("SetVar", typeof(SetVar))]
public SetVar[] Variables { get; set; }
[XmlArrayItemAttribute("Action", typeof(SMVAction))]
public SMVAction[] Build { get; set; }
[XmlArrayItemAttribute("Action", typeof(SMVAction))]
public SMVAction[] Analysis { get; set; }
}
[XmlRootAttribute("Action", Namespace = "")]
[Serializable]
public class SMVAction
{
public SMVAction()
{
this.breakOnError = true;
this.name = string.Empty;
this.executeOn = "local";
this.variables = null;
}
public SMVAction(SMVCommand[] commands, string name)
{
this.breakOnError = true;
this.name = name;
this.Command = commands;
this.executeOn = "local";
this.variables = null;
}
public SMVAction(SMVAction orig, string analysisProperty)
{
this.breakOnError = orig.breakOnError;
this.name = orig.name;
this.Command = orig.Command;
this.Path = orig.Path;
this.Env = orig.Env;
this.CopyArtifact = orig.CopyArtifact;
this.executeOn = orig.executeOn;
this.nextAction = orig.nextAction;
this.variables = orig.variables;
this.analysisProperty = analysisProperty;
}
public PathType Path { get; set; }
[XmlElementAttribute("Env")]
public SMVEnvVar[] Env { get; set; }
[XmlElementAttribute("CopyArtifact")]
public CopyArtifactType[] CopyArtifact { get; set; }
[XmlElementAttribute("Command")]
public SMVCommand[] Command { get; set; }
[XmlAttributeAttribute()]
public string name { get; set; }
[XmlAttributeAttribute()]
public bool breakOnError { get; set; }
[XmlAttributeAttribute()]
public string executeOn { get; set; }
[XmlAttributeAttribute()]
public string nextAction { get; set; }
[XmlIgnoreAttribute]
public SMVActionResult result { get; set; }
[XmlIgnoreAttribute]
public string analysisProperty { get; set; }
[XmlIgnoreAttribute]
public IDictionary<string, string> variables { get; set; }
public string GetFullName()
{
return (string.IsNullOrEmpty(analysisProperty)) ? name : name + " - " + analysisProperty;
}
}
[XmlRootAttribute("SetVar", Namespace = "")]
[Serializable]
public class SetVar
{
[XmlAttributeAttribute()]
public string key { get; set; }
[XmlAttributeAttribute()]
public string value { get; set; }
}
[XmlRootAttribute("Path", Namespace = "")]
[Serializable]
public class PathType
{
[XmlAttributeAttribute()]
public string value { get; set; }
}
[XmlRootAttribute("Env", Namespace = "")]
[Serializable]
public class SMVEnvVar
{
[XmlAttributeAttribute()]
public string key { get; set; }
[XmlAttributeAttribute()]
public string value { get; set; }
}
[XmlRootAttribute("CopyArtifact", Namespace = "")]
[Serializable]
public class CopyArtifactType
{
[XmlAttributeAttribute()]
public string name { get; set; }
[XmlAttributeAttribute()]
public string type { get; set; }
[XmlAttributeAttribute()]
public entityAttrType entity { get; set; }
[XmlAttributeAttribute()]
public string to { get; set; }
}
public enum entityAttrType
{
Module,
CompilationUnit,
FunctionUnit,
}
[XmlRootAttribute("Command", Namespace = "")]
[Serializable]
public class SMVCommand
{
[XmlAttributeAttribute()]
public string value { get; set; }
[XmlAttributeAttribute()]
public string arguments { get; set; }
}
[Serializable]
public class SMVActionResult
{
public SMVActionResult(string name, string output, bool isSuccessful, bool breakExecution)
{
this.name = name;
this.output = output;
this.isSuccessful = isSuccessful;
this.breakExecution = breakExecution;
}
public string name { get; private set; }
public string output { get; set; }
public bool isSuccessful { get; private set; }
public bool breakExecution { get; private set; }
}
}

109
SmvLibrary/config.xsd Normal file
Просмотреть файл

@ -0,0 +1,109 @@
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="SMV"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $ModuleName : Name of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleDateCreated : Date created timestamp of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleId : Id of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleLastModified : Last modified timestamp of the module [Available if SMV is run with /module:<name>] -->
<!-- $driverType : Driver type [Available in all actions following normal build] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- $analysisDir : $outputDir\SMV [Available in all actions following InterceptedBuild] -->
<!-- $ruleDir : Directory of the rule currently being checked [Available in all Analysis actions if rules are checked] -->
<xs:element name="SMVConfig">
<xs:complexType>
<xs:sequence>
<xs:element name="Variables" type="GlobalVariablesType" minOccurs="0" maxOccurs="1" />
<xs:element name="Build" type="ActionGroupType" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="Analysis" type="ActionGroupType" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="GlobalVariablesType">
<xs:sequence>
<xs:element ref="SetVar" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="ActionGroupType">
<xs:sequence>
<xs:element ref="Action" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
<xs:element name="Action" type="ActionType" />
<xs:complexType name="ActionType">
<xs:sequence>
<xs:element ref="Path" minOccurs="0" maxOccurs="1" />
<xs:element ref="Env" minOccurs="0" maxOccurs="unbounded" />
<xs:element ref="CopyArtifact" minOccurs="0" maxOccurs="unbounded" />
<xs:element ref="Command" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
<xs:attribute name="name" use="required" type="xs:string" />
<xs:attribute name="breakOnError" default="true" use="optional" type="xs:boolean" />
<xs:attribute name="executeOn" use="optional" type="ExecuteOnStringType" />
<xs:attribute name="nextAction" use="optional" type="xs:string" />
</xs:complexType>
<xs:simpleType name="ExecuteOnStringType">
<xs:restriction base="xs:string">
<xs:enumeration value="local" />
<xs:enumeration value="cloud" />
</xs:restriction>
</xs:simpleType>
<xs:element name="SetVar" type="SetVarType" />
<xs:complexType name="SetVarType">
<xs:attribute name="key" use="required" type="NonEmptyString"/>
<xs:attribute name="value" use="required" type="xs:string"/>
</xs:complexType>
<xs:simpleType name="NonEmptyString">
<xs:restriction base="xs:string">
<xs:minLength value="1"/>
</xs:restriction>
</xs:simpleType>
<xs:element name="Env" type="SMVEnvVar" />
<xs:complexType name="SMVEnvVar">
<xs:attribute name="key" use="required" type="NonEmptyString"/>
<xs:attribute name="value" use="required" type="xs:string"/>
</xs:complexType>
<xs:simpleType name="entityAttrType">
<xs:restriction base="xs:string">
<xs:enumeration value="Module" />
<xs:enumeration value="CompilationUnit" />
<xs:enumeration value="FunctionUnit" />
</xs:restriction>
</xs:simpleType>
<xs:element name="CopyArtifact" type="CopyArtifactType" />
<xs:complexType name="CopyArtifactType">
<xs:attribute name="name" use="required" type="NonEmptyString" />
<xs:attribute name="type" use="required" type="xs:string" />
<xs:attribute name="entity" use="required" type="entityAttrType" />
<xs:attribute name="to" use="optional" type="xs:string" />
</xs:complexType>
<xs:element name="Command" type="SMVCommand" />
<xs:complexType name="SMVCommand">
<xs:attribute name="value" use="required" type="NonEmptyString" />
<xs:attribute name="arguments" use="optional" type="xs:string" />
</xs:complexType>
<xs:element name="Path" type="PathType" />
<xs:complexType name="PathType">
<xs:attribute name="value" use="required" type="xs:string"/>
</xs:complexType>
</xs:schema>

135
SmvLibrary/log.cs Normal file
Просмотреть файл

@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SmvLibrary
{
sealed public class Log
{
private Log()
{
}
static string logPath;
public static void SetLogPath(string path)
{
if (!String.IsNullOrEmpty(path))
{
logPath = path;
}
}
/// <summary>
/// Logs a message to the Console or a logger
/// </summary>
/// <param name="type">The type of message.</param>
/// <param name="message">The message to log.</param>
static void WriteLog(string type, string message, TextWriter logger)
{
string result = String.Empty;
if (String.IsNullOrEmpty(type))
{
result = message;
}
else
{
result = String.Format(CultureInfo.InvariantCulture, "{0} : {1}", type, message);
}
if(logger != null)
{
lock (logger)
{
logger.WriteLine(result);
logger.Flush();
}
return;
}
Console.WriteLine(result);
}
/// <summary>
/// Logs a message to a file
/// </summary>
/// <param name="fileName">Filename.</param>
/// <param name="text">The text to log.</param>
public static void WriteToFile(string fileName, string text)
{
if (!String.IsNullOrEmpty(logPath))
{
string path = Path.Combine(logPath, fileName + ".txt");
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(text);
}
}
}
/// <summary>
/// Logs a generic message
/// </summary>
/// <param name="message">The message to log.</param>
public static void LogMessage(string message, TextWriter logger = null)
{
WriteLog("", message, logger);
}
/// <summary>
/// Logs a INFO message
/// </summary>
/// <param name="message">The message to log.</param>
public static void LogInfo(string message, TextWriter logger = null)
{
WriteLog("INFO", message, logger);
}
/// <summary>
/// Logs a DEBUG message
/// </summary>
/// <param name="message">the message to log</param>
/// <param name="logger"></param>
public static void LogDebug(string message, TextWriter logger = null)
{
if (Utility.debugMode)
{
WriteLog("DEBUG", message, logger);
}
}
/// <summary>
/// Logs a ERROR message
/// </summary>
/// <param name="message">The message to log.</param>
public static void LogError(string message, TextWriter logger = null)
{
WriteLog("ERROR", message, logger);
}
/// <summary>
/// Logs a error message and terminates
/// </summary>
/// <param name="message">The message to log.</param>
public static void LogFatalError(string message)
{
WriteLog("FATAL ERROR", message, null);
Environment.Exit(-1);
}
/// <summary>
/// Logs a WARNING message
/// </summary>
/// <param name="message">The message to log.</param>
public static void LogWarning(string message, TextWriter logger = null)
{
WriteLog("WARNING", message, logger);
}
}
}

Просмотреть файл

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Data.Edm" version="5.6.2" targetFramework="net45" />
<package id="Microsoft.Data.OData" version="5.6.2" targetFramework="net45" />
<package id="System.Spatial" version="5.6.2" targetFramework="net45" />
<package id="WindowsAzure.ServiceBus" version="3.2.0" targetFramework="net45" />
</packages>

22
SmvSkeleton/App.config Normal file
Просмотреть файл

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<clear />
<add name="SmvDbConnectionString" connectionString="Data Source=.;Initial Catalog=SmvDb;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.2.0" newVersion="5.6.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.6.2.0" newVersion="5.6.2.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Двоичные данные
SmvSkeleton/GlobalSuppressions.cs Normal file

Двоичный файл не отображается.

453
SmvSkeleton/Program.cs Normal file
Просмотреть файл

@ -0,0 +1,453 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
using System.Configuration;
using SmvAccessor;
using System.Xml;
using System.Xml.Schema;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using System.Collections;
using System.Xml.Serialization;
using SmvSkeleton.Properties;
using SmvLibrary;
using System.Reflection;
using System.Globalization;
namespace SmvSkeleton
{
class Program
{
const int defaultLocalThreadCount = 5;
static SMVConfig smvConfig;
const string configXmlFileName = "Config.xml";
const string configXsdFileName = "Config.xsd";
const string cloudConfigXmlFileName = "CloudConfig.xml";
const string cloudConfigXsdFileName = "CloudConfig.xsd";
private static bool doAnalysis = false;
private static string buildLogFileNamePrefix = "smvbuild";
/// <summary>
/// Prints the usage string to the console.
/// </summary>
static void PrintUsage()
{
Console.WriteLine(Resources.UsageString);
}
/// <summary>
/// Prints detailed help text to the console.
/// </summary>
static void PrintHelp()
{
PrintUsage();
Log.LogInfo(Resources.HelpTextWithoutUsageString);
}
/// <summary>
/// Processes command line arguments for Analysis.
/// </summary>
/// <param name="args">The list of command line arguments.</param>
/// <returns>true on success, false on failure.</returns>
static bool ProcessArgs(string[] args)
{
bool help = false;
bool unsupportedArgument = false;
for (int i = 0; i < args.Length; )
{
args[i] = args[i].ToLowerInvariant();
if (args[i].Equals("/help") || args[i].Equals("/?"))
{
help = true;
PrintHelp();
break;
}
#region module
if (args[i].StartsWith("/module:", StringComparison.InvariantCulture))
{
string path;
string dateTime = String.Empty;
Regex re = new Regex(@"^/module:([^@]+)@?(.+)?$");
Match match = re.Match(args[i].Trim());
if (!match.Success)
{
Log.LogError("Invalid argument: " + args[i]);
PrintUsage();
return false;
}
path = match.Groups[1].Value.Trim();
if (match.Groups.Count == 3)
{
dateTime = match.Groups[2].Value;
}
DateTime dt = default(DateTime);
if (!String.IsNullOrEmpty(dateTime))
{
try
{
dt = DateTime.ParseExact(dateTime, "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
}
catch (FormatException)
{
Log.LogError(String.Format(CultureInfo.InvariantCulture, "Could not parse timestamp: {0} from module parameter: {1}", dateTime, args[i]));
return false;
}
}
ISmvAccessor dbAccessor = Utility.GetSmvSQLAccessor();
Utility.smvModule = dbAccessor.GetModuleByName(path, dt, true);
if (Utility.smvModule == null)
{
Log.LogError("Module with name: " + path + " does not exist in the data source.");
return false;
}
i++;
}
#endregion
else if (args[i].Equals("/getavailablemodules", StringComparison.InvariantCulture))
{
Log.LogInfo("Printing list of all modules in the data source:");
ISmvAccessor dbAccessor = Utility.GetSmvSQLAccessor();
dbAccessor.PrintModuleStatistics();
i++;
return false;
}
else if (args[i].StartsWith("/searchmodules:", StringComparison.InvariantCulture))
{
string searchText = args[i].Replace("/searchmodules:", String.Empty);
Log.LogInfo(String.Format(CultureInfo.InvariantCulture, "INFO: Searching for modules with \"{0}\" in either the name field..", searchText));
ISmvAccessor dbAccessor = Utility.GetSmvSQLAccessor();
IEnumerable<SmvAccessor.Module> ms = dbAccessor.SearchModules(searchText);
dbAccessor.PrintModuleStatistics(ms);
i++;
return false;
}
else if (args[i].StartsWith("/config:", StringComparison.InvariantCulture) || args[i].StartsWith("/log:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (tokens.Length == 2)
{
string value = tokens[1].Replace(@"""", String.Empty);
if (tokens[0].Equals("/config"))
{
Utility.SetSmvVar("configFilePath", value);
}
else if (tokens[0].Equals("/log"))
{
if (!Directory.Exists(value))
{
Log.LogFatalError("Log path does not exist.");
}
Log.SetLogPath(value);
}
}
i++;
}
else if (args[i].Equals("/analyze"))
{
doAnalysis = true;
i++;
}
else if (args[i].StartsWith("/plugin:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (File.Exists(tokens[1]))
{
Utility.pluginPath = tokens[1].Replace(Environment.GetEnvironmentVariable("smv"), "%smv%");
Assembly assembly = Assembly.LoadFrom(tokens[1]);
string fullName = assembly.ExportedTypes.First().FullName;
Utility.plugin = (ISMVPlugin)assembly.CreateInstance(fullName);
if (Utility.plugin == null)
{
Log.LogFatalError("Could not load plugin.");
}
Utility.plugin.Initialize();
}
else
{
Log.LogFatalError("Plugin not found.");
}
i++;
}
else if (args[i].StartsWith("/projectfile:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
Utility.SetSmvVar("projectFileArg", tokens[1]);
i++;
}
else if (args[i].Equals("/debug"))
{
Utility.debugMode = true;
i++;
}
else
{
unsupportedArgument = true;
i++;
}
}
if (Utility.plugin != null)
{
Utility.plugin.ProcessPluginArgument(args);
}
else if (unsupportedArgument)
{
Log.LogFatalError("Unsupported arguments. Please provide a Plugin.");
}
if (help)
{
if (Utility.plugin != null)
{
Utility.plugin.PrintPluginHelp();
}
return false;
}
return true;
}
static void Main(string[] args)
{
Utility.SetSmvVar("workingDir", Directory.GetCurrentDirectory());
Utility.SetSmvVar("logFilePath", null);
Utility.SetSmvVar("assemblyDir", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
Utility.SetSmvVar("configFilePath", Path.Combine(Utility.GetSmvVar("workingDir"), configXmlFileName));
Utility.SetSmvVar("smvLogFileNamePrefix", buildLogFileNamePrefix);
// Process commandline arguments.
// Note that ProcessArgs will return false if execution should not continue.
// This happens in cases such as /help, /getAvailableModules, /searchmodules
if (!ProcessArgs(args))
{
return;
}
// Get the SMV version name.
string smvVersionTxtPath = Path.Combine(Utility.GetSmvVar("assemblyDir"), "SmvVersionName.txt");
if(!File.Exists(smvVersionTxtPath))
{
Log.LogFatalError("SmvVersionName.txt must exist in the SMV bin directory.");
}
string[] lines = File.ReadAllLines(smvVersionTxtPath);
if(lines.Length < 1)
{
Log.LogFatalError("SmvVersionName.txt is empty.");
}
Utility.version = lines[0];
// Consume specified configuration file
smvConfig = GetSMVConfig();
if (smvConfig == null)
{
Log.LogFatalError("Could not load Config file");
}
// Set the variables defined in the Variables node in the config file
LoadGlobalVariables(smvConfig.Variables);
// Project file value from command line overrides the Config value
if (!String.IsNullOrEmpty(Utility.GetSmvVar("projectFileArg")))
{
Utility.SetSmvVar("projectFile", Utility.GetSmvVar("projectFileArg"));
}
bool buildResult = false;
bool analysisResult = false;
double buildTime = 0, analysisTime = 0;
int localThreadCount = defaultLocalThreadCount;
if(Utility.GetSmvVar("localThreads") != null)
{
localThreadCount = int.Parse(Utility.GetSmvVar("localThreads"));
}
Log.LogInfo(String.Format("Running local scheduler with {0} threads", localThreadCount));
// Load the cloud config from an XML file.
SMVCloudConfig cloudConfig = GetSMVCloudConfig();
// Set up the schedulers.
using (Utility.scheduler = new MasterSMVActionScheduler())
using (var localScheduler = new LocalSMVActionScheduler(localThreadCount))
using (var cloudScheduler = new CloudSMVActionScheduler(cloudConfig))
{
Utility.scheduler.AddScheduler("local", localScheduler);
Utility.scheduler.AddScheduler("cloud", cloudScheduler);
// Do build if specified in the configuration file
if (smvConfig.Build != null)
{
Stopwatch sw = Stopwatch.StartNew();
// Populate the actions dictionary that will be used by the schedulers.
Utility.PopulateActionsDictionary(smvConfig.Build);
if (string.IsNullOrEmpty(Utility.GetSmvVar("projectFile")))
{
Log.LogFatalError("Project file not set");
}
List<SMVActionResult> buildActionsResult = Utility.ExecuteActions(Utility.GetRootActions(smvConfig.Build));
buildResult = Utility.IsExecuteActionsSuccessful(buildActionsResult);
if (Utility.plugin != null)
{
Utility.plugin.PostBuild(smvConfig.Build);
}
sw.Stop();
buildTime = sw.Elapsed.TotalSeconds;
}
// If build succeeded or it was not specified, do analysis (if specified and called)
if (smvConfig.Build == null || buildResult)
{
if (smvConfig.Analysis != null)
{
if (doAnalysis)
{
Stopwatch sw = Stopwatch.StartNew();
Utility.PopulateActionsDictionary(smvConfig.Analysis);
if (Utility.plugin != null)
{
Log.LogInfo("Using plugin " + Utility.plugin + " for analysis.");
analysisResult = Utility.plugin.DoPluginAnalysis(smvConfig.Analysis);
Utility.plugin.PostAnalysis(smvConfig.Analysis);
}
else
{
List<SMVActionResult> analysisActionsResult = Utility.ExecuteActions(Utility.GetRootActions(smvConfig.Analysis));
analysisResult = Utility.IsExecuteActionsSuccessful(analysisActionsResult);
}
if (!analysisResult)
{
Log.LogFatalError("Analysis failed.");
}
sw.Stop();
analysisTime = sw.Elapsed.TotalSeconds;
}
}
}
else
{
Log.LogFatalError("Build failed, skipping Analysis.");
}
}
Utility.PrintResult(Utility.result, buildTime, analysisTime);
Log.LogInfo(String.Format("DONE. Total time taken {0} seconds", (buildTime + analysisTime)));
}
/// <summary>
/// Load the cloud configuration from an XML file and store it in an SMVCloudConfig object.
/// </summary>
/// <returns>The SMVCloudConfig object containing the cloud configuration.</returns>
static SMVCloudConfig GetSMVCloudConfig()
{
string cloudConfigXmlPath = Path.Combine(Utility.GetSmvVar("assemblyDir"), cloudConfigXmlFileName);
string contents = Utility.ReadFile(cloudConfigXmlPath);
if (!String.IsNullOrEmpty(contents))
{
bool isXMLValid = false;
string schemaPath = Path.Combine(Utility.GetSmvVar("assemblyDir"), cloudConfigXsdFileName);
using (StringReader configContent = new StringReader(contents))
{
isXMLValid = Utility.ValidateXmlFile(schemaPath, configContent);
}
if (!isXMLValid)
{
Log.LogError("Could not load and validate XML file: " + Utility.GetSmvVar("configFilePath"));
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(SMVCloudConfig));
SMVCloudConfig config = null;
using (TextReader reader = new StringReader(contents))
{
config = (SMVCloudConfig)serializer.Deserialize(reader);
}
return config;
}
else
{
return null;
}
}
/// <summary>
/// Load the configuration from the config file and store it in an SMVConfig object.
/// </summary>
/// <returns>The configuration as an SMVConfig object.</returns>
static SMVConfig GetSMVConfig()
{
string configFileContent = Utility.ReadFile(Utility.GetSmvVar("configFilePath"));
if (!String.IsNullOrEmpty(configFileContent))
{
bool isXMLValid = false;
string schemaPath = Path.Combine(Utility.GetSmvVar("assemblyDir"), configXsdFileName);
using (StringReader configContent = new StringReader(configFileContent))
{
isXMLValid = Utility.ValidateXmlFile(schemaPath, configContent);
}
if (!isXMLValid)
{
Log.LogError("Could not load and validate XML file: " + Utility.GetSmvVar("configFilePath"));
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(SMVConfig));
using (TextReader reader = new StringReader(configFileContent))
{
smvConfig = (SMVConfig)serializer.Deserialize(reader);
}
return smvConfig;
}
else
{
return null;
}
}
/// <summary>
/// Sets the global variables, defined in the Config file, in the SmvVar dictionary
/// </summary>
/// <param name="globalVars">The variables defined in the config file.</param>
static void LoadGlobalVariables(SetVar[] globalVars)
{
if (globalVars != null)
{
foreach (SetVar smvVar in globalVars)
{
string value = Environment.ExpandEnvironmentVariables(smvVar.value);
Utility.SetSmvVar(smvVar.key, Utility.ExpandSmvVariables(value));
}
}
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
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("SmvSkeleton")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SmvSkeleton")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4d41175b-88cc-4b76-a920-bb5a577b4041")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

81
SmvSkeleton/Properties/Resources.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,81 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SmvSkeleton.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SmvSkeleton.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string HelpTextWithoutUsageString {
get {
return ResourceManager.GetString("HelpTextWithoutUsageString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to smvskeleton.exe [/Module:&lt;ModuleName&gt;[@&lt;LastModified&gt;]] [/Rules|Check:*|Rule1,Rule2,Rule3...] [/Log:&lt;Path to log file&gt;] [/Config:&lt;Path to config file&gt;] [/GetAvailableModules] [/SearchModules:&lt;SearchString&gt;] [/Help|/?].
/// </summary>
internal static string UsageString {
get {
return ResourceManager.GetString("UsageString", resourceCulture);
}
}
}
}

Просмотреть файл

@ -0,0 +1,127 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="HelpTextWithoutUsageString" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\HelpTextWithoutUsageString.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
<data name="UsageString" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\UsageString.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
</data>
</root>

26
SmvSkeleton/Properties/Settings.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SmvSkeleton.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
</SettingsFile>

Просмотреть файл

@ -0,0 +1,40 @@
/Debug
To write all the output to the console.
/ProjectFile
Name of the project file. It can also be set in the config file.
/Analyze
To run analysis.
/Module:<Name>[@<LastModified>]
Specify a module for processing. <Name> is the name of the module. If there
are multiple modules with the same name, the version that was most recently
modified is used. Specify which version of the module to use by passing the
<LastModified> value in yyyyMMddHHmmss format. Use /SearchModules to find
all versions of a particular module. If the analysis requires multiple
modules, pass this parameter once for each module.
Eg. For an analysis that requires three modules:
smvskeleton.exe /Module:module1 /Module:module2 /Module:mod3@20140604221756
/Rules|Check:*|Rule1,Rule2,Rule3...
Specify the rules (comma separated or * for all the rules), you want to verify.
/Log:<LogFilePath>
Specify the path for the log file, if you want to persist the log.
/Plugin:<DLLPath>
Specify the path to the DLL, if you want to use a plugin
/Config:<ConfigFilePath>
Specify the path for the Config file.
/GetAvailableModules
Print the entire list of modules in the system to the console.
/SearchModules:<SearchString>
Print the list of all the modules in the data source whose names or paths
contain <SearchString>.
/Help | /?
Print this help text.

Просмотреть файл

@ -0,0 +1 @@
smvskeleton.exe [/ProjectFile:<Name>] [/Analyze] [/Debug] [/Module:<Name>[@<LastModified>]] [/Rules|Check:*|Rule1,Rule2,Rule3...] [/Plugin:<DLLPath>] [/Log:<LogFilePath>] [/Config:<ConfigFilePath>] [/GetAvailableModules] [/SearchModules:<SearchString>] [/Help|/?]

Просмотреть файл

@ -0,0 +1,8 @@
#define SDV_NOTDONE 0
#define SDV_PASSED 1
#define SDV_FAILED 2
#define SDV_NA 3
#define SDV_TIMEOUT 4
#define SDV_SPACEOUT 5
#define SDV_GIVEUP 6
#define SDV_TOOLERROR 7

Просмотреть файл

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="." />
<SetVar key="outputDir" value="[$workingDir]\output\\" />
</Variables>
<Build>
<Action name="InterceptedBuild" nextAction="BPL">
<Command value="SET" arguments="CLToolExe=%smv%\bin\CL.exe" />
<Command value="SET" arguments="LinkToolExe=%smv%\bin\Link.exe" />
<Command value="SET" arguments="SMV_OUTPUT_DIR=[$outputDir]" />
<Command value="build" arguments="nuke" />
<Command value="mkdir" arguments="%SMV_OUTPUT_DIR%" />
<Command value="build" arguments="-cz /j [$smvLogFileNamePrefix]" />
</Action>
<Action name="BPL" breakOnError="false">
<Path value="[$outputDir]" />
<Env key="PATH" value="%smv%\analysisPlugins\sdv\bin\engine\engineq;%smv%\analysisPlugins\sdv\bin\engine\engineq\Corral;%PATH%" />
<Command value="slam" arguments=" -no_slamcl -leave_files –smv"/>
</Action>
</Build>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- $analysisDir : $outputDir\SMV [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="sources" />
</Variables>
<Build>
<!-- Do a normal build first to ensure everything builds correctly. -->
<Action name="NormalBuild" breakOnError="true" nextAction="InterceptedBuild">
<Command value="set" arguments="inetroot=c:\enlistments\edge" />
<Command value="set" arguments="corextbranch=edge" />
<Command value="set" arguments="smv_intercept=true" />
<Command value="c:\enlistments\edge\tools\path1st\myenv.cmd" arguments="" />
<Command value="build" arguments="-cz /j [$smvLogFileNamePrefix]" />
</Action>
<!-- Intercepted build to produce IR. -->
<Action name="InterceptedBuild">
<Command value="set" arguments="inetroot=c:\enlistments\edge" />
<Command value="set" arguments="corextbranch=edge" />
<Command value="set" arguments="smv_intercept=true" />
<Command value="c:\enlistments\edge\tools\path1st\myenv.cmd" arguments="" />
<Command value="build" arguments="-cz /j [$smvLogFileNamePrefix].a" />
</Action>
</Build>
<Analysis>
<Action name="NullCheckerAnalysis">
<Path value="[$outputDir]" />
<Env key="SMV_ORIG" value="%SMV%" />
<Env key="SMV" value="%smv_orig%\analysisPlugins\NullChecker\bin\engine" />
<Env key="PATH" value="%smv_orig%\analysisPlugins\NullChecker\bin\engine;%smv_orig%\analysisPlugins\NullChecker\bin\engine\;%smv_orig%\analysisPlugins\NullChecker\bin\engine\corral;%PATH%" />
<Command value="wlimit" arguments="/b /r /c /w 3000 /u 3000 /m 2500 slam -no_slamcl -leave_files -smv >wlimit.txt 2>wlimit.err" />
</Action>
</Analysis>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="fail_driver1.vcxproj" />
</Variables>
<Build>
<!-- Do a normal build first to ensure everything builds correctly. -->
<Action name="NormalBuild" breakOnError="true" nextAction="InterceptedBuild">
<Command value="build" arguments="nuke" />
<Command value="build" arguments="-cz /j [$smvLogFileNamePrefix]" />
</Action>
<Action name="InterceptedBuild" nextAction="BPL">
<!-- <Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" /> -->
<Command value="SET" arguments="SMV_OUTPUT_DIR=[$outputDir]" />
<Command value="SET" arguments="SMV_CL_ADD_ARG=" />
<Command value="msbuild" arguments="/noconsolelogger /fileLoggerParameters:LogFile=[$smvLogFileNamePrefix].log /t:rebuild /p:trackfileaccess=false /p:forcerebuild=true /p:cltoolpath=%smv%\bin /p:linktoolpath=%smv%\bin /p:libtoolpath=%smv%\bin [$projectFile]"/>
</Action>
<Action name="BPL" breakOnError="false">
<Path value="[$outputDir]" />
<Env key="PATH" value="%smv%\analysisPlugins\sdv\bin\engine\engineq;%smv%\analysisPlugins\sdv\bin\engine\engineq\Corral;%PATH%" />
<Command value="slam" arguments=" -no_slamcl -leave_files –smv"/>
</Action>
</Build>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="%MSBuildProjectFile_SDV%" />
</Variables>
<Build>
<!-- Do a normal build first to ensure everything builds correctly. -->
<Action name="NormalBuild" breakOnError="true" nextAction="InterceptedBuild">
<Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" />
<Command value="msbuild" arguments="/noconsolelogger /fileLoggerParameters:LogFile=[$smvLogFileNamePrefix].log /t:rebuild &quot;[$projectFile]&quot; /p:configuration=&quot;%CONFIGURATION_SDV%&quot; /p:platform=&quot;%PLATFORM_SDV%&quot;"/>
</Action>
<Action name="InterceptedBuild" nextAction="Scan">
<Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" />
<Command value="SET" arguments="SMV_OUTPUT_DIR=[$outputDir]" />
<Command value="SET" arguments="SMV_CL_ADD_ARG=-I\&quot;%smv%\analysisPlugins\sdv\osmodel\[$driverType]\&quot; -I\&quot;[$headersDir]\&quot;" />
<Command value="msbuild" arguments="/noconsolelogger /fileLoggerParameters:LogFile=[$smvLogFileNamePrefix].log /t:rebuild /p:trackfileaccess=false /p:forcerebuild=true /p:cltoolpath=&quot;%smv%\bin&quot; /p:linktoolpath=&quot;%smv%\bin&quot; &quot;[$projectFile]&quot; /p:configuration=&quot;%CONFIGURATION_SDV%&quot; /p:platform=&quot;%PLATFORM_SDV%&quot;"/>
</Action>
</Build>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="ms\ntdll.mak" />
</Variables>
<Build>
<!-- Do a normal build first to ensure everything builds correctly. -->
<Action name="NormalBuild" nextAction="Clean" breakOnError="true">
<Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" />
<Command value="nmake" arguments="-f [$projectFile] > smvbuild.log"/>
</Action>
<Action name="Clean" nextAction="InterceptedBuild" breakOnError="true">
<Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" />
<Command value="nmake" arguments="-f [$projectFile] clean"/>
</Action>
<Action name="InterceptedBuild">
<Command value="&quot;c:\program files (x86)\microsoft visual studio 12.0\vc\vcvarsall.bat&quot;" arguments="x86" />
<Command value="SET" arguments="SMV_OUTPUT_DIR=[$outputDir]" />
<Command value="SET" arguments="path=%smv%\bin;%path%" />
<Command value="nmake" arguments="-f [$projectFile] > smvbuild.log"/>
</Action>
</Build>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $ModuleName : Name of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleDateCreated : Date created timestamp of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleId : Id of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleLastModified : Last modified timestamp of the module [Available if SMV is run with /module:<name>] -->
<Analysis>
<Action name="Scan">
<Env key="PATH" value="%smv%\analysisPlugins\sdv\bin\engine;%smv%\analysisPlugins\sdv\bin\engine\engineq;%smv\analysisPlugins\sdv\bin\engine\engineq\corral;%PATH%" />
<CopyArtifact name="lidir" entity="Module" type="li" to="li" />
<Command value="cd" arguments="[$lidir]" />
<Command value="slamscan" arguments="--input slam --output scan --entry_points_base &quot;%smv%\analysisPlugins\sdv\osmodel\wdm\dispatch_routines.h&quot; /D_SDV_"/>
</Action>
</Analysis>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $ModuleName : Name of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleDateCreated : Date created timestamp of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleId : Id of the module [Available if SMV is run with /module:<name>] -->
<!-- $ModuleLastModified : Last modified timestamp of the module [Available if SMV is run with /module:<name>] -->
<Analysis>
<Action name="RunUnstableCodeAnalysis">
<Env key="acs_bin_dir" value="%smv%\analysisplugins\UnstableCodeAnalysis\AlmostCorrectSpecsBinaries" />
<CopyArtifact name="functionunitbpldir" entity="FunctionUnit" type="bpl" to="bpls" />
<CopyArtifact name="cfgDir" entity="CompilationUnit" type="rawcfgf" to="cfg" />
<!--<CopyArtifact name="sourceDir" entity="Module" type="source" to="src" />-->
<Command value="%smv%\analysisplugins\UnstableCodeAnalysis\scripts\unstable.bat" arguments="[$functionunitbpldir] -full -FindDoomedProgramPoints" />
</Action>
</Analysis>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- Available variables which can be used inside actions : -->
<!-- $assemblyDir : Directory where SMV binaries are located [Available in all actions] -->
<!-- $workingDir : Directory where SMV is run [Available in all actions] -->
<!-- $actionName : Name of the current action [Available in all actions] -->
<!-- $actionPath : Path where the current action is run [Available in all actions] -->
<!-- $configFilePath : Path of the config file provided to SMV [Available in all actions] -->
<!-- $logFilePath : Path to the log file [Available in all actions, if SMV is run with /log:<path>] -->
<!-- $outputDir : Directory where the build files are generated [Available in all actions following InterceptedBuild] -->
<!-- $analysisDir : $outputDir\SMV [Available in all actions following InterceptedBuild] -->
<!-- Run the normal build, intercepted build and the scan step -->
<Variables>
<SetVar key="projectFile" value="sources" />
</Variables>
<Build>
<!-- Do a normal build first to ensure everything builds correctly. -->
<Action name="NormalBuild" breakOnError="true" nextAction="InterceptedBuild">
<Command value="%sdxroot%\\tools\\razzle.cmd" arguments="no_certcheck amd64 fre no_oacr" />
<Command value="build" arguments="-cZe /j [$smvLogFileNamePrefix]"/>
</Action>
<!-- Intercepted build to produce IR. -->
<Action name="InterceptedBuild">
<Command value="%sdxroot%\\tools\\razzle.cmd" arguments="no_certcheck amd64 fre no_oacr" />
<Command value="SET" arguments="SMV_OUTPUT_DIR=[$outputDir]" />
<Command value="SET" arguments="SMV=%smv%" />
<Command value="SET" arguments="SMV_CL_ADD_ARG=-I%smv%\analysisPlugins\sdv\osmodel\[$driverType] -I[$headersDir]" />
<Command value="SET" arguments="STATIC_DRIVER_VERIFIER=%smv%\bin" />
<Command value="build" arguments="-cZe /j [$smvLogFileNamePrefix]"/>
</Action>
</Build>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8" ?>
<SMVConfig
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="Config.xsd"
>
<!-- Please don't add any comments with double hyphens in them. -->
<!-- XML does not support a double hyphen within a comment, since it is a delimiter. -->
<!-- $ModuleOutputDirectory: The directory where the build files are generated -->
<Analysis>
<Action name="RunSymDiff">
<Env key="sdxroot" value="C:\fbl_hyp_dev" />
<Env key="symdiff_root" value="C:\symdiff.1.0" />
<Env key="path" value="%SYMDIFF_ROOT%\scripts;%SYMDIFF_ROOT%\scripts\cygwin_binaries;%SYMDIFF_ROOT%\SymDiff\bin\x86\Debug\;%SYMDIFF_ROOT%\BoogieWrapper\bin\Debug\;%SYMDIFF_ROOT%\SymDiff\references;%PATH%" />
<Env key="havoc_dll_dir" value="%symdiff_root%\havoc_dlls\" />
<Env key="havocfeconfig" value="%symdiff_root%\havoc_dlls\havoc.config" />
<Env key="cygwin" value="nodosfilewarning" />
<CopyArtifact name="rawcfgfDirs" type="rawcfgf" entity="CompilationUnit" to="[$ModuleName][$ModuleDateCreated]" />
<Command value="C:\symdiff.1.0\scripts\run_symdiff_rawcfgf.cmd" arguments="[$rawcfgfDirs]"/>
</Action>
</Analysis>
</SMVConfig>

Просмотреть файл

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SmvSkeleton</RootNamespace>
<AssemblyName>SmvSkeleton</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<UseVSHostingProcess>true</UseVSHostingProcess>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<RunCodeAnalysis>true</RunCodeAnalysis>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SmvAccessor\SmvAccessor.csproj">
<Project>{5a923bec-71fc-48e3-b076-2a2aa81ebd03}</Project>
<Name>SmvAccessor</Name>
</ProjectReference>
<ProjectReference Include="..\SMVLibrary\SmvLibrary.csproj">
<Project>{e03dc0df-84cc-420c-91b1-2a937e88ff31}</Project>
<Name>SmvLibrary</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<None Include="Resources\HelpTextWithoutUsageString.txt" />
<None Include="Resources\UsageString.txt" />
<Content Include="Resources\sdv-pre-results.h" />
<Content Include="Samples\MSBuild-Build.xml" />
<Content Include="Samples\NMake-OpenSSL.xml" />
<Content Include="Samples\NoBuild-SlamScan.xml">
<SubType>Designer</SubType>
</Content>
<Content Include="Samples\NoBuild-UnstableCodeAnalysis.xml" />
<Content Include="Samples\Razzle-Build.xml" />
<Content Include="Samples\SymDiff.xml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>copy $(ProjectDir)\Resources\sdv-pre-results.h $(TargetDir)
</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>/plugin:"d:\slam1\src\t-apoup\smv\smvsdv\bin\debug\sdvplugin.dll" /config:"d:\slam1\smvcloud\analysisplugins\sdv\configurations\msbuild-build-verify.xml" /analyze</StartArguments>
<StartWorkingDirectory>D:\slam1\WDK\src_5043\fail_drivers\wdm\fail_driver1\</StartWorkingDirectory>
<StartAction>Project</StartAction>
</PropertyGroup>
<PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory>
<InstallUrlHistory />
<SupportUrlHistory />
<UpdateUrlHistory />
<BootstrapperUrlHistory />
<ErrorReportUrlHistory />
<FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
</PropertyGroup>
</Project>

Двоичные данные
dpks/SmvCloud.dpk Normal file

Двоичный файл не отображается.

9
msbuild.proj Normal file
Просмотреть файл

@ -0,0 +1,9 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Dirs Include="smvsdv"/>
</ItemGroup>
<Import Project="$(SLAMSRC)\msbuild\sdv.targets" />
</Project>

104
smv.sln Normal file
Просмотреть файл

@ -0,0 +1,104 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{00D1A9C2-B5F0-4AF3-8072-F6C62B433612}") = "SmvDb", "SmvDb\SmvDb.sqlproj", "{824F4A4A-89DA-47BB-95E0-8B3F3375505F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Smv2Sql", "Smv2Sql\Smv2Sql.csproj", "{B70DBC28-ED30-4306-8433-2E7B9C383CE7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvInterceptorWrapper", "SmvInterceptorWrapper\SmvInterceptorWrapper.csproj", "{8F9EA492-E86B-4F1C-ADC5-BF407466F448}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvAccessor", "SmvAccessor\SmvAccessor.csproj", "{5A923BEC-71FC-48E3-B076-2A2AA81EBD03}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvInterceptor", "SmvInterceptor\SmvInterceptor.csproj", "{2422E37E-3DC7-4B6C-8246-317AB656D788}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvAccessorDemo", "SmvAccessorDemo\SmvAccessorDemo.csproj", "{BDC040C9-7918-419B-A6CA-046F1AAA3813}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvSkeleton", "SmvSkeleton\SmvSkeleton.csproj", "{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvLibrary", "SMVLibrary\SmvLibrary.csproj", "{E03DC0DF-84CC-420C-91B1-2A937E88FF31}"
ProjectSection(ProjectDependencies) = postProject
{6F655D35-3867-4351-8929-23B4578E5190} = {6F655D35-3867-4351-8929-23B4578E5190}
{5A923BEC-71FC-48E3-B076-2A2AA81EBD03} = {5A923BEC-71FC-48E3-B076-2A2AA81EBD03}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvSdv", "SmvSdv\SmvSdv.csproj", "{332F53A7-E9F4-4A7E-BDAC-E490F3A6935A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvTest", "SmvTest\SmvTest.csproj", "{55EE08BA-C5E5-40C5-A667-B91D88DABD0D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvLineCounter", "SmvLineCounter\SmvLineCounter.csproj", "{417057CF-9FBD-4732-BE9D-42875EBA61C9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SMVActionsTable", "SMVActionsTable\SMVActionsTable.csproj", "{6F655D35-3867-4351-8929-23B4578E5190}"
EndProject
Project("{CC5FD16D-436D-48AD-A40C-5A424C6E3E79}") = "SmvCloud", "SmvCloud\SmvCloud.ccproj", "{3BBC4FAD-85A1-4451-8975-BC00EAF81E63}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SmvCloudWorker", "SmvCloudWorker\SmvCloudWorker.csproj", "{00D32586-D675-4EF4-B4F3-06DC45BBF079}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Release|Any CPU.Build.0 = Release|Any CPU
{824F4A4A-89DA-47BB-95E0-8B3F3375505F}.Release|Any CPU.Deploy.0 = Release|Any CPU
{B70DBC28-ED30-4306-8433-2E7B9C383CE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B70DBC28-ED30-4306-8433-2E7B9C383CE7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B70DBC28-ED30-4306-8433-2E7B9C383CE7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B70DBC28-ED30-4306-8433-2E7B9C383CE7}.Release|Any CPU.Build.0 = Release|Any CPU
{8F9EA492-E86B-4F1C-ADC5-BF407466F448}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8F9EA492-E86B-4F1C-ADC5-BF407466F448}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F9EA492-E86B-4F1C-ADC5-BF407466F448}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F9EA492-E86B-4F1C-ADC5-BF407466F448}.Release|Any CPU.Build.0 = Release|Any CPU
{5A923BEC-71FC-48E3-B076-2A2AA81EBD03}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5A923BEC-71FC-48E3-B076-2A2AA81EBD03}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5A923BEC-71FC-48E3-B076-2A2AA81EBD03}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5A923BEC-71FC-48E3-B076-2A2AA81EBD03}.Release|Any CPU.Build.0 = Release|Any CPU
{2422E37E-3DC7-4B6C-8246-317AB656D788}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2422E37E-3DC7-4B6C-8246-317AB656D788}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2422E37E-3DC7-4B6C-8246-317AB656D788}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2422E37E-3DC7-4B6C-8246-317AB656D788}.Release|Any CPU.Build.0 = Release|Any CPU
{BDC040C9-7918-419B-A6CA-046F1AAA3813}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BDC040C9-7918-419B-A6CA-046F1AAA3813}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E016F57D-68E9-48F9-ABCE-B0C3D7714C84}.Release|Any CPU.Build.0 = Release|Any CPU
{E03DC0DF-84CC-420C-91B1-2A937E88FF31}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E03DC0DF-84CC-420C-91B1-2A937E88FF31}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E03DC0DF-84CC-420C-91B1-2A937E88FF31}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E03DC0DF-84CC-420C-91B1-2A937E88FF31}.Release|Any CPU.Build.0 = Release|Any CPU
{332F53A7-E9F4-4A7E-BDAC-E490F3A6935A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{332F53A7-E9F4-4A7E-BDAC-E490F3A6935A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{332F53A7-E9F4-4A7E-BDAC-E490F3A6935A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{332F53A7-E9F4-4A7E-BDAC-E490F3A6935A}.Release|Any CPU.Build.0 = Release|Any CPU
{55EE08BA-C5E5-40C5-A667-B91D88DABD0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55EE08BA-C5E5-40C5-A667-B91D88DABD0D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55EE08BA-C5E5-40C5-A667-B91D88DABD0D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55EE08BA-C5E5-40C5-A667-B91D88DABD0D}.Release|Any CPU.Build.0 = Release|Any CPU
{417057CF-9FBD-4732-BE9D-42875EBA61C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{417057CF-9FBD-4732-BE9D-42875EBA61C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{417057CF-9FBD-4732-BE9D-42875EBA61C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{417057CF-9FBD-4732-BE9D-42875EBA61C9}.Release|Any CPU.Build.0 = Release|Any CPU
{6F655D35-3867-4351-8929-23B4578E5190}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6F655D35-3867-4351-8929-23B4578E5190}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6F655D35-3867-4351-8929-23B4578E5190}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6F655D35-3867-4351-8929-23B4578E5190}.Release|Any CPU.Build.0 = Release|Any CPU
{3BBC4FAD-85A1-4451-8975-BC00EAF81E63}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3BBC4FAD-85A1-4451-8975-BC00EAF81E63}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3BBC4FAD-85A1-4451-8975-BC00EAF81E63}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3BBC4FAD-85A1-4451-8975-BC00EAF81E63}.Release|Any CPU.Build.0 = Release|Any CPU
{00D32586-D675-4EF4-B4F3-06DC45BBF079}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00D32586-D675-4EF4-B4F3-06DC45BBF079}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00D32586-D675-4EF4-B4F3-06DC45BBF079}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00D32586-D675-4EF4-B4F3-06DC45BBF079}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal