Mongo2Go.Helper.ProcessControl.StartAndWaitForReady C# (CSharp) Méthode

StartAndWaitForReady() public static méthode

Reads from Output stream to determine if process is ready
public static StartAndWaitForReady ( Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle ) : Mongo2Go.Helper.ProcessOutput
process System.Diagnostics.Process
timeoutInSeconds int
processReadyIdentifier string
windowTitle string
Résultat Mongo2Go.Helper.ProcessOutput
        public static ProcessOutput StartAndWaitForReady(Process process, int timeoutInSeconds, string processReadyIdentifier, string windowTitle)
        {
            if (timeoutInSeconds < 1 ||
                timeoutInSeconds > 10)
            {
                throw new ArgumentOutOfRangeException("timeoutInSeconds", "The amount in seconds should have a value between 1 and 10.");
            }

            List<string> errorOutput = new List<string>();
            List<string> standardOutput = new List<string>();
            bool processReady = false;

            process.ErrorDataReceived += (sender, args) => errorOutput.Add(args.Data);
            process.OutputDataReceived += (sender, args) =>
                {
                    standardOutput.Add(args.Data);

                    if (!string.IsNullOrEmpty(args.Data) &&
                        args.Data.Contains(processReadyIdentifier))
                    {
                        processReady = true;
                    }
                };

            process.Start();

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            int lastResortCounter = 0;
            int timeOut = timeoutInSeconds * 10;
            while (!processReady)
            {
                Thread.Sleep(100);
                if (++lastResortCounter > timeOut)
                {
                    // we waited X seconds.
                    // for any reason the detection did not worked, eg. the identifier changed
                    // lets assume everything is still ok
                    break;
                }
            }

            process.CancelErrorRead();
            process.CancelOutputRead();

            return new ProcessOutput(errorOutput, standardOutput);
        }

Usage Example

Exemple #1
0
        /// <summary>
        /// Starts a new process.
        /// </summary>
        public IMongoDbProcess Start(string binariesDirectory, string dataDirectory, int port, bool doNotKill, bool singleNodeReplSet, string additionalMongodArguments, ushort singleNodeReplSetWaitTimeout = 5)
        {
            string fileName = @"{0}{1}{2}".Formatted(binariesDirectory, System.IO.Path.DirectorySeparatorChar.ToString(), MongoDbDefaults.MongodExecutable);

            string arguments = (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) ?
                               @"--dbpath ""{0}"" --port {1} --bind_ip 127.0.0.1".Formatted(dataDirectory, port) :
                               @"--sslMode disabled --dbpath ""{0}"" --port {1} --bind_ip 127.0.0.1".Formatted(dataDirectory, port);

            arguments  = singleNodeReplSet ? arguments + Space + "--replSet" + Space + ReplicaSetName : arguments;
            arguments += MongodArguments.GetValidAdditionalArguments(arguments, additionalMongodArguments);

            WrappedProcess wrappedProcess = ProcessControl.ProcessFactory(fileName, arguments);

            wrappedProcess.DoNotKill = doNotKill;

            string windowTitle = "mongod | port: {0}".Formatted(port);

            ProcessOutput output = ProcessControl.StartAndWaitForReady(wrappedProcess, 5, ProcessReadyIdentifier, windowTitle);

            if (singleNodeReplSet)
            {
                var replicaSetReady = false;

                // subscribe to output from mongod process and check for replica set ready message
                wrappedProcess.OutputDataReceived += (_, args) => replicaSetReady |= !string.IsNullOrWhiteSpace(args.Data) && args.Data.Contains(ReplicaSetReadyIdentifier);

                MongoClient client     = new MongoClient("mongodb://127.0.0.1:{0}/?connect=direct;replicaSet={1}".Formatted(port, ReplicaSetName));
                var         admin      = client.GetDatabase("admin");
                var         replConfig = new BsonDocument(new List <BsonElement>()
                {
                    new BsonElement("_id", ReplicaSetName),
                    new BsonElement("members",
                                    new BsonArray {
                        new BsonDocument {
                            { "_id", 0 }, { "host", "127.0.0.1:{0}".Formatted(port) }
                        }
                    })
                });
                var command = new BsonDocument("replSetInitiate", replConfig);
                admin.RunCommand <BsonDocument>(command);

                // wait until replica set is ready or until the timeout is reached
                SpinWait.SpinUntil(() => replicaSetReady, TimeSpan.FromSeconds(singleNodeReplSetWaitTimeout));

                if (!replicaSetReady)
                {
                    throw new TimeoutException($"Replica set initialization took longer than the specified timeout of {singleNodeReplSetWaitTimeout} seconds. Please consider increasing the value of {nameof(singleNodeReplSetWaitTimeout)}.");
                }
            }

            MongoDbProcess mongoDbProcess = new MongoDbProcess(wrappedProcess)
            {
                ErrorOutput    = output.ErrorOutput,
                StandardOutput = output.StandardOutput
            };

            return(mongoDbProcess);
        }
All Usage Examples Of Mongo2Go.Helper.ProcessControl::StartAndWaitForReady