Sprint’s new “Simply ‘Almost’ Everything®” Plans
By · CommentsI got one of the Sprint SERO plans for $30/month a few years ago, and it has met all of my needs except my need for a cooler phone. You see, the “unlimited data” plan packaged with my SERO plan isn’t “unlimited” enough to handle the newer (Android) phones.
I would have to upgrade at least to the “Everything Data 450″ plan for $70/month, which includes fewer plan minutes than my current SERO plan. For the past year I’ve decided I could do without, especially if Sprint’s idea of an upgrade is fewer minutes for twice the price.
Since the 4G EVO was released last month my attitude had slowly been changing, and as I was upgrading my phone I noticed this little gem from Sprint’s site: “Because we’ve boosted your data experience with this phone’s amazing services and features, you’ll need our $10/mo. Premium Data add-on plus one of the plans below.” Link.
Of course the “plans listed below” are the variations of Sprint’s aforementioned “Simply Everything®” plans. It’s probably going to take me at least another year before I’m ready to pay extra for a data plan for my “unlimited data plan” plan. Of course by then, it’ll probably be another $10 for a data plan for my premium data plan for my unlimited data plan. It’s almost enough to make me ask myself what it is I keep holding out for with Sprint.
CSS Changes in Flex 4
By · CommentsI recently purchased the book Adobe Flash Builder 4 and Flex 4 by David Gassner and will be publishing a complete review when I’m done with the book. I’m going through it looking for the coverage I feel would be most helpful for those experienced with Flex 3. Even more specifically, those like myself, who have been so busy with contracting work (because Flash is dead of course, and the only way to make a living as a contractor anymore is with HTML5 and CSS3) that they were only able to sample Gumbo during its development.
One such topic, which I happen to be going through now, are the additions to Flex 4’s CSS implementation over Flex 3. This information is available in a number of other places, so this post is more to help me internalize it than to be groundbreaking to everyone else.
1. CSS Namespaces
In order to support type selectors with the same name, CSS namespaces have been introduced. In Flash Builder selecting New->CSS File will show you what the syntax for declaring a CSS namespace is.
@namespace s "library://ns.adobe.com/flex/spark"; @namespace mx "library://ns.adobe.com/flex/mx";
If you’re not going to be using both Spark and Aeon/Halo in your application, you can declare the “default” namespace by omitting the prefix. Namespaces are used as follows:
s|Label { }
mx|Label { }
The lack of any white space between the namespace and the bar, and between the bar and the type selector is significant. Don’t include any white space there. Namespaces will need to be declared even for your custom components (I have a feeling this is going to get messy, but it’s for a good cause.)
2. Descendant Selectors
If you run into a situation where you want to use type selectors, but only when it is used in a particular container, you can use the descendant selectors. You can use them with your custom containers as well. The following declaration will affect all RichText editors contained within a Group:
s|Group s|RichText { color: #0000AA; }
This is another feature that could get out of hand, so use it wisely. Also don’t confuse this with declaring multiple type selectors on the same line, separating them with commas. Like this:
s|Group, s|RichText { color: #0000AA; }
3. ID Selectors
The ID selectors are similar to style name selectors. Recall with a style name selector, the CSS declaration has a name beginning with a ‘.’ and in the MXML declaration of the component you can use styleName="smallText", or something like that.
To use the ID selector, the styleName in the CSS is set to the id of the component you’re styling, prefixed with the # symbol. Like this:
<!-- The MXML Component --> <s:Label id="labelA" />
/* The CSS declaration */
#labelA { color: 0xFF00FF; }
Be sure you set the id explicitly in the MXML– this will not work if you have declared the component in ActionScript.
And that concludes my synopsis of the most important additions to CSS in Flex 4.
Dotted Underline LinkButton (Flex)
By · CommentsI needed a link control that would display a dotted-underline on hover. To achieve this I overrode the rollOverHandler and the rollOutHandler of a standard LinkButton. Inside the rollOverHandler I used the graphics API to draw a dotted underline beneath the control’s textField.
Here’s an example:
There are some magic numbers, but tweaking them to get the look you want shouldn’t be too difficult.
And here’s the source: DottedLinkButton.as
Installing Red5 Media Server on CentOS 5.5 / Fedora
By · CommentsThis post details the steps I took to install Red5 from source on a CentOS 5.5 base server.
1. Install Java using yum. (The -y flag provides a ‘yes’ answer to all prompts.)
yum -y install java-1.6.0-openjdk java-1.6.0-openjdk-devel
2. Install the Apache ant binary. I downloaded the most recent release one directly from Apache’s archives. The version installed using yum (and default repositories) will not compile Red5.
cd /usr/src wget http://archive.apache.org/dist/ant/binaries/apache-ant-1.8.1-bin.tar.bz2 tar jxvf apache-ant-1.8.1-bin.tar.bz2 mv apache-ant-1.8.1 /usr/local/ant
3. Set important Java environment variables.
export ANT_HOME=/usr/local/ant export JAVA_HOME=/usr/lib/jvm/java export PATH=$PATH:/usr/local/ant/bin export CLASSPATH=.:$JAVA_HOME/lib/classes.zip
4. You should also add them to
bashrc so they're available the next time you log in.
echo 'export ANT_HOME=/usr/local/ant' >> /etc/bashrc echo 'export JAVA_HOME=/usr/lib/jvm/java' >> /etc/bashrc echo 'export PATH=$PATH:/usr/local/ant/bin' >> /etc/bashrc echo 'export CLASSPATH=.:$JAVA_HOME/lib/classes.zip' >> /etc/bashrc
5. Install subversion with yum. If you did a base install of CentOS, subversion will not be preinstalled.
yum -y install subversion
6. Check out the Red5 source.
cd /usr/src svn checkout http://red5.googlecode.com/svn/java/server/trunk/ red5
7. Build Red5 with ant.
mv red5 /usr/local/ cd /usr/local/red5 ant prepare ant dist
8. Start Red5.
cp -r dist/conf . ./red5.sh
9. Create a startup script (optional):
vi /etc/init.d/red5
Then enter this text into the file.
#!/bin/bash
# chkconfig: 2345 80 80
# description: Red5 streaming server
# processname: red5
. /etc/rc.d/init.d/functions
[ -r /etc/sysconfig/red5 ] &amp;&amp; . /etc/sysconfig/red5
RETVAL=0
case "$1" in
start)
echo -n "Starting red5: "
cd /usr/local/red5
/usr/local/red5/red5.sh >/dev/null 2>/dev/null &amp;
RETVAL=$?
if [ $RETVAL -eq 0 ]; then
echo $! > /var/run/red5.pid
touch /var/lock/subsys/red5
fi
[ $RETVAL -eq 0 ] && success $"red5 startup" || failure $"red5 startup"
echo
;;
stop)
echo -n $"Stopping down red5: "
killproc -p /var/run/red5.pid
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/red5
;;
restart)
$0 stop
$0 start
;;
status)
status red5 -p /var/run/red5.pid
RETVAL=$?
;;
*)
echo $"Usage: $0 {start|stop|restart|status}"
RETVAL=1
esac
exit $RETVAL
10. Set permissions on the script.
chmod a+x vi /etc/init.d/red5 chkconfig red5 on
11. Add necessary ports to the iptables file.
vi /etc/sysconfig/iptables
Then add the following lines:
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5080 -j ACCEPT -A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 1935 -j ACCEPT
You may also want to add exceptions for 8443, 8088, 9035, 1936, and 9999 if necessary for your application,
service iptables restart
You may want to restart the server, and the Red5 test page can be accessed at http://localhost(or servername):5080/
MySQL Master-Master Replication
By · CommentsIn my opinion, having dual-writable master MySQL databases (in a replication configuration) is not worth the hassle. There are a host of problems, enough that you should seriously consider what you’re trying to gain when attempting it. However, the master-master replication scheme still has some very good uses when used in an active-passive way. The two most compelling reasons for me are:
1. Keeping a “hot spare”. You have an additional database already configured as a master. This might not seem like much, since you “almost” gain the same thing in a master-slave setup. However, if your master-master includes slave servers, this topology provides a very high degree of fault tolerance. Especially when each master-server pair is geographically separated.
2. Making changes to the database. Certain changes made to the database may require a long time to complete, particularly if you have a very large database. In the master-master setup, you can take one of the servers “offline” (by telling the other master not to replicate its changes), and make the changes necessary. Then bring it back online, after the changes have been made, make it the active master, and let the other master perform the changes.
This could be seen as an added benefit of keeping a “hot spare”.
The good news is that setting this up is identical to setting up master-slave replication, you simply do it twice. Each master is essentially the master of and a slave to the other database. To keep it active-passive, one of the databases will need to be made read-only. Here are the changes you will need to the my.cnf configuration file:
Active Master my.cnf
log_bin = mysql-bin server_id = 1001 relay_log = mysql-relay-bin log_slave_updates = 1
Passive Master my.cnf
log_bin = mysql-bin server_id = 1002 relay_log = mysql-relay-bin log_slave_updates = 1 read_only = 1 # Notice this line
Then set up the replication user accounts, as described in this post: Simple MySQL Master-Slave Replication
Finally you issue the slave directives, and start the slave process:
Active Master ‘change master’
# Active master is slave to passive host CHANGE MASTER TO MASTER_HOST='passive.mysql.host', MASTER_USER='rep_user', MASTER_PASSWORD='reppassword', MASTER_LOG_FILE='mysql-bin-000001', MASTER_LOG_POS=0; start slave;
Passive Master ‘change master’
# Passive master is slave to active host CHANGE MASTER TO MASTER_HOST='active.mysql.host', MASTER_USER='rep_user', MASTER_PASSWORD='reppassword', MASTER_LOG_FILE='mysql-bin-000001', MASTER_LOG_POS=0; start slave;
Flex Socket Connections : Socket Policy File
By · CommentsStarting with certain versions in the 9.0’s of Flash player, socket communication in Flex began adding additional security measures. The one I am going to discuss in the post is the socket policy file. In short, the socket policy file is an XML file that is served by default from port 843 and contains information regarding which ports on _this_ server that Flash may connect to. Additionally it allows you to specify from which domains you wish to allow connections.
Loading the Policy File From Flex
The policy file can be explicitly requested by making the call:
Security.loadPolicyFile("host.withpolicyfile.com:843");
Or you can trust it will implicitly make the request when you attempt a socket connection. The policy is valid for a particular IP address over the life of the SWF. A policy request consists of the following line, nothing more:
<policy-file-request/>
And the correct response is the policy file, followed by a null byte. My example policy server file will not be so picky about it’s request, use it at your own risk. Adobe has one that actually checks to see if the request was formatted correctly before sending the response. Furthermore, rather than reading in an actual policy file, my example hard codes it into the policy server.
Policy File Format
Here is a sample policy file, it is provided by Adobe. You can make whatever changes you need to, as I did in mine:
<?xml version="1.0"?> <!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd"> <!-- Policy file for xmlsocket://socks.example.com --> <cross-domain-policy> <!-- This is a master socket policy file --> <!-- No other socket policies on the host will be permitted --> <site-control permitted-cross-domain-policies="master-only"/> <!-- Instead of setting to-ports="*", administrator's can use ranges and commas --> <!-- This will allow access to ports 123, 456, 457 and 458 --> <!--allow-access-from domain="swf.example.com" to-ports="123,456-458" /--> <allow-access-from domain="*" to-ports="80" /> </cross-domain-policy>
Policy File Server
And here is the Perl code that runs the policy server. You can see it is just a basic socket server. Adobe’s version of this (which I based mine off) allows you to pass in the port as well as the path to the policy file. This is a stripped down version of that server, with most of the essentials hard coded.
use Socket;
my $NULLBYTE = pack('c', 0);
my $port = 843;
my $content ='<?xml version="1.0"?>'."\n" .
'<!DOCTYPE cross-domain-policy SYSTEM "/xml/dtds/cross-domain-policy.dtd">'."\n" .
'<cross-domain-policy>' . "\n" .
'<site-control permitted-cross-domain-policies="master-only"/>'."\n" .
'<allow-access-from domain="*" to-ports="80" />'."\n" .
'</cross-domain-policy>'."\n";
socket (LISTENSOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
or die "socket() error: $!";
setsockopt(LISTENSOCK, SOL_SOCKET, SO_REUSEADDR, pack('l', 1))
or die "setsockopt() error: $!";
bind (LISTENSOCK, sockaddr_in($port, INADDR_ANY))
or die "bind() error: $!";
listen (LISTENSOCK, SOMAXCONN)
or die "listen() error: $!";
while ( my $clientAddr = accept(CONNSOCK, LISTENSOCK)) {
my ($clientPort, $clientIp)= sockaddr_in($clientAddr);
my $clientIpStr = inet_ntoa($clientIp);
# Consume the request
local $/ = $NULLBYTE;
my $request = <CONNSOCK>;
chomp $request;
# Send the policy file
print CONNSOCK $content;
print CONNSOCK $NULLBYTE;
close CONNSOCK;
}
}
Opening A Port
Remember to open port 843 (in Fedora Core) by adding the following line in /etc/sysconfig/iptables :
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 843 -j ACCEPT
Then reload the iptables:
/etc/init.d/iptables restart
Simple Flex Socket Client
By · CommentsClient-server programming is one of my passions, and I enjoy doing it in almost any language. Which makes it fitting that Flex (ActionScript) is one of my favorite languages to develop in, because it truly is a client-side technology which pretty much means it’s open to just about any type of backend server. I suppose you could make that argument with just about any language depending on how it’s being used, but since Flex isn’t processed and returned to the browser as HTML, that makes it a little different in my opinion.
Even in Flex, most applications will connect to a backend server that’s running an HTTP service (which queries the database on behalf of Flex), but I’m even going to depart from that in this post. I’m going to be demonstrating how to make socket calls to another service. You could apply this to making HTTP requests on port 80, make requests directly to a MySQL server running on port 3306. In this particular post, I will keep it simple by demonstrating how to make an HTTP request.
Declaring and initializing the Socket
You declare socket like this:
import flash.net.Socket; private var socket : Socket;
Inside an initialization method, we will add a listener for the CONNECT event, and the SOCKET_DATA event. The CONNECT event alerts us when the connection has been made, and allows us to send our request. The SOCKET_DATA event is triggered whenever there is data waiting to be read from the socket.
socket = new Socket(); socket.addEventListener( Event.CONNECT, onConnect); socker.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData);
Connecting and Sending Data
At some point you will need to call connect on the socket, which accepts the URL of the server and the port it will be connecting to. In the onConnect() method, you will write the request using one of the writeXXX() methods, and call flush() which actually sends the data over the wire.
socket.connect(txtUrl.text, 80);
private function onConnect(event : Event) : void {
var requestString : String = getHttp_1_1Request();
socket.writeUTFBytes(requestString);
socket.flush();
}
Reading Data
As not all socket data will be available at once, as in most client programs, you will want to read the data in a loop, using one of the readXXX() methods.
private function onSocketData(event : ProgressEvent) : void {
while (socket.bytesAvailable) {
txtResponse.text += socket.readUTFBytes(socket.bytesAvailable);
}
socket.close();
}
In general you would be checking for the end of the response you’re expecting (based on protocol), to simplify things I simply close the socket after the while loop exits the first time. If you leave the socket open for too long without reading data, I have noticed that I receive the following error, regardless of whether I have the correct policy file including cross-domain.xml:
Error #2044: Unhandled securityError:. filename.swf text=Error #2048: Security sandbox violation cannot load data from the.host.name
In this example, the raw output received from the socket request will be shown in the text box. You can download the complete source to this example here (where you may also view a screencast demo of this procedure).
Depending on what version of the Flash Player you’re running, this example may not run as-is if the server you are connecting to does not implement the policy-file (served from port 843. I will be discussing this in an upcoming post where I delve into a little more advanced socket programming in Flex, including how and where to deploy a master policy file.
Book Review: Learning Perl
By · CommentsPerl is one of those languages I probably don’t care if I ever master, but I have to deal with it from time to time both in web applications and in shell scripting, that I wanted to gain a better understanding of it. For that reason I passed up on getting the highly acclaimed “camel book” and got Learning Perl, 5th edition, by Randal L. Schwartz, Tom Phoenix, and brian d foy, which is a slim 328 pages. I also found the subtitle encouraging, “Making Easy Things Easy & Hard Things Possible”– my early experiences with Perl have not been pleasant ones.
I enjoyed the book more than I expected, and have found it equal to the tasks I need to perform with Perl. It reads much like any “beginning” programming book (without all of the ‘what is a computer?’ nonsense you’d find in a Deitel&Deitel beginner book). My depth of experience with PHP helped me to be a little more comfortable with the syntax, and allowed me to ponder some of the trickier concepts a little more deeply. Like the default variable $_… I’m still thinking about that.
The book has a good introduction to modules, and covers both using cpan to install, and installing from source. Both of which I’ve had to do recently. The chapter on Regular Expressions was especially helpful, and probably one of the best short-tutorials on regular expressions I’ve ever read. Someday I’m going to have to read a book about those, maybe I’ll remember it better, but until then brief explanations like these will be my regex life blood.
The book offers exercises at the end of each chapter, in fact the authors claim this book is the product of their curriculum taught over a number of years. I didn’t work through all of them, but I did a few and I found them helpful. They also include possible solutions to each of them. As a student of computer science, I appreciated their preface to each solution “Here’s one way to do it:”.
All things considered, I enjoyed my experience with this book. If your goal is to become a hard core Perl wizard, you might want to go with the camel book. If your intentions for Perl are more casual, then you probably want this book.
Simple MySQL Master-Slave Replication
By · CommentsI’ve been doing a lot of research (not cutting edge type stuff) into MySQL scalability, and the first exercise I went through was configuring a simple master-slave replication setup. It was much simpler than I thought it would be. Here are the steps.
Editing the my.cnf Files
Because of the way replication works in MySQL, you will need to turn on binary logging. Essentially, the slave is going to connect to the master and request the log. After it gets the log (or the parts that it needs) it will replay it, executing the queries to bring it up to date. You also need to give the server an ID. So add these lines to the my.cnf (usually /etc/my.cnf) on the master database:
<mysqld> log_bin = mysql-bin server_id = 1001
You can give it any ID you want, you just want it to have a different ID than the slave. In the slave we will add a few additional lines, as well:
<mysqld> log_bin = mysql-bin server_id = 1002 relay_log = mysql-relay-bin log_slave_updates = 1 read_only = 1
Note: Replace the angle brackets above with square brackets. I haven’t figured out how to make my code plugin not treat [mysqld] as another code block definition.
According to Schwartz, et al. in High Performance MySQL (review forthcoming), the only parameter required on a slave is the server_id. The other parameters make it easy to switch the server between being a master or a slave. They also mention the read_only parameter is a good safety precaution but might not be applicable in all cases.
User Account Setup
Replication privileges need to be granted to the replication user on the master. If you want to be able to easily switch your server between master or slave, you can grant these privileges on both servers.
GRANT REPLICATION SLAVE ON *.* TO 'rep_user'@'10.0.0.%' IDENTIFIED BY 'reppassword';
There are certain features that are accessible by granting the REPLICATION CLIENT privilege. You can also limit the replication privileges to only certain databases or tables if so desired. Though it is not recommended, you could also grant access to all hosts, just as you might in any other GRANT statement.
Starting the Replication Procedure
Now that both the master and slave are configured, and correct permissions are granted to the replication user, the slave needs to be “started”. This is done by declaring the master host, and indicating necessary credentials and log file information, and then issuing the ’start slave’ command.
The host and credential information can be declared in the my.cnf file. However there are some advantages to making the declarations as MySQL commands. Specifically you will be able to make changes to these without having to restart the daemon. Here is the command you should issue to configure the slave:
CHANGE MASTER TO MASTER_HOST='master.mysql.host', MASTER_USER='rep_user', MASTER_PASSWORD='reppassword', MASTER_LOG_FILE='mysql-bin-000001', MASTER_LOG_POS=0;
And then you issue the command to start the slave:
start slave
If you were previously using binary logs on the master, and then cloned the server to create the slave, you might have trouble getting replication started without first deleting the binary log from the slave.
Sources
The MySQL documentation
High Performance MySQL, by Baron Schwartz et al.
Apache mod_proxy_balancer Self Registration : Part 3
By · CommentsI’ll start off by going over the basic high level architecture for my self registration procedure:
There is a register.php script residing on the load balancer, accessible via HTTP.
There is a deregister.php script residing on the load balancer, accessible via HTTP.
There is a register_with_lb.pl script residing on the web server, in /usr/local/bin/.
There is a deregister_with_lb.pl script residing on the web server, in /usr/local/bin/.
There is a MySQL database that stores the current configuration state, on it are two stored procedures register_lb and deregister_lb.
register.php
No changes were made to register.php as described in this post , though I’m considering some alterations to increase its security.
deregister.php
The biggest difference between register.php and deregister.php (aside from their purpose) is where the insert/delete database code is called from and why. When register.php is called by the web server, it will have already inserted information about itself into the database, including its hash. I made the decision that I did not want the load balancer responsible for inserting servers into the database. It would merely check that the requesting server inserted itself, and then regenerate the balancer_members.conf.
In the case of deregister.php I decided I wanted the server making the call to still be in the database so the script could verify the identity before removing it and regeneration the balancer_members. And since the deregistration SQL is contained within a stored procedure, I needed to make some changes to the script (as compared to register.php) regarding the database.
Specifically, the standard mysql library cannot call stored procedures. So I had to convert it to using mysqli, which is a similar, though more OO approach. The portion of the code that regenerates the balancer_members.conf is similar enough that I won’t re-list it here, but I will show how to connect using mysqli, and how to call a stored procedure.
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
$query = "SELECT count(*) as count FROM " . $dbtable . " WHERE ip='" . $_SERVER['REMOTE_ADDR'] . "';";
$result = $mysqli->query($query);
$row = $result->fetch_row();
echo $row[0];
if ($row[0] >= 1) {
$del_query = "call deregister_lb('" . $_SERVER['REMOTE_ADDR'] . "');";
$del_result = $mysqli->query($del_query);
//<code for regenerating the conf file removed here>
echo exec('echo "' . $file . '" > /etc/httpd/conf.d/balancer_members.conf');
echo exec("sudo /usr/local/bin/reload_httpd");
}
As you can see, I’m using the actual REMOTE_ADDR to determine the validity of the request.
(de)register_lb.sql Stored Procedure
Here is the code for the deregister_lb stored procedure:
DROP PROCEDURE IF EXISTS deregister_lb $$
CREATE PROCEDURE deregister_lb ( ip VARCHAR(100) )
BEGIN
DELETE FROM lb2_members
WHERE ip=_ip;
END $$
and also for the register_lb stored procedure:
DROP PROCEDURE IF EXISTS register_lb $$
CREATE PROCEDURE register_lb (
_hostname VARCHAR(100),
_ip VARCHAR(40),
_loadfactor INT,
_hash VARCHAR(100)
)
BEGIN
DECLARE already_exists INT DEFAULT 0;
SELECT count(*) INTO already_exists FROM lb2_members WHERE hash=_hash;
IF already_exists=1 THEN
UPDATE lb2_members
SET hostname=_hostname, ip=_ip, loadfactor=_loadfactor
WHERE hash=_hash;
ELSE
INSERT INTO lb2_members (ip, hostname, loadfactor, hash)
VALUES (_ip, _hostname, _loadfactor, _hash);
END IF;
END $$
Note that I’ve omitted the code that changes the delimiter to $$ instead of a semicolon.
register_with_lb.pl
This perl script uses perl DBI for accessing the database. I had to get that installed on my web server since it wasn’t already. Normally you can install perl packages using the cpan command. In which case you would issue the following commands to install DBI and a MySQL driver for it:
cpan DBI cpan DBD::mysql
If it’s the first time you’ve run cpan, you will need to go through some configuration. It’s pretty much self explanatory, and I just accepted all of the defaults. Everything installed correctly except for the MySQL driver, which I ended up having to install from source. If I had executed the command:
yum install mysql-devel.i386
first, then my cpan install of DBD::mysql might have worked, but I didn’t realize that until installing from source. In case you ever need to install a perl module from source, particularly the DBD::mysql driver, enter these commands (which I think is basically what cpan does):
yum install mysql-devel.i386 #(only requred in this particular instance) wget http://www.cpan.org/modules/by-module/DBD/DBD-mysql-4.011.tar.gz gzip -cd DBD-mysql-4.011.tar.gz | tar xf - cd DBD-mysql-4.011 #(or whatever version you downloaded) perl Makefile.PL make
Here is how you connect to the database and call a stored procedure:
my $dsn = "DBI:mysql:host=mysql.host;database=lb_register";
my $dbh = DBI->connect ($dsn, "lbuser", "lbpasswd")
or die "Cannot connect to MySQL server\n";
my $sql = "call register_lb('" . $localhost . "', '" . $localip . "', " . $loadfactor . ", '" . $hash . "')";
$dbh->do($sql);
$dbh->disconnect();
After that, register_with_lb.pl opens a socket to the load balancer and makes an HTTP request over the socket. There are probably easier ways to do this, I just happened to have the socket code lying around and was glad to be able to reuse it. Here’s the gist of it, in case you’re interested:
# Parse the URI.
my $url = URI->new("http://load.balancer.com/register/register.php?hash=" . $hash);
# Parse these in from the command line
$host = $url->host;
$port = $url->port;
$resource = $url->path;
$query = $url->query;
# Initialize the socket
$socket = IO::Socket::INET->new ( Proto => "tcp", PeerAddr => $host, PeerPort => $port,);
unless ($socket) { die "Error connecting to $host" }
$socket->autoflush(1);
# Format the request
my $request = "GET " . $resource . (($query)?"?" . $query : "") . " HTTP/1.1" . $EOL . "Host: " . $host . $EOL . "User-agent: register_script" . $EOR;
# Use send() to make the request, and output the response.
# Not necessary in this example, but informational.
if ( $socket->send($request) ) {
while ( <$socket> ) { print }
}
# Close the socket
close $socket;
The above code pretty much sums up deregister_from_lb.pl, since no database calls are made, a call is simply made to the deregister script. The line you would change is as follows:
my $url = URI->new("http://my.balancer.com/register/deregister.php");
Then make the files executable, and copy them to be used by the startup script described in the previous post:
chmod a+x register_with_lb.pl chmod a+x deregister_with_lb.pl cp register_with_lb.pl /usr/local/bin/ cp deregister_with_lb.pl /usr/local/bin
I don’t show it here, but right now my IP addresses are hard coded. There are a number of ways you can find out your actual IP address from within perl, I’m just not doing that right now.
Securing the register scripts
As an additional security measure, I’ve restricted access to the /register/ location on the load balancer to the IP address range I expect my web servers to be from, like this:
<Location /register> Order Deny,Allow Deny from all Allow from 10.0.0. </Location>
And now you have a web server that can register automatically (if you’ve gone through the previous two posts as well) with a mod_proxy_balancer load balancer.
Update
I did some searching around to find a way to determine your IP address from inside the perl script. This is a simple way if your server has a public IP address and reverse DNS set up correctly for that IP address:
use Socket; use Sys::Hostname; my $host = hostname(); my $addr = inet_ntoa(scalar(gethostbyname($host)) || 'localhost');
If your slave web servers are on a private network, the above command will return the loopback IP address (127.0.0.1) which isn’t useful for the load balancer (I wonder if it would start an infinite loop and crash the load balancer?). I found a function that prints out the IP address by parsing it out from the results of the ifconfig command.
It seemed a little long to just rip off and copy verbatim. So here’s a link to that code (which is what I’m using now) in case you’d like to use it. Perl script to get IP address.

