Example #1
0
        public static void WriteServerStatsAndWaitForEsc(RavenServer server)
        {
            Console.WriteLine("Showing stats, press any key to close...");
            Console.WriteLine("    working set     | native mem      | managed mem     | mmap size         | reqs/sec       | docs (all dbs)");
            var i = 0;

            while (Console.KeyAvailable == false)
            {
                var stats      = RavenCli.MemoryStatsWithMemoryMappedInfo();
                var reqCounter = server.Metrics.Requests.RequestsPerSec;

                Console.Write($"\r {((i++ % 2) == 0 ? "*" : "+")} ");

                Console.Write($" {stats.WorkingSet,-14} ");
                Console.Write($" | {stats.TotalUnmanagedAllocations,-14} ");
                Console.Write($" | {stats.ManagedMemory,-14} ");
                Console.Write($" | {stats.TotalMemoryMapped,-17} ");

                Console.Write($"| {Math.Round(reqCounter.OneSecondRate, 1),-14:#,#.#;;0} ");

                long allDocs = 0;
                foreach (var value in server.ServerStore.DatabasesLandlord.DatabasesCache.Values)
                {
                    if (value.Status != TaskStatus.RanToCompletion)
                    {
                        continue;
                    }

                    try
                    {
                        allDocs += value.Result.DocumentsStorage.GetNumberOfDocuments();
                    }
                    catch (Exception)
                    {
                        // may run out of virtual address space, or just shutdown, etc
                    }
                }

                Console.Write($"| {allDocs,14:#,#.#;;0}      ");

                for (int j = 0; j < 5 && Console.KeyAvailable == false; j++)
                {
                    Thread.Sleep(100);
                }
            }

            Console.ReadKey(true);
            Console.WriteLine();
            Console.WriteLine($"Stats halted.");
        }
Example #2
0
        public string ApplyScript(AdminJsScript script)
        {
            var sw = Stopwatch.StartNew();

            if (Log.IsOperationsEnabled)
            {
                Log.Operations($"Script : \"{script.Script}\"");
            }

            try
            {
                DocumentsOperationContext docsCtx = null;
                using (_server.AdminScripts.GetScriptRunner(new AdminJsScriptKey(script.Script), false, out var run))
                    using (_server.ServerStore.ContextPool.AllocateOperationContext(out JsonOperationContext ctx))
                        using (_database?.DocumentsStorage.ContextPool.AllocateOperationContext(out docsCtx))
                            using (var result = run.Run(ctx, docsCtx, "execute", new object[] { _server, _database }))
                            {
                                var toJson = RavenCli.ConvertResultToString(result);

                                if (Log.IsOperationsEnabled)
                                {
                                    Log.Operations($"Output: {toJson}");
                                }

                                if (Log.IsOperationsEnabled)
                                {
                                    Log.Operations($"Finished executing database script. Total time: {sw.Elapsed} ");
                                }

                                return(toJson);
                            }
            }
            catch (Exception e)
            {
                if (Log.IsOperationsEnabled)
                {
                    Log.Operations("An Exception was thrown while executing the script: ", e);
                }

                throw;
            }
            finally
            {
                _server.AdminScripts.RunIdleOperations();
            }
        }
Example #3
0
        public string ApplyScript(AdminJsScript script)
        {
            var sw = Stopwatch.StartNew();

            if (Log.IsOperationsEnabled)
            {
                Log.Operations($"Script : \"{script.Script}\"");
            }

            try
            {
                using (_server.AdminScripts.GetScriptRunner(new AdminJsScriptKey(script.Script), false, out var run))
                    using (var result = run.Run(null, "execute", new object[] { _server, _database }))
                    {
                        var toJson = RavenCli.ConvertResultToString(result);

                        if (Log.IsOperationsEnabled)
                        {
                            Log.Operations($"Output: {toJson}");
                        }

                        if (Log.IsOperationsEnabled)
                        {
                            Log.Operations($"Finished executing database script. Total time: {sw.Elapsed} ");
                        }
                        return(toJson);
                    }
            }
            catch (Exception e)
            {
                if (Log.IsOperationsEnabled)
                {
                    Log.Operations("An Exception was thrown while executing the script: ", e);
                }
                throw;
            }
        }
Example #4
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);
        }
Example #5
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);
        }
Example #6
0
        public static void Connect(int?pid)
        {
            bool reconnect = true;

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            while (reconnect)
            {
                reconnect = false;

                if (pid == null)
                {
                    pid = ServerProcessUtil.GetRavenServerPid();
                }

                try
                {
                    var pipeName = Pipes.GetPipeName(Pipes.AdminConsolePipePrefix, pid.Value);
                    var client   = new NamedPipeClientStream(pipeName);
                    if (PlatformDetails.RunningOnPosix) // TODO: remove this if and after https://github.com/dotnet/corefx/issues/22141 (both in RavenServer.cs and AdminChannel.cs)
                    {
                        var pathField = client.GetType().GetField("_normalizedPipePath", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (pathField == null)
                        {
                            throw new InvalidOperationException("Unable to set the proper path for the admin pipe, admin channel will not be available");
                        }
                        var pipeDir = Path.Combine(Path.GetTempPath(), "ravendb-pipe");
                        pathField.SetValue(client, Path.Combine(pipeDir, pipeName));
                    }
                    try
                    {
                        client.Connect(3000);
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(Environment.NewLine + "Couldn't connect to " + pipeName);
                        Console.ResetColor();
                        Console.WriteLine();
                        Console.WriteLine(ex);
                        Environment.Exit(100);
                    }

                    var reader = new StreamReader(client);
                    var writer = new StreamWriter(client);
                    var buffer = new char[16 * 1024];
                    var sb     = new StringBuilder();

                    RavenCli.Delimiter[] delimiters =
                    {
                        RavenCli.Delimiter.NotFound,
                        RavenCli.Delimiter.ReadLine,
                        RavenCli.Delimiter.ReadKey,
                        RavenCli.Delimiter.Clear,
                        RavenCli.Delimiter.Logout,
                        RavenCli.Delimiter.Shutdown,
                        RavenCli.Delimiter.RestartServer,
                        RavenCli.Delimiter.ContinuePrinting
                    };

                    string restOfString = null;
                    while (true)
                    {
                        sb.Clear();
                        bool skipOnceRead = false;
                        if (restOfString != null)
                        {
                            sb.Append(restOfString);
                            restOfString = null;
                            skipOnceRead = true; // to avoid situation where another delimiter passed in previous Read, and next Read might blocked forever
                        }

                        var delimiter = RavenCli.Delimiter.NotFound;
                        // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
                        while (delimiter == RavenCli.Delimiter.NotFound)
                        {
                            if (skipOnceRead == false)
                            {
                                var v = reader.Read(buffer, 0, 8192);
                                if (v == 0)
                                {
                                    continue;
                                }

                                sb.Append(new string(buffer, 0, v));
                            }
                            else
                            {
                                skipOnceRead = false;
                            }

                            var sbString          = sb.ToString();
                            var firstDelimiterPos = sbString.IndexOf(RavenCli.DelimiterKeyWord, StringComparison.Ordinal);
                            if (firstDelimiterPos == -1)
                            {
                                continue;
                            }
                            var delimiterString = sbString.Substring(firstDelimiterPos);

                            RavenCli.Delimiter firstDelimiter = RavenCli.Delimiter.NotFound;
                            int firstIndex = 0;
                            var lowestPos  = 8192;
                            foreach (var del in delimiters)
                            {
                                var index = delimiterString.IndexOf(RavenCli.GetDelimiterString(del), StringComparison.Ordinal);
                                if (index == -1)
                                {
                                    continue;
                                }
                                if (index < lowestPos)
                                {
                                    lowestPos      = index;
                                    firstDelimiter = del;
                                    firstIndex     = index;
                                }
                            }
                            if (firstDelimiter == RavenCli.Delimiter.NotFound)
                            {
                                continue;
                            }

                            var posAgterFirstDelimiter = firstIndex + RavenCli.GetDelimiterString(firstDelimiter).Length;
                            restOfString = delimiterString.Substring(posAgterFirstDelimiter);

                            delimiter = firstDelimiter;
                            break;
                        }

                        var str = sb.ToString();
                        Console.Write(str.Substring(0, str.IndexOf(RavenCli.DelimiterKeyWord, StringComparison.Ordinal)));

                        if (delimiter == RavenCli.Delimiter.ContinuePrinting)
                        {
                            continue;
                        }

                        switch (delimiter)
                        {
                        case RavenCli.Delimiter.ReadLine:
                            writer.WriteLine(Console.ReadLine());
                            break;

                        case RavenCli.Delimiter.ReadKey:
                            writer.Write(Console.ReadKey().KeyChar);
                            break;

                        case RavenCli.Delimiter.Clear:
                            Console.Clear();
                            break;

                        case RavenCli.Delimiter.Logout:
                        case RavenCli.Delimiter.Shutdown:
                            Console.WriteLine();
                            Environment.Exit(0);
                            break;

                        case RavenCli.Delimiter.RestartServer:
                            Console.WriteLine();
                            for (int i = 10; i >= 0; i--)
                            {
                                Console.Write($"\rTrying to reconnect in {i} seconds ...  ");
                                Thread.Sleep(1000);
                            }
                            Console.WriteLine();
                            reconnect = true;
                            break;
                        }
                        writer.Flush();
                        if (reconnect)
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Example #7
0
        public static int Main(string[] args)
        {
            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 = new RavenConfiguration(null, ResourceType.Server, CommandLineSwitches.CustomConfigPath);

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

            configuration.Initialize();

            LoggingSource.Instance.SetupLogMode(configuration.Logs.Mode, configuration.Logs.Path.FullPath);
            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 = new RavenConfiguration(null, ResourceType.Server, 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);
        }
Example #8
0
        public static void Main(string[] args)
        {
            string path          = string.Concat(Environment.CurrentDirectory, "\\settings.json");
            var    configuration = new RavenConfiguration(null, ResourceType.Server, path);

            configuration.Initialize();

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

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

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

            var rerun = false;
            RavenConfiguration configBeforeRestart = configuration;

            do
            {
                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");
                            }

                            server.Initialize();

                            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;

                            IsRunningNonInteractive = false;

                            Console.WriteLine("Server start completed");

                            Console.ReadLine();

                            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);
                        }
                    }

                    Console.WriteLine("Shutdown completed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error during shutdown");
                    Console.WriteLine(e);
                }
                finally
                {
                    if (Logger.IsOperationsEnabled)
                    {
                        Logger.OperationsAsync("Server has shut down").Wait(TimeSpan.FromSeconds(15));
                    }
                }
            } while (rerun);
        }
Example #9
0
        public static void Connect(int?pid)
        {
            bool reconnect = true;

            // ReSharper disable once ConditionIsAlwaysTrueOrFalse
            while (reconnect)
            {
                reconnect = false;

                if (pid == null)
                {
                    pid = ServerProcessUtil.GetRavenServerPid();
                }

                try
                {
                    var pipeName = Pipes.GetPipeName(Pipes.AdminConsolePipePrefix, pid.Value);
                    var client   = new NamedPipeClientStream(pipeName);

                    try
                    {
                        client.Connect(3000);
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(Environment.NewLine + "Couldn't connect to " + pipeName);
                        Console.ResetColor();
                        Console.WriteLine();
                        Console.WriteLine(ex);
                        Environment.Exit(100);
                    }

                    var reader = new StreamReader(client);
                    var writer = new StreamWriter(client);
                    var buffer = new char[16 * 1024];
                    var sb     = new StringBuilder();

                    RavenCli.Delimiter[] delimiters =
                    {
                        RavenCli.Delimiter.NotFound,
                        RavenCli.Delimiter.ReadLine,
                        RavenCli.Delimiter.ReadKey,
                        RavenCli.Delimiter.Clear,
                        RavenCli.Delimiter.Logout,
                        RavenCli.Delimiter.Shutdown,
                        RavenCli.Delimiter.RestartServer,
                        RavenCli.Delimiter.ContinuePrinting
                    };

                    string restOfString = null;
                    while (true)
                    {
                        sb.Clear();
                        bool skipOnceRead = false;
                        if (restOfString != null)
                        {
                            sb.Append(restOfString);
                            restOfString = null;
                            skipOnceRead = true; // to avoid situation where another delimiter passed in previous Read, and next Read might blocked forever
                        }

                        var delimiter = RavenCli.Delimiter.NotFound;
                        // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
                        while (delimiter == RavenCli.Delimiter.NotFound)
                        {
                            if (skipOnceRead == false)
                            {
                                var v = reader.Read(buffer, 0, 8192);
                                if (v == 0)
                                {
                                    continue;
                                }

                                sb.Append(new string(buffer, 0, v));
                            }
                            else
                            {
                                skipOnceRead = false;
                            }

                            var sbString          = sb.ToString();
                            var firstDelimiterPos = sbString.IndexOf(RavenCli.DelimiterKeyWord, StringComparison.Ordinal);
                            if (firstDelimiterPos == -1)
                            {
                                continue;
                            }
                            var delimiterString = sbString.Substring(firstDelimiterPos);

                            RavenCli.Delimiter firstDelimiter = RavenCli.Delimiter.NotFound;
                            int firstIndex = 0;
                            var lowestPos  = 8192;
                            foreach (var del in delimiters)
                            {
                                var index = delimiterString.IndexOf(RavenCli.GetDelimiterString(del), StringComparison.Ordinal);
                                if (index == -1)
                                {
                                    continue;
                                }
                                if (index < lowestPos)
                                {
                                    lowestPos      = index;
                                    firstDelimiter = del;
                                    firstIndex     = index;
                                }
                            }
                            if (firstDelimiter == RavenCli.Delimiter.NotFound)
                            {
                                continue;
                            }

                            var posAfterFirstDelimiter = firstIndex + RavenCli.GetDelimiterString(firstDelimiter).Length;
                            restOfString = delimiterString.Substring(posAfterFirstDelimiter);

                            delimiter = firstDelimiter;
                            break;
                        }

                        var str = sb.ToString();
                        Console.Write(str.Substring(0, str.IndexOf(RavenCli.DelimiterKeyWord, StringComparison.Ordinal)));

                        if (delimiter == RavenCli.Delimiter.ContinuePrinting)
                        {
                            continue;
                        }

                        switch (delimiter)
                        {
                        case RavenCli.Delimiter.ReadLine:
                            writer.WriteLine(Console.ReadLine());
                            break;

                        case RavenCli.Delimiter.ReadKey:
                            writer.Write(Console.ReadKey().KeyChar);
                            break;

                        case RavenCli.Delimiter.Clear:
                            Console.Clear();
                            break;

                        case RavenCli.Delimiter.Logout:
                        case RavenCli.Delimiter.Shutdown:
                            Console.WriteLine();
                            Environment.Exit(0);
                            break;

                        case RavenCli.Delimiter.RestartServer:
                            Console.WriteLine();
                            for (int i = 10; i >= 0; i--)
                            {
                                Console.Write($"\rTrying to reconnect in {i} seconds ...  ");
                                Thread.Sleep(1000);
                            }
                            Console.WriteLine();
                            reconnect = true;
                            break;
                        }
                        writer.Flush();
                        if (reconnect)
                        {
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Example #10
0
        public static int Main(string[] args)
        {
            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 configuration = new RavenConfiguration(null, ResourceType.Server, CommandLineSwitches.CustomConfigPath);

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

            configuration.Initialize();

            LoggingSource.Instance.SetupLogMode(configuration.Logs.Mode, configuration.Logs.Path.FullPath);
            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);
                }
                catch (Exception e)
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Error running Windows Service", e);
                    }

                    return(1);
                }

                return(0);
            }

            var rerun = false;
            RavenConfiguration configBeforeRestart = configuration;

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

                    configuration = new RavenConfiguration(null, ResourceType.Server, 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");
                            }
                            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)
                {
                    if (e.ToString().Contains(@"'WriteReqPool'") &&
                        e.ToString().Contains("System.ObjectDisposedException")) // TODO : Remove this check in dotnet 2.0 - https://github.com/aspnet/KestrelHttpServer/issues/1231
                    {
                        Console.WriteLine("Ignoring Kestrel's Exception : 'Cannot access a disposed object. Object name: 'WriteReqPool'");
                        Console.Out.Flush();
                    }
                    else
                    {
                        Console.WriteLine("Error during shutdown");
                        Console.WriteLine(e);
                        return(-2);
                    }
                }
            } while (rerun);

            return(0);
        }
Example #11
0
        public static async Task ListenToAdminConsolePipe(RavenServer ravenServer, NamedPipeServerStream adminConsolePipe)
        {
            var pipe = adminConsolePipe;

            // We start the server pipe only when running as a server
            // so we won't generate one per server in our test environment
            if (pipe == null)
            {
                return;
            }

            try
            {
                while (true)
                {
                    await pipe.WaitForConnectionAsync();

                    var reader = new StreamReader(pipe);
                    var writer = new StreamWriter(pipe);
                    try
                    {
                        var cli     = new RavenCli();
                        var restart = cli.Start(ravenServer, writer, reader, false, true);
                        if (restart)
                        {
                            await writer.WriteLineAsync("Restarting Server...<DELIMETER_RESTART>");

                            Program.RestartServerMre.Set();
                            Program.ShutdownServerMre.Set();
                            // server restarting
                            return;
                        }

                        await writer.WriteLineAsync("Shutting Down Server...<DELIMETER_RESTART>");

                        Program.ShutdownServerMre.Set();
                        // server shutting down
                        return;
                    }
                    catch (Exception e)
                    {
                        if (Logger.IsInfoEnabled)
                        {
                            Logger.Info("Got an exception inside CLI (internal error) while in pipe connection", e);
                        }
                    }

                    pipe.Disconnect();
                }
            }
            catch (ObjectDisposedException)
            {
                //Server shutting down
            }
            catch (Exception e)
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Got an exception trying to connect to server admin channel pipe", e);
                }
            }
        }