Esempio n. 1
0
        public static async Task <EventStoreInstance> StartAsync()
        {
            var installedSoftware = await InstallHelper.InstallAsync(SoftwareDescription).ConfigureAwait(false);

            var tcpPort             = TcpHelper.GetFreePort();
            var httpPort            = TcpHelper.GetFreePort();
            var connectionStringUri = new Uri($"tcp://*****:*****@{IPAddress.Loopback}:{tcpPort}");
            var exePath             = Path.Combine(installedSoftware.InstallPath, "EventStore.ClusterNode.exe");

            IDisposable processDisposable = null;

            try
            {
                processDisposable = ProcessHelper.StartExe(
                    exePath,
                    "'admin' user added to $users",
                    "--mem-db=True",
                    "--cluster-size=1",
                    $"--ext-tcp-port={tcpPort}",
                    $"--ext-http-port={httpPort}");

                var connectionSettings = ConnectionSettings.Create()
                                         .EnableVerboseLogging()
                                         .KeepReconnecting()
                                         .SetDefaultUserCredentials(new UserCredentials("admin", "changeit"))
                                         .Build();
                using (var eventStoreConnection = EventStoreConnection.Create(connectionSettings, connectionStringUri))
                {
                    var start = DateTimeOffset.Now;
                    while (true)
                    {
                        if (start + TimeSpan.FromSeconds(10) < DateTimeOffset.Now)
                        {
                            throw new Exception("Failed to connect to EventStore");
                        }

                        try
                        {
                            await eventStoreConnection.ConnectAsync().ConfigureAwait(false);

                            break;
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Failed to connect, retrying");
                        }
                    }
                }
            }
            catch (Exception)
            {
                processDisposable.DisposeSafe("Failed to dispose EventStore process");
                throw;
            }

            return(new EventStoreInstance(
                       connectionStringUri,
                       processDisposable));
        }
Esempio n. 2
0
        public void RefusesOverlappedEndPort()
        {
            // arrange
            var factory = Mock.Of <ITcpListenerWrapperFactory>();
            var helper  = new TcpHelper(factory);

            // act and assert
            Assert.Throws <ArgumentOutOfRangeException>("end", () => helper.GetFreePort(IPEndPoint.MaxPort, IPEndPoint.MaxPort - 1));
        }
Esempio n. 3
0
        public static async Task <ElasticsearchInstance> StartAsync()
        {
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("JAVA_HOME")))
            {
                throw new InvalidOperationException("The 'JAVA_HOME' environment variable is required");
            }

            var installedSoftware = await InstallHelper.InstallAsync(SoftwareDescription).ConfigureAwait(false);

            var version     = SoftwareDescription.Version;
            var installPath = Path.Combine(installedSoftware.InstallPath, $"elasticsearch-{version.Major}.{version.Minor}.{version.Build}");

            var tcpPort  = TcpHelper.GetFreePort();
            var exePath  = Path.Combine(installPath, "bin", "elasticsearch.bat");
            var nodeName = $"node-{Guid.NewGuid().ToString("N")}";

            var settings = new Dictionary <string, string>
            {
                { "http.port", tcpPort.ToString() },
                { "node.name", nodeName },
                { "index.number_of_shards", "1" },
                { "index.number_of_replicas", "0" },
                { "gateway.expected_nodes", "1" },
                { "discovery.zen.ping.multicast.enabled", "false" },
                { "cluster.routing.allocation.disk.threshold_enabled", "false" }
            };
            var configFilePath = Path.Combine(installPath, "config", "elasticsearch.yml");

            if (!File.Exists(configFilePath))
            {
                throw new ApplicationException($"Could not find config file at '{configFilePath}'");
            }
            File.WriteAllLines(configFilePath, settings.Select(kv => $"{kv.Key}: {kv.Value}"));

            IDisposable processDisposable = null;

            try
            {
                processDisposable = ProcessHelper.StartExe(exePath,
                                                           $"[${nodeName}] started");

                var elasticsearchInstance = new ElasticsearchInstance(
                    new Uri($"http://127.0.0.1:{tcpPort}"),
                    processDisposable);

                await elasticsearchInstance.WaitForGeenStateAsync().ConfigureAwait(false);

                await elasticsearchInstance.DeleteEverythingAsync().ConfigureAwait(false);

                return(elasticsearchInstance);
            }
            catch (Exception)
            {
                processDisposable.DisposeSafe("Failed to dispose Elasticsearch process");
                throw;
            }
        }
Esempio n. 4
0
        public void GetFreePortThrowsOnEndPortGreaterThanMaxPort()
        {
            // arrange
            var helper = new TcpHelper(TcpListenerWrapperFactory.Default);
            var end    = IPEndPoint.MaxPort + 1;

            // act
            void action() => helper.GetFreePort(1, IPEndPoint.MaxPort + 1);

            // assert
            Assert.Throws <ArgumentOutOfRangeException>(nameof(end), action);
        }
Esempio n. 5
0
        public void ThrowsOnNoFreePort()
        {
            // arrange
            var factory = Mock.Of <ITcpListenerWrapperFactory>();

            Mock.Get(factory).Setup(x => x.Create(1, true).Start()).Throws(new SocketException());
            Mock.Get(factory).Setup(x => x.Create(2, true).Start()).Throws(new SocketException());
            Mock.Get(factory).Setup(x => x.Create(3, true).Start()).Throws(new SocketException());

            var helper = new TcpHelper(factory);

            // act and assert
            var error = Assert.Throws <InvalidOperationException>(() => helper.GetFreePort(1, 3));

            Assert.Equal(Resources.Exception_ThereAreNoFreePortsWithinTheInputRange, error.Message);
        }
Esempio n. 6
0
        public PluginManagementService(
            ILogger logger,
            IRestClient restClient,
            IPluginInstaller pluginInstaller,
            IPluginLoader pluginLoader,
            IPluginHttpApi pluginHttpApi)
        {
            _logger          = logger;
            _restClient      = restClient;
            _pluginInstaller = pluginInstaller;
            _pluginLoader    = pluginLoader;
            _pluginHttpApi   = pluginHttpApi;

            _serverPort   = TcpHelper.GetFreePort();
            _pluginApiUri = new Uri($"http://127.0.0.1:{_serverPort}/");
        }
Esempio n. 7
0
        private async Task <IPluginProxy> InternalLoadPluginAsync(PluginPath pluginPath, Uri pluginApiUri, CancellationToken cancellationToken)
        {
            var pluginId = pluginPath.GetPluginId();
            var token    = Token.NewFor(pluginId);

            using (_logger.Time($"Loading plugin '{pluginId}'"))
            {
                var appDomainSetup = new AppDomainSetup
                {
                    ShadowCopyFiles    = "true",
                    LoaderOptimization = LoaderOptimization.MultiDomain,
                };
                var configFilePath = $"{pluginPath.Value}.config";
                if (File.Exists(configFilePath))
                {
                    appDomainSetup.ConfigurationFile = configFilePath;
                }

                var appDomain = _appDomainManager.CreateDomain(pluginId.Value, null, appDomainSetup);

                var pluginHost     = appDomain.CreateInstanceAndUnwrap(Assembly.GetAssembly(typeof(PluginHostClient)).FullName, typeof(PluginHostClient).ToString()) as PluginHostClient;
                var autoResetEvent = new AutoResetEvent(false);
                var clientPort     = TcpHelper.GetFreePort();

                try
                {
                    pluginHost.Launch(pluginPath.Value, appDomain, pluginApiUri, clientPort, token.Value);
                    autoResetEvent.Set();
                }
                catch (Exception e)
                {
                    _logger.Error(e, $"Plugin '{pluginId}' failed");
                    AppDomain.Unload(appDomain);
                    throw;
                }

                var pluginProxy = new PluginProxy(
                    pluginId,
                    appDomain,
                    new Plugin(_logger, new Uri($"http://127.0.0.1:{clientPort}"),
                               _restClient));

                await pluginProxy.Plugin.PingAsync(cancellationToken).ConfigureAwait(false);

                return(pluginProxy);
            }
        }
Esempio n. 8
0
        public void GetsFirstFreePortWithSingleParameter()
        {
            // arrange
            var factory = Mock.Of <ITcpListenerWrapperFactory>();

            Mock.Get(factory).Setup(x => x.Create(1, true).Start()).Throws(new SocketException());
            Mock.Get(factory).Setup(x => x.Create(2, true).Start()).Throws(new SocketException());
            Mock.Get(factory).Setup(x => x.Create(3, true).Stop()).Throws(new SocketException());

            var helper = new TcpHelper(factory);

            // act
            var port = helper.GetFreePort(1);

            // assert
            Assert.Equal(3, port);
        }