示例#1
0
        private static bool Iterate(Func <Unit, bool?> action, CommandLineSwitches switches, string question = null, string errorMessage = null)
        {
            if (switches != CommandLineSwitches.UserInput)
            {
                return(switches == CommandLineSwitches.SilentInstallAll);
            }

            bool?result = null;

            while (!result.HasValue)
            {
                if (!string.IsNullOrWhiteSpace(question))
                {
                    Console.Write(question);
                }

                result = action.Invoke(Unit.Default);

                if (!result.HasValue && !string.IsNullOrWhiteSpace(errorMessage))
                {
                    Console.WriteLine(errorMessage);
                }
            }

            return(result.Value);
        }
        // Refactoring: Method can be converted to non-virtual
        public virtual void Parse()
		{
            // Refactoring: Remove braces from 'if' and vice versa
            if (Parameters == null)
			{
				return;
			}

            // Refactoring: Use 'var' instead of 'string' on param
            // Refactoring: Conversion of foreach to for loop
            switches = 0;
			foreach (string param in Parameters)
			{
				switch (param)
				{
					case "-a":
						// 1. Analyzer should warn here about bit operation on enum, which is not annotated with [Flags]
                        // 2. Analyzer + CodeFix: Replace 'x |= y' by 'x = x | y'
						switches |= CommandLineSwitches.A;
						break;
					case "-b":
						switches |= CommandLineSwitches.B;
						break;
					case "-c":
						switches |= CommandLineSwitches.C;
						break;
					case "-d":
						switches |= CommandLineSwitches.D;
						break;
					case "-v":
						switches |= CommandLineSwitches.V;
						break;
				}
			}
		}
        /// <summary>
        /// For each argument actually passed, run defined action.
        /// </summary>
        /// <returns></returns>
        public static Boolean ProcessArguments()
        {
            Boolean           returnValue       = default(Boolean);
            CommandLineSwitch commandLineSwitch = default(CommandLineSwitch);

            try
            {
                //process arguments passed to app
                foreach (KeyValuePair <String, String> argument in Arguments)
                {
                    commandLineSwitch = CommandLineSwitches.Find(cls => cls.SwitchCharacter == argument.Key);
                    if (commandLineSwitch != null)
                    {
                        if (commandLineSwitch.ActionDelegate != null)
                        {
                            commandLineSwitch.ActionDelegate(argument.Value, ConsoleApplication.defaultOutputDelegate /*messageBoxWrapperOutputDelegate*/);
                        }
                        else
                        {
                            throw new ApplicationException(String.Format("Switch has no action defined: {0}", argument.Key));
                        }
                    }
                    else
                    {
                        throw new ApplicationException(String.Format("Switch not recognized: {0}", argument.Key));
                    }
                }

                #if debug
                foreach (CommandLineSwitch cls in CommandLineSwitches)
                {
                    if (cls.ActionDelegate != null)
                    {
                        cls.ActionDelegate("test", ConsoleApplication.defaultOutputDelegate /*messageBoxWrapperOutputDelegate*/);
                    }
                }
                #endif

                returnValue = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error);


                //throw;
            }
            return(returnValue);
        }
        /// <summary>
        /// Remove a CommandLineSwitch from list
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static Boolean RemoveCommandLineSwitch(CommandLineSwitch commandLineSwitch)
        {
            Boolean returnValue = default(Boolean);

            try
            {
                returnValue = CommandLineSwitches.Remove(CommandLineSwitches.Find(cls => cls.SwitchCharacter == commandLineSwitch.SwitchCharacter));
            }
            catch (Exception ex)
            {
                Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error);


                //throw;
            }
            return(returnValue);
        }
        // Refactoring: Method can be converted to non-virtual
        public virtual void Parse()
        {
            // Refactoring: Remove braces from 'if' and vice versa
            if (Parameters == null)
            {
                return;
            }

            // Refactoring: Use 'var' instead of 'string' on param
            // Refactoring: Conversion of foreach to for loop
            switches = 0;
            foreach (string param in Parameters)
            {
                switch (param)
                {
                case "-a":
                    // 1. Analyzer should warn here about bit operation on enum, which is not annotated with [Flags]
                    // 2. Analyzer + CodeFix: Replace 'x |= y' by 'x = x | y'
                    switches |= CommandLineSwitches.A;
                    break;

                case "-b":
                    switches |= CommandLineSwitches.B;
                    break;

                case "-c":
                    switches |= CommandLineSwitches.C;
                    break;

                case "-d":
                    switches |= CommandLineSwitches.D;
                    break;

                case "-v":
                    switches |= CommandLineSwitches.V;
                    break;
                }
            }
        }
        /// <summary>
        /// Add a CommandLineSwitch to list
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static Boolean AddCommandLineSwitch(CommandLineSwitch commandLineSwitch)
        {
            Boolean returnValue = default(Boolean);

            try
            {
                //check for duplicates first
                if (CommandLineSwitches.Contains(CommandLineSwitches.Find(cls => cls.SwitchCharacter == commandLineSwitch.SwitchCharacter)))
                {
                    RemoveCommandLineSwitch(commandLineSwitch);
                }
                CommandLineSwitches.Add(commandLineSwitch);

                returnValue = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error);


                //throw;
            }
            return(returnValue);
        }
示例#7
0
        private static void UpdatePluginConfiguration(Component component, string destination, CommandLineSwitches switches)
        {
            foreach (var componentLibrary in component.Libraries)
            {
                ActConfigurationHelper.AddPlugin(Path.Combine(destination, componentLibrary));
            }

            if (component.Configurations == null)
            {
                return;
            }

            bool?result = null;

            foreach (var componentConfiguration in component.Configurations)
            {
                var url             = componentConfiguration.Key;
                var confDestination = componentConfiguration.Value;

                ActConfigurationHelper.SaveConfiguration(url, confDestination, onDuplicatd: _ =>
                {
                    if (result.HasValue)
                    {
                        return(result != null && result.Value);
                    }

                    return(Iterate(__ =>
                    {
                        result = YesOrNoIteration();
                        return result != null && result.Value;
                    }, switches, $"##### Do you want to overwrite the existing configuration for {component.Name}? [Y/n] ",
                                   DefaultIterationErrorMessage));
                });
            }
        }
示例#8
0
        private static void Handle(WebInteractions webInteractions,
                                   SystemInteractions systemInteractions,
                                   Component component,
                                   CommandLineSwitches switches,
                                   string downloadTo,
                                   string installTo = "")
        {
            if (component.CanBeSkipped)
            {
                if (!Iterate(_ => YesOrNoIteration(), switches, $"##### Do you want to install {component.Name}? [Y/n] ", DefaultIterationErrorMessage))
                {
                    return;
                }
            }

            var componentVersionCheck = component.IsPrerequisite ? component.VersionCheck : Path.Combine(installTo, component.VersionCheck);

            if (systemInteractions.CheckVersion(componentVersionCheck, component.Version, () => Console.WriteLine($"##### Unable to check the version for {component.Name}...")))
            {
                Console.WriteLine($"##### The latest version of {component.Name} is already installed!");
                if (component.IsPlugin)
                {
                    UpdatePluginConfiguration(component, UpdatePluginInstallPath(component, installTo), switches);
                }
                return;
            }

            var          downloadToFullPath = Path.Combine(downloadTo, component.FileName);
            var          parsingText        = $"##### Parsing latest github api for {component.Name}...";
            var          downloadingText    = $"##### Downloading {component.Name} -> ";
            const string installText        = "##### {0} {1}...";

            var downloadFrom = component.Url;

            if (component.IsFromGitHub)
            {
                var isWin7 = !string.IsNullOrWhiteSpace(component.Win7InstallArguments) &&
                             Environment.OSVersion.Version.Major == 6 &&
                             Environment.OSVersion.Version.Minor == 1;

                var installArguments = isWin7 ? component.Win7InstallArguments : component.InstallArguments;
                downloadFrom = webInteractions.ParseAssetFromGitHub(downloadFrom, int.Parse(installArguments), () => Console.WriteLine(parsingText));
            }

            var bundle = webInteractions.Download(downloadFrom, downloadToFullPath, () => Console.Write(downloadingText), args => Console.Write($"\r{downloadingText} {args.ProgressPercentage}%"), () => Console.Write("\n"));

            if (bundle.Result == WebInteractionsResultType.Fail)
            {
                Console.WriteLine($"\nThere was an error while downloading {component.Name}.\nThe program will be terminated!\n");
                Console.ReadLine();
                Environment.Exit(1);
            }

            var file = bundle.DownloadedFile;

            if (component.ComponentType == ComponentType.Executable)
            {
                Console.WriteLine(installText, "Installing", component.Name);
                systemInteractions.Install(file.FullName, component.InstallArguments);
            }
            else
            {
                if (string.IsNullOrWhiteSpace(installTo))
                {
                    Console.WriteLine($"\nThere was an error while unzipping {component.Name}.\nThe install path was not valid, the program will be terminated!\n");
                    Console.ReadLine();
                    Environment.Exit(1);
                }

                if (component.IsPlugin)
                {
                    installTo = UpdatePluginInstallPath(component, installTo);
                    UpdatePluginConfiguration(component, installTo, switches);
                }

                try
                {
                    if (Directory.Exists(installTo))
                    {
                        Directory.Delete(installTo);
                    }
                }
                catch (Exception)
                {
                    // do nothing
                }

                Console.WriteLine(installText, "Unzipping", component.Name);
                systemInteractions.Unzip(file.FullName, installTo);
            }
        }
示例#9
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);
        }
示例#10
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);
        }
示例#11
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);
        }
        /// <summary>
        /// Parse arguments into switches and values.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static Boolean ParseArguments
        (
            String[] args
        )
        {
            Boolean returnValue = default(Boolean);
            String  argument    = String.Empty;
            String  argumentWithoutSwitchIndicator = String.Empty;

            String[]          argumentFieldsArray = default(String[]);
            String            key               = String.Empty;
            String            value             = String.Empty;
            CommandLineSwitch commandLineSwitch = default(CommandLineSwitch);

            Arguments = new Dictionary <String, String>();

            try
            {
                #if debug
                Console.WriteLine(args.Length.ToString());
                #endif

                for (Int32 i = args.GetLowerBound(0); i <= args.GetUpperBound(0); i++)
                {
                    argument = args[i].Trim();

                    //check for missing argument
                    if (argument == String.Empty)
                    {
                        throw new ArgumentException("Unexpected empty argument.");
                    }

                    //check for switch indicator
                    if (!CommandLineSwitchIndicators.Contains(argument[0]))
                    {
                        throw new ArgumentException(String.Format("Unexpected argument switch indicator: '{0}'", argument[0]));
                    }

                    //remove switch indicator
                    argumentWithoutSwitchIndicator = argument.Substring(1, argument.Length - 1);

                    #if debug
                    Console.WriteLine(argumentWithoutSwitchIndicator);
                    #endif

                    if (argumentWithoutSwitchIndicator.Contains(CommandLineSwitchValueSeparator))
                    {
                        //a compund switch
                        argumentFieldsArray = argumentWithoutSwitchIndicator.Split(CommandLineSwitchValueSeparator.ToCharArray());

                        if (argumentFieldsArray.Length < 1 || argumentFieldsArray.Length > 2)
                        {
                            throw new ArgumentException(String.Format("Unexpected argument format: '{0}'", argumentWithoutSwitchIndicator));
                        }

                        key = argumentFieldsArray[0].Trim();
                        if (key == String.Empty)
                        {
                            throw new ArgumentException(String.Format("Empty argument key. Argument: '{0}'", argument));
                        }
                        if (key.Length > 1)
                        {
                            throw new ArgumentException(String.Format("Unexpected argument key format; key should be single character. Argument: '{0}'", argument));
                        }

                        value = argumentFieldsArray[1].Trim();
                        if (value == String.Empty)
                        {
                            throw new ArgumentException(String.Format("Empty argument value. Argument: '{0}'", argument));
                        }
                    }
                    else
                    {
                        //simple switch
                        if (argumentWithoutSwitchIndicator.Length != 1)
                        {
                            //length greater than 1; not a valid simple switch
                            throw new ArgumentException(String.Format("Unexpected argument format. Separator not found: '{0}'", argumentWithoutSwitchIndicator));
                        }
                        else
                        {
                            //length is 1; valid simple switch
                            key   = argumentWithoutSwitchIndicator;
                            value = String.Empty;
                        }
                    }

                    #if debug
                    Console.WriteLine(key);
                    Console.WriteLine(value);
                    #endif

                    //check for switch
                    commandLineSwitch = CommandLineSwitches.Find(cls => cls.SwitchCharacter == key);
                    if (commandLineSwitch == null)
                    {
                        throw new ArgumentException(String.Format("Unexpected argument switch: '{0}'", key[0]));
                    }

                    //validate against UsesValue connectionString
                    if (commandLineSwitch.UsesValue)
                    {
                        if (value == String.Empty || value == null)
                        {
                            throw new ArgumentException(String.Format("Switch '{0}' is missing a value.", key[0]));
                        }
                    }
                    else
                    {
                        if (value != String.Empty && value != null)
                        {
                            throw new ArgumentException(String.Format("Switch '{0}' does not take a value.", key[0]));
                        }
                    }

                    //add item to dictionary
                    Arguments.Add(key, value);

                    //clean up this iteration
                    argument = String.Empty;
                    argumentWithoutSwitchIndicator = String.Empty;
                    argumentFieldsArray            = default(String[]);
                    key   = String.Empty;
                    value = String.Empty;
                }

                #if debug
                foreach (KeyValuePair <String, String> kvp in arguments)
                {
                    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
                }
                #endif

                returnValue = true;
            }
            catch (Exception ex)
            {
                Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error);
            }
            return(returnValue);
        }
示例#13
0
 public CommandLineResult(string installPath, CommandLineSwitches s)
 {
     InstallPath = installPath;
     Switch      = s;
 }
示例#14
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, Path.Combine(AppContext.BaseDirectory, configuration.Logs.Path));
            if (Logger.IsInfoEnabled)
            {
                Logger.Info($"Logging to { configuration.Logs.Path } set to {configuration.Logs.Mode} level.");
            }

            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;

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

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

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

                            var prevColor = Console.ForegroundColor;
                            Console.Write("Server available on: ");
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine($"{server.ServerStore.NodeHttpServerUrl}");
                            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...");

                            IsRunningAsService = false;
                            rerun = CommandLineSwitches.Daemon ? RunAsService() : 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);
        }