/// <summary>
        /// Creates the DI container for the application.
        /// </summary>
        /// <param name="storageDirectory">The directory that will contain the files for the current set of tests.</param>
        /// <param name="hostId">The endpoint ID of the host application.</param>
        /// <returns>The DI container.</returns>
        public static IContainer CreateContainer(string storageDirectory, EndpointId hostId)
        {
            var builder = new ContainerBuilder();
            {
                builder.RegisterModule(new UtilitiesModule());
                builder.RegisterModule(
                    new CommunicationModule(
                        new List<CommunicationSubject>
                            {
                                CommunicationSubjects.TestExecution,
                            },
                        new List<ChannelType>
                            {
                                ChannelType.NamedPipe,
                            },
                        false));

                builder.Register(
                        c =>
                        {
                            var ctx = c.Resolve<IComponentContext>();
                            return BuildReportFileUploader(ctx, storageDirectory, hostId);
                        })
                    .SingleInstance();

                RegisterFileSystem(builder);
                RegisterCore(builder, storageDirectory);
                RegisterCommands(builder);
                RegisterNotifications(builder);
                RegisterTestStepProcessors(builder);
            }

            return builder.Build();
        }
        private static UploadReportFilesForTestStep BuildReportFileUploader(IComponentContext context, string storageDirectory, EndpointId hostId)
        {
            UploadReportFilesForTestStep uploader =
                (stepIndex, filesToUpload) =>
                {
                    if (filesToUpload.Count == 0)
                    {
                        return;
                    }

                    var path = Path.Combine(
                        storageDirectory,
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "TestStepReport-{0}.zip",
                            stepIndex));
                    var package = new TestStepPackage(stepIndex);
                    foreach (var pair in filesToUpload)
                    {
                        var filePath = pair.Key.FullName;
                        var baseDirectory = pair.Value.FullName;

                        var relativePath = filePath.Substring(baseDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
                        package.Add(filePath, relativePath);
                    }

                    package.PackTo(path);

                    var uploads = context.Resolve<IStoreUploads>();
                    var token = uploads.Register(path);

                    var hub = context.Resolve<ISendCommandsToRemoteEndpoints>();
                    if (!hub.HasCommandFor(hostId, typeof(ITransferTestReportDataCommands)))
                    {
                        throw new MissingCommandSetException();
                    }

                    var command = hub.CommandsFor<ITransferTestReportDataCommands>(hostId);

                    var id = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
                    Action toExecute =
                        () =>
                        {
                            var task = command.PrepareReportFilesForTransfer(
                                stepIndex,
                                id,
                                token);
                            task.Wait();
                        };
                    CommandSetGuard.GuardAgainstCommunicationFailure(toExecute);
                };

            return uploader;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PluginLoadingAssemblyResolver"/> class.
        /// </summary>
        /// <param name="hostCommands">The object that provides the commands registered with the application.</param>
        /// <param name="layer">The object that handles the communication with the remote host.</param>
        /// <param name="fileSystem">The object that virtualizes the file system.</param>
        /// <param name="hostId">The ID of the host endpoint.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="hostCommands"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="layer"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="hostId"/> is <see langword="null" />.
        /// </exception>
        public PluginLoadingAssemblyResolver(
            ISendCommandsToRemoteEndpoints hostCommands,
            DownloadDataFromRemoteEndpoints layer,
            IFileSystem fileSystem,
            EndpointId hostId)
        {
            {
                Lokad.Enforce.Argument(() => hostCommands);
                Lokad.Enforce.Argument(() => layer);
                Lokad.Enforce.Argument(() => fileSystem);
                Lokad.Enforce.Argument(() => hostId);
            }

            m_HostCommands = hostCommands;
            m_Layer = layer;
            m_FileSystem = fileSystem;
            m_HostId = hostId;
        }
        public void LocatePluginAssembly()
        {
            var token = new UploadToken();
            var commands = new Mock<IHostApplicationCommands>();
            {
                commands.Setup(c => c.PreparePluginContainerForTransfer(It.IsAny<AssemblyName>()))
                    .Returns(Task<UploadToken>.Factory.StartNew(() => token));
            }

            var commandContainer = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandContainer.Setup(c => c.CommandsFor<IHostApplicationCommands>(It.IsAny<EndpointId>()))
                    .Returns(commands.Object);
            }

            DownloadDataFromRemoteEndpoints layer = (id, u, file) =>
            {
                Assert.AreSame(token, u);
                return Task<FileInfo>.Factory.StartNew(() => new FileInfo(file));
            };

            var fileSystem = new Mock<IFileSystem>();
            {
                fileSystem.Setup(f => f.Path)
                    .Returns(new MockPath());
                fileSystem.Setup(f => f.File)
                    .Returns(new MockFile(new Dictionary<string, string>()));
            }

            var endpoint = new EndpointId("a");
            var resolver = new PluginLoadingAssemblyResolver(
                commandContainer.Object,
                layer,
                fileSystem.Object,
                endpoint);
            Assert.AreEqual(
                Assembly.GetExecutingAssembly(),
                resolver.LocatePluginAssembly(new object(), new ResolveEventArgs(Assembly.GetExecutingAssembly().GetName().FullName)));
        }
示例#5
0
 public static void RaiseStaticEvent(Func <IMyEventOwner, Action> action, EndpointId targetEndpoint = new EndpointId(), Vector3D?position = new Vector3D?())
 {
     ReplicationLayer.RaiseEvent <IMyEventOwner, IMyEventOwner>(null, null, action, targetEndpoint, position);
 }
 public DomainBusConfigurationException(EndpointId id):base("Endpoint {0} is already registered".ToFormat(id))
 {
     
 }
示例#7
0
        public static void RaiseEvent <T1, T2, T3>(T1 arg1, Func <T1, Action <T2, T3> > action, T2 arg2, T3 arg3, EndpointId targetEndpoint = new EndpointId()) where T1 : IMyEventOwner
        {
            Vector3D?position = null;

            ReplicationLayer.RaiseEvent <T1, T2, T3, IMyEventOwner>(arg1, null, action, arg2, arg3, targetEndpoint, position);
        }
        private void StartNewTestExecution(
            int testId,
            List<TestStep> testSteps,
            List<InputParameter> environmentParameters,
            EndpointId callingEndpoint,
            UploadToken token)
        {
            var builder = m_SectionBuilders(Resources.ReportSection_Group_Name_Initialization);
            builder.Initialize(Resources.ReportSection_Name_Initialization);

            m_HostInformation.Id = callingEndpoint;

            string testFile;
            if (!DownloadTestData(callingEndpoint, token, m_StorageDirectory, builder, out testFile))
            {
                return;
            }

            m_TestInformation.TestId = testId;
            m_TestInformation.TestSteps = testSteps;
            m_TestInformation.TestPackage = testFile;
            m_TestInformation.EnvironmentParameters = environmentParameters;

            try
            {
                var pair = m_Layer.LocalConnectionFor(ChannelType.NamedPipe);
                m_CurrentEndpoint = StartExecutorApplication(pair.Item1, pair.Item2);

                m_TestInformation.CurrentState = TestExecutionState.Running;
                m_Diagnostics.Log(
                    LevelToLog.Debug,
                    ExecutorServiceConstants.LogPrefix,
                    Resources.Log_Messages_StartedTestApplication);
            }
            catch (Exception e)
            {
                m_TestInformation.CurrentState = TestExecutionState.None;

                m_Diagnostics.Log(
                    LevelToLog.Error,
                    ExecutorServiceConstants.LogPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.Log_Messages_FailedToStartTestApplication_WithError,
                        e));

                builder.AddErrorMessage(Resources.ReportSection_Error_FailedToStartTestingApplication);
                builder.FinalizeAndStore(false);
                m_TestExecutionEvents.RaiseOnTestCompletion(TestExecutionResult.Failed);
                return;
            }

            builder.AddInformationMessage(
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.ReportSection_Info_StartedTestApplication_WithId,
                    m_CurrentEndpoint));

            try
            {
                WaitForExecutorConnection(m_CurrentEndpoint);
            }
            catch (TestExecutionFailureException)
            {
                m_TestInformation.CurrentState = TestExecutionState.None;

                m_Diagnostics.Log(
                    LevelToLog.Error,
                    ExecutorServiceConstants.LogPrefix,
                    Resources.Log_Messages_FailedToConnectToTestApplication_WithError);

                builder.AddErrorMessage(Resources.ReportSection_Error_FailedToConnectToTestingApplication);
                builder.FinalizeAndStore(false);
                m_TestExecutionEvents.RaiseOnTestCompletion(TestExecutionResult.Failed);
                return;
            }

            ConnectEvents(m_CurrentEndpoint);
            builder.FinalizeAndStore(true);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandInvokedResponseMessage"/> class.
 /// </summary>
 /// <param name="origin">The endpoint that send the original message.</param>
 /// <param name="inResponseTo">The ID number of the message to which the current message is a response.</param>
 /// <param name="result">The result from the <see cref="ICommandSet"/> method that was invoked.</param>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="origin"/> is <see langword="null" />.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="inResponseTo"/> is <see langword="null" />.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="result"/> is <see langword="null" />.
 /// </exception>
 public CommandInvokedResponseMessage(EndpointId origin, MessageId inResponseTo, object result)
     : this(origin, new MessageId(), inResponseTo, result)
 {
 }
示例#10
0
        private static void DownloadTestData(
            EndpointId hostId,
            string storageDirectory,
            IComponentContext container,
            out IEnumerable<TestStep> testSteps,
            out IEnumerable<InputParameter> environmentParameters)
        {
            var diagnostics = container.Resolve<SystemDiagnostics>();
            var commandHub = container.Resolve<ISendCommandsToRemoteEndpoints>();
            var downloader = container.Resolve<DownloadDataFromRemoteEndpoints>();
            var fileSystem = container.Resolve<IFileSystem>();
            var packer = container.Resolve<ITestEnvironmentPackage>();

            diagnostics.Log(
                LevelToLog.Debug,
                ExecutorConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Log_Messages_DownloadingTestDataFromHost_WithHostUrl,
                    hostId));

            // Note that if this fails to get the command then it'll return null. Obviously the next method call will then
            // fail. That's ok, there's nothing we can do about it. Let the exception bubble up the stack and fix it there
            var transferCommands = commandHub.CommandsFor<ITransferTestDataCommands>(hostId);
            if (transferCommands == null)
            {
                throw new MissingCommandSetException();
            }

            var tokenTask = CommandSetGuard.GuardAgainstCommunicationFailure<Task<UploadToken>>(transferCommands.PrepareTestFilesForTransfer);
            var unzipTask = tokenTask.ContinueWith(
                t =>
                {
                    var file = Path.Combine(storageDirectory, fileSystem.Path.GetRandomFileName());

                    var streamTask = downloader(hostId, t.Result, file);
                    streamTask.Wait();

                    diagnostics.Log(
                        LevelToLog.Debug,
                        ExecutorConstants.LogPrefix,
                        string.Format(
                            CultureInfo.InvariantCulture,
                            Resources.Log_Messages_UnpackingTestData_WithSourceAndDestination,
                            streamTask.Result.FullName,
                            storageDirectory));

                    var tempLocation = Path.Combine(storageDirectory, "environment");
                    packer.LoadAndUnpack(streamTask.Result.FullName, tempLocation);
                    foreach (var testPackage in packer.Tests())
                    {
                        testPackage.UnpackTo(Path.Combine(storageDirectory, testPackage.TestStepIndex.ToString()));
                    }
                });

            var testCaseTask = transferCommands.TestCase();
            var parametersTask = transferCommands.EnvironmentParameters();
            Task.WaitAll(unzipTask, testCaseTask, parametersTask);

            diagnostics.Log(
                LevelToLog.Debug,
                ExecutorConstants.LogPrefix,
                Resources.Log_Messages_TestDataTransferredSuccessfully);

            testSteps = testCaseTask.Result;
            environmentParameters = parametersTask.Result;
        }
        private void ConnectEvents(EndpointId endpoint)
        {
            var notifications = m_RemoteNotifications.NotificationsFor<ITestExecutionNotifications>(endpoint);

            EventHandler<TestExecutionProgressEventArgs> progressHandle =
                (s, e) => m_TestExecutionEvents.RaiseOnExecutionProgress(e.SectionName, e.Section);
            notifications.OnExecutionProgress += progressHandle;

            EventHandler<TestExecutionResultEventArgs> completionHandle = null;
            completionHandle =
                (s, e) =>
                {
                    m_TestInformation.CurrentState = TestExecutionState.None;
                    m_TestExecutionEvents.RaiseOnTestCompletion(e.Result);
                    m_CurrentEndpoint = null;
                };
            notifications.OnTestCompletion += completionHandle;
        }
        /// <summary>
        /// Loads the dataset into the dataset application.
        /// </summary>
        /// <param name="ownerId">The ID of the endpoint which requested the load of the dataset.</param>
        /// <param name="token">The token that indicates which file should be uploaded.</param>
        /// <returns>A task that will finish once the dataset is loaded.</returns>
        public Task Load(EndpointId ownerId, UploadToken token)
        {
            // This one is more tricky than you think. We need to return a Task (not a Task<T>), however
            // if we do Task<T>.ContinueWith we get a System.Threading.Tasks.ContinuationTaskFromResultTask<System.IO.Stream>
            // object. When we give that back to the command system it tries to push the stream across the network ... not
            // really what we want.
            //
            // So to fix this we create a task and then inside that task we load the file (via another task) and continue
            // of the nested task. The continuation task is a child of the global task and all is well because the
            // global task doesn't finish until the nested child task is done, and we get a Task object back
            var globalTask = Task.Factory.StartNew(
                () =>
                {
                    var filePath = Path.GetTempFileName();

                    var task = m_DataDownload(ownerId, token, filePath);
                    task.ContinueWith(
                        t =>
                        {
                            using (m_Diagnostics.Profiler.Measure(BaseConstants.TimingGroup, "Loading dataset from file."))
                            {
                                m_LoadAction(new FileInfo(filePath));
                            }
                        },
                        TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);
                });

            return globalTask;
        }
        private void ProcessWrite(int maxBitPosition, ref VRage.Library.Collections.BitStream stream, EndpointId forClient, byte packetId)
        {
            m_streamSize = MyLibraryUtils.GetDivisionCeil(maxBitPosition - stream.BitPosition - HEADER_SIZE - SAFE_VALUE, 8) * 8;
            StreamClientData clientData = m_clientStreamData[forClient.Value];

            if (clientData.FailedIncompletePackets.Count > 0)
            {
                stream.WriteBool(true);
                WriteIncompletePacket(clientData, packetId, ref stream);
                return;
            }

            int  bitsToSend = 0;
            bool incomplete = false;

            if (clientData.ObjectData == null)
            {
                SaveReplicable(clientData);
            }
            else
            {
                incomplete = true;
            }

            clientData.NumParts = (short)MyLibraryUtils.GetDivisionCeil(clientData.ObjectData.Length * 8, m_streamSize);

            bitsToSend = clientData.RemainingBits;

            if (bitsToSend == 0)
            {
                clientData.ForceSend = false;
                clientData.Dirty     = false;

                stream.WriteBool(false);
                return;
            }

            stream.WriteBool(true);
            stream.WriteInt32(clientData.UncompressedSize);

            if (bitsToSend > m_streamSize || incomplete)
            {
                WritePart(ref bitsToSend, clientData, packetId, ref stream);
            }
            else
            {
                WriteWhole(bitsToSend, clientData, packetId, ref stream);
            }

            if (clientData.RemainingBits == 0)
            {
                clientData.Dirty     = false;
                clientData.ForceSend = false;
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectionVerificationResponseMessage"/> class.
 /// </summary>
 /// <param name="origin">The endpoint that send the original message.</param>
 /// <param name="id">The ID of the current message.</param>
 /// <param name="inResponseTo">The ID number of the message to which the current message is a response.</param>
 /// <param name="customData">The custom data for the current message.</param>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="origin"/> is <see langword="null" />.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="inResponseTo"/> is <see langword="null" />.
 /// </exception>
 public ConnectionVerificationResponseMessage(EndpointId origin, MessageId id, MessageId inResponseTo, object customData = null)
     : base(origin, id, inResponseTo)
 {
     ResponseData = customData;
 }
示例#15
0
        /// <summary>
        /// Attaches a new endpoint to the given host.
        /// </summary>
        /// <param name="host">The host to which the endpoint should be attached.</param>
        /// <param name="implementedContract">The contract implemented by the endpoint.</param>
        /// <param name="localEndpoint">The ID of the local endpoint, to be used in the endpoint metadata.</param>
        /// <returns>The newly attached endpoint.</returns>
        public ServiceEndpoint AttachMessageEndpoint(ServiceHost host, Type implementedContract, EndpointId localEndpoint)
        {
            var endpoint = host.AddServiceEndpoint(implementedContract, GenerateMessageBinding(), GenerateNewMessageAddress());

            foreach (var operation in endpoint.Contract.Operations)
            {
                var behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (behavior == null)
                {
                    behavior = new DataContractSerializerOperationBehavior(operation);
                    operation.Behaviors.Add(behavior);
                }

                behavior.DataContractResolver = m_DataContractResolver;
            }

            return(endpoint);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectionVerificationResponseMessage"/> class.
 /// </summary>
 /// <param name="origin">The endpoint that send the original message.</param>
 /// <param name="inResponseTo">The ID number of the message to which the current message is a response.</param>
 /// <param name="customData">The custom data for the current message.</param>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="origin"/> is <see langword="null" />.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="inResponseTo"/> is <see langword="null" />.
 /// </exception>
 public ConnectionVerificationResponseMessage(EndpointId origin, MessageId inResponseTo, object customData = null)
     : this(origin, new MessageId(), inResponseTo, customData)
 {
 }
示例#17
0
文件: Event.cs 项目: S17L/iGP11
 public Event(TData data, EndpointId notificationRecipientId)
 {
     Data = data;
     NotificationRecipientId = notificationRecipientId;
 }
示例#18
0
        protected override void ClientWrite(VRage.Library.Collections.BitStream stream, EndpointId forClient, uint timestamp, int maxBitPosition)
        {
            base.ClientWrite(stream, forClient, timestamp, maxBitPosition);

            stream.Write(Entity.WorldMatrix.Translation);

            MyShipController controller = MySession.Static.ControlledEntity as MyShipController;

            stream.WriteBool(m_grid != null && controller != null);
            if (m_grid != null && controller != null)
            {
                stream.WriteBool(m_grid.IsStatic);
                if (m_grid.IsStatic == false)
                {
                    stream.WriteBool(controller != null);
                    if (controller != null)
                    {
                        stream.WriteInt64(controller.EntityId);

                        Vector2 rotation = controller.RotationIndicator;
                        stream.WriteFloat(rotation.X);
                        stream.WriteFloat(rotation.Y);

                        stream.WriteHalf(controller.RollIndicator);

                        Vector3 position = controller.MoveIndicator;
                        stream.WriteHalf(position.X);
                        stream.WriteHalf(position.Y);
                        stream.WriteHalf(position.Z);

                        Vector3D gridPosition = m_grid.PositionComp.GetPosition();
                        MyGridPhysicsStateGroup.WriteSubgrids(m_grid, stream, ref forClient, timestamp, maxBitPosition, m_lowPositionOrientation, ref gridPosition, ref m_currentSentPosition);
                    }
                }
            }
        }
        /// <summary>
        /// Prepares the report files for upload.
        /// </summary>
        /// <param name="testId">The ID of the test to which the files belong.</param>
        /// <param name="testStepIndex">The index of the test step for which the report files are being uploaded.</param>
        /// <param name="callingEndpoint">The ID of the endpoint that called the method.</param>
        /// <param name="token">The upload token used to register the report files that need to be uploaded.</param>
        /// <returns>An upload token that can be used to download the desired files.</returns>
        public Task PrepareReportFilesForTransfer(int testId, int testStepIndex, EndpointId callingEndpoint, UploadToken token)
        {
            m_Diagnostics.Log(
                LevelToLog.Trace,
                MasterServiceConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Log_Messages_TransferingTestStepReportFiles_WithTestAndTestStep,
                    testId,
                    testStepIndex));

            var downloadDirectory = TestHelpers.StoragePathForReportFiles(testId, m_Configuration, m_FileSystem);
            if (!m_FileSystem.Directory.Exists(downloadDirectory))
            {
                 m_FileSystem.Directory.CreateDirectory(downloadDirectory);
            }

            var fileName = string.Format(
                CultureInfo.InvariantCulture,
                "{0}_{1}.reportfiles",
                testId,
                testStepIndex);
            var filePath = m_FileSystem.Path.Combine(
                downloadDirectory,
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}.zip",
                    fileName));
            var fileStream = m_DataDownload(
                callingEndpoint,
                token,
                filePath);
            var uploadTask = fileStream.ContinueWith(
                file =>
                {
                    try
                    {
                        var testPackage = new TestStepPackage(testStepIndex);

                        var unpackDirectory = Path.Combine(downloadDirectory, fileName);
                        testPackage.LoadAndUnpack(file.Result.FullName, unpackDirectory);

                        var notifications = m_ActiveTests.NotificationsFor(testId);
                        foreach (var notification in notifications)
                        {
                            foreach (var storedFile in testPackage.StoredFiles())
                            {
                                var relativePath = storedFile.FullName.Substring(downloadDirectory.Length).TrimStart(Path.DirectorySeparatorChar);
                                notification.StoreReportFile(storedFile.FullName, relativePath);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        m_Diagnostics.Log(
                            LevelToLog.Error,
                            MasterServiceConstants.LogPrefix,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.Log_Messages_TransferingTestStepReportFilesFailed_WithTestAndTestStepAndError,
                                testId,
                                testStepIndex,
                                e));
                    }
                });

            return uploadTask;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CommandInvokedMessage"/> class.
 /// </summary>
 /// <param name="origin">The endpoint that send the original message.</param>
 /// <param name="methodInvocation">The information about the <see cref="ICommandSet"/> method that was invoked.</param>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="origin"/> is <see langword="null" />.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     Thrown if <paramref name="methodInvocation"/> is <see langword="null" />.
 /// </exception>
 public CommandInvokedMessage(EndpointId origin, CommandInvokedData methodInvocation)
     : this(origin, new MessageId(), methodInvocation)
 {
 }
示例#21
0
        private static TestExecutionResult ExecuteTest(EndpointId hostId, string storageDirectory, IContainer container)
        {
            var diagnostics = container.Resolve<SystemDiagnostics>();
            var notifications = container.Resolve<ITestExecutionNotificationsInvoker>();
            var fileSystem = container.Resolve<IFileSystem>();

            TestExecutionResult testResult;
            try
            {
                CreateStorageDirectory(fileSystem, storageDirectory, diagnostics);
            }
            catch (IOException e)
            {
                diagnostics.Log(
                    LevelToLog.Error,
                    ExecutorConstants.LogPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.Log_Messages_FailedToCreateStorageDirectory_WithDirectoryAndError,
                        storageDirectory,
                        e));

                testResult = TestExecutionResult.Failed;
                notifications.RaiseOnTestCompletion(testResult);
                return testResult;
            }

            IEnumerable<TestStep> testSteps;
            IEnumerable<InputParameter> environmentParameters;
            try
            {
                DownloadTestData(hostId, storageDirectory, container, out testSteps, out environmentParameters);
            }
            catch (Exception)
            {
                testResult = TestExecutionResult.Failed;
                notifications.RaiseOnTestCompletion(testResult);
                return testResult;
            }

            var result = ExecuteTestSteps(container, testSteps, environmentParameters);
            diagnostics.Log(
                LevelToLog.Info,
                ExecutorConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Log_Messages_TestCompleted_WithResult,
                    result));

            return result;
        }
示例#22
0
        public void EnqueueEvent(BitStream stream, NetworkId objectInstance, uint eventId, EndpointId sender)
        {
            int requiredByteSize = stream.ByteLength - stream.BytePosition + 1;

            var e = ObtainEvent();

            e.Stream.ResetWrite();
            e.Stream.WriteBitStream(stream);
            e.Stream.ResetRead();
            e.ObjectInstance = objectInstance;
            e.EventId        = eventId;
            e.Sender         = sender;

            List <BufferedEvent> events;

            if (!m_buffer.TryGetValue(objectInstance, out events))
            {
                events = ObtainList();
                m_buffer.Add(objectInstance, events);
            }
            events.Add(e);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DistributionCalculator"/> class.
 /// </summary>
 public DistributionCalculator()
 {
     m_LocalEndpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
 }
示例#24
0
 /// <summary>
 /// Raises static multiplayer event.
 /// Usage: MyMultiplayer.RaiseStaticEvent(s => MyClass.MyStaticFunction);
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseStaticEvent(Func <IMyEventOwner, Action> action, EndpointId targetEndpoint = default(EndpointId))
 {
     ReplicationLayer.RaiseEvent((IMyEventOwner)null, (IMyEventOwner)null, action, targetEndpoint);
 }
        private string DownloadTestData(EndpointId callingEndpoint, UploadToken token, string storageDirectory)
        {
            var filePath = m_FileSystem.Path.Combine(
                storageDirectory,
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}.zip",
                    Guid.NewGuid().ToString("D")));
            var fileStream = m_DataDownload(callingEndpoint, token, filePath);
            fileStream.Wait();

            return fileStream.Result.FullName;
        }
示例#26
0
 /// <summary>
 /// Raises static multiplayer event.
 /// Usage: MyMultiplayer.RaiseStaticEvent(s => MyClass.MyStaticFunction, arg2, arg3);
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseStaticEvent <T2, T3>(Func <IMyEventOwner, Action <T2, T3> > action, T2 arg2, T3 arg3, EndpointId targetEndpoint = default(EndpointId))
 {
     ReplicationLayer.RaiseEvent((IMyEventOwner)null, (IMyEventOwner)null, action, arg2, arg3, targetEndpoint);
 }
        /// <summary>
        /// Prepares the report files for upload.
        /// </summary>
        /// <param name="testStepIndex">The index of the test step for which the report files are being uploaded.</param>
        /// <param name="callingEndpoint">The ID of the endpoint that called the method.</param>
        /// <param name="token">The upload token used to register the report files that need to be uploaded.</param>
        /// <returns>An upload token that can be used to download the desired files.</returns>
        public Task PrepareReportFilesForTransfer(int testStepIndex, EndpointId callingEndpoint, UploadToken token)
        {
            m_Diagnostics.Log(
                LevelToLog.Trace,
                ExecutorServiceConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.Log_Messages_TransferingTestStepReportFiles_WithTestStep,
                    testStepIndex));

            var filePath = m_FileSystem.Path.Combine(
                m_StorageDirectory,
                string.Format(
                    CultureInfo.InvariantCulture,
                    "{0}.zip",
                    Guid.NewGuid().ToString("D")));
            var fileStream = m_DataDownload(callingEndpoint, token, filePath);
            var uploadTask = fileStream.ContinueWith(
                file =>
                {
                    try
                    {
                        // Upload to the host here
                        var hostToken = m_Uploads.Register(file.Result.FullName);
                        if (!m_RemoteCommands.HasCommandFor(m_HostInformation.Id, typeof(IStoreTestReportDataCommands)))
                        {
                            throw new MissingCommandSetException();
                        }

                        var id = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
                        var command = m_RemoteCommands.CommandsFor<IStoreTestReportDataCommands>(m_HostInformation.Id);
                        var task = CommandSetGuard.GuardAgainstCommunicationFailure(
                            command.PrepareReportFilesForTransfer,
                            m_TestInformation.TestId,
                            testStepIndex,
                            id,
                            hostToken);
                        task.Wait();
                    }
                    catch (Exception e)
                    {
                        m_Diagnostics.Log(
                            LevelToLog.Error,
                            ExecutorServiceConstants.LogPrefix,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.Log_Messages_TransferingTestStepReportFilesFailed_WithException,
                                e));

                        throw;
                    }
                });

            return uploadTask;
        }
示例#28
0
 /// <summary>
 /// Raises static multiplayer event.
 /// Usage: MyMultiplayer.RaiseStaticEvent(s => MyClass.MyStaticFunction, arg2, arg3, arg4, arg5, arg6);
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseStaticEvent <T2, T3, T4, T5, T6, T7>(Func <IMyEventOwner, Action <T2, T3, T4, T5, T6, T7> > action, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, EndpointId targetEndpoint = default(EndpointId))
 {
     ReplicationLayer.RaiseEvent((IMyEventOwner)null, (IMyEventOwner)null, action, arg2, arg3, arg4, arg5, arg6, arg7, targetEndpoint);
 }
        public void ImplementPlan()
        {
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var filePath = @"c:\temp\myfile.txt";
            var storage = new Mock<IPersistenceInformation>();
            {
                storage.Setup(s => s.AsFile())
                    .Returns(new FileInfo(filePath));
            }

            var offlineInfo = CreateOfflineInfo(storage.Object);
            var plan = CreateNewDistributionPlan(new DatasetActivationProposal(), offlineInfo, systemDiagnostics);
            var localDistributor = new Mock<ICalculateDistributionParameters>();

            var datasetEndpoint = new EndpointId("OtherMachine:5678");
            var loader = new Mock<IDatasetActivator>();
            {
                loader.Setup(l => l.ActivateDataset(It.IsAny<EndpointId>(), It.IsAny<ChannelType>(), It.IsAny<Uri>()))
                    .Returns(datasetEndpoint);
            }

            var commands = new Mock<IDatasetApplicationCommands>();
            {
                commands.Setup(c => c.Load(It.IsAny<EndpointId>(), It.IsAny<UploadToken>()))
                    .Returns(
                        Task.Factory.StartNew(
                            () => { },
                            new CancellationToken(),
                            TaskCreationOptions.None,
                            new CurrentThreadTaskScheduler()));
            }

            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandHub.Setup(h => h.HasCommandsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                commandHub.Setup(h => h.HasCommandFor(It.IsAny<EndpointId>(), It.IsAny<Type>()))
                    .Returns(true);
                commandHub.Setup(h => h.CommandsFor<IDatasetApplicationCommands>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(datasetEndpoint, e))
                    .Returns(commands.Object);
            }

            var notifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(n => n.HasNotificationsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(datasetEndpoint, e))
                    .Returns(notifications.Object);
            }

            var communicationLayer = new Mock<ICommunicationLayer>();
            {
                communicationLayer.Setup(s => s.LocalConnectionFor(It.Is<ChannelType>(c => c == ChannelType.NamedPipe)))
                    .Returns(
                        new Tuple<EndpointId, Uri, Uri>(
                            EndpointIdExtensions.CreateEndpointIdForCurrentProcess(),
                            new Uri("net.pipe://localhost/pipe"),
                            new Uri("net.pipe://localhost/pipe/data")));
            }

            var uploads = new Mock<IStoreUploads>();

            var distributor = new LocalDatasetDistributor(
                localDistributor.Object,
                loader.Object,
                commandHub.Object,
                notificationHub.Object,
                uploads.Object,
                (d, e, n) =>
                {
                    return new DatasetOnlineInformation(
                        d,
                        e,
                        n,
                        commandHub.Object,
                        notificationHub.Object,
                        systemDiagnostics);
                },
                communicationLayer.Object,
                systemDiagnostics,
                new CurrentThreadTaskScheduler());

            Action<int, string, bool> progress = (p, m, e) => { };
            var result = distributor.ImplementPlan(plan, new CancellationToken(), progress);
            result.Wait();

            Assert.AreSame(datasetEndpoint, result.Result.Endpoint);
            Assert.AreSame(plan.DistributionFor.Id, result.Result.Id);
            Assert.AreSame(plan.MachineToDistributeTo, result.Result.RunsOn);
        }
示例#30
0
 /// <summary>
 /// Raises blocking multiplayer event.
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseBlockingEvent <T1, T2>(T1 arg1, T2 arg2, Func <T1, Action> action, EndpointId targetEndpoint = default(EndpointId))
     where T1 : IMyEventOwner
     where T2 : IMyEventOwner
 {
     ReplicationLayer.RaiseEvent(arg1, arg2, action, targetEndpoint);
 }
示例#31
0
 protected override bool HasProxyFor(EndpointId endpoint)
 {
     return(m_RemoteNotifications.ContainsKey(endpoint));
 }
示例#32
0
 /// <summary>
 /// Raises multiplayer event.
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseEvent <T1, T2>(T1 arg1, Func <T1, Action <T2> > action, T2 arg2, EndpointId targetEndpoint = default(EndpointId))
     where T1 : IMyEventOwner
 {
     ReplicationLayer.RaiseEvent(arg1, (IMyEventOwner)null, action, arg2, targetEndpoint);
 }
示例#33
0
        public static void RaiseEvent <T1, T2, T3, T4, T5, T6, T7>(T1 arg1, Func <T1, Action <T2, T3, T4, T5, T6, T7> > action, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, EndpointId targetEndpoint = new EndpointId()) where T1 : IMyEventOwner
        {
            Vector3D?position = null;

            ReplicationLayer.RaiseEvent <T1, T2, T3, T4, T5, T6, T7, IMyEventOwner>(arg1, null, action, arg2, arg3, arg4, arg5, arg6, arg7, targetEndpoint, position);
        }
示例#34
0
 /// <summary>
 /// Raises blocking multiplayer event.
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseBlockingEvent <T1, T2, T3, T4, T5>(T1 arg1, T5 arg5, Func <T1, Action <T2, T3, T4> > action, T2 arg2, T3 arg3, T4 arg4, EndpointId targetEndpoint = default(EndpointId))
     where T1 : IMyEventOwner
     where T5 : IMyEventOwner
 {
     ReplicationLayer.RaiseEvent(arg1, arg5, action, arg2, arg3, arg4, targetEndpoint);
 }
示例#35
0
 public static void RaiseStaticEvent <T2, T3, T4>(Func <IMyEventOwner, Action <T2, T3, T4> > action, T2 arg2, T3 arg3, T4 arg4, EndpointId targetEndpoint = new EndpointId(), Vector3D?position = new Vector3D?())
 {
     ReplicationLayer.RaiseEvent <IMyEventOwner, T2, T3, T4, IMyEventOwner>(null, null, action, arg2, arg3, arg4, targetEndpoint, position);
 }
示例#36
0
 /// <summary>
 /// Raises multiplayer event.
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseEvent <T1, T2, T3, T4, T5, T6>(T1 arg1, Func <T1, Action <T2, T3, T4, T5, T6> > action, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, EndpointId targetEndpoint = default(EndpointId))
     where T1 : IMyEventOwner
 {
     ReplicationLayer.RaiseEvent(arg1, (IMyEventOwner)null, action, arg2, arg3, arg4, arg5, arg6, targetEndpoint);
 }
示例#37
0
        public unsafe void SendMessage(MyMessageId id, BitStream stream, bool reliable, EndpointId endpoint)
        {
            m_sendStream.Position = 0;
            m_sendStream.WriteByte((byte)id);
            if (stream != null)
            {
                m_sendStream.WriteNoAlloc((byte *)(void *)stream.DataPointer, 0, stream.BytePosition);
            }

            SendMessage(m_sendStream, reliable ? P2PMessageEnum.ReliableWithBuffering : P2PMessageEnum.Unreliable, endpoint.Value, m_channel);
        }
示例#38
0
 /// <summary>
 /// Raises blocking multiplayer event.
 /// </summary>
 /// <param name="targetEndpoint">Target of the event. When broadcasting, it's exclude endpoint.</param>
 public static void RaiseEvent <T1, T2, T3, T4, T5, T6, T7, T8>(T1 arg1, T8 arg8, Func <T1, Action <T2, T3, T4, T5, T6, T7> > action, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, EndpointId targetEndpoint = default(EndpointId))
     where T1 : IMyEventOwner
     where T8 : IMyEventOwner
 {
     ReplicationLayer.RaiseEvent(arg1, arg8, action, arg2, arg3, arg4, arg5, arg6, arg7, targetEndpoint);
 }
示例#39
0
        private static void WaitForHostToConnect(EndpointId hostId, IComponentContext container)
        {
            var diagnostics = container.Resolve<SystemDiagnostics>();
            var commands = container.Resolve<ISendCommandsToRemoteEndpoints>();

            var resetEvent = new AutoResetEvent(false);
            var notificationAvailabilityNotifier =
                Observable.FromEventPattern<CommandSetAvailabilityEventArgs>(
                    h => commands.OnEndpointSignedIn += h,
                    h => commands.OnEndpointSignedIn -= h)
                .Where(args => args.EventArgs.Endpoint.Equals(hostId))
                .Take(1);

            var availability = notificationAvailabilityNotifier.Subscribe(args => resetEvent.Set());
            using (availability)
            {
                if (!commands.HasCommandsFor(hostId))
                {
                    diagnostics.Log(
                        LevelToLog.Debug,
                        ExecutorConstants.LogPrefix,
                        Resources.Log_Messages_WaitingForHostToConnect);

                    resetEvent.WaitOne();
                }
            }
        }
示例#40
0
        public void SendWithFailureOnRetry()
        {
            var count             = 0;
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var endpointId        = new EndpointId("id");
            var msg = new EndpointDisconnectMessage(endpointId);

            Func <IStoreV1CommunicationData, MessageReceptionConfirmation> handler =
                s =>
            {
                count++;
                throw new Exception("Lets bail the first one");
            };
            var receiver = new MockMessageReceivingEndpoint(handler);

            var uri  = new Uri("net.pipe://localhost/test/pipe");
            var host = new ServiceHost(receiver, uri);

            var binding        = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
            var address        = string.Format("{0}_{1}", "ThroughNamedPipe", Process.GetCurrentProcess().Id);
            var remoteEndpoint = host.AddServiceEndpoint(typeof(IMessageReceivingEndpoint), binding, address);

            foreach (var operation in remoteEndpoint.Contract.Operations)
            {
                var behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (behavior == null)
                {
                    behavior = new DataContractSerializerOperationBehavior(operation);
                    operation.Behaviors.Add(behavior);
                }

                behavior.DataContractResolver = new ProtocolDataContractResolver();
            }

            host.Open();
            try
            {
                var configuration = new Mock <IConfiguration>();
                {
                    configuration.Setup(c => c.HasValueFor(It.IsAny <ConfigurationKey>()))
                    .Returns(false);
                }

                var localAddress = string.Format("{0}/{1}", uri.OriginalString, address);
                var template     = new NamedPipeProtocolChannelTemplate(configuration.Object, new ProtocolDataContractResolver());
                var sender       = new RestoringMessageSendingEndpoint(
                    new Uri(localAddress),
                    template,
                    new ProtocolDataContractResolver(),
                    new IConvertCommunicationMessages[]
                {
                    new EndpointDisconnectConverter(),
                },
                    systemDiagnostics);

                // This message should fault the channel
                Assert.Throws <FailedToSendMessageException>(() => sender.Send(msg, 2));
                Assert.AreEqual(2, count);
            }
            finally
            {
                host.Close();
            }
        }
 public EndpointNotFoundException(EndpointId endpoint, string host) : base($"'{endpoint}' not found on host '{host}'")
 {
     Endpoint = endpoint;
 }
示例#42
0
        public void SendWithNoChannel()
        {
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var endpointId        = new EndpointId("id");
            var msg = new EndpointDisconnectMessage(endpointId);

            var  autoReset      = new AutoResetEvent(false);
            bool hasBeenInvoked = false;
            Func <IStoreV1CommunicationData, MessageReceptionConfirmation> handler =
                s =>
            {
                hasBeenInvoked = true;
                autoReset.Set();
                Assert.AreEqual(endpointId, s.Sender);
                return(new MessageReceptionConfirmation
                {
                    WasDataReceived = true,
                });
            };
            var receiver = new MockMessageReceivingEndpoint(handler);

            var uri  = new Uri("net.pipe://localhost/test/pipe");
            var host = new ServiceHost(receiver, uri);

            host.Faulted += (s, e) => Assert.Fail();

            var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                TransferMode = TransferMode.Buffered,
            };

            var address        = string.Format("{0}_{1}", "ThroughNamedPipe", Process.GetCurrentProcess().Id);
            var remoteEndpoint = host.AddServiceEndpoint(typeof(IMessageReceivingEndpoint), binding, address);

            foreach (var operation in remoteEndpoint.Contract.Operations)
            {
                var behavior = operation.Behaviors.Find <DataContractSerializerOperationBehavior>();
                if (behavior == null)
                {
                    behavior = new DataContractSerializerOperationBehavior(operation);
                    operation.Behaviors.Add(behavior);
                }

                behavior.DataContractResolver = new ProtocolDataContractResolver();
            }

            host.Open();
            try
            {
                var configuration = new Mock <IConfiguration>();
                {
                    configuration.Setup(c => c.HasValueFor(It.IsAny <ConfigurationKey>()))
                    .Returns(false);
                }

                var localAddress = string.Format("{0}/{1}", uri.OriginalString, address);
                var template     = new NamedPipeProtocolChannelTemplate(configuration.Object, new ProtocolDataContractResolver());
                var sender       = new RestoringMessageSendingEndpoint(
                    new Uri(localAddress),
                    template,
                    new ProtocolDataContractResolver(),
                    new IConvertCommunicationMessages[]
                {
                    new EndpointDisconnectConverter(),
                },
                    systemDiagnostics);

                sender.Send(msg, 1);

                autoReset.WaitOne(500);
                Assert.IsTrue(hasBeenInvoked);
            }
            finally
            {
                host.Close();
            }
        }
 /// <summary>
 /// Starts the execution of the given test steps.
 /// </summary>
 /// <param name="testId">The ID of the test that is being executed.</param>
 /// <param name="testSteps">The collection of test steps that should be executed.</param>
 /// <param name="environmentParameters">The collection that contains the parameters related to the test environment.</param>
 /// <param name="callingEndpoint">The ID of the endpoint that called the method.</param>
 /// <param name="token">The upload token that can be used to upload the file.</param>
 /// <returns>A task which completes when the execution has started successfully.</returns>
 public Task Execute(
     int testId,
     List<TestStep> testSteps,
     List<InputParameter> environmentParameters,
     EndpointId callingEndpoint,
     UploadToken token)
 {
     return Task.Factory.StartNew(() => StartNewTestExecution(testId, testSteps, environmentParameters, callingEndpoint, token));
 }
示例#44
0
 public void Add(EndpointId id, IDeliverToEndpoint instance) => _transporters.Add(id, instance);
        private bool DownloadTestData(
            EndpointId callingEndpoint,
            UploadToken token,
            string storageDirectory,
            ITestSectionBuilder builder,
            out string testFile)
        {
            testFile = string.Empty;
            try
            {
                testFile = DownloadTestData(callingEndpoint, token, storageDirectory);

                m_Diagnostics.Log(
                    LevelToLog.Debug,
                    ExecutorServiceConstants.LogPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.Log_Messages_DownloadedTestData_WithFile,
                        testFile));
                builder.AddInformationMessage(Resources.ReportSection_Info_DownloadedTestData);
            }
            catch (Exception)
            {
                builder.AddErrorMessage(Resources.ReportSection_Error_FailedToDownloadTestData);
                builder.FinalizeAndStore(false);
                m_TestExecutionEvents.RaiseOnTestCompletion(TestExecutionResult.Failed);

                return false;
            }

            return true;
        }
示例#46
0
 public IDeliverToEndpoint GetTransporter(EndpointId endpoint)
     => _transporters.GetValueOrDefault(endpoint);
        private EndpointId StartExecutorApplication(EndpointId endpointId, Uri address)
        {
            var localInstallDir = Assembly.GetExecutingAssembly().LocalDirectoryPath();
            var fullFilePath = Path.Combine(localInstallDir, "Sherlock.Executor.exe");
            var arguments = string.Format(
                CultureInfo.InvariantCulture,
                @"--host={0} --channeltype=""{1}"" --channeluri={2}",
                endpointId,
                ChannelType.NamedPipe,
                address);

            var startInfo = new ProcessStartInfo
                {
                    FileName = fullFilePath,
                    Arguments = arguments,

                    // Create no window for the process. It doesn't need one
                    // and we don't want the user to have a window they can
                    // kill. If the process has to die then the user will have
                    // to put in some effort.
                    CreateNoWindow = true,

                    // Do not use the shell to create the application
                    // This means we can only start executables.
                    UseShellExecute = false,

                    // Do not display an error dialog if startup fails
                    // We'll deal with that ourselves
                    ErrorDialog = false,

                    // Do not redirect any of the input or output streams
                    // We don't really care about them because we won't be using
                    // them anyway.
                    RedirectStandardInput = false,
                    RedirectStandardOutput = false,
                    RedirectStandardError = false,

                    // Set the working directory to something sane. Mostly the
                    // directory of the file that we're trying to read.
                    WorkingDirectory = localInstallDir,
                };

            var exec = new Process
                {
                    StartInfo = startInfo
                };

            exec.Exited += HandleOnExecutorApplicationExit;

            exec.Start();
            return exec.CreateEndpointIdForProcess();
        }
 public ProcessingStorageTransporter(Func<IAddMessageToProcessorStorage> factory,EndpointId processorName)
 {
     _factory = factory;
     _processorName = processorName;
 }
        private void WaitForExecutorConnection(EndpointId endpoint)
        {
            var resetEvent = new AutoResetEvent(false);
            var commandAvailabilityNotifier =
                        Observable.FromEventPattern<CommandSetAvailabilityEventArgs>(
                            h => m_RemoteCommands.OnEndpointSignedIn += h,
                            h => m_RemoteCommands.OnEndpointSignedIn -= h)
                        .Where(args => args.EventArgs.Endpoint.Equals(endpoint))
                        .Take(1);

            var notificationAvailabilityNotifier =
                Observable.FromEventPattern<NotificationSetAvailabilityEventArgs>(
                    h => m_RemoteNotifications.OnEndpointSignedIn += h,
                    h => m_RemoteNotifications.OnEndpointSignedIn -= h)
                .Where(args => args.EventArgs.Endpoint.Equals(endpoint))
                .Take(1);

            var availability = commandAvailabilityNotifier
                .Zip(notificationAvailabilityNotifier, (a, b) => true)
                .Subscribe(args => resetEvent.Set());

            using (availability)
            {
                if (!m_RemoteNotifications.HasNotificationsFor(endpoint))
                {
                    var timeoutInMilliSeconds = m_Configuration.HasValueFor(ExecutorServiceConfigurationKeys.ExecutorStartupTimeoutInMilliSeconds)
                        ? m_Configuration.Value<int>(ExecutorServiceConfigurationKeys.ExecutorStartupTimeoutInMilliSeconds)
                        : ExecutorServiceConstants.DefaultExecutorStartupTimeoutInMilliSeconds;

                    if (!resetEvent.WaitOne(timeoutInMilliSeconds))
                    {
                        throw new TestExecutionFailureException();
                    }
                }
            }
        }
        public void ProposeDistributionFor()
        {
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var offlineInfo = CreateOfflineInfo(new Mock<IPersistenceInformation>().Object);
            var result = new DatasetActivationProposal
            {
                Endpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess(),
                IsAvailable = true,
                ActivationTime = new TimeSpan(0, 1, 0),
                TransferTime = new TimeSpan(0, 1, 0),
                PercentageOfAvailableDisk = 50,
                PercentageOfMaximumMemory = 50,
                PercentageOfPhysicalMemory = 50,
            };

            var loaderCommands = new Mock<IDatasetActivationCommands>();
            {
                loaderCommands.Setup(l => l.ProposeFor(It.IsAny<ExpectedDatasetLoad>()))
                    .Returns(
                        Task.Factory.StartNew(
                            () => result,
                            new CancellationToken(),
                            TaskCreationOptions.None,
                            new CurrentThreadTaskScheduler()))
                    .Verifiable();
            }

            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandHub.Setup(h => h.CommandsFor<IDatasetActivationCommands>(It.IsAny<EndpointId>()))
                    .Returns(loaderCommands.Object);
            }

            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();

            var offlimitsMachines = new SortedList<string, object>
                {
                    { "someKeyStuff", "otherMachine" }
                };
            var config = new Mock<IConfiguration>();
            {
                config.Setup(c => c.HasValueFor(It.IsAny<ConfigurationKey>()))
                    .Returns(true);
                config.Setup(c => c.Value<IDictionary<string, object>>(It.IsAny<ConfigurationKey>()))
                    .Returns(offlimitsMachines);
            }

            var communicationLayer = new Mock<ICommunicationLayer>();
            {
                communicationLayer.Setup(s => s.LocalConnectionFor(It.Is<ChannelType>(c => c == ChannelType.TcpIP)))
                    .Returns(
                        new Tuple<EndpointId, Uri, Uri>(
                            EndpointIdExtensions.CreateEndpointIdForCurrentProcess(),
                            new Uri("net.tcp://localhost/tcp"),
                            new Uri("net.tcp://localhost/tcp/data")));
            }

            var distributor = new RemoteDatasetDistributor(
                config.Object,
                commandHub.Object,
                notificationHub.Object,
                new Mock<IStoreUploads>().Object,
                (d, e, n) => new DatasetOnlineInformation(
                    d,
                    e,
                    n,
                    commandHub.Object,
                    notificationHub.Object,
                    systemDiagnostics),
                communicationLayer.Object,
                systemDiagnostics,
                new CurrentThreadTaskScheduler());

            // Add the remote endpoints
            var forbiddenMachineId = new EndpointId("otherMachine:8080");
            commandHub.Raise(
                h => h.OnEndpointSignedIn += null,
                new CommandSetAvailabilityEventArgs(
                    forbiddenMachineId,
                    new[] { typeof(IDatasetActivationCommands) }));

            var legalMachineId = new EndpointId("myMachine:8080");
            commandHub.Raise(
                h => h.OnEndpointSignedIn += null,
                new CommandSetAvailabilityEventArgs(
                    legalMachineId,
                    new[] { typeof(IDatasetActivationCommands) }));

            var request = new DatasetActivationRequest
            {
                DatasetToActivate = offlineInfo,
                ExpectedLoadPerMachine = new ExpectedDatasetLoad(),
                PreferredLocations = DistributionLocations.All,
            };
            var plans = distributor.ProposeDistributionFor(request, new CancellationToken());
            var listPlans = plans.ToList();
            Assert.AreEqual(1, listPlans.Count());

            var plan = listPlans[0];
            Assert.IsTrue(ReferenceEquals(offlineInfo, plan.DistributionFor));
            Assert.AreEqual(new NetworkIdentifier(result.Endpoint.OriginatesOnMachine()), plan.MachineToDistributeTo);
            Assert.IsTrue(ReferenceEquals(result, plan.Proposal));

            loaderCommands.Verify(l => l.ProposeFor(It.IsAny<ExpectedDatasetLoad>()), Times.Once());
        }
 private void DisconnectCommunication(EndpointId endpoint)
 {
     var resetEvent = new AutoResetEvent(false);
     EventHandler<EndpointEventArgs> handler = (s, e) =>
     {
         if (e.Endpoint.Equals(endpoint))
         {
             resetEvent.Set();
         }
     };
     m_Commands.OnEndpointSignedOff += handler;
     try
     {
         // See if we already have the information
         if (m_Commands.HasCommandsFor(endpoint))
         {
             m_Disconnection(endpoint, ChannelType.TcpIP);
             resetEvent.WaitOne(GlobalConstants.DefaultMaximumNetworkSignInTimeInMilliseconds);
         }
     }
     finally
     {
         m_Commands.OnEndpointSignedOff -= handler;
     }
 }
        public void LocatePluginAssemblyWithUnknownAssemblyOnHost()
        {
            var commands = new Mock<IHostApplicationCommands>();
            {
                commands.Setup(c => c.PreparePluginContainerForTransfer(It.IsAny<AssemblyName>()))
                    .Returns(
                        Task<UploadToken>.Factory.StartNew(
                            () =>
                            {
                                throw new FileNotFoundException();
                            }));
            }

            var commandContainer = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandContainer.Setup(c => c.CommandsFor<IHostApplicationCommands>(It.IsAny<EndpointId>()))
                    .Returns(commands.Object);
            }

            DownloadDataFromRemoteEndpoints layer = (id, token, file) =>
                {
                    Assert.Fail();
                    return Task<FileInfo>.Factory.StartNew(() => new FileInfo(file));
                };

            var fileSystem = new Mock<IFileSystem>();

            var endpoint = new EndpointId("a");
            var resolver = new PluginLoadingAssemblyResolver(
                commandContainer.Object,
                layer,
                fileSystem.Object,
                endpoint);
            Assert.IsNull(resolver.LocatePluginAssembly(new object(), new ResolveEventArgs("a")));
        }
示例#53
0
        /// <summary>
        /// Sends a static event to one client
        /// </summary>
        /// <param name="method"></param>
        /// <param name="endpoint"></param>
        /// <param name="args"></param>
        public void RaiseStaticEvent(MethodInfo method, EndpointId endpoint, params object[] args)
        {
            try
            {
                if (method == null)
                {
                    throw new ArgumentNullException(nameof(method), "MethodInfo cannot be null!");
                }

                if (args.Length > 6)
                {
                    throw new ArgumentOutOfRangeException(nameof(args), "Cannot pass more than 6 arguments!");
                }

                if (!method.HasAttribute <EventAttribute>())
                {
                    throw new CustomAttributeFormatException("Provided event target does not have the Event attribute! Replication will not succeed!");
                }

                //array to hold arguments to pass into DispatchEvent
                object[] arguments = new object[11];

                arguments[0] = TryGetStaticCallSite(method);
                arguments[1] = endpoint;
                arguments[2] = 1f;
                arguments[3] = (IMyEventOwner)null;

                //copy supplied arguments into the reflection arguments
                for (int i = 0; i < args.Length; i++)
                {
                    arguments[i + 4] = args[i];
                }

                //pad the array out with DBNull
                for (int j = args.Length + 4; j < 10; j++)
                {
                    arguments[j] = e;
                }

                arguments[10] = (IMyEventOwner)null;

                //create an array of Types so we can create a generic method
                Type[] argTypes = new Type[8];

                for (int k = 3; k < 11; k++)
                {
                    argTypes[k - 3] = arguments[k]?.GetType() ?? typeof(IMyEventOwner);
                }

                //create a generic method of DispatchEvent and invoke to inject our data into the network
                var dispatch = typeof(MyReplicationLayerBase).GetMethod("DispatchEvent", BindingFlags.NonPublic | BindingFlags.Instance).MakeGenericMethod(argTypes);
                MySandboxGame.Static.Invoke(() =>
                {
                    try
                    {
                        dispatch.Invoke(MyMultiplayer.ReplicationLayer, arguments);
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.BaseLog.Error(ex);
                    }
                });
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectionInformationViewModel"/> class.
 /// </summary>
 /// <param name="endpoint">The endpoint.</param>
 public ConnectionInformationViewModel(EndpointId endpoint)
 {
     Id = endpoint;
 }
示例#55
0
        /// <summary>
        /// Loads the dataset into an external application and returns when the dataset application has started.
        /// </summary>
        /// <param name="endpointId">The endpoint ID for the owner.</param>
        /// <param name="channelType">The type of channel on which the dataset should be contacted.</param>
        /// <param name="address">The channel address for the owner.</param>
        /// <returns>The ID number of the newly created endpoint.</returns>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="endpointId"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="address"/> is <see langword="null" />.
        /// </exception>
        public EndpointId ActivateDataset(EndpointId endpointId, ChannelType channelType, Uri address)
        {
            {
                Lokad.Enforce.Argument(() => endpointId);
                Lokad.Enforce.Argument(() => address);
            }

            var deploymentDir = DeployLocation();
            m_Diagnostics.Log(
                LevelToLog.Debug,
                BaseConstants.LogPrefix,
                string.Format(CultureInfo.InvariantCulture, "Deploying to: {0}", deploymentDir));

            DeployApplication(deploymentDir);

            var fullFilePath = Path.Combine(deploymentDir, DatasetApplicationFileName);
            var arguments = string.Format(
                CultureInfo.InvariantCulture,
                @"--host={0} --channeltype=""{1}"" --channeluri={2}",
                endpointId,
                channelType,
                address);

            var startInfo = new ProcessStartInfo
            {
                FileName = fullFilePath,
                Arguments = arguments,

                // Create no window for the process. It doesn't need one
                // and we don't want the user to have a window they can
                // kill. If the process has to die then the user will have
                // to put in some effort.
                CreateNoWindow = true,

                // Do not use the shell to create the application
                // This means we can only start executables.
                UseShellExecute = false,

                // Do not display an error dialog if startup fails
                // We'll deal with that ourselves
                ErrorDialog = false,

                // Do not redirect any of the input or output streams
                // We don't really care about them because we won't be using
                // them anyway.
                RedirectStandardInput = false,
                RedirectStandardOutput = false,
                RedirectStandardError = false,

                // Set the working directory to something sane. Mostly the
                // directory of the file that we're trying to read.
                WorkingDirectory = deploymentDir,
            };

            using (var exec = new Process())
            {
                exec.StartInfo = startInfo;
                exec.Start();

                // Link to the current process so that the datasets die if we die
                s_ProcessTrackingJob.LinkChildProcessToJob(exec);

                return exec.CreateEndpointIdForProcess();
            }
        }
示例#56
0
 public EndpointEvent(EventId hubEventId, EndpointId endpointId, Event @event)
 {
     HubEventId = hubEventId;
     EndpointId = endpointId;
     Event      = @event;
 }
        public void ImplementPlan()
        {
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var loaderEndpoint = new EndpointId("myMachine:8080");
            var proposal = new DatasetActivationProposal
            {
                Endpoint = loaderEndpoint,
                IsAvailable = true,
                ActivationTime = new TimeSpan(0, 1, 0),
                TransferTime = new TimeSpan(0, 1, 0),
                PercentageOfAvailableDisk = 50,
                PercentageOfMaximumMemory = 50,
                PercentageOfPhysicalMemory = 50,
            };

            var filePath = @"c:\temp\myfile.txt";
            var storage = new Mock<IPersistenceInformation>();
            {
                storage.Setup(s => s.AsFile())
                    .Returns(new FileInfo(filePath));
            }

            var plan = CreateNewDistributionPlan(proposal, CreateOfflineInfo(storage.Object), systemDiagnostics);
            var datasetEndpoint = new EndpointId("OtherMachine:5678");
            var loaderCommands = new Mock<IDatasetActivationCommands>();
            {
                loaderCommands.Setup(l => l.Activate(It.IsAny<EndpointId>(), It.IsAny<ChannelType>(), It.IsAny<Uri>(), It.IsAny<DatasetId>()))
                    .Returns(
                        Task.Factory.StartNew(
                            () => datasetEndpoint,
                            new CancellationToken(),
                            TaskCreationOptions.None,
                            new CurrentThreadTaskScheduler()));
            }

            var applicationCommands = new Mock<IDatasetApplicationCommands>();
            {
                applicationCommands.Setup(c => c.Load(It.IsAny<EndpointId>(), It.IsAny<UploadToken>()))
                    .Returns(
                        Task.Factory.StartNew(
                            () => { },
                            new CancellationToken(),
                            TaskCreationOptions.None,
                            new CurrentThreadTaskScheduler()));
            }

            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandHub.Setup(h => h.HasCommandsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                commandHub.Setup(h => h.CommandsFor<IDatasetActivationCommands>(It.IsAny<EndpointId>()))
                    .Returns(loaderCommands.Object);
                commandHub.Setup(h => h.CommandsFor<IDatasetApplicationCommands>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(datasetEndpoint, e))
                    .Returns(applicationCommands.Object);
            }

            var notifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(n => n.HasNotificationsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(datasetEndpoint, e))
                    .Returns(notifications.Object);
            }

            var config = new Mock<IConfiguration>();
            {
                config.Setup(c => c.HasValueFor(It.IsAny<ConfigurationKey>()))
                    .Returns(false);
            }

            var communicationLayer = new Mock<ICommunicationLayer>();
            {
                communicationLayer.Setup(s => s.LocalConnectionFor(It.Is<ChannelType>(c => c == ChannelType.TcpIP)))
                    .Returns(
                        new Tuple<EndpointId, Uri, Uri>(
                            EndpointIdExtensions.CreateEndpointIdForCurrentProcess(),
                            new Uri("net.tcp://localhost/tcp"),
                            new Uri("net.tcp://localhost/tcp/data")));
            }

            var distributor = new RemoteDatasetDistributor(
                config.Object,
                commandHub.Object,
                notificationHub.Object,
                new Mock<IStoreUploads>().Object,
                (d, e, n) => new DatasetOnlineInformation(
                    d,
                    e,
                    n,
                    commandHub.Object,
                    notificationHub.Object,
                    systemDiagnostics),
                communicationLayer.Object,
                systemDiagnostics,
                new CurrentThreadTaskScheduler());

            // Add the remote endpoints
            commandHub.Raise(
                h => h.OnEndpointSignedIn += null,
                new CommandSetAvailabilityEventArgs(
                    loaderEndpoint,
                    new[] { typeof(IDatasetActivationCommands) }));

            Action<int, string, bool> progress = (p, m, e) => { };
            var result = distributor.ImplementPlan(plan, new CancellationToken(), progress);
            result.Wait();

            Assert.AreSame(datasetEndpoint, result.Result.Endpoint);
            Assert.AreSame(plan.DistributionFor.Id, result.Result.Id);
            Assert.AreSame(plan.MachineToDistributeTo, result.Result.RunsOn);
        }
示例#58
0
 /// <summary>
 /// Returns the notification proxy for the given endpoint.
 /// </summary>
 /// <typeparam name="TNotification">The typeof notification set that should be returned.</typeparam>
 /// <param name="endpoint">The ID number of the endpoint for which the notifications should be returned.</param>
 /// <returns>The requested notification set.</returns>
 public TNotification NotificationsFor <TNotification>(EndpointId endpoint) where TNotification : class, INotificationSet
 {
     return(NotificationsFor(endpoint, typeof(TNotification)) as TNotification);
 }
示例#59
0
 /// <summary>
 /// Handles the reception of new notification types.
 /// </summary>
 /// <param name="endpoint">The ID of the endpoint that owns the notifications.</param>
 /// <param name="notificationTypes">An array containing the notification types for a given endpoint.</param>
 public void OnReceiptOfEndpointNotifications(EndpointId endpoint, IEnumerable <OfflineTypeInformation> notificationTypes)
 {
     OnReceiptOfEndpointProxies(endpoint, notificationTypes);
 }
 private void RemoveEndpoint(EndpointId endpoint)
 {
     lock (m_Lock)
     {
         if (m_ActivatorCommands.ContainsKey(endpoint))
         {
             m_ActivatorCommands.Remove(endpoint);
         }
     }
 }