view ServerMonitor/Objects/Checks/SshCheck.cs @ 9:7127d5b5ac75

Code cleanup and comments
author Brad Greco <brad@bgreco.net>
date Mon, 08 Apr 2019 21:29:54 -0400
parents 052aa62cb42a
children a36cc5c123f4
line wrap: on
line source

using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace ServerMonitorApp
{
    [DisplayName("SSH check"), Description("Check the result of a command run over SSH"), DisplayWeight(10)]
    public class SshCheck : Check
    {
        public virtual string Command { get; set; }

        public bool CheckExitCode { get; set; }

        public int ExitCode { get; set; }

        public bool CheckCommandOutput { get; set; }

        public MatchType CommandOutputMatchType { get; set; }

        public string CommandOutputPattern { get; set; }

        public bool CommandOutputUseRegex { get; set; }

        protected override Task<CheckResult> ExecuteCheckAsync(CancellationToken token)
        {
            try
            {
                if (!Server.SshClient.IsConnected)
                {
                    if (Server.LoginType == LoginType.PrivateKey && Server.PrivateKeyFile == null)
                        return Task.FromResult(Fail(string.Format("Private key '{0}' is locked or not accessible", Server.KeyFile)));
                    Server.SshClient.Connect();
                }
            }
            catch (Exception e)
            {
                return Task.FromResult(Fail(e));
            }
            return Task.Run(() =>
            {
                try
                {
                    token.ThrowIfCancellationRequested();
                    using (SshCommand command = Server.SshClient.CreateCommand(Command))
                    {
                        token.Register(command.CancelAsync);
                        IAsyncResult ar = command.BeginExecute();
                        token.ThrowIfCancellationRequested();
                        string output = (command.EndExecute(ar).Trim() + command.Error.Trim()).ConvertNewlines();
                        return MergeResults(ProcessCommandResult(output, command.ExitStatus).ToArray());
                    }
                }
                catch (Exception e)
                {
                    return Fail(e);
                }
            }, token);
        }

        protected virtual List<CheckResult> ProcessCommandResult(string output, int exitCode)
        {
            List<CheckResult> results = new List<CheckResult>();
            if (CheckExitCode)
            {
                CheckResult result = GetIntResult(ExitCode, exitCode, "Exit code");
                if (result.Failed)
                    result.Message += ". Command output: " + output;
                results.Add(result);
            }
            if (CheckCommandOutput)
                results.Add(GetStringResult(CommandOutputMatchType, CommandOutputPattern, CommandOutputUseRegex, output, "Command output"));
            return results;
        }

        public override string Validate(bool saving = true)
        {
            string message = base.Validate();
            if (Server.Port <= 0)
                message += "Server SSH port is required." + Environment.NewLine;
            if (Server.Username.IsNullOrEmpty())
                message += "Server SSH username is required." + Environment.NewLine;
            if (Server.LoginType == LoginType.Password && Server.Password.IsNullOrEmpty())
                message += "Server SSH password is required." + Environment.NewLine;
            if (Server.LoginType == LoginType.PrivateKey && Server.KeyFile.IsNullOrEmpty())
                message += "Server SSH key is required." + Environment.NewLine;
            if (Command.IsNullOrEmpty())
                message += "Command is required." + Environment.NewLine;
            if (!CheckExitCode && !CheckCommandOutput)
                message += "At least one check must be enabled." + Environment.NewLine;
            if (CheckCommandOutput && CommandOutputUseRegex)
            {
                try
                {
                    Regex re = new Regex(CommandOutputPattern);
                }
                catch (ArgumentException)
                {
                    message += "Invalid regular expression for command output." + Environment.NewLine;
                }
            }
            return message;
        }
    }
}