Shantanu's Blog

Database Consultant

September 30, 2009

 

Using Sakila test database

If you want to install a test database "sakila" can be downloaded from mysql site.
The foreign key checks stored procedure can also be downloaded and used with the database.

!#/bin/sh

wget http://downloads.mysql.com/docs/sakila-db.tar.gz

tar xvf sakila-db.tar.gz

cd sakila-db

mysqladmin create sakila

time mysql sakila < sakila-schema.sql

time mysql sakila < sakila-data.sql

lynx -source http://110.212.191.57/shantanu/checkforeign.txt | mysql sakila

_____

World Database :

wget http://downloads.mysql.com/docs/world.sql.gz
gunzip world.sql.gz
mysqladmin create world
time mysql world < world.sql
_____

If you want a really big database, try the test employee database available at launchpad.

wget http://launchpad.net/test-db/employees-db-1/1.0.6/+download/employees_db-dump-files-1.0.5.tar.bz2

Labels:


September 27, 2009

 

Helper table to calculate dates:

There are times when you want to extract only a part of the date field, for e.g. month-day. You can simply use the relevant function for e.g. quarter(dateval) or month(dateval), but it will not use indexes. In order to improve the query you can now simply
join the table with mycalendar on dateval filed and use the column quarter or month in the "where" clause.

Slow:
select count(*) from sometable where year(entry_date) = 2009 and month(entry_date) = 9;

Fast:
select count(*) from sometable as a inner join mycalendar as b on a.entry_date = b.dateval where b.year=2009 and b.month=9;

Apart from the speed advantage, you can now easily select the function as column name without actually executing it. For e.g.

select b.dayname, b.monthname from sometable as a inner join mycalendar as b on a.entry_date = b.dateval where ...

Today's date and its properties will be stored in this helper table as shown below:

mysql> select * from mycalendar where dateval = current_date()\G
*************************** 1. row ***************************
id: 40082
dateval: 2009-09-27
year: 2009
month: 9
dayofmonth: 27
dayname: Sunday
dayofweek: 1
dayofyear: 270
last_day: 2009-09-30
monthname: September
quarter: 3
to_days: 734042
week: 39
weekday: 6
weekofyear: 39
yearweek: 200939
1 row in set (0.00 sec)

_____

drop table if exists mycalendar;

CREATE TABLE `mycalendar` (
`id` int(11) NOT NULL auto_increment,
`dateval` date default NULL,
`year` year(4) default NULL,
`month` tinyint(4) default NULL,
`dayofmonth` tinyint(4) default NULL,
dayname varchar(100) default NULL,
`dayofweek` tinyint(4) default NULL ,
`dayofyear` int(11) default NULL,
`last_day` date default NULL,
`monthname` varchar(100) default NULL,
`quarter` tinyint(4) default NULL,
`to_days` int(11) default NULL,
`week` tinyint(4) default NULL,
`weekday` tinyint(4) default NULL,
`weekofyear` tinyint(4) default NULL,
`yearweek` mediumint(11) default NULL,
`yearmonth` mediumint(11) default NULL,
`yearmonthday` int(11) default NULL,
PRIMARY KEY (`id`),
KEY (dateval)
) ENGINE=MyISAM ;

Run the following shell script to generate days starting from 1900-01-01 to the year 2038
>> cat mycal.sh
#!/bin/sh
for (( i = 0 ; i < 50500 ; i++ ))
do
mysql -e"insert into test.mycalendar (dateval) select '$1' + interval $i day;"
done

>> sh mycal.sh '1901-01-01'

Run the following update statement to populate the column values.

update mycalendar set year = year(dateval), month = month(dateval), dayofmonth=day(dateval), dayname = dayname(dateval), dayofweek=dayofweek(dateval), dayofyear=dayofyear(dateval), last_day=last_day(dateval), monthname = monthname(dateval), quarter = quarter(dateval), to_days=to_days(dateval), week = week(dateval), weekday = weekday(dateval), weekofyear= weekofyear(dateval), yearweek = yearweek(dateval), yearmonth = date_format(dateval, '%Y%m'), yearmonthday = date_format(dateval, '%Y%m%d') ;

Labels:


September 24, 2009

 

Maatkit examples

If you want to check if the table exists on the second server, use --nocrc check. "count" check is disabled by default. If you want to check if the tables are the same based on the count of the records, use the second example.

mk-table-checksum

# mk-table-checksum h=localhost,u=root,P=3306 --databases myDB h=192.168.50.113,u=root,p=PassWd,P=3306 --databases myDB --nocrc | mk-checksum-filter
myDB.sometbl does not exist on slave 192.168.50.113:3306 at /usr/bin/mk-table-checksum line 4798.
myDB.othertbl does not exist on slave 192.168.50.113:3306 at /usr/bin/mk-table-checksum line 4798.
myDB.third does not exist on slave 192.168.50.113:3306 at /usr/bin/mk-table-checksum line 4798.

# mk-table-checksum h=localhost,u=root,P=3306 --databases myDB h=192.168.50.113,u=root,p=passWd,P=3306 --databases myDB --nocrc --count | mk-checksum-filter
DATABASE TABLE CHUNK HOST ENGINE COUNT CHECKSUM TIME WAIT STAT LAG
myDB tbla 0 192.168.50.113 InnoDB 0 NULL 0 0 NULL NULL
myDB tbla 0 localhost InnoDB 9 NULL 0 0 NULL NULL
myDB xyz 0 192.168.50.113 InnoDB 6250 NULL 0 0 NULL NULL
myDB xyz 0 localhost InnoDB 30 NULL 0 0 NULL NULL
myDB pqr does not exist on slave 192.168.50.113:3306 at /usr/bin/mk-table-checksum line 4798.
myDB pqr 0 192.168.50.113 MyISAM NULL NULL 0 0 NULL NULL
myDB pqr 0 localhost MyISAM 1 NULL 0 0 NULL NULL
myDB mnp 0 192.168.50.113 InnoDB 51 NULL 0 0 NULL NULL
myDB mnp 0 localhost InnoDB 52 NULL 0 0 NULL NULL

You can check all the databases against the other server using the shell script.
#/bin/sh
for each dbName in `mysqlshow`
do
mk-table-checksum h=localhost,u=root,P=3306 --databases $dbName h=192.168.100.101,u=root,p=PassWord,P=3306 --databases $dbName --no-crc --count | mk-checksum-filter
done

_____

mk-table-sync

On Localhost:
+------+---------------------+
| id | tran_time |
+------+---------------------+
| 1 | 2011-06-07 07:58:51 |
| 1 | 2011-06-07 17:38:51 |
+------+---------------------+

On 10.10.10.24:
+------+---------------------+
| id | tran_time |
+------+---------------------+
| 1 | 2011-06-07 07:58:51 |
+------+---------------------+
_____

When you will need to sync the localhost data with remote 24 server, you will need one insert statement. Whereas if you want to sync the remote 24 with the local, then in that case, one delete is required.

/usr/bin/mk-table-sync --print --no-check-slave h=localhost,u=shantanu,p=shantanu@123,P=3306 --databases test --tables tz1 h=10.10.10.24,u=shantanu,p=shantanu@123,P=3306 --databases test --tables tz1 | more
INSERT INTO `test`.`tz1`(`id`, `tran_time`) VALUES ('1', '2011-06-07 17:38:51')

/usr/bin/mk-table-sync --print --no-check-slave h=10.10.10.24,u=shantanu,p=shantanu@123,P=3306 --databases test --tables tz1 h=localhost,u=shantanu,p=shantanu@123,P=3306 --databases test --tables tz1 | more
DELETE FROM `test`.`tz1` WHERE `id`='1' AND `tran_time`='2011-06-07 17:38:51' LIMIT 1

* The print option will display the statements instead of actually executing it.
* Change the --print to --execute if you want to really sync the data.

Example command:

mk-table-sync --execute --charset utf8 --verbose --no-foreign-key-checks h=1.2.3.4,d=sync,t-uad_b_stop,u=myuser,p=mypass

_____

parallel-dump and restore

Dump all the tables from someDB database, excluding the tables starting with the name "mail" and "qb". For e.g. mail_backup, mail_head

$ time /usr/bin/mk-parallel-dump -h'localhost' --no-gzip --base-dir '/home/develop/pdump' --databases 'someDB' --ignore-tables-regex 'mail|qb'
--ignore-tables 'tbl1,tbl2,tbl3,tbl4' --socket '/tmp/mysql.sock'

We can restore all or any one table (for e.g. Customer) using the following statement.
$ /usr/bin/mk-parallel-restore -h'localhost' -u'root' --database 'shantanu' --tables 'Customer' '/home/develop/pdump'

You may need to change the ownership of the folder /pdump like this...
rm -rf /pdump/
mkdir /pdump/
chmod 777 /pdump/

# in order to restore a single table for e.g. ach_routing_info use the following command
# /usr/bin/mk-parallel-restore -h'localhost' -u'shantanu' -p'xyz' --no-foreign-key-checks --database 'customer' --tables 'ach_routing_info' '/pdump'
_____

Copy the entire database from one server to another
Master:
mkdir -p /home/shantanu/today`date +%Y%m%d`
mk-parallel-dump --base-dir /home/shantanu/today`date +%Y%m%d` --databases mumbaicentral
scp -r /home/shantanu/today`date +%Y%m%d`/default/ root@199.199.199.199:/home/shantanu/

Slave on 199.199.199.199:
mk-parallel-restore /home/shantanu/default/mumbaicentral/ --database mumbaicentral

# The binary log position is dumped to a file named 00_master_data.sql in the --base-dir.
_____

Install Maatkit

These are the 5 steps to download and install Maatkit

wget http://maatkit.googlecode.com/files/maatkit-7119.tar.gz
tar -zxf maatkit-7119.tar.gz
cd maatkit-7119
perl Makefile.PL
make install

Confirm that everything is working:
mk-show-grants

OR

wget http://maatkit.googlecode.com/files/maatkit-7540-1.noarch.rpm
yum localinstall --nogpgcheck maatkit-7540-1.noarch.rpm --skip-broken

_____

mk-loadavg

Load Avg Utility: There are times when you need to collect the server stats when the application is running too slow or doesn't work at all. You will need to look at process list, IO and VM stats, mysql processlist, etc. You can save these stats using a cron, but I need the data only when there is a trigger, for e.g. average load is more than 50%
loadavg utility from maatkit does exactly that.


1) Download the maatkit utility called load Average.
wget http://www.maatkit.org/get/mk-loadavg

2) Write a shell script that will collect all the relevant stats when the processor load is too high. for e.g.
#!/bin/bash
ps -eaf >> collected/today.txt 2>&1 &

3) Change the permission of this file to 777
chmod 777 collect-stats.sh

4) Call the program whenever there are more than 50 mysql threads running simultaneously.
perl mk-loadavg -uroot -pPassWd --watch "Status:status:Threads_running:>:50" --execute-command /home/shantanu/collect-stats.sh

http://www.maatkit.org/doc/mk-loadavg.html#OPTIONS

The server stats those are really needed to be looked at...
> statsFile.txt
ps -eaf >> statsFile.txt 2>&1 &
top -bn1 > statsFile.txt 2>&1 &
mysql -uroot -pPassWOrd -e 'show innodb status\G show full processlist\G' >> statsFile.txt 2>&1 &
vmstat 1 30 > statsFile.txt 2>&1 &
iostat -dx 1 30 > statsFile.txt 2>&1 &
mysqladmin -uroot -pPassWord ext > statsFile.txt 2>&1 &

_____

mk-kill

# mk-kill --match-command Sleep --print --no-only-oldest
# mk-kill --match-command Sleep --kill --no-only-oldest

Print, do not kill, queries running longer than 60s:
mk-kill --busy-time 60 --print --match-command Query

Check for sleeping processes and kill them all every 10s:
mk-kill --match-command Sleep --kill --no-only-oldest --interval 10

--match-command
Common Command values are:

Query
Sleep
Binlog Dump
Connect
Delayed insert
Execute
Fetch
Init DB
Kill
Prepare
Processlist
Quit
Reset stmt
Table Dump

--match-state --ignore-state
Common State values are:

Locked
login
copy to tmp table
Copying to tmp table
Copying to tmp table on disk
Creating tmp table
executing
Reading from net
Sending data
Sorting for order
Sorting result
Table lock
Updating

--match-info --ignore-info
The Info column of the processlist shows the query that is being executed or NULL if no query is being executed.

--all
If some ignore options are specified, then every connection except ignored connections are killed.

--idle-time
Kill connections that have been idle/sleeping for longer than this time. The queries must be in Command=Sleep status. This matches a query's Time value as reported by SHOW PROCESSLIST.

--ignore-command
Ignore queries whose Command matches this Perl regex.
See --match-command.
_____

# mysql -e"select sleep(100)" &
[1] 20148

# mysql -e"show processlist;"
+--------+------------+--------------------+--------+-------------+------+----------------------------------------------------------------+-------------------+
| Id | User | Host | db | Command | Time | State | Info |
+--------+------------+--------------------+--------+-------------+------+----------------------------------------------------------------+-------------------+
| 125873 | root | localhost | NULL | Sleep | 43 | | NULL |
| 125895 | wuser | 110.10.10.183:57113 | mydb | Sleep | 76 | | NULL |
| 125932 | wuser | 110.10.10.82:57090 | this | Sleep | 61 | | NULL |
| 125934 | slave_user | 110.10.10.3:60019 | NULL | Binlog Dump | 54 | Has sent all binlog to slave; waiting for binlog to be updated | NULL |
| 125942 | wuser | 110.10.10.62:32913 | yourdb | Sleep | 47 | | NULL |
| 125963 | wcuser | 110.10.10.62:57956 | yourdb | Sleep | 28 | | NULL |
| 125968 | root | localhost | NULL | Query | 26 | executing | select sleep(100) |
| 125985 | wuser | 110.10.10.62:57976 | somedv | Sleep | 15 | | NULL |
| 125997 | root | localhost | NULL | Query | 0 | NULL | show processlist |
+--------+------------+--------------------+--------+-------------+------+----------------------------------------------------------------+-------------------+

# mk-kill --match-state executing --match-command Query --ignore-info NULL --print
# 2011-01-11T02:00:22 KILL 125968 (Query 30 sec) select sleep(100)

You can add the command to the cron so that it will check the processlist every minute and log/ mail the killed queries as well!


# kill query running too long
* * * * * /usr/bin/mk-kill --print --daemonize --interval 5 --busy-time 2000 --ignore-info '(?i-smx:^insert|^update|^delete)' --match-info '(?i-xsm:select)' --log /var/log/mk-kill.log --execute-command '(echo "Subject: mk-kill query found on `hostname`"; tail -1 /var/log/mk-kill.log) | mail -s "mk-kill on `hostname`" shantanu.oak@gmail.com' --kill-query >> /home/shantanu/kill_success.txt 2>> /home/shantanu/kill_err.txt


delay slave by 10 minutes

mk-slave-delay --delay 1h --interval 59s --run-time 10m 10.10.10.10

Labels: ,


September 22, 2009

 

The start-up message

I installed MySQL on my server and when I first started it, I got the following message.

This seems to be very helpful tip for the beginners.


# service mysqld start
Initializing MySQL database: WARNING: The host 'shantanuserver.com' could not be looked up with resolveip.
This probably means that your libc libraries are not 100 % compatible
with this binary MySQL version. The MySQL daemon, mysqld, should work
normally with the exception that host name resolving will not work.
This means that you should use IP addresses instead of hostnames
when specifying MySQL privileges !
Installing MySQL system tables...
OK
Filling help tables...
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:
/usr/bin/mysqladmin -u root password 'new-password'
/usr/bin/mysqladmin -u root -h shantanuserver.com password 'new-password'
See the manual for more instructions.
You can start the MySQL daemon with:
cd /usr ; /usr/bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl
cd mysql-test ; perl mysql-test-run.pl

Please report any problems with the /usr/bin/mysqlbug script!

The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at http://shop.mysql.com
[ OK ]
Starting MySQL: [ OK ]

Labels:


September 20, 2009

 

Introduction to PEAR - Barcodes

set_include_path('.:/usr/share/pear');
require_once 'Image/Barcode.php';
$bar_code_data = $_GET['myvar'];
Image_Barcode::draw($bar_code_data, 'postnet', 'png');

The file can be called with the variable "myvar=" as shown here...
mybarcode.php?myvar=dbid123

The ‘Image_Barcode’ library supports the following barcode types:
code39, code128, ean13, int25, postnet, upca

Labels:


 

Introduction to PEAR - Number to Words

There is a very useful Number to Words Pear extension available.

http://pear.php.net/package/Numbers_Words

If you need to print "One Hundred forty five Rupees Fifty paisa" instead of "145.50", here is the 2 lines code...

require_once('Numbers/Words.php');

printf("%s\n", Numbers_Words::tocurrency(145.50,"en_GB"));
_____

If you want the Indian Currency

Change the lang.en_GB file

'GBP' => array(array('pound', 'pounds'), array('pence', 'pence')),
To something like this....
'GBP' => array(array('Rupee', 'Rupees'), array('paisa', 'paisa')),

Labels:


September 19, 2009

 

Mysql backup and restore

You can add the following cron to take the hourly / daily backup of your important database. For e.g. Drupal

time mysqldump -uroot -pPassWord Drupal --routines --single-transaction --master-data=2 > /backup/dumpmysql/Drupal`date +'%d-%b-%Y-%H-%M'`.sql

The following command will keep the latest 2 backups and remove all the Drupal backup files from the directory.

(ls /backup/dumpmysql/Drupal* -t | head -n 2; ls /backup/dumpmysql/Drupal*)| sort | uniq -u | xargs rm

_____

If in case Master MySQL DB crashes, you still have a few options available with you to restore data in very short time.

1) If hourly backups are available, restore DB from that backup file and then run the sql statements from relay log of slave.

mysqlbinlog /var/run/mysqld/mysqld-relay-bin.* --start-datetime="`date +'%Y-%m-%d\ %H:00:00'`" | more

2) If you have only daily backups and slave relay log is not available, you can check if binary files on master server can be used.
You can also execute the statements related only to a single table for e.g. "tickets" like this...

mysqlbinlog /var/log/mysql/mysql-bin.000073 --start-datetime="`date -d"2 days ago" +'%Y-%m-%d\ %H:%M:%S'`" | awk '/tickets/,/;/' | more

mysqlbinlog /var/log/mysql/mysql-bin.* --start-datetime="`date -d"3 hours ago" +'%Y-%m-%d\ %H:%M:%S'`" | awk '/( seats | tickets | ticket_details )/,/;/' | more

(replace the "more" command with mysql -hMyHost -uroot -pPassWD Drupal )

Labels:


September 16, 2009

 

Analysing access_log

Apache access log is one of the best way to analyse if your application is working as expected or not. But there are a few changes those needs to be made to httpd.conf file so that the data can be dumped to MySQL table.

# cat /etc/httpd/conf/httpd.conf | grep LogFormat
#Old Format to be changed to the new format
#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "\"%h\" \"%l\" \"%u\" \"%{%Y-%m-%d %H:%M:%S}t\" \"%r\" \"%>s\" \"%b\" \"%{Referer}i\" \"%{User-Agent}i\"" combined

use db_Name;
CREATE TABLE `access_log` (
`ip` varchar(100) NOT NULL default '',
`RFC` varchar(100) default NULL,
`user` varchar(100) default NULL,
`mytime` datetime default NULL,
`request` varchar(100) default NULL,
`response` int(11) NOT NULL default '0',
`bytes` bigint(20) NOT NULL default '0',
`referer` varchar(100) default NULL,
`browser` varchar(500) default NULL,
UNIQUE KEY `mygroup` (`ip`,`RFC`,`user`,`mytime`,`request`)
);

mysqlimport --ignore --fields-terminated-by ' ' --fields-enclosed-by '"' db_Name /var/log/httpd/access_log

Pages being accessed:
mysql> select distinct(substring_index(referer, '?', -1)) as link from access_log where (substring_index(referer, '?', -1)) like 'http%' order by link;

IP addresses accessing the application:
mysql> select ip, count(*) as cnt from access_log group by ip order by cnt desc;

_____

Once the access data is imported, you can create an error_code table to compare the response codes from access log and analyse.

CREATE TABLE `mycode` (
`id` int(11) NOT NULL auto_increment,
`response` int(11) default NULL,
`expl` varchar(100) default NULL,
`type` varchar(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
INSERT INTO `mycode` VALUES (1,200,'OK','OK'),(2,202,'ACCEPTED','OK'),(3,201,'Created','OK'),(4,203,'Partial','OK'),(5,400,'Bad Request','error'),(6,401,'Unauthorized','error'),(7,402,'Payment Requested','error'),(8,403,'Forbidden','error'),(9,404,'Not Found','error'),(10,500,'Internal Error','error'),(11,501,'Not Implemented','error'),(12,502,'Service temporarily overloaded','error'),(13,503,'Gateway timeout','error'),(14,301,'Moved','OK'),(15,302,'Found','OK'),(16,303,'Modified','OK'),(17,304,'Not Modified','OK'),(18,405,'Method not allowed','error');

Page requests having error code:
mysql> select a.response, b.expl, b.type, count(*) as cnt from access_log as a inner join mycode as b on a.response = b.response where request not like '%favicon.ico%' group by response;

mysql> select a.response, a.request from access_log as a inner join mycode as b on a.response = b.response where b.type = 'error' and request not like '%favicon%' order by a.response;
Analysing access_log
Apache access log is one of the best way to analyse if your application is working as expected or not. But there are a few changes those needs to be made to httpd.conf file so that the data can be dumped to MySQL table.

# cat /etc/httpd/conf/httpd.conf | grep LogFormat
#Old Format to be changed to the new format
#LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "\"%h\" \"%l\" \"%u\" \"%{%Y-%m-%d %H:%M:%S}t\" \"%r\" \"%>s\" \"%b\" \"%{Referer}i\" \"%{User-Agent}i\"" combined

use db_Name;
CREATE TABLE `access_log` (
`ip` varchar(100) NOT NULL default '',
`RFC` varchar(100) default NULL,
`user` varchar(100) default NULL,
`mytime` datetime default NULL,
`request` varchar(100) default NULL,
`response` int(11) NOT NULL default '0',
`bytes` bigint(20) NOT NULL default '0',
`referer` varchar(100) default NULL,
`browser` varchar(500) default NULL,
UNIQUE KEY `mygroup` (`ip`,`RFC`,`user`,`mytime`,`request`)
);

mysqlimport --ignore --fields-terminated-by ' ' --fields-enclosed-by '"' db_Name /var/log/httpd/access_log

Pages being accessed:
mysql> select distinct(substring_index(referer, '?', -1)) as link from access_log where (substring_index(referer, '?', -1)) like 'http%' order by link;

IP addresses accessing the application:
mysql> select ip, count(*) as cnt from access_log group by ip order by cnt desc;

_____

Once the access data is imported, you can create an error_code table to compare the response codes from access log and analyse.

CREATE TABLE `mycode` (
`id` int(11) NOT NULL auto_increment,
`response` int(11) default NULL,
`expl` varchar(100) default NULL,
`type` varchar(100) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
INSERT INTO `mycode` VALUES (1,200,'OK','OK'),(2,202,'ACCEPTED','OK'),(3,201,'Created','OK'),(4,203,'Partial','OK'),(5,400,'Bad Request','error'),(6,401,'Unauthorized','error'),(7,402,'Payment Requested','error'),(8,403,'Forbidden','error'),(9,404,'Not Found','error'),(10,500,'Internal Error','error'),(11,501,'Not Implemented','error'),(12,502,'Service temporarily overloaded','error'),(13,503,'Gateway timeout','error'),(14,301,'Moved','OK'),(15,302,'Found','OK'),(16,303,'Modified','OK'),(17,304,'Not Modified','OK'),(18,405,'Method not allowed','error');

Page requests having error code:
mysql> select a.response, b.expl, b.type, count(*) as cnt from access_log as a inner join mycode as b on a.response = b.response where request not like '%favicon.ico%' group by response;

mysql> select a.response, a.request from access_log as a inner join mycode as b on a.response = b.response where b.type = 'error' and request not like '%favicon%' order by a.response;

_____

The following shell script can be used to import the data to a central server.

#!/bin/sh
# The following line will change the logformat to include response time
# sed -i 's/^LogFormat.*combined$/LogFormat "\\\"%h\\\" \\\"%l\\\" \\\"%u\\\" \\\"%{%Y-%m-%d %H:%M:%S}t\\\" \\\"%r\\\" \\\"%>s\\\" \\\"%b\\\" \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\" \\\"%D\\\" \\\"%T\\\" \\\"%q\\\" \\\"%f\\\" \\\"%v\\\" " combined/' /etc/httpd/conf/httpd.conf

# find database name
mydb=$(mysqlshow -uroot -ptrimax | awk '{print $2}' | egrep -v 'Databases|information_schema|mysql|test|lost\+found|freshnew1' | sed '/^$/d')

# add the database name to the end of the log
sed "s/$/\"$mydb\"/" /var/log/httpd/access_log | tail > /home/develop/access_log

# import the log to a central server
mysqlimport -h111.222.333.444 -uroot -pPassWord --local --ignore --fields-terminated-by ' ' --fields-enclosed-by '"' DBName /home/develop/access_log

_____


1) Change the logformat so that fields are terminated by pipe "|"
2) Create a table in mysql and load the data.
3) Upload log file to S3 and then import it to Redshift - data warehouse software.

cp /etc/apache2/apache2.conf /etc/apache2/apache2.conf.back

sed -i  's/^LogFormat.*combined$/LogFormat "%h | %l | %u | %{%Y-%m-%d %H:%M:%S}t | %r | %>s | %O | %{Referer}i | %{User-Agent}i | %B | %D | %T | %q | %f | %v " combined/' /etc/apache2/apache2.conf

/etc/init.d/apache2 restart
_____

use test;
drop table access;

CREATE TABLE `access` (
`ip` varchar(100) NOT NULL default '',
`RFC` varchar(100) default NULL,
`user` varchar(100) default NULL,
`request_time` datetime default NULL,
`request_first_line` varchar(255) default NULL,
`status` int(11) NOT NULL default '0',
`bytes_sent` bigint(20) NOT NULL default '0',
`referer` varchar(100) default NULL,
`user_agent` varchar(500) default NULL,
`bytes_sent_exc_header` bigint(20),
`response_time_microsec` bigint(20),
`response_time_sec` bigint(20),
`query_string` varchar(255),
`request_file` varchar(255),
`server_name` varchar(255),
UNIQUE KEY `mygroup` (`ip`,`RFC`,`user`,`request_time`,`request_first_line`)
);

load data infile 'access.log' into table access fields terminated by  '|';
_____

# copy the file to S3 and then delete or move the file to a different location

s3cmd put access.log.2.gz s3://Aug26/access.log.2.aug26_11_19.gz
rm access.log.2.gz

 

Labels:


September 13, 2009

 

Binary analysis

The following 1 line Linux command (reformatted for ease of reading) gave me the report of update/ insert statements from binary file 999

$ mysqlbinlog /path/to/mysql-bin.000999 | \
grep -i -e "^update" -e "^insert" -e "^delete" -e "^replace" -e "^alter" | \
cut -c1-100 | tr '[A-Z]' '[a-z]' | \
sed -e "s/\t/ /g;s/\`//g;s/(.*$//;s/ set .*$//;s/ as .*$//" | sed -e "s/ where .*$//" | \
sort | uniq -c | sort -nr

33389 update e_acc
17680 insert into r_b
17680 insert into e_rec
14332 insert into rcv_c
13543 update e_rec
10805 update loc
3339 insert into r_att
2781 insert into o_att

Labels:


 

Search "String" from mysql files

The unix tool strings can be used against many types of files. In particular, though, you can use strings on the mysql/user.MYD file to see the username, host, and password hash.

$ cd /data/mysql/
$ strings -f */mysql/user.MYD | grep username
instance5/mysql/user.MYD: username*XXX
instance7/mysql/user.MYD: username*XXX

$ grep username */mysql/user.MYD
Binary file instance5/mysql/user.MYD matches
Binary file instance7/mysql/user.MYD matches

(note that strings only shows strings longer than 3 characters, so if your host or username is 3 characters or less, it will not show up in the output of strings. You can change this with the -n option to strings)

Labels:


 

Query Wikipedia via console over DNS

Query Wikipedia by issuing a DNS query for a TXT record. The TXT record will also include a short URL to the complete corresponding Wikipedia entry. You can also write a little shell script like:

$ cat wikisole.sh
#!/bin/sh
dig +short txt ${1}.wp.dg.cx

and run it like
./wikisole.sh unix

were your first option ($1) will be used as search term.
You can also create a BASH function and syntax will look something like...

wiki india

Labels:


Archives

June 2001   July 2001   January 2003   May 2003   September 2003   October 2003   December 2003   January 2004   February 2004   March 2004   April 2004   May 2004   June 2004   July 2004   August 2004   September 2004   October 2004   November 2004   December 2004   January 2005   February 2005   March 2005   April 2005   May 2005   June 2005   July 2005   August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   May 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   June 2007   July 2007   August 2007   September 2007   October 2007   November 2007   December 2007   January 2008   February 2008   March 2008   April 2008   July 2008   August 2008   September 2008   October 2008   November 2008   December 2008   January 2009   February 2009   March 2009   April 2009   May 2009   June 2009   July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   February 2010   March 2010   April 2010   May 2010   June 2010   July 2010   August 2010   September 2010   October 2010   November 2010   December 2010   January 2011   February 2011   March 2011   April 2011   May 2011   June 2011   July 2011   August 2011   September 2011   October 2011   November 2011   December 2011   January 2012   February 2012   March 2012   April 2012   May 2012   June 2012   July 2012   August 2012   October 2012   November 2012   December 2012   January 2013   February 2013   March 2013   April 2013   May 2013   June 2013   July 2013   September 2013   October 2013   January 2014   March 2014   April 2014   May 2014   July 2014   August 2014   September 2014   October 2014   November 2014   December 2014   January 2015   February 2015   March 2015   April 2015   May 2015   June 2015   July 2015   August 2015   September 2015   January 2016   February 2016   March 2016   April 2016   May 2016   June 2016   July 2016   August 2016   September 2016   October 2016   November 2016   December 2016   January 2017   February 2017   April 2017   May 2017   June 2017   July 2017   August 2017   September 2017   October 2017   November 2017   December 2017   February 2018   March 2018   April 2018   May 2018   June 2018   July 2018   August 2018   September 2018   October 2018   November 2018   December 2018   January 2019   February 2019   March 2019   April 2019   May 2019   July 2019   August 2019   September 2019   October 2019   November 2019   December 2019   January 2020   February 2020   March 2020   April 2020   May 2020   July 2020   August 2020   September 2020   October 2020   December 2020   January 2021   April 2021   May 2021   July 2021   September 2021   March 2022   October 2022   November 2022   March 2023   April 2023   July 2023   September 2023   October 2023   November 2023   April 2024   May 2024   June 2024   August 2024   September 2024   October 2024   November 2024   December 2024  

This page is powered by Blogger. Isn't yours?