private void PowerOff(SimReserved simulator) { Thread.CurrentThread.SetName(simulator.AssetId); UpdateItemStatus(simulator, "Checking power status..."); if (VMController.IsPoweredOn(simulator.VirtualMachine)) { if (JediSimulatorManager.IsSimulatorReady(simulator.HostAddress)) { UpdateItemStatus(simulator, "Shutting down simulator..."); JediSimulatorManager.ShutdownSimulator(simulator.VirtualMachine); UpdateItemStatus(simulator, "Simulator Shutdown complete."); } UpdateItemStatus(simulator, "Powering Off VM..."); VMController.Shutdown(simulator.VirtualMachine); UpdateItemStatus(simulator, "Power Off complete."); } else { UpdateItemStatus(simulator, "Already powered off."); } }
public void MinimalApiTest_WithAuthorizeOnUnauthenticatedClient_AccessDenied() { var vmName = "HelloWorldAccessDenied"; var builder = WebApplication.CreateBuilder(); builder.Services.AddDotNetify().AddSignalR(); var app = builder.Build(); app.MapVM(vmName, [Authorize]() => new { FirstName = "Hello", LastName = "World" }); var vm = VMController.CreateVMInstance(vmName); var hubEmulator = new HubEmulatorBuilder() .Register(vmName, vm) .UseFilter <AuthorizeFilter>() .Build(); var identity = Stubber.Create <IIdentity>().Setup(x => x.AuthenticationType).Returns(string.Empty).Object; var client = hubEmulator.CreateClient(user: null); var response = client.Connect(vmName); Assert.IsTrue(response.First().ToString().Contains(nameof(UnauthorizedAccessException))); }
public void MinimalApiTest_WithObservable_ReturnsStatePeriodically() { var vmName = "LiveData"; var builder = WebApplication.CreateBuilder(); builder.Services.AddDotNetify().AddSignalR(); builder.Services.AddScoped <ILiveDataService, LiveDataService>(); var app = builder.Build(); app.MapVM(vmName, (ILiveDataService live) => new { ServerUsage = live.ServerUsage }); var vm = VMController.CreateVMInstance(vmName); var hubEmulator = new HubEmulatorBuilder() .Register(vmName, vm) .Build(); var client = hubEmulator.CreateClient(); client.Connect(vmName); var response = client.Listen(2100); Assert.IsTrue(response.Count >= 3); }
public void Middleware_ResponseIntercepted() { VMController.Register <MiddlewareTestVM>(); var hub = new MockDotNetifyHub() .UseMiddleware <ExtractHeadersMiddleware>() .UseMiddleware <JwtBearerAuthenticationMiddleware>() .UseMiddleware <CustomMiddleware3>() .Create(); hub.RequestVM(nameof(MiddlewareTestVM), _vmArg); string responsePropertyValue = null; hub.Response += (sender, e) => { dynamic data = JsonConvert.DeserializeObject <dynamic>(e.Item2); responsePropertyValue = data.ResponseProperty; }; hub.UpdateVM(nameof(MiddlewareTestVM), new Dictionary <string, object> { { "TriggerProperty", true } }); Assert.AreEqual("TRIGGERED", responsePropertyValue); }
public void Filter_ResponseIntercepted() { VMController.Register <FilterTestVM>(); var hub = new MockDotNetifyHub() .UseMiddleware <ExtractHeadersMiddleware>() .UseMiddleware <JwtBearerAuthenticationMiddleware>() .UseFilter <AuthorizeFilter>() .UseFilter <CustomFilter1>() .UseFilter <CustomFilter2>() .Create(); Action filter1Assertions = null; _filter1.Invoked += (sender, tuple) => { if (tuple.Item2.HubContext.CallType != "Response_VM") { return; } var attr = tuple.Item1; var vmContext = tuple.Item2; var context = vmContext.HubContext; var connectionId = context.CallerContext.ConnectionId; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); filter1Assertions = () => { Assert.AreEqual(hub.ConnectionId, connectionId); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); Assert.AreEqual(_vm, vmContext.Instance); Assert.AreEqual("Welcome", attr.Property); }; }; Action filter2Assertions = null; _filter2.Invoked += (sender, tuple) => { if (tuple.Item2.HubContext.CallType != "Response_VM") { return; } var attr = tuple.Item1; var vmContext = tuple.Item2; var context = vmContext.HubContext; var connectionId = context.CallerContext.ConnectionId; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); filter2Assertions = () => { Assert.AreEqual(hub.ConnectionId, connectionId); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); Assert.AreEqual(_vm, vmContext.Instance); Assert.AreEqual("Bienvenu", attr.Property); }; }; hub.RequestVM(nameof(FilterTestVM), _vmArg); hub.UpdateVM(nameof(FilterTestVM), new Dictionary <string, object> { { "TriggerProperty", true } }); filter1Assertions(); filter2Assertions(); }
public void Filter_RequestIntercepted() { VMController.Register <FilterTestVM>(); var hub = new MockDotNetifyHub() .UseMiddleware <ExtractHeadersMiddleware>() .UseMiddleware <JwtBearerAuthenticationMiddleware>() .UseFilter <AuthorizeFilter>() .UseFilter <CustomFilter1>() .UseFilter <CustomFilter2>() .Create(); string vmName = null; dynamic vmData = null; hub.Response += (sender, e) => { vmName = e.Item1; vmData = JsonConvert.DeserializeObject <dynamic>(e.Item2); }; Action filter1Assertions = null; _filter1.Invoked += (sender, tuple) => { var attr = tuple.Item1; var vmContext = tuple.Item2; var context = vmContext.HubContext; var callType = context.CallType; var connectionId = context.CallerContext.ConnectionId; var testVMPropValue = (context.Data as JObject)[nameof(FilterTestVM.Property)]; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); filter1Assertions = () => { Assert.AreEqual("Request_VM", callType); Assert.AreEqual(hub.ConnectionId, connectionId); Assert.AreEqual("World", testVMPropValue); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); Assert.AreEqual(_vm, vmContext.Instance); Assert.AreEqual("Welcome", attr.Property); }; }; Action filter2Assertions = null; _filter2.Invoked += (sender, tuple) => { var attr = tuple.Item1; var vmContext = tuple.Item2; var context = vmContext.HubContext; var callType = context.CallType; var connectionId = context.CallerContext.ConnectionId; var testVMPropValue = (context.Data as JObject)[nameof(FilterTestVM.Property)]; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); filter2Assertions = () => { Assert.AreEqual("Request_VM", callType); Assert.AreEqual(hub.ConnectionId, connectionId); Assert.AreEqual("World", testVMPropValue); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); Assert.AreEqual(_vm, vmContext.Instance); Assert.AreEqual("Bienvenu", attr.Property); }; }; hub.RequestVM(nameof(FilterTestVM), _vmArg); Assert.AreEqual(nameof(FilterTestVM), vmName); Assert.AreEqual("World", vmData.Property.ToString()); filter1Assertions(); filter2Assertions(); }
public static void Initialize(TestContext testContext) { VMController.RegisterAssembly <BaseVM>(typeof(ControlTypesVM).Assembly); }
/// <summary> /// Powers off this instance. /// </summary> public void PowerOff() { VMController.PowerOff(Name); }
/// <summary> /// Reverts a VM to it's last snapshot. /// </summary> public void Revert(bool wait = false) { VMController.Revert(Name, wait); }
public async Task <string> Update_VM( string vmId, [FromQuery] string vmArg, [FromBody] Dictionary <string, object> vmData, [FromServices] IVMFactory vmFactory, [FromServices] IHubServiceProvider hubServiceProvider, [FromServices] IVMServiceScopeFactory serviceScopeFactory, [FromServices] IHubPipeline hubPipeline, [FromServices] IPrincipalAccessor principalAccessor) { var taskCompletionSource1 = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); var taskCompletionSource2 = new TaskCompletionSource <string>(TaskCreationOptions.RunContinuationsAsynchronously); Task responseVM(string arg1, string arg2, string arg3) { if (!taskCompletionSource1.TrySetResult(arg3)) { taskCompletionSource2.TrySetResult(arg3); } return(Task.CompletedTask); } var vmController = new VMController(responseVM, vmFactory, serviceScopeFactory.CreateScope()) { ResponseVMFilter = CreateRespondingVMFilter(hubPipeline, vmId, vmData) }; var httpCallerContext = InitializeContext(vmController, hubServiceProvider, principalAccessor); var connectionId = httpCallerContext.ConnectionId; try { var hubContext = new DotNetifyHubContext(httpCallerContext, nameof(Request_VM), vmId, vmArg, BuildHeaders(), httpCallerContext.User); vmController.RequestVMFilter = CreateVMFilter(hubContext, hubPipeline); await hubPipeline.RunMiddlewaresAsync(hubContext, async ctx => { await vmController.OnRequestVMAsync(connectionId, ctx.VMId, ctx.Data); }); } catch (Exception ex) { var finalEx = await hubPipeline.RunExceptionMiddlewareAsync(httpCallerContext, ex); if (finalEx is OperationCanceledException == false) { taskCompletionSource1.TrySetResult(DotNetifyHub.SerializeException(finalEx)); } } await taskCompletionSource1.Task; try { var hubContext = new DotNetifyHubContext(httpCallerContext, nameof(Update_VM), vmId, vmData, BuildHeaders(), httpCallerContext.User); vmController.UpdateVMFilter = CreateVMFilter(hubContext, hubPipeline); await hubPipeline.RunMiddlewaresAsync(hubContext, async ctx => { await vmController.OnUpdateVMAsync(connectionId, ctx.VMId, ctx.Data as Dictionary <string, object>); vmController.Dispose(); }); } catch (Exception ex) { var finalEx = await hubPipeline.RunExceptionMiddlewareAsync(httpCallerContext, ex); if (finalEx is OperationCanceledException == false) { taskCompletionSource2.TrySetResult(DotNetifyHub.SerializeException(finalEx)); } } return(await taskCompletionSource2.Task); }
/// <summary> /// Performs a guest shutdown on a VM. /// </summary> /// <param name="wait">if set to <c>true</c> [wait until powered off].</param> public void Shutdown(bool wait = true) { VMController.Shutdown(Name, wait); }
public void Middleware_RequestIntercepted() { VMController.Register <MiddlewareTestVM>(); var hub = new MockDotNetifyHub() .UseMiddleware <ExtractHeadersMiddleware>() .UseMiddleware <JwtBearerAuthenticationMiddleware>() .UseMiddleware <CustomMiddleware1>() .UseMiddleware <CustomMiddleware2>() .Create(); string vmName = null; dynamic vmData = null; hub.Response += (sender, e) => { vmName = e.Item1; vmData = JsonConvert.DeserializeObject <dynamic>(e.Item2); }; Action middleware1Assertions = null; _middleware1.Invoked += (sender, context) => { if (middleware1Assertions != null) { return; } var callType = context.CallType; var connectionId = context.CallerContext.ConnectionId; var testVMPropValue = (context.Data as JObject)[nameof(MiddlewareTestVM.Property)]; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); middleware1Assertions = () => { Assert.AreEqual("Request_VM", callType); Assert.AreEqual(hub.ConnectionId, connectionId); Assert.AreEqual("World", testVMPropValue); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); }; }; Action middleware2Assertions = null; _middleware2.Invoked += (sender, context) => { if (middleware2Assertions != null) { return; } var callType = context.CallType; var connectionId = context.CallerContext.ConnectionId; var testVMPropValue = (context.Data as JObject)[nameof(MiddlewareTestVM.Property)]; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); middleware2Assertions = () => { Assert.AreEqual("Request_VM", callType); Assert.AreEqual(hub.ConnectionId, connectionId); Assert.AreEqual("World", testVMPropValue); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(1, pipelineData.Count); }; }; hub.RequestVM(nameof(MiddlewareTestVM), _vmArg); Assert.AreEqual(nameof(MiddlewareTestVM), vmName); Assert.AreEqual("World", vmData.Property.ToString()); middleware1Assertions(); middleware2Assertions(); }
private string GetInitialState(string vm) => vm == null ? null : $@" window.vmStates = window.vmStates || {{}}; window.vmStates['{vm}'] = {VMController.GetInitialState(vm) ?? "{}"};";
private void StartSimulatorHandler() { bool alreadyRetried = false; TraceFactory.Logger.Debug("Starting simulator {0}".FormatWith(_machine.Name)); while (true) { try { if (_machine.IsPoweredOn()) { // The machine is already powered on, see if the simulator is responsive // and handle accordingly. TraceFactory.Logger.Debug("{0} is already powered on...".FormatWith(_machine.Name)); if (JediSimulatorManager.IsSimulatorReady(_machine.Name)) { // The simulator is on and ready to go, just return return; } else { // Since the machine is running, but the simulator doesn't respond // attempt to stop the simulator try { // Attempt to shutdown the simulator. If this fails then log it and continue TraceFactory.Logger.Debug("Attempting to shutdown the simulator"); JediSimulatorManager.ShutdownSimulator(_machine.Name); } catch (Exception ex) { TraceFactory.Logger.Debug("Simulator shutdown failed, error: {0}".FormatWith(ex.Message)); } } } else { // The machine isn't on, so boot it and then try to start the simulator. try { MachineStart.Run(_machine.Name, () => { TraceFactory.Logger.Debug("Booting {0}".FormatWith(_machine.Name)); MapElement.UpdateStatus("Booting"); // Don't track "In Use" for simulator VMs, they are already handled through // asset reservation. _machine.PowerOn(setInUse: false); }); } catch (Exception ex) { TraceFactory.Logger.Error("Error booting virtual machine", ex); MapElement.UpdateStatus("Error booting VM", RuntimeState.Error); return; } MapElement.UpdateStatus("ReadyWait"); if (!VMController.WaitOnMachineAvailable(_machine.Name, _cancel.Token)) { TraceFactory.Logger.Debug("Cancellation request received, returning..."); throw new OperationCanceledException("Cancellation received"); } } // Now the machine should be booted and ready to start the simulator. MapElement.UpdateStatus("Starting"); JediSimulatorManager.LaunchSimulator(_machine.Name, ((JediSimulatorDetail)Asset).Product, _machine.Name, _cancel.Token); return; } catch (Exception ex) { // If an exception is hit trying to start on the first attempt, then try one // more time after first shutting down the machine. TraceFactory.Logger.Debug("Error starting simulator on {0}".FormatWith(_machine.Name)); if (alreadyRetried) { MapElement.UpdateStatus("Unable to start this simulator: {0}".FormatWith(ex.Message), RuntimeState.Error); throw new OperationCanceledException("Cancellation received"); } else { // Unable to start the simulator, so perform a hard restart and try one more time. _machine.Shutdown(); alreadyRetried = true; } } } }
private string BuildStateString(string vm) => $"window.vmStates = window.vmStates || {{}}; window.vmStates['{vm}'] = {VMController.GetInitialState(vm) ?? "{}"};";
/// <summary> /// Is a VM powered on. /// </summary> /// <returns>True if it's powered on.</returns> public bool IsPoweredOn() { return(VMController.IsPoweredOn(Name)); }
static VMControllerTest() { VMController.RegisterAssembly <BaseVM>(typeof(UnitTestVM).Assembly); }
public void Middleware_DisposeIntercepted() { VMController.Register <MiddlewareTestVM>(); var hub = new MockDotNetifyHub() .UseMiddleware <ExtractHeadersMiddleware>() .UseMiddleware <JwtBearerAuthenticationMiddleware>() .UseMiddleware <CustomMiddleware1>() .UseMiddleware <CustomMiddleware2>() .Create(); Action middleware1Assertions = null; _middleware1.Invoked += (sender, context) => { if (context.CallType != "Dispose_VM") { return; } var connectionId = context.CallerContext.ConnectionId; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); middleware1Assertions = () => { Assert.AreEqual(hub.ConnectionId, connectionId); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(0, pipelineData.Count); }; }; Action middleware2Assertions = null; _middleware2.Invoked += (sender, context) => { if (context.CallType != "Dispose_VM") { return; } var connectionId = context.CallerContext.ConnectionId; var authToken = (context.Headers as JObject)["Authorization"].ToString(); var principalName = context.Principal.Identity.Name; var pipelineData = new Dictionary <string, object>(context.PipelineData); middleware2Assertions = () => { Assert.AreEqual(hub.ConnectionId, connectionId); Assert.IsTrue(authToken.StartsWith("Bearer ")); Assert.AreEqual("admin", principalName); Assert.AreEqual(1, pipelineData.Count); }; }; hub.RequestVM(nameof(MiddlewareTestVM), _vmArg); hub.DisposeVM(nameof(MiddlewareTestVM)); middleware1Assertions(); middleware2Assertions(); }
public void Initialize() { VMController.Register <MasterVM>(); VMController.Register <DetailsVM>(); }
/// <summary> /// Creates the view model for a widget. /// </summary> public BaseVM CreateWidgetVM(string iWidgetTypeName, string iWidgetId) { var widgetType = GetType().GetTypeInfo().Assembly.GetExportedTypes().FirstOrDefault(i => i.Name == iWidgetTypeName); return(VMController.CreateInstance(widgetType, new object[] { iWidgetId }) as BaseVM); }