Compare commits

...

1 Commits

Author SHA1 Message Date
Sebastien Ros
295e5e8785 Adding Multi-Tenant Commands feature 2015-08-07 17:40:47 -07:00
7 changed files with 541 additions and 6 deletions

View File

@@ -1,4 +1,5 @@
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Security;
using Orchard.UI.Navigation;
@@ -24,4 +25,33 @@ namespace Orchard.MultiTenancy {
.Permission(StandardPermissions.SiteOwner)));
}
}
[OrchardFeature("Orchard.MultiTenancy.Commands")]
public class CommandsAdminMenu : INavigationProvider
{
private readonly ShellSettings _shellSettings;
public CommandsAdminMenu(ShellSettings shellSettings)
{
_shellSettings = shellSettings;
}
public Localizer T { get; set; }
public string MenuName
{
get { return "admin"; }
}
public void GetNavigation(NavigationBuilder builder)
{
if (_shellSettings.Name != ShellSettings.DefaultName)
return;
builder.Add(T("Tenants"), "90",
menu => menu.Add(T("Commands"), "1", item => item.Action("Index", "Commands", new { area = "Orchard.MultiTenancy" })
.Permission(StandardPermissions.SiteOwner)));
}
}
}

View File

@@ -0,0 +1,145 @@
using Orchard.Commands;
using Orchard.Data;
using Orchard.Environment;
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.MultiTenancy.Services;
using Orchard.MultiTenancy.ViewModels;
using Orchard.Security;
using Orchard.Themes;
using Orchard.Tokens;
using Orchard.UI.Admin;
using Orchard.UI.Notify;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
namespace Orchard.MultiTenancy.Controllers
{
[Themed, Admin, OrchardFeature("Orchard.MultiTenancy.Commands")]
public class CommandsController : Controller
{
private readonly ITenantService _tenantService;
private readonly IOrchardHost _orchardHost;
private readonly ShellSettings _shellSettings;
public CommandsController(
IOrchardServices services,
ITenantService tenantService,
IOrchardHost orchardHost,
ShellSettings shellSettings)
{
_tenantService = tenantService;
_orchardHost = orchardHost;
_shellSettings = shellSettings;
Services = services;
T = NullLocalizer.Instance;
Logger = NullLogger.Instance;
}
public IOrchardServices Services { get; set; }
public Localizer T { get; set; }
public ILogger Logger { get; set; }
public ActionResult Index()
{
return Execute();
}
public ActionResult Execute()
{
if (!Services.Authorizer.Authorize(StandardPermissions.SiteOwner))
{
return new HttpUnauthorizedResult();
}
if (!EnsureDefaultTenant())
return new HttpUnauthorizedResult();
return View("Execute", new CommandsExecuteViewModel
{
Tenants= _tenantService.GetTenants()
.Where(x => x.State == Environment.Configuration.TenantState.Running)
.Select(x => x.Name)
});
}
[HttpPost]
public ActionResult Execute(string tenant, string commandLine)
{
if(!Services.Authorizer.Authorize(StandardPermissions.SiteOwner))
{
return new HttpUnauthorizedResult();
}
if (!EnsureDefaultTenant())
return new HttpUnauthorizedResult();
string output = "";
var shellContext = _orchardHost.GetShellContext(tenant);
if(shellContext == null)
{
return Json(new
{
error = T("Tenant not found: {0}", tenant).Text,
});
}
if (shellContext.Settings.State != TenantState.Running)
{
return Json(new
{
error = T("Tenant not running: {0}", tenant).Text,
});
}
using (var workContext = shellContext.LifetimeScope.CreateWorkContextScope())
{
var commandManager = workContext.Resolve<ICommandManager>();
var transactionManager = workContext.Resolve<ITransactionManager>();
var tokenizer = workContext.Resolve<ITokenizer>();
try
{
using (var writer = new StringWriter())
{
commandLine = tokenizer.Replace(commandLine, new Dictionary<string, object>());
var parameters = CommandParser.ParseCommandParameters(commandLine);
parameters.Output = writer;
commandManager.Execute(parameters);
output = writer.ToString();
}
return Json(new
{
data = output
});
}
catch (Exception exception)
{
Logger.Error(T("Error executing command for tenant {0}: {1}", tenant, exception.Message).Text);
transactionManager.Cancel();
return Json(new
{
error = exception.Message,
data = output
});
}
}
}
private bool EnsureDefaultTenant()
{
return _shellSettings.Name == ShellSettings.DefaultName;
}
}
}

View File

@@ -6,6 +6,13 @@ Website: http://orchardproject.net
Version: 1.9.1
OrchardVersion: 1.9
Description: The multi-tenancy module enables multiple Orchard sites to run in isolation inside of a single web application, improving site density on a single server or hosted account.
FeatureDescription: Configure multiple site tenants.
Category: Hosting
Dependencies: Orchard.jQuery
Features:
Orchard.MultiTenancy:
FeatureDescription: Configure multiple site tenants.
Category: Hosting
Dependencies: Orchard.jQuery
Orchard.MultiTenancy.Commands:
Name: Multi Tenancy Commands
FeatureDescription: Run commands on tenants.
Category: Hosting
Dependencies: Orchard.Tokens

View File

@@ -25,6 +25,7 @@
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -48,6 +49,13 @@
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Autofac">
<HintPath>..\..\..\..\lib\autofac\Autofac.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
@@ -59,22 +67,45 @@
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Entity" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\lib\aspnetmvc\System.Web.Mvc.dll</HintPath>
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="AdminMenu.cs" />
<Compile Include="Annotations\SqlDatabaseConnectionStringAttribute.cs" />
<Compile Include="Controllers\CommandsController.cs" />
<Compile Include="ResourceManifest.cs" />
<Compile Include="Commands\TenantCommand.cs" />
<Compile Include="Controllers\AdminController.cs" />
<Compile Include="Extensions\UrlHelperExtensions.cs" />
<Compile Include="Routes.cs" />
<Compile Include="Services\CommandParser.cs" />
<Compile Include="Services\ITenantService.cs" />
<Compile Include="Services\TenantService.cs" />
<Compile Include="ViewModels\CommandsExecuteViewModel.cs" />
<Compile Include="ViewModels\ModuleEntry.cs" />
<Compile Include="ViewModels\TenantEditViewModel.cs" />
<Compile Include="ViewModels\TenantAddViewModel.cs" />
@@ -102,6 +133,10 @@
<Name>Orchard.Framework</Name>
<Private>False</Private>
</ProjectReference>
<ProjectReference Include="..\Orchard.Tokens\Orchard.Tokens.csproj">
<Project>{6f759635-13d7-4e94-bcc9-80445d63f117}</Project>
<Name>Orchard.Tokens</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="Content\Web.config">
@@ -123,6 +158,9 @@
</SubType>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="Views\Commands\Execute.cshtml" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>

View File

@@ -0,0 +1,176 @@
using Orchard.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Orchard.MultiTenancy.Services
{
// Utility class for parsing lines of commands.
// Note: This lexer handles double quotes pretty harshly by design.
// In case you needed them in your arguments, hopefully single quotes work for you as a replacement on the receiving end.
public class CommandParser
{
public static CommandParameters ParseCommandParameters(string command)
{
var args = SplitArgs(command);
var arguments = new List<string>();
var result = new CommandParameters
{
Switches = new Dictionary<string, string>()
};
foreach (var arg in args)
{
if (arg.StartsWith("/"))
{
//If arg is not empty and starts with '/'
int index = arg.IndexOf(':');
var switchName = (index < 0 ? arg.Substring(1) : arg.Substring(1, index - 1));
var switchValue = (index < 0 || index >= arg.Length ? string.Empty : arg.Substring(index + 1));
if (string.IsNullOrEmpty(switchName))
{
throw new ArgumentException(string.Format("Invalid switch syntax: \"{0}\". Valid syntax is /<switchName>[:<switchValue>].", arg));
}
result.Switches.Add(switchName, switchValue);
}
else
{
arguments.Add(arg);
}
}
result.Arguments = arguments;
return result;
}
class State
{
private readonly string _commandLine;
private readonly StringBuilder _stringBuilder;
private readonly List<string> _arguments;
private int _index;
public State(string commandLine)
{
_commandLine = commandLine;
_stringBuilder = new StringBuilder();
_arguments = new List<string>();
}
public StringBuilder StringBuilder { get { return _stringBuilder; } }
public bool EOF { get { return _index >= _commandLine.Length; } }
public char Current { get { return _commandLine[_index]; } }
public IEnumerable<string> Arguments { get { return _arguments; } }
public void AddArgument()
{
_arguments.Add(StringBuilder.ToString());
StringBuilder.Clear();
}
public void AppendCurrent()
{
StringBuilder.Append(Current);
}
public void Append(char ch)
{
StringBuilder.Append(ch);
}
public void MoveNext()
{
if (!EOF)
_index++;
}
}
/// <summary>
/// Implement the same logic as found at
/// http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
/// The 3 special characters are quote, backslash and whitespaces, in order
/// of priority.
/// The semantics of a quote is: whatever the state of the lexer, copy
/// all characters verbatim until the next quote or EOF.
/// The semantics of backslash is: If the next character is a backslash or a quote,
/// copy the next character. Otherwise, copy the backslash and the next character.
/// The semantics of whitespace is: end the current argument and move on to the next one.
/// </summary>
private static IEnumerable<string> SplitArgs(string commandLine)
{
var state = new State(commandLine);
while (!state.EOF)
{
switch (state.Current)
{
case '"':
ProcessQuote(state);
break;
case '\\':
ProcessBackslash(state);
break;
case ' ':
case '\t':
if (state.StringBuilder.Length > 0)
state.AddArgument();
state.MoveNext();
break;
default:
state.AppendCurrent();
state.MoveNext();
break;
}
}
if (state.StringBuilder.Length > 0)
state.AddArgument();
return state.Arguments;
}
private static void ProcessQuote(State state)
{
state.MoveNext();
while (!state.EOF)
{
if (state.Current == '"')
{
state.MoveNext();
break;
}
state.AppendCurrent();
state.MoveNext();
}
state.AddArgument();
}
private static void ProcessBackslash(State state)
{
state.MoveNext();
if (state.EOF)
{
state.Append('\\');
return;
}
if (state.Current == '"')
{
state.Append('"');
state.MoveNext();
}
else
{
state.Append('\\');
state.AppendCurrent();
state.MoveNext();
}
}
}
}

View File

@@ -0,0 +1,8 @@
using System.Collections.Generic;
namespace Orchard.MultiTenancy.ViewModels
{
public class CommandsExecuteViewModel {
public IEnumerable<string> Tenants { get; set; }
}
}

View File

@@ -0,0 +1,131 @@
@model Orchard.MultiTenancy.ViewModels.CommandsExecuteViewModel
@{
Script.Require("jQuery").AtFoot();
Script.Include(Url.Content("~/Themes/TheAdmin/Scripts/admin.js")).AtFoot();
}
<h1>
@Html.TitleForPage(T("Command line").ToString())
</h1>
<div>
<fieldset>
<label for="command-line">@T("Command Line")</label>
<input id="command-line" type="text" value="" class="text large"/>
</fieldset>
<fieldset>
<button type="button" id="button-run" class="button">@T("Run")</button>
<button type="button" id="button-cancel" class="button" style="display: none">@T("Cancel")</button>
<div class="message message-Warning" id="message-progress" style="display: none"></div>
</fieldset>
<div class="tenants">
@foreach(var tenant in Model.Tenants) {
<fieldset class="tenant" id="tenant-@tenant" data-tenant="@tenant">
<label>@tenant</label>
<pre class="result"> </pre>
</fieldset>
}
</div>
</div>
@using (Script.Foot()) {
<script type="text/javascript">
$(function() {
var executeCommandUrl = '@HttpUtility.JavaScriptStringEncode(Url.Action("Execute", "Commands"))';
var antiForgeryToken = '@HttpUtility.JavaScriptStringEncode(Html.AntiForgeryTokenValueOrchard().ToString())';
var endMessage = '@HttpUtility.JavaScriptStringEncode(T("All tenants have been processed").Text)';
var cancelMessage = '@HttpUtility.JavaScriptStringEncode(T("Cancellation requested").Text)';
var tenantsRemainingMessage = '@HttpUtility.JavaScriptStringEncode(T("{0} tenants remaining", "{0}").Text)';
var tenants = ['@Html.Raw(String.Join("', '", Model.Tenants.Select(HttpUtility.JavaScriptStringEncode)))'];
var cancel = false;
var isCancelled = function () {
return cancel;
}
$('#button-cancel').click(function () {
cancel = true;
$('#message-progress').text(endMessage);
$('#button-cancel').hide();
});
$('#button-run').click(function () {
cancel =false;
$('#button-cancel').show();
$('#button-run').hide();
var remaining = tenants.length;
$('#message-progress').show();
var deferred = $.Deferred();
var tail = deferred.promise();
tenants.forEach(function (tenant) {
console.log("enlisting");
if (tenant.toLowerCase() == "default") {
return;
}
$('#tenant-' + tenant).find("label").removeClass();
tail = tail.then(function () {
if (isCancelled()) {
console.log("reject");
var t = $.Deferred();
t.reject();
return t.promise();
}
return $.ajax({
type: 'POST',
url: executeCommandUrl,
// async: false,
beforeSend: function (xhr, opts) {
console.log("::send");
var fieldset = $('#tenant-' + tenant);
fieldset.find("label").removeClass().addClass("progress");
},
data: {
__RequestVerificationToken: antiForgeryToken,
tenant: tenant,
commandLine: $('#command-line').val()
},
success: function (result) {
var fieldset = $('#tenant-' + tenant);
if (result.error) {
fieldset.find("label").removeClass().addClass("fail");
fieldset.find("pre").text(result.error);
}
else {
fieldset.find("label").removeClass().addClass("success");
fieldset.find("pre").text(result.data);
}
fieldset.find("label").expandoControl(function (controller) { return controller.nextAll("pre"); }, { collapse: true, remember: false });
remaining--;
}
});
});
});
tail
.fail(function () {
$('#message-progress').text(cancelMessage);
})
.done(function () {
$('#message-progress').text(endMessage);
})
.always(function () {
cancel = false;
$('#button-run').show();
$('#button-cancel').hide();
});
deferred.resolve();
});
});
</script>
}