<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Xi Group Ltd. Company Blog &#187; Xi Group Ltd. Company Blog &#187; distributed systems</title>
	<atom:link href="http://blog.xi-group.com/tag/distributed-systems/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xi-group.com</link>
	<description>High-quality DevOps Services</description>
	<lastBuildDate>Tue, 09 Jun 2015 11:38:46 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.2.2</generator>
	<item>
		<title>How to implement multi-cloud deployment for scalability and reliability</title>
		<link>http://blog.xi-group.com/2014/07/how-to-implement-multi-cloud-deployment-for-scalability-and-reliability/</link>
		<comments>http://blog.xi-group.com/2014/07/how-to-implement-multi-cloud-deployment-for-scalability-and-reliability/#comments</comments>
		<pubDate>Fri, 18 Jul 2014 15:20:12 +0000</pubDate>
		<dc:creator><![CDATA[Ivo Vachkov]]></dc:creator>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Operations]]></category>
		<category><![CDATA[theCloud]]></category>
		<category><![CDATA[AWS CLI]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[cloudflare]]></category>
		<category><![CDATA[distributed systems]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[elastic computing]]></category>
		<category><![CDATA[joyent]]></category>
		<category><![CDATA[multi-cloud]]></category>

		<guid isPermaLink="false">http://blog.xi-group.com/?p=279</guid>
		<description><![CDATA[Introduction This post will present interesting approach to scalability and reliability: How to implement multi-cloud application deployment ?! There are many reasons why this is interesting topic. Avoiding provider lockdown, reducing cloud provider outage impact, increasing world-wide coverage, disaster recovery / preparedness are only some of them. The obvious benefits of multi-cloud deployment are increased [&#8230;]]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p style="text-align: justify;">This post will present interesting approach to scalability and reliability:</p>
<p style="text-align: center;"><strong>How to implement multi-cloud application deployment ?!</strong></p>
<p style="text-align: justify;">There are many reasons why this is interesting topic. Avoiding provider lockdown, reducing cloud provider outage impact, increasing world-wide coverage, disaster recovery / preparedness are only some of them. The obvious benefits of multi-cloud deployment are increased reliability and outage impact minimization. However, there are drawbacks too: supporting different sets of code to accommodate similar, but different services, increased cost, increased infrastructure complexity, different tools &#8230; Yet, despite the drawbacks, the possible benefits far outweigh the negatives!</p>
<p style="text-align: justify;">In the following article a simple service will be deployed in automated fashion over two different Cloud Service Providers: Amazon AWS and Joyent. Third provider, CloudFlare, will be used to service DNS requests. The choice of providers is not random. They are chosen because of particular similarities and because the ease of use. All of those providers have consistent, comprehensive APIs that allow automation through programming in parallel to the command line tools.</p>
<h2>Preliminary information</h2>
<p style="text-align: justify;">The service setup, described here, although synthetic, is representative of multiple usage scenarios. More complex scenarios are also possible. Special care should be taken to address use of common resources or non-replicable resources/states. Understand the dependencies of your application architecture before using multi-cloud setup. Or contact <a href="http://blog.xi-group.com/contact-us/">Xi Group Ltd.</a> to aid you in this process!</p>
<p style="text-align: justify;">The following Cloud Service Providers will be used to deploy executable code on:</p>
<ul>
<li><a href="https://aws.amazon.com/">Amazon AWS</a></li>
<li><a href="http://www.joyent.com/">Joyent</a></li>
</ul>
<p style="text-align: justify;">DNS requests will be served by <a href="https://www.cloudflare.com/">CloudFlare</a>. The test domain is: <strong>scalability.expert</strong></p>
<p style="text-align: justify;">Required tools are:</p>
<ul>
<li><a href="http://aws.amazon.com/cli/">Amazon AWS CLI</a></li>
<li><a href="https://github.com/joyent/node-smartdc">Joyent SmartDataCenter tools</a></li>
</ul>
<p style="text-align: justify;">Additional information can be found in <a href="http://aws.amazon.com/cli/">AWS CLI</a>, <a href="https://apidocs.joyent.com/cloudapi/">Joyent CloudAPI Documentation</a> and <a href="https://www.cloudflare.com/docs/client-api.html">CloudFlare ClientAPI</a>.</p>
<h2>Implementation Details</h2>
<p style="text-align: justify;">A service, website for <strong>www.scalability.expert</strong>, has to be deployed over multiple clouds. For simplicity, it is assumed that this is a static web site, served by NginX. It will run on Ubuntu 14.04 LTS. Instance types chosen in both AWS and Joyent are pretty limited, but should provide enough computing power to run NginX and serve static content. CloudFlare must be configured with basic settings for the DNS zone it will serve (in this case, the free CloudFlare account is used).</p>
<p style="text-align: justify;">Each computing instance, when bootstrapped or restarted, will start the NginX and register itself in CloudFlare. At that point it should be able to receive client traffic. Upon termination or shutdown, each instance should remove its own entries from CloudFlare thus preventing DNS zone pollution with dead entries. In a previous article, <a href="http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/">How to implement Service Discovery in the Cloud</a>, it was discussed how <strong>DNS-SD</strong> can be implemented for similar setup with increased client complexity. In a multi-tier architecture this a proper solution. However, lack of control over the client browser may prove that a simplistic solution, like the one described here, is a better choice.</p>
<h3>CloudFlare</h3>
<p style="text-align: justify;">CloudFlare setup uses the free account and one domain, <strong>scalability.expert</strong>, is configured:</p>
<p><a href="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-1.18.32-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-1.18.32-PM.png" alt="Screen Shot 2014-07-18 at 1.18.32 PM" width="985" height="154" class="alignnone size-full wp-image-288 img-thumbnail img-responsive" /></a> </p>
<p style="text-align: justify;">Basic configuration includes only one entry for the zone name:</p>
<p><a href="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-1.19.03-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-1.19.03-PM.png" alt="Screen Shot 2014-07-18 at 1.19.03 PM" width="976" height="222" class="alignnone size-full wp-image-289 img-thumbnail img-responsive" /></a></p>
<p style="text-align: justify;">As seen by the orange cloud icon, the requests for this record will be routed through CloudFlare&#8217;s network for inspection and analysis!</p>
<h3>AWS UserData / Joyent Script</h3>
<p style="text-align: justify;">To automate the process of configuring instances, the following UserData script will be used:</p>
<p></p><pre class="crayon-plain-tag">#!/bin/bash -ex

# Debian apt-get install function
apt_get_install()
{
    DEBIAN_FRONTEND=noninteractive apt-get -y \
    -o DPkg::Options::=--force-confdef \
    -o DPkg::Options::=--force-confold \
    install $@
}
 
# Mark execution start
echo "STARTING" > /root/user_data_run
 
# Some initial setup
export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get upgrade -y

# Mark progress ...
echo "OS UPDATE FINISHED" >> /root/user_data_run
 
# Install required packages
apt_get_install jq nginx

# Mark progress ...
echo "SOFTWARE DEPENDENCIES INSTALLED" >> /root/user_data_run

# Create test html page
mkdir /var/www
cat > /var/www/index.html << "EOF"
<html>
    <head>
        <title>Demo Page</title>
    </head>
 
    <body>
        <center><h2>Demo Page</h2></center><br>
        <center>Status: running</center>
    </body>
</html>
EOF

# Configure NginX
cat > /etc/nginx/conf.d/demo.conf << "EOF"
# Minimal NginX VirtualHost setup
server {
    listen 8080;
 
    root /var/www;
    index index.html index.htm;
 
    location / {
        try_files $uri $uri/ =404;
    }
}
EOF
 
# Restart NginX with the new settings
/etc/init.d/nginx restart

# Mark progress ...
echo "NGINX CONFIGURED" >> /root/user_data_run

# /etc/init.d startup script
cat > /etc/init.d/cloudflare-submit.sh << "EOF"
#! /bin/bash
#
# Author: Ivo Vachkov (ivachkov@xi-group.com)
#
### BEGIN INIT INFO
# Provides: DNS-SD Service Group Registration / De-Registration
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description:    Start / Stop script for DNS-SD
# Description:          Use to JOIN/LEAVE DNS-SD Service Group
### END INIT INFO

set -e
umask 022

# DNS Configuration details
ZONE="scalability.expert"
HOST="www"
TTL="120"
IP=""

# CloudFlare oSpecific Settings
CF_HOST="https://www.cloudflare.com/api_json.html"
CF_SERVICEMODE="0" # 0: Disable / 1: Enable CloudFlare acceleration network

# Edit the following parameters with your specific settings
CF_TOKEN="cloudflaretoken" 
CF_ACCOUNT="account@cloudflare.com"

# Execution log file
LOG_FILE=/var/log/cloudflare-submit.log

source /lib/lsb/init-functions

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin"

# Get public IP
get_public_ip () {
        # Check what cloud provider this code is running on
        if [ ! -f "/var/lib/cloud/data/instance-id" ]; then
                echo "$0: /var/lib/cloud/data/instance-id is not available! Unsupported environment! Exiting ..."
                exit 1
        fi

        # Get the instance public IP address
        I_ID=`cat /var/lib/cloud/data/instance-id`
        if [[ $I_ID == i-* ]]; then
                # Amazon AWS
                IP=`curl http://169.254.169.254/latest/meta-data/public-ipv4`
        else
                # Joyent
                IP=`ifconfig eth0 | grep "inet addr" | awk '{print $2}' | cut -c6-`
        fi
}

# Default Start function
cloudflare_register () {
        # Get instance public IP address
        get_public_ip

        # Check the resutl
        if [ -z "$IP" ]; then
                echo "$0: Unable to obtain public IP Address! Exiting ..."
                exit 1
        fi

        # Execute update towards CloudFlare API
        curl -s $CF_HOST \
                -d "a=rec_new" \
                -d "tkn=$CF_TOKEN" \
                -d "email=$CF_ACCOUNT" \
                -d "z=$ZONE" \
                -d "type=A" \
                -d "name=$HOST" \
                -d "content=$IP" \
                -d "ttl=$TTL" >> $LOG_FILE
    
        # Get record ID for this IP
        REC_ID=`curl -s $CF_HOST \
                -d "a=rec_load_all" \
                -d "tkn=$CF_TOKEN" \
                -d "email=$CF_ACCOUNT" \
                -d "z=$ZONE" | jq -a '.response.recs.objs[] | .content, .rec_id' | grep -A 1 $IP| tail -1 | awk -F"\"" '{print $2}'`

        # Update with desired service mode
        curl -s $CF_HOST \
                -d "a=rec_edit" \
                -d "tkn=$CF_TOKEN" \
                -d "email=$CF_ACCOUNT" \
                -d "z=$ZONE" \
                -d "id=$REC_ID" \
                -d "type=A" \
                -d "name=$HOST" \
                -d "content=$IP" \
                -d "ttl=1" \
                -d "service_mode=$CF_SERVICEMODE" >> $LOG_FILE
}

# Default Stop function
cloudflare_deregister () {
        # Get instance public IP address
        get_public_ip

        # Check the resutl
        if [ -z "$IP" ]; then
                echo "$0: Unable to obtain public IP Address! Exiting ..."
                exit 1
        fi

        # Get record ID for this IP
        REC_ID=`curl -s $CF_HOST \
                -d "a=rec_load_all" \
                -d "tkn=$CF_TOKEN" \
                -d "email=$CF_ACCOUNT" \
                -d "z=$ZONE" | jq -a '.response.recs.objs[] | .content, .rec_id' | grep -A 1 $IP| tail -1 | awk -F"\"" '{print $2}'`

        # Execute update towards CloudFlare API
        curl -s $CF_HOST \
                -d "a=rec_delete" \
                -d "tkn=$CF_TOKEN" \
                -d "email=$CF_ACCOUNT" \
                -d "z=$ZONE" \
                -d "id=$REC_ID" >> $LOG_FILE
}

case "$1" in
start)
        log_daemon_msg "Registering $HOST.$ZONE  with CloudFlare ... " || true
        cloudflare_register
        ;;
stop)
        log_daemon_msg "De-Registering $HOST.$ZONE with CloudFlare ... " || true
        cloudflare_deregister
        ;;
restart)
        log_daemon_msg "Restarting ... " || true
        cloudflare_deregister
        cloudflare_register
        ;;
*)
        log_action_msg "Usage: $0 {start|stop|restart}" || true
        exit 1
esac

exit 0
EOF

# Add it to the startup / shutdown process
chmod +x /etc/init.d/cloudflare-submit.sh
update-rc.d cloudflare-submit.sh defaults 99

# Mark progress ...
echo "CLOUDFLARE SCRIPT INSTALLED" >> /root/user_data_run

# Register with CloudFlare to start receiving requests
/etc/init.d/cloudflare-submit.sh start

# Mark execution end
echo "DONE" > /root/user_data_run</pre><p></p>
<p style="text-align: justify;">This UserData script contains three components:</p>
<ol>
<li>
<p style="text-align: justify;"><strong>Lines 0 &#8211; 62</strong>: Boilerplate, OS update, installation and configuration of NginX;</p>
</li>
<li>
<p style="text-align: justify;"><strong>Lines 64 &#8211; 215</strong>: cloudflare-submit.sh, main script that will be called on startup and shutdown of the instance. cloudflare-submit.sh will register the instance&#8217;s public IP address with CloudFlare and set required protection. By default, protection and acceleration is off. Additional configuration is required to make this script work for your setup, account details must be configured in the specified variables!</p>
</li>
<li>
<p style="text-align: justify;"><strong>Lines 217 &#8211; 228</strong>: Setting proper script permissions, configuring automatic start of cloudflare-submit.sh and executing it to register with CloudFlare. </p>
</li>
</ol>
<p style="text-align: justify;">Code is reasonably straight-forward. init.d startup script is divided to multiple functions and output is redirected to a log file for debugging purposes. External dependencies are kept to a minimum. Distinguishing between AWS EC2 and Joyent instances is done by analyzing the instance ID. In AWS, all EC2 instances have instance IDs starting with &#8216;i-&#8216;, while Joyent uses (by the looks of it) some sort of UUID. This part of the logic is particularly important if the code should be extended to support other cloud providers!</p>
<p style="text-align: justify;">Both AWS and Joyent offer Ubuntu 14.04 support, so the <strong>same code can be use to configure the instances</strong> in automated fashion. This is particularly handy when it comes to data driven instance management and <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">the DRY principle</a>. Command line tools for both cloud providers also offer similar syntax, which makes it easier to utilize this functionality.</p>
<h3>Amazon AWS</h3>
<p style="text-align: justify;">Staring new instances within Amazon AWS is straight-forward, assuming <strong>awscli</strong> is properly configured:</p>
<p></p><pre class="crayon-plain-tag">aws ec2 run-instances \
    --image-id ami-018c9568 \
    --count 1 \
    --instance-type t1.micro \
    --key-name test-key \
    --security-groups test-sg \
    --user-data file://userdata-script.sh</pre><p></p>
<h3>Joyent</h3>
<p style="text-align: justify;">Starting news instances within Joyent is somewhat more complex, but there is comprehensive <a href="https://apidocs.joyent.com/cloudapi/">documentation</a>:</p>
<p></p><pre class="crayon-plain-tag">sdc-createmachine \
    --account account_name \
    --keyId aa:bb:cc:dd:ee:ff:gg:hh:ii:jj:kk:ll:mm:nn:oo:pp \
    --name test \
    --package "4dad8aa6-2c7c-e20a-be26-c7f4f1925a9a" \
    --tag Name=test \
    --url "https://us-east-1.api.joyentcloud.com" \
    --metadata "Name=test" \
    --image 286b0dc0-d09e-43f2-976a-bb1880ebdb6c \
    --script userdata-script.sh</pre><p></p>
<p style="text-align: justify;">This particular example will start new SmartMachine instance using the <strong>4dad8aa6-2c7c-e20a-be26-c7f4f1925a9a</strong> package (g3-devtier-0.25-kvm, 3rd generation, virtual machine (KVM) with 256MB RAM) and <strong>286b0dc0-d09e-43f2-976a-bb1880ebdb6c</strong> (ubuntu-certified-14.04) image. SSH key details are supplied through the specific combinations of Web-interface settings and SSH key signature. For the list of available packages (instance types) and images (software stacks) consult the API: <a href="https://apidocs.joyent.com/cloudapi/#ListPackages">ListPackages</a>, <a href="https://apidocs.joyent.com/cloudapi/#ListImages">ListImages</a>.</p>
<p style="text-align: justify;"><strong>NOTE</strong>: Joyent offers rich Metadata support, which can be quite flexible tool when managing large number of instances!</p>
<h2>Successful service configuration</h2>
<p style="text-align: justify;">Successful service configuration will result in proper DNS entries to be added to the <strong>scalability.expert</strong> DNS zone in CloudFlare:</p>
<p><a href="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-4.12.43-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-4.12.43-PM.png" alt="Screen Shot 2014-07-18 at 4.12.43 PM" width="1031" height="374" class="alignnone size-full wp-image-292 img-thumbnail img-responsive" /></a></p>
<p style="text-align: justify;">After configured TTL, those should be visible world-wide:</p>
<p></p><pre class="crayon-plain-tag">:~> nslookup www.scalability.expert
Server:         8.8.4.4
Address:        8.8.4.4#53

Non-authoritative answer:
Name:   www.scalability.expert
Address: 54.83.175.90
Name:   www.scalability.expert
Address: 165.225.137.102

:~></pre><p></p>
<p style="text-align: justify;">As seen, both AWS (54.83.175.90) and Joyent (165.225.137.102) IP addresses are returned, i.e. DNS Round-Robin. Service can simply be tested with:</p>
<p></p><pre class="crayon-plain-tag">:~> curl http://www.scalability.expert:8080/
<html>
    <head>
        <title>Demo Page</title>
    </head>

    <body>
        <center><h2>Demo Page</h2></center><br>
        <center>Status: running</center>
    </body>
</html>
:~></pre><p></p>
<p style="text-align: justify;">Resulting calls can be seen in the NginX log files on both instances:</p>
<p><a href="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-5.30.50-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/07/Screen-Shot-2014-07-18-at-5.30.50-PM.png" alt="Screen Shot 2014-07-18 at 5.30.50 PM" width="1284" height="1083" class="alignnone size-full wp-image-301 img-thumbnail img-responsive" /></a></p>
<p style="text-align: justify;"><strong>NOTE</strong>: CloudFlare protection and acceleration features are explicitly disabled in this example! It is strongly suggested to enabled them for production purposes!</p>
<h2>Conclusion</h2>
<p style="text-align: justify;">It should be clear now, that whenever software architecture follows certain design principles and application is properly decoupled in multiple tiers, the whole system can be deployed within multiple cloud providers. DevOps principles for automated deployment can be implemented in this environment as well. The overall system is with improved scalability, reliability and in case of data driven elastic deployments, even cost! Proper design is key, but the technology provided by companies like Amazon and Joyent make it easier to turn whiteboard drawings into actual systems with hundreds of nodes!</p>
<p>References</p>
<ul>
<li><a href="http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/">How to implement Service Discovery in the Cloud</a></li>
<li><a href="https://aws.amazon.com/">https://aws.amazon.com/</a></li>
<li><a href="http://aws.amazon.com/cli/">http://aws.amazon.com/cli/</a></li>
<li><a href="http://www.joyent.com/">http://www.joyent.com/</a></li>
<li><a href="https://github.com/joyent/node-smartdc">https://github.com/joyent/node-smartdc</a></li>
<li><a href="https://apidocs.joyent.com/cloudapi/">https://apidocs.joyent.com/cloudapi/</a></li>
<li><a href="https://www.cloudflare.com/">https://www.cloudflare.com/</a></li>
<li><a href="https://www.cloudflare.com/docs/client-api.html">https://www.cloudflare.com/docs/client-api.html</a></li>
</ul>
<div class="rpbt_shortcode">
<h3>Related Posts</h3>
<ul>
					
			<li><a href="http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/">How to implement Service Discovery in the Cloud</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/02/how-to-deploy-single-node-hadoop-setup-in-aws/">How to deploy single-node Hadoop setup in AWS</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/01/userdata-teplate-for-ubuntu-14-04-ec2-instances-in-aws/">UserData Template for Ubuntu 14.04 EC2 Instances in AWS</a></li>
					
			<li><a href="http://blog.xi-group.com/2014/11/small-tip-how-to-use-block-device-mappings-to-manage-instance-volumes-with-aws-cli/">Small Tip: How to use &#8211;block-device-mappings to manage instance volumes with AWS CLI</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/01/small-tip-how-to-use-aws-cli-filter-parameter/">Small Tip: How to use AWS CLI &#8216;&#8211;filter&#8217; parameter</a></li>
			</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.xi-group.com/2014/07/how-to-implement-multi-cloud-deployment-for-scalability-and-reliability/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to implement Service Discovery in the Cloud</title>
		<link>http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/</link>
		<comments>http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/#comments</comments>
		<pubDate>Tue, 17 Jun 2014 13:51:42 +0000</pubDate>
		<dc:creator><![CDATA[Ivo Vachkov]]></dc:creator>
				<category><![CDATA[AWS]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[DevOps]]></category>
		<category><![CDATA[theCloud]]></category>
		<category><![CDATA[AWS CLI]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[distributed systems]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[dns-sd]]></category>
		<category><![CDATA[elastic computing]]></category>
		<category><![CDATA[service discovery]]></category>

		<guid isPermaLink="false">http://blog.xi-group.com/?p=49</guid>
		<description><![CDATA[Introduction Service Discovery is not new technology. Unfortunately, it is barely understood and rarely implemented. It is a problem that many system architects face and it is key to multiple desirable qualities of a modern, cloud enabled, elastic distributed system such as reliability, availability, maintainability. There are multiple ways to approach service discovery: Hardcode service [&#8230;]]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p style="text-align: justify;"><a title="Service Discovery" href="http://en.wikipedia.org/wiki/Service_discovery">Service Discovery</a> is not new technology. Unfortunately, it is barely understood and rarely implemented. It is a problem that many system architects face and it is key to multiple desirable qualities of a modern, cloud enabled, elastic distributed system such as <strong>reliability</strong>, <strong>availability</strong>, <strong>maintainability</strong>. There are multiple ways to approach service discovery:</p>
<ul>
<li>Hardcode service locations;</li>
<li>Develop proprietary solution;</li>
<li>Use existing technology.</li>
</ul>
<p style="text-align: justify;">Hardcoding is still the common case. How often do you encounter hardcoded URLs in configuration files?! Developing proprietary solution becomes popular too. Multiple companies decided to address Service Discovery by implementing some sort of distributed key-value store. Amongst the popular ones: Etsy&#8217;s <a href="https://github.com/coreos/etcd">etcd</a>, Heroku&#8217;s <a href="https://github.com/ha/doozerd">Doozer</a>, Apache <a href="http://zookeeper.apache.org">ZooKeeper</a>, Google&#8217;s <a href="http://research.google.com/archive/chubby.html">Chubby</a>. Even <a href="http://redis.io">Redis</a> can used for such purposes. But for many cases additional software layers and programming complexity is not needed. There is already existing solution based on DNS. It is called DNS-SD and is defined in <a href="http://tools.ietf.org/html/rfc6763">RFC6763</a>.</p>
<p style="text-align: justify;">DNS-SD utilizes <strong>PTR</strong>, <strong>SRV</strong> and <strong>TXT</strong> DNS records to provide flexible service discovery. All major DNS implementations support it. All major cloud providers support it. DNS is well established technology, well understood by both Operations and Development personnel with strong support in programming languages and libraries. It is highly-available by replication.</p>
<h2>How does DNS-SD work?</h2>
<p style="text-align: justify;">DNS-SD uses three DNS records types: PTR, SRV, TXT:</p>
<ul>
<li><strong>PTR</strong> record is defined in <a href="http://tools.ietf.org/html/rfc1035">RFC1035</a> as &#8220;domain name pointer&#8221;. Unlike CNAME records no processing of the contents is performed, data is returned directly.</li>
<li><strong>SRV</strong> record is defined in <a href="http://tools.ietf.org/html/rfc2782">RFC2782</a> as &#8220;service locator&#8221;. It should provide protocol agnostic way to locate services, in contrast to the MX records. It contains four components: <strong>priority</strong>, <strong>weight</strong>, <strong>port</strong> and <strong>target</strong>.</li>
<li><strong>TXT</strong> record is defined in <a href="http://tools.ietf.org/html/rfc1035">RFC1035</a> as &#8220;text string&#8221;.</li>
</ul>
<p style="text-align: justify;">There are multiple specifics around protocol and service naming conventions that are beyond the scope of this post. For more information please refer to <a href="http://tools.ietf.org/html/rfc6763">RFC6763</a>. For the purposes of this article, it is assumed that a proprietary TCP-based service, called <strong>theService</strong> that has different reincarnations runs on <strong>TCP port 4218</strong> on multiple hosts. The basic idea is:</p>
<ol>
<li>Create a pointer record for _theSerivce that contains all available incarnations of the service;</li>
<li>For each incarnation create SRV record (where the service is located) and TXT record (any additional information for the client) that specify the service details.</li>
</ol>
<p>This is what sample configuration looks like in AWS Route53 for the unilans.net. domain:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.41.42-PM.png"><img class="alignnone size-full wp-image-101 img-thumbnail img-responsive" src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.41.42-PM.png" alt="Screen Shot 2014-06-14 at 10.41.42 PM" width="1482" height="198" /></a></p>
<p>Using <strong>nslookup</strong> results can be verified:</p><pre class="crayon-plain-tag">:~&gt; nslookup -q=PTR _theService._tcp.unilans.net.
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
_theService._tcp.unilans.net    name = _incarnation1._theService._tcp.unilans.net.
_theService._tcp.unilans.net    name = _incarnation2._theService._tcp.unilans.net.

Authoritative answers can be found from:

:~&gt; nslookup -q=any _incarnation1._theService._tcp.unilans.net.
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
_incarnation1._theService._tcp.unilans.net      text = "txtvers=1\; data=sampledata\;"
_incarnation1._theService._tcp.unilans.net      service = 0 0 4218 host1.unilans.net.

Authoritative answers can be found from:

:~&gt;</pre><p></p>
<p>Now a client that wants to use incarnation1 of theService has means to access it (Host: <strong>host1.unilans.net</strong>, Port: <strong>4218</strong>).</p>
<p>Load-balaing can be implementing by adding another entry in the service locator record with the same priority and weight:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.42.28-PM.png"><img class="alignnone size-full wp-image-103 img-thumbnail img-responsive" src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.42.28-PM.png" alt="Screen Shot 2014-06-14 at 10.42.28 PM" width="1484" height="241" /></a></p>
<p>Resulting DNS lookup:</p><pre class="crayon-plain-tag">:~&gt; nslookup -q=any _incarnation1._theService._tcp.unilans.net.
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
_incarnation1._theService._tcp.unilans.net      text = "txtvers=1\; data=sampledata\;"
_incarnation1._theService._tcp.unilans.net      service = 0 0 4218 host1.unilans.net.
_incarnation1._theService._tcp.unilans.net      service = 0 0 4218 host100.unilans.net.

Authoritative answers can be found from:

:~&gt;</pre><p></p>
<p>In a similar way, fail-over can be implemented by using different priority (or load distribution using different weights):<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.54.41-PM.png"><img class="alignnone size-full wp-image-105 img-thumbnail img-responsive" src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-14-at-10.54.41-PM.png" alt="Screen Shot 2014-06-14 at 10.54.41 PM" width="1483" height="241" /></a></p>
<p>Resulting DNS lookup:</p><pre class="crayon-plain-tag">:~&gt; nslookup -q=any _incarnation1._theService._tcp.unilans.net.
Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
_incarnation1._theService._tcp.unilans.net      text = "txtvers=1\; data=sampledata\;"
_incarnation1._theService._tcp.unilans.net      service = 0 0 4218 host1.unilans.net.
_incarnation1._theService._tcp.unilans.net      service = 1 0 4218 host100.unilans.net.

Authoritative answers can be found from:

:~&gt;</pre><p></p>
<p>NOTE: With DNS the client is the one to implement the load-balacing or the fail-over (although there are exceptions to this rule)!</p>
<h2>Benefits of using DNS-SD for Service Discovery</h2>
<p style="text-align: justify;">This technology can be used to support multiple version of a service. Using the built-in support for different reincarnations of the same service, versioning can be implemented in clean granular way. Common problem in REST system, usually solved by nasty URL schemes or rewriting URLs. With DNS-SD required metadata can be passed through the TXT records and multiple versions of the communication protocol can be supported, each in contained environment &#8230; No name space pollution, no clumsy URL schemes, no URL rewriting &#8230;</p>
<p style="text-align: justify;">This technology can be utilized to <strong>reduce complexity</strong> while building distributed systems. The clients will most certainly go through the process of name resolution anyway, so why not incorporate service discover in it?! Instead of dealing with external system (installation, operation, maintenance) and all the possible issues (hard to configure, hard to maintain, immature, fault-intollerant, requires additional libraries in the codebase, etc), incorporate this with the name resolution. DNS is well supported on virtually all operating systems and with all programming languages that provide network programming abilities. System architecture complexity is reduced because subsystem that already exists is providing additional services, instead of introducing new systems.</p>
<p style="text-align: justify;">This technology can be utilized to <strong>increase reliability / fault-tolerance</strong>. Reliability / fault-tolerance can be easily increased by serving multiple entries with the service locator records. <strong>Priority</strong> can be used by the client to go through the list of entries in controlled manner and <strong>weight</strong> to balance the load between the service providers on each priority level. The combination of backend support (control plane updating DNS-SD records) and reasonably intelligent clients (implementing service discovery and priority/weight parsing) should give granular control over the fail-over and load-balancing processes in the communication between multiple entities.</p>
<p style="text-align: justify;">This technology supports <strong>system elasticity</strong>. Modern cloud service providers have APIs to control DNS zones. In this article, AWS Route53 will be used to demonstrate how elastic service can be introduced through DNS-SD to clients. Backend service scaling logic can modify service locator records to reflect current service state as far as DNS zone modification API is available. This is just part of the control plane for the service &#8230;</p>
<p style="text-align: justify;">Bonus point: <strong>DNS also gives you simple, replicated key-value store through TXT records!</strong></p>
<h2>Implementation of Service Discovery with DNS-SD, AWS Route53, AWS IAM and AWS EC2 UserData</h2>
<p>Following is a set of steps and sample code to implement Service Discovery in AWS, using Route53, IAM and EC2.</p>
<h3>Manual configuration</h3>
<p>1. Create <strong>PTR</strong> and <strong>TXT</strong> Records for theService in Route53:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-2.07.22-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-2.07.22-PM.png" alt="Screen Shot 2014-06-16 at 2.07.22 PM" width="1482" height="51" class="alignnone size-full wp-image-123 img-thumbnail img-responsive" /></a></p>
<p>This is a simple example for one service with one incarnation (v1).</p>
<p>NOTE: There is no SRV since the service is currently not running anywhere! Active service providers will create/update/delete SRV entries. </p>
<p>2. Create IAM role for EC2 instances to be able to modify DNS records in desired Zone:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-2.24.34-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-2.24.34-PM.png" alt="Screen Shot 2014-06-16 at 2.24.34 PM" width="1549" height="281" class="alignnone size-full wp-image-124 img-thumbnail img-responsive" /></a></p>
<p>Use the following policy:</p><pre class="crayon-plain-tag">{
   "Version": "2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "route53:ListHostedZones"
         ],
         "Resource":"*"
      },
      {
         "Effect":"Allow",
         "Action":[
            "route53:GetHostedZone", 
            "route53:ListResourceRecordSets",
            "route53:ChangeResourceRecordSets"
         ],
         "Resource":"arn:aws:route53:::hostedzone/XXXXYYYYZZZZ"
      },
      {
         "Effect":"Allow",
         "Action":[
            "route53:GetChange"
         ],
         "Resource":"arn:aws:route53:::change/*"
      }
   ]
}</pre><p></p>
<p>&#8230; where <strong>XXXXYYYYZZZZ</strong> is your hosted zone ID!</p>
<h3>Automated JOIN/LEAVE in service group</h3>
<p style="text-align: justify;">Manual settings, outlined in the previous section give the basic framework of the DNS-SD setup. There is no SRV record since there are no active instances providing the service. Ideally, each active service provider will register/de-register with the service when available. This is key here: DNS-SD can be integrated cleanly with the elastic nature of the cloud. Once this integration is at place, all clients will only need to resolve DNS records in order to obtain list of active service providers. For demonstration purposes the following script was created:</p>
<p></p><pre class="crayon-plain-tag">#!/usr/bin/env python

# The following code modifies AWS Route53 entries to demonstrate usage of DNS-SD in cloud environments
#
# To JOIN Service group:
# 	dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 join
#
# To LEAVE Service group:
#	dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 leave
#
# NOTE: THIS IS FOR DEMONSTRATION PURPOSES ONLY! ERROR HANDLING IS ABSOLUTE MINIMAL! THIS IS *NOT* PRODUCTION CODE!

import sys
import copy
import argparse

import requests
import boto.route53

def main():
	"""
	Main entry point
	"""

	# Parse command line arguments
	parser = argparse.ArgumentParser(description='Example code to update service records in Route53 hosted DNS zones')
	parser.add_argument('-z', '--zone', type=str, required=True, dest='zone', help='Zone Name')
	parser.add_argument('-s', '--service', type=str, required=True, dest='service', help='Service Name')
	parser.add_argument('-p', '--port', type=int, required=True, dest='port', help='Service Port')
	parser.add_argument('operation', metavar='OPERATION', type=str, help='Operation [join|leave]', choices=['join', 'leave'])

	args = parser.parse_args()
	operation = args.operation
	zone = args.zone
	service = args.service
	port = args.port

	# Establish connection to Route53 API
	conn = boto.route53.connection.Route53Connection()

	# Get zone handler
	z = conn.get_zone(zone)
	if not z:
		print "{progname}: Wrong or inaccessible zone!".format(progname=sys.argv[0])
		sys.exit(-1)

	# Get EC2 Public IP Address
	response = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4')
	if response.status_code == 200:
		public_ipv4 = response.text
	else:
		print "{progname}: Unable to obtain public IP address from AWS!".format(progname=sys.argv[0])
		sys.exit(-1)

	# Generate domain-specific hostname
	fqdn_hostname = '{hostname}.{zone}'.format(hostname=public_ipv4.replace(".", "-"), zone=zone)

	# Act, based on operation request (join | leave)
	if operation.upper() == 'join'.upper():
		# Create A record
		z.add_a(fqdn_hostname, public_ipv4, ttl=60)

		# Obtain service locator records
		r = z.find_records(service, 'SRV')
		if not r:
			# Create SRV record
			srv_value = u'0 0 {port} {fqdn}'.format(port=port, fqdn=fqdn_hostname)
			z.add_record('SRV', service, srv_value, ttl=60)
		else:
			# Add to SRV record
			srv_value = u'0 0 {port} {fqdn}'.format(port=port, fqdn=fqdn_hostname)
			tmp_r = copy.deepcopy(r)
			tmp_r.resource_records.append(srv_value)
			z.update_record(r, tmp_r.resource_records)

	elif operation.upper() == 'leave'.upper():
		# Remove entry from the SRV record
		r = z.find_records(service, 'SRV')
		if r:
			tmp_r = copy.deepcopy(r)
			for record in tmp_r.resource_records:
				if fqdn_hostname in record:
					tmp_r.resource_records.remove(record)

			if len(tmp_r.resource_records) == 0:
				# Remove the SRV entry itself
				z.delete_record(r)
			else:
				# Update the SRV record
				z.update_record(r, tmp_r.resource_records)

		# Remove A record
		r = z.find_records(fqdn_hostname, 'A')
		if r:
			z.delete_record(r)

	else:
		print "{progname}: Wrong operation!".format(progname=sys.argv[0])
		sys.exit(-1)

if __name__ == '__main__':
	main()</pre><p></p>
<p>Copy of the code can be downloaded from <a href="https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/dns-sd.py">https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/dns-sd.py</a></p>
<p>This code, given DNS zone, service name and service port, will update necessary DNS records to join or leave the service group. </p>
<p>Starting with initial state:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.40-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.40-PM.png" alt="Screen Shot 2014-06-16 at 4.59.40 PM" width="1482" height="51" class="alignnone size-full wp-image-128 img-thumbnail img-responsive" /></a></p>
<p>Executing JOIN:</p><pre class="crayon-plain-tag">dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 join</pre><p></p>
<p>Result:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.07-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.07-PM.png" alt="Screen Shot 2014-06-16 at 4.59.07 PM" width="1483" height="103" class="alignnone size-full wp-image-129 img-thumbnail img-responsive" /></a></p>
<p>Executing LEAVE:</p><pre class="crayon-plain-tag">dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 leave</pre><p></p>
<p>Result:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.40-PM1.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-4.59.40-PM1.png" alt="Screen Shot 2014-06-16 at 4.59.40 PM" width="1482" height="51" class="alignnone size-full wp-image-130 img-thumbnail img-responsive" /></a></p>
<p style="text-align: justify;">Domain-specific hostname is created, service location record (SRV) is created with proper port and hostname. When host leaves the service group, domain-specific hostname is removed, so is the entry in the SRV record, or the whole record if this is the last entry.</p>
<h3>Fully automated setup</h3>
<p style="text-align: justify;">UserData will be used to fully automate the process. There are many options: Puppet, Chef, Salt, Ansible and all of those can be used, but the UserData solution is with reduced complexity, no external dependencies and can be directly utilized by other AWS Services like CloudFormation, AutoScalingGroups, etc.</p>
<p>The full UserData content is as follows:</p><pre class="crayon-plain-tag">#!/bin/bash -ex

# Debian apt-get install function
apt_get_install()
{
	DEBIAN_FRONTEND=noninteractive apt-get -y \
	-o DPkg::Options::=--force-confdef \
	-o DPkg::Options::=--force-confold \
	install $@
}

# Mark execution start
echo "STARTING" > /root/user_data_run

# Some initial setup
set -e -x
export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get upgrade -y

# Install required packages
apt_get_install python-boto python-requests
apt_get_install nginx

# Create test html page
mkdir /var/www
cat > /var/www/index.html << "EOF"
<html>
	<head>
		<title>Demo Page</title>
	</head>

	<body>
		<center><h2>Demo Page</h2></center><br>
		<center>Status: running</center>
	</body>
</html>
EOF

# Configure NginX
cat > /etc/nginx/conf.d/demo.conf << "EOF"
# Minimal NginX VirtualHost setup
server {
	listen 8080;

	root /var/www;
	index index.html index.htm;

	location / {
		try_files $uri $uri/ =404;
	}
}
EOF

# Restart NginX with the new settings
/etc/init.d/nginx restart

# Create dns-sd.py
cat > /usr/local/sbin/dns-sd.py << "EOF"
#!/usr/bin/env python

# The following code modifies AWS Route53 entries to demonstrate usage of DNS-SD in cloud environments
#
# To JOIN Service group:
# 	dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 join
#
# To LEAVE Service group:
#	dns-sd.py -z unilans.net -s _v1._theservice._tcp.unilans.net. -p 8080 leave
#
# NOTE: THIS IS FOR DEMONSTRATION PURPOSES ONLY! ERROR HANDLING IS ABSOLUTE MINIMAL! THIS IS *NOT* PRODUCTION CODE!

import sys
import copy
import argparse

import requests
import boto.route53

def main():
	"""
	Main entry point
	"""

	# Parse command line arguments
	parser = argparse.ArgumentParser(description='Example code to update service records in Route53 hosted DNS zones')
	parser.add_argument('-z', '--zone', type=str, required=True, dest='zone', help='Zone Name')
	parser.add_argument('-s', '--service', type=str, required=True, dest='service', help='Service Name')
	parser.add_argument('-p', '--port', type=int, required=True, dest='port', help='Service Port')
	parser.add_argument('operation', metavar='OPERATION', type=str, help='Operation [join|leave]', choices=['join', 'leave'])

	args = parser.parse_args()
	operation = args.operation
	zone = args.zone
	service = args.service
	port = args.port

	# Establish connection to Route53 API
	conn = boto.route53.connection.Route53Connection()

	# Get zone handler
	z = conn.get_zone(zone)
	if not z:
		print "{progname}: Wrong or inaccessible zone!".format(progname=sys.argv[0])
		sys.exit(-1)

	# Get EC2 Public IP Address
	response = requests.get('http://169.254.169.254/latest/meta-data/public-ipv4')
	if response.status_code == 200:
		public_ipv4 = response.text
	else:
		print "{progname}: Unable to obtain public IP address from AWS!".format(progname=sys.argv[0])
		sys.exit(-1)

	# Generate domain-specific hostname
	fqdn_hostname = '{hostname}.{zone}'.format(hostname=public_ipv4.replace(".", "-"), zone=zone)

	# Act, based on operation request (join | leave)
	if operation.upper() == 'join'.upper():
		# Create A record
		z.add_a(fqdn_hostname, public_ipv4, ttl=60)

		# Obtain service locator records
		r = z.find_records(service, 'SRV')
		if not r:
			# Create SRV record
			srv_value = u'0 0 {port} {fqdn}'.format(port=port, fqdn=fqdn_hostname)
			z.add_record('SRV', service, srv_value, ttl=60)
		else:
			# Add to SRV record
			srv_value = u'0 0 {port} {fqdn}'.format(port=port, fqdn=fqdn_hostname)
			tmp_r = copy.deepcopy(r)
			tmp_r.resource_records.append(srv_value)
			z.update_record(r, tmp_r.resource_records)

	elif operation.upper() == 'leave'.upper():
		# Remove entry from the SRV record
		r = z.find_records(service, 'SRV')
		if r:
			tmp_r = copy.deepcopy(r)
			for record in tmp_r.resource_records:
				if fqdn_hostname in record:
					tmp_r.resource_records.remove(record)

			if len(tmp_r.resource_records) == 0:
				# Remove the SRV entry itself
				z.delete_record(r)
			else:
				# Update the SRV record
				z.update_record(r, tmp_r.resource_records)

		# Remove A record
		r = z.find_records(fqdn_hostname, 'A')
		if r:
			z.delete_record(r)

	else:
		print "{progname}: Wrong operation!".format(progname=sys.argv[0])
		sys.exit(-1)

if __name__ == '__main__':
	main()

EOF

# Make dns-sd.py executable
chmod +x /usr/local/sbin/dns-sd.py

# Create startup job
cat > /etc/init.d/dns-sd << "EOF"
#! /bin/bash
#
# Author: Ivo Vachkov (ivachkov@xi-group.com)
#
### BEGIN INIT INFO
# Provides: DNS-SD Service Group Registration / De-Registration
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description:    Start / Stop script for DNS-SD
# Description:          Use to JOIN/LEAVE DNS-SD Service Group
### END INIT INFO

set -e
umask 022

# Configuration details
DNS_SD="/usr/local/sbin/dns-sd.py"
DNS_ZONE="unilans.net"
SERVICE_NAME="_v1._theservice._tcp.unilans.net."
SERVICE_PORT="8080"

. /lib/lsb/init-functions

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin"

# Default Start function
dns_sd_join () {
	$DNS_SD -z $DNS_ZONE -s $SERVICE_NAME -p $SERVICE_PORT join
}

# Default Stop function
dns_sd_leave () {
	$DNS_SD -z $DNS_ZONE -s $SERVICE_NAME -p $SERVICE_PORT leave
}

case "$1" in
start)
	log_daemon_msg "Joining $DNS_ZONE|$SERVICE_NAME:$SERVICE_PORT ... " || true
	dns_sd_join
	;;
stop)
	log_daemon_msg "Leaving $DNS_ZONE|$SERVICE_NAME:$SERVICE_PORT ... " || true
	dns_sd_leave
	;;
restart)
	log_daemon_msg "Restarting ... " || true
	dns_sd_leave
	dns_sd_join
	;;
*)
	log_action_msg "Usage: $0 {start|stop|restart}" || true
	exit 1
esac

exit 0
EOF

# Make /etc/init.d/dns-sd executable
chmod +x /etc/init.d/dns-sd

# Set automatic execution on start/shutdown
update-rc.d dns-sd defaults 99

# Execute initial service group JOIN
/etc/init.d/dns-sd start

# Mark execution end
echo "DONE" > /root/user_data_run</pre><p></p>
<p>Copy of the code can be downloaded from <a href="https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/userdata.sh">https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/userdata.sh</a></p>
<p>Starting 3 test instances to verify functionality:</p><pre class="crayon-plain-tag">aws ec2 run-instances --image-id ami-018c9568 --count 3 --instance-type t1.micro --key-name test-key --security-groups test-sg --iam-instance-profile Name=DNS-SD-Route53-EC2-Role --user-data file://userdata.sh</pre><p></p>
<p>Resulting changes to Route53:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-7.21.05-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-7.21.05-PM.png" alt="Screen Shot 2014-06-16 at 7.21.05 PM" width="1482" height="190" class="alignnone size-full wp-image-132 img-thumbnail img-responsive" /></a></p>
<p>Three new boxes self-registered in the Service group. Stopping manually one leads to de-registration:<br />
<a href="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-7.22.19-PM.png"><img src="http://blog.xi-group.com/wp-content/uploads/2014/06/Screen-Shot-2014-06-16-at-7.22.19-PM.png" alt="Screen Shot 2014-06-16 at 7.22.19 PM" width="1482" height="146" class="alignnone size-full wp-image-133 img-thumbnail img-responsive" /></a></p>
<p><strong>Elastic systems are possible to implement with DNS-SD!</strong> Note however, that the DNS records are limited to 65536 bytes, so the amount of entries that can go into SRV record, although big, is limited!</p>
<h2>Client code</h2>
<p style="text-align: justify;">To demonstrate DNS-SD resolution, the following sample code was created:</p>
<p></p><pre class="crayon-plain-tag">#!/usr/bin/env python

# The following code demonstrates how to resolve DNS-SD Service Descriptions
#
# Example execution:
#	client.py -z unilans.net. -s theService -p tcp -v v1
#
# NOTE: THIS IS FOR DEMONSTRATION PURPOSES ONLY! ERROR HANDLING IS ABSOLUTE MINIMAL! THIS IS *NOT* PRODUCTION CODE!

import sys
import random
import argparse

import requests
import dns.resolver

def main():
	"""
	Main entry point
	"""

	# Parse command line arguments
	parser = argparse.ArgumentParser(description='Example code to resolve DNS-SD service descriptions')
	parser.add_argument('-z', '--zone', type=str, required=True, dest='zone', help='Zone Name')
	parser.add_argument('-s', '--service', type=str, required=True, dest='service', help='Service Name')
	parser.add_argument('-p', '--protocol', type=str, required=True, dest='protocol', help='Service Transport Protoco [tcp|udp]', choices=['tcp', 'udp'])
	parser.add_argument('-v', '--version', type=str, required=True, dest='version', help='Service Version')

	args = parser.parse_args()
	zone = args.zone
	service = args.service
	protocol = args.protocol
	version = args.version

	# Obtain PTR Record
	service_id = '_{service}._{protocol}.{zone}'.format(service=service, protocol=protocol, zone=zone)
	answer = dns.resolver.query(service_id, 'PTR')

	# Find the service incarnation
	if answer:
		for record in answer.rrset:
			r = str(record.target).split('.')
			if version in r[0]:
				service_version = str(record.target)

	# Discover and consume the actual service
	if service_version:
		# Get SRV and TXT
		answer_srv = dns.resolver.query(service_version, 'SRV')
		answer_txt = dns.resolver.query(service_version, 'TXT')

		service_addr = ''
		service_port = 0

		# If those are valid get random service location entry
		if answer_srv and answer_txt:
			srv_entry = random.choice(answer_srv.rrset.items)
			if srv_entry:
				service_addr = srv_entry.target
				service_port = srv_entry.port

	service_uri = 'http://{host}:{port}/'.format(host=service_addr, port=service_port)
	r = requests.get(service_uri)
	if r.status_code == 200:
		print r.text

if __name__ == '__main__':
	main()</pre><p></p>
<p>Copy of the code can be downloaded from <a href="https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/client.py">https://s3-us-west-2.amazonaws.com/blog.xi-group.com/aws-route53-iam-ec2-dns-sd/client.py</a></p>
<p style="text-align: justify;">Why would that be better?! Yes, there is added complexity in the name resolution process. But, more importantly, details needed to find the service are agnostic to its location, or specific to the client. Service-specific infrastructure can change, but the client will not be affected, as long as the discovery process is performed.</p>
<p>Sample run:</p><pre class="crayon-plain-tag">:~> client.py -z unilans.net. -s theService -p tcp -v v1
<html>
        <head>
                <title>Demo Page</title>
        </head>

        <body>
                <center><h2>Demo Page</h2></center><br>
                <center>Status: running</center>
        </body>
</html>
:~></pre><p></p>
<p><strong>Voilà! Reliable Service Discovery in elastic systems!</strong></p>
<h2>Additional Notes</h2>
<p>Some additional notes and well-knowns:</p>
<ul>
<li>
<p style="text-align: justify;">Examples in this article could be extended to support fail-over or more sophisticated forms of load-balancing. Current random.choice() solution should be good enough for the generic case;</p>
</li>
<li>
<p style="text-align: justify;">More complex setup with different priorities and weights can be demonstrated too;</p>
</li>
<li>
<p style="text-align: justify;">Service health-check before DNS-SD registration can be demonstrated too;</p>
</li>
<li>
<p style="text-align: justify;">Non-HTTP service can be demonstrated to use DNS-SD. Technology is application-agnostic.</p>
</li>
<li>
<p style="text-align: justify;">TXT contents are not used throughout this article. Those can be used to carry additional meta-data (NOTE: This is public! Anyone can query your DNS TXT records with this setup!).</p>
</li>
</ul>
<h2>Conclusion</h2>
<p style="text-align: justify;">Quick implementation of DNS-SD with AWS Route53, IAM and EC2 was presented in this article. It can be used as a bare-bone setup that can be further extended and productized. It solves common problem in elastic systems: Service Discovery! All key components are implemented in either Python or Shell script with minimal dependencies (sudo aptitude install awscli, python-boto, python-requests, python-dnspython), although the implementation is not dependent on a particular programming language.</p>
<p>References</p>
<ul>
<li><a href="http://tools.ietf.org/html/rfc6763">http://tools.ietf.org/html/rfc6763</a></li>
<li><a href="http://www.infoq.com/articles/rest-discovery-dns">http://www.infoq.com/articles/rest-discovery-dns</a></li>
<li><a href="http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/UsingWithIAM.html">http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/UsingWithIAM.html</a></li>
</ul>
<div class="rpbt_shortcode">
<h3>Related Posts</h3>
<ul>
					
			<li><a href="http://blog.xi-group.com/2014/07/how-to-implement-multi-cloud-deployment-for-scalability-and-reliability/">How to implement multi-cloud deployment for scalability and reliability</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/02/how-to-deploy-single-node-hadoop-setup-in-aws/">How to deploy single-node Hadoop setup in AWS</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/01/userdata-teplate-for-ubuntu-14-04-ec2-instances-in-aws/">UserData Template for Ubuntu 14.04 EC2 Instances in AWS</a></li>
					
			<li><a href="http://blog.xi-group.com/2014/11/small-tip-how-to-use-block-device-mappings-to-manage-instance-volumes-with-aws-cli/">Small Tip: How to use &#8211;block-device-mappings to manage instance volumes with AWS CLI</a></li>
					
			<li><a href="http://blog.xi-group.com/2015/01/small-tip-how-to-use-aws-cli-filter-parameter/">Small Tip: How to use AWS CLI &#8216;&#8211;filter&#8217; parameter</a></li>
			</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.xi-group.com/2014/06/how-to-implement-service-discovery-in-the-cloud/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
