Thursday, July 26, 2012

Ruby Regex Syntax

Regular-expression modifiers:

Regular expression literals may include an optional modifier to control various aspects of matching. The modifier is specified after the second slash character, as shown previously and may be represented by one of these characters:

ModifierDescription
iIgnore case when matching text.
oPerform #{} interpolations only once, the first time the regexp literal is evaluated.
xIgnores whitespace and allows comments in regular expressions
mMatches multiple lines, recognizing newlines as normal characters
u,e,s,nInterpret the regexp as Unicode (UTF-8), EUC, SJIS, or ASCII. If none of these modifiers is specified, the regular expression is assumed to use the source encoding.

Like string literals delimited with %Q, Ruby allows you to begin your regular expressions with %r followed by a delimiter of your choice. This is useful when the pattern you are describing contains a lot of forward slash characters that you don't want to escape:

# Following matches a single slash character, no escape required
%r|/|               

# Flag characters are allowed with this syntax, too
%r[</(.*)>]i  

Regular-expression patterns:

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash.

Following table lists the regular expression syntax that is available in Ruby.

PatternDescription
^Matches beginning of line.
$Matches end of line.
.Matches any single character except newline. Using m option allows it to match newline as well.
[...]Matches any single character in brackets.
[^...]Matches any single character not in brackets
re*Matches 0 or more occurrences of preceding expression.
re+Matches 1 or more occurrence of preceding expression.
re?Matches 0 or 1 occurrence of preceding expression.
re{ n}Matches exactly n number of occurrences of preceding expression.
re{ n,}Matches n or more occurrences of preceding expression.
re{ n, m}Matches at least n and at most m occurrences of preceding expression.
a| bMatches either a or b.
(re)Groups regular expressions and remembers matched text.
(?imx)Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?-imx)Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.
(?: re)Groups regular expressions without remembering matched text.
(?imx: re)Temporarily toggles on i, m, or x options within parentheses.
(?-imx: re)Temporarily toggles off i, m, or x options within parentheses.
(?#...)Comment.
(?= re)Specifies position using a pattern. Doesn't have a range.
(?! re)Specifies position using pattern negation. Doesn't have a range.
(?> re)Matches independent pattern without backtracking.
\wMatches word characters.
\WMatches nonword characters.
\sMatches whitespace. Equivalent to [\t\n\r\f].
\SMatches nonwhitespace.
\dMatches digits. Equivalent to [0-9].
\DMatches nondigits.
\AMatches beginning of string.
\ZMatches end of string. If a newline exists, it matches just before newline.
\zMatches end of string.
\GMatches point where last match finished.
\bMatches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.
\BMatches nonword boundaries.
\n, \t, etc.Matches newlines, carriage returns, tabs, etc.
\1...\9Matches nth grouped subexpression.
\10Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

Regular-expression Examples:

Literal characters:

ExampleDescription
/ruby/Match "ruby".
¥Matches Yen sign. Multibyte characters are suported in Ruby 1.9 and Ruby 1.8.

Character classes:

ExampleDescription
/[Rr]uby/ Match "Ruby" or "ruby"
/rub[ye]/ Match "ruby" or "rube"
/[aeiou]/Match any one lowercase vowel
/[0-9]/ Match any digit; same as /[0123456789]/
/[a-z]/Match any lowercase ASCII letter
/[A-Z]/Match any uppercase ASCII letter
/[a-zA-Z0-9]/Match any of the above
/[^aeiou]/ Match anything other than a lowercase vowel
/[^0-9]/Match anything other than a digit

Special Character Classes:

ExampleDescription
/./ Match any character except newline
/./m In multiline mode . matches newline, too
/\d/Match a digit: /[0-9]/
/\D/ Match a nondigit: /[^0-9]/
/\s/Match a whitespace character: /[ \t\r\n\f]/
/\S/ Match nonwhitespace: /[^ \t\r\n\f]/
/\w/ Match a single word character: /[A-Za-z0-9_]/
/\W/Match a nonword character: /[^A-Za-z0-9_]/

Repetition Cases:

ExampleDescription
/ruby?/ Match "rub" or "ruby": the y is optional
/ruby*/ Match "rub" plus 0 or more ys
/ruby+/Match "rub" plus 1 or more ys
/\d{3}/Match exactly 3 digits
/\d{3,}/Match 3 or more digits
/\d{3,5}/Match 3, 4, or 5 digits

Nongreedy repetition:

This matches the smallest number of repetitions:

ExampleDescription
/<.*>/Greedy repetition: matches "<ruby>perl>"
/<.*?>/ Nongreedy: matches "<ruby>" in "<ruby>perl>"

Grouping with parentheses:

ExampleDescription
/\D\d+/ No group: + repeats \d
/(\D\d)+/ Grouped: + repeats \D\d pair
/([Rr]uby(, )?)+/Match "Ruby", "Ruby, ruby, ruby", etc.

Backreferences:

This matches a previously matched group again:

ExampleDescription
/([Rr])uby&\1ails/Match ruby&rails or Ruby&Rails
/(['"])(?:(?!\1).)*\1/Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

Alternatives:

ExampleDescription
/ruby|rube/Match "ruby" or "rube"
/rub(y|le))/Match "ruby" or "ruble"
/ruby(!+|\?)/ "ruby" followed by one or more ! or one ?

Anchors:

This need to specify match position

ExampleDescription
/^Ruby/Match "Ruby" at the start of a string or internal line
/Ruby$/ Match "Ruby" at the end of a string or line
/\ARuby/ Match "Ruby" at the start of a string
/Ruby\Z/Match "Ruby" at the end of a string
/\bRuby\b/Match "Ruby" at a word boundary
/\brub\B/\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
/Ruby(?=!)/Match "Ruby", if followed by an exclamation point
/Ruby(?!!)/ Match "Ruby", if not followed by an exclamation point

Special syntax with parentheses:

ExampleDescription
/R(?#comment)/ Matches "R". All the rest is a comment
/R(?i)uby/ Case-insensitive while matching "uby"
/R(?i:uby)/ Same as above
/rub(?:y|le))/Group only without creating \1 backreference
http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm -------------------------------------------------------------------------------------------------------------- Disclaimer: I cannot assume any liability for the content of external pages. Solely the operators of those linked pages are responsible for their content. I make every reasonable effort to ensure that the content of this Web site is kept up to date, and that it is accurate and complete. Nevertheless, the possibility of errors cannot be entirely ruled out. I do not give any warranty in respect of the timeliness, accuracy or completeness of material published on this Web site, and disclaim all liability for (material or non-material) loss or damage incurred by third parties arising from the use of content obtained from the Web site. Registered trademarks and proprietary names, and copyrighted text and images, are not generally indicated as such on my Web pages. But the absence of such indications in no way implies the these names, images or text belong to the public domain in the context of trademark or copyright law. All product and firm names on www.erco.com are proprietary names of their corresponding owners All products and firm names used in this site are proprietary names of their corresponding owners. All rights are reserved which are not explicitly granted here.

Friday, June 22, 2012

Installation of Elastic Search and Mongo DB


Installation of Elastic Search and MongoDB
Preparation:
#sudo apt-get update
#sudo apt-get upgrade

Installing OpenJDk and its dependencies: It will take some time to complete full installation
#sudo apt-get install python-software-properties
#sudo add-apt-repository ppa:ferramroberto/java  ### show repository
#sudo apt-get update
#sudo apt-get install sun-java6-jre sun-java6-plugin openjdk-6-jre

Installing Elasticsearch:
#curl http://cloud.github.com/downloads/elasticsearch/elasticsearch/elasticsearch-0.19.4.tar.gz | tar zxv
#ln -s elasticsearch-0.19.4/ elasticsearch

Downloading and uncompressing Service Wrapper:
#curl -k -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz

Moving service wrapper to bin folder:
#mv *servicewrapper*/service elasticsearch/bin/

Removing Service Wrapper file:
#rm -Rf *servicewrapper*

Configuring ElasticSearch:

#ln -s `readlink -f elasticsearch/bin/service/elasticsearch` /usr/bin/elasticsearch_ctl
#sed -i -e 's|# cluster.name: elasticsearch|cluster.name: graylog2|' /opt/elasticsearch/config/elasticsearch.yml
#/etc/init.d/elasticsearch start

Verifying Elasticsearch status:
#curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

Output should be as given below
curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'
{
  "cluster_name" : "graylog2",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 1,
  "number_of_data_nodes" : 1,
  "active_primary_shards" : 0,
  "active_shards" : 0,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0
}

--------------------------------------------------------------------------------------------------------------

elasticsearch-head

A web front end for an ElasticSearch cluster

http://mobz.github.com/elasticsearch-head

Installing and Running

There are two ways of running and installing elasticsearch-head

Running as a plugin of ElasticSearch (this is the preferred method)

If you’ve installed the .deb package, then the plugin exectuable will be available at /usr/share/elasticsearch/bin/plugin.
  • sudo elasticsearch/bin/plugin -install mobz/elasticsearch-head
  • open http://localhost:9200/_plugin/head/
This will automatically download the latest version of elasticsearch-head from github and run it as a plugin within the elasticsearch cluster. In this mode;
  • elasticsearch provides a simple webserver to run head
  • elasticsearch-head automatically connects to the node that is running it
  • is available at http://localhost:9200/_plugin/head/ (or whatever the address of your cluster is)
  • Will not work with elasticsearch prior to version 0.17

Running as a standalone webapp

  • git clone git://github.com/mobz/elasticsearch-head.git
  • cd elasticsearch-head
  • open index.html
This will manually download the latest version of elasticsearch-head from github and run it standalone. In this mode;
  • elasticsearch-head is running from the file system and some features will not work
  • may have trouble connecting to the node if the node is protected by some security measures
  • works with any version of elasticsearch

Alternatives

elastisearch-head is a standalone webapp written in good-ol’ html5. This means, you can put it up on any webserver, run it directly from the filesystem, use it on an ipad, or put it on a floppy disk and carry it with you.
------------------------------------------------------------------------------------------------------

How to backup ElasticSearch with rsync
http://karussell.wordpress.com/2011/07/10/how-to-backup-elasticsearch-with-rsync/
Although there is a gateway feature implemented in ElasticSearch which basically recovers your index on start if it is corrupted or similar it is wise to create backups if there are bugs in Lucene or ElasticSearch (assuming you have set the fs gateway). The backup script looks as follows and uses the possibility to enable and disable the flushing for a short time:
# TO_FOLDER=/something
# FROM=/your-es-installation

DATE=`date +%Y-%m-%d_%H-%M`
TO=$TO_FOLDER/$DATE/
echo "rsync from $FROM to $TO"
# the first times rsync can take a bit long - do not disable flusing
rsync -a $FROM $TO

# now disable flushing and do one manual flushing
$SCRIPTS/es-flush-disable.sh true
$SCRIPTS/es-flush.sh
# ... and sync again
rsync -a $FROM $TO

$SCRIPTS/es-flush-disable.sh false

# now remove too old backups
rm -rf `find $TO_FOLDER -maxdepth 1 -mtime +7` &> /dev/null
E.g. you could call the backup script regularly (even hourly) from cron and it will create new backups. By the way – if you want to take a look on the settings of all indices (e.g. to check the disable flushing stuff) this might be handy:
curl -XGET 'localhost:9200/_settings?pretty=true'




MONGODB Installation Steps:

#sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10

To ensure database software you download is actually the software published by 10gen.

Now we have to add 10gen repository location in the system by adding the following line to the end of /etc/apt/sources.list

#nano /etc/apt/sources.list

Add this line to the bottom of the file
deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen

Save the file and exit

Update the repository list and install MongoDB
#sudo apt-get update
#sudo apt-get install mongodb-10gen

* This will take some time to complete depending upon your internet connection and the system performance.

When MongoDB has finished installing, run mongo just to check whether MongoDB is running correctly.
If you get the same as above it means MongoDB is successfully installed.

MongoDB configuration steps:
Now we need to create an admin user for mongo and add a user to mongo for the ‘graylog2’ collection. I like to use a Secure Password Generator (https://secure.pctools.com/guides/password/) to generate passwords.

Click on "Generate Password(s)" button for generating the number of secure Password(s).
For the sake of this documentation I have used some simple passwords.
use admin
db.addUser('admin', 'MongoDB@123')
db.auth('admin', 'MongoDB@123')
use graylog2
db.addUser('grayloguser', 'password@123')
db.auth('grayloguser', 'password@123')


Now you are ready with Elastic Search and MongoDB for installing Graylog2 Log management tool www.graylog2.org.

MongoDB connectivity problem Troubleshooting:
Error: couldn't connect to server 127.0.0.1 shell/mongo.js:79
exception: connect failed

Logs from  /var/log/mongodb/mongodb.log

***** SERVER RESTARTED *****


Mon Jul 30 08:39:27
Mon Jul 30 08:39:27 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Mon Jul 30 08:39:27
Mon Jul 30 08:39:27 [initandlisten] MongoDB starting : pid=886 port=27017 dbpath=/var/lib/mongodb 32-bit host=ubuntu-OptiPlex-990
Mon Jul 30 08:39:27 [initandlisten]
Mon Jul 30 08:39:27 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Mon Jul 30 08:39:27 [initandlisten] **       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Mon Jul 30 08:39:27 [initandlisten] **       with --journal, the limit is lower
Mon Jul 30 08:39:27 [initandlisten]
Mon Jul 30 08:39:27 [initandlisten] db version v2.0.6, pdfile version 4.5
Mon Jul 30 08:39:27 [initandlisten] git version: e1c0cbc25863f6356aa4e31375add7bb49fb05bc
Mon Jul 30 08:39:27 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_41
Mon Jul 30 08:39:27 [initandlisten] options: { config: "/etc/mongodb.conf", dbpath: "/var/lib/mongodb", logappend: "true", logpath: "/var/log/mongodb/mongodb.log" }
**************
Unclean shutdown detected.
Please visit http://dochub.mongodb.org/core/repair for recovery instructions.
*************
Mon Jul 30 08:39:27 [initandlisten] exception in initAndListen: 12596 old lock file, terminating
Mon Jul 30 08:39:27 dbexit:
Mon Jul 30 08:39:27 [initandlisten] shutdown: going to close listening sockets...
Mon Jul 30 08:39:27 [initandlisten] shutdown: going to flush diaglog...
Mon Jul 30 08:39:27 [initandlisten] shutdown: going to close sockets...
Mon Jul 30 08:39:27 [initandlisten] shutdown: waiting for fs preallocator...
Mon Jul 30 08:39:27 [initandlisten] shutdown: closing all files...
Mon Jul 30 08:39:27 [initandlisten] closeAllFiles() finished
Mon Jul 30 08:39:27 dbexit: really exiting now


To fix this please follow the step by step approach:
First try connecting with the below given command
1)
#mongod --config /etc/mongodb.conf --dbpath /var/lib/mongodb
Where /etc/mongodb.conf is your mongodb configuration file and /var/lib/mongodb is your database path.

If it gives the same connection error. Then remove the lock file of mongodb by issuing the command.
2)
Locate the "mongod.lock" fie
#rm -rf /var/lib/mongodb/mongod.lock

3)
Issue the Database repair command:
#mongod --repair --config /etc/mongodb.conf --dbpath /var/lib/mongodb

4)
Restart the mongod and mongo services.
#service mongod stop
#service mongod start

#service mongo stop
#service mongo start

5)
 Issue the Database connecting command.
#mongod --config /etc/mongodb.conf --dbpath /var/lib/mongodb&

6)
Try connecting
root@ubuntu# mongo
MongoDB shell version: 2.0.6
connecting to: test
>
You should be Happy once you see the above prompt.


Backup and Restoration of MongoDB.
Refer the link below for the steps and methods for backup of MongoDB.
http://docs.mongodb.org/manual/administration/backups/

mongodump syntax and options:
# mongodump --help
Export MongoDB data to BSON files.

options:
  --help                   produce help message
  -v [ --verbose ]         be more verbose (include multiple times for more
                           verbosity e.g. -vvvvv)
  --version                print the program's version and exit
  -h [ --host ] arg        mongo host to connect to ( /s1,s2 for
                           sets)
  --port arg               server port. Can also use --host hostname:port
  --ipv6                   enable IPv6 support (disabled by default)
  -u [ --username ] arg    username
  -p [ --password ] arg    password
  --dbpath arg             directly access mongod database files in the given
                           path, instead of connecting to a mongod  server -
                           needs to lock the data directory, so cannot be used
                           if a mongod is currently accessing the same path
  --directoryperdb         if dbpath specified, each db is in a separate
                           directory
  --journal                enable journaling
  -d [ --db ] arg          database to use
  -c [ --collection ] arg  collection to use (some commands)
  -o [ --out ] arg (=dump) output directory or "-" for stdout
  -q [ --query ] arg       json query
  --oplog                  Use oplog for point-in-time snapshotting
  --repair                 try to recover a crashed database
  --forceTableScan         force a table scan (do not use $snapshot)

# mongorestore --help
usage: mongorestore [options] [directory or filename to restore from]
options:
  --help                  produce help message
  -v [ --verbose ]        be more verbose (include multiple times for more
                          verbosity e.g. -vvvvv)
  --version               print the program's version and exit
  -h [ --host ] arg       mongo host to connect to ( /s1,s2 for sets)
  --port arg              server port. Can also use --host hostname:port
  --ipv6                  enable IPv6 support (disabled by default)
  -u [ --username ] arg   username
  -p [ --password ] arg   password
  --dbpath arg            directly access mongod database files in the given
                          path, instead of connecting to a mongod  server -
                          needs to lock the data directory, so cannot be used
                          if a mongod is currently accessing the same path
  --directoryperdb        if dbpath specified, each db is in a separate
                          directory
  --journal               enable journaling
  -d [ --db ] arg         database to use
  -c [ --collection ] arg collection to use (some commands)
  --objcheck              validate object before inserting
  --filter arg            filter to apply before inserting
  --drop                  drop each collection before import
  --oplogReplay           replay oplog for point-in-time restore
  --keepIndexVersion      don't upgrade indexes to newest version


eg:-
#mongodump -h 127.0.0.1 --dbpath /var/lib/mongodb -o /usr/bin/dump/2012-08-06
#mongorestore -h 127.0.0.1 /usr/bin/dump/2012-08-06



Now you are done with the Installation and configuration of Elasticsearch and MongoDB for Graylog2.
                Request everyone to put a comment about this blog and give your suggestions for improvement.
 --------------------------------------------------------------------------------------------------------------


Disclaimer:

I cannot assume any liability for the content of external pages. Solely the operators of those linked pages are responsible for their content.
I make every reasonable effort to ensure that the content of this Web site is kept up to date, and that it is accurate and complete. Nevertheless, the possibility of errors cannot be entirely ruled out. I do not give any warranty in respect of the timeliness, accuracy or completeness of material published on this Web site, and disclaim all liability for (material or non-material) loss or damage incurred by third parties arising from the use of content obtained from the Web site.
Registered trademarks and proprietary names, and copyrighted text and images, are not generally indicated as such on my Web pages. But the absence of such indications in no way implies the these names, images or text belong to the public domain in the context of trademark or copyright law.
All product and firm names on www.erco.com are proprietary names of their corresponding owners
 All products and firm names used in this site are proprietary names of their corresponding owners. All rights are reserved which are not explicitly granted here.

Monday, May 28, 2012

How to send Logs from Network Device > Syslog-ng > Logstash > Graylog2


Network Device > Syslog-ng > Logstash > Graylog2




Step 1

Cisco Device configuration for enabling Logging to a syslog server:
Global configuration:
(config)#logging trap debugging
logging origin-id hostname
logging facility syslog
logging host {ip_address_of_syslog_server} transport udp port {1000}      #####custom port for UDP
logging host {ip_address_of_syslog_server} transport tcp port {1540}      #####custom port for TCP
logging on

Juniper Device configuration for enabling Logging to a syslog server:
From Home screen Configuration>Report Settings>Syslog:


Step 2

Syslog Server configuration:


Install syslog-ng on the linux
#apt-get install syslog-ng

Step 3


Configure the syslog-ng.conf file for collecting and creating log files
# locate syslog-ng.conf
#nano  /etc/syslog-ng/syslog-ng.conf                 #######Default file location

Syslog-ng configuration File:
 -------------------------------------------------------------------------------------------------------
Paste the below contents in syslog-ng.conf:
###### Source Network definition ################
source s_network_udp {
  udp(ip(0.0.0.0) port(1000));
 };
source s_network_tcp {
  tcp(ip(0.0.0.0) port(1000) max-connections(5000));
};
########## Destination file Definition #########
########## Create the path if not already there /var/log/HOSTS/ #########
destination d_clients { file("/var/log/HOSTS/$HOST"); };
######### Collecting logs from devices and writing to files ##########
##### Source:s_network_udp and destination:d_clients defined in earlier steps
log { source(s_network_udp); destination(d_clients); };
-----------------------------------------------------------------------------------------------------------
Save the syslog-ng.conf and restart the service.
# service syslog-ng start | Restart
_____________________________________________________
Above step will create log entry files for all the devices sending syslog messages on port 1000 to the directory /var/log/HOSTS/

Making directory:
# mkdir /var/log/HOSTS/
# chmod XXX /var/log/HOSTS/

Verify it with command:
# ls -ll /var/log/HOSTS
eg:- /var/log/HOSTS/x.x.x.x.log
      /var/log/HOSTS/hostname.log

Step 4

Download latest Logstash file logstash-x.x.x-monolithic.jar from the site http://logstash.net/


Step 5

Create a new configuration file  "mylogstash.conf". The configuration file name could be anything eg:-sharmith.conf :)

Logstash configuration:
Logstash configuration file Name: mylogstash.conf
# vi mylogstash.conf
-----------------------------------------------------------------------------------------------------------
###INPUT###
input {
file {
 type => "Network"
 path => [ "/var/log/HOSTS/**/*" ]
 }
}
######## For reflecting the real Hostnames in Graylog2 interface ##########
filter {
  grok { match => [ "@source_path", "/var/log/HOSTS/%{HOSTNAME:host}" ] }
  mutate { replace => [ "@source_host", "%{host}" ] }
}
output {
  stdout {
  }

 elasticsearch {
      embedded => true
  }
  gelf {
    chunksize => 1420
#    facility => "logstash-gelf"              #########Default Setting ##########
    facility => "%{@type}"
    host => "127.0.0.1"
#    level => "INFO"                             #########Default Setting ##########
    level => "%{level}"                        
    port => 12201
    sender => "%{@source_host}"
  }
}
---------------------------------------------------------------------------------------------------------------

Step 6


Save the configuration and execute
# java -jar logstash-1.1.0-monolithic.jar agent -f mylogstash.conf -- web --backend elasticsearch:///?local&

To check the status of logstash service and start it automatically if it is not running.

1)      Create a Directory called "cron" in the folder /opt/logstash
               #mkdir cron

2)      Create a script file named "logstash_check.sh" inside directory "/opt/logstash/cron"
#nano logstash_check.sh
#### Paste the below portion to the file. Save it and exit. ##########
#!/bin/bash
cd /opt/logstash
PATH=/usr/bin:/bin:/opt/logstash:/usr/sbin/:/sbin
clear
echo "Checking Logstash service"

while true
do
    sleep 5  # check the process every 5 seconds
echo "Sleep timer passed"
    if [ `pgrep -c -f logstash-1.1.1-monolithic.jar` = 0 ]
echo "pgrep command executed"
    then
        echo "problem!"
        sendmail sharmithr@fss.co.in < /opt/logstash/email_text.txt
         java -jar logstash-1.1.1-monolithic.jar agent -f mylogstash.conf -- web --backend elasticsearch:///?local&
        echo "Mail sent to administrator"
        break
        echo "After Break"
        killall logstash_check.sh
else
         echo "Logstash working"
                killall logstash_check.sh
   fi
done

3)      check the script by running it manually
#./logstash_check.sh
In the paths directory mention the location of the commands by using the "locate" command.
eg:- locate echo
                 locate sendmail
                 locate logstash-1.1.1-monolithic.jar
                locate killall
4)      Issue the command on the command prompt before creating the file. This will show the status output.
# pgrep -c -f logstash-1.1.1-monolithic.jar
1


5)      Make the script run in the background automatically with the help of cron process.

#crontab -e

#### Paste the below portion to the file. Save it and exit. ##########
30 8 * * *       /opt/logstash/cron/logstash_check.sh



***I have mentioned those “echo” commands for verifying the working of the shell script. Upon your requirement “echo” commands could be edited or removed.

Logstash Tips:

Step 7

Graylog2 Server, Graylog2 Web Interface, Mongo DB and Elastic search configuration.
Refer the Step by Step Guide mentioned in the below links.

http://sharmith.blogspot.in/2012/08/installing-elasticsearch-on-fedora-1.html 
Graylog2 on Fedora


#nano /opt/graylog2-web-interface/config/mongoid.yml
Make sure that there is no space before the "production:" Space will lead to errors.



Creating Virtual Host in Apache 2

Paste the below lines in /etc/apache2/apache2.conf at the bottom of the file.
###############

   LoadModule passenger_module /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.$
   PassengerRoot /usr/local/lib/ruby/gems/1.9.1/gems/passenger-3.0.12
   PassengerRuby /usr/local/bin/ruby
################

Create a file called graylog2 in /etc/apache2/sites-available/ folder


Add the below lines as per your custom port in /etc/apache2/ports.conf file:
-----------------------------------------------------------------------------
NameVirtualHost *:8080          ######## Custom Port for Graylog2 #######
Listen 8080
 ----------------------------------------------------------------------------
Restart Apache2 service
# service apache2 restart | start


For verifying whether the logs are coming to your server, run the below command: tcpdump package required.
 Troubleshooting  & fine tuning tips:
#tcpdump dst port {graylog2_Listen_port}
#tcpdump dst port 514

To make Graylog2 listen to custom port:
Required if you are running multiple services on the same server.

First verify the port status.
# ps aux | grep {port}
If there are no services running on the specific port, configure the port in /etc/graylog2.conf file as given below:
------------------------------------------------------------------------------------------------
# On which port (UDP) should we listen for Syslog messages? (Standard: 514)
syslog_listen_port =xxx
#syslog_listen_port = 5400         ###########example configuration
syslog_protocol = udp
------------------------------------------------------------------------------------------------

Restart Graylog2 Service
# service graylog2-server restart | start | stop


Any queries or difficulties in configuring this please feel free to send a note to sharmith@gmail.com. Enjoy :)

I got an error message while trying to restart Graylog2 server after a system reboot. It gave me the error message "FATAL: org.graylog2.Main - Could not start syslog server core thread. Do you have permissions to listen on port 514?"
I checked whether any other ports are listening to that port or not but found none and tried changing the port to another but with no luck.

Fixed the issue by killing the java process.
#ps aux | grep java
It listed a Java process as given below
root      1469  1.0  1.9 1049788 62860 ?       Sl   10:10   0:19 /usr/bin/java -jar /opt/graylog2-server/graylog2-server.jar

Issued the command "kill 1469" to terminate the process and started the graylog2-server process and it worked fine.

Graylog2 Email notification Configuration:
To get email notification for Alarms and Subscriptions you need to enable email notification in Graylog2.
Main configuration files:
/opt/graylog2-web-interface/config/general.yml
/opt/graylog2-web-interface/config/email.yml
 ------------------------------------------------------------------------------------------------------------

Step 1)

Editing to be done in the files according to your SMTP server and domain name:
#nano /opt/graylog2-web-interface/config/general.yml
######## Contents of the file ######################
general:
  external_hostname: "your-graylog2.example.org" # Used for example to generate permalinks. Don't add 'http://' or trailing slashes.
  date_format: "%d.%m.%Y - %H:%M:%S" # http://ruby-doc.org/core/classes/Time.html#M000298 (strftime syntax)
  allow_deleting: false # Allowing deleting of messages negatively impacts performance
  allow_version_check: true # Enables manual (/versioncheck/index) and automatic (every 30min from overview page) version checking against graylog2.org via HTTP.
  # custom_cookie_name: graylog2_staging1 # Set an own cookie name - Useful for multiple deployments on same host like example.org/staging1/graylog2, example.org/staging2/grayl$

# Settings for stream subscription emails.
subscriptions:
  from: graylog2subscriptions@example.org
  subject: "[graylog2] Subscription"

# Settings for stream alarm emails.
streamalarms:
  from: graylog2alarms@example.org
  subject: "[graylog2] Stream alarm!"

hoptoad:
  enabled: false
  ssl: false
  api_key: 123

 
#nano /opt/graylog2-web-interface/config/email.yml
################Copy from here and paste it in the file ############
production:
  via: smtp # via: sendmail
  host: 10.x.x.x
  enable_starttls_auto: true
  port: 25
####### If you don’t want authentication comment out the next three lines ######
#  auth: plain # plain, login, cram_md5 - Comment out or remove to use no auth
#  user: somebody
#  password: yourpass
  domain: example.org # the HELO domain provided by the client to the server
#########################################################
---------------------------------------------------------------------------------------------------------------

Step 2)


Create a script file for executing Stream Alarm check and Stream Subscription check.
#nano run_rake_tasks_Alarms.sh
###### Copy the file and paste it into the file #############
#!/bin/bash
cd /opt/graylog2-web-interface/
PATH=/usr/local/bin
rake RAILS_ENV=production streamalarms:send

########################################################

### Path of the rake command could be found by issuing the command
#locate rake | more
#nano run_rake_tasks_ Subscriptions.sh
###### Copy the file and paste it into the file #############
#!/bin/bash
cd /opt/graylog2-web-interface/
PATH=/usr/local/bin
rake RAILS_ENV=production subscriptions:send
########################################################
 --------------------------------------------------------------------------------------------------------------

Step 3)

Create a cron file for executing your scripts based on your requirement.
I am pasting the configuration for executing the scripts every one minute.
#crontab –e
######## Copy and paste the below items to the cron file bottom##########

* * * * *       /opt/graylog2-web-interface/cron/run_rake_tasks_Subscription.sh
* * * * *       /opt/graylog2-web-interface/cron/run_rake_tasks_Alarms.sh
 --------------------------------------------------------------------------------------------------------------
Verify whether the below given screenshot is displayed in the Home screen right corner showing the services as running.


Request everyone to put a comment about this blog and give your suggestions for improvement.
 --------------------------------------------------------------------------------------------------------------


Disclaimer:
I cannot assume any liability for the content of external pages. Solely the operators of those linked pages are responsible for their content.
I make every reasonable effort to ensure that the content of this Web site is kept up to date, and that it is accurate and complete. Nevertheless, the possibility of errors cannot be entirely ruled out. I do not give any warranty in respect of the timeliness, accuracy or completeness of material published on this Web site, and disclaim all liability for (material or non-material) loss or damage incurred by third parties arising from the use of content obtained from the Web site.
Registered trademarks and proprietary names, and copyrighted text and images, are not generally indicated as such on my Web pages. But the absence of such indications in no way implies the these names, images or text belong to the public domain in the context of trademark or copyright law.
All product and firm names on www.erco.com are proprietary names of their corresponding owners
 All products and firm names used in this site are proprietary names of their corresponding owners. All rights are reserved which are not explicitly granted here.
All rights are reserved which are not explicitly granted here.
All product and firm names on www.erco.com are proprietary names of their corresponding owners

All product and firm names on www.erco.com are proprietary names of their corresponding owners