<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Nathan Evans&#039; Nemesis of the Moment</title>
	<atom:link href="http://nbevans.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nbevans.wordpress.com</link>
	<description>My nemesis of the moment</description>
	<lastBuildDate>Tue, 21 Feb 2012 19:07:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='nbevans.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Nathan Evans&#039; Nemesis of the Moment</title>
		<link>http://nbevans.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://nbevans.wordpress.com/osd.xml" title="Nathan Evans&#039; Nemesis of the Moment" />
	<atom:link rel='hub' href='http://nbevans.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Why doesn&#8217;t C# support lambdas for properties?</title>
		<link>http://nbevans.wordpress.com/2012/02/01/why-doesnt-c-support-lambdas-for-properties/</link>
		<comments>http://nbevans.wordpress.com/2012/02/01/why-doesnt-c-support-lambdas-for-properties/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 14:57:42 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[.NET Framework]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=207</guid>
		<description><![CDATA[Any time I write a C# property these days I can&#8217;t help thinking to myself how they would be so much cleaner if they supported a (syntactically restricted) form of lambda expression on both the getter and setter. Consider this: Would you agree that it looks cleaner like the following? The biggest seller for it, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=207&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Any time I write a C# property these days I can&#8217;t help thinking to myself how they would be so much cleaner if they supported a (syntactically restricted) form of lambda expression on both the getter and setter.</p>
<p>Consider this:</p>
<p><pre class="brush: csharp; gutter: false; wrap-lines: false;">
public DateTime Timestamp {
    get {
        return Settings.Default.Timestamp;
    }
    set {
        Settings.Default.Timestamp = value;
        Settings.Default.Save();
    }
}
</pre></p>
<p>Would you agree that it looks cleaner like the following?</p>
<p><pre class="brush: csharp; gutter: false; wrap-lines: false;">
public DateTime Timestamp {
    get =&gt; Settings.Default.Timestamp;
    set =&gt; {
        Settings.Default.Timestamp = value;
        Settings.Default.Save();
    }
}
</pre></p>
<p>The biggest seller for it, for me at least, is that it removes a largely superfluous &#8220;return&#8221; statement on the getter.</p>
<p>C# properties are all about the syntactic sugar, so why not go the last mile?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/207/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/207/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/207/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=207&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2012/02/01/why-doesnt-c-support-lambdas-for-properties/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>Anti-virus in the year 2012</title>
		<link>http://nbevans.wordpress.com/2012/01/09/anti-virus-in-the-year-2012/</link>
		<comments>http://nbevans.wordpress.com/2012/01/09/anti-virus-in-the-year-2012/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 13:25:59 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[Windows Environment]]></category>
		<category><![CDATA[anti-virus]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=202</guid>
		<description><![CDATA[This is why you don&#8217;t install anti-virus crapware onto production servers: You&#8217;ll log on to them one day and this dialog is sitting there waiting for you. In this case, it is a customer&#8217;s server; so not really my problem (yet!). But still. What is also interesting is that the server had only just came [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=202&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is why you don&#8217;t install anti-virus crapware onto production servers:</p>
<p><a href="http://nbevans.files.wordpress.com/2012/01/av-bad.png"><img class="alignnone size-full wp-image-203" title="Naughty anti-virus products" src="http://nbevans.files.wordpress.com/2012/01/av-bad.png?w=720" alt=""   /></a></p>
<p>You&#8217;ll log on to them one day and this dialog is sitting there waiting for you.</p>
<p>In this case, it is a customer&#8217;s server; so not really my problem (yet!). But still.</p>
<p>What is also interesting is that the server had only just came back up a few hours before from a batch of Windows Updates. So why didn&#8217;t AVG piggyback its updates onto that reboot?</p>
<p>Microsoft really needs to clamp down on all this seemingly legalised crapware. How does it even pass Windows Logo requirements?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/202/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=202&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2012/01/09/anti-virus-in-the-year-2012/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>

		<media:content url="http://nbevans.files.wordpress.com/2012/01/av-bad.png" medium="image">
			<media:title type="html">Naughty anti-virus products</media:title>
		</media:content>
	</item>
		<item>
		<title>WebSocket servers on Windows Server</title>
		<link>http://nbevans.wordpress.com/2011/12/20/websocket-servers-on-windows-server/</link>
		<comments>http://nbevans.wordpress.com/2011/12/20/websocket-servers-on-windows-server/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 11:58:16 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[Windows Environment]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=191</guid>
		<description><![CDATA[This is a slight continuation of the previous WebSockets versus REST… fight! post. Buoyed with enthusiasm of WebSockets, I set about implementing a simple test harness of a WebSockets server in C#.NET using System.Net.HttpListener. Unfortunately, things did not go well. It turns out that HttpListener (and indeed, the underlying HTTP Server API a.k.a. http.sys) cannot be used at [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=191&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is a slight continuation of the previous <a title="WebSockets versus REST… fight!" href="http://nbevans.wordpress.com/2011/12/16/websockets-versus-rest-fight/">WebSockets versus REST… fight!</a> post.</p>
<p>Buoyed with enthusiasm of WebSockets, I set about implementing a simple test harness of a WebSockets server in C#.NET using <code>System.Net.HttpListener</code>. Unfortunately, things did not go well. It turns out that <code>HttpListener</code> (and indeed, the underlying HTTP Server API a.k.a. <code>http.sys</code>) cannot be used at all to develop a WebSockets server on current versions of Windows. The <code>http.sys</code> is simply too strict with its policing of what it believes to be correct HTTP protocol.</p>
<p>In an IETF discussion thread, a Microsoft fellow called <a href="http://www.ietf.org/mail-archive/web/hybi/current/msg04606.html">Stefen Shackow was quoted as saying</a> the following:</p>
<blockquote><p><em>The current technical issue for our stack is that the low-level Windows HTTP driver that handles incoming HTTP request (http.sys) does not recognize the current websockets format as having a valid entity body. As you have noted, the lack of a content length header means that http.sys does not make the nonce bytes in the entity available to any upstack callers. That&#8217;s part of the work we will need to do to build websockets support into http.sys. Basically we need to tweak http.sys to recognize what is really a non-HTTP request, as an HTTP request.</em></p>
<p><em>Implementation-wise this boils down to how strictly a server-side HTTP listener interprets incoming requests as HTTP. For example a server stack that instead treats port 80 as a TCP/IP socket as opposed to an HTTP endpoint can readily do whatever it wants with the websockets initiation request.</em></p>
<p><em>For our server-side HTTP stack we do plan to make the necessary changes to support websockets since we want IIS and ASP.NET to handle websockets workloads in the future. We have folks keeping an eye on the websockets spec as it progresses and we do plan to make whatever changes are necessary in the future.</em></p></blockquote>
<p>This is a damn shame. As it stands right now, Server 2008/R2 boxes cannot host WebSockets. At least, not whilst sharing ports 80 and 443 with IIS web server. Because, sure, you could always write your WebSocket server to bind to those ports with a raw TCP socket and rewrite a ton of boilerplate HTTP code that <code>http.sys</code> can already do, and then put up with the fact that you can&#8217;t share the port with IIS on the same box. This is something that most people, me included, do not want to do.</p>
<p>Obviously it isn&#8217;t really anyone&#8217;s fault because back in the development time frame of Windows 7 and Server 2008/R2 (between 2006 to 2009) they could not have foreseen the WebSockets standard and the impact it might have on the design of APIs for HTTP servers.</p>
<p>The good thing is that Windows 8 Developer Preview seems to have this covered. <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa364499(v=vs.85).aspx">According to the MSDN documentation</a>, the HTTP Server API&#8217;s <code>HttpSendHttpResponse</code> function supports a new special flag called <code>HTTP_SEND_RESPONSE_FLAG_OPAQUE</code> that seems to suggest it will put the HTTP session into a sort of &#8220;dumb mode&#8221; whereby you can pass-thru pretty much whatever you want and <code>http.sys</code> won&#8217;t interfere:</p>
<blockquote><p><em><code>HTTP_SEND_RESPONSE_FLAG_OPAQUE</code></em></p>
<p><em>Specifies that the request/response is not HTTP compliant and all subsequent bytes should be treated as entity-body. Applications specify this flag when it is accepting a Web Socket upgrade request and informing HTTP.sys to treat the connection data as opaque data.</em></p>
<p><em>This flag is only allowed when the <code>StatusCode</code> member of <code>pHttpResponse</code> is <code>101</code>, switching protocols. <code>HttpSendHttpResponse</code> returns <code>ERROR_INVALID_PARAMETER</code> for all other HTTP response types if this flag is used.</em></p>
<p><em>Windows Developer Preview and later: This flag is supported.</em></p></blockquote>
<p>Aside from the new <code>System.Net.WebSockets</code> namespace in .NET 4.5, there are also clear indications of this behaviour being exposed in the <code>HttpListener</code> of .NET 4.5 through a new <a href="http://msdn.microsoft.com/en-us/library/hh194297(v=VS.110).aspx"><code>HttpListenerContext.AcceptWebSocketAsync()</code></a> method. The preliminary documentation seems to suggest that this method will support 2008 R2 and Windows 7. But this is almost certainly a misprint because I have inspected these areas of the .NET 4.5 libraries using Reflector and it is very clear that this is not the case:</p>
<p style="padding-left:30px;">The <code>HttpListenerContext.AcceptWebSocketAsync()</code> method directly calls into <code>System.Net.WebSockets.WebSocketHelper</code> (static class) which has a corresponding <code>AcceptWebSocketAsync()</code> method of its own. This method will then call a sanity check method tellingly named <code>EnsureHttpSysSupportsWebSockets()</code> which evaluates an expression containing the words &#8220;<code>ComNetOS.IsWin8orLater</code>&#8220;. I need say no more.</p>
<p>It seems clear now that Microsoft has chosen not to back port this minor HTTP Server API improvement to Server 2008 R2 / Windows 7. So now we must all hope that Windows Server 8 runs a beta program in tandem with the Windows 8 client, and launches within a month of each other. Otherwise Metro app development possibilities are going to be severely limited whilst we all wait for the Windows Server product to host our WebSocket server applications! Even still, it&#8217;s a shame that Server 2008 R2 won&#8217;t ever be able to host WebSockets.</p>
<p>It will be interesting if <a href="http://1wt.eu/">Willie Tarreau</a> (of HA-Proxy fame) will come up with some enhancements in his project that might benefit those determined enough to still want to host (albeit, raw TCP-based) WebSockets on Server 2008 R2.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/191/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/191/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/191/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=191&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/12/20/websocket-servers-on-windows-server/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>WebSockets versus REST&#8230; fight!</title>
		<link>http://nbevans.wordpress.com/2011/12/16/websockets-versus-rest-fight/</link>
		<comments>http://nbevans.wordpress.com/2011/12/16/websockets-versus-rest-fight/#comments</comments>
		<pubDate>Fri, 16 Dec 2011 18:04:30 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[soap]]></category>
		<category><![CDATA[software design]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=168</guid>
		<description><![CDATA[On 8th December 2011, a little known (but growing in awareness) standard called &#8220;WebSockets&#8221; was upgraded to W3C Candidate Recommendation status. That is one small step shy of becoming a fully ratified web standard. And just to remove any remaining possible doubt: Next-gen platforms and frameworks such as Windows 8 and .NET 4.5 (at three [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=168&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<div class="wp-caption alignright" style="width: 318px"><a href="http://www.infoq.com/articles/rest-soap"><img class="     " title="InfoQ's take on current adoption" src="http://www.infoq.com/resource/articles/rest-soap/en/resources/figure2.jpg" alt="" width="308" height="176" /></a><p class="wp-caption-text">Where will WebSockets be on this InfoQ chart, in three years time?</p></div>
<p>On 8th December 2011, a little known (but growing in awareness) <a href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17">standard called &#8220;WebSockets&#8221; was upgraded to W3C Candidate Recommendation status</a>. That is one small step shy of becoming a fully ratified web standard. And just to remove any remaining possible doubt: Next-gen platforms and frameworks such as Windows 8 and .NET 4.5 (at three levels: <code>System.Net</code>, WCF and ASP.NET) already have deeply nested support, and they aren&#8217;t even beta  yet!</p>
<p>After reading up about the standard in detail and absorbing the various online discussion around it, it is becoming increasingly clear to me that this standard is going to steal a large chunk of mind share from RESTful web services. What I mean is that there will come a stage in product development where somebody will have to ask the question:</p>
<blockquote><p><em>Right guys, shall we use WebSockets or REST for this project?</em></p>
</blockquote>
<p>I expect that WebSockets will, within a year or two, begin stunting the growth of RESTful web services – at least as we know them today.</p>
<h2>What are WebSockets?</h2>
<p>They are an overdue and rather elegant protocol extension for HTTP 1.1 that allows what is fundamentally a bi-directional TCP data stream to be tunnelled over a HTTP session. They provide a built-in implementation of TCP message framing, so developers don&#8217;t need to worry about any boilerplate code stuff like that when designing their application protocol.</p>
<h2>Why are WebSockets a threat to RESTful web services?</h2>
<p>From the last few years of working on projects that expose RESTful web services, I have noticed a few shortcomings. I should probably make clear that I&#8217;m not claiming that WebSockets answers all those shortcomings. I&#8217;m merely suggesting that REST is not the silver bullet solution that it is often hyped up to be. What I am saying is that there is definitely space for another player that can still operate at &#8220;web scale&#8221;. WebSockets have more scope to be a little more like a black box or quick&#8217;n'dirty solution than REST which requires a more design up-front approach due to versioning and public visibility concerns. Always use the correct tool for the job, as they say.</p>
<h3>Sub-par frameworks</h3>
<p>They might claim REST support but they still haven&#8217;t truly &#8220;groked&#8221; it yet, in my opinion. WCF REST is a good example of this. Admittedly, the WCF Web API for .NET is starting to get <em>close</em> to where things should be, but it is not yet production ready.</p>
<p>Perhaps even more serious is the lack of widespread cross-platform RESTful clients that work <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm">in the way that Roy prescribed</a>; of presenting an entry point resource that allows the client to automatically discover and autonomously navigate between further nested resources in a sort of state machine fashion. A single client framework that can operate with hundreds of totally different RESTful web services from different organisations. This does not exist yet, today. This is why so many big providers of RESTful web services end up seeding their own open source projects in various programming languages to provide the essential REST client.</p>
<h3>Enterprise loves SOAP (and other RPCs)</h3>
<p>Third-parties that want to use your web services often prefer SOAP over REST. Many haven&#8217;t even heard of REST! WebSockets are a message-based protocol allowing for SOAP-like RPC protocols that enterprise seem to adore so much. Hell there&#8217;s nothing stopping actual SOAP envelopes being transferred over a WebSocket!</p>
<p>This might not be the case if you&#8217;re operating in an extremely leading edge market such as perhaps cloud computing where everyone is speaking the same awesomesauce.</p>
<h3>Complex domain models</h3>
<p>Mapping out complex domain models onto REST can be slow and labourious. You&#8217;ll find yourself constantly having to work around its architectural constraints. Transactions, for example, can be a particular problem. Of course, this is partly related to the first problem (sub-par frameworks) but one cannot reasonably expect transaction support in a REST framework. What is probably needed is a set of common design patterns for mapping domain models to REST. And then an extension library for the framework that provides reusable implementations of those patterns. But alas, none of this exists yet.</p>
<h3>Text-based formats</h3>
<p>JSON/XML (for reasons unknown) are commonly used with REST and these are of course text-based formats. This is great for interoperability and cross-platform characteristics. But it is not so great for memory and bandwidth usage. This especially has implications on mobile devices.</p>
<p>You&#8217;ll find yourself running into walls if you try to use something that isn&#8217;t JSON or XML, at least that is my experience with current frameworks.</p>
<h3>Request-response architecture of HTTP</h3>
<p>Fundamentally, REST is nothing more than a re-specification of the way HTTP works and a proposal of a design pattern to build applications on top of HTTP. This means it retains the same statelessness and sessionless characteristics of HTTP. It therefore precludes REST from being bi-directional where the server could act as the requester of some resource from the client, or sender of some message to the client. As a result it requires &#8220;hacks&#8221; to be used to emulate server-side events, and these hacks have bad characteristics such as high latency (round trip time) and are wasteful of battery life.</p>
<h3>Public visibility, versioning concerns</h3>
<p>Sometimes having everything publicly visible is not what you want. People start using APIs that you don&#8217;t want them to use yet. You have to design everything to the nth degree much more. Have a proper versioning strategy in place. It encourages a more discerning approach to software development, that is for sure. Whilst these are usually good things, they can be a hindrance on early stage &#8220;lean agile&#8221; projects.</p>
<h2>What can WebSockets do that is so amazing?</h2>
<p>The fact that there will soon be a second player in this space suggests that there will be rebalancing of use-cases. WebSockets will prove to be disruptive for several reasons:</p>
<h3>True bi-directional capability and server-side events, no hacks</h3>
<p>Comet, push technology, long-polling etc in web apps are slow, inefficient, inelegant and have a higher potential magnitude for unreliability. They often work by requesting a resource from the server, causing the server to block until such a time that an event (or events) need to be transferred back to the client. They can be unreliable because the TCP connection could be teared down by a intermediate router during the time it is waiting for the response. Or worse, a proxy server might deliberately  time out the long-running request. As such, many implementations of this hack will use some kind of self-timeout mechanism so that perhaps every 60 seconds they will reissue the request to the server anyway. This has implications on both bandwidth and battery usage.</p>
<p>The true bi-directional capability offered by WebSockets is a first for any HTTP-borne protocol. It is something that neither SOAP nor REST have. And which Comet/push/long-polling can only emulate, inefficiently. The bi-directional capability is inherently so good that you could tunnel a real-time TCP protocol such as Remote Desktop or VNC over a WebSocket, if you wanted.</p>
<h3>Great firewall penetration characteristics</h3>
<p>WebSockets can tunnel out of heavily firewalled or proxied environments far easier than many other RPC designs. I&#8217;m sure I&#8217;m not alone in observing that enterprise environments rarely operate their SOAP services on port 80 or 443.</p>
<p>If you can access the web on port 80 <em>without</em> a proxy, WebSockets <em>will</em> work.</p>
<p>If you can access the web on port 80 <em>with</em> a proxy, WebSockets <em>should </em>work as long as the proxy software isn&#8217;t in the 1% that are broken and incompatible.</p>
<p>If  you can access the web on port 443 with or without a proxy, WebSockets <em>will</em> work.</p>
<p>I strongly suspect that there will be a whole raft of new Logmein/Remote Desktop and VPN solutions that are built on top of WebSockets, purely because of the great tunnelling characteristics.</p>
<h3>Lightweight application protocols and TCP tunnelling</h3>
<p>There is the potential for extremely lightweight application protocols, in respect of performance, bandwidth and battery usage. Like REST, the application schema/protocol isn&#8217;t defined by the standard; it is left completely wide open. WebSockets can transfer either text strings or binary data. It is clear that the text string support was included to aid in transferring JSON messages to JavaScript engines which lack the concept of byte arrays. Whilst the binary support will be most useful tunnelling TCP streams or for custom RPC implementations. After a WebSocket session is established, the overhead per message can be as small as just two bytes (!). Compare that to REST which has a huge HTTP header to attach to every single request <em>and</em> response.</p>
<h2>How will the use-cases of REST change?</h2>
<p>I believe that REST will lose a certain degree of its lustre. Project teams will less eagerly adopt it if they can get away with a bare bones WebSocket implementation. REST will probably remain the default choice for projects that need highly visible and cross-platform interoperable web services.</p>
<p>Projects without those requirements will probably opt for WebSockets instead and either run JSON over it, or use a bespoke wire protocol. They will particularly be used by web and mobile applications for their back-end communications i.e. data retrieval and push-events. Windows 8 &#8220;Metro&#8221; applications will need to use them extensively.</p>
<p>I suppose you could summarise that as:</p>
<ul>
<li>REST will be (and remain) popular for publicly visible interfaces.</li>
<li>WebSockets will be popular for private, internal or &#8220;limited eyes only&#8221; interfaces.</li>
</ul>
<p>Note: By &#8220;public&#8221; and &#8220;private&#8221; I am not referring literally to some form of paid/subscription/membership web service. I am referring to the programming API contract and its level of exposure to eyes outside of your development team or company.</p>
<h2>Conclusion</h2>
<p>Even though they are competing, the good thing is that REST and WebSockets can actually co-exist with one another. In fact, because they are both built upon HTTP fundamentals they will actually complement each other. A RESTful hypermedia resource could actually refer to a WebSocket as though it were another resource through a <code>ws://</code> URL. This will pave the way for new RESTful design patterns and framework features. It will allow REST to remedy some of its shortcomings, such as with transaction support; because a WebSocket session could act as the transactional unit of work.</p>
<p>The next year is going to be very interesting on the web.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/168/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=168&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/12/16/websockets-versus-rest-fight/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>

		<media:content url="http://www.infoq.com/resource/articles/rest-soap/en/resources/figure2.jpg" medium="image">
			<media:title type="html">InfoQ&#039;s take on current adoption</media:title>
		</media:content>
	</item>
		<item>
		<title>Building automated two-way applications on top of SMS text messaging</title>
		<link>http://nbevans.wordpress.com/2011/11/30/building-automated-two-way-applications-on-top-of-sms-text-messaging/</link>
		<comments>http://nbevans.wordpress.com/2011/11/30/building-automated-two-way-applications-on-top-of-sms-text-messaging/#comments</comments>
		<pubDate>Wed, 30 Nov 2011 15:38:31 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[Software Design]]></category>
		<category><![CDATA[gsm]]></category>
		<category><![CDATA[request-response]]></category>
		<category><![CDATA[smpp]]></category>
		<category><![CDATA[sms]]></category>
		<category><![CDATA[software design]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=117</guid>
		<description><![CDATA[For the past 8 years of my life I have been engrossed in the development of fully automated applications that use two-way SMS text messaging as their communication layer. SMS started life as being nothing more than what was basically the &#8220;ICMP protocol&#8221; of GSM networks. It used to be fairly hidden away in the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=117&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For the past 8 years of my life I have been engrossed in the development of fully automated applications that use two-way SMS text messaging as their communication layer. SMS started life as being nothing more than what was basically the &#8220;ICMP protocol&#8221; of GSM networks. It used to be fairly hidden away in the menus of those early Nokia phones. And even then it was very much akin to sending a &#8220;ICMP ping&#8221; message to your friend, and then he pinged you back. I guess that&#8217;s where modern services like &#8220;PingChat&#8221; got their name!</p>
<p>SMS is a very simple protocol; there is only three essential things you need to understand:</p>
<ol>
<li>It is limited to 160 characters per message, if you use the GSM 03.38 7-bit character set.</li>
<li>It is limited to 70 characters per message, if you use the UCS-2 (a.k.a. Unicode, UTF-16) character set.</li>
<li>Multiple messages can be joined together to form a multi-part message by including a special concatenation header, which eats up 6 or 12 characters (depending on whether you&#8217;re using GSM or UCS-2 character set). Most phones these days refer to this concept on their GUI as &#8220;pages&#8221;.</li>
</ol>
<p>Unfortunately the protocol is severely handicapped for when it comes to building automated two-way applications, and here&#8217;s why:</p>
<p style="padding-left:30px;">It does not provide any facility, not even an extension standard or extension <em>point</em>, for performing <strong>reply correlation</strong>.</p>
<p>What do I mean by &#8220;reply correlation&#8221;? It is a simple concept. Assume that you send a question to a buddy, and then he responds to you with the answer. One might <del>hope</del> expect that the message containing the answer contains some sort of ID code, token or cookie (hidden away in its header information, of course) that relates it to the original question message. Unfortunately, it does not and this is the problem; SMS does not include any such ID/token/cookie, anywhere. It simply wasn&#8217;t included in neither the original standard nor any subsequent revisions or extensions of the standard.</p>
<p>It is not necessarily the creators fault because clearly they couldn&#8217;t foresee how ubiquitous SMS would become. But there is evidence that they <em>did</em> recognise and respond to its popularity in the late 1990&#8242;s very quickly by publishing new standard extensions that built upon SMS, such as multi-part messages and WAP. So one can only wonder why they didn&#8217;t make an extension that would allow replies to be correlated with their original message. And unfortunately the window of opportunity to actually get this sorted out was over a decade ago, so we&#8217;re pretty much screwed then and will have to make do with it.</p>
<p>This is a big problem for SMS. It makes the process of building two-way fully automated applications much more difficult. Very very few companies have actually managed the solve the problem, and those that have tend to be very small or operating in niché markets. I don&#8217;t understand this at all, because the possibilities and prospects for building two-way SMS applications are absolutely huge, almost endless.</p>
<p>One of my key responsibilities over the last 8 years has been in devising production-ready solutions that work around this problem and this blog post is going to summarise all of them.</p>
<h2>An overview of the solution</h2>
<p>The key to solving this problem lies with two fields contained within the header information of every SMS message: the source and destination address. Or what I call the &#8220;address pairing&#8221;.</p>
<p>By using the address pairing in an intelligent way we can find the right compromise for a particular two-way application. Essentially, whenever the application needs to send a question to a mobile phone number it must ensure that no existing question is already outstanding on the same address pairing.</p>
<p>There are several ways that an application can be designed around this basic concept.</p>
<h2>Solution #1: My application only has one source address</h2>
<p>The application must be designed to &#8220;serialise&#8221; the transmission of questions. It can use a mutual exclusion mechanism that will prevent itself sending a further question to the same mobile phone number if an outstanding question is still waiting for a response. It can be expected that some characteristics of a &#8220;transaction&#8221; or &#8220;transactional unit of work&#8221; would be adopted in the design of the application to model this mutual exclusion concept.</p>
<p>My past implementations of this pattern were based on a database table with a composite primary key between both the &#8220;source&#8221; and &#8220;destination&#8221; columns. The application would try to insert the address pairing into this table and, if successful, it continues sending the message. But if the insertion were to fail then it would realise that a question is already outstanding with the mobile phone number, prompting it to give up and retry later. Or rather than retrying later based on some timer mechanism, you might enqueue it as a job somewhere; so that when a response for the outstanding question is received the application can check the queue for further jobs for that address pairing and dequeue/execute the top job.</p>
<p>There is a caveat with this solution however, and it comes as a side affect of &#8220;serialising&#8221; the questions one after the other. What if it takes days or weeks for the person to respond to the question? The questions that are queued up waiting to acquire a lock on the address pairing are going to get pushed back and back. They could get pushed back so far that the premise of the question has been entirely voided (e.g. an appointment reminder/confirmation).</p>
<p>The solution to this problem is to introduce a further concept of a &#8220;timeout&#8221; value. This will ensure that any question sent to the mobile phone can only be outstanding for up to a designated time period. You would probably typically set this to around 24-48 hours, but some questions that contain more time sensitive content may use a lower value of between 1-4 hours.</p>
<p>It is important (though not essential) that when implementing the timeout value concept that you use the &#8220;Validity Period&#8221; field that is available in every outbound SMS message. You should set the validity period to roughly match what your timeout value for that question will be. This will help ensure messaging integrity in the event that, for example, the mobile phone is turned off for a week and when it is turned back on then you don&#8217;t want your &#8220;expired&#8221; questions to be delivered when your back-end application has already timed out the workflow that was running for that question.</p>
<h2>Solution #2: My application can have multiple source addresses</h2>
<p>The idea is that you would have a relatively large pool of source addresses, perhaps as many as 50 or 100. Your application would, as with Solution #1, maintain some kind of database table or data structure that prevents duplicate address pairings. The application would then have some logic that enables it to &#8220;select&#8221; a free source address i.e. a source address that is not &#8220;in use&#8221; for the destination mobile phone number.</p>
<p>It would still be advisable to implement some kind of &#8220;timeout&#8221; mechanism, as with Solution #1, but the advantage would be that you would be able to have substantially greater timeout periods. Possibly in the order of weeks or months. Really the timeout mechanism here would be acting more as a type of garbage collector, than as a question expedite governor as in Solution #1.</p>
<p>I&#8217;ve always considered that this solution is better suited to applications that provide a &#8220;shared&#8221; or cloud service of some kind. Simply because setting up a large pool of dedicated source addresses for each of your application&#8217;s customers is surely going to get painful.</p>
<p>This solution does have the disadvantage that end-users on their mobile phone will be communicating, potentially, with lots of different source addresses even though it is really the same company/application at the other end. It can mess up the user&#8217;s normal &#8220;texting&#8221; experience, it would rob them of their iPhone&#8217;s &#8220;bubble chat&#8221; GUI style of presentation and the ability of perhaps creating a Contact list entry for a regular contact. Obviously there are things you can do to try to minimise this risk, such as always trying to select the source address with the lowest index. But really I think that will just make things worse. At some point you WILL want to send multiple questions to a mobile phone number, and there&#8217;s no getting around that fact. If you&#8217;ve got a large pool of source addresses then you&#8217;re going to want to use them.</p>
<h2>Solution #3: My application only has one source address, but I need to send concurrent questions to the same mobile phone</h2>
<p>You can&#8217;t. Well you can, but I don&#8217;t recommend it at all. I tried it once, on an early version of our system, and our customers didn&#8217;t like it.</p>
<p>Essentially you combine the concepts detailed in Solution #1 and then rely on some text processing logic in your response handling code. So rather than perhaps phrasing your question like &#8220;Are you attending the meeting tomorrow? Reply with A=Yes or B=No.&#8221; You&#8217;d phrase it as &#8220;&#8230; Reply with A1=Yes or B1=No&#8221;. Notice the &#8220;1&#8243; digit in there? That&#8217;s the key bit. That digit refers to a transaction code that will be used for correlation. My implementation of this basically went from zero to nine, so you could have a total of 10 concurrent questions open with the same mobile number.</p>
<p>I don&#8217;t like this solution for the following reasons:</p>
<ul>
<li>Many end-users forget to include the essential digit in their reply. They might reply &#8220;A&#8221; instead of &#8220;A1&#8243;. I&#8217;ve seen this happen in the wild.</li>
<li>Accessing digits on mobile phones when typing a SMS message is often an unintuitive process. Even an iPhone needs you to access a sub-keyboard screen. Blackberry&#8217;s need you to hit the ALT key.</li>
<li>It prohibits your application from accepting literal text responses. Many users would simply reply &#8220;Yes&#8221; rather than &#8220;A&#8221; or &#8220;A1&#8243;. If they do this, your application would be screwed because it wouldn&#8217;t have the essential digit to correlate the reply with the original question. I&#8217;ve seen this happen in the wild.</li>
<li>It prohibits your application from accepting &#8220;freeform&#8221; text responses. You might want to send a question like &#8220;What is your full name?&#8221;. There&#8217;s no way you can tag on the end of that a list of options. It simply doesn&#8217;t make sense.</li>
<li>It reveals implementation details onto the user interface of your application. Not good.</li>
<li>It compromises messaging integrity. An end-user might inadvertently reply (or possibly even deliberately!) with an incorrect digit.</li>
<li>It requires both the &#8220;reply analysis/text processing&#8221; and &#8220;reply correlation&#8221; concerns of your application to be interdependent on each other, when really they should not be – at least not to perform something so simple.</li>
</ul>
<h2>Experimental solutions</h2>
<p>On the last bullet point of Solution #3 I suggested that your application&#8217;s &#8220;reply analysis&#8221; and &#8220;reply correlation&#8221; concerns shouldn&#8217;t be linked together. This I believe is true for something as simple as what was described in that solution. However, there is plenty of mileage to be explored in adopting this approach for more advanced designs.</p>
<p>When you send a question with a constrained set of response options such as &#8220;Yes, No, Maybe&#8221;, you might want to record these as part of your address pairing in the database or data structure (as described in Solution #1). Then if you need to send a further question (to the same mobile phone, whilst the first question is still outstanding) you can check if the set of response options are different. This question might be looking for a &#8220;Good, Bad, Ugly&#8221; response. In which case there is no conflict, is there? So a lock on the address pairing, based upon those expected response options, can be allowed to be acquired. Obviously this wouldn&#8217;t be possible (or at least would have ramifications on your overall design) if you were expecting a &#8220;freeform&#8221; response.</p>
<p>Another possible avenue to be explored is an area of computer science called &#8220;<a href="http://en.wikipedia.org/wiki/Natural_language_processing">natural language processing</a>&#8220;. The idea is that when you ask a question like &#8220;What is your name?&#8221; then you would prime your NLP engine to be expecting a reply that looks like somebody&#8217;s name. Anything that arrives from that mobile phone that doesn&#8217;t look like a person&#8217;s name can be assumed to not be related to the outstanding question. Obviously if you want to ask a concurrent question like &#8220;What is your wife&#8217;s name?&#8221; then you&#8217;re back to square one. Because that would be a conflict and you&#8217;d need to serialise the questions as described in Solution #1. This (NLP and SMS applications) is an active area of research for me, so I may blog about it in more detail at a later time.</p>
<h2>Conclusion</h2>
<p>Solution #1 is the best, for now. It strikes the right level of compromise without sacrificing neither messaging integrity nor user friendliness. If you desperately need to send multiple concurrent questions to a mobile phone then I would suggest that you should rethink your approach. Perhaps logically separating your business departments and/or workflow concerns onto different source addresses would be a solution in this case. That way you can send out an urgent question, perhaps relating a missed bill payment, on a source address that is dedicated for that purpose.</p>
<p>Solution #2 is usable, and I can think of several use-cases. But I feel it is not as good for <em>frequent</em> one-to-one contact between a company and their customers. It has serious disadvantages in user friendliness. It is best suited to a hosted cloud service of some kind, where everyone shares the same pool of source addresses and where contact is expected to be infrequent.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/117/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/117/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/117/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=117&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/11/30/building-automated-two-way-applications-on-top-of-sms-text-messaging/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>Automated builds and versioning, with Mercurial</title>
		<link>http://nbevans.wordpress.com/2011/05/16/automated-builds-and-versioning-with-mercurial/</link>
		<comments>http://nbevans.wordpress.com/2011/05/16/automated-builds-and-versioning-with-mercurial/#comments</comments>
		<pubDate>Mon, 16 May 2011 21:42:21 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Automation]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[Source Control]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[mercurial]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=91</guid>
		<description><![CDATA[Yes this blog post is about that seemingly perennial need to set-up some sort of automatically incrementing version number system for your latest project. As it happens the &#8220;trigger&#8221; for me this time around was not a new project but more as a result of our switch from TFS to Mercurial for our source control. It took [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=91&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Yes this blog post is about that seemingly perennial need to set-up some sort of automatically incrementing version number system for your latest project.</p>
<p>As it happens the &#8220;trigger&#8221; for me this time around was not a new project but more as a result of our switch from TFS to Mercurial for our source control. It took some time for Mercurial to &#8220;bed in&#8221;, but it definitely has now. So then you reach that point where you start asking &#8220;Okay, so what else can we do with this VCS to improve the way we work?&#8221;.</p>
<p>Our first pass at automated versioning was to simply copy the status quo that worked with TFS. This was rather crude at best. Basically we had a MSBuild task that would increment (based on our own strategy) the <code>AssemblyFileVersionAttribute</code> contained inside the <code>GlobalAssemblyInfo.cs</code>. The usual hoo-har really, involving a simple regular expression etc. This was fine. However we did not really like it because it was, effectively, storing versioning information inside of a file held inside the repository. Separation of concerns and all that. It also caused a small amount of workflow overhead involving merging of named branches &#8211; with the occasional albeit easily resolvable conflict. Not a major issue, but not ideal either. Of course, not all projects use named branches. But we do; as they&#8217;re totally awesome for maintaining many concurrently supported backward releases.</p>
<h2>Versioning strategies</h2>
<p>The way I see it, there is only a small number of routes you can go down with project versioning:</p>
<ol>
<li>Some sort of <code>yyyy.mm.dd</code> timestamp strategy.<br />
This is great for &#8220;forward only&#8221; projects that don&#8217;t need to maintain supported backward releases. So for web applications, cloud apps etc &#8211; this is, I suspect, quite popular. For other projects, it simply doesn&#8217;t make sense. Because if you want to release a minor bug fix for a release from over a year ago it wouldn&#8217;t make any sense for the version to suddenly jump to the current date. How would you differentiate between major product releases?</li>
<li>The typical <code>major.minor.build.revision</code> strategy.<br />
The Major and Minor would be &#8220;fixed&#8221; for each production branch in the repository. And then you&#8217;d increment the build and/or revision parts based on some additional strategy.</li>
<li>A DVCS-only strategy where you use the global changeset hash.<br />
Unfortunately this is of limited use today on .NET projects because both the <code>AssemblyVersionAttribute</code> and <code>AssemblyFileVersionAttribute</code> won&#8217;t accept neither a string nor a byte array. Of course there is nothing stopping you coming up with your own Attribute (we called ours <code>DvcsIdentificationAttribute</code>) and including/updating that in your <code>GlobalAssemblyInfo.cs</code> (or equivilent) whenever you run a build. But it is of zero use to the .NET framework itself.</li>
<li>Some sort of hybrid between #1 and #2 (and possibly even #3!).<br />
This is what we do. We use a <code>major.minor.yymm.revision</code> strategy, to be precise.</li>
</ol>
<p>We like our #4 hybrid strategy because it brings us the following useful characteristics:</p>
<ul>
<li>It has &#8220;fixed&#8221; Major and Minor parts. Great for projects with multiple concurrent versions.</li>
<li>It contains a cursory Year and Month that can be read from a glance. When chasing down a problem on a customer environment it is simple things like this that can speed up diagnosis times.</li>
<li>An incremental Revision part that ensures each build in the same month has a unique index.</li>
</ul>
<p>So then, how did we implement this strategy on the Microsoft stack and with Mercurial?</p>
<h2>Implementation</h2>
<p>The key to implementing this strategy is first and foremost with retrieving from the repository the &#8220;most recent&#8221; tag for the current branch. Originally I had big plans here to go write some .NET library to walk the Mercurial <a href="http://mercurial.selenic.com/wiki/FileFormats" target="_blank">revlog file structure</a>. It would have been a cool project to learn some of the nitty gritty details of how Mercurial works under the hood. Unfortunately, I soon discovered that Mercurial has a template command available that already does what I need. It&#8217;s called the &#8220;<code>latesttag</code>&#8221; template. It&#8217;s really simple to use as well, for example:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
$ hg parents --template {latesttag}
&gt; v5.4.1105.5-build
</pre></p>
<p>There is also a related and potentially useful template called &#8220;<code>latesttagdistance</code>&#8220;. This will count, as it walks the revlog tree, the number of changesets that it walks past in search for the latest tag. It is possible that you could use this value as the incrementation extent for the Revision part in the strategy.</p>
<p>At this point most of the Mercurial fan base will go off and write a Bash script or Python script to do the job. Unfortunately in .NET land it&#8217;s not quite that simple, as we all know. I could have written a, erm, &#8220;posh&#8221; Powershell script to do it, for sure. But then I have to wire that in to the MSBuild script &#8211; which I suspect would be a bit difficult and have all sort of gotchas involved.</p>
<p>So I wrote a couple MSBuild tasks to do it, with the interesting one aptly named as <code>MercurialAssemblyFileVersionUpdate</code>:</p>
<p><pre class="brush: csharp; gutter: false; wrap-lines: false;">
public class MercurialAssemblyFileVersionUpdate : AssemblyFileVersionUpdate {

    private Version _latest;

    public override bool Execute() {
        var cmd = new MercurialCommand {
            Repository = Path.GetDirectoryName(BuildEngine.ProjectFileOfTaskNode),
            Arguments = &quot;parents --template {latesttag}&quot;
        };

        if (!cmd.Execute()) {
            Log.LogMessagesFromStream(cmd.StandardOutput, MessageImportance.High);
            Log.LogError(&quot;The Mercurial Execution task has encountered an error.&quot;);
            return false;
        }

        _latest = ParseOutput(cmd.StandardOutput.ReadToEnd());

        return base.Execute();
    }

    protected override Version GetAssemblyFileVersion() {
        return _latest;
    }

    private Version ParseOutput(string value) {
        return string.IsNullOrEmpty(value) || value.Equals(&quot;null&quot;, StringComparison.InvariantCultureIgnoreCase)
                   ? base.GetAssemblyFileVersion()
                   : new Version(ParseVersionNumber(value));
    }

    private string ParseVersionNumber(string value) {
        var ver_trim = new Regex(@&quot;(\d+\.\d+\.\d+\.\d+)&quot;, RegexOptions.Singleline | RegexOptions.CultureInvariant);

        var m = ver_trim.Match(value);
        if (m.Success)
            return m.Groups[0].Value;

        throw new InvalidOperationException(
            string.Format(&quot;The latest tag in the repository ({0}) is not a parsable version number.&quot;, value));
    }
}
</pre></p>
<p><a href="http://pastebin.com/uy4nJ5wB" target="_blank">Click here to view the full source</a>, including a couple dependency classes that you&#8217;ll need for the full solution.</p>
<p>With that done, it was just a case of updating our MSBuild script to use the new bits:</p>
<p><pre class="brush: xml; gutter: false; highlight: [4,5,6,7,8,9,10,13,15]; wrap-lines: false;">
&lt;Target Name=&quot;incr-version&quot;&gt;
  &lt;MercurialExec Arguments='revert --no-backup &quot;$(GlobalAssemblyInfoCsFileName)&quot;' /&gt;
  &lt;Message Text=&quot;Updating '$(GlobalAssemblyInfoCsFileName)' with new version number...&quot; /&gt;
  &lt;MercurialAssemblyFileVersionUpdate FileName=&quot;$(GlobalAssemblyInfoCsFileName)&quot;&gt;
    &lt;Output TaskParameter=&quot;VersionNumber&quot; PropertyName=&quot;VersionNumber&quot; /&gt;
    &lt;Output TaskParameter=&quot;MajorNumber&quot; PropertyName=&quot;MajorNumber&quot; /&gt;
    &lt;Output TaskParameter=&quot;MinorNumber&quot; PropertyName=&quot;MinorNumber&quot; /&gt;
    &lt;Output TaskParameter=&quot;BuildNumber&quot; PropertyName=&quot;BuildNumber&quot; /&gt;
    &lt;Output TaskParameter=&quot;RevisionNumber&quot; PropertyName=&quot;RevisionNumber&quot; /&gt;
  &lt;/MercurialAssemblyFileVersionUpdate&gt;&lt;/strong&gt;
  &lt;Message Text=&quot;Done update to '$(GlobalAssemblyInfoCsFileName)'.&quot; /&gt;
  &lt;Message Text=&quot;Tagging current changeset in local repo.&quot; /&gt;
  &lt;MercurialExec Arguments=&quot;tag --force v$(VersionNumber)-build&quot; /&gt;
  &lt;Message Text=&quot;Pushing commit to master server.&quot; /&gt;
  &lt;MercurialExec Arguments='push' /&gt;
  &lt;Message Text=&quot;All done.&quot; /&gt;
&lt;/Target&gt;
</pre></p>
<p>Of course, don&#8217;t forget to include your tasks into the script, ala:</p>
<p><pre class="brush: xml; gutter: false; wrap-lines: false;">
&lt;UsingTask AssemblyFile=&quot;Build Tools\AcmeCorp.MsBuildTasks.dll&quot;
           TaskName=&quot;AcmeCorp.MsBuildTasks.MercurialAssemblyFileVersionUpdate&quot; /&gt;

&lt;UsingTask AssemblyFile=&quot;Build Tools\AcmeCorp.MsBuildTasks.dll&quot;
           TaskName=&quot;AcmeCorp.MsBuildTasks.MercurialExec&quot; /&gt;
</pre></p>
<p>You&#8217;ll notice that the parsing implementation is quite forgiving. It is a regular expression that will extract anything that looks like a parsable <code>System.Version</code> string. This is cool because it means the tags themselves don&#8217;t have to be exactly pure as <code>System.Version</code> would need them. You can leave a &#8220;v&#8221; in front, or add a suffix like &#8220;-build&#8221;. Whatever your convention is, it just makes things a bit more convenient.</p>
<h2>Remaining notes</h2>
<p>The implementation above will generate global tags that are revision controlled in the repository. I did consider using &#8220;local tags&#8221; as those wouldn&#8217;t need to be held in the repository at all and could just sit on the automated build server only. However unfortunately the &#8220;<code>latesttag</code>&#8221; template does not work with local tags, it only appears to work with global tags. It would also of course mean that developers wouldn&#8217;t benefit from the tags at all, which would be a shame.</p>
<p>Mercurial stores global tags inside a <code>.hgtags</code> file in the root working directory. The file is revision controlled but only for auditing purposes. It does not matter which version you have in your working directory at any given time.</p>
<p>You may still require a workflow to perform merges between your branches after running a build, in order to propagate the <code>.hgtags</code> file immediately (and not leave it to someone else!). If any merge conflicts arise you should <a href="http://mercurial.selenic.com/wiki/Tag#My_tags_had_a_conflict_when_I_was_merging.__Why.3F__How_should_I_merge_them.3F" target="_blank">take the changes from both sides</a> as the <code>.hgtags</code> file can be considered &#8220;cumulative&#8221;.</p>
<h2>Related reading</h2>
<p><a href="http://kiln.stackexchange.com/questions/2194/best-practice-generating-build-numbers">http://kiln.stackexchange.com/questions/2194/best-practice-generating-build-numbers</a><br />
<a href="http://stackoverflow.com/questions/4726257/most-recent-tag-before-tip-in-mercurial">http://stackoverflow.com/questions/4726257/most-recent-tag-before-tip-in-mercurial</a><br />
<a href="http://www.jaharmi.com/2010/03/24/generate_version_numbers_for_mac_os_x_package_installers_with_mercurial_and_semantic_vers">http://www.jaharmi.com/2010/03/24/generate_version_numbers_for_mac_os_x_package_installers_with_mercurial_and_semantic_vers</a><br />
<a href="http://mercurial.selenic.com/wiki/NearestExtension">http://mercurial.selenic.com/wiki/NearestExtension</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/91/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=91&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/05/16/automated-builds-and-versioning-with-mercurial/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>Memory leaks with an infinite-lifetime instance of MarshalByRefObject</title>
		<link>http://nbevans.wordpress.com/2011/04/17/memory-leaks-with-an-infinite-lifetime-instance-of-marshalbyrefobject/</link>
		<comments>http://nbevans.wordpress.com/2011/04/17/memory-leaks-with-an-infinite-lifetime-instance-of-marshalbyrefobject/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 20:31:46 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[.NET Framework]]></category>
		<category><![CDATA[Software Design]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[appdomain]]></category>
		<category><![CDATA[clr profiler]]></category>
		<category><![CDATA[memory leak]]></category>
		<category><![CDATA[remoting]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=83</guid>
		<description><![CDATA[Recently we discovered an issue with the way our product performs AppDomain sandboxing. We were leaking small amounts of memory, quite badly, from each sandbox and every sandbox operation ever created over the lifetime of the process. After much investigation using CLR Profiler, it transpired that our subclasses of MarshalByRefObject which were using &#8220;null&#8221; as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=83&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently we discovered an issue with the way our product performs AppDomain sandboxing. We were leaking small amounts of memory, quite badly, from each sandbox and every sandbox <em>operation</em> ever created over the lifetime of the process. After much investigation using <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=be2d842b-fdce-4600-8d32-a3cf74fda5e1">CLR Profiler</a>, it transpired that our subclasses of <code>MarshalByRefObject</code> which were using &#8220;null&#8221; as the return from their <code>InitializeLifetimeService()</code> will cause a permanent reference to be held open by some fairly low level area in the .NET remoting stack, specifically <code>System.Runtime.Remoting.ServerIdentity</code> (which is marked internal). This was preventing any of our object(s) derived from <code>MarshalByRefObject</code> from being garbage collected, and thus the memory footprint would keep growing and growing. Fortunately we run our servers with rather huge page files so it never got to a point where customers were affected, but obviously it was something we needed to fix fairly urgently.</p>
<p>After playing around a lot with all the lifetime services stuff like the <code><a href="http://msdn.microsoft.com/en-us/library/system.runtime.remoting.lifetime.isponsor.aspx">ISponsor</a></code> interface to do sponsorship with nasty hacky timeout values etc (which would have had side-affects for our product, but which we were about to resign ourselves too!) we came across a much better alternative solution in the form of <code>RemotingServices.Disconnect()</code>. Hoorah. Is it just me or does the whole remoting story in .NET need a damn good overhaul? Cross-AppDomain communications deserves something better.</p>
<p>With this discovery, I came up with a useful class that improves <code>MarshalByRefObject</code>  by adding deterministic disposal of both itself and any such nested objects (which is more an implementation detail for us but I&#8217;m sure could be useful for anyone).</p>
<p><pre class="brush: csharp; gutter: false; wrap-lines: false;">
/// &lt;summary&gt;
/// Enables access to objects across application domain boundaries.
/// This type differs from &lt;see cref=&quot;MarshalByRefObject&quot;/&gt; by ensuring that the
/// service lifetime is managed deterministically by the consumer.
/// &lt;/summary&gt;
public abstract class CrossAppDomainObject : MarshalByRefObject, IDisposable {

    private bool _disposed; 

    /// &lt;summary&gt;
    /// Gets an enumeration of nested &lt;see cref=&quot;MarshalByRefObject&quot;/&gt; objects.
    /// &lt;/summary&gt;
    protected virtual IEnumerable&lt;MarshalByRefObject&gt; NestedMarshalByRefObjects {
        get { yield break; }
    }

    ~CrossAppDomainObject() {
        Dispose(false);
    }

    /// &lt;summary&gt;
    /// Disconnects the remoting channel(s) of this object and all nested objects.
    /// &lt;/summary&gt;
    private void Disconnect() {
        RemotingServices.Disconnect(this);

        foreach (var tmp in NestedMarshalByRefObjects)
            RemotingServices.Disconnect(tmp);
    }

    public sealed override object InitializeLifetimeService() {
        //
        // Returning null designates an infinite non-expiring lease.
        // We must therefore ensure that RemotingServices.Disconnect() is called when
        // it's no longer needed otherwise there will be a memory leak.
        //
        return null;
    }

    public void Dispose() {
        GC.SuppressFinalize(this);
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing) {
        if (_disposed)
            return;

        Disconnect();
        _disposed = true;
    }

}
</pre></p>
<p>It was then just a case of modifying a few of our classes to derive from this instead of <code>MarshalByRefObject</code> and then update a couple other locations in our codebase by ensuring that <code>Dispose()</code> was called during clean-up.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/83/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=83&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/04/17/memory-leaks-with-an-infinite-lifetime-instance-of-marshalbyrefobject/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>Solved: Hyper-V&#8217;s VMConnect tool sporadically losing connection to VM</title>
		<link>http://nbevans.wordpress.com/2011/03/05/solved-hyper-vs-vmconnect-tool-sporadically-losing-connection-to-vm/</link>
		<comments>http://nbevans.wordpress.com/2011/03/05/solved-hyper-vs-vmconnect-tool-sporadically-losing-connection-to-vm/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 11:27:13 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[Windows Environment]]></category>
		<category><![CDATA[hyper-v]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=77</guid>
		<description><![CDATA[Last night we performed a big switch over in our data centre. We moved everything onto a new managed switch and Sonicwall firewall, re-pointed and re-addressed lots and lots of servers, and well basically just done a bunch of stuff we should have done yonks ago! Everything seemed to go really well except for one thing: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=77&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last night we performed a big switch over in our data centre. We moved everything onto a new managed switch and Sonicwall firewall, re-pointed and re-addressed lots and lots of servers, and well basically just done a bunch of stuff we should have done yonks ago! Everything seemed to go really well except for one thing: our Hyper-V hosts were now throwing really annoying and random disconnection errors when connected straight into a VM using its &#8220;<em>Connect&#8230;</em>&#8221; menu item, or otherwise known as <code>VMConnect.exe</code>. The connection would work for at least a couple seconds, sometimes for as long as a minute or two. But then it would barf up and the following error message dialog would be displayed.</p>
<div id="attachment_74" class="wp-caption alignnone" style="width: 310px"><a href="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-error.png"><img class="size-medium wp-image-74" title="Hyper-V's VMConnect tool displaying the disconnection error message" src="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-error.png?w=300&#038;h=229" alt="" width="300" height="229" /></a><p class="wp-caption-text">Hyper-V&#039;s VMConnect tool displaying the disconnection error message</p></div>
<p>The full description of the error was as follows:</p>
<blockquote><p><em>The connection to the virtual machine was lost. This can occur when a virtual machine stops unexpectedly, or when network problems occur. Try to connect again. If the problem persists, contact your system administator.</em></p>
<p><em>Would you like to try to reconnnect?</em></p></blockquote>
<p>This was really annoying because we were connecting to local VMs that were present on the exact same VM host from which we were connecting. So presumably there wouldn&#8217;t be any packets hitting the network, and thus ruling out any of the new hardware and network changes we had just made.</p>
<p>After racking my brains on it for a bit (which included firing up Wireshark to perform a sanity check), I loaded up <a href="http://technet.microsoft.com/en-us/sysinternals/bb897437">TCPView</a>. This is a really great little tool from <a href="http://blogs.technet.com/b/markrussinovich/">Mark Russinovich</a>&#8216;s stable called <a href="http://technet.microsoft.com/en-us/sysinternals/">Windows Sysinternals</a>. With this tool running I then retried the VMConnect, so that I could see what socket activities it was performing.</p>
<div id="attachment_76" class="wp-caption alignnone" style="width: 310px"><a href="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpview.png"><img class="size-medium wp-image-76" title="TCPView shows the VMConnect appearing to use TCP/IP V6 even for localhost" src="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpview.png?w=300&#038;h=52" alt="" width="300" height="52" /></a><p class="wp-caption-text">TCPView shows the VMConnect appearing to use TCP/IP V6 even for localhost</p></div>
<p>What this showed is that even when connecting to the local VM host using &#8220;<code>localhost</code>&#8221; or &#8220;<code>127.0.0.1</code>&#8221; as the address (i.e. IPv4) the VMConnect tool was seemingly transforming this into a IPV6 address and then forming a TCPV6 connection. This was interesting.</p>
<p>I immediately went to check whether IPV6 was actually enabled on the VM host&#8217;s network adapters. Low and behold, it was not. Turns out that when we flicked over the Gateway IP to point to the new firewall, we also subconciously turned off the IPV6 protocol on the list! A fairly innocuous thing to do, one would think, especially on an internal LAN!</p>
<div id="attachment_75" class="wp-caption alignnone" style="width: 248px"><a href="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpip-settings.png"><img class="size-medium wp-image-75" title="Hyper-V's virtual network adapter TCP/IP settings" src="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpip-settings.png?w=238&#038;h=300" alt="" width="238" height="300" /></a><p class="wp-caption-text">Hyper-V&#039;s virtual network adapter TCP/IP settings</p></div>
<p>So there you have it. If you come across this problem with Hyper-V, I would recommend you immediately check to ensure that you have not inadvertently disabled the IPV6 protocol on your virtual network adapter for Hyper-V.</p>
<p>The very moment we re-enabled IPV6, the problem with VMConnect constantly disconnecting every few seconds totally went away!</p>
<p>Not many problems get more obscure than this.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=77&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/03/05/solved-hyper-vs-vmconnect-tool-sporadically-losing-connection-to-vm/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>

		<media:content url="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-error.png?w=300" medium="image">
			<media:title type="html">Hyper-V&#039;s VMConnect tool displaying the disconnection error message</media:title>
		</media:content>

		<media:content url="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpview.png?w=300" medium="image">
			<media:title type="html">TCPView shows the VMConnect appearing to use TCP/IP V6 even for localhost</media:title>
		</media:content>

		<media:content url="http://nbevans.files.wordpress.com/2011/03/hyperv-vmconnect-disconnect-tcpip-settings.png?w=238" medium="image">
			<media:title type="html">Hyper-V&#039;s virtual network adapter TCP/IP settings</media:title>
		</media:content>
	</item>
		<item>
		<title>Cultural learnings of HA-Proxy, for make benefit&#8230;</title>
		<link>http://nbevans.wordpress.com/2011/03/03/cultural-learnings-of-ha-proxy-for-make-benefit/</link>
		<comments>http://nbevans.wordpress.com/2011/03/03/cultural-learnings-of-ha-proxy-for-make-benefit/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 22:27:53 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[Unix Environment]]></category>
		<category><![CDATA[haproxy]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=58</guid>
		<description><![CDATA[I&#8217;ve been setting up lots and lots of small details on our HA-Proxy cluster this week. This post is just a small digest of some of the things I have learnt. The option nolinger is considered harmful. I read somewhere that this option should be enabled because it frees up socket resources quicker and doesn&#8217;t [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=58&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been setting up lots and lots of small details on our HA-Proxy cluster this week. This post is just a small digest of some of the things I have learnt.</p>
<h2>The <code>option nolinger</code> is considered harmful.</h2>
<p>I read somewhere that this option should be enabled because it frees up socket resources quicker and doesn&#8217;t leave them lying around when blatently dead. I enabled it and thought nothing more of it. Having forgot I had done so, I then started noticing strange behaviours. Most tellingly was that HA-Proxy&#8217;s webstats UI would truncate abruptly before completing. Fortunately, Willy Tarreau (the author/maintainer) was very quick to respond to my pestering e-mails and after seeing my Wireshark trace he immediately had a few ideas of what could be causing it. After following his suggestion to avoid using the &#8220;no linger&#8221; option, I removed it from my configuration and the problem went away.</p>
<p>Therefore: &#8220;option nolinger considered harmful.&#8221; You&#8217;ve be warned!</p>
<h2>Webstats UI has &#8220;hidden&#8221; administrative functions</h2>
<p>While reading the infamous &#8220;<a href="http://haproxy.1wt.eu/download/1.4/doc/configuration.txt">wall of text</a>&#8221; that is the HA-Proxy documentation, I came across a neat option called &#8220;<code>stats admin</code>&#8220;. It enables a single piece of extra functionality (at least it does in v1.4.11) that will let you flag servers as being online or offline. This is useful if you&#8217;re planning to take one or more servers out of a backend&#8217;s pool, for maintenance possibly. I would wager that Willy intends to add more administrative features in the future so adding this one to your config now could save you some time in the future.</p>
<p>Of course, it is not likely that you will want such a sensitive function to be exposed to everyone that uses webstats. So it is fortunate then that this option supports a condition expression. I set mine up like the following:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
userlist UsersFor_HAProxyStatistics
  group admin users admin
  user admin insecure-password godwouldntbeupthislate
  user stats insecure-password letmein

listen HAProxy-Statistics *:81
  mode http
  stats enable
  stats uri /haproxy?stats
  stats refresh 60s
  stats show-node
  stats show-legends
  acl AuthOkay_ReadOnly http_auth(UsersFor_HAProxyStatistics)
  acl AuthOkay_Admin http_auth_group(UsersFor_HAProxyStatistics) admin
  stats http-request auth realm HAProxy-Statistics unless AuthOkay_ReadOnly
  stats admin if AuthOkay_Admin
</pre></p>
<h2>Request/response rewriting is mutually exclusive of keep-alive connections</h2>
<p>At least in current versions, HA-Proxy doesn&#8217;t seem to be able to perform rewriting on connections that have been kept alive. It is limited to analysing only the first request and response. Any further requests that occur on that connection will go unanalysed. So if you are doing request or response rewriting, it is imperative that you set a special option to ensure that a connection can only be used once.</p>
<p>In my case, I just added the following to my <code>frontend</code> definition.</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
option http-server-close
</pre></p>
<h2>Identifying your frontend from your backend</h2>
<p>I was creating some rules to ensure that a particular URL could <em>only </em>be accessed through my HTTPS frontend. I wanted to prevent unencrypted HTTP access to this URL because it was using HTTP Basic authentication which uses clear text passwords across the wire.</p>
<p>Fortunately, HA-Proxy supports a fairly neat way of doing this by the means of tagging your frontend with a unique identifier which can then be matched against by the backend.</p>
<p>First of all, I setup my frontends like the following:<br />
<pre class="brush: plain; gutter: false; highlight: [2,9]; wrap-lines: false;">
frontend Public-HTTP
  id 80
  mode http
  bind *:80
  option http-server-close
  default_backend Web-Farm

frontend Public-HTTPS
  id 8443
  mode http
  # Note: Port 8443 because the true 443 is being terminated by Stunnel, which then forwards to this 8433.
  bind *:8443
  option http-server-close
  default_backend Web-Farm
</pre></p>
<p>Then in my backend I cleared a space for defining &#8220;reusable&#8221; ACLs and then added the protective rule for the URL in question:</p>
<p><pre class="brush: plain; gutter: false; highlight: [9,10,13,14]; wrap-lines: false;">
backend Web-Farm
  mode http
  balance roundrobin
  option httpchk
  server Web0 172.16.61.181:80 check
  server Web1 172.16.61.182:80 check

  # Common/useful ACLs
  acl ViaFrontend_PublicHttp fe_id 80
  acl ViaFrontend_PublicHttps fe_id 8443

  # Application security for: /MyWebPage/
  acl PathIs_MyWebPage path_beg -i /mywebpage
  http-request deny if PathIs_MyWebPage !ViaFrontend_PublicHttps
</pre></p>
<p>The piece of magic that makes this all work is the <code>fe_id</code> ACL criterion. Note that the &#8220;fe&#8221; stands for &#8220;frontend&#8221;.</p>
<p>Note the http-request deny rule is comprised of two ACLs, by boolean AND&#8217;ing them. HA-Proxy defaults to AND&#8217;ing. If you want to OR just type &#8220;<code>or</code>&#8221; or &#8220;<code>||</code>&#8220;. Negation is done in the normal C way by using an exclamation symbol, as shown in the above example. I seem to like avoiding the use of the &#8220;<code>unless</code>&#8221; statement as I prefer the explicitness of using &#8220;<code>if</code>&#8221; and then using negation. But that&#8217;s just my personal preference as a long-time coder <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now if a user tries to visit <code>http://.../MyWebPage</code> they will get a big fat ugly <strong><code>403 Forbidden</code></strong> error.</p>
<h2>HTTP Basic authentication is finally very basic to do!</h2>
<p>I came across a stumbling block this week. I assumed that Microsoft IIS, one of the best web servers available, could do HTTP Basic authentication i.e. clear text passwords over the wire and then validating against some sort of clear text password file or database. Turns out that while IIS does support HTTP Basic auth&#8217;, it doesn&#8217;t support any form of simple backend. You have to validate against either the web servers local Windows user accounts, or against Active Directory. Great. The web page in question was just a little hacky thing we knocked up to get a customer of ours out of a hole. We didn&#8217;t want to be creating maintenance headaches for ourselves by creating a local user account on each web server in the farm, nor did we fancy creating them an AD account. They don&#8217;t even belong to our company!</p>
<p>Fortunately (that word again), and despite how poorly documented it is, HA-Proxy *<em>does</em>* support this!</p>
<p>First of all you need to create a userlist that will contain your users/groups that you will authenticate against:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
userlist UsersFor_AcmeCorp
  user joebloggs insecure-password letmein
</pre></p>
<p>Then in your backend, you need to create an ACL that uses the <code>http_auth</code> criterion. And lastly, create an <code>http-request auth</code> rule that will cause the appropriate <code><strong>401 Unauthorized</strong></code> and <code><strong>WWW-Authenticate: Basic</strong></code> response to be generated if the authentication has failed.</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
backend HttpServers
  .. normal backend stuff goes here as usual ..
  acl AuthOkay_AcmeCorp http_auth(UsersFor_AcmeCorp)
  http-request auth realm AcmeCorp if !AuthOkay_AcmeCorp
</pre></p>
<h2>Remove sensitive IIS / ASP.NET response headers</h2>
<p>Security unconscious folk need not apply.</p>
<p>It&#8217;s a slight security risk to be leaking your precise IIS and ASP.NET version numbers. Whilst these can be turned off in IIS configuration, it is more a concern for your frontend load balancer i.e. HA-Proxy. The reason I believe this is because the headers can be useful debugging on the internal LAN/VPN inside your company. Only when the headers are about to touch the WAN does it become dangerous. Therefore:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
frontend Public-HTTP
  # Remove headers that expose security-sensitive information.
  rspidel ^Server:.*$
  rspidel ^X-Powered-By:.*$
  rspidel ^X-AspNet-Version:.*$
</pre></p>
<h2>HTTPS and separation of concerns</h2>
<p>I don&#8217;t know about Apache, but IIS 7.5 can have some annoying (but arguably expected) behaviours when HA-Proxy is passing traffic where the client believes it has an end-to-end HTTPS connection with the web server. My setup involves Stunnel terminating the SSL connection and then from that point on it is just standard HTTP traffic to the backend servers. This means the backend servers don&#8217;t actually need to be listening on HTTPS/443 at all. However when GET requests come in to them using the https:/ scheme they can get a bit confused (or argumentative, I&#8217;m undecided). IIS seems to like sending back a <strong><code>302 Moved Permanently</code></strong> response, with a <strong><code>Location</code></strong> header that uses the http:/ scheme. So then of course the web browser will follow the redirect to either a URL that doesn&#8217;t exist or one which does exist but is already merely a redirect to the https:/ scheme! Infinitely loop anyone?</p>
<p>The way to solve this is request rewriting, through some clever use of <a href="http://www.amazon.co.uk/Mastering-Regular-Expressions-Powerful-Techniques/dp/1565922573">regular expressions</a>.</p>
<p><pre class="brush: plain; gutter: false; highlight: [10,15,16]; wrap-lines: false;">
frontend Public-HTTPS
  id 8443
  mode http
  bind *:8443
  option http-server-close
  default_backend Web-Farm

  # Rewrite requests so that they are passed to the backend as http:/ schemed requests.
  # This may be required if the backend web servers don't like handling https schemed requests over non-https transport.
  # I didn't use this in the end - but it might come in handy in the future so I left it commented out.
  # reqirep ^(\w+\ )https:/(/.*)$ \1http:/\2

  # Rewrite responses containing a Location header with HTTP scheme using the relative path.
  # We could alternatively just rewrite the http:/ to be https:/ but then it could break off-site redirects.
  rspirep ^Location:\s*http://.*?\.acmecorp.co.tld(/.*)$ Location:\ \1
  rspirep ^Location:(.*\?\w+=)http(%3a%2f%2f.*?\.acmecorp.co.tld%2f.*)$ Location:\ \1https\2
</pre></p>
<p>The first <code>rspirep</code> in the above example is the most important. The second is something more specific to a particular web application we&#8217;re hosting that uses a <code>?Redirect=http://yada.yada</code> style query string in certain places.</p>
<p>The <code>rsprep</code> / <code>rspirep</code> rule (the <code>i</code> means case-insensitive matching) is very powerful. The only downside is that you do need to be fairly fluent with regular expressions. It requires only two parameters, the first is your regular expression and the second is your string replacement.</p>
<p>The string replacement that occurs in the second parameter supports expansion based upon indexed capture groups from the regular expression that was matched. This is useful for merging very specific pieces from the match back into the replacement string, as I am doing in the example above. They take the form of <code>\1</code> or <code>\2</code> etc. Where the number indicates the capture group index number. And capture groups are denoted in the regular expression by using parenthesis, if you didn&#8217;t know.</p>
<h2>Truly &#8220;live&#8221; updates on the Webstats UI</h2>
<p>One of the first things I noticed in the hours after deploying HA-Proxy is that the webstat counters that are held for each frontend, listen and backend are not actually updated as frequently as they perhaps ought to be. Indeed, the counters for any given connection are not accumulated until that connection has ended. This is bad if your application(s) tend to hold open long-duration connections. It reduces your usability of HA-Proxy&#8217;s reporting. I&#8217;m sure there are very good performance reasons that Willy did this, as that is what is alluded to in the documentation. Fortunately there is a very simple workaround for this in the form of the contstats option.</p>
<p>Simply add the following to your proxy and benefit from higher accuracy webstats:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
option contstats
</pre></p>
<p>Until next time&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/58/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/58/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/58/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=58&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/03/03/cultural-learnings-of-ha-proxy-for-make-benefit/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
		<item>
		<title>Safely pairing HA-Proxy with virtual network interface providers like Keepalived or Heartbeat</title>
		<link>http://nbevans.wordpress.com/2011/03/01/safely-pairing-haproxy-with-virtual-network-interface-providers-like-keepalived-or-heartbeat/</link>
		<comments>http://nbevans.wordpress.com/2011/03/01/safely-pairing-haproxy-with-virtual-network-interface-providers-like-keepalived-or-heartbeat/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 14:28:10 +0000</pubDate>
		<dc:creator>Nathan Evans</dc:creator>
				<category><![CDATA[Unix Environment]]></category>
		<category><![CDATA[haproxy]]></category>
		<category><![CDATA[heartbeat]]></category>
		<category><![CDATA[keepalived]]></category>

		<guid isPermaLink="false">http://nbevans.wordpress.com/?p=46</guid>
		<description><![CDATA[This is sort of a follow-up to the Deploying HA-Proxy + Keepalived with Mercurial for distributed config post. During testing we were coming across an issue where the HA-Proxy instance running on the slave member of our cluster would fail to bind some of its frontend proxies: After some head scratching I noticed that the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=46&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is sort of a follow-up to the <a href="http://nbevans.wordpress.com/2011/02/27/deploying-ha-proxy-keepalived-with-mercurial-for-distributed-config/">Deploying HA-Proxy + Keepalived with Mercurial for distributed config</a> post.</p>
<p>During testing we were coming across an issue where the HA-Proxy instance running on the slave member of our cluster would fail to bind some of its frontend proxies:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
Starting haproxy: [ALERT] : Starting proxy Public-HTTPS: cannot bind socket
</pre></p>
<p>After some head scratching I noticed that the problem was only arising on those proxies that explicitly defined the IP address of a virtual interface that was being managed by Keepalived (or maybe Heartbeat for you).</p>
<p>This is because both of these High-Availability clustering systems use a rather simplistic design whereby the &#8220;shared&#8221; virtual IP is only installed on the <em>active</em> node in the cluster. While the nodes that are in a dormant state (i.e. the slaves) do not actually have those virtual IPs assigned to them during that state. It&#8217;s a sort of &#8220;IP address hot-swapping&#8221; design. I learnt this by executing a simple a command, first from the master server:</p>
<p><pre class="brush: plain; gutter: false; highlight: [6,7]; wrap-lines: false;">
$ ip a
&lt;snipped stuff for brevity&gt;
2: seth0:  mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 00:15:5d:28:7d:19 brd ff:ff:ff:ff:ff:ff
    inet 172.16.61.151/24 brd 172.16.61.255 scope global seth0
    inet 172.16.61.150/24 brd 172.16.61.255 scope global secondary seth0:0
    inet 172.16.61.159/24 brd 172.16.61.255 scope global secondary seth0:1
    inet6 fe80::215:5dff:fe28:7d19/64 scope link
       valid_lft forever preferred_lft forever
&lt;snipped trailing stuff for brevity&gt;
</pre></p>
<p>Then again, from the slave server:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
$ ip a
&lt;snipped stuff for brevity&gt;
2: seth0:  mtu 1500 qdisc pfifo_fast qlen 1000
    link/ether 00:15:5d:2d:9c:11 brd ff:ff:ff:ff:ff:ff
    inet 172.16.61.152/24 brd 172.16.61.255 scope global seth0
    inet6 fe80::215:5dff:fe2d:9c11/64 scope link
       valid_lft forever preferred_lft forever
&lt;snipped trailing stuff for brevity&gt;
</pre></p>
<p>Unfortunately this behaviour can cause problems for programs like HA-Proxy which have been configured to expect the existence of specific network interfaces on the server. I was considering working around it by writing some scripts that hook events within the HA cluster to handle stopping and starting the HA-Proxy when needed. But this approach seemed clunky and unintuitive. So I dug a little deeper and came across a bit of a gem hidden away in the depths of the Linux networking stack. It is a simple boolean setting called &#8220;<code>net.ipv4.ip_nonlocal_bind</code>&#8221; and it allows a program like HA-Proxy to create listening sockets on network interfaces that do not actually exist on the server. It was created specially for this situation.</p>
<p>So in the end the fix was as simple as adding/updating the <code>/etc/sysctl.conf</code> file to include the following key/value pair:</p>
<p><pre class="brush: plain; gutter: false; wrap-lines: false;">
net.ipv4.ip_nonlocal_bind=1
</pre></p>
<p>My previous experience of setting up these low-level High-Availability clusters was with Windows Server&#8217;s feature called Network Load Balancing (NLB). This works quite different from Keepalived and Heartbeat. It relies upon some low level ARP hacking/trickery and some sort of distributed time splicing algorithm. But it does ensure that each node in the cluster (whether in a master or slave position) will remain allocated with the virtual IP address(es) at all times. I suppose there is always more than one way to crack an egg&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nbevans.wordpress.com/46/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nbevans.wordpress.com/46/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nbevans.wordpress.com/46/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nbevans.wordpress.com&amp;blog=13441406&amp;post=46&amp;subd=nbevans&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nbevans.wordpress.com/2011/03/01/safely-pairing-haproxy-with-virtual-network-interface-providers-like-keepalived-or-heartbeat/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/9d93e1c44b5203e7725c739887ac9899?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">nbevans</media:title>
		</media:content>
	</item>
	</channel>
</rss>
