Archive for the ‘Cloud-computing’ Category

Deploying Play Framework 2 apps, with Java AND Scala, to Openshift

Let’s Play! in the cloud

A couple of weeks, Mark Atwood, Jorge Aliss, and me, Sebastián Scarano participated in Red Hat’s webinar LET’S PLAY! IN THE CLOUD: DEVELOPING JAVA WEB APPS ON OPENSHIFT

In the webinar Mark gave a neat introduction to Openshift, Red Hat’s free Platform as a Service:

Then we developed a basic contact manager web application, combining Java and Scala source code in the same Play 2 application, and deployed it on Openshift.

With this quickstart (https://github.com/opensas/play2-openshift-quickstart) you’ll be able to take any Play 2 application and deploy it on openshift. Just follow this instructions.

And here (https://github.com/opensas/play2-contacts-demo) you will find the contact demo app.

In the demo, in spite our internet connection conspiring against us, we managed to cover the following topics:

You can also check this article in which we explain in detail how we took advantage of the new “do-it-yourself” application type on Openshift to achieve native support for Play Framework application on Openshift.

So, if you want to start deploying your play apps on openshift right away, just sign up at openshift.com and enter PLAY!WEBINAR as promotional code, and you’ll get 3 gears, each with 1GB ram and 512 MB data space, for free.

Have fun playing on the cloud!

Troubleshooting Play Framework 2 apps on Openshift

Troubleshooting Openshift

With the do-it-yourself application type you really get a lot of freedom to support almost any framework or server that can be built and run on a linux box. But you do have to make your homework, and do some research.

So in this article I’ll show you a couple of tips I learnt playing around with Openshift and Play Framework.

Comments are more than welcome, so I hope you can also provide me some more tips to help us all get our apps running on the cloud.

Providing native support for play framework application

Right now, the solution we found for deploying Play 2.0 apps on openshift is quite handy, but we could make it a little better..

The problem is that we have to compile the app locally (issuing play stage) and then push 30 MB of libraries to Openshift. The ideal thing, and that’s what we did with the Play 1.x quickstart and with the latest version of Openshift module for Play Framework 1.x, would be to just upload our sources and then let Openshift download and install Play, compile our app, and start it.

Unfortunately we’ve ran with some memory constraints (seems like compiling Play 2 apps is a bit memory demanding) that eventually raised some issues. We are trying to work them out, but perhaps, with this tips, you could help has troubleshoot it.

With the opensourcing of Openshift and the new Origin livecd we have more tools available for us to further investigate what’s going on, I just didn’t have time yet to start playing with it.

So, enought chatter, and let’s get our hands dirty.

Houston, we have a problem

All right, you’ve just read this guide or followed our steps on the Play Framework webinar using this Play 2.0 quickstart (in fact, some of this tips will help trouble shoot any app running on Openshift) and something went wrong.

First of all, have a look at the logs. Just issue

rhc app tail -a myapp -l mylogin@openshift.com -p mysecretpass

Leave that window open, it will become quite handy later.

Then we’ll ssh into our remote machine. Just issue:

rhc app show -a myapp -l mylogin@openshift.com -p mysecretpass

and you’ll get something like

Application Info
================
contacts
    Framework: diy-0.1
     Creation: 2012-04-19T14:20:16-04:00
         UUID: 0b542570e41b42e5ac2a255c316871bc
      Git URL: ssh://0b542570e41b42e5ac2a255c316871bc@myapp-mylogin.rhcloud.com/~/git/myapp.git/
   Public URL: http://myapp-mylogin.rhcloud.com/

 Embedded: 
      None

Take the part after the ssh of the Git URL stuff, and log into you openshift machine:

ssh 96e487d1d4a042f8833efc696604f1e7@myapp-mylogin.rhcloud.com

(If you are lazy like me, go on and vote for an easier way to ssh into openshift)

It’s also a good idea to open another command window, ssh into openshift, and run something like “top” or “watch -n 2 free -m” to keep an eye on memory usage.

Troubleshooting Play

You know the old motto, “write once, run everywhere”… well it just “should” work, but just in case you could try compiling your app with the same JDK version as the one running on openshift.

Just run

java -version
java version "1.6.0_22"
OpenJDK Runtime Environment (IcedTea6 1.10.6) (rhel-1.43.1.10.6.el6_2-i386)
OpenJDK Server VM (build 20.0-b11, mixed mode)

And install the same jdk version on your box. Then compile your app and redeploy (you can use the convenience script openshift_deploy)

If that doesn’t work, try to do the whole process manually on Openshift. You should do something like this:

# download play
cd ${OPENSHIFT_DATA_DIR} 
curl -o play-2.0.1.zip http://download.playframework.org/releases/play-2.0.1.zip
unzip play-2.0.1.zip
cd ${OPENSHIFT_REPO_DIR}

#stop app
.openshift/action_hooks/stop

#clean everything - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play clean 

if you get something like:

/var/lib/stickshift/0b542570e41b42e5ac2a255c316871bc/myapp/data/play-2.0.1/framework/build: line 11: 27439 Killed 

It means it failed miserably (that’s the memory problem I told you about)

And it’s such a bad tempered error that you’ll also loose you command prompt. Just blindily type “reset” and hit enter, you’ll get your prompt back.

And then just try again…

You might also get this message:

This project uses Play 2.0!
Update the Play sbt-plugin version to 2.0.1 (usually in project/plugins.sbt)

That means you created the app with Play 2.0 and you are now trying to compile it with a different version.

Just update project/plugins.sbt file or download the appropiate version.

Now compile and stage your app.

#compile everything - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play compile

#stage - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play stage

Then run it (don’t be shy and have a look at the action hooks scripts on the quickstart repo).

target/start -Dhttp.port=8080 -Dhttp.address=${OPENSHIFT_INTERNAL_IP} -Dconfig.resource=openshift.conf

Go check it at https://myapp-mylogin.rhcloud.com

If everything works ok, just stop it with ctrl-c, and then run:

.openshift/action_hooks/start

You should see your app starting in the console with the logs files

Now you can log out from the ssh session with ctrl-d, and issue:

rhc app restart -a myapp -l mylogin@openshift.com -p mysecretpass

and you should see something like

Stopping play application
Trying to kill proccess, attempt number 1
kill -SIGTERM 19128
/var/lib/stickshift/0b542570e41b42e5ac2a255c316871bc/openbafici/repo/target/start "-DapplyEvolutions.default=true" -Dhttp.port=8080 -Dhttp.address=127.11.189.129 -Dconfig.resource=openshift.conf
Play server process ID is 21226
[info] play - Application started (Prod)
[info] play - Listening for HTTP on port 8080...

I hope this tips will become useful. As I told, I’m looking forward to start playing with the Openshift Origin livecd, and then I’ll tell you about.

In the meantime I’ll leave you with the company of the good old Openshift Rocket Bear, I know you miss him too, so why not get him back?

Desplegando aplicaciones de Play Framework 2, con Java Y Scala, en Openshift

Play framework en la nube de Red Hat

Hace un par de semanas, Mark Atwood, Jorge Aliss, y quien les escribe, Sebastián Scarano participamos del webinar LET’S PLAY! IN THE CLOUD: DEVELOPING JAVA WEB APPS ON OPENSHIFT organizado por Red Hat.

En el webinar, Mark dio una completa introducción a Openshift, la plataforma de cloud computing de Red Hat:

Luego junto con Jorge desarrollamos una simple agenda de contactos, usando Play Framework 2.0, combinando en una misma aplicación código fuente en Java y en Scala, y luego la pusimos en producción en Openshift.

Con este quickstart (https://github.com/opensas/play2-openshift-quickstart) podrán desplegar cualquier aplicación de Play 2.0 en Openshift. Simplemente sigan estas instrucciones.

Y aquí (https://github.com/opensas/play2-contacts-demo) encontrarán el código fuente de la agenda de contactos.

En la demo, a pesar de que nuestra conexión a internet nos jugó una mala pasada, logramos abordar los siguientes temas:

También pueden consultar este artículo en el cual analizamos en detalle cómo aprovechar el nuevo tipo de aplicación “do-it-yourself” (hagalo usted mismo) de Openshift para brindar soporte nativo a las aplicaciones de Play.

Si que si desean empezar a jugar con Openshift ya mismo, regístrense en openshift.com ingresen PLAY!WEBINAR como código de promoción, y recibirán 3 gears, cada uno con 1GB de memoria ram y 512 MB de espacio de almacemiento, gratis.

¡Esperamos que les guste!

Soporte nativo para Play framework en Openshift con el nuevo tipo de aplicación DIY

Por Sebastián Scarano @develsas. La versión original de este artículo está disponible en el Blog oficial de Openshift

Ya está en línea el contenido del webinar en el que mostramos cómo desarrollar una aplicación de Play 2.0, combinando Java Y Scala en la misma aplicación, y ponerla en producción en Openshift.

Cuando todas las opciones no son suficientes

Hace tan sólo algunos días nos enteremos del lanzamiento de un nuevo tipo de aplicación en Openshift denominada “do-it-yourself” o “hágalo-usted-mismo”. En este artículo mostraremos cómo podemos sacar el máximo provecho de esta nueva herramienta que se suma al arsenal de Openshift.

¿Qué es Play? Play es un framework que nos permite desarrollador aplicaciones Web, con Java o Scala, de una manera mucho más fácil, permitiéndonos alcanzar niveles de productividad que hasta el momento parecían patrimonio exclusivo de los frameworks basados en lenguajes dinámicos, como rails o django. Play forma parte también de los nuevos frameworks que se atrevieron a darle la espalda a la API de servlets y decidieron tomar otro rumbo. Es así como Play implementa su propio servidor http, sumamente liviano y optimizado, preparado para funcionar de manera asincrónica. Todo esto haciendo uso de Netty, una librería específicamente pensada para desarrollar este tipo de servidores, y que casualmente forma parte del stack de Jboss.

Ahora bien, si ya conoce Openshift, sabrá que le brinda múltiples opciones a la hora de desarrollar y poner en producción sus aplicaciones en la nube de Red Hat. Puede elegir trabajar con PHP, Ruby, Perl, Python, Node.js o Java. Y en lo que respecta a la base de datos puede elegir entre MySQL, PostreSQL y MongoDB.

Sin embargo, a pesar de esta abundante cantidad de opciones, el desarrollo de aplicaciones web se mueve a un ritmo tan rápido que ninguna plataforma es capaz de seguirle el paso. Cada día es más común trabajar con servidores http hechos a medida, construidos pensando en alta escalabilidad con bajo consumo de recursos. En lo que respecta a Java, el omnipresente servlet container, ya ha dejado de ser la única opción disponible.

Frente a este panorama, ¿qué podemos hacer para soportar todas estas heterogéneas tecnologías en constante movimiento? Bueno, los ingenieros de Red Hat dieron con una solución muy simple, pero al mismo tiempo sumamente poderosa.

Presentando el tipo de aplicación DIY – Hágalo-usted-mismo

Estos son los tipos de aplicación actualmente soportados en Openshift: jbossas-7, python-2.6, jenkins-1.4, ruby-1.8, diy-0.1, php-5.3, and perl-5.10

Bueno, no cuesta mucho darse cuenta de qué trata cada uno, salvo uno de ellos que se ve un tanto sospechoso: diy-0.1

Una aplicación “DIY” no es más que una aplicación completamente vacía, sin ningún framework ni servidor previamente cargado, listo para que lo personalicemos según nuestras propias necesidades. Con este nuevo tipo de aplicación, Openshift está comenzado a hacer más difusa la línea que separa un IaaS (Infraestructura como servicio) de un PaaS (Plataforma como servicio), poniendo a nuestro alcance un entorno controlado y escalable, pero al mismo tiempo dándonos la libertad para implementar la tecnología que mejor se ajuste a nuestras necesidades. [Tenga en cuenta que al momento de escribir este artículo, el tipo de aplicación DIY se encuentra en estado experimental]

Soporte nativo de Play en Openshift

Para mostrar las posibilidades que este nuevo tipo de aplicación pone en nuestras manos, implementaremos uno de los pedidos más votados en Openshift: soporte nativo para Play framework.

Hasta el día de hoy, para poner en producción una aplicación Play en Openshift, la única opción que teníamos era empaquetarla en un archivo war y desplegarla en un servlet container, lo cual funcionaba muy bien y era muy fácil, como explica este artículo. La única contra era que al hacerlo desperciábamos preciosos recursos y no podíamos hacer uso de prestaciones avanzadas de Play, como el manejo de requests asincrónicos.

Para darse una idea de qué es lo que nos proponemos conseguir, pueden echar una mirada al quickstart que preparamos para este artículo. Simplemente tienen que crear una nueva aplicación en Openshift, eligiendo como tipo diy-0.1, hacer un pull de los fuentes del quickstart, y luego hacer un push a su repositorio de openshift… ¡y eso es todo! Aquí están los pasos:

rhc app create -a play -t diy-0.1 -l yourlogin@yourmail.com
cd play 
git remote add quickstart -m master https://github.com/opensas/play-example.git
git pull -s recursive -X theirs quickstart master 
git push 

Luego de completados esos pasos, su aplicación estará lista y esperándolo en http://play-yournamespace.rhcloud.com

También hemos preparado un quickstart para Play framework 2.

Ahora, si tiene ganas de meterse a fondo y ver cómo hemos logrado esto, y al mismo tiempo prepararse para empezar a crear sus propios quickstarts, no tiene más que seguir leyendo…

¡Adiós a los servlets!

Antes de intentar crear una aplicación de tipo DIY en Openshift, tendrá que familizarse con la tecnología que planea poner en producción. Es preciso conocer en detalle los pasos necesarios para configurar todas las herramientas necesarias en su propia estación de trabajo, para luego replicar esto en Openshift.

En el caso de una aplicación de Play framework, no necesitaremos un completo servidor de aplicaciones como Jboss, ni tampoco un servidor web al estilo Tomcat, es más, ni siquiera un simple servlet container. Tan sólo tendremos que instalar Play e iniciar el servidor http que trae incluido.

Hacer esto en su propia estación de trabajo es tan fácil como descargar Play de la web, descomprimirlo y ejecutar:

play new demo 
cd demo 
play start

Y para detener la aplicación:

play stop

Ahora tan solo tendremos que hacer esto mismo en nuestro servidor en Openshift.

Conociendo nuestra propia nube

Vamos a crear una nueva aplicación en Openshift, de tipo diy-1.0, llamada ‘raw’.

rhc app create -a raw -t diy-0.1 -l yourlogin@yourmail.com

Ahora echémosle una mirada a lo que acabamos de crear

rhc app show -a raw -l yourlogin@yourmail.com

Application Info
================
raw
    Framework: diy-0.1
     Creation: 2012-03-19T01:18:31-04:00
         UUID: youruuid
      Git URL: ssh://youruuid@raw-yourdomain.rhcloud.com/~/git/raw.git/
   Public URL: http://raw-yourdomain.rhcloud.com/

Puede navegar a http://raw-yourdomain.rhcloud.com/ para ver la página de nuestro sitio.

Es la misma página estática que encontraremos en raw/index.html

Ahora veamos que nos espera en nuestro repositorio local:

cd raw
ls -a

.git                      # nuestro repositorio local de git
misc                      # un directorio vacío, puede borrarlo, nadie extrañará su presencia
.openshift/action_hooks   # aquí están los scripts para iniciar y frenar nuestra aplicación
raw                       # la paǵina estática de error
README                    # información de utilidad

Como ya dijimos, una aplicación completamente vacía, pero hay una carpeta que nos resultará particularmente interesante:

ls .openshift/actions_hooks
build  deploy  post_deploy  pre_build  start  stop

Estos son los scripts que Openshift utiliza para compilar, desplegar, iniciar y detener nuestra aplicación. Estos escripts son ejecutados en el servidor remoto de Openshift luego de cada push. Así que ahora los analizaremos en detalle para conocer mejor el entorno en que correrá nuestra aplicación.

Tomemos la salida del comando `rhc app show -a raw` y ejecutemos el siguiente comando:

ssh youruuid@raw-yourdomain.rhcloud.com

De esta manera podrá acceder a su máquina remota en openshift. En su directorio HOME encontrará los siguientes directorios:

git
    .env            # Contiene la definición de las variables de entorno

    .git  # Aquí está su propio repositorio de git, disponible en ssh://youruuid@raw-yourdomain.rhcloud.com/~/git/raw.git/



    repo            # $OPENSHIFT_DATA_DIR - Aquí está el contenido de la carpeta de su aplicación.
                    # Cada vez que hace un push, los datos se guardan aquí.

    data            # $OPENSHIFT_DATA_DIR - Este es un directorio persistente, 
                    # la info que guarde allí no se irá con cada reinicio del servidor

    logs            # $OPENSHIFT_LOG_DIR - Aquí debería guardar los archivos de log de su aplicación
                    # Es la carpeta que consulta el comando 'rhc app tail'

/tmp/             # $OPENSHIFT_TMP_DIR - Carpeta temporal, aquí tenemos permiso de lectura y escritura

Estas son básicamente las carpetas que más nos interesan.

Basta de discursos, queremos ver el código

Para este artículo tomaremos una versión simplificada del quickstart para desplegar aplicaciones Play 1.x en Openshift. Agregamos links a los scripts originales para que pueda consultarlos.

Antes que nada tendremos que desarrollar el script .openshift/action_hooks/pre_build, que será el encargado de verificar que el framework se encuentre instalado. De no ser así, deberá descargarlo de la web y descomprimirlo.

El script podría ser algo tan simple como esto:

.openshift/action_hooks/pre_build (script en github)

if ! [[ -d ${OPENSHIFT_DATA_DIR}play-1.2.4 ]]; then
  curl -o ${OPENSHIFT_DATA_DIR}play-1.2.4.zip http://download.playframework.org/releases/play-1.2.4.zip
  unzip ${OPENSHIFT_DATA_DIR}play-1.2.4.zip
  rm ${OPENSHIFT_DATA_DIR}play-1.2.4.zip
fi

Luego, para iniciar la aplicación:

.openshift/action_hooks/start (script en github)

cd ${OPENSHIFT_REPO_DIR}

.openshift/action_hooks/stop

#le indicamos a Play que guarde los archivos de auditoria en el directorio OPENSHIFT_LOG_DIR
export PLAY_LOG_PATH=${OPENSHIFT_LOG_DIR}

#ejecutamos la aplicación con el id openshift
${OPENSHIFT_DATA_DIR}play-1.2.4/play start --%openshift

No olvide configurar el su aplicación para que el servidor http escuche en el puerto ${OPENSHIFT_INTERNAL_PORT} de la dirección ${OPENSHIFT_INTERNAL_IP}

En nuestro caso simplemente deberemos agregar estas líneas al archivo application.conf:

%openshift.http.port=${OPENSHIFT_INTERNAL_PORT}
%openshift.http.address=${OPENSHIFT_INTERNAL_IP}

Y ahora solo nos queda el script para detener la aplicación

.openshift/action_hooks/stop (script en github)

cd ${OPENSHIFT_REPO_DIR}

if [[ -f “server.pid” ]]; then
${OPENSHIFT_DATA_DIR}play-1.2.4/play stop
fi

¡Eso es todo!

Simplemente nos resta guardar los cambios en nuestro repositorio git y hacer un push a openshift:

git add .
git commit -m "nuestra aplicación de Play corriendo en Openshift"
git push

Entonces verá a nuestra criatura en acción, descargando e instalando play 1.2.4 del sitio de Play, y finalmente ejecutando nuestra aplicación. No sea tímido, hágale una visita en : http://raw-yourdomain.rhcloud.com/

Recuerde que esta es una versión simplificada del quickstart original, no estamos chequeando errores ni guardando información en el archivo de logs. Para un ejemplo más completo consulte los scripts del quickstart en Openshift.

Play y Openshift, jugando en la nube de Red Hat

Desde sus inicios Openshift se destacó por brindar soporte a una amplísima gama de frameworks y servidores web. Con esta nueva opción, también nos brinda las herramientas necesarias para personalizarlo según nuestras necesidades. Lo único que necesita es familiarizarse con el entorno de Openshift y comenzar a programar unos simples scripts en bash. Me pregunto qué creará la comunidad con este nuevo tipo de aplicación Do-It-Yourself en Openshift.

Por Sebastián Scarano @develsas

Sebastián Scarano es un desarrollador web de Buenos Aires, apasionado por compartir su conocimiento y desarrollar buenos sitios web. Actualmente se desempeña como líder de proyectos en el Ministerio de Trabajo, Empleo y Seguridad Social de la República Argentina. Durante el último año ha estado participando activamente de la comunidad Play. Más recientemente publicó el módulo Openshift para Play, para que todos puedan desplegar fácilmente sus aplicaciones en la nube de Red Hat.

Play!, Openshift y Twitter Bootstrap: Combo para programadores perezosos pero impacientes

Ya que estan, por que no se pegan una vuelta por el sitio de openshift y votan para agregar soporte nativo para Play en Openshift.

Hace rato que descubri en Play un poderosisimo web framework para Java, y tengo la suerte de poder aplicarlo diariamente en mi actual trabajo. Sin entrar en demasiados detalles tenemos todos los beneficios del conocido patron MVC, junto con un poderoso WebApp container y un sistema de templates muy amigable. Pero lo que lo hace mas amigable y poderoso a mi parecer es la comunidad y lo facil que resulta desarrollar e integrar los famosos modulos de Play. El que mas nos ocupa hoy es el de Openshift cuyo autor es Sebastian Scarano akka @opensas (el que “mas” lo digo porque el desarrollo incluye dos mas que son nativos: CRUD y Secure)

Disclaimer: Como entiendo que mi post es acotado y especifico quizas cometa el error de dar por sentado un monton de cosas, pero si necesitan que me extienda en algun punto por favor haganmelo saber.

Instalacion y armado del entorno

Deben contar con Git y !Play instalado. Si todavia no lo hicieron, vayan a al sitio de !Play. Y tambien

(sudo) apt-get install git-core

Tambien van a necesitar el cliente de Openshift. Para ello

(sudo) gem install rhc

y

(sudo) gem install test-unit

A continuacion en su directorio de trabajo ejecutan

(sudo) play install openshift

Con esto ya tenemos el modulo de Openshift instalado en nuestro stack de !Play. A continuacion creamos nuestra aplicacion de la siguiente manera:

play new myApp --with openshift

Acto seguido haran vuestra magia con la aplicacion, corriendola en modo local y versionadolo debidamente ;-). Pero atentos que deben trabajar con Git puntualmente ya que OpenShift les creara un repo propio a donde el modulo hara el deployment.

Aca viene lo interesante: con vuestra cuenta debidamente creada en OpenShift deben agregar estas entradas en el archivo application.conf de la aplicacion en cuestion:

openshift.rhlogin = myuserOpenShift
openshift.password = myPassOplenshift
openshift.application.name = myApp@Openshift

Acto seguido vamos a instalar/desplegar por primera vez nuestra aplicacion:

play rhc:deploy -o

Cuando este comando se procese y al no existir aun la aplicacion en la nube nos preguntara si queremos crearla y si ademas queremos tener un repo en Openshift. A todo le responderemos que SI, ya que por mas que parezca en ese sentido no existe un libre albeldrio. Lo siento ;).

Hasta aqui todo muy bonito pero nuestra aplicacion es standalone y no tiene persistencia de ningun tipo. Entonces con estos comandos :

rhc-ctl-app -a myApp -e add-mysql-5.1 --rhlogin Myuser -p mypass
rhc-ctl-app -a myApp -e add-myphpadmin-3.4 --rhlogin Myuser -p mypass

y con el output de esos comandos se generan estas nuevas entradas en el application.conf

db.url=jdbc:mysql://xxx.xxx.xxx.xxxx:3306/myApp
db.driver=com.mysql.jdbc.Driver
db.user=admin
db.pass=myadminPass

Ya tenemos mysql en nuestro box al cual podemos administrar con phpmyadmin.

Pero la cereza del postre seria que pudieramos cambiar ese feo dominio myApp-myNameSpace.rhcloud.com por algo mas chevere. Para eso agregan un cname tipo host en donde tengan registrado su dominio (en es caso lo hice con GoDaddy), declarando la ip de la url anterior (con un ping ya lo tienen) y desde sus maquinas corran el siguiente comando:

rhc-ctl-app -a myApp -e add-alias mydomain.com --rhlogin Myuser -p mypass

y voila!!! Esto agrega el dominio en vuestra aplicacion. Dicho sea de paso pueden agregar mas de un dominio a una sola aplicacion.

Ok, hasta aqui llego hoy. Para no aturdilos mucho, en la proxima entrega les explico en forma muuuuy sencilla como agregue a esta misma aplicacion el Css Framework de twitter: Bootstrap.

La aplicacion la pueden ver en progreso en Blog’s @DiegoRam

Las mas grande agradecimiento para Sebastian Scarano (@opensas) y Luis Farzati (@luisfarzati) que me dieron una mano terrible en el proceso.

Saludos y comenten.

Iba a hacer una version con acentos, pero que mierda!! el codigo no lleva acentos y, como ya dije en el título de este artículo, soy muy perezoso 😉

Play framework on the cloud made easy: Openshift module

Consider voting for Play framework native support on Openshift.

Just a couple of years ago finding an afordable hosting solution for a java web application was a hard task, and looking for a free one was an impossible mission. Not to mention that even thinking about things like auto-scaling, one-command deploy, continuos integration, and that sort of stuff was plain science fiction.

This last year has witnessed a cloud revolution, and nowdays there’s a really appalling amount of alternatives to choose from. It seemed like every medium-to-large size IT player had to come out with their own Platform as a Service (PaaS) cloud offering.

In this scenario, an offering from Red Hat couldn’t go unnoticed. Red Hat engineers really know a lot about managing servers, and, lucklily for us, they also know a lot about java web applications. Fortunately, they took the challenge, and what they have to offer would certainly not disappoint us.

openshift homepage

Isn't that panda bear cute?

So, here comes Openshift. Openshift is Red Hat’s free, auto-scaling, cloud-based platform-as-a-service for Java, Perl, PHP, Python, and Ruby applications. It’s a quickly evolving platform, that managed to shape a vibrant and helpful community supporting it. Moreover, it’s free offering largely surpases anything that the competence has to offer. Just by entering your email and choosing a password, you get five applicacions namespaces, each of them with a git repository and half GB of data (code + database) to use as you like it. Add to that support for mysql (with phpmyadmin), PostgreSQL, MongoDB 2.0 (with MongoRock) and even a fully functional Jenkins instance to have a continuous integration environment.

Deploying a java web application to openshift is really easy, just git add, git commit, git push… and that’s it. But we, play developers, spoiled by our beloved framework as we are, would rather just type something like play rhc:deploy and forget about it.

That’s what openshift module for play framework is about.

The short story

So you have everything set up to deploy a play framework application to openshift. That means you have installed JDK 1.6 or 1.5, play framework, ruby, ruby gems, openshift client tools, and that you have signed up at openshift and also created a domain.

In that case, you just have to:

$ play install openshift

and then

$ play new <my app> --with openshift
$ cd <my app>
$ play rhc:deploy -o

… and that’s it.

Your application is ready... and running on Openshift!

Every time you want to deploy your changes to openshift, just issue once again play rhc:deploy -o. The -o parameters just tells the module to open your application on a web browser right after deployment.

From zero to the cloud

Just as a reminder to myself, here are the steps required to go from a bare linux installation to deployment on openfhit:

1. Install Java jdk 1.6

on debian based linux distributions (like ubuntu, mint and others)

$ sudo apt-get install openjdk-6-jdk

on rmp based linux distributions (like fedora, red hat, centos, and others)

$ sudo yum install java-1.6.0-openjdk-devel.i686

2. Install play framework

Here’s my quick and dirty list of commands to install play framework.

$ cd ~
$ mkdir dev
$ cd dev
$ wget http://download.playframework.org/releases/play-1.2.4.zip
$ unzip play-1.2.4.zip 

$ echo "export PATH=$PATH:~/dev/play-1.2.4" >> ~/.profile

$ source ~/.profile

And then test it with:

$ play version
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~
~ play! 1.2.4, http://www.playframework.org
~
1.2.4

Note: If you are running on fedora, you might need to issue sudo yum remove sox, because the sox package comes with it’s own play command that conflicts with play framework.

3. Sign up for openshift

Go to https://openshift.redhat.com/app/user/new/express enter your email and choose a password.

4. Install, git and ruby gems

On a Debian based linux distro:

$ sudo apt-get install git ruby rubygems

Rpm version:

$ sudo yum install git ruby rubygems

5. Install openshift client tools

Once you have installed ruby gems, installing red hat cloud tools is as easy as:

$ sudo gem install rhc

6. Create a domain

Your domain namespace is used to help identify your applications and as part of the URLs to your applications. It’s unique to you across all of openshift. For example, let’s say you have the namespace awesome, when you create a new app called wicked, you’ll find it at http://wicked-awesome.rhcloud.com. When you create a new app called freakin, it’ll be at http://freakin-awesome.rhcloud.com.

So go to your openshift control panel at https://openshift.redhat.com/app/control_panel and click on edit on the NAMESPACE section. Then enter something like playdemo (well, that one is already taken) and click save.

7. Create and register your SSH keys

Now you’ll have to a SSH key, which in fact means creating a private and a public key, so that openshift can validate that it’s really you the one trying to push something to the remote git repository. Just follow the steps at http://help.github.com/linux-set-up-git/, you just have to open a terminal and then

$ cd ~/.ssh

If you get a No such file or directory error, don’t worry, it means that you didn’t have any SSH key on your system. On the other hand, if you already have a SSH key, it would be a good idea to make a backup.

$ ssh-keygen -t rsa -C "<my email>"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sas/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/sas/.ssh/id_rsa.
Your public key has been saved in /home/sas/.ssh/id_rsa.pub.
The key fingerprint is:
22:7b:cd:f3:98:4f:92:de:80:1d:ad:d6:ea:73:20:c2 <my email>
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|         .       |
|   .. . S .      |
|    Eo.*.=       |
|    ..o.@.o      |
|     . o.@.      |
|       .*++      |
+-----------------+

And then, you can setup your username and email, like this:

$ git config --global user.name "<my name>"
$ git config --global user.email "<my email>"

Now you have to register this key at openshift. Just copy the content of the id_rsa.pub (be careful not to copy the file id_rsa, it’s your private key, and you should keep that to yourself) and add it as a new SSH KEY from your control panel.

On Fedora is pretty annoying having to enter your passphrase on every git operation. To avoid it, just run ssh-add and enter your passphrase for the last time.

Alternatively, you can also use the following command

$ rhc-create-domain -l <your email> -p <your password> -n <pick a domain>

and let openshift create a a pair of private and public keys as libra_id_rsa and libra_id_rsa.pub at your .ssh/ directory. I had a couple of conflicts between my own SSH keys and the libra ones created by openshift, so I prefer to handle the ssh keys myself.

Note: You won’t be able to push anything to your git repository unless you have a valid public key registered at openshift. Take into account that you can add as many keys as needed.

Go to your control panel at https://openshift.redhat.com/app/control_panel to check that everything is right.

Going to the cloud

And now yes, we are ready to deploy our play framework application to the cloud.

$ play install openshift
$ play new <my app> --with openshift
$ cd <my app>

Now, for every command you’ll have to enter, at least, your username and password. You can spare yourself this trouble by adding the following keys to your conf/application.conf file:

# Openshift module configuration
openshift.rhlogin=<my login>
openshift.password=<my password>

After that you should check that you have installed all the prerequisites. Just run:

$ play rhc:chk

It will check for a java 1.6 or 1.5 install, git, ruby, rubygem, and openshift client tools 0.84.15 or higher. It will also check that the application exists on openshift, otherwise it will ask you to create it, and finally it will check that you have a local git repository pointing at the remote repository at openshift.

Then you can deploy your app with:

$ play rhc:deploy -o

The first time it will take quite some time to issue the deploy, because the module has to upload all of the play framework libraries. After that initial deploy, subsequent commits will be much faster, because git is smart enough to send only the changed files. Moreover, the module will ask your permission to create the app on openshift, and also to create a local repo. If you just want the script to create everything withour asking for permission, just add a --bypass or -b parameter to the command.

Your application will now be available at: http://<my app>-<my domain>.rhcloud.com.

If you have already deployed your application to openshift, and you just want to retrieve it from your remote git repository, just issue:

$ play rhc:fetch

Take into account that this is a destructive operation. It will completely remove your local application and replace it with the contents of your remote repository.

To have a look at your server logs, issue:

$ play rhc:logs
Openshift log files

Having a look at openshift log files with "play rhc:logs"

To display information about your applications on openshift run:

$ play rhc:info

Which is just a short-hand for the rhc-domain-info command.

You can open your application at openshift anytime issuing:

$ play rhc:open

Which is also a short-hand for opening a web browser at http://<my app>-<my domain>.rhcloud.com.

Finally, if you think you want to remove your application from openshift, just run:

$ play rhc:destroy

Installing the openshift module

There are two ways to install openshift module. One is just to issue play install openshift, which will install the module directly with your framework, at <play install folder>/modules/openshift-0.1.1. That way it will be available to every app you create with

$ play new my-app --with openshift

The other way is to manually configure it as a dependency. Just add the following line to your conf/dependencies.yml file:

# Application dependencies
require:
    - play
    - play -> openshift 0.1.1

And then issue

play deps

Note: play keeps a cache of fetched dependencies at ~/.ivy2/cache. If you are having troubles with dependencies just clean that directory and try again.

Along with the module there’s a sample application at <openshift module folder>/samples_and_tests/openshift-demo. Just go to that folder and issue play deps and then play run to see it running locally. It just displays play configuration and the host environment variables to let you check that your app is running on openshift.

Openshift module demo application

Openshift module demo application

Then run play rhc:chk to verify that you have installed all the prerequisites. After that issue play rhc:deploy -o to create your remote application at openshift, create a local git repo, package your app as a war file, commit your new app, and deploy to openshift. Thanks to the -o parameter the module will open your openshift app in a web browser after deployment.

Getting help

You can have a look at the module’s commands issuing:

$ play help
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~
~ play! 1.2.4, http://www.playframework.org
~

[...]
~
~ Modules commands:
~ ~~~~~~~~~~~~~~~~~
~ rhc:chk             Check openshift prerequisites, application and git repo.
~ rhc:deploy          Deploys application on openshift.
~ rhc:destroy         Destroys application on openshift.
~ rhc:fetch           Fetches application from remote openshift repository.
~ rhc:info            Displays information about user and configured applications.
~ rhc:logs            Show the logs of the application on openshift.
~ rhc:open            Opens the application deployed on openshift in web browser.
~
~ Also refer to documentation at http://www.playframework.org/documentation
~

Then you can get more help about parameters with the -h or --help parameter:

$ play rhc:chk -h
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~
~ play! 1.2.4, http://www.playframework.org
~
Usage: play [options]

Options:
  -h, --help            show this help message and exit
  -a APP, --app=APP     Application name  (alphanumeric) (required)
  -s SUBDOMAIN, --subdomain=SUBDOMAIN
                        Application subdomain, root by default  (alphanumeric)
                        (optional)
  -l RHLOGIN, --rhlogin=RHLOGIN
                        Red Hat login (RHN or OpenShift login with OpenShift
                        Express access)
  -p PASSWORD, --password=PASSWORD
                        RHLogin password  (optional, will prompt)
  -d, --debug           Print Debug info
  -m MESSAGE, --message=MESSAGE
                        Commit message
  --timeout=TIMEOUT     Timeout, in seconds, for connection
  -o, --open            Open site after deploying
  -b, --bypass          Bypass warnings

You can also specify these options in the conf/application.conf file with the following keys:

openshift.rhlogin: Red Hat login (RHN or OpenShift login with OpenShift Express access)
openshift.password: RHLogin password  (optional, will prompt)
openshift.application.name: Application name  (alphanumeric) (required)
openshift.application.subdomain: Application subdomain, root by default  (alphanumeric)
openshift.debug: Print Debug info
openshift.timeout: Timeout, in seconds, for connection

You can see all versions of the module at the openshift module’s page on http://www.playframework.org/modules/openshift.

You can check the documentation at http://www.playframework.org/modules/openshift-0.1.1/home, or running locally your app in dev mode with play run, and then going to http://localhost:9000/@documentation/modules/openshift/home.

Local documentation

Browsing module documentation locally

You can ask questions at the play framework discussion list at https://groups.google.com/group/play-framework, or you can try with it’s spanish cousin at https://groups.google.com/group/play-latam.

Known issues

Unfortunately, right now the openshift module doesn’t work with windows. That’s because the module issues many git commands, and you can’t do that on windows from the standard shell, it requires a special “git bash” prompt.

Further steps

In the next version I’ll be exploring the possibility of building a java only version of the module using openshift’s java api. That way we won’t be needing git, ruby, nor the rhc tools installation. Morevoer, we should be able to use it all from windows as well.

Resources

Play framework openshift module page: http://www.playframework.org/modules/openshift

Latest version: http://www.playframework.org/modules/openshift-0.1.1/home

Project at github: https://github.com/opensas/openshift

Detailed tutorial about how to deploy a Play Framework application to openshift: https://github.com/opensas/play-demo/wiki/Step-12.5—deploy-to-openshift

Excellent tutorial about deploying java applications to openshift: https://gist.github.com/1637464#file_tutorial.rst

A couple of articles on jboss planet:
http://planet.jboss.org/post/let_s_play_on_the_red_hat_cloud_using_the_play_framework_on_openshift_express_with_jboss_as_7
https://community.jboss.org/blogs/thomas.heute/2011/06/29/play-framework-on-jboss-as-7?_sscc=t