Thursday, 30 April 2015

My March & April CPAN PR Challenge dists

As I got ready to blog about my PR Challenge assigned dist for April, I realized I had forgotten to blog about my last month's assigned dist, so I have decided to write a joined march/april report :)

March distribution: Web::Library::UnderscoreJS


This neat module by Marcel Grünauer is a wrapper for the Underscore JavaScript library, which itself provides over a 100 functional helpers and goodies for your frontend programming like function binding, JS templating, quick indexes, and much more.

The wrapper comes from Web::Library, a general manager for client-side dependencies. Say you have a web application. You spawn the Web::Library singleton and mount the libraries you want to use (Underscore in our case):

    my $library_manager = Web::Library->instance;
    $library_manager->mount_library({ name => 'UnderscoreJS' });


Then you set the include_paths() from the instance as directories to search for static files. In Catalyst, this can be achieved with Catalyst::Plugin::Static::Simple, like so:

    __PACKAGE__->config(
        'Plugin::Static::Simple' => {
            include_path => [ $library_manager->include_paths ] },
        ...
    );


Then pass the instance to your templates and call the appropriate methods to print the required CSS/JS lines:

    <head>
        ...
        [% web_library.css_link_tags_for('UnderscoreJS') %]
   
</head>
    <body>
        ...
        [% web_library.script_tags_for('UnderscoreJS') %]
   
</body>

My pull requests for this distribution involved bumping up the copyright year, some minor pod formatting issues, updating the UndescoreJS library versions (up to 1.8.2), and adding a Travis-CI code badge. I also investigated some CPAN Testers failure reports for this distribution on MS Windows, but they turned out to come from Web::Library itself. Nevertheless, I also send a PR with a fix and another one that reduced the minimum perl version to 5.6, which was asked in an open issue.


April distribution: Mojolicious::Plugin::ServerStatus


This is a plugin for Mojolicious that shows server status information, similar to Apache's mod_status. It is based on the general Plack::Middleware::ServerStatus::Lite middleware and works on multiprocess servers like morbo and hypnotoad. It's not able to monitor keepalive sessions and network I/O wait, but it still gives some nice output in different formats.

All you have to do is load the plugin and tell it which route path to render. Optionally, for security, you can set which IPs to allow:

    plugin 'ServerStatus' => {
        path => '/server-status',
        allow => [ '127.0.0.1', '192.168.0.0/16' ],
    };


That's it! After the server is up, all you have to do is query the proper path:

    % curl http://server:port/server-status
    Uptime: 1234567789
    Total Accesses: 123
    BusyWorkers: 2
    IdleWorkers: 3
    --
    pid status remote_addr host method uri protocol ss
    20060 A 127.0.0.1 localhost:10001 GET / HTTP/1.1 1
    20061 .
    20062 A 127.0.0.1 localhost:10001 GET /server-status HTTP/1.1 0
    20063 .
    20064 .


You can also ask for JSON output format:

    % curl http://server:port/server-status?json
    {"Uptime":"1332476669","BusyWorkers":"2",
     "stats":[
       {"protocol":null,"remote_addr":null,"pid":"78639",
        "status":".","method":null,"uri":null,"host":null,"ss":null},
       {"protocol":"HTTP/1.1","remote_addr":"127.0.0.1","pid":"78640",
        "status":"A","method":"GET","uri":"/","host":"localhost:10226","ss":0},
       ...
    ],"IdleWorkers":"3"}


Unfortunately, this distribution didn't have any contents in the main github repository, so instead of making several branches off of master, I used my own master branch and made one commit per change in a single pull request. The first commit of course was just a sync between the repository and the version available on CPAN. Other commits included updating the README, setting up the proper dependencies (which should fix current failure reports from CPAN Testers), adding a Changes file which was missing from the dist, and some minor pod fixes.

That's it! Hopefully those commits and pull requests will be useful to the authors (and users too). And now I can't wait to see what Neil Bowers have picked for me next month :)


Saturday, 14 March 2015

How to add online code badges to your Perl projects


If you hang around Github you might have seen a lot of projects adding extra information to their README files in the form of badges, like so:

screenshot of badges shown on Clone's README file













Not only do they make your project's Github page look cooler, they also help developers, from curious potential users to regular contributors, easily spot how active and healthy is the code.

Wanna join in on the fun? There are several free code badges out there for you to use, and these are the ones (that I know of) that work for your awesome Perl code! \o/

Travis CI


Travis CI is a continuous integration service used to build and test projects hosted on Github. They'll let you know whether your code builds and tests pass in many different versions of perl (but, unlike CPAN Testers, they'll do it in only one platform). Using their service is super simple:

1. Go to the Travis CI homepage and sign in with your Github account. It's the big link in the top right corner of the page, you can't miss it :)

2. If this is your first rodeo, you'll see Travis CI asks for some permissions on Github. You must allow it to proceed. They have outlined the whys and hows if you're feeling cautious.

3. Go to your Travis CI profile page and wait for all your repositories to sync. Once they're all listed in there, it should look something like this (with, of course, your own name, groups and projects):

 4. See that "on-off" switch next to each of your repositories? Just flick the ones you want to have a Travis CI report. We're almost done!

5. Add a file named .travis.yml to the root of your project repository (note the "." in front of the filename!). It should contain valid YAML with the main language and the different versions of Perl 5 you want to test against. For example, if you want to test against 5.14 and 5.20, your ".travis.yml" should look like this:

language: perl
perl:
  - "5.14"
  - "5.20"

If you need any extra information or customization of your perl builds, just read Travis CI's Perl specific documentation. Note that if something goes wrong (e.g. you make a typo in the filename or its contents), Travis will assume you're testing against the current stable version of Ruby, which is definitely not what you want :)

A few moments after you commit it to your repository and push it to Github, go back to your Travis CI profile page and you should be able to see the build results! If you skipped a step and added the ".travis.yml" file to your repo before enabling the project in the Travis CI page, just push any commit to trigger it.

6. Badge time! Make sure your README file is in Markdown - just rename it to README.md and adjust it as you see fit (it's also a great way to make your project stand out while still making it readable as plain text). Then go to your Travis CI profile and click on the project you want to add the badge. You should see the badge right next to the project's name. Click on it and it's going to let you copy the badge for your project in several formats:



Choose "Markdown" and paste it on your README.md file. The one from Clone, as you can see from the picture above, looks like this:

[![Build Status](https://travis-ci.org/garu/Clone.svg?branch=master)](https://travis-ci.org/garu/Clone)

After pushing your changes, go to your project's Github page and see the badge in all its glory!

Coveralls


Now that we have Travis CI doing some tests for us, how about we get some test coverage reports also? That's where coveralls.io comes in!

1 & 2. Just like we did with Travis CI, go to the Coveralls home page and sign in with Github, granting them access to your repositories.

3. The Coveralls repository page will list all projects being analyzed for coverage, and now is probably the time to click the "add repos" button on that page and add the ones you want coverage analysis of.

4. Adjust your .travis.yml file to add code coverage. Coveralls is engine agnostic so we'll use the not nearly enough praised Devel::Cover suite to do the hard work, together with the Devel::Cover::Report::Coveralls interface. Basically, Travis CI gives us a lot of granularity while building and testing our projects, so we tweak it to include coverage commands in the appropriate build steps.

There are a few ways to go about it: in the manual way we export the environment variables we need and install the coverage dependencies. For instance, we could update our file above to look something like this:

language: perl
perl:
  - "5.14"
  - "5.20"

install:
     - export RELEASE_TESTING=1 AUTOMATED_TESTING=1 AUTHOR_TESTING=1 HARNESS_OPTIONS=c HARNESS_TIMER=1
     - cpanm --quiet --notest Devel::Cover::Report::Coveralls
     - cpanm --quiet --notest --installdeps .

script:
     - PERL5OPT=-MDevel::Cover=-coverage,statement,branch,condition,path,subroutine prove -lrsv t
     - cover

after_success:
    - cover -report coveralls


in the automatic way, we delegate most of the work to some fine-tuned helper scripts created just for Perl projects on Travis and Coveralls. The same original .travis.yml file would, in this case, look like this:

language: perl
perl:
  - "5.14"
  - "5.20"
matrix:
  include:
    - perl: 5.20
      env: COVERAGE=1
before_install:
  - eval $(curl https://travis-perl.github.io/init) --auto


To me this one looks much easier to read, as most of the complexity is enclosed in the "init" script of the well maintained travis-perl project. I highly recommend it. In fact, after you get it right for your code, I suggest you go read their helper intro and play with some settings, you won't regret it. Also, check out Moo's .travis.yml file for a glimpse of all the cool stuff you can get, from testing against blead perl to reporting on a specific irc channel!

5. Now that your commits are tested on Travis CI and reported by Coveralls (mind you, it might take several minutes for a build coverage to show up, and they only start after you push to Github *after* having activated Coveralls and pushed your .travis.yml file), let's put a badge on your README!

On the project listings on Coveralls, click on the project to go to its page, and you should see a badge right at the top, with a "BADGE URLS" link next to it. Click on that link to copy your badge in several different formats, like so:


Put the markdown code on your README.md file next to the Travis CI badge (or wherever you see fit) and that's it!

Version badge


This one really comes in handy for Github, as it lets your users know exactly what's the current stable version on CPAN and how to get it, and it's also by far the easiest to set up: just go to the Version Badge link for Perl projects and type in the name of your target dist (note that it's The-Distribution-Name, not The::MainModule::Name). Once you click on "Find", it's going to give you the badge in several different formats ready for use:


Showing your badges on MetaCPAN


Now that your README.md is all shiny and colorful with badges, your project's Github page is starting to look even cooler than the MetaCPAN page, and that's just not cool. MetaCPAN's web interface is awesome and it will look even better when you put your brand new badges in it, so let's get on with that.

Perl's Pod format allows us to to specify sections that will only show when a given format is supported. For instance, if you write this in your pod:

=for html
<img src="http://example.com/path/to/some/image.png" />

Then this block will render the image when the renderer supports html (like the MetaCPAN web interface), and not do anything on renderers that don't support it (like your command line "perldoc"). Pretty cool, right? Graphic modules and tutorial-like documentation have been taking advantage of this feature for years, and we should too!

So go to the links above and find the HTML version of the badges, then put them in a "=for html" paragraph at the top of your Pod. For the Clone module they look like this:

=head1 NAME

Clone - recursively copy Perl datatypes

=for html
<a href="https://travis-ci.org/garu/Clone"><img alt="Build Status" src="https://travis-ci.org/garu/Clone.png?branch=master" /></a>
<a href="https://coveralls.io/r/garu/Clone?branch=master"><img alt="Coverage Status" src="https://coveralls.io/repos/garu/Clone/badge.png?branch=master" /></a>
<a href="https://metacpan.org/pod/Clone"><img alt="CPAN version" src="https://badge.fury.io/pl/Clone.svg" /></a>

=head1 SYNOPSIS 
 
   ... 

As soon as you push the new version to CPAN, you'll see the badges right there on MetaCPAN!
















If you are too lazy to go back and copy the HTML version from all those sites, just run the following one-liner on your README.md to print the html version of the markdown links in there:

perl -nE 'BEGIN{ say q(=for html) } say qq(<a href="https://www.blogger.com/$3"><img alt="$1" src="$2" /></a>) if /\[!\[([^\]]+)\]\(([^\)]+)\)\]\(([^\)]+)\)/' README.md

Then copy the block to your pod and make a new CPAN release :)

That's all there is to it. Have fun with your badges! \o/

(oh, and let me know if you find any other Perl-related badges you know of)

Saturday, 28 February 2015

My February CPAN PR Challenge: Template::Plugin::Autoformat

For this month's CPAN Pull Request Challenge I was assigned with  Template::Plugin::Autoformat, a module that lets you easily format text and numbers in your Template Toolkit templates, using Damian Conway's excellent Text::Autoformat. If you ever needed to adjust text right/left/center justification, alignment, capitalization, bullets, indenting, without being able to resort to CSS - for example, if your templates are not for HTML or if said text is inside a <pre> tag - this module could make your life much easier!

A different challenge


It was an unusually busy month for me and I didn't get a chance to tackle it until yesterday - I even got Neil's "One week left!" email reminder, which was nice. Even so, I figured it would be ok, because the original PR Challenge email mentioned this module had several CPAN Testers FAIL reports, CPANTS issues, and hadn't seen an update in several years.

Except now when I finally checked it out and it saw it was last released a month ago, had zero failures on CPAN Testers, no open issue on either RT or Github, no CPANTS issues, pristine documentation, even complete META resource information! I thought I had been assigned to a dist needing help, but instead what I was looking at was a stable and well-maintained one.

As it turns out, Template::Plugin::Autoformat hadn't seen a single update between 2008 and 2014, when it was adopted by Peter Karman. Peter started making several developer releases until he was satisfied with the results, and released a stable version in January 2015 (which is probably why it was still in the CPAN PR Challenge's list, created prior to said release). His new version fixed all open issues, had a great test coverage and felt like one of those modules that do one thing and do it very well.

And now I had 1 day to send a nice pull request to a module that looked like it needed no pull requests, or I'd lose the challenge :X

Starting small


Okay, instead of being caught in analysis paralysis, I cloned the repo and looked for low hanging fruits. Turns out there were some!

  1. The copyright year was still 2014. This is the first place I look because it's also the first place I overlook in my own projects :) It's such a simple patch that it almost feels like cheating, but you have to start somewhere, right? Done.
  2.  The README was not in Markdown. I love markdown READMEs, because they make the Github project page look *so* much nicer without compromising reading it from the terminal. Even better, "README.md" is fully supported by PAUSE & CPAN \o/. As I was making the conversion, I noticed the README's contents were just a copy of the pod, so I tweaked it a bit to include installation instructions and just a teaser pointing to the full docs, online and via perldoc. This is a good thing for the developer too, as there's less duplicate content to worry about. Done.
  3. The distribution did not declare a minimum perl version. CPANTS Kwalitee is a terrific free service for the Perl community, letting users and authors know whether a given module passes or fails several quality assurance metrics. While, as I mentioned before, Template::Plugin::Autoformat passed all core CPANTS metrics, this extra metric was not being met. In fact, it was the only extra metric not being met. Thankfully, the excellent perlver tool makes it very easy to find the minimum perl version for your module or app. It reported 5.6.0 as being the minimum version so, after a very simple addition to the Makefile.PL, I had my third pull request of the night.
  4. The Changes file was not fully compliant with the CPAN::Changes spec. This was also an easy one to fix, since the only standing issue was formatting the release dates to something CPAN::Changes would understand. Next!
  5. Test coverage was almost 100%, but not exactly 100%. This is another great way to help other projects: check the code coverage and see if you can improve it in any way. In this case, after running the great cover tool, I found out it had 100% statement coverage, but 50% pod coverage and 91.6% branch coverage. The pod coverage was actually a mistake - there was a private function being counted as public. Adding the missing branch test was also pretty straightforward. After the patch, Template::Plugin::Autoformat got 100% coverage in everything - which is pretty cool!
  6. The "NAME" key in Makefile.PL had the distribution name, not the main package's name. Now, the builder is clever enough to do the right thing, but nevertheless it was triggering a warning every time I ran "make" - which was quite a bit while I played with test coverage. Easy fix again, just s/Template-Plugin-Autoformat/Template::Plugin::Autoformat/ and I was done for the night.
So after a couple of hours having fun with Template::Plugin::Autoformat, I had 6 PRs to show for on the PR Challenge. Woot! Best of all, just a few hours later Peter Karman merged all my PRs and made a new release \o/

Thursday, 29 January 2015

My CPAN Pull Request Challenge for January: Fuse


So! Back in December I subscribed to Neil Bowers' CPAN Pull Request Challenge. In a nutshell, throughout 2015 every participant will get an email in the first days of each month with a CPAN module that needs a little bit of love, and we have until the end of the month to submit at least one pull request for that module's Github repository.

The module I got was "Fuse".

What is Fuse?


I must admit to my ignorance as I have never heard of Fuse before. So the first thing I did was jump to Fuse's page on MetaCPAN and have a look. Fuse is a Perl interface to the FUSE library (Filesystem in USErspace), and lets you implement filesystems in Perl. Wow! That's pretty cool, right?!

Where to start


If Neil was pointing me to Fuse, it means there's probably work for me to do. So what I did was read the documentation, CPAN Testers reports, open issues and the Github page. Then I downloaded the source code and grep'd for tags like "FIXME" and "TODO". In the end it was a very well-thought distribution and I think the authors did - and are still doing - a pretty nice job. Still, this is what I thought I could help with:
  • The (external) FUSE kernel/lib doesn't seem to be linked anywhere in the main doc, just on the README;
  • The SYNOPSIS and DESCRIPTION could be a bit more verbose - maybe I'm just not used to the FUSE library, but I felt a lot was being taken for granted;
  • The README (displayed on github) doesn't point to a lot of useful places in the Perl-sphere (other than the examples and how to install);
  • There is no license information on the main pod - though it's there on the META resources;
  • The latest version is not indexed for some reason;
  • There are a lot of FAIL and UNKNOWN reports on CPAN Testers.

First things first


There were several small things for me to attempt here, so rather than making a huge bundled Pull Request for Fuse, I chose to compartmentalize them into smaller, separate, PRs. This way the authors'd probably be more comfortable reviewing my changes and I wouldn't depend on all of them being accepted. This is super easy with git and github: just create a branch from master and make the pull request from your specific branch to the author's master. This will let you easily go back to their master (instead of to the one you might have changed) and work on something else independently.

1. Doc fixes

Since I was really short of free time this month, I decided to start with the lowest hanging fruit. So I created a "garu/doc_patches" branch and tried my best to improve on the existing documentation. I expanded the SYNOPSIS, put external links whenever I missed them, and did some minor tweaks here and there with the pod formatting to improve readability. I also moved the README to markdown so it looks awesome on Github while still being nice to read on the console. When I was satisfied, I sent out the pull request.

This was great and really helped me understand what Fuse was all about and how to use it. I recommend anyone trying to learn and contribute to a project to first read the docs and try to improve them whenever you find something you don't quite understand. Most of the time the ones writing the documentation are too familiar with the code and API so they can take a lot of it for granted.

2. WHY U NO INDEX?

There was an open ticket saying 0.16.1 was not indexed. Upon further investigation, I saw versions 0.16_01 and 0.16.1 were in fact indexed, but available as if they were older releases. Why weren't they showing up as the latest? I went to #metacpan on irc.perl.org and asked around.

As haarg++ pointed out, Fuse inadvertently mixed single dotted and double dotted version formats, releasing '0.16' (instead of '0.16.0') and '0.16.1'. When the CPAN indexer compares version numbers, 0.16.1 becomes 0.016001 and plain 0.16 becomes 0.160000, and as such, "0.16" is indeed greater than "0.16.1".

While I believe version numbers should be boring, I understand why some people go for the major.minor.revision semantic versioning format. So I went ahead and filed a pull request bumping up the version to 0.160.2, and another one that bumps it to 0.17. Both numbers are greater than 0.16 so they'll definitely show as latest, and the authors can just pick whichever format they prefer and discard the other PR.

3. Making tests pass

Finally, I noticed that all the UNKNOWN tags on CPAN Testers were there because FUSE was not installed. Implementing an Alien::FUSE module seems like a good idea, but it is a bit out of scope for the PR Challenge and the limited free time I had. So I went on and installed FUSE for OS X using homebrew. For my surprise, the Makefile.PL was still not finding it:

    $ perl Makefile.PL
    Cannot build for platform: darwin
    Please install OSXFUSE from http://osxfuse.github.com/

I checked Makefile.PL's source and found out what was wrong: it's trying to find libfuse using the "pkg-config" tool. Although "pkg-tool" is rather ubiquitous in major Linux systems, my OS X did not have it. So a made another PR that checks for the existence of either 'pkg-config' or 'ppkg-config' (a Pure-Perl alternative to 'pkg-config' available with the excellent PkgConfig CPAN module) early on the Makefile.PL, dying with an explanatory message if none are available. There's even an opportunity here to simply depend on PkgConfig and use the module version of the commands instead of relying on external "(p)pkg-config" tools, but I thought I rather wait a bit and see how well received this change is first.

Now the module compiles on OSX, but I still can't make the tests pass. I dug a bit and found some commands like read_buf and write_buf are required for testing, but are only available in libfuse versions 2.9.0 and above. However, osxfuse seems to use a different version equivalence and the latest version (released just a month ago) is still 2.7.4. I couldn't find an osxfuse <=> libfuse version equivalence, and because of this, the Fuse module doesn't create the proper bindings for such functions and the tests fail. There might be other issues still, but I stopped there, filing a ticket and hoping someone else will pick it up where I left off.

Wrapping up


I had a lot of fun finding out about Fuse and playing with it. By the end of January I was able to file 4 pull requests and 1 RT ticket to the main repo. I'm sad I wasn't able to get the tests to pass on OS X, but hopefully someone else will read this and be inspired :)

I'd like to thank Neil for this awesome PR Challenge idea, Graham "plicease" Ollis for the great PkgConfig module and for quickly replying to and merging the small changes I proposed that allowed me to use it on Fuse, and Graham "haarg" Knop and everybody from #metacpan for their amazing support.

Also, of course, a huge thank you to Dobrica Pavlinušić, Derrik Pates, Mark Glines and the entire Fuse team for such a great module, and for allowing me the opportunity to be a part of it.

Can't wait to see which module I'll get next month! :)

Sunday, 6 April 2014

Perl Dancer on Media Temple (gs)

Recently I was asked by a friend to install Dancer on Media Temple Grid Service (gs), and after I couldn't find a tutorial to do so, I decided to write one myself :)

Hopefully, you'll be able to get up an running in seven easy steps. I am assuming you know how to use remote *nix shells via ssh, editing files, etc.

You should be aware that none of this is really supported by Media Temple so if you run into trouble or if something changes on the grid, you're on your own. For anything other than simple dynamic websites (in PHP), Media Temple recommends their more robust (and expensive) dedicated virtual (dv) server solution.


Step #1 - Login with SSH on Media Temple


At the time of this writing, Media Temple's GS runs on Perl 5.10.1, which is not very recent, but is good enough for us. Teaching you how to setup ssh is a bit beyond the scope of this tutorial, but thankfully Media Temple provides a very nice ssh guide.

Media Temple runs Apache, but error logging is not enabled by default, so you should probably enable error_log on Media Temple. If you run into any trouble on the following sections of this tutorial, following the error log (by something like running "tail -f $HOME/../../logs/error_log" on another window) is definitely going to help you!

Step #2 - Sanity check


After you log in, you'll see Media Temple's domains come with 2 directories (at least that's how they showed up to me): "cgi-bin" and "html". This structure implies that dynamic content should be under cgi-bin and static content should be under "html". Just to make sure everything is sane, up and running, let's create a very simple pure-perl script and place it under the "cgi-bin" directory:

    #!/usr/bin/perl
    # ^^^ Media Temple requires the shebang!
    use strict;
    use warnings;
    print "Content-type: text/html\n\n";
    print "Hello, Media Temple";

Save this file as "test.cgi" and set permissions to 700 (required, apparently):

    chmod 700 test.cgi

The owner of the file should be the main account for that domain as well:

    chown $USER:$USER test.cgi

(where $USER is the username of the main account)

You should also make sure the cgi-bin directory's permissions is set to exactly 755, otherwise things won't work.

Now try and run it from your web browser, by opening "http://your-domain/cgi-bin/test.cgi", where "your-domain" is your Media Temple domain. If you see an "Internal Server Error" message, try checking out your error_log and review the previous steps (for example, make sure the script is exactly as it is above, and all permissions are right).

Step #3 - Installing Perl modules on Media Temple (mt) Grid


Media Temple provides a Knowledge Base tutorial on how to install Perl modules on the Grid, but it only lists manual installations which are boring and error prone. After all, we live in the future, where it's simple to install Perl modules as a user on a shared hosting service. All you have to do is type the following on your server's command line (it's just one line, and you can cut and paste as it is):

    curl -L http://cpanmin.us | perl - --local-lib=~/perl5 local::lib App::cpanminus && eval $(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)

 This is going to install local::lib and cpanm into your home directory, and enable you to install any other modules there by simply typing "cpanm My::Module" (where "My::Module" is, of course, the name of the module you want to install).

While you're at it, remember to add the line:

    eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)

to your ~/.bash_profile file (create it if necessary, of course).

Step #4 - Installing Dancer (and everything else!)


After the previous step, installing Dancer is easy as pie:

    cpanm Dancer

Done! Let's also install Plack::Runner, in case we need it:

   cpanm Plack::Runner

You can take this moment to install all your app's dependencies. For instance, my friend's app is also using Template Toolkit and DBIx::Class

   cpanm Template DBIx::Class

Step #5 - Making a default Dancer app (or moving your current one)


If you already have a Dancer app, just move it to Media Temple's domain directory. For example, if your Dancer app is called "my-app", move it to:  "/home/XXXXX/domains/mydomain.com/my-app" (replacing XXXXX and "mydomain.com" to the appropriate values for your grid account).

Otherwise, just go there (/home/XXXX/domains/mydomain.com) and create your Dancer app by typing "dancer -a appname".


Step #6 - Change "html" to a symlink:


Your Dancer app's base directory is usually "appname/public", but Media Temple forces you to have an "html" directory as base. So we remove the original (just rename it instead if you're not brave enough :) and create it again, only this time as a symbolic link to "appname/public":

    cd ~/domains/mydomain.com
    mv html html_old
    ln -s myapp/public html

Step #7 - Add the appropriate .htacess files


Media Temple runs Apache on the grid server, so we control what runs with .htaccess files. This is the content we put in the file "myapp/public/.htaccess":

    # Allow /public to run Perl code
    Options +ExecCGI +FollowSymLinks
    AddHandler cgi-script .cgi .pl


    # Initialize mod_rewrite
    RewriteEngine On
    RewriteBase /
 

    # If file doesn't exist on the server, dispatch!
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)$ dispatch.cgi/$1 [L]



At this point I bumped into trouble. Media Temple's Apache doesn't seem to let Perl see variables such as PERL5LIB. There's likely a clean way to fiddle with "SetEnv" on .htaccess to fix this (let me know if you get it working!),  but what I did was add a "use lib" line on top of public/dispatch.cgi, like so:

#!/usr/bin/env perl
use 5.10.0;

# Media Temple doesn't read our environment
use lib qw(
   /home/XXXXX/users/.home/perl5/lib/perl5
   /home/XXXXX/users/.home/perl5/lib/perl5/x86_64-linux-gnu-thread-multi
);

That's the basic setup! If everything went well, you should be able to point your web browser to your domain and see Dancer's main page \o/

You should notice we're running Dancer on standard cgi, which means it's going to be somewhat slow, specially when loading modules.

Appendix: Perl with FastCGI on the Media Temple Grid


Sadly, Media Temple doesn't seem to provide proper FastCGI support for Perl - at least from my understanding. Of course, that didn't stop me from trying, so here's what I did:

First, enable PHP FastCGI on the GS. It should have created a .htaccess in your domain root (i.e. the parent of your "html" dir) with some basic FastCGI settings. I changed them to this:

    # BEGIN (mt) controlled settings
    <IfModule !mod_fcgid.c>
      AddHandler cgi-script .cgi .pl
    </IfModule>
    <IfModule mod_fcgid.c>
      AddHandler fcgid-script .fcgi
      <Files *.fcgi>
        Options +ExecCGI
      </Files>
    </IfModule>
    # END (mt) controlled settings


(this is basically their default script, with "php" replaced with "cgi", "pl" and "fcgi").

Then I went to our own html/.htaccess file (it's a symlink to myapp/public/.htaccess, remember?) and replaced "dispatch.cgi" with "dispatch.fcgi" on the rewrite rules described in step 7 above. Finally, I updated the file "dispatch.fcgi" to include the same "use lib" I did for dispatch.cgi, deleted dispatch.cgi and voilá :)

Done!


Again, Media Temple recommends that any serious app go to their dedicated virtual server (dv) solution. Still, the current gs setup should be enough for you to have some fun and play around with possibilities before moving to a more expensive plan.

There are tons of other cool things you can do, such as creating remote git repositories and making hooks to do automatic deploys, but that's a bit out of the scope of this tutorial :)

Have fun, and happy Perl hacking!

Monday, 8 July 2013

Scala for Perl 5 Programmers



Maybe you want to contribute to the Moe project. Maybe you want to improve your Perl programming skills by stepping out of your comfort zone - after all, learning new languages is generally considered A Good Thing™. Maybe you're doing it just for kicks, or as a second language, or... well, it doesn't really matter.

When I decided to learn a bit of Scala earlier this year, I was devastated to find that most tutorials are for people coming from Java. Well, I'm not really a Java person, so I decided to write a Scala tutorial for people with mostly a Perl 5 background. As I was learning (and writing), I realized Scala feels very Perlish, with anonymous methods, more than one way to do things, weird operators and even a context variable "_" (looks familiar?)

If you're interested, take a look and let me know what you think. It's all on Github, written in their flavored Markdown syntax. And if you find any mistakes - hey, I'm learning too! - or if you have interesting additions to the tutorial, just send me a pull request :)

Happy hacking!

Saturday, 29 June 2013

YAPC::NA 2013 ROCKED!

[Sorry for the delayed post. I wanted to release this right after the YAPC::NA but just a few days after I got back to my country we got kinda in the middle of something.]

In the live music capital of the world, over 400 Perl hackers from 18 countries got together a few weeks ago for Yet Another Perl ConcertConference. If you're not familiar with Perl and its amazing culture, you might think I'm exaggerating as I struggle to find the proper adjectives to describe just how remarkably incredible it was. So, instead, I'm going to describe a few of the things that happened there and how they unfolded from my own perspective. Since everyone's experience is a bit different, I look forward to seeing your post too!

tl;dr - If you've never been to a YAPC before, I strongly recommend you do so. You'll never forget it.

Nothing Like a Little Rock 'n' Roll Before The Conference Starts

I really enjoy Rock/Jazz/Blues, so Austin is one of the great places for me to be. I was a bit sad though knowing that Monte Montgomery, one of my all-time favorite guitarists, and one pretty active in the Austin scene, was not giving a concert while I'd be in town. I even bitched about it on Twitter, like you're supposed to do. And guess what? Just a couple of days before my trip, and two weeks after my rant, Nutty Brown Cafe replied to my tweet and made my trip even more worthwhile!


I was really excited, and it was even more than I hoped for! Nutty Brown is a great place, with great beer and an awesome open air stage in the back. And Monte is even better live! Seriously, I tried to find the person behind the @nuttybrowncafe to thank her (they told me it's a "she") personally, but she wasn't there at the time. I dreamed of seeing this dude perform live for years, and if not for that single tweet I might never have. I guess this whole social network thing works, eh?

But I digress. Back to the conference!

Arrival Dinner

The arrival dinner was at a place called the Hula Hut, serving us some great drinks and TexMex food "with a surfer twist". I'm not really sure what that means but food was delicious, and I think everybody had a great time. I know I did!


Hook 'em Horns!

The venue was in the University of Texas, home of the Texas Longhorns, a very engaging athletics program for students. Everywhere you looked you'd see someone wearing one of their orange t-shirts. It always amazed me how the USA is so into sports (not just american football, but every single sport they can find), and now I got to see that passion first hand. It might be a no-brainer for you, but as a brazilian, I know my country mostly just cares about football, and even so we don't have our college competitions shown on prime time (or any time, for that matter).


Also, as a metal fan, the "Hook 'em Horns" hand gesture was quite familiar (and a bit funny to see in statues and such).

Christmas in June

One of the reasons I look forward to the YAPC every year is because I get to see a lot of the good friends I made over the years in the Perl community, friends I share a lot in common with but whom I get to see only once or twice a year, if I'm lucky.  Being able to hang out with people like sawyer, auggy, ribasushi, perigrin, sartak, ingy, liz, wendy, apeiron, abigail, frew, dha, stevan, genehack, rjbs, jayhannah, hobbs, karen pauley, hugmeir, mdk, mst, nperez, drolsky, jim keenan, nick patch, paul mantz, scrottie and so many others... just being next to these great, fun and sparkling minds already makes this giant trip worthwhile.

I also had the opportunity to meet other great people, some of which I only knew online. Tobias Leich (FROGGS) has been a partner in crime in the Perl SDL project for several years now, but this was the first time we met in person. He showed me a few pictures of his kid and we talked about some of his cool new Perl 6 hacking. He's not only a great guy but an excellent hacker, even more awesome in person than I expected - and I have pretty high standards! =P

I also spotted the great Tokuhiro Matsuno next to (the also great) Xaicron on the first day and introduced myself, since I'm a big fan of his stuff. I actually mixed them together at first (ごめんね!!) but I blame it all on Xaicron's remarkable orange glasses, which I remembered from his gravatar. I also let Matsuno-san know about a recent issue some people were having when trying to report test results for his Minilla app to CPAN Testers through cpanm-reporter, and he fixed it on the same day! Wow! A few days later at the speaker's dinner I'd be laughing with them (and Karen Pauley, and Shawn) about some very weird (miss)translations we have between languages such as portuguese and japanese. I only talked to them briefly but I hope they've has as much of a good time as I had, and hope to see them again (and even more Japanese developers) on future editions of YAPC::NA.

Other great people I met there for the first time whom I'd only talked to online included Naveed "Ironcamel" Massjouni and Al Newkirk. Al was in fact one of the first people I interacted with over on irc.perl.org, so I was really glad to finally meet him. Oh! And at last I got to met Karen Etheridge, who's been stalking me online for several months now. Fine, fine, I was the one stalking her - it was driving me mad that all of a sudden she was the release manager of a ton of modules I loved and used on a daily basis and yet I had no idea who she was! Turns out she's not only a great developer but also a very nice person, so yay!

I really can't explain it. There's something about the Perl community that feels like family - for better or worse. So, to me, attending the YAPC is like walking into one big Christmas party. I just love it! :-)

As any family this big, I missed a lot of people who couldn't be there this year, and hope to see them in other conferences or back at the YAPC::NA next year!

CGI.pm is Dead. Long live CGI.pm!

One of the (many) interesting highlights of this year's conference was the whole discussion of CGI.pm - specifically whether it should be removed from the Perl 5 core or not. SawyerX did a lightning talk making a strong case for "killing" CGI.pm. Perrin Harkins, on the other hand, came up on stage with a lovely tribute to all the great stuff that CGI.pm acomplished back in the day and bid it a fond farewell from the core. Later on the conference, Casey West went totally the other way, not accepting CGI.pm's fate/doom in a very funny rendition of his arguments which included sarcasm, the shortest wiki in the world and doing a handwalk on stage wearing nothing but a swimsuit!

The Keynotes

Mark "mdk" Keating gave the first keynote of the conference which secured his Diva status in the Perl community with a brilliant, brilliant talk called Perl of Christmas Past, in which he dwells on the history of the language and other fun facts. For example, did you know that Perl 1.0 was released on the very same day as Final Fantasy 1?! Did you know Perl has been used in Mars? I don't think I'll ever forgive myself for not making it in time to watch it live, but thankfully the conference recorded it so I was able to watch it afterwards, and you should too!

In the evening, Larry Wall gave an entertaining and enlightening (as usual) keynote. It was also the first time (I think) where he openly talked about his recently found cancer and discussed his legacy and Perl's future as a language and community. Not a lot of people know this, but back in 2009 I lost my father to cancer, so I really related to a lot of the things he said. The talk was extremely passionate and got him a well-deserved standing ovation. Incidentally, Perl is being used throughout the world in cancer research, helping to achieve some great breakthroughs in the fight against it over the past several years now. I truly hope Larry wins this battle, and I'm pretty sure the entire community is supportive and wishing him and his family all the best.

Tuesday, Stevan Little gave the "Perl: The Detroit of Scripting Languages" keynote, in which he evolved his OPW talk with new experiences and insights on the present of Perl, stuff we love, stuff we hate, and where to go from there.

Finally, in wednesday Matt S. Trout gave his "Velociraptor of Christmas Future" keynote, also filled with nice insights and perspectives on what the future holds for Perl as a language and as a community, all in mst's unique shoutingtalking style ;-)

cPanel Party Night!

pics, or it didn't happen ;)
On the very first day of talks, cPanel greeted all attendants with an open bar(!!) party at the Recess Arcade Bar down on 6th street, featuring a very nice band called The Spazmatics playing some cool covers. I had a great time there and even got to finish TMNT with 4 other guys (hey, it's an Arcade Bar after all!). It really got me back to my childhood. Thanks, cPanel! You guys are awesome!

Later that evening some of us moved to the pub in front of Recess to chat for a bit - the arcade bar was great, but also pretty loud. This is where I was exposed to the InfoWars magazine for the very first time. I... I... let's move on :-)

Game Night

Tuesday's talk ended with a great dinner with ribs and tex-mex at a place called Salt Lick BBQ - yet another fully paid for dinner, courtesy of our amazing sponsors! The conference organizers even got us private buses(!) to drive everybody there. Food was great, with tasty ribs, lots of side dishes and even dessert. In the meantime they also featured a caricature artist drawing everybody brave enough to ask for it.

During dinner I engaged in a great discussion with Shawn O'Connor, CTO of Perceptyx, about companies and employee engagement. As a manager myself, it was very reassuring to talk to another peer about the rights and wrongs of steering a company and motivating teams. We also had a great talk about football because, well, Brazil :-)

Then it was time for Game Night! Some people went outside to enjoy the atmosphere and play Jenga, and wound up creating pretty big towers - and even more spectacular crashes! Others stayed inside for some board and card games, or just to chat. At one point I was even hit in the back by a frisbee, so I guess there was that too :)

I for one enjoyed a very nice D&D(ish) game by Rik set in the future, who in the end revealed it to be a Star Trek Next Generation spin-off adventure. I'm not a hardcore trekkie but it surprised me that none of us could actually spot his (now obvious) hints and easter eggs throughout the adventure.

Talks, talks everywhere!

This year I spend most of my time in the "hallway tracks", bouncing from room to room and engaging in great conversations with fellow developers. I also volunteered to help the organizers (brown shirts FTW!) so I hung around the main LBJ desk helping Chris "perigrin" Prather as best as I could.

That doesn't mean I didn't enjoy a few of the 80+ talks (not to mention lightning talks) spread through the 3 days of the conference. I liked them all very much, but I feel I need to mention at least two of them here: first, Ricardo "rjbs" Signes' talk on the future of Perl 5 ("Postcards from the Edge") was great, debunking a few myths and unveiling a lot of how things are thought through in the core development of P5P and what we can expect from Perl 5 versions in the near future - including long-awaited signatures! Second, Augustina "auggy" Ragwitz' talk on extremely easy ways to contribute to Perl 5 (and dip your toes in Perl 5 development in general) was very well thought of and presented, and I really think it can break some entry barriers and reach developers having their first contact with Perl.

The Lightning Talks sessions were also very entertaining and fun. It amazes me how people in the US just rush to line up and talk about all the cool stuff they're doing with Perl. In Brazil, at least, most YAPC attendants don't seem attracted to giving lightning talks. Maybe they're too embarrassed, I don't know. Still need to think about ways to change this around here, I just love lightning talks too much :-)

Worldwide Job Fair

One of the high points of the conference is the job fair, specially if you're looking for new challenges, moving opportunities or simply a larger paycheck. Perl-centric companies from all over the world come to YAPC::NA to promote their business to potential employees and recruit them.

I'd like to take this moment to thank cPanel, Whitehat Security, LiquidWeb, Linode, AthenaHealth, The Game Crafter, MediaMath, Shutterstock, Bluehost.com, Booking.com, HostGator, NextGen, GlobalNOC and everybody else at the job fair (really sorry if I missed your company, just let me know and I'll update this) for being there, not just for the conference, but for Perl developers all over.

Seriously. These companies built their businesses around Perl and heavily rely on it for striving in the competitive market every single day. You should definitely support them if you can. And if you're looking for a full-time Perl job, please send them your resume.

"You're not my community. You're my family."

In between the Lightning Talks, while speakers were setting things up, people had the opportunity to make quick (~30s) announcements on whatever it is they felt like it. On the last day, Ribasushi poured his heart out thanking the Perl community for sponsoring his trip to the event via Crowdtilt. It was very touching, specially since I kinda feel the same way.

My Lightning Talk

For the first time ever, I went to a Perl conference committed to not giving any talks. I failed :) Jim Keenan approached Brian "Hugmeir" Fraser and myself during the pre-conference dinner asking us to follow his fiendish plot of having a Spanish & Portuguese lightning talk at the conference. We were really excited of being able to share a bit of our language and culture with everyone (Hugmeir is from Argentina), specially in a US state so close to Mexico. We were also terrified, thinking there was no way we could pull this off, and that people would just have to settle with a 5 minute "wtf" talk in not one but two different languages. So I figured what the hell, let's make it a comedy act and have the slides in english pretending they're part of the english-only audience and not getting anything we say. Hugmeir was totally up for it and we even got guest stars Genehack and Sawyer to help us flip the slides. As we started talking the crowd quickly turned its initial confusion to giant bursts of laughter. We had a great time and the response has been overwhelming!


We even got featured on the Shutterstock YAPC::NA blog post! This was also pretty big for Hugmeir as it was his very first talk. Thanks everyone!

Bingo \o/


The conference itself is filled with small pleasures, and one of them is the YAPC Bingo. Every attendant gets a card filled with stuff to do during the conference. Every time you do one of them, you cross it on the card. This year the only one I missed was the Bad Movie BOF, which I heard was great and fun as usual. This was a very tough choice for me as I really enjoy watching crappy movies. Besides, David Adler is an amazing bad movie connoisseur and a fun guy to hang out with in general, but when so many things are going on, you eventually get caught up in them. Also, since I don't see many of these people throughout the year, I just couldn't bear to let go of the hanging out and chatting.

Also, Sawyer managed to reach out to first-time attendants, finding tons of seasoned volunteers to help them with whatever Perl help they needed for their projects, provided they showed their YAPC Bingo cards with at least one full row/column/diagonal line completed.


That's it! I'm pretty sure I missed a lot of highlights, so make sure to blog about them if you can, or just let people know the stuff you liked in the comments below. A huge THANK YOU is in order to master chief Todd Rinaldo and the great Austin Perl Mongers for organizing such an incredible conference.
 
And now I can't wait for YAPC::EU, YAPC::Asia, YAPC::Brazil..... see you out there!