Пример #1
0
        private void OnUpdate()
        {
            UpdateWatch.Restart();

            try
            {
                ServiceStartMode?PreviousStartType = StartType;
                bool             LockIt            = GetSettingBool("Locked", true);

                ServiceController[] Services = ServiceController.GetServices();

                foreach (ServiceController Service in Services)
                {
                    if (Service.ServiceName == WindowsUpdateServiceName)
                    {
                        StartType = Service.StartType;

                        if (PreviousStartType.HasValue && PreviousStartType.Value != StartType.Value)
                        {
                            App.AddLog("Start type changed");

                            ChangeLockMode(Service, LockIt);
                        }

                        StopIfRunning(Service, LockIt);

                        PreviousStartType = StartType;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                App.AddLog($"(from OnUpdate) {e.Message}");
            }
        }
Пример #2
0
        public void ShoudThrowOnBadHash()
        {
            string expectedImage = "parity/parity:v2.3.4";
            string expectedHash  = "bbbbcc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514";

            StateChangeAction changeAction = new StateChangeAction
            {
                Mode        = UpdateMode.Docker,
                Payload     = "parity/parity:v2.3.4",
                PayloadHash = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };
            NodeState nodeState = new NodeState
            {
                DockerImage    = "parity/parity:v2.3.4",
                DockerChecksum = "a783cc3d9b971ea268eb723eb8c653519f39abfa3d6819c1ee1f0292970cf514"
            };


            Mock <IDockerControl> mocDcc = new Mock <IDockerControl>(MockBehavior.Loose);

            // Setup image pull mock
            mocDcc.Setup(mock => mock.PullImage(
                             It.Is <ImagesCreateParameters>(icp => icp.Tag == "v2.3.4" && icp.FromImage == "parity/parity"),
                             It.Is <AuthConfig>(obj => obj == null),
                             It.IsAny <Progress <JSONMessage> >()))
            .Verifiable("Did not pull correct image");

            // Setup inspect image mock
            mocDcc
            .Setup(mock => mock.InspectImage(
                       It.Is <string>(i => i == expectedImage)
                       ))
            .Returns(new ImageInspectResponse
            {
                ID = expectedHash
            })
            .Verifiable("Did not inspect the correct image");


            // setup delete mock
            mocDcc
            .Setup(mock => mock.DeleteImage(expectedImage))
            .Verifiable("Did not correctly delete the wrong image");

            MockConfigProvider confProvider = new MockConfigProvider();

            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = "/some/path",
                DockerControl         = mocDcc.Object,
                ConfigurationProvider = confProvider,
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            // Run the update action
            Action updateDocker = () => { uw.UpdateDocker(changeAction, nodeState); };

            updateDocker.Should()
            .Throw <UpdateVerificationException>()
            .WithMessage("Docker image hashes don't match.");

            // Verify the mocks
            mocDcc.Verify();

            // make sure nothing else was called
            mocDcc.VerifyNoOtherCalls();

            // verify no new state was written
            confProvider.CurrentState.Should().BeNull();
        }
        public void ShouldHashStringCorrectly(string plainText, string expectedHash)
        {
            string computedHash = UpdateWatch.HashString(plainText);

            computedHash.Should().Be(expectedHash);
        }
        public void ShouldDownloadChainspec()
        {
            // Test setup
            string expectedUrl     = "https://example.com/chain.json";
            string expectedPayload = "This would be a complete chainspec file.";
            string expectedHash    = "8394d0987bd84c677122872aa67f60295b972eceb3f75bec068e83570d3c6999";

            // prepare directory
            string basePath = $"nodecontrol-tests-{Guid.NewGuid()}";
            string path     = Path.Join(Path.GetTempPath(), basePath);

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(Path.Join(path, "config"));

            // write existing dummy chainspec
            File.WriteAllText(Path.Join(path, "config", "chainspec.json"), "This is not a chainspec file");

            // get a mock dcc
            MockDockerControl mockDcc = new MockDockerControl();

            StateChangeAction sca = new StateChangeAction
            {
                Mode        = UpdateMode.ChainSpec,
                Payload     = expectedUrl,
                PayloadHash = expectedHash
            };


            bool urlCorrect = false;
            // setup mock http handler
            Mock <HttpMessageHandler> handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            // prepare the expected response of the mocked http call
            .ReturnsAsync((HttpRequestMessage request, CancellationToken cancellationToken) =>
            {
                // make sure queried url is correct
                urlCorrect = request.RequestUri.ToString() == expectedUrl;

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content             = new StringContent(expectedPayload);
                return(response);
            })
            .Verifiable();

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup(
                "Dispose",
                ItExpr.IsAny <bool>()
                )
            .Verifiable();


            // Run the test
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = path,
                DockerControl         = mockDcc,
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action update = () =>
            {
                uw.UpdateChainSpec(sca, handlerMock.Object);
            };

            // Execute test
            update.Should().NotThrow();


            // Should have create a backup file

            // Should have written the new payload to file
            string newFileContents = File.ReadAllText(Path.Join(path, "config", "chainspec.json"));

            newFileContents.Should().Be(expectedPayload);

            // should have called with the correct url
            urlCorrect.Should().Be(true);

            // Should have triggered an update
            mockDcc.ApplyChangesCallCount.Should().Be(1);
            mockDcc.SendRestartOnly.Should().Be(true);
            mockDcc.SendPathToStack.Should().Be(path);

            // http client should have been disposed
            Action verifyDispose = () => handlerMock.VerifyAll();

            verifyDispose.Should().NotThrow();
        }
        public void ShouldFailtoVerifyWhenUnableToDownload()
        {
            // Test setup
            string expectedUrl  = "https://example.com/chain.json";
            string expectedHash = "8394d0987bd84c677122872aa67f60295b972eceb3f75bec068e83570d3c6999";

            // prepare directory
            string basePath = $"nodecontrol-tests-{Guid.NewGuid()}";
            string path     = Path.Join(Path.GetTempPath(), basePath);

            Directory.CreateDirectory(path);
            Directory.CreateDirectory(Path.Join(path, "config"));

            // write existing dummy chainspec
            string existingChainSpecContent = "This is the existing chainspec file before update";

            File.WriteAllText(Path.Join(path, "config", "chainspec.json"), existingChainSpecContent);

            // get a mock dcc
            MockDockerControl mockDcc = new MockDockerControl();

            StateChangeAction sca = new StateChangeAction
            {
                Mode        = UpdateMode.ChainSpec,
                Payload     = expectedUrl,
                PayloadHash = expectedHash
            };

            // setup mock http handler
            Mock <HttpMessageHandler> handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Loose);

            handlerMock
            .Protected()
            // Setup the PROTECTED method to mock
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            // prepare the expected response of the mocked http call
            .ReturnsAsync((HttpRequestMessage request, CancellationToken cancellationToken)
                          => new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("error")
            })
            .Verifiable();

            // Run the test
            UpdateWatch uw = new UpdateWatch(new UpdateWatchOptions
            {
                RpcEndpoint           = "http://example.com",
                ContractAddress       = "0x0",
                ValidatorAddress      = "0x0",
                DockerStackPath       = path,
                DockerControl         = mockDcc,
                ConfigurationProvider = new MockConfigProvider(),
                ContractWrapper       = new MockContractWrapper()
            }, new MockLogger());

            Action update = () =>
            {
                uw.UpdateChainSpec(sca, handlerMock.Object);
            };

            // Execute test
            update.Should().Throw <UpdateVerificationException>()
            .WithMessage("Unable to download new chainspec")
            .WithInnerException <AggregateException>();


            // should not call apply updates
            mockDcc.ApplyChangesCallCount.Should().Be(0);

            // should not touch current chainspec
            string currentChainspecFileContents = File.ReadAllText(Path.Join(path, "config", "chainspec.json"));

            currentChainspecFileContents.Should().Be(existingChainSpecContent);
        }
Пример #6
0
        private void OnUpdate()
        {
            try
            {
                Logger.AddLog("%% Running timer callback");

                int LastTimerDispatcherCount = Interlocked.Decrement(ref TimerDispatcherCount);
                UpdateWatch.Restart();

                Logger.AddLog($"Watch restarted, Elapsed = {LastTotalElapsed}, pending count = {LastTimerDispatcherCount}");

                Settings.RenewKey();

                Logger.AddLog("Key renewed");

                ServiceStartMode?PreviousStartType = StartType;
                bool             LockIt            = IsSettingLock;

                Logger.AddLog("Lock setting read");

                ServiceController[] Services = ServiceController.GetServices();
                if (Services == null)
                {
                    Logger.AddLog("Failed to get services");
                }
                else
                {
                    Logger.AddLog($"Found {Services.Length} service(s)");

                    foreach (ServiceController Service in Services)
                    {
                        if (Service.ServiceName == WindowsUpdateServiceName)
                        {
                            Logger.AddLog($"Checking {Service.ServiceName}");

                            StartType = Service.StartType;

                            Logger.AddLog($"Current start type: {StartType}");

                            if (PreviousStartType.HasValue && PreviousStartType.Value != StartType.Value)
                            {
                                Logger.AddLog("Start type changed");

                                ChangeLockMode(Service, LockIt);
                            }

                            StopIfRunning(Service, LockIt);

                            PreviousStartType = StartType;
                            break;
                        }
                    }
                }

                ZombifyMe.Zombification.SetAlive();

                Logger.AddLog("%% Timer callback completed");
            }
            catch (Exception e)
            {
                Logger.AddLog($"(from OnUpdate) {e.Message}");
            }
        }