This tutorial explains how to configure alerting using ElastAlert with the popular proprietary issue tracking product JIRA.

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.

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. 

Our Goal

The goal of the tutorial is to use Qbox as a Centralized Logging, Alerting and Monitoring solution to automatically create and assign issues on JIRA. We will assume you do have a JIRA account set-up and running. Qbox provides a turnkey solution for Elasticsearch, Kibana and many of Elasticsearch analysis and monitoring plugins. We 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 visualizing 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:

  • ProviderAWS
  • Version5.1.1
  • RAM1GB
  • CPUvCPU1
  • Replicas0

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 spike rule of type spike
  • Twitter single metric aggregation rule of type metric_aggregation

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 spike rule matches when the volume of events during a given time period is spike_height times larger or smaller than during the previous time period. It uses two sliding windows to compare the current and reference frequency of events.
  • The metric aggregation rule matches when the value of a metric within the calculation window is higher or lower than a threshold. By default, this is buffer_time.
# Alert when at least 5 tweets are made consisting of the term “mobile” within a timeframe of 60 minutes
name: Twitter frequency rule
type: frequency
index: twitter-*
num_events: 5
timeframe:
 minutes: 60
realert:
 hours: 2
filter:
- query:
  query_string:
   query: "text:mobile"
alert:
- "jira"
# The hostname of the JIRA server.
jira_server: "XXXXjira.atlassian.net"
# The project to open the ticket under.
jira_project: "QBOX_ELAST_ALERT"
#  The type of issue that the ticket will be filed as. Note that this is case sensitive.
jira_issuetype: "bug"
# The path to the file which contains JIRA account credentials.
jira_account_file: "BASE_PATH/jira_acct.txt"

The account file is also yaml formatted and must contain two fields:

user: The username.

password: The password.

Here is an example JIRA account file:

# Example jira_account information file
# You should make sure that this file is not globally readable or version controlled! (Except for this example)
# Jira username
user: qbox-elastalert-jira
# Jira password
password: p455XXXw0rd

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 spike config, we configure our rule as follows:

# Alert when there is a sudden spike(2 times of previous count) in the volume of matching events within a sliding window of 30 minutes
# (Required)
# Rule name, must be unique
name: Event spike rule
# (Required)
# Type of alert.
# the spike rule type compares the number of events within two sliding windows to each other
type: spike
# (Required)
# Index to search, wildcard supported
index: twitter-*
# (Required one of _cur or _ref, spike specific)
# The minimum number of events that will trigger an alert
# For example, if there are only 2 events between 12:00 and 2:00, and 20 between 2:00 and 4:00
# _cur is 2 and _ref is 20, and the alert will fire because 20 is greater than threshold_cur
threshold_cur: 5
#threshold_ref: 5
# (Required, spike specific)
# The size of the window used to determine average event frequency
# We use two sliding windows each of size timeframe
# To measure the 'reference' rate and the current rate
timeframe:
 minutes: 30
# (Required, spike specific)
# The spike rule matches when the current window contains spike_height times more
# events than the reference window
spike_height: 2
# (Required, spike specific)
# The direction of the spike
# 'up' matches only spikes, 'down' matches only troughs
# 'both' matches both spikes and troughs
spike_type: "up"
# (Required)
# A list of Elasticsearch filters used for find events
# These filters are joined with AND and nested in a filtered query
filter:
- query:
   query_string:
     query: "text:elasticsearch"
- type:
   value: "twitter_logs"
# (Required)
# The alert is used when a match is found
alert:
- "jira"
# The hostname of the JIRA server.
jira_server: "XXXXjira.atlassian.net"
# The project to open the ticket under.
jira_project: "QBOX_ELAST_ALERT"
#  The type of issue that the ticket will be filed as. Note that this is case sensitive.
jira_issuetype: "bug"
# The path to the file which contains JIRA account credentials.
jira_account_file: "BASE_PATH/jira_acct.txt"

Finally, let’s configure our final metric_aggregation rule as follows:

# Alert when average retweet count for a particular user’s truncated tweet is either less than 2 or greater than 10 within a timeframe of 1 hour
# (Required)
# Rule name, must be unique
name: Event Twitter Metric Aggregation Rule
# (Required)
# Type of alert
type: metric_aggregation
index: twitter-*
# default the calculation window
buffer_time:
 hours: 1
# name of the field over which the metric value will be calculated
metric_agg_key: retweet_count
# The type of metric aggregation to perform on the metric_agg_key field
metric_agg_type: avg
# Group metric calculations by this field. For each unique value of the query_key field, the metric will be calculated and evaluated separately against the threshold(s).
query_key: user.id
doc_type: twitter_logs
bucket_interval:
 minutes: 5
sync_bucket_interval: true
# If the calculated metric value is greater than this number, an alert will be triggered. This threshold is exclusive.
max_threshold: 10
# If the calculated metric value is smaller than this number, an alert will be triggered. This threshold is exclusive.
min_threshold: 2
# (Required)
# A list of Elasticsearch filters used for find events
# These filters are joined with AND and nested in a filtered query
filter:
- term:
   truncated: true
# (Required)
# The alert is used when a match is found
alert:
- "jira"
# The hostname of the JIRA server.
jira_server: "XXXXjira.atlassian.net"
# The project to open the ticket under.
jira_project: "QBOX_ELAST_ALERT"
#  The type of issue that the ticket will be filed as. Note that this is case sensitive.
jira_issuetype: "bug"
# The path to the file which contains JIRA account credentials.
jira_account_file: "BASE_PATH/jira_acct.txt"

Thus, Qbox Configuration for Alerting must be as follows:

name: Twitter frequency rule
type: frequency
index: twitter-*
num_events: 5
timeframe:
 minutes: 60
realert:
 hours: 2
filter:
- query:
  query_string:
   query: "text:mobile"
alert:
- "jira"
jira_server: "XXXXjira.atlassian.net"
jira_project: "QBOX_ELAST_ALERT"
jira_issuetype: "bug"
jira_account_file: "BASE_PATH/jira_acct.txt"
---
name: Event spike rule
type: spike
index: twitter-*
threshold_cur: 5
timeframe:
 minutes: 30
spike_height: 2
spike_type: "up"
filter:
- query:
   query_string:
     query: "text:elasticsearch"
- type:
   value: "twitter_logs"
alert:
- "jira"
jira_server: "XXXXjira.atlassian.net"
jira_project: "QBOX_ELAST_ALERT"
jira_issuetype: "bug"
jira_account_file: "BASE_PATH/jira_acct.txt"
---
name: Event Twitter Metric Aggregation Rule
type: metric_aggregation
index: twitter-*
buffer_time:
 hours: 1
metric_agg_key: retweet_count
metric_agg_type: avg
query_key: user.id
doc_type: twitter_logs  
bucket_interval:
 minutes: 5
sync_bucket_interval: true
max_threshold: 10
min_threshold: 2
filter:
- term:
   truncated: true
alert:
- "jira"
jira_server: "XXXXjira.atlassian.net"
jira_project: "QBOX_ELAST_ALERT"
jira_issuetype: "bug"
jira_account_file: "BASE_PATH/jira_acct.txt"

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 frequency 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 on the channel.

And, as the time passes, we will receive other alerts as well, like the spike 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.

Other Helpful Tutorials

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.