<?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>~ #_</title>
	<atom:link href="http://daltonmatos.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://daltonmatos.wordpress.com</link>
	<description>Desenvolvimento, Linux e coisas que a faculdade não te ensina.</description>
	<lastBuildDate>Sat, 07 Jan 2012 20:30:47 +0000</lastBuildDate>
	<language>pt-br</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='daltonmatos.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>~ #_</title>
		<link>http://daltonmatos.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://daltonmatos.wordpress.com/osd.xml" title="~ #_" />
	<atom:link rel='hub' href='http://daltonmatos.wordpress.com/?pushpress=hub'/>
		<item>
		<title>How to configure wsgid and mongrel2 to handle arbitrary sized requests</title>
		<link>http://daltonmatos.wordpress.com/2012/01/07/how-to-configure-wsgid-and-mongrel2-to-handle-arbitrary-sized-requests/</link>
		<comments>http://daltonmatos.wordpress.com/2012/01/07/how-to-configure-wsgid-and-mongrel2-to-handle-arbitrary-sized-requests/#comments</comments>
		<pubDate>Sat, 07 Jan 2012 20:28:57 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Projetos]]></category>
		<category><![CDATA[mongrel2]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[wsgid]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=621</guid>
		<description><![CDATA[Intro Wsgid is a generic handler for the mongrel2 web server. It acts as a bridge between WSGI and mongrel2 and makes it possible to run any WSGI python application using mongrel2 as the front end. To know more about both projects visit their official websites at: http://wsgid.com and http://mongrel2.org In this post we will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=621&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>Intro</h1>
<p style="text-align:justify;">Wsgid is a generic handler for the mongrel2 web server. It acts as a bridge between WSGI and mongrel2 and makes it possible to run any WSGI python application using mongrel2 as the front end. To know more about both projects visit their official websites at: <a class="reference external" title="WSGID official website" href="http://wsgid.com" target="_blank">http://wsgid.com</a> and <a class="reference external" title="Mongrel2 official website" href="http://mongrel2.org" target="_blank">http://mongrel2.org</a></p>
<p style="text-align:justify;">In this post we will see how to configure mongrel2 and wsgid so your application will be able to handle arbitrary sized requests very easily and with a low memory usage.</p>
<div id="why" class="section">
<h1>Why?</h1>
<p style="text-align:justify;">The problem of receiving big requests is that depending on how your front end server deals with it, you can easily become out of resources and in a worst case scenario your application can stop responding for a while. If your application exposes any POST endpoint, then you should be prepared to handle some big requests along the way.</p>
</div>
<div id="the-big-picture" class="section">
<h1 style="text-align:justify;">The big picture</h1>
<p style="text-align:justify;">Mongrel2 has a very clever way to handle big requests without consuming all your server&#8217;s resources, in fact without consuming almost nothing, only bandwidth. Basically what it does is to dump the entire request to disk, using almost none additional memory. Here is how it works:</p>
<p style="text-align:justify;">When the request comes in, mongrel2 sends a special message to the back-end handler containing only the original headers. This message notifies the start of this request. It&#8217;s up to the handler to accept or deny it. To accept the request, your handler just do nothing. If you want to deny the request, your handler must send a 0-length message back to mongrel2. Due to mongrel2 async model, you can send this <em>deny message</em> at any time, does not need to be imediatelly after receiving the <em>request start</em> message.</p>
<p style="text-align:justify;">If you happen to be using wsgid (I hope you are!) this happens without your WSGI application ever knowing. All your application will see (if at all) is the <tt class="docutils literal">wsgi.input</tt> attribute of the WSGI environ (if you happen to write a WSGI framework) or just <tt>request.POST </tt>(or something similar depending on what framework you&#8217;re using). It&#8217;s all transparent.</p>
<p style="text-align:justify;">After the request is completely dumped, mongrel2 sends another message notifying the end of the upload and that&#8217;s when wsgid will actually call your application. During all the upload process, your application does not even know that a new request has come and was being handled.</p>
<p style="text-align:justify;">All this happens <strong>while</strong> mongrel2 is <strong>already</strong> dumping the request content to disk. If your handler happen to deny the request, mongrel2 will close the connection and remove the temporary file. To know more about how mongrel2 notifies the handlers, you can read the on-line manual: <a class="reference external" title="Mongrel2 official Manual" href="http://mongrel2.org/static/mongrel2-manual.html" target="_blank">http://mongrel2.org/static/mongrel2-manual.html</a>.</p>
</div>
<div id="configuring-mongrel2-to-handle-big-requests" class="section">
<h1 style="text-align:justify;">Configuring mongrel2 to handle big requests</h1>
<p style="text-align:justify;">The configuration of the server is extremely simple. All you have to do is tell it where to dump any big request that may arrive. You may ask: How big a request must be to be dumped to disk? The truth is that <strong>you</strong> decide this and tell mongrel2 about it.</p>
<p style="text-align:justify;">To tell it where to dump the request you must set the option <tt class="docutils literal">upload.temp_store</tt> to the correct path. This path must include the filename template. An example could be: <tt class="docutils literal">/uploads/m2.XXXXXX</tt>. This must be a <tt class="docutils literal">mkstemp(3)</tt> compatible template. See the manpage for more details.</p>
<p style="text-align:justify;">The size of the request is set with the <tt class="docutils literal">limits.content_length</tt>. This sets the biggest request mongrel2 will handle without dumping to disk. This size is set in bytes.</p>
</div>
<div id="configuring-wsgid-to-understand-what-mongrel2-is-saying" class="section">
<h1 style="text-align:justify;">Configuring wsgid to understand what mongrel2 is saying</h1>
<p style="text-align:justify;">Since mongrel is saving requests on disk wsgid must be able to open these files and pass its contents to the application being run. It&#8217;s important to note that the path chosen on the <tt>upload.temp_store</tt> is always relative to where your mongrel2 is chrooted, so somehow we must tell wsgid where this is.</p>
<p style="text-align:justify;">Fortunately this new release of wsgid comes with a new command line option: <tt>--mongrel2-chroot</tt>. You just have to pass this to your wsgid instance to be able to handle big requests.</p>
<p style="text-align:justify;">Alternatively you can add this options to your <tt>wsgid.json</tt> configuration file if you want. This can be complished with a simple command:</p>
<p style="text-align:justify;"><tt>$ wsgid config --app-path=/path/to/your/wsgid-app --mongrel2-chroot=/path/to/mongrel2/chroot</tt></p>
<p style="text-align:justify;">This will save this new option on your config file. Just restart your wsgid instance and it will re-read the config file.</p>
</div>
<div id="working-without-knowing-where-mongrel2-is-chrooted" class="section">
<h1 style="text-align:justify;">Working without knowing where mongrel2 is chrooted</h1>
<p style="text-align:justify;">There is another way to handle these big requests. In this approach your don&#8217;t need to pass <tt>--mongrel2-chroot</tt> to all your wsgid instances. The trick here is to mount the same device on many different places. The easiest way to do this is to have mongrel2&#8242;s <cite>temp_store</cite> in a separated partition (or logical volume if you are using LVM). Let&#8217;s see an example:</p>
<p style="text-align:justify;">Suppose we have mongrel2 chrooted at <tt>/var/mongrel2/</tt> and configured this way:</p>
<p style="text-align:justify;"><tt>upload.temp_store = '/uploads/m2.XXXXXX'</tt></p>
<p style="text-align:justify;">Since mongrel2 assumes <tt>/uploads</tt> is relative to its chroot we must mount this device ate the right place.</p>
<p style="text-align:justify;"><tt># mount /dev/vg01/uploads /var/mongrel2/uploads</tt></p>
<p style="text-align:justify;">Now our logical volume is mounted at <tt>/var/mongrel2/uploads</tt>. There is one last setp so we can start serving big requests with wsgid. When mongrel2 sends the <cite>upload started</cite> message to wsgid, which contains the path of the temporary file, the path received by wsgid is the same we put on mongrel2&#8242;s config. So wsgid will try to read <tt class="docutils literal">/uploads/m2.384Tdg</tt> (for example) and obviously will fail. So we need a way to make <tt class="docutils literal">/uploas/</tt> also available to wsgid (that normally is not chrooted anywhere) and the trick to do this is to re-mount the same device at a different place. And this is how we do it:</p>
<p style="text-align:justify;"><tt># mount /dev/vg01/uploads /uploads</tt></p>
<p style="text-align:justify;">So now we have the same device mongrel2 writes the temporary files available to all wsgid processes that need to read them. Remember that mongrel2 does not remove any of these file because obviously it does not know when your app is done. So it&#8217;s up to you to clean them.</p>
<p style="text-align:justify;">If your <tt>/upload</tt> directory is part of a bigger volume or is not on a separated one, you still can accomplish this multi-mount approach. Just use the <tt>--bind</tt>. This way you can re-mount any directory at another place. Read the mount man page for more details.</p>
</div>
<div id="conclusion" class="section">
<h1 style="text-align:justify;">Conclusion</h1>
<p style="text-align:justify;">This is another cool mongrel2 feature that the latest wsgid release (0.5.0) already supports. So now wsgid supports all major features mongrel2 provides and is starting to be more mature, trying to find its way into a production-ready tool.</p>
<p style="text-align:justify;">This release complete changelog is available at <a title="Wsgid changelog" href="http://wsgid.com/changelog" target="_blank">wsgid.com/changelog</a> and you can grab your wsgid copy at <a title="WSGID official website" href="http://wsgid.com" target="_blank">wsgid.com</a>.</p>
<p style="text-align:justify;">Thanks for reading and enjoy!</p>
</div>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/mongrel2/'>mongrel2</a>, <a href='http://daltonmatos.wordpress.com/tag/python/'>python</a>, <a href='http://daltonmatos.wordpress.com/tag/server/'>server</a>, <a href='http://daltonmatos.wordpress.com/tag/wsgid/'>wsgid</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/621/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/621/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/621/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=621&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2012/01/07/how-to-configure-wsgid-and-mongrel2-to-handle-arbitrary-sized-requests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>Deploying your django application with mongrel2 and wsgid</title>
		<link>http://daltonmatos.wordpress.com/2011/11/06/deploying-your-django-application-with-mongrel2-and-wsgid/</link>
		<comments>http://daltonmatos.wordpress.com/2011/11/06/deploying-your-django-application-with-mongrel2-and-wsgid/#comments</comments>
		<pubDate>Sun, 06 Nov 2011 21:10:20 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[mongrel2]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[wsgid]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=546</guid>
		<description><![CDATA[Some time ago when people talked about webapp deployment they were probably talking about the LAMP stack. Since the appearance of the nginx webserver this has changed quite a bit. In this post you will know another stack, that does not use neither apache nor nginx but that is equally interesting and quite scalable too. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=546&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Some time ago when people talked about webapp deployment they were probably talking about the LAMP stack. Since the appearance of the nginx webserver this has changed quite a bit. In this post you will know another stack, that does not use neither apache nor nginx but that is equally interesting and quite scalable too. We will be talking about <a title="Mongrel2 official website" href="http://mongrel2.org" target="_blank">mongrel2</a> for the frontend and <a title="Wsgid official website" href="http://wsgid.com" target="_blank">wsgid</a> for the backend worker processes.</p>
<h2>TL;DR</h2>
<p>In this post you will learn how to configure <a title="Mongrel2 official website" href="http://mongrel2.org" target="_blank">mongrel2</a> and <a title="Wsgid official website" href="http://wsgid.com" target="_blank">wsgid</a> to run your WSGI appalication. If you are interested in web servers, web application deployment and system administration, read on!</p>
<p style="text-align:justify;"><span id="more-546"></span></p>
<h2>Mongrel2</h2>
<p style="text-align:justify;">Mongrel2 is a different webserver. At least different from all web servers I&#8217;ve seen until I found it. This difference stands on the fact that mongrel2 is language agnostic, that is, it does not matter in which language your application is written. You will understand why very soon, keep reading!</p>
<p style="text-align:justify;">Mongrel2 decouples application from web server in a very simple yet powerful and intelligent way. It uses a high performance queue to talk to your application. The queue used here is <a title="ZeroMQ official website" href="http://zeromq.org" target="_blank">zeromq</a>. So everything your applications needs to have mongrel2 as its front-end is to know how to <em>speak zeromq.</em> Fortunately there are already <a title="Current ZeroMQ available bindings" href="http://www.zeromq.org/bindings:_start" target="_blank">30+ zeromq bindings</a>, so if your language of choice has a zeromq binding you are ready to plug your app into mongrel2 infrastructure.</p>
<p style="text-align:justify;">This decoupling means that your app and mongrel2 runs on different operating system processes, in fact nothing forbids them to run of <strong>different machines</strong>. To accomplish this mongrel2 uses a pair of sockets to communicate to back-end handlers. These are two zeromq sockets: One to push messages to back-end handlers and another to get the responses. And why is this great? Because the zeromq socket (PUSH/PULL) mongrel2 uses to push messages comes for free with round robin load balancing, this means that if you have 32 connected handlers to this socket each one of them will receive one message at a time in a round robin fashion. Cool, isn&#8217;t it?</p>
<p style="text-align:justify;">Another big advantage of this <em>load balancing</em> is that it&#8217;s different from other load balancing setups and I will explain why. Usually when we see a load balancing setup, it uses the proxy technique. That&#8217;s nothing wrong with it, but one thing that you must know beforehand is the IP:PORT of all your back-end servers, the servers that you will proxy requests to. It happens like this: The front-end receives a new request, connects to one of the back-end proxies and delivers the just received request. If you want to add a new back-end server, you need to edit your front-end config, introduce this new server to it and tell your front-end to reload.</p>
<p style="text-align:justify;">With mongrel2 you <strong>don&#8217;t need</strong> to do this, yes you don&#8217;t. That&#8217;s because of how zeromq works. What mongrel2 does is: It opens one zeromq PUSH socket on localhost (This is chosen on mongrel2 configuration, more on this later) and here is the magic: The back-end workers are the ones who connects to this socket. So who needs to know where to connect is the back-end handler, not the front-end! See? Because of this sort of <em>inversion</em> you can add/remove new handlers without mongrel2 even knowing you did it, without touching any config files and the best: without the need to restart/reload mongrel2 config values. This  was the functionality that blew my mind, by the way.</p>
<p style="text-align:justify;">You may be thinking: &#8220;Alright, so I have to write my own mongrel2 handler to run my apps on it?&#8221; The answer is Yes and No. If you are interested on running python WSGI applications with mongrel2 you won&#8217;t have to write a handler, in fact your WSGI app won&#8217;t even need to know it is running with mongrel2. That&#8217;s when wsgid comes in to rescue you (more on this later), it is the bridge between mongrel2 and your WSGI app.</p>
<p style="text-align:justify;">So let&#8217;s see how to configure our mongrel2 instance and then we will see how to use wsgid to run our web app.</p>
<h3>Configuration <em>files</em></h3>
<p style="text-align:justify;">I said <em>files</em> because mongrel2 reads its configuration from a database. Yes, from a database! Breathe&#8230;., still with me? Alright! At first you may think: &#8220;What? From a database? WTF!? This is crazy!&#8221;. But when you think clearly you start to see some advantages, and the most important is that it becomes <strong>absolutelly easy</strong> to change any config you want, and to do this all you need is a sqlite client. Even better, you can build your own tool to manage this config database yourself (no need to write nay kind of file parser). Note: Mongrel2 already have internal infrastructure to be able to load its config values from <em>anywhere</em>, see more at this <a title="Mongrel 1.7 release notes" href="http://sheddingbikes.com/posts/1307388904.html" target="_blank">blog post</a>.</p>
<p style="text-align:justify;">One disadvantage that probably you thought about was: &#8220;It is very non optimal to read config values from a database&#8221;, and you are not completely wrong here, but there is one thing that changes it all: Mongrel2 does not keep reading the database during its run. It reads the configs only when starting up, so what you end up with is <em>one read from the database</em> against <em>one read/parse from the config files</em>. Maybe some additional milliseconds to read the database, but honestly, not that bad, right? Also mongrel2 has a <em>hot reload</em> functionality, you just <em>SIGHUP</em> it and all config values will be reloaded on the next request.</p>
<h2 style="text-align:justify;">Installing mongrel2</h2>
<p>Installing is pretty usual, as awlays it&#8217;s a matter of:</p>
<pre>$ make
# make install</pre>
<p>If you happen do use Gentoo linux, there is an overlay that conatins mongrel2 ebuilds, It&#8217;s here: <a href="https://github.com/daltonmatos/gentoo-overlay">https://github.com/daltonmatos/gentoo-overlay</a>. Just add it to your Gentoo installation and you will be able to do an <em>emerge mongrel2</em> to install it. If you are installing manually remember to install also zeromq and sqlite3.</p>
<h2>Configuring mongrel2</h2>
<p>As said before, mongrel2 uses a database to store its configurations. So we need a database schema to start with. Mongrel2 ships with a tool names <em>m2sh</em> that can build your database schema for the first time. There are some example config files that m2sh understands inside mongrel2 source code, they are inside examples/configs. All you have to do is:</p>
<pre>$ m2sh load -config &lt;your-config-file.conf&gt;</pre>
<p>this will build a file named <em>config.sqlite.</em> That&#8217;s your database! Rather than learning the syntax that m2sh understands (because if we work with the files that m2sh understands, we will lose all the advantages of having a database as a source of our settings) we will focus on the database it creates for us. You not always need <em>m2sh</em>, mongrel2 comes with one SQL file that re-creates the schema for you, it&#8217;s the src/config/config.sql and can be seen here: <a href="https://github.com/zedshaw/mongrel2/blob/master/src/config/config.sql">https://github.com/zedshaw/mongrel2/blob/master/src/config/config.sql</a>. So let&#8217;s see what do we get with <em>m2sh load</em> command:</p>
<pre>$ sqlite3 config.sqlite
SQLite version 3.7.7.1 2011-06-28 17:39:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite&gt; .tables
directory  host       mimetype   route      setting
handler    log        proxy      server     statistic
sqlite&gt;</pre>
<p>So here are the tables mongrel2 needs to store all your configuration. The tables we will see are:</p>
<ul>
<li>server &#8211; Stores all servers we have, here we have the port that this server is listening to;</li>
<li>host &#8211; Here are all <em>virtual hosts</em>, each host is <em>attached</em> to one server;</li>
<li>route &#8211; Here are our routes, each route is <em>attached</em> to one host and to one <em>target</em> (more on this later) that can be a handler, proxy or directory;</li>
<li>handler &#8211; Here we define our backends;</li>
<li>directory &#8211; Here are all our directories that contains static data.</li>
</ul>
<h3>The server table</h3>
<p>Here is the schema of this table:</p>
<pre>sqlite&gt; .schema server
CREATE TABLE server (id INTEGER PRIMARY KEY,
    uuid TEXT,
    access_log TEXT,
    error_log TEXT,
    chroot TEXT DEFAULT '/var/www',
    pid_file TEXT,
    default_host TEXT,
    name TEXT DEFAULT '',
    bind_addr TEXT DEFAULT "0.0.0.0",
    port INTEGER,
    use_ssl INTEGER default 0);
sqlite&gt;</pre>
<p>And here is some data from my personal deployment:</p>
<pre>sqlite&gt; select * from server;
          id = 1
        uuid = f400bf85-4538-4f7a-8908-67e313d515c2
  access_log = /logs/access.log
   error_log = /logs/error.log
      chroot = /var/mongrel2
    pid_File = /run/mongrel2.pid
        name = mainserver
   bind_addr = 0.0.0.0
        port = 80
     use_ssl = 0
default_host = wsgid.com
sqlite&gt;</pre>
<p><em>I used one value per line for clarity.</em> So here we have one typical server deployed on port 80. One important thing to see here is the <em>chroot</em> field. Mongrel2 always chroots to one specified location before start serving requests. All paths at the <em>directory</em> table will be relative to this path, for example.</p>
<h3>The host table</h3>
<p>Here is the schema:</p>
<pre>sqlite&gt; .schema host
CREATE TABLE host (id INTEGER PRIMARY KEY,
    server_id INTEGER,
    maintenance BOOLEAN DEFAULT 0,
    name TEXT,
    matching TEXT);
sqlite&gt;</pre>
<p>The important parts are:  server_id is the server that this host belongs to. The <em>name</em> is just a name for this host, you use this value to refer tho this host inside you configuration. The <em>matching</em> field is what mongrel2 uses to match the <em>Host</em> header of the HTTP request. You can use some regular expression here, see more at <a title="Host and Route pattern matching" href="http://mongrel2.org/static/mongrel2-manual.html#x1-350003.6" target="_blank">mongrel2 docs</a>.</p>
<p>Here are some data of my same deploy cited above:</p>
<pre>sqlite&gt; select * from host where name in ('daltonmatos.com', 'wsgid.com');
         id = 4
  server_id = 1
maintenance = 0
       name = wsgid.com
   matching = wsgid.com

         id = 6
  server_id = 1
maintenance = 0
       name = daltonmatos.com
   matching = daltonmatos.com
sqlite&gt;</pre>
<p>Here we have two deployed hosts. Until here mongrel2 is not useufl yet, because we are not serving any content. Now we start to configure our backends.</p>
<h3>The route table</h3>
<p>Here is the schema:</p>
<pre>sqlite&gt; .schema route
CREATE TABLE route (id INTEGER PRIMARY KEY,
    path TEXT,
    reversed BOOLEAN DEFAULT 0,
    host_id INTEGER,
    target_id INTEGER,
    target_type TEXT);
sqlite&gt;</pre>
<p>Here we put all routes we want mongrel2 to respond to and attach them either to a handler, proxy or directory. In this post we will see only handler and directory backends. Here is some real data:</p>
<pre>sqlite&gt; select * from route where host_id = 6;
         id = 12
       path = /static
   reversed = 0
    host_id = 6
  target_id = 5
target_type = dir

         id = 13
       path = /
   reversed = 0
    host_id = 6
  target_id = 2
target_type = handler
</pre>
<p>These two routes are attached to my personal website host: <a title="My personal website" href="http://daltonmatos.com" target="_blank">daltonmatos.com</a>, and are respectively for the static content and for the main application (it&#8217;s a Django app). So let&#8217;s see how we configure our handlers:</p>
<h3>The directory table, for static serving</h3>
<p>Here is the schema:</p>
<pre>sqlite&gt; .schema directory
CREATE TABLE directory (id INTEGER PRIMARY KEY,
   base TEXT,   
   index_file TEXT,
   default_ctype TEXT,
   cache_ttl INTEGER DEFAULT 0);
sqlite&gt;</pre>
<p>And here is some real data from my deploy:</p>
<pre>sqlite&gt; select * from directory where id = 5;
           id = 5
         base = apps/daltonmatos.com/app/daltonmatosdotcom/static/
   index_file = index.html
default_ctype = text/html
    cache_ttl = 0
sqlite&gt;</pre>
<p>This is the <em>target</em> that the <em>/static</em> route is attached to. Remember the <em>base</em> path is always relative to the <em>chroot</em> path you choosed when creating your servers. Now, the final part where we present our application handlers to mongrel2</p>
<h3>The handler table</h3>
<p>Here is the schema:</p>
<pre>sqlite&gt; .schema handler
CREATE TABLE handler (id INTEGER PRIMARY KEY,
    send_spec TEXT, 
    send_ident TEXT,
    recv_spec TEXT,
    recv_ident TEXT,
   raw_payload INTEGER DEFAULT 0, protocol TEXT default 'json');
sqlite&gt;</pre>
<p>And the data for the daltonmatos.com host:</p>
<pre>sqlite&gt; select * from handler where id = 2;
         id = 2
  send_spec = tcp://127.0.0.1:5002
 send_ident = 35353f12-6a2a-11e0-b898-001fe149503a
  recv_spec = tcp://127.0.0.1:5003
 recv_ident = 35ad3ab2-6a2a-11e0-b898-001fe149503a
raw_payload = 0
   protocol = json
sqlite&gt;</pre>
<p style="text-align:justify;">So here is the magic behind mongrel2. See these two IP:PORT configs? So these are the two sockets I talked about earlier at the beginning of this post. The <em>send_spec</em> is the socket used by mongrel2 to dispatch messages to the handlers. The <em>recv_spec</em> is the socket used to receive the responses.</p>
<p style="text-align:justify;">Here is how mongrel2 decouples from you application. Since it talks to your app across the network, it does not matter in which language you write you apps, as long as your app speaks <em><a title="Mongrel2 internal protocol specification" href="http://mongrel2.org/static/mongrel2-manual.html#x1-710005.3" target="_blank">mongrel2 protocol language</a></em>. And thats where wsgid enters the story. Lucky you, none of your already written django apps need to know about mongrel2 protocol because wsgid speaks both <em>mongrel2 protocol</em> and <em> WSGI</em>. Let&#8217;s see how we can use wsgid to run ou apps with mongrel2 as the frontend.</p>
<p style="text-align:justify;">So long story short, every request that comes to the root of daltonmatos.com, mongrel2 parses the HTTP requests and dispatches it to this <em>send_spec</em> socket, and from here on until the response comes back, is <a title="ZeroMQ official website" href="http://zeromq.org" target="_blank">zeromq</a> machinery. To know more about how mongrel2 handles this two sockets you can go to the <a title="Mongrel2 manual" href="http://mongrel2.org/static/mongrel2-manual.html" target="_blank">official docs</a>.</p>
<h2 style="text-align:justify;">Starting your server</h2>
<p style="text-align:justify;">Now all you have to do is call mongrel2 on the command line to start it up. Since we may have multiple server on the same database config we must choose which server we will start and we do this passing the <em>uuid</em> of your sever on the command line , like this:</p>
<pre># mongrel2 &lt;config.sqlite&gt; &lt;uuid&gt;</pre>
<p style="text-align:justify;">This will start the server with uuid = &lt;uuid&gt;, reading from the config database passed as the first argument. From now on mongrel2 is ready to receive requests. Now it&#8217;s time to see how wsgid helps us on running our django app.</p>
<h2>wsgid</h2>
<p>Now that you know about mongrel2 handlers and all that, you can see wsgid as a generic WSGI handler for mongrel2 applications. With it you can run any WSGI app having mongrel2 as the front-end, and here is how we do it.</p>
<h2>Installing Wsgid</h2>
<p>You can install wsgid downloading it from the official website: <a title="Wsgid official website" href="http://wsgid.com" target="_blank">http://wsgid.com</a>. After downloading, extract it to one location of your choice and run:</p>
<pre># python setup.py install</pre>
<p>from inside this folder. To check your instalation, you can run:</p>
<pre>$ wsgid --version</pre>
<p>and you should see the current installed version.</p>
<h2>Creating a wsgid app folder</h2>
<p>Since wsgid runs your app as a *nix daemon, it needs a special location with some specific folders inside. Let&#8217;s call it <em>application folder (app folder)</em>. There is where you will put the source-code of you Django app. To create a new app folder you can run:</p>
<pre>$ wsgid init --app-path=/path/to/my/app/folder</pre>
<p>Wsgid will create this folder if it does not exists and initialize all needed sub folders for you. In this example, let&#8217;s use /tmp/myapp. So an initialized folder looks like this:</p>
<pre>daltonmatos@jetta /tmp/myapp [13]$ ls
app  logs  pid
daltonmatos@jetta /tmp/myapp [14]$</pre>
<h2>Deploying you Django app</h2>
<p>All our app source-code lives inside the <em>app/</em> folder. So we just need to cd to <em>/tmp/myapp/app</em> and create our brand new django project:</p>
<pre>daltonmatos@jetta /tmp/myapp/app [16]$ django-admin.py startproject myproj
daltonmatos@jetta /tmp/myapp/app [17]$ ls
myproj
daltonmatos@jetta /tmp/myapp/app [18]$</pre>
<p>Ok, so this is a common django project. Of course that when deploying your already written django project you will just copy the project folder to this location, it will have the very same effect.</p>
<h2>Starting wsgid instance to run your django app</h2>
<p>Now it&#8217;s time to start wsgid so we can send requests to our app. Remember that two sockets we saw earlier on this post? Remember that the back-end handler is who needs to know where to connetc? Here is how we do it.</p>
<p>Let&#8217;s use the same handlers we saw earlier:</p>
<ul>
<li>send_spec = tcp://127.0.0.1:5002</li>
<li>recv_spec = tcp://127.0.0.1:5003</li>
</ul>
<p>So here is how we pass this to wsgid:</p>
<pre>$ wsgid --app-path=/tmp/myapp --recv=tcp://127.0.0.1:5002 --send=tcp://127.0.0.1:5003 --workers=4</pre>
<p>Now we have one instance of wsgid running and calling our django app when a new request arrives. You can confirm that wsgid started successfully looking at the logs:</p>
<pre>$ tail -f /tmp/myapp/logs/wsgid.log
<span class="Apple-style-span" style="font-family:Consolas, Monaco, monospace;font-size:12px;line-height:18px;white-space:pre;">2011-11-06 18:06:56,115 - wsgid [pid=27900] - INFO - Master process started</span>
<span class="Apple-style-span" style="font-family:Consolas, Monaco, monospace;font-size:12px;line-height:18px;white-space:pre;">2011-11-06 18:06:56,116 - wsgid [pid=27900] - INFO - New wsgid worker created pid=27903</span>
2011-11-06 18:06:56,117 - wsgid [pid=27900] - INFO - New wsgid worker created pid=27904
2011-11-06 18:06:56,118 - wsgid [pid=27900] - INFO - New wsgid worker created pid=27905
2011-11-06 18:06:56,119 - wsgid [pid=27900] - INFO - New wsgid worker created pid=27906
2011-11-06 18:06:56,145 - wsgid [pid=27903] - INFO - Using AppLoader: DjangoAppLoader
2011-11-06 18:06:56,145 - wsgid [pid=27904] - INFO - Using AppLoader: DjangoAppLoader
2011-11-06 18:06:56,150 - wsgid [pid=27905] - INFO - Using AppLoader: DjangoAppLoader
2011-11-06 18:06:56,168 - wsgid [pid=27906] - INFO - Using AppLoader: DjangoAppLoader
2011-11-06 18:06:56,223 - wsgid [pid=27903] - INFO - All set, ready to serve requests...
2011-11-06 18:06:56,228 - wsgid [pid=27904] - INFO - All set, ready to serve requests...
2011-11-06 18:06:56,231 - wsgid [pid=27905] - INFO - All set, ready to serve requests...
2011-11-06 18:06:56,238 - wsgid [pid=27906] - INFO - All set, ready to serve requests...</pre>
<p>Wsgid automatically detects what kind of application it is loading and uses the appropriately AppLoader. Considering that you have a localhost registered on your host table, just hit <em>http://localhost</em> in your browser and see your running Django application.</p>
<pre>daltonmatos@jetta ~ [2]$ curl -i http://localhost/
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 2051

daltonmatos@jetta ~ [3]$</pre>
<p>To know more about wsgid command line options, try <em>wsgid &#8211;help</em>.</p>
<h2>Using wsgid config  files</h2>
<p>You don&#8217;t need to call a complete command line, full of arguments every time you want to start a new wsgid instance. You can tell wsgid to create a simple JSON config file inside your app folder. Just add <em>config</em> as the first command line argument:</p>
<pre>$ wsgid config --app-path=/tmp/myapp --recv=tcp://127.0.0.1:5002 --send=tcp://127.0.0.1:5003 --workers=4</pre>
<p>Wsgid now created a <em>/tmp/myapp/wsgid.json</em> file with all these options:</p>
<pre>daltonmatos@jetta /tmp/myapp [41]$ cat wsgid.json
{
  "debug": "False",
  "workers": 4,
  "keep_alive": "True",
  "recv": "tcp://127.0.0.1:5002",
  "send": "tcp://127.0.0.1:5003"
}
daltonmatos@jetta /tmp/myapp [42]$</pre>
<p style="text-align:justify;">From now on you can start this same instance just with <em>wsgid &#8211;app-path=/tmp/myapp</em>. If you want to change any value inside the config file just re-run the command with the new values and wsgid will update the config file accordingly.</p>
<p>Now if you want to run more instances of you app on different machines (considering that you have a copy of your app there) all you have to do is to access that machine a run:</p>
<pre>$ wsgid --app-path=/tmp/myapp --recv=tcp://MONGREL2_IP:5002 --send=tcp://MONGREL2_IP:5003 --workers=4</pre>
<p>And you are done! No need to tell mongrel2 about it. Just run this and you will have 4 more processes added to the zeromq round robin load balancing logic.</p>
<p>Wsgid has others usfeul command line options, such as: <em>wsgid reload</em> to reload your app code on the fly, <em>wsgid status</em> to show you the PID number of all your processes and many more. See all of them ad the official docs: <a title="Wsgid official docs" href="http://wsgid.com/docs" target="_blank">http://wsgid.com/docs</a>.</p>
<h2>Final words</h2>
<p style="text-align:justify;">So what you just saw here is another way to deploy and scale your app. There is nothing brand new here, just a known technique applied with smart tools to make your life a lot easier! I&#8217;ve been using this setup for a couple of months now and I can say that I&#8217;m absolutely happy with it. I even ran a <a title="Blitz.io invite link" href="http://blitz.io/gcbEjuJz2eNac" target="_blank">blitz.io</a> (this is my blitz.io invite link) rush against wsgid.com and mongrel2+wsgid handled all requests pretty well!</p>
<p style="text-align:justify;">So let me know what you think! Give this setup a try and share your thoughts. What can we do the make it even better?</p>
<p style="text-align:justify;">Thanks for reading!</p>
<pre></pre>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/django/'>django</a>, <a href='http://daltonmatos.wordpress.com/tag/mongrel2/'>mongrel2</a>, <a href='http://daltonmatos.wordpress.com/tag/python/'>python</a>, <a href='http://daltonmatos.wordpress.com/tag/wsgid/'>wsgid</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/546/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/546/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/546/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=546&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/11/06/deploying-your-django-application-with-mongrel2-and-wsgid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>How I&#8217;m planning to test one of my projects by writing another one</title>
		<link>http://daltonmatos.wordpress.com/2011/10/16/how-im-planning-to-test-one-of-my-projects-writing-another-one/</link>
		<comments>http://daltonmatos.wordpress.com/2011/10/16/how-im-planning-to-test-one-of-my-projects-writing-another-one/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 21:23:46 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Projetos]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[projects]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=585</guid>
		<description><![CDATA[The purpose Some time ago, I started writing wsgid. It is a project that brings to you the ability to run any WSGI application with mongrel2 web server. Some time ago I had this idea of writing a web application that could help me test wsgid on a real production environment. Both wsgid&#8217; official website [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=585&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2 style="text-align:justify;">The purpose</h2>
<p style="text-align:justify;">Some time ago, I started writing <a title="Wsgid Official Website" href="http://wsgid.com" target="_blank">wsgid</a>. It is a project that brings to you the ability to run any WSGI application with <a title="Mongrel2 Official Website" href="http://mongrel2.org" target="_blank">mongrel2</a> web server. Some time ago I had this idea of writing a web application that could help me test wsgid on a real production environment. Both <a title="Wsgid Official Website" href="http://wsgid.com" target="_blank">wsgid&#8217; official website</a> and <a title="daltonmatos.com" href="http://daltonmatos.com" target="_blank">my personal website</a> are hosted using wsgid and mongrel2 as the backend, but none of them even uses a database (and maybe won&#8217;t for a long time) and since they are very simple and low traffic websites, I think they aren&#8217;t good enough to test wsgid.</p>
<p style="text-align:justify;"><span class="Apple-style-span">I thought about some type of applications that would be better to test wsgid and end up with the decision to write my own blog engine. This same engine will soon power my own blog, self hosted and managed by me.</span></p>
<h2>Wait, another blog engine? Why?</h2>
<p style="text-align:justify;">Yes, it will be a blog engine, another one! =) Before you think about <a title="Not Invented Here" href="http://en.wikipedia.org/wiki/Not_Invented_Here" target="_blank">NIH</a>, I will try to explain why I decided to start this project. The very first thing I did when I thought about writing one more blog engine was to find some existing ones. But it could not be any blog engine, they must obey some rules:</p>
<ul>
<li style="text-align:justify;">Written in python</li>
<li>Used a WSGI framework</li>
<li>Bonus points for engines written in Django</li>
</ul>
<p style="text-align:justify;">These rules are obvious. If I&#8217;m trying to test wsgid (that is a WSGI gateway) the application must be written in Python and be compliant to the WSGI specification. The last one was a bonus point because I&#8217;m currently learning Django. I found that are there plenty of Django blog engines, but one decision made me not choose any of them: I want to learn something new, and I think the best way to do this is having a project. And not any one, but one that you will really use. And writing the code of my own blog is a good way to maintain the project alive, evolving and getting better and better.</p>
<p style="text-align:justify;">Another point that helped me on this decision was the willing to self host my applications. This will give me very important knowledge and experience on system administration, servers, deployment, clusters and may more. Recently I had <a title="The importance to share your knowledge and your projects" href="http://daltonmatos.wordpress.com/2011/09/25/the-importance-to-share-your-knowledge-and-your-projects/" target="_blank">two amazing opportunities</a> to work with these topics and I&#8217;m sure that if I were already managing my own infra-structure for a while I could have done much better on these two interviews.</p>
<p>Until the day of witting this blog post, my blog is still hosted on wordpress.com. I  plan to migrate to my own servers as soon as this new project becomes minimally usable. This will be good for many reasons that I already said and one more is that I will be able to have my own domain name and not pay any more money for this, since I already own <a href="http://daltonmatos.com" target="_blank">daltonmatos.com</a>.</p>
<div><span class="Apple-style-span" style="font-size:20px;font-weight:bold;">Wish me luck</span></div>
<p style="text-align:justify;">Starting a new project is always a great responsibility, first with yourself, second with the people that follow your projects and more important: with who uses your project. So today I decided to start this new project: The blog engine. It has no name yet, the only certainty is that I will create this project and host my own blog. The code will be hosted on github, where I publish all my codes. So if you are intersted <a title="Dalton Matos Github profile" href="https://github.com/daltonmatos" target="_blank">follow me there</a> and stay tuned!</p>
<p style="text-align:justify;">Thank you for reading!</p>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/django/'>django</a>, <a href='http://daltonmatos.wordpress.com/tag/projects-2/'>projects</a>, <a href='http://daltonmatos.wordpress.com/tag/python/'>python</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/585/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/585/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/585/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=585&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/10/16/how-im-planning-to-test-one-of-my-projects-writing-another-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>The importance to share your knowledge and your projects</title>
		<link>http://daltonmatos.wordpress.com/2011/09/25/the-importance-to-share-your-knowledge-and-your-projects/</link>
		<comments>http://daltonmatos.wordpress.com/2011/09/25/the-importance-to-share-your-knowledge-and-your-projects/#comments</comments>
		<pubDate>Mon, 26 Sep 2011 02:41:44 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Projetos]]></category>
		<category><![CDATA[career]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[sharing]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=561</guid>
		<description><![CDATA[In this post I will talk about how important is to me to have side projects. And how these same projects gave me some considerable visibility to other developers and also to big tech companies. I talk also about what I learned after being part of the hiring process of Google and Facebook, both opportunities [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=561&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">In this post I will talk about how important is to me to have side projects. And how these same projects gave me some considerable visibility to other developers and also to big tech companies. I talk also about what I learned after being part of the hiring process of Google and Facebook, both opportunities thanks to my projects and my publishing.</p>
<p><span class="Apple-style-span" style="font-size:20px;font-weight:bold;">Visibility</span></p>
<p style="text-align:justify;">Sometimes you just want to learn something new, and one of the greatest ways to do this is having a project. You don&#8217;t need to have a project that is used by many people. That&#8217;s not what measures whether a project is good or not, a project is good when <strong>you</strong> care about it. More important, a project is really good when <strong>you</strong> learn something useful during its development.</p>
<p style="text-align:justify;">Other than that, your project can be your showcase, so use it also to show others what you are capable of doing. There are other ways to show yourself to the world, and one of them is be part of the community around someone else&#8217;s project. But you can&#8217;t just choose a random project, the project must be important to you, either because you are interested or because you use it to solve an important problem. And remember, always give valuable feed backs, don&#8217;t just make noise. If you have nothing to say, so just don&#8217;t say it.</p>
<h2>First, the Projects</h2>
<p style="text-align:justify;">I always try to convince who is near me that having side projects are a great idea! I&#8217;m always trying  to help my friends with their projects, sending patches, doing pair programming or whatever I can do to help. Until 1 year ago I didn&#8217;t have any side project, but not because I didn&#8217;t want to, it was just because none of them were such a big deal. And then when I started to study python I saw the first opportunity to have one project. At that time I was deploying a <a title="Trac official website" href="http://trac.edgewall.org" target="_blank">Trac</a> instance and because of this I started to read its source-code. When I realized how amazing Trac&#8217;s internal component management was I decided to create my first project, and then <a title="PlugnPlay github project page" href="https://github.com/daltonmatos/plugnplay" target="_blank">plugnplay</a> was born. This project gave me the knowledge about the python language and at this time I already had chosen python as my language of choice.</p>
<p style="text-align:justify;">The idea for the second one came when I found out about another project named <a title="Mongrel2 official project" href="http://mongrel2.org" target="_blank">mongrel2</a>. Actually I don&#8217;t remember how I came across mongrel2, but as soon as I realized that it lacked python support, added the fact that I had just chosen python as my language, I decided to start <a title="Wsgid official website" href="http://wsgid.com" target="_blank">wsgid</a>. Wsgid provides WSGI support for mongrel2. As I wanted this project to be more presentable I also bought a domain name (wsgid.com) and made an official website (that runs using wsgid itself!). Over time, wsgid earned its place on mongrel2 official site, where it shows all <a title="Mongrel2 supported languages" href="http://mongrel2.org/features/languages.html" target="_blank">supported languages</a>. This was, with no doubt, a big move for the project and gave me even more motivation to move further.</p>
<h2>The first contact, Google</h2>
<p style="text-align:justify;">So there I was, developing my projects as always when suddenly I see in my inbox an email from a <em>@google.com</em> address. At that exact moment I thought: &#8220;Ok, Gmail spam filter has failed. Let me mark this and go on with my life.&#8221; But then I decided to just do a little research about that message. I looked at the original communication between the smtp servers, and all that seemed real. The email talked about my contributions to the open source community and my blog, and the recruiter was asking if I was interested in a full-time opportunity at Google.</p>
<p style="text-align:justify;">So I decided to reply to that message and two things could happen. Or I would be eternally without response, and then I would confirm that it was spam. Or I would receive another response and realize that is was real! And that&#8217;s what happened. I was absolutely happy and proud to know that Google was offering me the opportunity to be part of its hiring process.</p>
<p style="text-align:justify;">This was January this year, and then I started chatting with the recruiter. I had two phone calls. The first was not technical, was just to know a bit more about me, my background, my time in college, my current work and some other things. After this we scheduled the first technical interview. I, obviously, was very nervous before and during the interviews, mainly because all them was made in English, that is not my mother language.</p>
<p style="text-align:justify;">The second phone call (first technical) was ~20min chat with general questions about system administration, network, etc. I tried my best, considering the poor call audio quality. I had to ask the interviewer to repeat several times, some of them he didn&#8217;t. Some weeks later I received another call telling me that we were not moving forward with the process, and so my chances with Google were finished.</p>
<h2>The second, Facebook</h2>
<p style="text-align:justify;">Some weeks ago, around end August, it happened again. And this time was from a Facebook recruiter. Same story, and this time they saw my blog and since one of my projects was server related (wsgid), they contacted me about a full-time sysops position. This time the domain of the sender was unusual to me, it was <em>@fb.com</em>. But a simple DNS query was able to show me that <em>fb.com</em> was in fact controlled by facebook. This made me feel more confident about all that story.</p>
<p style="text-align:justify;">And, again, I decided to accept the challenge. So I started chatting with the recruiter and on the next week I was already with a scheduled phone interview. This first interview was an elimitaory one, just to know if they would continue with the process or stop right there. Again, the audio quality of the call was awful, but different from Google interview, every time I asked the person to repeat the question I was attended. This first call was very quick (~20min) and some of the questions were about protocols, command line tools and system administration in general. I answered right almost all the questions, and then the interviewer finished the call with a compliment. Saying that I was pretty good at Linux. =)</p>
<p style="text-align:justify;">The next week was time for another phone call, this time a non-technical one. The recruiter just wanted to give me valuable tips about the overall process and specifically about the interview that was to come, the first really technical one. And the day has come, I already knew that the interview would be a ~45min call with 2 or 3 problems to be solved. They used <a title="Collabedit.com" href="http://collabedit.com" target="_blank">collabedit.com</a> to see the code I was writing.</p>
<p style="text-align:justify;">During the one week I had to prepare myself, I studied algorithms, data structures, grabbed some problems from programming competitions and solved them. As I was focused on algorithms, during the interview I got stuck trying to solve the problem with an algorithm written in python. The position was to sysops, that is, heavy linux server users with great command line powers. Even though I simply didn&#8217;t try to use bash during the call. After almost 20 min trying to solve this with python code, the call was finished by one of the interviewers and he said that soon they would contact me again. As soon as I hang up the phone, a one-line bash solution came into my mind!</p>
<h2>What I learned about all this?</h2>
<p style="text-align:justify;">Even not being selected on both opportunities, something good comes out of it. When all this ended and I started to think about it, I realized that my simple projects, started mainly to learn something new, went beyond all my expectations! All my projects are published on my personal website: <a title="My personal website" href="http://daltonmatos.com" target="_blank">daltonmatos.com</a>. What all this taught me is that is all the effort put on my own projects, the contributions I made to other projects, all these worth it!</p>
<p style="text-align:justify;">I also realized that big companies are always looking for good developers out there and one of these could be you, the same way these two times it was me.</p>
<h2 style="text-align:justify;">So what can you do about this?</h2>
<p style="text-align:justify;">What I would like you to understand is that whenever you have some code that solves a specific problem for you, publish it! You can be sure that this your solution can be useful for many others. I already saw some friends not publishing their code because of many weird reasons, from &#8220;the code is still too bad, let me evolve it a bit&#8221; to &#8220;This is a super-secret project, somebody will end up stealing my <em>super-coll</em> idea&#8221;. If you also think like this, I hope that the story I just told you changes your mind, at least a little bit!</p>
<p style="text-align:justify;">So go start your projects or publish an already written one!</p>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/career/'>career</a>, <a href='http://daltonmatos.wordpress.com/tag/projects-2/'>projects</a>, <a href='http://daltonmatos.wordpress.com/tag/sharing/'>sharing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/561/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/561/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/561/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=561&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/09/25/the-importance-to-share-your-knowledge-and-your-projects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>Finalmente meu site pessoal está lançado: daltonmatos.com</title>
		<link>http://daltonmatos.wordpress.com/2011/08/21/finalmente-meu-site-pessoal-esta-lancado-daltonmatos-com/</link>
		<comments>http://daltonmatos.wordpress.com/2011/08/21/finalmente-meu-site-pessoal-esta-lancado-daltonmatos-com/#comments</comments>
		<pubDate>Mon, 22 Aug 2011 01:11:43 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Projetos]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[wsgid]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=551</guid>
		<description><![CDATA[&#160; Hoje é um dia muito importante. Finalmente depois de muito tempo consegui lançar meu próprio site. Já tinha comprado o domínio há bastante tempo mas não tinha ainda parado pra escrever os textos e o código do site. O site é uma aplicação django e roda com o auxílio de um projeo meu já [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=551&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p>Hoje é um dia muito importante. Finalmente depois de muito tempo consegui lançar meu próprio site. Já tinha comprado o domínio há bastante tempo mas não tinha ainda parado pra escrever os textos e o código do site.</p>
<p>O site é uma aplicação django e roda com o auxílio de um projeo meu já citado aqui no blog, o <a title="Rodando sua aplicação WSGI como um *nix daemon" href="http://daltonmatos.wordpress.com/2011/04/09/rodando-sua-aplicacao-wsgi-como-um-nix-daemon/">wsgid</a>. Por enquanto o blog continua aqui no wordpress.com mas pretendo migrá-lo pra lá, pois assim terei tudo centralizado. Ainda tenho que encontrar uma blog engine para que possa migrar o blog.</p>
<p>Bem, é isso aí! Vai lá e dá uma olhada: <a title="daltonmatos.com" href="http://daltonmatos.com">http://daltonmatos.com</a></p>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/django/'>django</a>, <a href='http://daltonmatos.wordpress.com/tag/python/'>python</a>, <a href='http://daltonmatos.wordpress.com/tag/wsgid/'>wsgid</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/551/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=551&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/08/21/finalmente-meu-site-pessoal-esta-lancado-daltonmatos-com/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>Gentoo com kernel land 64 bits e user land 32 bits</title>
		<link>http://daltonmatos.wordpress.com/2011/07/09/gentoo-com-kernel-land-64-bits-e-user-land-32-bits/</link>
		<comments>http://daltonmatos.wordpress.com/2011/07/09/gentoo-com-kernel-land-64-bits-e-user-land-32-bits/#comments</comments>
		<pubDate>Sun, 10 Jul 2011 02:03:38 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Dica]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[gentoo]]></category>
		<category><![CDATA[kernel]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=537</guid>
		<description><![CDATA[O problema Recentemente comprei um novo  notebook e por isso tive a oportunidade de instalar um novo S.O do zero, afinal já estava com uma mesma instalação desde 2008 (quando comprei meu primeiro notebook). Até poderia transferir uma instalação de um notebook para o outro, mas daria um trabalho parecido (ou maior) do que instalar novamente. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=537&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>O problema</h2>
<p style="text-align:justify;">Recentemente comprei um novo  notebook e por isso tive a oportunidade de instalar um novo S.O do zero, afinal já estava com uma mesma instalação desde 2008 (quando comprei meu primeiro notebook). Até poderia <em>transferir</em> uma instalação de um notebook para o outro, mas daria um trabalho parecido (ou maior) do que instalar novamente.</p>
<p style="text-align:justify;">Nesse momento surgiu a mesma dúvida de sempre: Instalar a versão 64 bits ou 32 bits? Em 2008 tentei instalar uma versão totalmente 64 bits e tive problemas com plugin do flash, cheguei a ter um firefox 32 bits só para poder ver vídeos usando flash. Pouco tempo depois desisti do sistema 64 bits por esses e outros motivos e acabei instalando 32 bits mesmo.</p>
<p style="text-align:justify;">Dessa vez a mesma dúvida. Achei que 3 anos depois as coisas estariam melhores, mas já de cara tive problemas com o driver de vídeo. A tela simplesmente não dava refresh corretamente. Um <em>ls</em> no terminal não retornava nenhum resultado, a não ser que a janela do terminal fosse movida de lugar, aí sim acontecia o refresh e o resultado do <em>ls</em> (já executado) aparecia. Isso significa que estava simplesmente impossível de usar o sistema.</p>
<p style="text-align:justify;">Percebi que no live-DVD que estava usando, o driver de vídeo funcionava perfeitamente, então comecei a <em>estudar</em> o que o sistema do live-DVD tinha de diferente. Percebi que ele era <em><a title="Kernel space / User space" href="http://en.wikipedia.org/wiki/User_space" target="_blank">userland</a></em> 32 bits, apesar de reconhecer os 4GB do novo notebook. Nesse momento tive a idéia de tentar uma instalação mista: Kernel 64 bits e userland 32 bits.</p>
<h2>Crosscompiling</h2>
<p style="text-align:justify;">O termo crosscompiling é usado quando temos um compilador rodando em um sistema e gerando código para outro. Por exemplo, você tem um notebook (intel x86) e consegue compilar um código em C que roda no seu celular (processador ARM, por exemplo). Mas o crosscompiling não serve apenas para gerar código entre máquinas diferentes, pode ser usado também para gerar código para a mesma máquinas, apenas escolhendo se o resultado será um binário de 32 bits ou 64 bits.</p>
<p style="text-align:justify;">Foi exatamente isso que fiz nesse caso. Para fazer o que estava querendo precisava ter dois compiladores. Primeiro usei o gcc que é instalado no gentoo para compilar um outro gcc, esse último gerando código 64 bits. Ou seja, tenho agora um compilador que roda em um ambiente 32 bits mas que gera código 64 bits. E esse compilador foi gerado por um outro compilador que roda em 32 bits e também gera código 32 bits, entendeu? Ainda comigo? Ok, vamos lá.</p>
<p style="text-align:justify;">Toda a mágica desse processo é feita pelo pacote <em>sys-devel/crossdev</em>, que faz parte da árvore principal do Gentoo. O que esse script faz é construir todo o toolkit necessário para gerar o <em><a title="Cross Compiler, Wikipedia" href="http://en.wikipedia.org/wiki/Cross_compiler" target="_blank">cross compiler</a></em> que precisamos. O que precisamos fazer é muito simples:</p>
<pre># emerge crosdevv
# crossdev -t x86_64-pc-linux-gnu</pre>
<p style="text-align:justify;">E isso é suficiente. Quando vi que realmente funcionava lembrei de 2004, quando ainda estava usando slackware e tive que fazer isso &#8220;na unha<em>&#8220;</em>. Cheguei até a <a href="http://twitter.com/daltonmatos/status/86089112418926592" target="_blank">postar no twitter</a> um agradecimento a quem quer que tenha escrito esse script. Merecido!</p>
<h2>Compilando o novo kernel</h2>
<p style="text-align:justify;">Agora, com tudo pronto, temos dois compiladores: O que gera código 32 bits, que podemos chamar apenas digitando <em>gcc,</em> e o que gera código 64 bits que podemos chamar com o comando <em>x86_64-pc-linux-gnu-gcc</em>. O que temos que fazer agora é configurar nosso kernel para que use o compilador correto. Felizmente alguém já precisou fazer o que estou fazendo e existe uma maneira fácil de escolher o compilador que vai gerar nosso kernel.</p>
<div id="attachment_539" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/07/kernel-option-custom-compiler.png"><img class="size-full wp-image-539" title="Escolhendo compilador customizado para nosso kernel" src="http://daltonmatos.files.wordpress.com/2011/07/kernel-option-custom-compiler.png?w=620&#038;h=400" alt="" width="620" height="400" /></a><p class="wp-caption-text">Escolhendo compilador customizado para nosso kernel</p></div>
<p style="text-align:justify;">Para isso basta irmos ao menu <em>General setup/</em> e escolher o valor correto para a opção <em>Cross-compiler tool prefix.</em> Isso fará com que nosso novo compilador seja usado no momento de compilar nosso kernel. Agora o que temos que fazer é compilar nosso kernel como fazemos normalmente, o de sempre:</p>
<pre># make
# make modules
# make modules_install</pre>
<p style="text-align:justify;">Agora é só copiar nosso novo <em>64 bit kernel</em> para o lugar certo, adicionar uma nova entrada no boot loader e bootar nosso novo kernel. E isso é o que temos depois de um boot com sucesso:</p>
<div id="attachment_540" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/07/kernel64-userland32-4gb.png"><img class="size-full wp-image-540" title="Kernel 64 bits com userland 32 bits" src="http://daltonmatos.files.wordpress.com/2011/07/kernel64-userland32-4gb.png?w=620&#038;h=400" alt="" width="620" height="400" /></a><p class="wp-caption-text">Kernel 64 bits com userland 32 bits</p></div>
<p>Exatamente o que queríamos:</p>
<ul>
<li>Kernel 64 bits (X86_64)</li>
<li>Userland 32 bits (todos os binários são ELF 32-bit)</li>
<li>Os 4 GB RAM corretamente sendo usados</li>
</ul>
<div>Agora tenho o driver de vídeo funcionando perfeitamente, com aceleração 3D e o novo <a title="GNOME3 official website" href="http://gnome3.org/" target="_blank">gnome3</a> rodando sem nenhum problema! Perfeito!</div>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/gentoo/'>gentoo</a>, <a href='http://daltonmatos.wordpress.com/tag/kernel/'>kernel</a>, <a href='http://daltonmatos.wordpress.com/tag/linux/'>Linux</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/537/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/537/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/537/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=537&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/07/09/gentoo-com-kernel-land-64-bits-e-user-land-32-bits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/07/kernel-option-custom-compiler.png" medium="image">
			<media:title type="html">Escolhendo compilador customizado para nosso kernel</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/07/kernel64-userland32-4gb.png" medium="image">
			<media:title type="html">Kernel 64 bits com userland 32 bits</media:title>
		</media:content>
	</item>
		<item>
		<title>Gentoo com partição raiz encriptada</title>
		<link>http://daltonmatos.wordpress.com/2011/06/28/gentoo-com-particao-raiz-encriptada/</link>
		<comments>http://daltonmatos.wordpress.com/2011/06/28/gentoo-com-particao-raiz-encriptada/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 00:31:29 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Dica]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=498</guid>
		<description><![CDATA[A idéia desse post é apenas mostrar o caminho para instalar um Gentoo tendo a partição raiz (e todas as outras) encriptadas. Não é um texto muito detalhado, é para quem já tem costume com a instalação de gentoo. Mas mesmo que você não tenha familiaridade com esta distribuição, pode ler mesmo assim, apenas por [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=498&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">A idéia desse post é apenas mostrar o caminho para instalar um <a title="Gentoo website" href="http://gentoo.org" target="_blank">Gentoo</a> tendo a partição raiz (e todas as outras) encriptadas. Não é um texto muito detalhado, é para quem já tem costume com a instalação de gentoo. Mas mesmo que você não tenha familiaridade com esta distribuição, pode ler mesmo assim, apenas por curiosidade. =)</p>
<p style="text-align:justify;">Um ponto negativo da abordagem que vou apresentar é que fica praticamente impossível recuperar seu laptop com programas como <a title="Prey Project" href="http://preyproject.com/" target="_blank">preyproject</a>. A idéia nesse caso é proteger seus dados, não o aparelho. Esse último, bem ou mal, pode-se juntar dinheiro (mesmo que por muito tempo) e comprar outro, mas seus dados pessoais em mãos erradas, pode ser fatal. Lembrem-se sempre de manter seus backups atualizados. Bem, chega de papo e vamos ao que interessa.</p>
<h1 style="text-align:justify;">Preparando as partições</h1>
<p style="text-align:justify;">Antes de começar a instalação, precisamos particionar nosso disco de forma correta. Repare que o que teremos encriptado será somente a partição raiz onde o S.O estará inslatado, tudo bem que isso corresponderá a quase 100% do disco, mas precisamos dexar claro que uma pequena parte do disco permanecerá sem encriptação, e você entenderá porque mais a frente.</p>
<p style="text-align:justify;">Essas são as partções originais do notebook onde fiz essa instalação:</p>
<div id="attachment_505" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/00-particoes-originais.png"><img class="size-full wp-image-505" title="Particoes originais" src="http://daltonmatos.files.wordpress.com/2011/06/00-particoes-originais.png?w=620&#038;h=375" alt="" width="620" height="375" /></a><p class="wp-caption-text">Particoes originais</p></div>
<p>Preciasmos, basciamente, criar duas partições:</p>
<ul>
<li>Uma onde guardaremos as imagens dos kernels que vamos usar (/boot, 256MB)</li>
<li>Outra contendo o restande do disco, onde o S.O estará instalado</li>
</ul>
<p style="text-align:justify;">O motivo pelo qual temos que ter essa partição não encriptada é que nosso boot loader (grub) não é capaz de ler uma partição que esteja encriptada, se isso fosse possível poderíamos encriptar 100% do disco, inclusive a partição onde estão os kernels. Feito isso, nosso disco agora tem apenas duas partições:</p>
<div id="attachment_510" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/03-novas-particoes-criadas.png"><img class="size-full wp-image-510 " title="Novas particoes criadas" src="http://daltonmatos.files.wordpress.com/2011/06/03-novas-particoes-criadas.png?w=620&#038;h=375" alt="" width="620" height="375" /></a><p class="wp-caption-text">Novas particoes criadas</p></div>
<h1>Encriptando a partição principal</h1>
<p>Agora o que precisamos fazer é efetivamente encriptar a partição onde vamos instalar o gentoo, para isso usaremos o cryptsetup:</p>
<div id="attachment_512" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/05-formatando-com-cryptsetup-luksformat.png"><img class="size-full wp-image-512" title="Formatando com cryptsetup luksformat" src="http://daltonmatos.files.wordpress.com/2011/06/05-formatando-com-cryptsetup-luksformat.png?w=620&#038;h=375" alt="" width="620" height="375" /></a><p class="wp-caption-text">Formatando com cryptsetup luksformat</p></div>
<p>Agora temos que fazer com que essa partição encriptada fique disponível como um <em>block device</em>.</p>
<div id="attachment_513" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/06-destravando-crypt-root.png"><img class="size-full wp-image-513" title="Destravando crypt root" src="http://daltonmatos.files.wordpress.com/2011/06/06-destravando-crypt-root.png?w=620&#038;h=375" alt="" width="620" height="375" /></a><p class="wp-caption-text">Destravando crypt root</p></div>
<p>A partir desse momento já poderíamos formatar esse <em>block device</em> (mke2fs -j), mas como vamos usar LVM2 em cima da encriptação, precisamos fazer mais algumas coisas antes de começar a instalação. O comando acima cria um <em>block device</em> em /dev/mapper/crypt-root.</p>
<h1>Configurando o LVM2</h1>
<p>Agora que já temos toda a partição encripada é hora de configurar o <a title="LVM2" href="http://sourceware.org/lvm2/" target="_blank">LVM2</a>. Vamos criar apenas um volume físico (physical volume) que ocupará toda a partição que acabamos de encriptar. Depois criaremos um <em>Volume Group</em> e dois <em>Logical Volumes</em>.</p>
<div id="attachment_514" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/07-criando-volumes-lvm2.png"><img class="size-full wp-image-514" title="Criando volumes lvm2" src="http://daltonmatos.files.wordpress.com/2011/06/07-criando-volumes-lvm2.png?w=620&#038;h=400" alt="" width="620" height="400" /></a><p class="wp-caption-text">Criando volumes lvm2</p></div>
<p>Agora é hora de formatar os volumes que acabamos de criar:</p>
<div id="attachment_515" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/08-formatando-root-crypt-lvm.png"><img class="size-full wp-image-515" title="Formatando volume lógico que será a partição raiz so S.O" src="http://daltonmatos.files.wordpress.com/2011/06/08-formatando-root-crypt-lvm.png?w=620&#038;h=400" alt="" width="620" height="400" /></a><p class="wp-caption-text">Formatando volume lógico que será a partição raiz do S.O</p></div>
<div id="attachment_516" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/09-format-home-crypt-lvm.png"><img class="size-full wp-image-516" title="Formatando o volume lógico que será o /home" src="http://daltonmatos.files.wordpress.com/2011/06/09-format-home-crypt-lvm.png?w=620&#038;h=400" alt="" width="620" height="400" /></a><p class="wp-caption-text">Formatando o volume lógico que será o /home</p></div>
<p>Agora que temos dois volumes prontos, podemos começar a instalar o gentoo. Basta montar o <em>block device</em> /dev/vg01/root em /mnt/gentoo (como recomenda o <a title="Gentoo Handobook" href="http://www.gentoo.org/doc/en/handbook/handbook-x86.xml" target="_blank">gentoo handbook</a>) e podemos continuar a partir do <a title="Gentoo Handbook, capítulo 5." href="http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=1&amp;chap=5" target="_blank">passo 5</a>.</p>
<h1>Configurando o kernel</h1>
<p>No momento de configurar o kernel (handbook, <a title="Gentoo handkbook: Configurando o kernel" href="http://www.gentoo.org/doc/en/handbook/handbook-x86.xml?part=1&amp;chap=7" target="_blank">passo 7</a>) que usaremos, precisamos adicionar opções especiais para que tudo dê certo. Basicamente essas opções são:</p>
<ul>
<li>Suporte a <em>Device mapper</em>, com suporte a encripatação</li>
<li>Suporte ao algoritmo de encriptação usado</li>
</ul>
<div id="attachment_522" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/13-kernel-options-luks-device-mapper.png"><img class="size-full wp-image-522" title="Kernel option: device mapper" src="http://daltonmatos.files.wordpress.com/2011/06/13-kernel-options-luks-device-mapper.png?w=620&#038;h=421" alt="" width="620" height="421" /></a><p class="wp-caption-text">Kernel option: device mapper</p></div>
<div id="attachment_520" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-ciphers-kernel-options.png"><img class="size-full wp-image-520" title="Kernel Option: Algoritmo de encriptação" src="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-ciphers-kernel-options.png?w=620&#038;h=421" alt="" width="620" height="421" /></a><p class="wp-caption-text">Kernel Option: Algoritmo de encriptação</p></div>
<div id="attachment_521" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-options-sha256.png"><img class="size-full wp-image-521" title="Kernel Option: Sha 256 support" src="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-options-sha256.png?w=620&#038;h=375" alt="" width="620" height="375" /></a><p class="wp-caption-text">Kernel Option: Sha 256 support</p></div>
<p>Essa última opção só foi necessária pois usamos &#8211;cipher twofish-cbc-essiv:sha256 no momento de encriptar a partição /dev/sda2.</p>
<p>Para podermos compilar esse kernel, o melhor é usarmos o utilitário genkernel. Basta instalar usando emerge normal. Antes de efetivamente compilar esse kernel, precisamos instalar dois pacotes. Atenção para as USE flags específicas de cada um deles:</p>
<ul>
<li>sys-fs/lvm2 USE: +static</li>
<li>sys-fs/cryptsetup USE: +static-libs</li>
</ul>
<p>Isso é necessário pois o ramdisk que será criado daqui a pouco precisará deles. O genkernel é uma mão na roda e é quem fará o trabalho duro de adicionar suporte para que seja possível bootar esse sistema com do disco encriptado. Como o genkernel já salva automaticamente os arquivos em /boot, temos que montar nossa partição (aquela que não é encriptada) no lugar certo:</p>
<pre># mount /dev/sda1 /boot</pre>
<p>Agora poderemos usar o genkernel para preparar tudo:</p>
<pre># genkernel --menuconfig --luks --lvm all</pre>
<p>Isso vai fazer com que o menu de configuração do kernel seja chamado (onde teremos que adicionar as opções citadas acima) e depois que salvarmos a configuração já começará a compilar nosso novo kernel. No final da compilação, teremos em /boot dois arquivos: O kernel e o initramfs criados pelo genkernel.</p>
<h1>Configurando o boot loader</h1>
<p>Nesse momento, o que falta é configurar o boot loader, nesse caso o Grub.</p>
<pre># emerge grub
# grub
grub&gt; root (hd0,0)
gurb&gt; setup (hd0)
quit</pre>
<p>Repare que estamos instalando o grub no <a title="MBR: Wikipedia" href="http://en.wikipedia.org/wiki/Master_boot_record" target="_blank">MBR</a>, isso é válido pois nesse caso temos apenas um S.O instalado. Se estivéssemos fazendo dual-boot e já tivéssemos um outro S.O rodando, teríamos que instalar o grub na partição sda1, nesse caso em (hd0,0).</p>
<p>Como estamos preparando um sistema e um kernel especiais, precisamos passar opções especiais para o Grub, só assim ele poderá carregar nosso novo S.O. As linhas do /boot/grub/menu.lst ficam assim:</p>
<pre>title Gentoo Linux 2.6.38-gentoo-r6
root (hd0,0)
kernel /boot/kernel-genkernel-x86_64-2.6.38-gentoo-r6 dolvm root=/dev/ram0 crypt_root=/dev/sda2 real_root=/dev/vg01/root
initrd /boot/initramfs-genkernel-x86_64-2.6.38-gentoo-r6</pre>
<h1>Ajustando o /etc/fstab</h1>
<p>O último passo é ajustar o arquivo /etc/fstab para que as partições corretas sejam montadas. Temos que adicionar o /boot e o /, ficando assim:</p>
<div id="attachment_529" class="wp-caption aligncenter" style="width: 630px"><a href="http://daltonmatos.files.wordpress.com/2011/06/18-fstab-final.png"><img class="size-full wp-image-529" title="Como fica o /etc/fstab" src="http://daltonmatos.files.wordpress.com/2011/06/18-fstab-final.png?w=620&#038;h=548" alt="" width="620" height="548" /></a><p class="wp-caption-text">Como fica o /etc/fstab</p></div>
<p>Nesse arquivo temos o /home, que no meu caso foi necessário pois sempre deixo a home separada. Não esqueça de retirar a linha do SWAP, pois não criamos uma.</p>
<p>Agora é dar reboot e curtir o novo sistema com os dados totalmente encriptados. Como estamos usando LVM2, qualquer <em>partição</em> adicional que você criar no futuro, <strong>já estará</strong> encriptada.</p>
<h1>Considerações finais</h1>
<p>É bem verdade que pelo fato de ter seu disco encriptado você terá uma perda de performance. Eu sei disso. A questão é que já uso essa configuração há 3 anos (usei desde o primeiro notebook) e como nunca tive um notebook sem ter o disco encriptado acabo <em>não sabendo</em> qual é a real perda de performance.</p>
<p>Usei o primeiro notebook durante todo o tempo, sem achar que ele estava lento por qualquer motivo. O notebook novo já é naturalmente mais rápido (Processador melhor, disco melhor, etc) então mesmo tendo novamente o disco encriptado, já percebi uma melhoria considerável na performance do novo aparelho. Então, diante disso, tá tudo bem! =)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/498/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/498/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/498/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=498&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/06/28/gentoo-com-particao-raiz-encriptada/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/00-particoes-originais.png" medium="image">
			<media:title type="html">Particoes originais</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/03-novas-particoes-criadas.png" medium="image">
			<media:title type="html">Novas particoes criadas</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/05-formatando-com-cryptsetup-luksformat.png" medium="image">
			<media:title type="html">Formatando com cryptsetup luksformat</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/06-destravando-crypt-root.png" medium="image">
			<media:title type="html">Destravando crypt root</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/07-criando-volumes-lvm2.png" medium="image">
			<media:title type="html">Criando volumes lvm2</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/08-formatando-root-crypt-lvm.png" medium="image">
			<media:title type="html">Formatando volume lógico que será a partição raiz so S.O</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/09-format-home-crypt-lvm.png" medium="image">
			<media:title type="html">Formatando o volume lógico que será o /home</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/13-kernel-options-luks-device-mapper.png" medium="image">
			<media:title type="html">Kernel option: device mapper</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-ciphers-kernel-options.png" medium="image">
			<media:title type="html">Kernel Option: Algoritmo de encriptação</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/13-crypto-options-sha256.png" medium="image">
			<media:title type="html">Kernel Option: Sha 256 support</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2011/06/18-fstab-final.png" medium="image">
			<media:title type="html">Como fica o /etc/fstab</media:title>
		</media:content>
	</item>
		<item>
		<title>O que aprendi desenvolvendo projetos de código aberto</title>
		<link>http://daltonmatos.wordpress.com/2011/06/19/o-que-aprendi-desenvolvendo-projetos-de-codigo-aberto/</link>
		<comments>http://daltonmatos.wordpress.com/2011/06/19/o-que-aprendi-desenvolvendo-projetos-de-codigo-aberto/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 19:35:21 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Projetos]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=482</guid>
		<description><![CDATA[Nesse post vou escrever um pouco sobre minha primeira experiência no desenvolvimento de projetos de código aberto. O interesse por software de código aberto Desde muito tempo tive interesse no desenvolvimento de software, especialmente em softwares de código aberto. Um interesse especial é o fato de você ter a oportunidade de ver códigos escritos por [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=482&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Nesse post vou escrever um pouco sobre minha primeira experiência no desenvolvimento de projetos de código aberto.</p>
<h2>O interesse por software de código aberto</h2>
<p style="text-align:justify;">Desde muito tempo tive interesse no desenvolvimento de software, especialmente em softwares de código aberto. Um interesse especial é o fato de você ter a oportunidade de ver códigos escritos por outras pessoas. Ler código de outras pessoas nos faz aprender muito, pois vemos abordagens diferentes para um mesmo problema e podemos aprender <em>hacks</em> que não fazíamos idéia que seriam possíveis.</p>
<p style="text-align:justify;">Sempre publiquei meus códigos para quem quisesse ver e defendo a idéia de que as pessoas deveriam também sempre publicar seus códigos. A unica situação em que faz sentido não publicar algum código é quando esse código é crucial para um negócio qualquer. Nesse caso não faz sentido <em>entregar o ouro</em>, claro.</p>
<h2>Primeiras contribuições</h2>
<p style="text-align:justify;">O primeiro passo para ter seu projeto de código aberto é fazer parte de algum outro projeto. Fazendo isso você pode ter contato com outros desenvolvedores, aprender como funciona o projeto especificamente, como é o processo para que você possa contribuir, além de ganhar experiência para que um dia possa tocar seu próprio projeto de código aberto.</p>
<p style="text-align:justify;">Minha participação em projetos de código aberto teve início quando comecei a estudar python, há pouco mais de um ano atrás.  Antes de escrever código em python, lia bastante sobre a linguagem. Aprendi lendo o próprio site da linguagem e sempre que tinha alguma dúvida específica sobre alguma sintaxe, ia direto ler a <a title="Gramática da linguagem Python" href="http://docs.python.org/reference/grammar.html" target="_blank">gramática</a>. Acho essa forma mais eficiente do que ler <em>hello worlds</em> por aí.</p>
<p style="text-align:justify;">Em uma dessas pesquisas, estava tentando encontrar um framework web que fosse bem simples de entender, afinal eu estava começando a estudar a linguagem. Apesar de já ter experiência com sistemas web, conhecer sobre HTTP, requisições e etc. Web + python era, naquela época, algo novo.</p>
<p style="text-align:justify;">Foi então que encontrei um framework chamado <a title="Pyroutes" href="http://pyroutes.com" target="_blank">pyroutes</a>. Pois bem, desde o início gostei da implementação pois ela faz uso dos <a title="Python Decorators" href="http://www.python.org/dev/peps/pep-0318/" target="_blank">decorators</a>, que é uma coisa que acho fantástica na linguagem. Então comecei a estudar o código desse projeto, fiz meu <em>fork</em> no github e comecei a enviar <em>pull requests</em>. Comecei simples, apenas corrigindo erros triviais nos testes automatizados: <a href="https://github.com/pyroutes/pyroutes/commit/2d921fa913178f89b93e1f3b2b835d93f7e2e08e" target="_blank">2d921fa91</a> e <a href="https://github.com/pyroutes/pyroutes/commit/22a3211fc13a8bcfdaec1cc61f07c0f4e5c2147e" target="_blank">22a3211</a>. Pouco depois, já estava corrigindo bugs e fazendo implementações menos triviais: <a href="https://github.com/pyroutes/pyroutes/commit/44d1708f83e647aa6dfe5442e139e0a5f9ad6f42" target="_blank">44d1708</a>.</p>
<p style="text-align:justify;">O que ganhei com tudo isso? Bastante experiência! Contato com pessoas de outras nacionalidades, conhecimento na linguagem que estava aprendendo e o mais importante: A oportunidade de outras pessoas me conhecerem e saberem das minhas habilidades e conhecimentos. Nesse projeto especificamente ganhei outra coisa também muito impotante: permissão de commit no repositório oficial!</p>
<h2>A hora de começar meu próprio projeto</h2>
<p style="text-align:justify;">Depois de ter colaborado por algum tempo com esse projeto decidi que tinha chegado a hora de tentar uma nova empreitada: Tocar meu próprio projeto de código aberto. A idéia desse projeto apareceu ainda quando estava estudando sobre a linguagem. Como já disse aqui, acho muito importante ler código de outras pessoas e foi lendo o código do <a title="Trac Project" href="http://trac.edgewall.org" target="_blank">Trac</a> que tive a idéia para o meu primeiro projeto: <a title="Plug n’ Play: um sistema de plugins genérico para python" href="http://daltonmatos.wordpress.com/2010/11/14/plug-n-play-um-sistema-de-plugins-generico-para-python/" target="_blank">plugnplay</a>.</p>
<p style="text-align:justify;">O desenvolvimento desse projeto foi bem legal, foi meu primeiro código publicado que realmente tinha chance de ser útil para alguém além de mim, e isso é fantástico. Foi desenvolvido em apenas uma semana (de acordo com o <a title="Histórico de commits: plugnplay" href="https://github.com/daltonmatos/plugnplay/commits/master" target="_blank">histórico de commits</a>).</p>
<p style="text-align:justify;">O projeto é bem pequeno e fiquei bem feliz quando vi que ele já tinha 3 <em>watchers</em>!</p>
<h2>O Segundo projeto</h2>
<p style="text-align:justify;">É claro que não parei por aí! Continuei com minhas pesquisas até que surgiu a idéia para o segundo projeto: <a title="Rodando sua aplicação WSGI como um *nix daemon" href="http://daltonmatos.wordpress.com/2011/04/09/rodando-sua-aplicacao-wsgi-como-um-nix-daemon/" target="_blank">wsgid</a>. Essa idéia surgiu quando me deparei com um outro projeto: <a href="http://mongrel2.org/static/mongrel2-manual.html" target="_blank">mongrel2</a>. O objetivo do wsgid é me ajudar a ter uma infra-estrutura totalmente automatizada para fazer o deploy de minhas aplicações, e esse é o primeiro passo para que consiga chegar a esse objetivo.</p>
<p style="text-align:justify;">Ao contráio do plugnplay, para esse projeto fiz um <a title="WSGID: Website oficial" href="http://wsgid.com/" target="_blank">website</a>, uma <a title="Documentação oficial WSGID" href="http://wsgid.com/docs" target="_blank">documentação completa</a> e até comprei o domínio (wsgid.com), ou seja, coisa séria! =) E isso se mostrou muito importante. Querendo ou não, um projeto que apresenta um site oficial e uma documentação completa de suas funcionalidades atrai muito mais a atenção das pessoas, pois passa uma credibilidade maior. Uma coisa interessante é que o site oficial do wsgid roda usando o próprio wsgid!</p>
<p style="text-align:justify;">A questão da documentação é especialmente importante pois temos que lembrar que nem todo mundo (mesmo desenvolvedores) terá curiosidade suficiente para ler o código-fonte para poder aprender a usar seu projeto, então ter uma forma fácil de começar a usar o projeto se mostra muito importante.</p>
<h2>Visibilidade do projeto</h2>
<p style="text-align:justify;">O projeto wsgid teve uma visibilidade muito maior do que o plugnplay, e acho que isso se deve a alguns fatores. Em primeiro lugar ele é um <em>projeto satélite</em> de um projeto grande, o mongrel2. Só isso já te dá mais visibilidade. Outra coisa é que como eu estava participando da lista de desenvolvimento do mongrel2, mandei emails para essa lista divulgando o projeto e recebi feedbacks importantes. O fato da URL do site oficial estar na assinatura de todos os meus emails também ajuda. Novamente, isso só é possível pois o projeto possui um website.</p>
<p style="text-align:justify;">Durante o desenvolvimento do projeto (até hoje, na verdade) ainda recebo notificações por email quando o projeto ganha mais um <em>watcher</em> em seu <a href="https://github.com/daltonmatos/wsgid" target="_blank">repositório</a>. Hoje o projeto está com 13 <em>watchers</em>, o que é fantástico! Esse tipo de coisa te dá mais gás para continuar escrevendo o código, pois você vê que existem pessoas que acharam seu projeto interessante a ponto de decidirem acompanhar sua evolução. E isso é muito bom! Outra coisa ainda melhor é o número de <em>forks</em> que o projeto recebeu, até agora já são <a href="https://github.com/daltonmatos/wsgid/network/members" target="_blank">5</a> em 6 meses de projeto.</p>
<p style="text-align:justify;">Novamente, durante o desenvolvimento desse projeto tive a oportunidade de me comunicar com outras pessoas. Como já disse, entrei para a lista de desenvolveores do projeto mongrel2 e novamente comecei a submeter patches com pequenas correções. Depois, quando já estava com um domínio maior sobre o código já comecei a enviar códigos menos triviais, participei de várias discussões na lista até que, novamente, ganhei permissões de commit no repositório oficial. Essa é a <a href="https://github.com/zedshaw/mongrel2/commits/master?author=daltonmatos" target="_blank">lista de commits</a> que fiz no repositório oficial, até o momento.</p>
<h2>Conclusão</h2>
<p style="text-align:justify;">Minha conclusão disso tudo é que é muito divertido contribuir com algum projeto, melhor ainda é ter seus próprios e receber contribuições de outras pessoas  (já recebi um <em>patch</em> para o wsgid). Ter um <em>side-project</em> te dá mais conhecimento, faz com que as pessoas possam te conhecer (e isso é muito importante!) e te permite aprimorar suas habilidades.</p>
<p style="text-align:justify;">Se você ainda não posui um projeto, comece um! Os dois que tenho surgiram para resolver problemas que eu tinha no dia-a-dia, tenho certeza que você também já viveu situações onde um programa poderia te ajudar ou até mesmo resolver seu problema. Pense que outras pessoas certamente já tiveram o mesmo problema e também poderiam ser ajudadas pelo seu projeto.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/482/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/482/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/482/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=482&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/06/19/o-que-aprendi-desenvolvendo-projetos-de-codigo-aberto/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>Rodando sua aplicação WSGI como um *nix daemon</title>
		<link>http://daltonmatos.wordpress.com/2011/04/09/rodando-sua-aplicacao-wsgi-como-um-nix-daemon/</link>
		<comments>http://daltonmatos.wordpress.com/2011/04/09/rodando-sua-aplicacao-wsgi-como-um-nix-daemon/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 23:00:47 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[Projetos]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[webserver]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=437</guid>
		<description><![CDATA[For english readers, pease see post below. Quase sempre quando pensamos em aplicações web (eu inclusive), pensamos na apache stack. Esse post apresenta uma forma diferente de fazer o deploy de sua aplicação, começando pelo fato de usarmos o servidor web apache. Primeiro de tudo, precisamos conhecer uma peça chave diso tudo: Mongrel2 Mongrel2 é [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=437&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For english readers, pease see <a href="#en">post below</a>.</p>
<p>Quase sempre quando pensamos em aplicações web (eu inclusive), pensamos na <a title="Apache stack" href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29"><em>apache stack</em></a>. Esse post apresenta uma forma diferente de fazer o deploy de sua aplicação, começando pelo fato de usarmos o servidor web apache.</p>
<p>Primeiro de tudo, precisamos conhecer uma peça chave diso tudo:</p>
<h2>Mongrel2</h2>
<p>Mongrel2 é um servidor web escrito por Zed A. Shaw. Esse é um servidor que simplismente não se importa em que linguagem sua aplicação foi escrita, tudo que você precisa fazer é seguir algumas regras bem simples para conseguir juntar mongrel2 e sua aplicação.</p>
<p>A primeira regra é que sua aplicação precisa saber se comunicar através de uma fila, nesse caso <strong>ØMQ</strong> (<a title="ZeroMQ" href="http://zeromq.org">http://zeromq.org</a>) e a segunda regra é que sua aplicação precisa entender o protocolo definido pelo mongrel2. Você pode (e deve!) saber mais sobre o mongrel2 no site oficial: <a title="Mongrel2" href="http://mongrel2.org" target="_blank">http://mongrel2.org</a><strong>.<br />
</strong></p>
<p>A grande sacada do mongrel2 é que, o fato dele usar uma fila para se comunicar com sua aplicação faz com que sua aplicação possa rodar de forma desacoplada do servidor, isso significa que sua aplicação não roda com a ajuda de um mod_algumacoisa ou como um processo filho do servidor web. Uma outra vantagem é que o ØMQ permite enviar mensagem por TCP, isso significa que sua aplicação pode estar rodando em uma máquina diferente de onde o mongrel2 está rodando.</p>
<p>Poder rodar sua aplicação em máquinas diferentes é fantástico pois sempre que necessário você pode adicionar mais uma máquina ao seu cluster e startar mais instâncias da sua apliação, todas as instâncias vão se comunicar com o mesmo mongrel2, que vai balancear as requisições entre todas as instâncias conectadas, usando uma politica <a title="Round Robin" href="http://pt.wikipedia.org/wiki/Round-robin_%28algoritmo%29" target="_blank">round-robin</a>.</p>
<h2>wsgid</h2>
<p>wsgid é o projeto que desenvolvi para tornar possível rodar suas aplicações WSGI usando como servidor web o mongrel2. O wsgid é a ponte entre o mongrel2 e a especificação WSGI (<a title="PEP-333" href="http://www.python.org/dev/peps/pep-0333/" target="_blank">PEP-333</a>), isso significa que basta a sua aplicação obedecer à especificação WSGI para já estar pronta para rodar com o mongrel2.</p>
<p>O wsgid entende tanto a língua do mongrel2 (zeromq + protocolo) quanto a especificação WSGI. Além disso, sua aplicação agora é um processo separado, com PID e tudo mais. Isso te traz algumas vantagens, como:</p>
<ul>
<li>Pode rodar com permissões de qualquer usuário, a sua escolha;</li>
<li>Por ser um processo do sistema operacional, está automaticamente sujeito a quaisquer configurações que o S.O possa oferecer, como por exemplo: limite de banda, memória, CPU e etc;</li>
<li>Pode ser rodado dentro de um <a title="Chroot" href="http://en.wikipedia.org/wiki/Chroot" target="_blank"><em>chroot</em></a>, caso você precise rodar código não confiável;</li>
<li>Entre outras.</li>
</ul>
<p>Iniciar uma nova instância de sua aplicação é tão fácil quanto:</p>
<pre>   $ wsgid --app-path=/path/to/wsgid-app-folder/ --recv=tcp://127.0.0.1:8888 --send=tcp://127.0.0.1:8889
      --workers=4</pre>
<p>Nesse exemplo simples estamos conectando ao endpoint 0MQ que está na mesma máquna em que nossa aplicação, mas nada impede de usarmos &#8211;recv=tcp://129.168.0.2:8888, sendo esse IP o de uma máquina qualquer em seu cluster. Ainda nesse exemplo a opção &#8211;workers=4 cria 4 processos que vão ser responsáveis por atender requisições de sua aplicação.</p>
<h2>wsgid, principais funcionalidades</h2>
<p>Além de facilitar o deploy de aplicações WSGI com o mongrel2, o wsgid possui ainda outras funcionalidades importantes:</p>
<h3>workers</h3>
<p>Com a opção workers você pode iniciar quantos processos desejar, de uma só vez. Isso significa que você não precisa rodar o comando 4 vezes caso queira 4 instâncias, apesar de você poder fazer isso, sem problema nenhum. Mas essa opção te dá a possibilidade de fazer &#8211;workers=4, que te dará o mesmo resultado.</p>
<h3>keep alive</h3>
<p>Com a opção keep-alive o wsgid reinicia automaticamente qualquer processo que tenha terminado sua execução. Isso significa que uma chamada ao wsgid com &#8211;workers=4 &#8211;keep-alive manterá sempre 4 workers trabalhando para sua aplicação.</p>
<h3>hot deploy</h3>
<p>Sempre que o wsgid restarta um dos processos, o código de sua aplicação é recarregado, afinal é um novo processo que está sendo criado. Isso significa que você pode atualizar o código-fonte de sua aplicação e apenas mandar um SIGTERM para todos os seus workers, isso fará com que o wsgid restarte cada um deles, mas dessa vez já rodando o novo código-fonte.</p>
<h3>chroot</h3>
<p>O wsgid já pode, automaticamente, fazer o chroot para uma localidade onde a aplicação está. Isso faz com que essa aplicação possa rodar de forma isolada, criando assim um ambiente um pouco mais seguro (não totalmente) caso você esteja rodando códigos não confiáveis.</p>
<h3>Sistema plugável para carregar diferentes aplicações</h3>
<p>O wsgid conta com um sistema de plugins muito simples porém bem poderoso. Com ele você pode escrever seu próprio <em>Application Loader</em>, caso o wsgid não consiga carregar sua aplicação. Com isso será muito simples adicionar suporte a outros frameworks WSGI para que mais aplicações possam fazer uso desse projeto.</p>
<p>Espero que tenha gostado do projeto, qualquer feedback é bem vindo. Para saber mais sobre o projeto visite o site oficial: <a title="Wsgid official website" href="http://wsgid.com" target="_blank">http://wsgid.com</a> e saiba mais.</p>
<p>Mas lembre-se, use o que for melhor para você, use o que te atende melhor. Não estou dizendo que a solução mongrel2+wsgid é a melhor sempre, estou apenas dizendo que essa combinação é fantástica, e deve ser considerada no momento de publicar uma nova aplicação WSGI.</p>
<p>Apenas por curiosidade, o site wsgid.com é uma aplicação django e está rodado usando o próprio wsgid.</p>
<hr />
<h1 id="en">Running your WSGI app as a *nix daemon</h1>
<p>Almost every time we think about web apps (at least me) we think about the <a title="Apache stack" href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29"><em>apache stack</em></a>. This post will show you a different method to deploy your aps, starting by not using apache as the web server.</p>
<p>First of all, we need to know a key piece of all this:</p>
<h2>Mongrel2</h2>
<p>Mongrel2 is a webserver written by Zed A. Shaw. The server is language  agnostic, which means that it just doesn&#8217;t care which language you wrote  you app, all you have to do is follow some very simple rules and you  will be able to plug mongrel2 and your app together.</p>
<p>The first rule is that your app must know how to communicate through a queue, in this case <strong>ØMQ</strong> (<a title="ZeroMQ" href="http://zeromq.org/">http://zeromq.org</a>) and the second one is that you must follow the very simple protocol specified by mongrel2. You can (and must!) know more about mongre2 on the official website: <a title="Mongrel2" href="http://mongrel2.org/" target="_blank">http://mongrel2.org</a><strong>.</strong></p>
<p>The key feature of mongrel2 is that, that fact of using a queue to communicate with the applications makes it possible to run the apps decoupled from the server, this means that your app doesn&#8217;t run with a <em>mod_something</em> or as a child process of the webserver. Another advantage is that ØMQ allows you to communicate over TCP, that&#8217;s how you can run your app on a machine other than where mongrel2 is running.</p>
<p>The ability to run your app this way, that is, on different machines is fantastic, because whenever needed you can add a new node to your cluster and start new instances of your app. All these instances will connect to the same mongrel2, and the requests will be load-balanced among all instances in a <a title="Round-robin" href="http://en.wikipedia.org/wiki/Round_robin_algorithm#Computing" target="_blank">round-robin</a> policy.</p>
<h2>wsgid</h2>
<p>wsgid is a project I developed to make possible to run your WSGI apps with mongrel2 webserver. wsgid is the brifge between mongrel2 and the WSGI specification (<a title="PEP-333" href="http://www.python.org/dev/peps/pep-0333/" target="_blank">PEP-333</a>), this means that just by conforming with the WSGI spec your app is ready to run with mongrel2+wsgid.</p>
<p>wsgid talks both mongrel2 and WSGI, also from now on your app will be a separated process, with it&#8217;s own PID and everything a process has. This brings you some advantages:</p>
<ul>
<li>Can run as any user on your operating system;</li>
<li>As being a O.S process, is automatically submitted to all characteristcs and O.S process has, eg: bandwith limit, memory limits, CPU scheduling, etc;</li>
<li>Can run inside a <a title="Chroot" href="http://en.wikipedia.org/wiki/Chroot" target="_blank"><em>chroot</em></a>, in caso you are running untrusted code;</li>
<li>Many others.</li>
</ul>
<p>Start new instances of your app is as easy as:</p>
<pre>   $ wsgid --app-path=/path/to/wsgid-app-folder/ --recv=tcp://127.0.0.1:8888 --send=tcp://127.0.0.1:8889
      --workers=4</pre>
<p>I this very simple example we are connecting to a ØMQ endponit in same machine that the app will be running, but nothing prevents us from using &#8211;recv=tcp://192.168.0.2:8888, being this IP the address of another node on the cluster. Still in this example, the option &#8211;worker=4 starts 4 processes that will respond to requests for your app.</p>
<h2>wsgid, key features</h2>
<p>Besides facilitating the deployment of WSGI applications with mongrel2, wsgid also has other important features:</p>
<h3>workers</h3>
<p>With this option you will be able to start any number of processes you want at once. That means you don&#8217;t need to run the same wsgid command 4 times if you want four instances, although you can do this without any problem. But this option gives you the possibility to do &#8211;workers=4, which gives you the same result.</p>
<h3>keep alive</h3>
<p>With the keep-alive option wsgid automatically restarts any process which has finished its execution. This means that with a call to wsgid with &#8211;workers=4 &#8211;keep-alive, wsgid will always keep 4 processes working for your application.</p>
<h3>hot deploy</h3>
<p>Whenever wsgid re-starts one of the processes, the code of your application is reloaded, after all is a new process being created. That means you can update the source code of your application and just SIGTERM all its workers, it will make  wsgid restart all workers, but this time already running the new source code.</p>
<h3>chroot</h3>
<p>wsgid can chroot to the location where the application is. This makes such application run in isolated, thus creating an environment a little safer (not entirely) if you are running untrusted code.</p>
<h3>Plugable system for Application Loading</h3>
<p>wsgid has a very simple but very powerful plugin sub-system . With it you can write your own application loader, in case wsgid is not able to load your WSGI app. With such a sub-system, it will be very simple to add support for other WSGI frameworks so that more applications can make use of this project.</p>
<p>That&#8217;s it! Hope you enjoyed the project, any feedback is more than welcome. To learn more about the project visit the official website: <a title="Wsgid official website" href="http://wsgid.com" target="_blank">http://wsgid.com</a>.</p>
<p>But remember, use what works best for you, use what best serves you. I&#8217;m not saying that the solution mongrel2+wsgid is the best ever, I&#8217;m just saying that this combination is fantastic and should be considered whenever you are thinking of publishing a new WSGI application.</p>
<p>Just out of curiosity, the wsgid.com website is a django application and runs with wsgid.</p>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/python/'>python</a>, <a href='http://daltonmatos.wordpress.com/tag/webserver/'>webserver</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/437/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/437/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/437/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=437&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2011/04/09/rodando-sua-aplicacao-wsgi-como-um-nix-daemon/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>
	</item>
		<item>
		<title>Acessando os sites que você quiser no trabalho</title>
		<link>http://daltonmatos.wordpress.com/2010/12/05/acessando-os-sites-que-voce-quiser-no-trabalho/</link>
		<comments>http://daltonmatos.wordpress.com/2010/12/05/acessando-os-sites-que-voce-quiser-no-trabalho/#comments</comments>
		<pubDate>Sun, 05 Dec 2010 21:09:55 +0000</pubDate>
		<dc:creator>daltonmatos</dc:creator>
				<category><![CDATA[Dica]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[rede]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://daltonmatos.wordpress.com/?p=390</guid>
		<description><![CDATA[Esse post mostra uma (dentre várias) formas de burlar os diversos bloqueios impostos por algumas empresas no que diz respeito a acesso à internet. Veremos uma forma bem simples e eficiente de navegar em sites que supostamente não poderíamos estar vendo. =) Muitas vezes nos deparamos com a desagradável situação em que precisamos acessar um [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=390&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:justify;">Esse post mostra uma (dentre várias) formas de burlar os diversos bloqueios impostos por algumas empresas no que diz respeito a acesso à internet. Veremos uma forma bem simples e eficiente de navegar em sites que supostamente não poderíamos estar vendo. =)</p>
<p><span id="more-390"></span></p>
<p style="text-align:justify;">Muitas vezes nos deparamos com a desagradável situação em que precisamos acessar um site qualquer mas em vez disso recebemos uma página dizendo que não podemos prosseguir. Pois então, sabemos que esse tipo de bloqueio nem sempre é eficiente, muito menos quando é mal executado (o que geralmente acontece!) =)</p>
<p style="text-align:justify;">A idéia de escrever esse post veio depois que li uma mensagem de um amigo:  <a href="http://twitter.com/#!/fjleite/status/9923497178435584" target="_blank">http://twitter.com/#!/fjleite/status/9923497178435584</a>. Achei que essa dica serviria para muitas outras pessoas, que estão na mesma situação.</p>
<p style="text-align:justify;">A técnica é <strong>muito simples</strong> e, na verdade, é a <strong>mesma</strong> técnica usada em um <a title="Como burlar limitações de conectividade impostas por hoteis e afins" href="http://daltonmatos.wordpress.com/2010/09/12/como-burlar-limitacoes-de-conectividade-impostas-por-hoteis-e-afins/" target="_blank">post anterior</a>, mas agora o propósito é outro. Naquele caso era apenas para manter uma conexão aberta, já que o servidor não destruia conexões já estabelecidas no momento em que seu <em>cartão de internet</em> expirava. Nesse caso, usaremos a técnica para tunelar todo o tráfego que entra/sai de nosso computador.</p>
<h2 style="text-align:justify;">Antes de continuar, pense um pouco</h2>
<p style="text-align:justify;">Só escrevi esse post pois acho que esse tipo de bloqueio é totalmente <em>idiota</em> e <strong>ineficiente</strong>! É muito ingênuo pensar que um funcionário vai trabalhar mais porque não consegue acessar determinados sites na internet. Se o cara não quer trabalhar ele vai fazer isso independente de poder ou não acessar livremente a rede.</p>
<p style="text-align:justify;">Não que eu esteja querendo que todos fiquem acessando sites durante o expediente, não é isso. Apenas acredito que cada um deve saber qual é seu limite e deve ter bom senso ao acessar conteúdos não relacionado ao trabalho do dia-a-dia.</p>
<p style="text-align:justify;">Portanto se você for usar essa téncnica, use-a com moderação. Pode seguir!</p>
<h2>Detectando uma rede vulnerável</h2>
<p style="text-align:justify;">É muito fácil saber se essa técnica vai funcionar ou não na rede em que estamos, para saber disso basta abrir um terminal e tentar acessar qualquer servidor ssh fora de sua rede.</p>
<pre>usuario@maquina ~: ssh servidor-externo</pre>
<p style="text-align:justify;">Se aparecer o promtp pedindo sua senha, você está na vantagem! Poderá acessar o que quiser em muito pouco tempo. =)</p>
<h2>Executando a técnica</h2>
<p style="text-align:justify;">Para que tudo comece a funcionar basta passar um parametro especial para o seu cliente ssh, que é o <em>-D &lt;porta&gt;.</em> Onde <em>&lt;porta&gt;</em> deve ser uma porta que não está sendo usada em seu computador.</p>
<pre>usuario@maquina ~: ssh -D 9999 servidor-externo</pre>
<p style="text-align:justify;">Após isso, apenas entre com sua senha, certifique-se que o login no servidor remoto foi feito com sucesso e deixe esse terminal <strong>aberto</strong>.</p>
<p style="text-align:justify;">Agora é hora de mexer nas configurações do seu browser. Precisamos apenas configurá-lo para usar um servidor Proxy Socks5 para todos os acessos a sites da web. Qualquer browser moderno é capaz de fazer isso e aqui darei o exemplo usando o Firefox.</p>
<p style="text-align:justify;">Vá em Preferências (geralmente no menu <em>Editar/Preferências</em>), acesse a aba <em>Avançado</em> e depois aba <em>Rede</em>.</p>
<div id="attachment_400" class="wp-caption aligncenter" style="width: 626px"><a href="http://daltonmatos.files.wordpress.com/2010/12/preferencias-ff.png"><img class="size-full wp-image-400" title="preferencias-ff" src="http://daltonmatos.files.wordpress.com/2010/12/preferencias-ff.png?w=620" alt="Preferências do Firefox"   /></a><p class="wp-caption-text">Tela de Preferências do Firefox</p></div>
<p style="text-align:justify;">Depois clique em <em>Configurar conexão</em> e preencha as informações para que o FF use o Proxy Socks5 para acessar os sites.</p>
<div id="attachment_401" class="wp-caption aligncenter" style="width: 512px"><a href="http://daltonmatos.files.wordpress.com/2010/12/proxy-ff.png"><img class="size-full wp-image-401" title="proxy-ff" src="http://daltonmatos.files.wordpress.com/2010/12/proxy-ff.png?w=620" alt="Configurações de Proxy"   /></a><p class="wp-caption-text">Firefox configurado para usar Proxy Socks5</p></div>
<p style="text-align:justify;">Apenas clique OK e curta sua navegação <em>sem limites</em>. Percebeu que o servidor proxy é sua <strong>própria máquina</strong> (127.0.0.1)? Pois é, explico isso logo abaixo.</p>
<h2>Como tudo funciona</h2>
<p style="text-align:justify;">O que fazemos é uma coisa muito simples. Na verdade não fazemos muita coisa, quem faz é o cliente ssh! E o que ele faz é o seguinte:</p>
<p style="text-align:justify;">Ele abre um túnel entre nossa máquina e o servidor remoto, na porta que escolhemos. Mas um detalhe importante é que <em>do lado de lá</em> existe um servidor proxy socks5 esperando nossas conexões. Isso significa que sempre que acessamos um site na internet usando esse túnel, na visão do site, quem fez o acesso foi o servidor remoto e não nossa máquina, onde o site está sendo exibido.</p>
<p style="text-align:justify;">Esse detalhe pode ser útil em outras situações como por exemplo quando estamos baixando arquivos de sites que só permitem um download de cada vez. Nesse caso podemos abrir um proxy para um servidor externo e baixar o arquivo normalmente, pois na visão do site de download o acesso está sendo feito a partir do servidor remoto e não de nossa máquina. Então acabamos conseguindo baixar dois arquivos: Um acessando diretamente de nosso computador e outro fazendo o acesso pelo proxy socks5.</p>
<p style="text-align:justify;">Um <em>double bônus</em> é que todo o tráfego entre nossa máquina e o servidor remoto está <strong>encriptado</strong>, ou seja, nem se o administrador da rede tiver monitorando os pacotes ele vai conseguir ver alguma coisa. O máximo que ele verá serão pacotes ssh passando pra lá e pra cá.</p>
<p style="text-align:justify;">Lembre-se que essa situação será sempre uma corrida entre gato e rato. Você descobre uma falha, alguém que não quer que você explore essa falha descobre que você sabe do problema e corrige a falha. Esse mesmo alguém fica na vantagem até você descobrir outra falha e aí começa tudo outra vez.</p>
<br /> Tagged: <a href='http://daltonmatos.wordpress.com/tag/linux/'>Linux</a>, <a href='http://daltonmatos.wordpress.com/tag/rede/'>rede</a>, <a href='http://daltonmatos.wordpress.com/tag/ssh/'>ssh</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/daltonmatos.wordpress.com/390/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/daltonmatos.wordpress.com/390/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/daltonmatos.wordpress.com/390/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=daltonmatos.wordpress.com&amp;blog=6801919&amp;post=390&amp;subd=daltonmatos&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://daltonmatos.wordpress.com/2010/12/05/acessando-os-sites-que-voce-quiser-no-trabalho/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/b12e40fbc46262db7d075593811ed974?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">daltonmatos</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2010/12/preferencias-ff.png" medium="image">
			<media:title type="html">preferencias-ff</media:title>
		</media:content>

		<media:content url="http://daltonmatos.files.wordpress.com/2010/12/proxy-ff.png" medium="image">
			<media:title type="html">proxy-ff</media:title>
		</media:content>
	</item>
	</channel>
</rss>
