<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>rodrigolive</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/" />
    <link rel="self" type="application/atom+xml" href="http://blogs.perl.org/users/rodrigolive/atom.xml" />
    <id>tag:blogs.perl.org,2009-11-03:/users/rodrigolive//66</id>
    <updated>2011-11-03T23:02:07Z</updated>
    <subtitle>A blog about the Perl programming language</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type Pro 4.38</generator>

<entry>
    <title>smart-matching and sub funhouse</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2011/11/smart-match-and-sub-funhouse.html" />
    <id>tag:blogs.perl.org,2011:/users/rodrigolive//66.2394</id>

    <published>2011-11-03T21:57:11Z</published>
    <updated>2011-11-03T23:02:07Z</updated>

    <summary>Bad timing: now that smart-matching is under scrutiny, I&apos;ve started to have fun writing Perl like this: use signatures; use Path::Class; file( &apos;file.txt&apos; ) ~~ sub ($f) { say $f-&gt;basename; say $f-&gt;slurp; }; This style and syntax is reminiscent of...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="perlsmartmatch" label="perl smart-match" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>Bad timing: now that <a href="http://blogs.perl.org/users/brian_d_foy/2011/07/rethinking-smart-matching.html">smart-matching is under scrutiny</a>, I've started to have fun writing Perl like this:</p>

<pre>
use signatures;
use Path::Class;

file( 'file.txt' ) ~~ sub ($f) {
   say $f->basename;
   say $f->slurp;
};
</pre>

<p><p>
This style and syntax is reminiscent of Python's <code>with</code> and Ruby's <code>do</code>, and, for this use case in particular, feels a bit more natural to me than right-to-left, functional-style Perl5: </p>

<pre>
map { say $_->slurp } file( 'file.txt');
</pre>

<p><p>
I was just wondering if anyone likes them Perl served like tha'. </p>

<p>Thinking of an alternative, but similar syntax, a year or so ago I forked Perl 5.13.x and patched it trying to make it take <code>sub { }</code> as a method call. Things didn't work as I expected as I'm a Perl5 internals noob, it was a really hot Madrid summer afternoon and I had a higher-than-usual dead brain cell count, but the idea was to be able to call closures on objects:</p>

<pre>
my $f = file( 'ah-ha' );
$f -> sub {
    say $_->basename . ' = ' . $_->slurp;
};
</pre> 

<p><p>
Which probably could work nicely on native types too:</p>

<pre>
( 1..10 ) -> sub { ... };  # same as sub{ ... }->( 1..10 );
@arr -> sub { ... }; # sub{ ... }->( @arr );
%hash -> sub { ... }; 
"string" -> sub { ... };
</pre>

<p><p>
The insignificant white-space before and after the arrow makes it even more expressive. </p>

<p>This is not a proposal, Perl6 already that covered: '<a href="http://perlcabal.org/syn/S06.html#Blocks">ponty-blocks</a>' come to mind, which even drops <code>sub</code> altogether. But it sure feels like something that could make quite easily into Perl5 without causing a lot of grief.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>OTRS on Plack</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2010/06/otrs-on-plack.html" />
    <id>tag:blogs.perl.org,2010:/users/rodrigolive//66.630</id>

    <published>2010-06-10T16:34:05Z</published>
    <updated>2010-06-10T16:10:45Z</updated>

    <summary>Lately I&apos;ve been playing around with the OTRS ticketing system on one of my servers. OTRS is written in Perl, and is typically run as a CGI, mod_perl or FastCGI app. Usually I&apos;d map it as a FastCGI app on...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="plack" label="plack" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>Lately I've been playing around with the <a href="http://otrs.org"><span class="caps">OTRS </span>ticketing system</a> on one of my servers. <span class="caps">OTRS </span>is written in Perl, and is typically run as a <span class="caps">CGI, </span>mod_perl or FastCGI app. Usually I'd map it as a FastCGI app on Nginx and start the 2 FastCGI servers via a init.d script (one for the customer helpdesk and another for the management console). </p>

<p>But this time I wanted to give Plack a try. </p>

<p>I'm new to <a href="http://search.cpan.org/perldoc?Plack">Plack</a> and <span class="caps">PSGI, </span>but I can't wait to start moving my apps to this badass middleware framework. </p>

<p>Plack comes with 2 <span class="caps">CGI </span>wrapper modules, <a href="http://search.cpan.org/perldoc?Plack%3A%3AApp%3A%3AWrapCGI">Plack::App::WrapCGI</a> and <a href="http://search.cpan.org/perldoc?Plack%3A%3AApp%3A%3ACGIBin">Plack::App::CGIBin</a>. WrapCGI seems like the most appropriate for my needs. Apparently it even precompiles <span class="caps">CGI</span>s using <code>CGI::Compile</code>, for added performance.</p>

<p>So I wrote a little app.psgi in the <code>/opt/otrs</code> directory:</p>

<pre><code>use Plack::App::CGIBin;
use Plack::Builder;
my $app_main = Plack::App::WrapCGI-&gt;new(script =&gt; &quot;/opt/otrs/bin/cgi-bin/index.pl&quot;)-&gt;to_app;
my $app_customer = Plack::App::WrapCGI-&gt;new(script =&gt; &quot;/opt/otrs/bin/cgi-bin/customer.pl&quot;)-&gt;to_app;
my $app_web = Plack::App::File-&gt;new(root =&gt; &quot;/opt/otrs/var/httpd/htdocs&quot;)-&gt;to_app;
builder {
      mount &quot;/otrs&quot; =&gt; $app_main;
      mount &quot;/helpdesk&quot; =&gt; $app_customer;
      mount &quot;/otrs-web&quot; =&gt; $app_web;
};</code></pre>

<p>And fired it off:</p>

<p><code>/opt/otrs $ plackup</code></p>

<p><span class="caps">OTRS </span>was listening on the default <code>http://localhost:5000/otrs</code> and working flawlessly! But, naturally as it's running on plain plackup, it was a little slow handling requests. So I decided to upgrade it to the preforking Starman. </p>

<p><code>/opt/otrs $ starman</code></p>

<p>All I had to do was run the <code>starman</code> command-line, it uses the same app.psgi to spawn 5 processes. <span class="caps">OTRS </span>responsiveness was noticiable. </p>

<p>Now, following advice from the Starman's <span class="caps">POD,</span> I decided to preload some modules to get the benefits of copy-on-write on forking. I don't know the <span class="caps">OTRS </span>internals well, so I chose packages almost randomly. </p>

<p><code>/opt/otrs $ starman --preload-app -MDBD::mysql -MKernel::System::Ticket</code></p>

<p>That brought total reported memory usage for 5 Starman processes from 90K to 130K and slowed down startup a little. But after firing off many requests, the preloading started to pay off, reporting a stable 150K (preloaded), versus 200K+ (no preload).</p>

<p>My server is somewhat overloaded these days, but I decided to fire off some concurrency benchmarks anyway. Values are in reqs/sec. </p>

<table style="border: 1px solid black" cellspacing="0"><tr><th>server</th><th>Nginx+FastCGI</th><th>&nbsp;</th><th>Starman</th><th>&nbsp;</th><th>Plackup</th></tr><tr><td>dynamic content</td><td align="right">11.77</td><td>&nbsp;</td><td align="right">18.34</td><td>&nbsp;</td><td align="right">9.18</td></tr><tr><td>static content</td><td align="right">23656.65</td><td>&nbsp;</td><td align="right">6892.42</td><td>&nbsp;</td><td align="right">225.54</td></tr></table>

<p>&nbsp;</p>

<p>Starman does a really good job handling concurrency for dynamic content. For obvious reasons, Nginx static handling blows anything away. So a good setup would be Nginx for static content and Starman as the centralized application server. </p>

<p>Hopefully, more and more legacy Perl apps will migrate to Plack. For the meanwhile, Plack seems like an excellent choice for centralizing Perl webapp management. </p>]]>
        
    </content>
</entry>

<entry>
    <title>CPAN source syntax highlighting</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2010/06/cpan-source-syntax-highlighting.html" />
    <id>tag:blogs.perl.org,2010:/users/rodrigolive//66.606</id>

    <published>2010-06-03T19:39:26Z</published>
    <updated>2010-06-03T21:53:58Z</updated>

    <summary>I&apos;ve just updated a syntax highlighter bookmarklet I wrote a while back so that it now supports Chrome and Safari, besides Firefox. I find it useful to syntax highlight when I peek at a module&apos;s source code in the CPAN...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="bookmarklet" label="bookmarklet" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>I've just updated a syntax highlighter bookmarklet I wrote a while back so that it now supports Chrome and Safari, besides Firefox.</p>

<p>I find it useful to syntax highlight when I peek at a module's source code in the <span class="caps">CPAN </span>website. You may find it useful too. </p>

<p>To install it, create a new bookmark and paste the following code into the location field (sorry, I couldn't find a way to post this as a <code>javascript:</code> link in this blog):</p>

<script style="font-size:8pt" src="http://gist.github.com/424499.js?file=cpan_syntaxhigh_bookmarklet.js"></script>

<p>It will be even handier if you stick it in your bookmark toolbar.</p>

<p>Then view any <a href="http://cpansearch.perl.org/src/FLORA/Moose-1.06/lib/Moose.pm">module's source in <span class="caps">CPAN</span></a>, fire off this bookmarklet and voilà. </p>

<p>I've even thrown in some regex to allow linking from one module to the next. It works 90% of the time, moreless. </p>

<p>The code is actually kept <a href="http://github.com/rodrigolive/bookmarklets">here</a>. There you'll also find a lushier, Alex Gorbatchev's syntax highlighter version available, but I couldn't get it to work in Chrome nor Safari, only in Firefox. </p>

<p>It should be easy to tailor these bookmarklets to fancy your taste buds. </p>]]>
        
    </content>
</entry>

<entry>
    <title>Perl::Critic --praise</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2010/05/perlcritic---praise.html" />
    <id>tag:blogs.perl.org,2010:/users/rodrigolive//66.564</id>

    <published>2010-05-20T10:45:14Z</published>
    <updated>2010-05-20T15:16:54Z</updated>

    <summary>Wouldn&apos;t it be cool if Perl::Critic had a --praise option? It would tell programmers they have done something worth mentioning and throw in some inspirational kudos and uplifting recognition: $ perlcritic --praise script.pl Good! Filehandle is not a Bareword at...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="food_for_thoughthumoracme" label="food_for_thought humor acme" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>Wouldn't it be cool if Perl::Critic had a <code>--praise</code> option? </p>

<p>It would tell programmers they have done something worth mentioning and throw in some inspirational kudos and uplifting recognition: </p>

<pre><code>$ perlcritic --praise script.pl
Good! Filehandle is not a Bareword at line 4, column 1.  See page 202,204 of PBP.  (Cleverness: 1)
Nice use of comments in a regex. Maintainers will be happy at line 9, column 1.  See page 289 of PBP.  (Cleverness: 3)
Outstanding use of Moose roles at line 11, column 1.  (Cleverness: 2)
Named parameters are definitely easier to read at line 42, column 1 (Cleverness: 1)
Quite sure this 1 line of Perl translates to at least 12 in Java at line 58, column 1 
Oh yeah! You rock! at line 74, column 1.  (Cleverness: 4)
This package may be useful to the community. Make sure you upload it to the CPAN at line 74, column 1.  (Cleverness: 5)</code></pre>

<p>I think psychologists call it positive reinforcement. :)</p>]]>
        
    </content>
</entry>

<entry>
    <title>Test-driving MongoDB on a Moose</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2010/05/mongodb-fun.html" />
    <id>tag:blogs.perl.org,2010:/users/rodrigolive//66.556</id>

    <published>2010-05-16T18:16:07Z</published>
    <updated>2010-05-19T19:58:36Z</updated>

    <summary>I spent a few hours this last weekend trying out MongoDB, and its Perl driver. I was curious to see how I could put NoSQL databases to good programming use. MongoDB stroke me as a good contender for some experiments:...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="mongodbmoose" label="mongodb moose" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>I spent a few hours this last weekend trying out <a href="http://www.mongodb.org">MongoDB</a>, and its <a href="http://search.cpan.org/dist/MongoDB/">Perl driver</a>. </p>

<p>I was curious to see how I could put NoSQL databases to good programming use. MongoDB stroke me as a good contender for some experiments: it's easy to install, well documented and has an intuitive query language that reminds me of <a href="http://search.cpan.org/perldoc?SQL%3A%3AAbstract"><span class="caps">SQL</span>::Abstract</a> syntax. Besides, MongoDB <a href="http://www.idiotsabound.com/did-i-mention-mongodb-is-fast-way-to-go-mongo">allegedly is very fast</a> and scalable, which left me wondering how my configuration management apps could benefit from a backend switch from relational to a non-ACID document based DB like MongoDB, just like <a href="http://blog.boxedice.com/2009/07/25/choosing-a-non-relational-database-why-we-migrated-from-mysql-to-mongodb/">these people did for their server monitoring software</a>. </p>

<p>One of the things I liked the most about MongoDB is the fact that its Perl driver has a straightforward Moose-based interface. So I decided to take it out for a drive. Actually, my goal wasn't MongoDB's performance, nor its query language features. I was more interested in exploring how could MongoDB could become the base for a Perl object persistence framework out-of-the-box...Out of sheer curiosity and a chance for fun self-learning.</p>

<p>(I know <a href="http://search.cpan.org/dist/KiokuDB/">KiokuDB</a> is just sitting out there saying "well, try ME out then". It even has a <a href="http://search.cpan.org/perldoc?KiokuDB%3A%3ABackend%3A%3AMongoDB">MongoDB backend</a> prêt-à-porter, but I feared KiokuDB could add some unnecessary overhead, since it caters to a wide range of backends.  And, at this point, I just wanted to sketch something up myself to ruminate on.)</p>

<p>So I tried to model a very basic CD-Artist relationship. I came up with a use case: </p>

<pre><code>my $db = MediaDB-&gt;new;
# create the artist and store it
my $artist = Artist-&gt;new( name =&gt; 'Paco de Lucia' );
$db-&gt;collection('Artists')-&gt;insert( $artist );
# create a CD and store it
my $cd = CD-&gt;new( title=&gt;'Almoraima', artist=&gt;$artist );
my $cds = $db-&gt;collection('CDs');
$cds-&gt;insert( $cd ); 
# now retrieve it back
my $favorite = $cds-&gt;find_one({ title=&gt;'Almoraima' });
say $favorite-&gt;stringify;</code></pre>

<p>Even though the MongoDB driver relies on Moose (<code>Any::Moose</code> actually) for most of its classes (Database, Collection, <span class="caps">OID, </span>etc.), data is represented by an unblessed hashref, which in MongoDB lingo is called a <em>Document</em>. So I figured I needed to wrap some of these objects up to create a proof-of-concept storage framework that would also fit in a blog post. </p>

<p>First I needed a MediaDB class that would make the <code>get_collection</code> method bless collections into my own classes. With a little help from <code>MooseX::Declare</code>, I sketched up a "MediaDB" class:</p>

<pre><code>use MooseX::Declare;
class MediaDB extends MongoDB::Database {
	method BUILDARGS (ClassName $class: @args ) {
		my %args = (@args);
		$args{_connection} ||= MongoDB::Connection-&gt;new;
		$args{name} ||= 'mediadb';
		return \%args;
	};
	method collection( $name ) {
		return bless $self-&gt;get_collection($name), $name;
	}
}</code></pre>

<p>Now, to be able to store my objects as documents, I needed to serialize them into hashrefs, and vice-versa. Just unblessing them wouldn't take care of its nested objects, so I went shopping around the <span class="caps">CPAN.</span> I found this neat module, <a href="http://search.cpan.org/perldoc?MooseX%3A%3AStorage">MooseX::Storage</a>, which I had no idea about. It came quite handy!  </p>

<p>So I drafted up a serializing Document role for the MongoDB document common code: </p>

<pre><code>role Document {
	use MooseX::Storage;
	with Storage;
}</code></pre>

<p>That installs a <code>pack</code> and a <code>unpack</code> method for every Document-role consumer.</p>

<p>Now I went on to create the collection role for wrapping the two methods I needed for running my code, so that I could pack and unpack objects on the fly:</p>

<pre><code>role Collection {
	around find_one( HashRef $query, HashRef $fields? ) {
		my $doc = $self-&gt;$orig( $query, $fields );
		my $doc_class = $doc-&gt;{__CLASS__};
		return $doc_class-&gt;unpack( $doc );
	}
	around insert( HashRef $doc, HashRef $options? ) {
		return $doc-&gt;{oid} = $self-&gt;$orig( $doc-&gt;pack );
	}
}</code></pre>

<p>I'm not sure a Collection role is the best fit because I still need to <code>extend</code> <code>MongoDB::Collection</code> for every class I create. <br />
 <br />
As a nice collateral, when using MooseX::Storage I get MongoDB documents that have a <code>__CLASS__</code> attribute telling me how to unpack them back after fetching data. It has some drawbacks though, since it ties data and code representation.<br />
 <br />
Now that I had a very embryonic framework, I threw in my "schema" classes:</p>

<pre><code>class CDs with Collection extends MongoDB::Collection;
class Artists with Collection extends MongoDB::Collection;
class CD with Document {
	has 'title' =&gt; ( is=&gt;'rw', isa=&gt;'Str' );
	has 'artist' =&gt; ( is=&gt;'rw', isa=&gt;'Artist' );
	method stringify {
		$self-&gt;title . ', by ' . $self-&gt;artist-&gt;name;
	}
}
class Artist with Document {
	has 'name' =&gt; ( is=&gt;'rw', isa=&gt;'Str' );
	has 'cds' =&gt; ( is=&gt;'rw', isa=&gt;'CDs' );
}</code></pre>

<p>Here, an Artist also <code>has 'cds'</code>, an implementation bomb that I'll keep unused for the time being. </p>

<p>After running the use-case, this is how data looked in the DB:</p>

<pre><code>$ mongo 
&gt; use mediadb
switched to db mediadb
&gt; db.CDs.find()
{ &quot;_id&quot; : ObjectId(&quot;4bf032abe293830299931162&quot;), &quot;__CLASS__&quot; : &quot;CD&quot;, &quot;artist&quot; : { &quot;__CLASS__&quot; : &quot;Artist&quot;, &quot;name&quot; : &quot;Paco de Lucia&quot; }, &quot;title&quot; : &quot;Almoraima&quot; }</code></pre>

<p>True. This experiment taps into the untamed waters of object persistance. It left me with a sense of accomplishment: creating a leaner homemade persistence layer is doable with MongoDB -- except I still have many issues to chew over:</p>


<ul>
<li><strong>Relationships</strong>: instead of embedding documents into one another, sometimes it's best to <a href="http://www.mongodb.org/display/DOCS/Schema+Design#SchemaDesign-Embedvs.Reference">store them separately and link the two</a> -- good'ol normalization. But where would be the best place to enforce such "normalization"? How to avoid duplicating objects?</li>
</ul>




<ul>
<li><strong>Object IDs</strong>: the only reliable unique object id in MongoDB seems to be its auto-generated <span class="caps">OID</span>s, which are guaranteed to be unique across replicated servers. How should I handle them in my classes? How about auto-increment ids from my relational models? Could I live without them easy to read, incremental <em>numbers</em>? Should I create <span class="caps">UUID</span>s in my code? </li>
</ul>




<ul>
<li><strong>Performance</strong>: to serialize objects back and forth from the DB is expensive. What would be the most performant way of turning MongoDB documents into Perl objects, and vice-versa, without sacrificing too much? To just carelessly <code>bless</code> them, or to instantiate with <code>Class-&gt;new</code> every time?</li>
</ul>




<ul>
<li><strong>Approaches</strong>: what other difficulties and approaches on persisting objects into a document-based database like MongoDB can one come across?</li>
</ul>



<p>I figure KiokuDB authors have sorted out most of these questions. Maybe next weekend I'll dive into that.</p>

<p>But it does look promising. MongoDB feels very natural in Perl, maybe because the MongoDB team tend to blaze the trail by creating and maintaining their own language driver implementations, something uncanny for most new and established databases out there.</p>]]>
        
    </content>
</entry>

<entry>
    <title>compiling nginx on aix</title>
    <link rel="alternate" type="text/html" href="http://blogs.perl.org/users/rodrigolive/2009/11/compiling-nginx-on-aix.html" />
    <id>tag:blogs.perl.org,2009:/users/rodrigolive//66.39</id>

    <published>2009-11-24T11:04:54Z</published>
    <updated>2009-11-25T09:45:18Z</updated>

    <summary>Another working day in AIX... This time trying to compile a nginx server to run on top of Catalyst. This is what has worked for me: $ ./configure --prefix=/opt/nginx --user=nginx--group=nginx \ --without-http_rewrite_module \ --without-http-cache --with-zlib=/opt/tmp/zlib-1.2.3 $ make Of course, first...</summary>
    <author>
        <name>rodrigolive</name>
        
    </author>
    
    <category term="aix" label="aix" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.perl.org/users/rodrigolive/">
        <![CDATA[<p>Another working day in <span class="caps">AIX...</span> This time trying to compile a nginx server to run on top of Catalyst.</p>

<p>This is what has worked for me: </p>



<pre>
$ ./configure --prefix=/opt/nginx --user=nginx--group=nginx \
--without-http_rewrite_module \
--without-http-cache --with-zlib=/opt/tmp/zlib-1.2.3

$ make
</pre>



<p>Of course, first you need to get <code>gcc</code> from the <span class="caps">IBM</span> Linux Toolbox. And download the zlib source, as the nginx make will attempt to build the zlib libs. </p>]]>
        
    </content>
</entry>

</feed>
