Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Monday, December 14, 2009

Help Save MySQL!

We are using MySQL, help save it!

Creator of MySQL, Michael "Monty" Widenius, blogged this passed Saturday urging all MySQL users to show their support. As we all know already, Oracle has acquired Sun and this puts MySQL's future in their hands. Monty outlines the dangers that are near if Oracle gets their way. The main form of showing support is to email the European Commission.

Monty was even kind enough to set up email templates so now all you need to do is copy/paste! I've reposted below:


Send this to: comp-merger-registry@ec.europa.eu
If you want to keep us updated, send a copy to ec@askmonty.org

If you have extra time to help, fill in the following, if not, just skip to the main text.

Name:
Title:
Company:
Size of company:
How many MySQL installations:
Total data stored in MySQL (megabyte):
For what type of applications is MySQL used:
Should this email be kept confidential by EC: Yes/No

Copy or use one of the below texts as a base for your answer:

a)
I don't trust that Oracle will take good care of MySQL and MySQL should be divested to another company or foundation that have everything to gain by developing and promoting MySQL. One should also in the future be able to combine MySQL with closed source application (either by exceptions, a more permissive license or be able to dual license MySQL under favourable terms)

b)

I think that Oracle could be a good steward of MySQL, but I would need EC to have legally binding guarantees from Oracle that:
- All of MySQL will continue to be fully Open Source/free software in the future (no closed source modules).
- Open Source version and dual-licensed version of MySQL should have same source (like today).
- That development will be done in community friendly way.
- The manual should be released under a permissive license (so that one can fork it, the same way one can fork the server)
- That MySQL should be released under a more permissive license to ensure that forks can truly compete with Oracle if Oracle is not a good steward after all.
Alternatively:
- One should be able to always buy low priced commercial licenses for MySQL.
- All of the above should be perpetual and irrevocable.

There should also be mechanism so that if Oracle is not doing what is expected of it, forks should be able to compete with Oracle

c)
I trust Oracle and I suggest that EC will approve the deal unconditionally.


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

Tuesday, April 7, 2009

Moving a MySQL Cluster to New Hardware

Well, it came to that point in any server's life, it could no longer add any additional disks for space, the cost to upgrade the memory and/or hard disks don't outweigh the benefits of upgrading to new hardware; it's time to put these babies to sleep.

So one of our active/passive MySQL clusters had a three hour maintenance window last night (technically this morning: 12am-3am). The servers came in a few weeks earlier so I had them prepped beforehand. Though, how do you minimize downtime while moving moving the databases over? Well, obviously don't take down the server unless absolutely necessary and of course automate as much of the process as possible!

12am: I'll kick off my script that backs up all DBs in our cluster and saves them in a mount point on a SAN that the new servers can read as well.
## I really could have run this process before 12am as it didn't cause an outage. Ah well, next time.

~12:45am: Now that we have the data, we can now take down the MySQL cluster. I basically rebooted the cluster servers with new IP addresses and hostnames. I now set the IP addresses of the new cluster boxes to have the original IP addresses of the old cluster. See what I did there? Basically, we have a lot of web apps pointing to the DNS of the MySQL cluster, so we need that DNS. (Yes, yes, we could've just updated DNS as well; it's a long story, but basically my department doesn't handle DNS, so going this route is more seamless.)

I already set up replication in MySQL, but as the hostnames have now changed, well replication broke. This was the only snag in the maintenance really. Basically, what happened was MySQL was looking for the old relay logs with the old hostname. Enter, MySQL's nice documentation. I just needed to do this really:

shell< cat new_host_name-relay-bin.index >> old_host_name-relay-bin.index

shell< mv old_host_name-relay-bin.index new_host_name-relay-bin.index


1am: Now that replication is working, all I needed to do was load the data, which is one last script to run.

Here's the basic rundown:
- find the db dump
- create the db
- gunzip the db dump to a tmp dir
- load the dump to the db
- run GRANTs for whatever user


#!/usr/bin/perl -w

# mysqldumpload.pl

use strict;
use DBI;
use File::Find;

my $dbuser = qw(dbuser);
my $dbpass = qw(dbpass);
my $backupdir = "/mnt/backup/mysql";
my $dumpdir = "/usr/local/tmp/dump";

my $dbh = DBI->connect("DBI:mysql:mysql",$dbuser,$dbpass)
or die "Couldn't connect to db: $!";

my @files;

find(\&findFile, $backupdir);


sub findFile {
my $file = $File::Find::name;
# if it's a db, another_db, or another_db2 process it!
if ($_ =~ /db/ or $_ =~ /another_db/ or $_ =~ /another_db2/) {
print "Processing $_...\n";
my $dump = $_;
$dump =~ s/\.gz//g;
my $mysqldb = $dump;
$mysqldb =~ s/\.sql//g;
my $sql = qq!CREATE DATABASE $mysqldb!;
$sth = $dbh->prepare($sql);
print "$sql\n";
$sth->execute();
my $dumpfile = "$dumpdir/$dump";
my $gunzip = qq!gunzip -c $file > $dumpfile!;
print "$gunzip\n";
system($gunzip);
my $mysqlload = qq!mysql --user=$dbuser --password=$dbpass $mysqldb < $dumpfile!;
print "$mysqlload\n";
system($mysqlload);
if ($_ =~ m/db/) {
$sql = qq!GRANT ALL PRIVILEGES on `$mysqldb`.* TO 'dbuser'\@'%'!;
$sth = $dbh->prepare($sql);
print "$sql\n";
$sth->execute();
}
if ($_ =~ m/another_db/) {
$sql = qq!GRANT ALL PRIVILEGES on `$mysqldb`.* TO 'another_db'\@'%'!;
$sth = $dbh->prepare($sql);
print "$sql\n";
$sth->execute();
}
}
}


~1:45am: The script finally finished with the last DB around 1:45am. Not too bad!

Now, as you can see, we have a fairly simple setup. We only wanted to move over certain DBs and only needed a few db users to grant privileges to. With minor modifications to this script, you can have it fit your needs.

*NOTE: A lot of the prep work (i.e. adding mysql users) was done earlier, but can probably be done in one shot as well.

1400+ databases successfully moved to a new cluster, yay! Cheers!

Tuesday, March 3, 2009

Check MySQL Tables Across Multiple Databases

If you manage multiple databases on a MySQL server that are identical in architecture, but unique in data well I'm sure you may come across this issue at some point in time. This issue being that, the MySQL err log shows an error on a table, but it doesn't specify which database!

(Error looks like this: # 090217 18:38:22 [ERROR] /usr/local/bin/mysqld: Can't open file: 'wp_comments.MYI' (errno: 144)
)

Now sure, you can just run a mysqlcheck on all-databases' tables, but obviously that may take a while, especially if you manage a lot of databases.

So, remember just a few blog posts before, I mentioned a way of monitoring MySQL's err log. Well, to be honest, that was actually a product of my original idea; that idea being:
- monitor the MySQL err log for table errors
- if there is a table error, run a mysqlcheck for that specific table against all databases
- email the results

Well, why only search for one specific error if you can search for them all? So, I broke my script down into two; an err log monitor and a mysqlcheck. Same as always, tailor the code to fit your environment. For example in this line: if ($dbdata->[0] =~ m/^wp_.+/) { I'm only going to search through our Wordpress databases and skip everything else. You can change the regex so that you will only check databases that begin with the letter 'a' if that fits your situation (/^a.+/).

I'm sure you get the point! Eventually (when I'm less busy), I'll modify some of my code so that this will run more of an automated process. --All you need to do is have the err log script write to a file with the tables giving errors and then write a wrapper to process the err log script, then process the mysqlcheck script. But, that's for another day kids!

Cheers!


#!/usr/bin/perl -w
#
# chkmysqltables.pl v1.0
# 2009-02-17
# Adrian J. Cruz
#

use strict;
use DBI;

if (!$ARGV[0]) {
print "Usage: $0 \" [db_table]\"\n";
print "Note: Use quotes if you are checking multiple tables.\n";
exit;
}

my $db_table = $ARGV[0];

my $mysqlu = "dbuser";
my $mysqlp = qw(dbpass);
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
my $yy = sprintf("%02d", $year % 100);
$year += 1900;
$mon += 1;
if ($mon < 10) { $mon = 0 . $mon; }
if ($mday < 10) { $mday = 0 . $mday; }
my $todaylog = $year . $mon . $mday . $hour . $min;
my $runlog = "/root/log/chkmysqltables.$todaylog.log";

my @tables;
push @tables, $db_table;
# we only want the unique tables
my %sorthash;
@sorthash{@tables} = ();
my @error_tables = keys %sorthash;

my @dbs;
my $dbh = DBI->connect("DBI:mysql:mysql",$mysqlu,$mysqlp)
|| die "Unable to connect: $!\n";
my $query = "SHOW DATABASES";
my $sth = $dbh->prepare($query)
|| die "Could not prepare: $!\n";
$sth->execute || die "Could not execute: $!\n";
while (my $dbdata = $sth->fetchrow_arrayref) {
if ($dbdata->[0] =~ m/^wp_.+/) {
push(@dbs,$dbdata->[0]);
}
}
$sth->finish;

open(LOG, ">>$runlog");
print LOG "$todaylog\n";
for my $t (@error_tables) {
for my $db (@dbs) {
system "/usr/local/bin/mysqlcheck --password=$mysqlp $db $t >> $runlog\n";
}
}
print LOG "--END LOG--\n";
close(LOG);

my $email_message;
open(MSG, "<$runlog");
$email_message = do {local $/; };
close(MSG);

sendMail( "you\@email.com", "mysqlerr\@email.com",
"mysqlerr: $db_table", "$email_message" );

sub sendMail {
my ($to, $from, $subject, $message) = @_;
my $sendmail = "/usr/sbin/sendmail";
open(MAIL, "|$sendmail -oi -t");
print MAIL "From: $from\n";
print MAIL "To: $to\n";
print MAIL "Subject: $subject\n\n";
print MAIL "$message\n";
close(MAIL);
}

Wednesday, February 18, 2009

Monitoring the MySQL ERR Log

If you've ever wanted a quick and easy way to monitor MySQL for errors, well, you've stumbled onto the right place.

At work we've been getting these corrupt tables that go unnoticed until an end-user notifies us. Which, of course, for any website is utterly disastrous since some part of your site (even if it is just a minuscule widget on the site) is now broken. So, being the proactive technologists that we are we decided to monitor the MySQL err log daily. You can find your err log in the "data" directory where you installed MySQL (it defaults to the name: hostname.err).

What this perl script does is parse through the err log and find today's ERRORs. After it finds the errors, it then emails them. So, obviously go through and change the variables to your likings and set up a cron to have this run at the end of the day.

Cheers!


#!/usr/bin/perl -w
#
# chkmysqlerrlog.pl v1.0
# 2009-02-17
# Adrian J. Cruz
#

use strict;

my $dbserver = "dbserver.domain.com";
my $email_to = "email\@domain.com";
my $email_from = "mysqlerr\@domain.com";
my $errlog = "/usr/local/mysql/data/dbserver.domain.com.err";
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
my $yy = sprintf("%02d", $year % 100);
$year += 1900;
$mon += 1;
if ($mon < 10) {
$mon = 0 . $mon;
}
# set $today in date format: YYMMDD to get today's errors
# e.g.:
# 090217 18:38:22 [ERROR] mysqld: Can't open file: 'ts.MYI' (errno: 144)
my $today = $yy . $mon . $mday;
my $todaylog = $year . $mon . $mday . $hour . $min;

# parse through the mysql err log for ERRORs
my @errors;
open(IN, $errlog);
while () {
chomp;
if ($_ =~ m/$today.+(\[ERROR\].+$)/) {
push(@errors, $1);
}
}
close(IN);

# we only want the unique errors
my %sorthash;
@sorthash{@errors} = ();
my @error_msgs = keys %sorthash;

my $email_message = "$todaylog\n";
for my $e (@error_msgs) {
$email_message .= $e . "\n";
}

if ($email_message && @error_msgs) {
sendMail( $email_to, $email_from,
"$todaylog $dbserver ERRORS", $email_message );
}

sub sendMail {
my ($to, $from, $subject, $message) = @_;
my $sendmail = "/usr/sbin/sendmail";
open(MAIL, "|$sendmail -oi -t");
print MAIL "From: $from\n";
print MAIL "To: $to\n";
print MAIL "Subject: $subject\n\n";
print MAIL "$message\n";
close(MAIL);
}


NOTE: with a little bit of work you can even include the Warnings; we weren't too worried about those.

Friday, January 23, 2009

Regular Expressions in MySQL

Do you need to limit your SQL results and LIKE '%foo%' isn't giving you a narrow enough result list?

Well, I'm sure you know how to narrow down those SQL results with a regex! So all there is to it is the REGEXP operator! Yay!

Example:

SELECT * FROM table WHERE column REGEXP 'data[0-9]';


You get the point; now enjoy! Cheers!

Friday, January 16, 2009

MySQL Search and Replace

I recently had to update some information in MySQL. Yes, I'm sure you're thinking, "yea, so...that's easy!". But, the way the data was entered in the column was more like an entire paragraph! The information I needed to change was only a last name in the paragraph. So, obviously I didn't want to type out the entire paragraph again with my edits just so i can UPDATE the table. So instead, MySQL has a nice replace function built in. Yay!

The code will look as follows:
UPDATE your_table set your_column=replace(your_column,'Smith','Jones');

And now your_column will replace all occurrences of "Smith" with "Jones".

Cheers!