ELK scales well and helps with incident response, comparing metrics, tracking bugs, etc. However, as the number of dashboards and amount of data grow, we have a need for automation. Unless someone is actively looking at a dashboard or searching for the right thing, we miss a lot.

We need a way to monitor the data we have in Elasticsearch in near real time. We want a generic way to look for certain patterns in our data, without duplicating our data somewhere or spinning up a heavyweight service. The final requirement is the data should be accessible to engineers and operations from every team across the organization for quick resolution.

ElastAlert, developed by Yelp, is a simple framework for alerting on anomalies, spikes, or other patterns of interest from data in Elasticsearch. Several organisations use Elasticsearch, Logstash and Kibana for managing their ever increasing amount of data and logs. Kibana is great for visualizing and querying data, but a companion tool is needed for alerting on inconsistencies in the data. Out of this need, ElastAlert was created. If you have data being written into Elasticsearch in near real time and want to be alerted when that data matches certain patterns, ElastAlert is the tool for you.

For this post, we will be using hosted Elasticsearch on Qbox.io. You can sign up or launch your cluster here, or click "Get Started" in the header navigation. If you need help setting up, refer to "Provisioning a Qbox Elasticsearch Cluster." 

ElastAlert is now available on Qbox provisioned Elasticsearch clusters and can be easily configured. Implementing ElastAlert is easy on Qbox. When you provision a cluster, there is a configuration box where you can input your Alert rules.  If you’re unclear how to structure rules in YAML, be sure to consult the ElastAlert Documentation.

Our Goal

The goal of the tutorial is to use Qbox as a Centralized Logging, Alerting and Monitoring solution. Qbox provides out of box solution for Elasticsearch, Kibana and many of Elasticsearch analysis and monitoring plugins. We will set up Logstash in a separate node or machine to gather twitter stream and use Qbox provisioned ElastAlert alerting to configure rules and set up alerts for detection of anomalies and inconsistencies in data.

Our ELK stack setup has four main components:

  • Elasticsearch: It is used to store all of the application and monitoring logs(Provisioned by Qbox).

  • Logstash: The server component that processes incoming logs and feeds to ES.

  • ElastAlert:  The superb open-source alerting tool built by the team at Yelp Engineering and now available on all new Elasticsearch clusters on AWS.

  • Kibana(optional): A web interface for searching and visualising logs (Provisioned by Qbox).

Prerequisites

The amount of CPU, RAM, and storage that your Elasticsearch Server will require depends on the volume of logs that you intend to gather. For this tutorial, we will be using a Qbox provisioned Elasticsearch with the following minimum specs:

  • Provider: AWS

  • Version: 5.1.1

  • RAM: 1GB

  • CPU: vCPU1

  • Replicas: 0

The above specs can be changed per your desired requirements. Please select the appropriate names, versions, regions for your needs. For this example, we used Elasticsearch version 5.1.1, the most current version is 5.3. We support all versions of Elasticsearch on Qbox. (To learn more about the major differences between 2.x and 5.x, click here.)  

In addition to our Elasticsearch Server, we will require a separate logstash server to process incoming twitter stream from twitter API and ship them to Elasticsearch. For simplicity and testing purposes, the logstash server can also act as the client server itself. The Endpoint and Transport addresses for our Qbox provisioned Elasticsearch cluster are as follows:

common_1.png

Endpoint

REST API

https://ec18487808b6908009d3:efcec6a1e0@eb843037.qb0x.com:32563

Authentication

  • Username = ec18487808b6908009d3

  • Password = efcec6a1e0

TRANSPORT (NATIVE JAVA)

eb843037.qb0x.com:30543

Note: Please make sure to whitelist the logstash server IP from Qbox Elasticsearch cluster.

Configure Alerting

Now, let’s create the “rules” namely

  • Twitter frequency rule of type frequency

  • Twitter flatline rule of type flatline

  • Twitter blacklist rule of type blacklist

Using these, we will test 3 types of rules that Elastalert can manage:

  • The frequency rule, which will alert when a number of documents for a certain period of time is reached.

  • The flatline rule, which will alert when the number of documents matched for a search drop below a threshold.

  • The v rule, which will alert when any document containing a list of words is found on the timeframe collected by the tool.

Of course, there are other rule types alongside those that we will cover in this tutorial, like the spike rule that can detect abnormal growth or shrinks on data across a time period, or the whitelist rule, which alert on any documents that contain any words from a list.

First, we create the frequency rule, by configuring the following code:

# Alert when at least 3 tweets are made consisting of the term “elasticsearch” within a timeframe of 30 minutes
name: Twitter frequency rule
type: frequency
index: twitter-*
num_events: 3
timeframe:
 minutes: 30
realert:
 hours: 2
filter:
- query:
  query_string:
   query: "text:elasticsearch"
alert:
 - "email"
email:
 - "elastalert@qbox.com"

The rule is configured by setting the following properties:

  • name: The name of the rule. This must be unique across all rules. This property acts as the rule ID.

  • type: The RuleType to use. This may either be one of the built in rule types or loaded from a module.

  • index: The name of the index that will be searched. Wildcards can be used here, such as: index: twitter-* which will match twitter-2014-10-05.

  • num_events: The number of events which will trigger an alert.

  • timeframe: The time that num_events must occur within.

  • realert: This option allows you to ignore repeating alerts for a period of time. If the rule uses a query_key, this option will be applied on a per key basis.

  • filter: A list of Elasticsearch query DSL filters that is used to query Elasticsearch. ElastAlert will query Elasticsearch using the format {'filter': {'bool': {'must': [config.filter]}}} with an additional timestamp range filter.

  • alert: Each rule may have any number of alerts attached to it. This property is a list of targets which we want our alerts to be sent.

As we can see, this is a very straightforward and simple configuration. For the flatline config, we configure our rule as follows:

# Alert when less than 30 tweets are made matching the query filter within a timeframe of 30 minutes
name: Twitter flatline rule
type: flatline
index: twitter-*
threshold: 30
timeframe:
minutes: 30
realert:
minutes: 30
filter:
- query:
  query_string:
   query: "text:logging"
use_count_query: true
doc_type: twitter_logs
alert:
 - "email"
email:
 - "elastalert@qbox.com"

The configuration is pretty much the same of the previous file, with the exception of 3 new properties:

  • threshold: This property defines the minimum number of events for an alert not to be triggered.

  • use_count_query:  If true, ElastAlert will poll Elasticsearch using the count api, and not download all of the matching documents. This is useful is you care only about numbers and not the actual data.

  • doc_type: Specify the _type of document to search for. This must be present if use_count_query or use_terms_query is set.

Finally, let’s configure our final blacklist rule:

# Alert when any tweet is made consisting of blacklisted keywords and matching the query filter
name: Twitter blacklist rule
type: blacklist
index: twitter-*
compare_key: text
blacklist:
- "android"
- "java"
realert:
  hours: 4
filter:
- query:
   query_string:
    query: "text:mobile"
alert:
 - "email"
email:
 - "elastalert@qbox.com"

On this rule, the new properties that we needed to configure are:

  • compare_key: The name of the field to use to compare to the blacklist. If the field is null, those events will be ignored.

  • blacklist: The blacklist rule will check a certain field against a blacklist, and match if it is in the blacklist.

Thus, Qbox Configuration for Alerting must be as follows:

name: Twitter frequency rule
type: frequency
index: twitter-*
num_events: 3
timeframe:
 minutes: 30
realert:
 hours: 2
filter:
- query:
  query_string:
   query: "text:elasticsearch"
alert:
 - "email"
email:
 - "elastalert@qbox.com"
---
name: Twitter flatline rule
type: flatline
index: twitter-*
threshold: 30
timeframe:
minutes: 30
realert:
minutes: 30
filter:
- query:
  query_string:
   query: "text:logging"
use_count_query: true
doc_type: twitter_logs
alert:
 - "email"
email:
 - "elastalert@qbox.com"
---
name: Twitter blacklist rule
type: blacklist
index: twitter-*
compare_key: text
blacklist:
- "android"
- "java"
realert:
  hours: 4
filter:
- query:
   query_string:
    query: "text:mobile"
alert:
 - "email"
email:
 - "elastalert@qbox.com"

Install Logstash

Download and install the Public Signing Key:

wget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -

We will use the Logstash version 2.4.x as compatible with our Elasticsearch version 5.1.x. The Elastic Community Product Support Matrix can be referred in order to clear any version issues.

Add the repository definition to your /etc/apt/sources.list file:

echo "deb https://packages.elastic.co/logstash/2.4/debian stable main" | sudo tee -a /etc/apt/sources.list

Run sudo apt-get update and the repository is ready for use. You can install it with:

sudo apt-get update && sudo apt-get install logstash

Alternatively, logstash tar can also be downloaded from Elastic Product Releases Site. Then, the steps of setting up and running logstash are pretty simple:

  • Download and unzip Logstash

  • Prepare a logstash.conf config file

  • Run bin/logstash -f logstash.conf -t to check config (logstash.conf)

  • Run bin/logstash -f logstash.conf

Configure Logstash (Twitter Stream)

Logstash configuration files are in the JSON-format, and reside in /etc/logstash/conf.d. The configuration consists of three sections: inputs, filters, and outputs.

We need to be authorized to take data from Twitter via its API. This part is easy:

  1. Login to your Twitter account

  2. Go to https://dev.twitter.com/apps/

  3. Create a new Twitter application (here I give Twitter-Qbox-Stream as the name of the app).

t1.png

After you successfully create the Twitter application, you get the following parameters in "Keys and Access Tokens":

  1. Consumer Key (API Key)

  2. Consumer Secret (API Secret)

  3. Access Token

  4. Access Token Secret

t2.png

We are now ready to create the Twitter data path (stream) from Twitter servers to our machine. We will use the above four parameters (consumer key, consumer secret, access token, access token secret) to configure twitter input for logstash.

Let's create a configuration file called 02-twitter-input.conf and set up our "twitter" input:

sudo vi /etc/logstash/conf.d/02-twitter-input.conf

Insert the following input configuration:

input {
 twitter {
   consumer_key => "BCgpJwYPDjXXXXXX80JpU0"
   consumer_secret => "Eufyx0RxslO81jpRuXXXXXXXMlL8ysLpuHQRTb0Fvh2"
   keywords => ["mobile", "java", "android", "elasticsearch", "search"]
   oauth_token => "193562229-o0CgXXXXXXXX0e9OQOob3Ubo0lDj2v7g1ZR"
   oauth_token_secret => "xkb6I4JJmnvaKv4WXXXXXXXXS342TGO6y0bQE7U"
 }
}

Save and quit the file 02-twitter-input.conf.

This specifies a twitter input that will filter tweets with keywords "mobile", "java", "android", "elasticsearch", "search" and pass them to logstash output. Save and quit. Lastly, we will create a configuration file called 30-elasticsearch-output.conf:

sudo vi /etc/logstash/conf.d/30-elasticsearch-output.conf

Insert the following output configuration:

output {
 elasticsearch {
   hosts => ["https://eb843037.qb0x.com:32563/"]
   user => "ec18487808b6908009d3"
   password => "efcec6a1e0"
   index => "twitter-%{+YYYY.MM.dd}"
   document_type => "twitter_logs"
 }
 stdout { codec => rubydebug }
}

Save and exit. This output basically configures Logstash to store the twitter logs data in Elasticsearch which is running at https://eb843037.qb0x.com:30024/, in an index named after the twitter.

If you have downloaded logstash tar or zip, you can create a logstash.conf file having input, filter and output all in one place.

sudo vi LOGSTASH_HOME/logstash.conf

Insert the following input and output configuration in logstash.conf

input {
 twitter {
   consumer_key => "BCgpJwYPDjXXXXXX80JpU0"
   consumer_secret => "Eufyx0RxslO81jpRuXXXXXXXMlL8ysLpuHQRTb0Fvh2"
   keywords => ["mobile", "java", "android", "elasticsearch", "search"]
   oauth_token => "193562229-o0CgXXXXXXXX0e9OQOob3Ubo0lDj2v7g1ZR"
   oauth_token_secret => "xkb6I4JJmnvaKv4WXXXXXXXXS342TGO6y0bQE7U"
 }
}
output {
 elasticsearch {
   hosts => ["https://eb843037.qb0x.com:32563/"]
   user => "ec18487808b6908009d3"
   password => "efcec6a1e0"
   index => "twitter-%{+YYYY.MM.dd}"
   document_type => "twitter_logs"
 }
 stdout { codec => rubydebug }
}

Test your Logstash configuration with this command:

sudo service logstash configtest

It should display Configuration OK if there are no syntax errors. Otherwise, try and read the error output to see what's wrong with your Logstash configuration.

Restart Logstash, and enable it, to put our configuration changes into effect:

sudo service logstash restart
sudo update-rc.d logstash defaults 96 9

If you have downloaded logstash tar or zip, it can be run using following command

bin/logstash -f logstash.conf

Numerous responses are received. The structure of document is as follows:

{
 "text": "Learn how to automate anomaly detection on your #Elasticsearch #timeseries data with #MachineLearning:",
 "created_at": "2017-05-07T07:54:47.000Z",
 "source": "<a href="%5C">Twitter for iPhone</a>",
 "truncated": false,
 "language": "en",
 "mention": [],
 "retweet_count": 0,
 "hashtag": [
   {
     "text": "Elasticsearch",
     "start": 49,
     "end": 62
   },
   {
     "text": "timeseries",
     "start": 65,
     "end": 75
   },
   {
     "text": "MachineLearning",
     "start": 88,
     "end": 102
   }
 ],
 "location": {
   "lat": 33.686657,
   "lon": -117.674558
 },
 "place": {
   "id": "74a60733a8b5f7f9",
   "name": "elastic",
   "type": "city",
   "full_name": "San Francisco, CA",
   "street_address": null,
   "country": "United States",
   "country_code": "US",
   "url": "https://api.twitter.com/1.1/geo/id/74a60733a8b5f7f9.json"
 },
 "link": [],
 "user": {
   "id": 2873953509,
   "name": "Elastic",
   "screen_name": "elastic",
   "location": "SF, CA",
   "description": "The company behind the Elastic Stack (#elasticsearch, #kibana, Beats, #logstash), X-Pack, and Elastic Cloud"
 }
}

The simplest of the rules to test it out is the flatline rule. All we have to do is wait for about 5 minutes with Elasticsearch running and Logstash stopped, so no documents are streaming. After the wait, we can see on our channel that an alert is received:

And, as the time passes, we will receive other alerts as well, like the frequency alert:

Conclusion

ElastAlert helps to learn a lot from data and use it to monitor many critical systems. If you know what you’re looking for, archiving log files and retrieving them manually might be sufficient, but this process is tedious. As your infrastructure scales, so does the volume of log files, and the need for a log management system becomes apparent. Qbox provisioned Elasticsearch is already very successful for indexing logs, faster retrieval, powerful search tools, great visualizations and many other purposes. Qbox built in support for ElastAlert will help greatly in alerting on anomalies, spikes, or other patterns of interest from data in Elasticsearch.

There are several types of included alerters. Of course, as in the example, you can send emails. You can also open JIRA issues, run arbitrary commands, and custom python code. Each alerter has it’s own specific options, but there are several that can apply to any type, such as realert, which is the minimum time before sending a subsequent alert for a given rule, and aggregation, which allows you to aggregate all alerts which occur within a timeframe for a rule together.

Give It a Whirl!

It's easy to spin up a standard hosted Elasticsearch cluster on any of our 47 Rackspace, Softlayer, or Amazon data centers. And you can now provision your own AWS Credits on Qbox Private Hosted Elasticsearch

Questions? Drop us a note, and we'll get you a prompt response.

Not yet enjoying the benefits of a hosted ELK-stack enterprise search on Qbox? We invite you to create an account today and discover how easy it is to manage and scale your Elasticsearch environment in our cloud hosting service.