예제 #1
0
        public void GivenUnsecuredAccessSetInCliArgsRemoveItAfterSetupIfRunOnDocker()
        {
            // ARRANGE
            var args = new string[]
            {
                "--Security.UnsecuredAccessAllowed=PublicNetwork"
            };

            var          oldEnv                = Environment.GetEnvironmentVariables();
            const string RavenInDocker         = "RAVEN_IN_DOCKER";
            const string RemoveUnsecuredCliArg = "REMOVE_UNSECURED_CLI_ARG_AFTER_RESTART";

            string[] updatedArgs;
            try
            {
                Environment.SetEnvironmentVariable(RavenInDocker, "true");
                Environment.SetEnvironmentVariable(RemoveUnsecuredCliArg, "true");

                var confBeforeRestart = RavenConfiguration.CreateForServer(null);

                var newConf = RavenConfiguration.CreateForServer(null);

                // ACT
                updatedArgs = PostSetupCliArgumentsUpdater.Process(args, confBeforeRestart, newConf);
            }
            finally
            {
                Environment.SetEnvironmentVariable(RavenInDocker, oldEnv[RavenInDocker] as string);
                Environment.SetEnvironmentVariable(RemoveUnsecuredCliArg, oldEnv[RemoveUnsecuredCliArg] as string);
            }

            // ASSERT
            Assert.True(updatedArgs.Length == 0);
        }
예제 #2
0
        public void Default_database_path_settings()
        {
            var config = RavenConfiguration.CreateForTesting("foo", ResourceType.Database, _emptySettingFile);

            config.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");

            config.Initialize();

            Assert.Equal(new PathSetting("Databases/foo").FullPath, config.Core.DataDirectory.FullPath);
            Assert.Equal(new PathSetting("Databases/foo/Indexes").FullPath, config.Indexing.StoragePath.FullPath);

            Assert.Null(config.Indexing.TempPath);

            Assert.Null(config.Storage.TempPath);

            // actual configuration is created in the following manner

            config = RavenConfiguration.CreateForDatabase(RavenConfiguration.CreateForServer(null, _emptySettingFile), "foo");

            config.Initialize();

            Assert.Equal(new PathSetting("Databases/foo").FullPath, config.Core.DataDirectory.FullPath);
            Assert.Equal(new PathSetting("Databases/foo/Indexes").FullPath, config.Indexing.StoragePath.FullPath);

            Assert.Null(config.Indexing.TempPath);

            Assert.Null(config.Storage.TempPath);
        }
예제 #3
0
        public void Resource_specific_paths_do_not_require_any_suffixes()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), $@"{_rootPathString}Deployment");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Storage.TempPath), $@"{_rootPathString}temp");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Indexing.TempPath), $@"{_rootPathString}indexes-temp");

            server.Initialize();

            var database = RavenConfiguration.CreateForDatabase(server, "Foo");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), $@"{_rootPathString}MyDatabase");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Storage.TempPath), $@"{_rootPathString}my-temp-path");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Indexing.TempPath), $@"{_rootPathString}my-indexes-temp");

            database.Initialize();

            Assert.Equal(new PathSetting($@"{_rootPathString}MyDatabase").FullPath, database.Core.DataDirectory.FullPath);

            Assert.Equal(new PathSetting($@"{_rootPathString}my-temp-path").FullPath, database.Storage.TempPath.FullPath);

            Assert.Equal(new PathSetting($@"{_rootPathString}my-indexes-temp").FullPath, database.Indexing.TempPath.FullPath);
        }
예제 #4
0
        protected RachisConsensus <CountingStateMachine> SetupServer(bool bootstrap = false, int port = 0, int electionTimeout = 300, [CallerMemberName] string caller = null)
        {
            var tcpListener = new TcpListener(IPAddress.Loopback, port);

            tcpListener.Start();
            char ch;

            if (bootstrap)
            {
                ch = (char)65;
            }
            else
            {
                ch = (char)(65 + Interlocked.Increment(ref _count));
            }

            var url = $"tcp://localhost:{((IPEndPoint)tcpListener.LocalEndpoint).Port}/?{caller}#{ch}";

            var server = StorageEnvironmentOptions.CreateMemoryOnly();

            int seed          = PredictableSeeds ? _random.Next(int.MaxValue) : (int)Interlocked.Read(ref _count);
            var configuration = RavenConfiguration.CreateForServer(caller);

            configuration.Initialize();
            configuration.Core.RunInMemory        = true;
            configuration.Core.PublicServerUrl    = new UriSetting($"http://localhost:{((IPEndPoint)tcpListener.LocalEndpoint).Port}");
            configuration.Cluster.ElectionTimeout = new TimeSetting(electionTimeout, TimeUnit.Milliseconds);
            var serverStore = new RavenServer(configuration)
            {
                ThrowOnLicenseActivationFailure = true
            }.ServerStore;

            serverStore.Initialize();
            var rachis             = new RachisConsensus <CountingStateMachine>(serverStore, seed);
            var storageEnvironment = new StorageEnvironment(server);

            rachis.Initialize(storageEnvironment, configuration, configuration.Core.ServerUrls[0], out _);
            rachis.OnDispose += (sender, args) =>
            {
                serverStore.Dispose();
                storageEnvironment.Dispose();
            };
            if (bootstrap)
            {
                rachis.Bootstrap(url, "A");
            }

            rachis.Url = url;
            _listeners.Add(tcpListener);
            RachisConsensuses.Add(rachis);
            var task = AcceptConnection(tcpListener, rachis);

            return(rachis);
        }
예제 #5
0
 public void GivenNonExistingFileAsCustomConfigPathConfigurationLoadingShouldThrow()
 {
     try
     {
         var configuration = RavenConfiguration.CreateForServer(null, "thisIsANonExistentSettingsFile.json");
         throw new Exception("Configuration loading should have thrown.");
     }
     catch (FileNotFoundException exc)
     {
         Assert.Equal("Custom configuration file has not been found.", exc.Message);
     }
 }
예제 #6
0
        public void IfConfigurationKeyIsStringArrayThenItShouldSupportValuesWithSemicolonPropely()
        {
            var configuration = RavenConfiguration.CreateForServer("Foo");

            configuration.SetSetting(RavenConfiguration.GetKey(x => x.Core.ServerUrls), "http://123.123.123.123:10105;http://123.123.123.124:10105");
            configuration.SetSetting(RavenConfiguration.GetKey(x => x.Core.PublicServerUrl), "http://public.url.com");
            configuration.Initialize();

            Assert.NotNull(configuration.Core.ServerUrls);
            Assert.Equal(2, configuration.Core.ServerUrls.Length);
            Assert.Contains("http://123.123.123.123:10105", configuration.Core.ServerUrls);
            Assert.Contains("http://123.123.123.124:10105", configuration.Core.ServerUrls);
        }
예제 #7
0
        protected virtual RavenServer GetNewServer(IDictionary <string, string> customSettings = null, bool deletePrevious = true, bool runInMemory = true, string partialPath = null, string customConfigPath = null)
        {
            lock (_getNewServerSync)
            {
                var configuration = RavenConfiguration.CreateForServer(Guid.NewGuid().ToString(), customConfigPath);

                configuration.SetSetting(RavenConfiguration.GetKey(x => x.Replication.ReplicationMinimalHeartbeat), "1");
                configuration.SetSetting(RavenConfiguration.GetKey(x => x.Replication.RetryReplicateAfter), "3");
                configuration.SetSetting(RavenConfiguration.GetKey(x => x.Cluster.AddReplicaTimeout), "10");

                if (customSettings != null)
                {
                    foreach (var setting in customSettings)
                    {
                        configuration.SetSetting(setting.Key, setting.Value);
                    }
                }

                configuration.Initialize();
                configuration.Logs.Mode = LogMode.None;
                if (customSettings == null || customSettings.ContainsKey(RavenConfiguration.GetKey(x => x.Core.ServerUrls)) == false)
                {
                    configuration.Core.ServerUrls = new[] { "http://127.0.0.1:0" };
                }
                configuration.Server.Name        = ServerName;
                configuration.Core.RunInMemory   = runInMemory;
                configuration.Core.DataDirectory =
                    configuration.Core.DataDirectory.Combine(partialPath ?? $"Tests{Interlocked.Increment(ref _serverCounter)}");
                configuration.Server.MaxTimeForTaskToWaitForDatabaseToLoad = new TimeSetting(60, TimeUnit.Seconds);
                configuration.Licensing.EulaAccepted = true;
                if (customSettings == null || customSettings.ContainsKey(RavenConfiguration.GetKey(x => x.Core.FeaturesAvailability)) == false)
                {
                    configuration.Core.FeaturesAvailability = FeaturesAvailability.Experimental;
                }

                if (deletePrevious)
                {
                    IOExtensions.DeleteDirectory(configuration.Core.DataDirectory.FullPath);
                }

                var server = new RavenServer(configuration)
                {
                    ThrowOnLicenseActivationFailure = true
                };
                server.Initialize();
                server.ServerStore.ValidateFixedPort = false;

                return(server);
            }
        }
예제 #8
0
        public RavenConfiguration GetConfiguration(string serverUrl = null, string tcpServerUrl = null, string certPath = null)
        {
            var configuration = RavenConfiguration.CreateForServer(null);

            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.ServerUrls), serverUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.TcpServerUrls), tcpServerUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Security.CertificatePath), certPath);

            configuration.Initialize();

            return(configuration);
        }
예제 #9
0
        public void CanParseNestedJsonObjectsFromSettingsJsonFile()
        {
            DoNotReuseServer();

            string settingsJsonFile = default;

            try
            {
                const string jsonWithNestedContent = @"{
                                                         ""ETL.MaxBatchSizeInMb"":77,
                                                         ""ETL"":
                                                         {
                                                            ""MaxNumberOfExtractedItems"":222,
                                                            ""MaxNumberOfExtractedDocuments"":333
                                                         },
                                                         ""ETL"":
                                                         {
                                                            ""SQL"":
                                                            {
                                                               ""CommandTimeoutInSec"":444
                                                            }
                                                         }
                                                      }";

                settingsJsonFile = Path.Combine($"{Path.GetDirectoryName(GetTempFileName())}", "settings.json");
                File.WriteAllText(settingsJsonFile, jsonWithNestedContent);

                var serverConfig = RavenConfiguration.CreateForServer(null, settingsJsonFile);
                serverConfig.Initialize();

                var databaseConfig = RavenConfiguration.CreateForDatabase(serverConfig, "dbName");
                databaseConfig.Initialize();

                Assert.Equal("77 MBytes", serverConfig.Etl.MaxBatchSize.ToString());
                Assert.Equal(222, serverConfig.Etl.MaxNumberOfExtractedItems);
                Assert.Equal(333, serverConfig.Etl.MaxNumberOfExtractedDocuments);
                Assert.Equal(444, serverConfig.Etl.SqlCommandTimeout.Value.GetValue(TimeUnit.Seconds));

                Assert.Equal("77 MBytes", databaseConfig.Etl.MaxBatchSize.ToString());
                Assert.Equal(222, databaseConfig.Etl.MaxNumberOfExtractedItems);
                Assert.Equal(333, databaseConfig.Etl.MaxNumberOfExtractedDocuments);
                Assert.Equal(444, databaseConfig.Etl.SqlCommandTimeout.Value.GetValue(TimeUnit.Seconds));
            }
            finally
            {
                File.Delete(settingsJsonFile);
            }
        }
예제 #10
0
        protected RachisConsensus <CountingStateMachine> SetupServer(bool bootstrap = false, int port = 0, int electionTimeout = 300, [CallerMemberName] string caller = null)
        {
            var tcpListener = new TcpListener(IPAddress.Loopback, port);

            tcpListener.Start();
            var ch = (char)(66 + _count++);

            if (bootstrap)
            {
                ch = (char)65;
                _count--;
            }

            var url = "tcp://localhost:" + ((IPEndPoint)tcpListener.LocalEndpoint).Port + "/?" + caller + "#" + ch;

            var server = StorageEnvironmentOptions.CreateMemoryOnly();

            int seed          = PredictableSeeds ? _random.Next(int.MaxValue) : _count;
            var configuration = RavenConfiguration.CreateForServer(caller);

            configuration.Initialize();
            configuration.Core.RunInMemory        = true;
            configuration.Cluster.ElectionTimeout = new TimeSetting(electionTimeout, TimeUnit.Milliseconds);
            var serverStore = new RavenServer(configuration).ServerStore;

            serverStore.Initialize();
            var rachis             = new RachisConsensus <CountingStateMachine>(serverStore, seed);
            var storageEnvironment = new StorageEnvironment(server);

            rachis.Initialize(storageEnvironment, configuration, configuration.Core.ServerUrls[0]);
            rachis.OnDispose += (sender, args) =>
            {
                serverStore.Dispose();
                storageEnvironment.Dispose();
            };
            if (bootstrap)
            {
                rachis.Bootstrap(url);
            }

            rachis.Url = url;
            _listeners.Add(tcpListener);
            RachisConsensuses.Add(rachis);
            var task = AcceptConnection(tcpListener, rachis);

            return(rachis);
        }
예제 #11
0
        public void ShouldWork()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Storage.ForceUsing32BitsPager), "true");
            server.Initialize(); // should not throw

            Assert.True(server.Storage.ForceUsing32BitsPager);

            var database = RavenConfiguration.CreateForDatabase(server, "dbName");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Storage.ForceUsing32BitsPager), "true");

            var e = Assert.Throws <InvalidOperationException>(() => database.Initialize());

            Assert.Equal($"Configuration '{RavenConfiguration.GetKey(x => x.Storage.ForceUsing32BitsPager)}' can only be set at server level.", e.Message);
        }
예제 #12
0
        private static void Validate(string key)
        {
            Environment.SetEnvironmentVariable(key, LogMode.Information.ToString());

            try
            {
                var configuration = RavenConfiguration.CreateForServer("test");

                configuration.Initialize();

                Assert.Equal(LogMode.Information, configuration.Logs.Mode);
            }
            finally
            {
                Environment.SetEnvironmentVariable(key, null);
            }
        }
예제 #13
0
        public void Null_path_database_setting_should_default_to_server_value()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), "/mnt/Raven/Data");

            server.Initialize();

            var database = RavenConfiguration.CreateForDatabase(server, "foo");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), null);

            database.Initialize();

            Assert.Equal(new PathSetting("/mnt/Raven/Data/Databases/foo").FullPath, database.Core.DataDirectory.FullPath);
            Assert.Equal(new PathSetting("/mnt/Raven/Data/Databases/foo/Indexes").FullPath, database.Indexing.StoragePath.FullPath);
        }
예제 #14
0
        public void Should_create_data_in_directory_specified_at_server_level()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), $@"{_rootPathString}RavenData");

            server.Initialize();

            var database = RavenConfiguration.CreateForDatabase(server, "Foo");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), @"Items");

            database.Initialize();

            Assert.Equal(new PathSetting($@"{_rootPathString}RavenData\Items").FullPath, database.Core.DataDirectory.FullPath);
        }
예제 #15
0
        public void Database_creation_using_relative_path_creates_directories_incorrectly()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");
            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), "RavenData");

            server.Initialize();

            var database = RavenConfiguration.CreateForDatabase(server, "foo");

            database.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");
            database.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), @"MyWork\MyDatabaseFolder");

            database.Initialize();

            Assert.Equal(new PathSetting("RavenData/MyWork/MyDatabaseFolder").FullPath, database.Core.DataDirectory.FullPath);
            Assert.Equal(new PathSetting("RavenData/MyWork/MyDatabaseFolder/Indexes").FullPath, database.Indexing.StoragePath.FullPath);
        }
예제 #16
0
        public RavenConfiguration GetConfiguration(string publicServerUrl = null, string publicTcpServerUrl = null, string serverUrl = null, string tcpServerUrl = null, string certPath = null, string unsecuredAccessAddressRange = nameof(UnsecuredAccessAddressRange.Local))
        {
            var configuration = RavenConfiguration.CreateForServer(null);

            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.ServerUrls), serverUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.PublicServerUrl), publicServerUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.PublicTcpServerUrl), publicTcpServerUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Core.TcpServerUrls), tcpServerUrl);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Security.CertificatePath), certPath);
            configuration.SetSetting(
                RavenConfiguration.GetKey(x => x.Security.UnsecuredAccessAllowed), unsecuredAccessAddressRange);
            configuration.Initialize();

            return(configuration);
        }
예제 #17
0
        public void Restart()
        {
            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Restarting RavenDB Windows Service: {ServiceName}.");
            }

            _ravenServer.Dispose();
            var configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

            if (_args != null)
            {
                configuration.AddCommandLine(_args);
            }

            configuration.Initialize();
            _ravenServer = new RavenServer(configuration);
            Start(_args, _serviceStoppedCallback);

            configuration.Initialize();
        }
예제 #18
0
        public void GivenServerUrlCliArgAndSecuredSetupSchemeShouldBeUpdatedAfterRestart()
        {
            // ARRANGE
            var args = new string[]
            {
                "--ServerUrl=http://0.0.0.0:8080"
            };

            var confBeforeRestart = RavenConfiguration.CreateForServer(null);

            confBeforeRestart.Core.ServerUrls = new[] { "http://0.0.0.0:8080" };

            var newConf = RavenConfiguration.CreateForServer(null);

            newConf.SetSetting("ServerUrl", "https://127.0.0.1:9090");

            // ACT
            var updatedArgs = PostSetupCliArgumentsUpdater.Process(args, confBeforeRestart, newConf);

            // ASSERT
            Assert.Equal("--ServerUrl=https://0.0.0.0:8080", updatedArgs[0]);
        }
예제 #19
0
        public void Inherits_server_settings_and_appends_resource_specific_suffix_paths()
        {
            var server = RavenConfiguration.CreateForServer(null);

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.RunInMemory), "true");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Core.DataDirectory), $@"{_rootPathString}Deployment");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Storage.TempPath), $@"{_rootPathString}temp");

            server.SetSetting(RavenConfiguration.GetKey(x => x.Indexing.TempPath), $@"{_rootPathString}indexes-temp");

            server.Initialize();

            var database = RavenConfiguration.CreateForDatabase(server, "Foo");

            database.Initialize();

            Assert.Equal(new PathSetting($@"{_rootPathString}Deployment\Databases\Foo").FullPath, database.Core.DataDirectory.FullPath);

            Assert.Equal(new PathSetting($@"{_rootPathString}temp\Databases\Foo").FullPath, database.Storage.TempPath.FullPath);

            Assert.Equal(new PathSetting($@"{_rootPathString}indexes-temp\Databases\Foo").FullPath, database.Indexing.TempPath.FullPath);
        }
예제 #20
0
        public static int Main(string[] args)
        {
            UseOnlyInvariantCultureInRavenDB();

            SetCurrentDirectoryToServerPath();

            string[] configurationArgs;
            try
            {
                configurationArgs = CommandLineSwitches.Process(args);
            }
            catch (CommandParsingException commandParsingException)
            {
                Console.WriteLine(commandParsingException.Message);
                CommandLineSwitches.ShowHelp();
                return(1);
            }

            if (CommandLineSwitches.ShouldShowHelp)
            {
                CommandLineSwitches.ShowHelp();
                return(0);
            }

            if (CommandLineSwitches.PrintVersionAndExit)
            {
                Console.WriteLine(ServerVersion.FullVersion);
                return(0);
            }

            new WelcomeMessage(Console.Out).Print();

            var targetSettingsFile = new PathSetting(string.IsNullOrEmpty(CommandLineSwitches.CustomConfigPath)
                ? "settings.json"
                : CommandLineSwitches.CustomConfigPath);

            var destinationSettingsFile = new PathSetting("settings.default.json");

            if (File.Exists(targetSettingsFile.FullPath) == false &&
                File.Exists(destinationSettingsFile.FullPath)) //just in case
            {
                File.Copy(destinationSettingsFile.FullPath, targetSettingsFile.FullPath);
            }

            var configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

            if (configurationArgs != null)
            {
                configuration.AddCommandLine(configurationArgs);
            }

            configuration.Initialize();

            LoggingSource.Instance.SetupLogMode(configuration.Logs.Mode, configuration.Logs.Path.FullPath);
            LoggingSource.UseUtcTime = configuration.Logs.UseUtcTime;

            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Logging to {configuration.Logs.Path} set to {configuration.Logs.Mode} level.");
            }

            if (Logger.IsOperationsEnabled)
            {
                Logger.Operations(RavenCli.GetInfoText());
            }

            if (WindowsServiceRunner.ShouldRunAsWindowsService())
            {
                try
                {
                    WindowsServiceRunner.Run(CommandLineSwitches.ServiceName, configuration, configurationArgs);
                }
                catch (Exception e)
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Error running Windows Service", e);
                    }

                    return(1);
                }

                return(0);
            }

            RestartServer = () =>
            {
                ResetServerMre.Set();
                ShutdownServerMre.Set();
            };

            var rerun = false;
            RavenConfiguration configBeforeRestart = configuration;

            do
            {
                if (rerun)
                {
                    Console.WriteLine("\nRestarting Server...");
                    rerun = false;

                    configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

                    if (configurationArgs != null)
                    {
                        var argsAfterRestart = PostSetupCliArgumentsUpdater.Process(
                            configurationArgs, configBeforeRestart, configuration);

                        configuration.AddCommandLine(argsAfterRestart);
                        configBeforeRestart = configuration;
                    }

                    configuration.Initialize();
                }

                try
                {
                    using (var server = new RavenServer(configuration))
                    {
                        try
                        {
                            try
                            {
                                server.OpenPipes();
                            }
                            catch (Exception e)
                            {
                                if (Logger.IsInfoEnabled)
                                {
                                    Logger.Info("Unable to OpenPipe. Admin Channel will not be available to the user", e);
                                }
                                Console.WriteLine("Warning: Admin Channel is not available:" + e);
                            }

                            server.Initialize();

                            if (CommandLineSwitches.PrintServerId)
                            {
                                Console.WriteLine($"Server ID is {server.ServerStore.GetServerId()}.");
                            }

                            new RuntimeSettings(Console.Out).Print();

                            if (CommandLineSwitches.LaunchBrowser)
                            {
                                BrowserHelper.OpenStudioInBrowser(server.ServerStore.GetNodeHttpServerUrl());
                            }

                            new ClusterMessage(Console.Out, server.ServerStore).Print();

                            var prevColor = Console.ForegroundColor;
                            Console.Write("Server available on: ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{server.ServerStore.GetNodeHttpServerUrl()}");
                            Console.ForegroundColor = prevColor;

                            var tcpServerStatus = server.GetTcpServerStatus();
                            prevColor = Console.ForegroundColor;
                            Console.Write("Tcp listening on ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{string.Join(", ", tcpServerStatus.Listeners.Select(l => l.LocalEndpoint))}");
                            Console.ForegroundColor = prevColor;

                            Console.WriteLine("Server started, listening to requests...");

                            prevColor = Console.ForegroundColor;
                            Console.ForegroundColor = ConsoleColor.DarkGray;
                            Console.WriteLine("TIP: type 'help' to list the available commands.");
                            Console.ForegroundColor = prevColor;

                            IsRunningNonInteractive = false;
                            rerun = CommandLineSwitches.NonInteractive ||
                                    configuration.Core.SetupMode == SetupMode.Initial
                                ? RunAsNonInteractive()
                                : RunInteractive(server);

                            Console.WriteLine("Starting shut down...");
                            if (Logger.IsInfoEnabled)
                            {
                                Logger.Info("Server is shutting down");
                            }
                        }
                        catch (Exception e)
                        {
                            string message = null;
                            if (e.InnerException is AddressInUseException)
                            {
                                message =
                                    $"{Environment.NewLine}Port might be already in use.{Environment.NewLine}Try running with an unused port.{Environment.NewLine}" +
                                    $"You can change the port using one of the following options:{Environment.NewLine}" +
                                    $"1) Change the ServerUrl property in setting.json file.{Environment.NewLine}" +
                                    $"2) Run the server from the command line with --ServerUrl option.{Environment.NewLine}" +
                                    $"3) Add RAVEN_ServerUrl to the Environment Variables.{Environment.NewLine}" +
                                    "For more information go to https://ravendb.net/l/EJS81M/4.1";
                            }
                            else if (e is SocketException && PlatformDetails.RunningOnPosix)
                            {
                                var ravenPath = typeof(RavenServer).Assembly.Location;
                                if (ravenPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                                {
                                    ravenPath = ravenPath.Substring(ravenPath.Length - 4);
                                }

                                message =
                                    $"{Environment.NewLine}In Linux low-level port (below 1024) will need a special permission, " +
                                    $"if this is your case please run{Environment.NewLine}" +
                                    $"sudo setcap CAP_NET_BIND_SERVICE=+eip {ravenPath}";
                            }

                            if (Logger.IsOperationsEnabled)
                            {
                                Logger.Operations("Failed to initialize the server", e);
                                Logger.Operations(message);
                            }

                            Console.WriteLine(message);

                            Console.WriteLine();

                            Console.WriteLine(e);

                            return(-1);
                        }
                    }

                    Console.WriteLine("Shutdown completed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error during shutdown");
                    Console.WriteLine(e);
                    return(-2);
                }
                finally
                {
                    if (Logger.IsOperationsEnabled)
                    {
                        Logger.OperationsAsync("Server has shut down").Wait(TimeSpan.FromSeconds(15));
                    }
                }
            } while (rerun);

            return(0);
        }
예제 #21
0
        public static int Main(string[] args)
        {
            UseOnlyInvariantCultureInRavenDB();

            SetCurrentDirectoryToServerPath();

            string[] configurationArgs;
            try
            {
                configurationArgs = CommandLineSwitches.Process(args);
            }
            catch (CommandParsingException commandParsingException)
            {
                Console.WriteLine(commandParsingException.Message);
                CommandLineSwitches.ShowHelp();
                return(1);
            }

            if (CommandLineSwitches.ShouldShowHelp)
            {
                CommandLineSwitches.ShowHelp();
                return(0);
            }

            if (CommandLineSwitches.PrintVersionAndExit)
            {
                Console.WriteLine(ServerVersion.FullVersion);
                return(0);
            }

            new WelcomeMessage(Console.Out).Print();

            var targetSettingsFile = new PathSetting(string.IsNullOrEmpty(CommandLineSwitches.CustomConfigPath)
                ? "settings.json"
                : CommandLineSwitches.CustomConfigPath);

            var destinationSettingsFile = new PathSetting("settings.default.json");

            if (File.Exists(targetSettingsFile.FullPath) == false &&
                File.Exists(destinationSettingsFile.FullPath)) //just in case
            {
                File.Copy(destinationSettingsFile.FullPath, targetSettingsFile.FullPath);
            }

            var configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

            if (configurationArgs != null)
            {
                configuration.AddCommandLine(configurationArgs);
            }

            configuration.Initialize();

            LoggingSource.Instance.SetupLogMode(configuration.Logs.Mode, configuration.Logs.Path.FullPath);
            LoggingSource.UseUtcTime = configuration.Logs.UseUtcTime;

            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Logging to {configuration.Logs.Path} set to {configuration.Logs.Mode} level.");
            }

            if (Logger.IsOperationsEnabled)
            {
                Logger.Operations(RavenCli.GetInfoText());
            }

            if (WindowsServiceRunner.ShouldRunAsWindowsService())
            {
                try
                {
                    WindowsServiceRunner.Run(CommandLineSwitches.ServiceName, configuration, configurationArgs);
                }
                catch (Exception e)
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Error running Windows Service", e);
                    }

                    return(1);
                }

                return(0);
            }

            RestartServer = () =>
            {
                ResetServerMre.Set();
                ShutdownServerMre.Set();
            };

            var rerun = false;
            RavenConfiguration configBeforeRestart = configuration;

            do
            {
                if (rerun)
                {
                    Console.WriteLine("\nRestarting Server...");
                    rerun = false;

                    configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

                    if (configurationArgs != null)
                    {
                        var argsAfterRestart = PostSetupCliArgumentsUpdater.Process(
                            configurationArgs, configBeforeRestart, configuration);

                        configuration.AddCommandLine(argsAfterRestart);
                        configBeforeRestart = configuration;
                    }

                    configuration.Initialize();
                }

                try
                {
                    using (var server = new RavenServer(configuration))
                    {
                        try
                        {
                            try
                            {
                                server.OpenPipes();
                            }
                            catch (Exception e)
                            {
                                if (Logger.IsInfoEnabled)
                                {
                                    Logger.Info("Unable to OpenPipe. Admin Channel will not be available to the user", e);
                                }
                                Console.WriteLine("Warning: Admin Channel is not available:" + e);
                            }

                            server.Initialize();

                            if (CommandLineSwitches.PrintServerId)
                            {
                                Console.WriteLine($"Server ID is {server.ServerStore.GetServerId()}.");
                            }

                            new RuntimeSettings(Console.Out).Print();

                            if (CommandLineSwitches.LaunchBrowser)
                            {
                                BrowserHelper.OpenStudioInBrowser(server.ServerStore.GetNodeHttpServerUrl());
                            }

                            new ClusterMessage(Console.Out, server.ServerStore).Print();

                            var prevColor = Console.ForegroundColor;
                            Console.Write("Server available on: ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{server.ServerStore.GetNodeHttpServerUrl()}");
                            Console.ForegroundColor = prevColor;

                            var tcpServerStatus = server.GetTcpServerStatus();
                            prevColor = Console.ForegroundColor;
                            Console.Write("Tcp listening on ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{string.Join(", ", tcpServerStatus.Listeners.Select(l => l.LocalEndpoint))}");
                            Console.ForegroundColor = prevColor;

                            Console.WriteLine("Server started, listening to requests...");

                            prevColor = Console.ForegroundColor;
                            Console.ForegroundColor = ConsoleColor.DarkGray;
                            Console.WriteLine("TIP: type 'help' to list the available commands.");
                            Console.ForegroundColor = prevColor;

                            IsRunningNonInteractive = false;
                            rerun = CommandLineSwitches.NonInteractive ||
                                    configuration.Core.SetupMode == SetupMode.Initial
                                ? RunAsNonInteractive()
                                : RunInteractive(server);

                            Console.WriteLine("Starting shut down...");
                            if (Logger.IsInfoEnabled)
                            {
                                Logger.Info("Server is shutting down");
                            }
                        }
                        catch (Exception e)
                        {
                            if (Logger.IsOperationsEnabled)
                            {
                                Logger.Operations("Failed to initialize the server", e);
                            }
                            Console.WriteLine(e);

                            return(-1);
                        }
                    }

                    Console.WriteLine("Shutdown completed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error during shutdown");
                    Console.WriteLine(e);
                    return(-2);
                }
                finally
                {
                    if (Logger.IsOperationsEnabled)
                    {
                        Logger.OperationsAsync("Server has shut down").Wait(TimeSpan.FromSeconds(15));
                    }
                }
            } while (rerun);

            return(0);
        }
예제 #22
0
        public static unsafe int Main(string[] args)
        {
            NativeMemory.GetCurrentUnmanagedThreadId = () => (ulong)Pal.rvn_get_current_thread_id();

            Lucene.Net.Util.UnmanagedStringArray.Segment.AllocateMemory = NativeMemory.AllocateMemory;
            Lucene.Net.Util.UnmanagedStringArray.Segment.FreeMemory     = NativeMemory.Free;

            UseOnlyInvariantCultureInRavenDB();

            SetCurrentDirectoryToServerPath();

            string[] configurationArgs;
            try
            {
                configurationArgs = CommandLineSwitches.Process(args);
            }
            catch (CommandParsingException commandParsingException)
            {
                Console.WriteLine(commandParsingException.Message);
                CommandLineSwitches.ShowHelp();
                return(1);
            }

            if (CommandLineSwitches.ShouldShowHelp)
            {
                CommandLineSwitches.ShowHelp();
                return(0);
            }

            if (CommandLineSwitches.PrintVersionAndExit)
            {
                Console.WriteLine(ServerVersion.FullVersion);
                return(0);
            }

            new WelcomeMessage(Console.Out).Print();

            var targetSettingsFile = new PathSetting(string.IsNullOrEmpty(CommandLineSwitches.CustomConfigPath)
                ? "settings.json"
                : CommandLineSwitches.CustomConfigPath);

            var destinationSettingsFile = new PathSetting("settings.default.json");

            if (File.Exists(targetSettingsFile.FullPath) == false &&
                File.Exists(destinationSettingsFile.FullPath)) //just in case
            {
                File.Copy(destinationSettingsFile.FullPath, targetSettingsFile.FullPath);
            }

            var configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

            if (configurationArgs != null)
            {
                configuration.AddCommandLine(configurationArgs);
            }

            configuration.Initialize();

            EncryptionBuffersPool.Instance.Disabled = configuration.Storage.DisableEncryptionBuffersPooling;

            LoggingSource.UseUtcTime = configuration.Logs.UseUtcTime;
            LoggingSource.Instance.MaxFileSizeInBytes = configuration.Logs.MaxFileSize.GetValue(SizeUnit.Bytes);
            LoggingSource.Instance.SetupLogMode(
                configuration.Logs.Mode,
                configuration.Logs.Path.FullPath,
                configuration.Logs.RetentionTime?.AsTimeSpan,
                configuration.Logs.RetentionSize?.GetValue(SizeUnit.Bytes),
                configuration.Logs.Compress
                );

            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Logging to {configuration.Logs.Path} set to {configuration.Logs.Mode} level.");
            }

            InitializeThreadPoolThreads(configuration);

            MultiSourceNuGetFetcher.Instance.Initialize(configuration.Indexing.NuGetPackagesPath, configuration.Indexing.NuGetPackageSourceUrl);

            LatestVersionCheck.Instance.Initialize(configuration.Updates);

            if (Logger.IsOperationsEnabled)
            {
                Logger.Operations(RavenCli.GetInfoText());
            }

            if (WindowsServiceRunner.ShouldRunAsWindowsService())
            {
                try
                {
                    WindowsServiceRunner.Run(CommandLineSwitches.ServiceName, configuration, configurationArgs);
                }
                catch (Exception e)
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Error running Windows Service", e);
                    }

                    return(1);
                }

                return(0);
            }

            RestartServer = () =>
            {
                RestartServerMre.Set();
                ShutdownServerMre.Set();
            };

            var rerun = false;
            RavenConfiguration configBeforeRestart = configuration;

            do
            {
                if (rerun)
                {
                    Console.WriteLine("\nRestarting Server...");

                    configuration = RavenConfiguration.CreateForServer(null, CommandLineSwitches.CustomConfigPath);

                    if (configurationArgs != null)
                    {
                        var argsAfterRestart = PostSetupCliArgumentsUpdater.Process(
                            configurationArgs, configBeforeRestart, configuration);

                        configuration.AddCommandLine(argsAfterRestart);
                        configBeforeRestart = configuration;
                    }

                    configuration.Initialize();
                }

                try
                {
                    using (var server = new RavenServer(configuration))
                    {
                        try
                        {
                            try
                            {
                                server.OpenPipes();
                            }
                            catch (Exception e)
                            {
                                if (Logger.IsInfoEnabled)
                                {
                                    Logger.Info("Unable to OpenPipe. Admin Channel will not be available to the user", e);
                                }
                                Console.WriteLine("Warning: Admin Channel is not available:" + e);
                            }

                            server.BeforeSchemaUpgrade = x => BeforeSchemaUpgrade(x, server.ServerStore);
                            server.Initialize();

                            if (CommandLineSwitches.PrintServerId)
                            {
                                Console.WriteLine($"Server ID is {server.ServerStore.GetServerId()}.");
                            }

                            new RuntimeSettings(Console.Out).Print();

                            if (rerun == false && CommandLineSwitches.LaunchBrowser)
                            {
                                BrowserHelper.OpenStudioInBrowser(server.ServerStore.GetNodeHttpServerUrl());
                            }

                            new ClusterMessage(Console.Out, server.ServerStore).Print();

                            var prevColor = Console.ForegroundColor;
                            Console.Write("Server available on: ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{server.ServerStore.GetNodeHttpServerUrl()}");
                            Console.ForegroundColor = prevColor;

                            var tcpServerStatus = server.GetTcpServerStatus();
                            if (tcpServerStatus.Listeners.Count > 0)
                            {
                                prevColor = Console.ForegroundColor;
                                Console.Write("Tcp listening on ");
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine($"{string.Join(", ", tcpServerStatus.Listeners.Select(l => l.LocalEndpoint))}");
                                Console.ForegroundColor = prevColor;
                            }

                            Console.WriteLine("Server started, listening to requests...");

                            prevColor = Console.ForegroundColor;
                            Console.ForegroundColor = ConsoleColor.DarkGray;
                            Console.WriteLine("TIP: type 'help' to list the available commands.");
                            Console.ForegroundColor = prevColor;

                            if (configuration.Storage.IgnoreInvalidJournalErrors == true)
                            {
                                var message =
                                    $"Server is running in dangerous mode because {RavenConfiguration.GetKey(x => x.Storage.IgnoreInvalidJournalErrors)} was set. " +
                                    "It means that storages of databases, indexes and system one will be loaded regardless missing or corrupted journal files which " +
                                    "are mandatory to properly load the storage. " +
                                    "This switch is meant to be use only for recovery purposes. Please make sure that you won't use it on regular basis. ";

                                if (Logger.IsOperationsEnabled)
                                {
                                    Logger.Operations(message);
                                }

                                prevColor = Console.ForegroundColor;
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine(message);
                                Console.ForegroundColor = prevColor;
                            }

                            IsRunningNonInteractive = false;
                            rerun = CommandLineSwitches.NonInteractive ||
                                    configuration.Core.SetupMode == SetupMode.Initial
                                ? RunAsNonInteractive()
                                : RunInteractive(server);

                            Console.WriteLine("Starting shut down...");
                            if (Logger.IsInfoEnabled)
                            {
                                Logger.Info("Server is shutting down");
                            }
                        }
                        catch (Exception e)
                        {
                            string message = null;
                            if (e.InnerException is AddressInUseException)
                            {
                                message =
                                    $"{Environment.NewLine}Port might be already in use.{Environment.NewLine}Try running with an unused port.{Environment.NewLine}" +
                                    $"You can change the port using one of the following options:{Environment.NewLine}" +
                                    $"1) Change the ServerUrl property in setting.json file.{Environment.NewLine}" +
                                    $"2) Run the server from the command line with --ServerUrl option.{Environment.NewLine}" +
                                    $"3) Add RAVEN_ServerUrl to the Environment Variables.{Environment.NewLine}" +
                                    "For more information go to https://ravendb.net/l/EJS81M/5.1";
                            }
                            else if (e is SocketException && PlatformDetails.RunningOnPosix)
                            {
                                message =
                                    $"{Environment.NewLine}In Linux low-level port (below 1024) will need a special permission, " +
                                    $"if this is your case please run{Environment.NewLine}" +
                                    $"sudo setcap CAP_NET_BIND_SERVICE=+eip {Path.Combine(AppContext.BaseDirectory, "Raven.Server")}";
                            }
                            else if (e.InnerException is LicenseExpiredException)
                            {
                                message = e.InnerException.Message;
                            }

                            if (Logger.IsOperationsEnabled)
                            {
                                Logger.Operations("Failed to initialize the server", e);
                                Logger.Operations(message);
                            }

                            Console.WriteLine(message);

                            Console.WriteLine();

                            Console.WriteLine(e);

                            return(-1);
                        }
                    }

                    Console.WriteLine("Shutdown completed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error during shutdown");
                    Console.WriteLine(e);
                    return(-2);
                }
                finally
                {
                    if (Logger.IsOperationsEnabled)
                    {
                        Logger.OperationsWithWait("Server has shut down").Wait(TimeSpan.FromSeconds(15));
                    }
                    ShutdownCompleteMre.Set();
                }
            } while (rerun);

            return(0);
        }