Exemple #1
0
        public void PublishCheckResult(JObject check)
        {
            var payload = new JObject();

            payload["check"]  = check;
            payload["client"] = _sensuClientConfigurationReader.SensuClientConfig.Client.Name;
            if (_sensuClientConfigurationReader.SensuClientConfig.Client.MailTo != null && _sensuClientConfigurationReader.SensuClientConfig.Client.MailTo.Count > 0)
            {
                payload["check"]["mail_to"] = string.Join(",", _sensuClientConfigurationReader.SensuClientConfig.Client.MailTo);
            }
            payload["check"]["executed"] = SensuClientHelper.CreateTimeStamp();
            payload["check"]["issued"]   = payload["check"]["executed"];

            try
            {
                PublishResult(payload);

                if (_sensuClientConfigurationReader.SensuClientConfig.Client.SendMetricWithCheck && ((string)check["type"]).Equals("standard"))
                {
                    // publish the same result as metric too
                    payload["check"]["type"] = "metric";
                    PublishResult(payload);
                }
            } catch (Exception e)
            {
                Log.Warn(e, "Error publishing check Result");
            }
        }
Exemple #2
0
        private void PublishKeepAlive(IModel ch)
        {
            var keepAlive = _sensuClientConfigurationReader.Configuration.Config["client"];

            keepAlive["timestamp"] = SensuClientHelper.CreateTimeStamp();
            keepAlive["version"]   = Version; // Undocumented stuff to send the client version
            keepAlive["plugins"]   = "";

            List <string> redactlist = null;

            redactlist = SensuClientHelper.GetRedactlist((JObject)keepAlive);

            var payload = SensuClientHelper.RedactSensitiveInformaton(keepAlive, redactlist);

            Log.Debug("Publishing keepalive");
            var properties = new BasicProperties
            {
                ContentType  = "application/octet-stream",
                Priority     = 0,
                DeliveryMode = 1
            };

            try
            {
                ch.BasicPublish("", "keepalives", properties, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));
            }
            catch (Exception)
            {
                Log.Error("Lost MQ connection when trying to publish keepalives!");
            }
        }
        public void should_merge_localcheck_with_check_defenition()
        {
            var checks = (JObject)_sensuClientConfigurationReader.Configuration.Config["checks"];
            var check  = SensuClientHelper.GetStandAloneChecks(checks).First();

            check = _sensuClientConfigurationReader.MergeCheckWithLocalCheck(check);

            check["team"].ToString().ShouldBe("pink");
        }
Exemple #4
0
        public void can_not_substitute_command_with_no_defaultdivider()
        {
            var parseErrors = "";

            _jsonCheck["command"] = "check-ram.rb -w :::params.ram.warning::: -c :::params.ram.critical:::";

            SensuClientHelper.SubstitueCommandTokens(_jsonCheck, out parseErrors, _jsonClient);

            parseErrors.ShouldBe(SensuClientHelper.ErroTextDefaultDividerMissing);
        }
Exemple #5
0
        public void can_substitute_command_with_no_client_params()
        {
            var parseErrors = "";

            _jsonCheck["command"] = "check-ram.rb -w :::params.ram.warning|10::: -c :::params.ram.critical|5:::";

            var substitueCommandTokens = SensuClientHelper.SubstitueCommandTokens
                                             (_jsonCheck, out parseErrors, _jsonClient);

            substitueCommandTokens.ShouldBe("check-ram.rb -w 10 -c 5");
        }
Exemple #6
0
        public void should_return_empty_redactlist_when_client_has_no_redact_key()
        {
            string        jsonparams = @"{
                client: { 
              }
            }";
            var           check      = JObject.Parse(jsonparams);
            List <string> redactlist = null;

            redactlist = SensuClientHelper.GetRedactlist(check);
            Assert.That(redactlist, Is.Null);
        }
Exemple #7
0
        public void can_substitute_command_from_client_config()
        {
            var parseErrors = "";

            _jsonCheck["command"]   = ":::ramcheck|check-ram.rb:::";
            _jsonClient["ramcheck"] = "other-ram-check.sh";

            var substitueCommandTokens = SensuClientHelper.SubstitueCommandTokens
                                             (_jsonCheck, out parseErrors, _jsonClient);

            substitueCommandTokens.ShouldBe("other-ram-check.sh");
        }
        public void ExecuteCheckCommand(JObject check)
        {
            Log.Debug("Attempting to execute check command {0}", JsonConvert.SerializeObject(check, SerializerSettings));
            if (check["name"] == null)
            {
                CheckDidNotHaveValidName(check);
                return;
            }
            var checkName = check["name"].ToString();

            if (!checksInProgress.Lock(checkName))
            {
                return;
            }

            try {
                var commandParseErrors = "";
                check["command"] = SensuClientHelper.SubstitueCommandTokens(
                    check, out commandParseErrors, (JObject)_sensuClientConfigurationReader.Configuration.Config["client"]);

                if (!String.IsNullOrEmpty(commandParseErrors))
                {
                    Log.Warn("Errors parsing the command: {0}", commandParseErrors);
                    CheckDidNotHaveValidParameters(check, commandParseErrors);
                    throw new Exception(String.Format("Errors parsing the command {0}", commandParseErrors));
                }

                Log.Debug("Preparing check to be launched: {0}", checkName);

                int?timeout = null;
                if (check["timeout"] != null)
                {
                    timeout = SensuClientHelper.TryParseNullable(check["timeout"].ToString());
                }

                var commandToExcecute = CommandFactory.Create(
                    new CommandConfiguration()
                {
                    Plugins = _sensuClientConfigurationReader.SensuClientConfig.Client.Plugins,
                    TimeOut = timeout
                }, check["command"].ToString());

                Log.Debug("About to run command: " + checkName);
                Task <JObject> executingTask = ExecuteCheck(check, commandToExcecute);
                checksInProgress.SetTask(checkName, executingTask);
                executingTask.ContinueWith(ReportCheckResultAfterCompletion).ContinueWith(CheckCompleted);
            } catch (Exception e)
            {
                Log.Error(e, "Error preparing check {0}", checkName);
                checksInProgress.UnlockAnyway(checkName);
            }
        }
Exemple #9
0
        public void should_be_able_to_parse_redact_string_to_list()
        {
            string        jsonparams = @"{
                client: { 
                redact: 'password passwd pass api_key secret'
              }
            }";
            var           check      = JObject.Parse(jsonparams);
            List <string> redactlist = null;

            redactlist = SensuClientHelper.GetRedactlist(check);
            redactlist.ShouldContain("password");
        }
Exemple #10
0
        public void should_not_brake_when_empty_client_redact_string()
        {
            string        jsonparams = @"{
                client: { 
                redact: ''
              }
            }";
            var           check      = JObject.Parse(jsonparams);
            List <string> redactlist = null;

            redactlist = SensuClientHelper.GetRedactlist(check);
            Assert.That(redactlist, Is.Null);
        }
        public void should_return_standalone_checkdefenitions()
        {
            var obj = (JObject)_sensuClientConfigurationReader.Configuration.Config["checks"];

            var standAloneChecks = SensuClientHelper.GetStandAloneChecks(obj);

            standAloneChecks.Any().ShouldBe(true);
            standAloneChecks.Count().ShouldBe(2);
            //{"name":"check_standalone_cpu_windows","issued":1423609458,"command":"check_standalone_cpu_windows.ps1"}
            standAloneChecks.First()["command"].Value <string>().ShouldNotBeEmpty();
            standAloneChecks.First()["interval"].Value <int>().ShouldBeGreaterThan(0);
            standAloneChecks.First()["name"].Value <string>().ShouldNotBeEmpty();
            standAloneChecks.First()["name"].Value <string>().ShouldBe("check_standalone_cpu_windows");
        }
Exemple #12
0
        public void should_validate_false_when_output_is_not_a_string()
        {
            string json  = @"{
                    name: 'mymetrics',
                    output: 3,
                    status: 0,
                    type: 'metric',
                    handlers: 'irc'
            }";
            var    check = JObject.Parse(json);

            var resultcheck = SensuClientHelper.ValidateCheckResult(check);

            resultcheck.ShouldBe(false);
        }
Exemple #13
0
        public void should_validate_true_when_valid_values()
        {
            string json  = @"{
                    name: 'mymetrics',
                    output: 'name  value',
                    status: 0,
                    type: 'metric',
                    handlers: 'irc'
            }";
            var    check = JObject.Parse(json);

            var resultcheck = SensuClientHelper.ValidateCheckResult(check);

            resultcheck.ShouldBe(true);
        }
Exemple #14
0
        public void should_validate_false_when_name_contains_special_characters()
        {
            string json  = @"{
                    name: 'mymet$rics',
                    output: 3,
                    status: 0,
                    type: 'metric',
                    handlers: 'irc'
            }";
            var    check = JObject.Parse(json);

            var resultcheck = SensuClientHelper.ValidateCheckResult(check);

            resultcheck.ShouldBe(false);
        }
Exemple #15
0
        public void should_not_redact_nonsensitive_information()
        {
            string jsonparams = @"{
                check_cpu_windows: {
                ram: {
                    warning: 'hemliga arne',
                    critical: 'mumbojumbo'
                }
              }
            }";
            var    check      = JObject.Parse(jsonparams);

            var resultcheck = (JObject)SensuClientHelper.RedactSensitiveInformaton(check);

            resultcheck["check_cpu_windows"]["ram"]["warning"].Value <string>().ShouldBe("hemliga arne");
            resultcheck["check_cpu_windows"]["ram"]["critical"].Value <string>().ShouldBe("mumbojumbo");
        }
Exemple #16
0
        public void should_redact_sensitive_information()
        {
            string jsonparams = @"{
                check_cpu_windows: {
                ram: {
                    secret: 'hemliga arne',
                    password: '******'
                }
              }
            }";
            var    check      = JObject.Parse(jsonparams);

            var resultcheck = (JObject)SensuClientHelper.RedactSensitiveInformaton(check);

            resultcheck["check_cpu_windows"]["ram"]["secret"].Value <string>().ShouldBe("REDACTED");
            resultcheck["check_cpu_windows"]["ram"]["password"].Value <string>().ShouldBe("REDACTED");
        }
Exemple #17
0
        public void can_substitute_command_with_no_substitutions()
        {
            var parseErrors = "";

            _jsonCheck["command"] = "check-ram.rb -w 25 -c 45";
            string jsonparams = @"{
                ram: {
                    warning: 20,
                    critical: 10
                }
            }";

            var clientparams = JObject.Parse(jsonparams);

            _jsonClient["params"] = clientparams;

            var substitueCommandTokens = SensuClientHelper.SubstitueCommandTokens
                                             (_jsonCheck, out parseErrors, _jsonClient);

            substitueCommandTokens.ShouldBe("check-ram.rb -w 25 -c 45");
        }
Exemple #18
0
        public void can_substitute_command_with_arguments()
        {
            var parseErrors = "";

            _jsonCheck["command"] = "check-ram.rb -w :::params.ram.warning|10::: -c :::params.ram.critical|5:::";
            var jsonparams = @"{
                ram: {
                    warning: 20,
                    critical: 10
                }
            }";

            var clientparams = JObject.Parse(jsonparams);

            _jsonClient["params"] = clientparams;

            var substitueCommandTokens = SensuClientHelper.SubstitueCommandTokens
                                             (_jsonCheck, out parseErrors, _jsonClient);

            substitueCommandTokens.ShouldBe("check-ram.rb -w 20 -c 10");
        }
        private static string ParseCheckResult(string data)
        {
            if (data.TrimEnd('\n') == "ping")
            {
                return("pong");
            }

            JObject check;

            if (!SensuClientHelper.TryParseData(data, out check))
            {
                return("Invalid Json!");
            }
            if (!SensuClientHelper.ValidateCheckResult(check))
            {
                return("Invalid check format!");
            }
            _checkProcessor.PublishCheckResult(check);

            return("ok");
        }
Exemple #20
0
        private IModel CreateChannelAndConsumer(IModel ch, ref QueueingBasicConsumer consumer)
        {
            var connection = _sensuRabbitMqConnectionFactory.GetRabbitConnection();

            if (connection == null)
            {
                //Do nothing - we'll loop around the while loop again with everything null and retry the connection.
            }
            else
            {
                ch = connection.CreateModel();
                var queueName = SensuClientHelper.CreateQueueName();
                foreach (var subscription in _sensuClientConfigurationReader.SensuClientConfig.Client.Subscriptions)
                {
                    Log.Debug("Binding queue {0} to exchange {1}", queueName, subscription);
                    try
                    {
                        ch.ExchangeDeclare(subscription, "fanout");

                        var q = ch.QueueDeclare(queueName, false, false, true, null);

                        ch.QueueBind(q.QueueName, subscription, "");
                    }
                    catch (Exception exception)
                    {
                        Log.Warn(exception, "Could not bind to subscription: {0}", subscription);
                    }
                }
                consumer = new QueueingBasicConsumer(ch);
                try
                {
                    ch.BasicConsume(queueName, true, consumer);
                }
                catch (Exception)
                {
                    Log.Warn("Could not consume queue: {0}", queueName);
                }
            }
            return(ch);
        }
        private void InitializeSheduledItems()
        {
            var obj = (JObject)_sensuClientConfigurationReader.Configuration.Config["checks"];

            var standAloneChecks = SensuClientHelper.GetStandAloneChecks(obj);

            if (!standAloneChecks.Any())
            {
                return;
            }

            foreach (JObject item in standAloneChecks)
            {
                if (item == null || item["interval"] == null)
                {
                    continue;
                }

                var defaultInterval = item["interval"].Value <int>();
                SheduledItems.TryAdd(item["name"].Value <string>(), new SchedueledItem(() => _processor.ProcessCheck(item), item["name"].Value <string>(), defaultInterval));
                Log.Debug("Adding scheduled item with interval property:  {0} | {1}", defaultInterval, item["name"]);
            }
        }
Exemple #22
0
        public JObject MergeCheckWithLocalCheck(JObject check)
        {
            var checks = (JObject)Configuration.Config["checks"];

            if (checks == null)
            {
                return(check);
            }

            var localcheck = SensuClientHelper.GetCheckByName(check, checks);

            if (localcheck == null)
            {
                return(check);
            }

            localcheck.Merge(check, new JsonMergeSettings
            {
                // union array values together to avoid duplicates
                MergeArrayHandling = MergeArrayHandling.Merge
            });

            return(localcheck);
        }
Exemple #23
0
 public void create_queuename_should_return_a_nonempty_string()
 {
     SensuClientHelper.CreateQueueName().ShouldNotBeEmpty();
 }
Exemple #24
0
 public void create_queuename_should_contain_assembly_version()
 {
     SensuClientHelper.CreateQueueName().ShouldContain(CoreAssembly.Version.ToString());
 }
Exemple #25
0
 public void create_queuename_should_contain_hostname()
 {
     SensuClientHelper.CreateQueueName().ShouldContain(SensuClientHelper.GetFQDN());
 }