Пример #1
0
        public void RestartService(string serviceName, TimeSpan timeout)
        {
            CmdHelper cmd = new CmdHelper();
            CommandExecutionResult result = cmd.ExecuteCommand2(
                @"cmd /c sc \\{0} stop {1}".FormatWith(this.machine, serviceName),
                this.userName,
                this.password,
                this.Domain);

            if (result.ExitCode == 0)
            {
                DateTime start = DateTime.Now;
                while (!this.GetServiceStatus(serviceName).Equals("Stopped", StringComparison.OrdinalIgnoreCase))
                {
                    if (DateTime.Now.Subtract(start) < timeout)
                    {
                        System.Threading.Thread.Sleep(2000);
                    }
                    else
                    {
                        throw new Exception("Timeout after {0} when stopping service {1} on machine {2}.".FormatWith(timeout.ToString(), serviceName, this.machine));
                    }
                }

                CommandExecutionResult resultStart = cmd.ExecuteCommand2(
                    "cmd /c sc \\{0} start {1}".FormatWith(this.machine, serviceName),
                    this.userName,
                    this.password,
                    this.Domain);
                if (result.ExitCode == 0)
                {
                    start = DateTime.Now;
                    while (!this.GetServiceStatus(serviceName).Equals("running", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeout)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when starting service {1} on machine {2}.".FormatWith(timeout.ToString(), serviceName, this.machine));
                        }
                    }
                }
                else
                {
                    throw new Exception("Failed to start service {0} on machine {1} after stopped it.\r\n{2}".FormatWith(serviceName, this.machine, resultStart.ToSerializedXmlString()));
                }
            }
            else
            {
                throw new Exception("Failed to stop service {0} on machine {1}.\r\n{2}".FormatWith(serviceName, this.machine, result.ToSerializedXmlString()));
            }
        }
Пример #2
0
        /// <summary>
        /// Executes the commands concurrently and waits for them all to exit.
        /// </summary>
        /// <param name="commands">The commands.</param>
        public List <CommandExecutionResult> ExecuteCommandsConcurrently(string[] commands, string userName = "", string password = "", string domain = "")
        {
            List <CommandExecutionResult> results = new List <CommandExecutionResult>();
            CountdownEvent countdownEvent         = new CountdownEvent(commands.Length);

            // Start workers
            for (int i = 0; i < commands.Length; i++)
            {
                string      command = commands[i];
                ThreadStart ts      = delegate()
                {
                    try
                    {
                        CommandExecutionResult result = this.ExecuteCommand2(command, userName, password, domain);
                        lock (results)
                        {
                            results.Add(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                    }
                    finally
                    {
                        countdownEvent.Signal();
                    }
                };

                Thread t = new Thread(ts);
                t.Name = "ExecuteCommandsConcurrently[{0}]".FormatWith(i);
                t.Start();
            }

            // Wait for workers.
            countdownEvent.Wait();
            countdownEvent.Dispose();

            return(results);
        }
Пример #3
0
        public void RestartServices(string[] services, TimeSpan timeoutPerService)
        {
            // Stop them one by one (Must one by one because they may have dependencies)
            CmdHelper cmd = new CmdHelper();

            for (int i = 0; i < services.Length; i++)
            {
                Log.Info("Restart services with {0}\\{1}...", this.Domain, this.userName);
                CommandExecutionResult result = cmd.ExecuteCommand2(
                    @"cmd /c sc \\{0} stop {1}".FormatWith(this.machine, services[i])
                    //, this.userName
                    //, this.password
                    //, this.Domain
                    );
                if (result.ExitCode == 0)
                {
                    DateTime start  = DateTime.Now;
                    string   status = this.GetServiceStatus(services[i]);
                    while (!status.Equals("Stopped", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeoutPerService)
                        {
                            Log.Info("Waiting...");
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when stopping service {1} on machine {2}. Latest status: {3}.".FormatWith(timeoutPerService.ToString(), services[i], this.machine, status));
                        }

                        status = this.GetServiceStatus(services[i]);
                    }
                }
                else
                {
                    Log.Info(result.StandardOutput.ToString());
                    Log.Error(result.StandardError.ToString());

                    DateTime start  = DateTime.Now;
                    string   status = this.GetServiceStatus(services[i]);
                    while (!status.Equals("Stopped", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeoutPerService)
                        {
                            Log.Info("Waiting...");
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when stopping service {1} on machine {2}. Latest status is {3}.".FormatWith(timeoutPerService.ToString(), services[i], this.machine, status));
                        }

                        status = this.GetServiceStatus(services[i]);
                    }

                    //throw new Exception("Failed to stop service {0} on machine {1}.\r\n{2}".FormatWith(services[i], this.machine, result.ToSerializedXmlString()));
                }
            }

            // Start them one by one
            for (int i = services.Length - 1; i >= 0; i--)
            {
                CommandExecutionResult result = cmd.ExecuteCommand2(
                    @"cmd /c sc \\{0} start {1}".FormatWith(this.machine, services[i])
                    //, this.userName
                    //, this.password
                    //, this.Domain
                    );
                if (result.ExitCode == 0)
                {
                    DateTime start  = DateTime.Now;
                    string   status = this.GetServiceStatus(services[i]);
                    while (!status.Equals("running", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeoutPerService)
                        {
                            Log.Info("Waiting...");
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when starting service {1} on machine {2}. Latest status: {3}.".FormatWith(timeoutPerService.ToString(), services[i], this.machine, status));
                        }

                        status = this.GetServiceStatus(services[i]);
                    }
                }
                else
                {
                    Log.Info(result.StandardOutput.ToString());
                    Log.Error(result.StandardError.ToString());

                    DateTime start  = DateTime.Now;
                    string   status = this.GetServiceStatus(services[i]);
                    while (!status.Equals("running", StringComparison.OrdinalIgnoreCase))
                    {
                        if (DateTime.Now.Subtract(start) < timeoutPerService)
                        {
                            Log.Info("Waiting...");
                            System.Threading.Thread.Sleep(2000);
                        }
                        else
                        {
                            throw new Exception("Timeout after {0} when starting service {1} on machine {2}. Latest status: {3}.".FormatWith(timeoutPerService.ToString(), services[i], this.machine, status));
                        }

                        status = this.GetServiceStatus(services[i]);
                    }

                    //throw new Exception("Failed to start service {0} on machine {1}.\r\n{2}".FormatWith(services[i], this.machine, result.ToSerializedXmlString()));
                }
            }
        }
Пример #4
0
        public CommandExecutionResult ExecuteCommand2(string command, string workingDirectory, string userName = "", string password = "", string domain = "")
        {
            CommandExecutionResult result = new CommandExecutionResult()
            {
                CommandText = command.Trim(),
                ExitCode    = -1
            };

            Log.Info(string.Format("Trying to start '{0}' as '{1}\\{2}'...", result.CommandText, domain, userName));

            Process          process   = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();

            if (!string.IsNullOrEmpty(userName))
            {
                startInfo.UserName = userName;
                SecureString secureString = new SecureString();

                for (int i = 0; i < password.Length; i++)
                {
                    secureString.AppendChar(password[i]);
                }

                startInfo.Password = secureString;

                startInfo.Domain = domain;
            }
            int index = result.CommandText.IndexOf(' ', 0);

            if (index > 0)
            {
                startInfo.FileName  = result.CommandText.Substring(0, index);
                startInfo.Arguments = result.CommandText.Substring(index + 1);
            }
            else
            {
                startInfo.FileName = result.CommandText;
            }
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //startInfo.FileName = "cmd.exe";
            //startInfo.Arguments = "/C " + input;
            startInfo.UseShellExecute        = false;
            startInfo.RedirectStandardError  = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.WorkingDirectory       = workingDirectory;
            if (!Directory.Exists(workingDirectory))
            {
                Directory.CreateDirectory(workingDirectory);
            }
            process.StartInfo = startInfo;
            try
            {
                bool start = process.Start();
                result.ProcessId = process.Id;
                result.StandardOutput.AppendLine(string.Format("Process {0}: '{1}' started {2}...", process.Id, command, start ? "successfully" : "failed"));

                using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
                    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                    {
                        process.OutputDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                outputWaitHandle.Set();
                            }
                            else
                            {
                                result.StandardOutput.AppendLine(e.Data);
                            }
                        };
                        process.ErrorDataReceived += (sender, e) =>
                        {
                            if (e.Data == null)
                            {
                                errorWaitHandle.Set();
                            }
                            else
                            {
                                result.StandardError.AppendLine(e.Data);
                            }
                        };
                        process.BeginOutputReadLine();
                        process.BeginErrorReadLine();
                        if (process.WaitForExit(Int32.MaxValue) && outputWaitHandle.WaitOne(Int32.MaxValue) && errorWaitHandle.WaitOne(Int32.MaxValue))
                        {
                            result.StandardOutput.AppendLine();
                            result.StandardOutput.AppendLine(string.Format("Process {0}: '{1}' exited with: {2}", process.Id, command, process.ExitCode));
                            result.ExitCode = process.ExitCode;
                        }
                        else
                        {
                            result.StandardOutput.AppendLine();
                            result.StandardOutput.AppendLine(string.Format("Timeout: {0} when waiting for process: {1} '{2}'", TimeSpan.FromMilliseconds(Int32.MaxValue), process.Id, command));
                        }
                    }
            }
            catch (Exception ex)
            {
                result.StandardOutput.AppendLine(string.Format("{0}\r\nCorresponding input: '{1}'", ExceptionHelper.ExceptionLog(ex), command));
            }
            finally
            {
                try
                {
                    if (process != null)
                    {
                        try
                        {
                            if (!process.HasExited)
                            {
                                process.Kill();
                            }
                        }
                        catch (Exception ex)
                        {
                            result.StandardOutput.AppendLine(ExceptionHelper.ExceptionLog(ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    result.StandardOutput.Append("Exception met with this command: {0}\r\n{1}".FormatWith(command, ExceptionHelper.ExceptionLog(ex)));
                }
                finally
                {
                    process.Close();
                    process.Dispose();

                    //Log.Info(result.StandardOutput.ToString());
                    //Log.Error(result.StandardError.ToString());
                }
            }

            return(result);
        }