Building a Real Time Activity Stream on Cloud Foundry with Node.js, Redis and MongoDB – Part I

Cloud Foundry provides developers with several choices of frameworks, application infrastructure services and deployment clouds. This approach to providing a platform as a service enables the fast creation of useful cloud applications that take advantage of polyglot programming and multiple data services. As an example of how this enables us to be more productive, I was able to use Node.js, Redis, and MongoDB to create an Activity Streams application in a short time, despite the fact that I mainly develop Web Applications in Ruby. Based on the developer interest after a demo of this application at NodeSummit 2012 and MongoSF 2012,  I was inspired to do a 3 part blog series that fully details the creation, deployment, and scaling of this application on CloudFoundry.com.

The application is based on an interesting project I came across recently called “node-express-boilerplate” developed by @mape which is a full-featured but simple boilerplate Node.js app. Given my previous experience working on Social Networking software and Open Web Standards, I decided to morph this app into an Activity Streams sample application.

Initial Boilerplate Architecture without MongoDB or Redis PubSub

“Node-express-boilerplate” is a starter application written in Node.js which showcases how users can log into a website using Facebook, Twitter or GitHub, display basic profile info from those sites, and have real-time communication between server and clients. In this first blog post, we are going to review the components of the boilerplate application so that developers can learn how to use them for other applications and  deploy locally as well as on Cloud Foundry.

A tour of the Boilerplate Components

Before we move to the setup, here are some code highlights explaining the various parts of the application.

Express MVC Framework

Working with the Express framework is very easy to do because its creator, @tjholowaychuk, has made it simple yet flexible to use while providing good documentation and screencasts.

You can use any web templating engine. For my project, I switched from using Embedded Javascript (EJS) to jade which is even terser than HTML Abstraction Markup Language (Haml).

// Settings
app.configure(function() {
	app.set('view engine', 'jade');
	app.set('views', __dirname+'/views');
});

Route Middleware

This middleware allows us to chain functions to pre-process the request. In this example I am showing how to invoke loadUser to read the current user, getDistinctStreams to get all the different topics and getMetaData to get the list of verbs and object types.

app.get('/streams/:streamName', loadUser, getDistinctStreams, getMetaData, function(req, res) {

    asmsDB.getActivityStream(req.params.streamName, 20, function (err, docs) {
        var activities = [];
        if (!err && docs) {
            activities = docs;
        }
        req.streams[req.params.streamName].items = activities;
        res.render('index', {
            currentUser: req.user,
            providerFavicon: req.providerFavicon,
            streams : req.streams,
            desiredStream : req.session.desiredStream,
            objectTypes : req.objectTypes,
            verbs: req.verbs
        });
    });

});

Session Management

In the boilerplate application, sessions are stored in Redis, allowing us to scale to more than one instance. Not only does this application properly manage user sessions, it also supports single sign-on with  GitHub, Facebook and Twitter via module everyauth.

Packaging Assets

In real world applications today, users expect immediate feedback and this cannot be done if your client is executing multiple http requests to render the app. This boilerplate sample uses @mape‘s module connect-assetmanager which minifies and bundles CSS and Javascript assets so the responses are very fast. This module is very flexible and allows pre and post manipulation of assets.

Here is an example which packages the js and the css files

var assetManager = require('connect-assetmanager');
var assetHandler = require('connect-assetmanager-handlers');
...
var assetsSettings = {
	'js': {
		'route': /\/static\/js\/[a-z0-9]+\/.*\.js/
		, 'path': './public/js/'
		, 'dataType': 'javascript'
		, 'files': [
			'http://code.jquery.com/jquery-latest.js'
			, siteConf.uri+'/socket.io/socket.io.js' // special case since the socket.io module serves its own js
			, 'jquery.client.js'
		]
		, 'debug': true
		, 'postManipulate': {
			'^': [
				assetHandler.uglifyJsOptimize
				, function insertSocketIoPort(file, path, index, isLast, callback) {
					callback(file.replace(/.#socketIoPort#./, siteConf.port));
				}
			]
		}
	}
	, 'css': {
		'route': /\/static\/css\/[a-z0-9]+\/.*\.css/
		, 'path': './public/css/'
		, 'dataType': 'css'
		, 'files': [
			'reset.css'
			, 'client.css'
		]
		, 'debug': true
		, 'postManipulate': {
			'^': [
				assetHandler.fixVendorPrefixes
				, assetHandler.fixGradients
				, assetHandler.replaceImageRefToBase64(__dirname+'/public')
				, assetHandler.yuiCssOptimize
			]
		}
	}
};

var assetsMiddleware = assetManager(assetsSettings);

Client-Server Real Time Communication

Socket.io is used to send messages back and forth between the user-agent and the server. This saves us from having to do entire page refreshes to show new content.

In the example below you can see how we subscribe to different events and change the page content accordingly.

var socketIoClient = io.connect(null, {
		'port': '#socketIoPort#'
		, 'rememberTransport': true
		, 'transports': ['xhr-polling']
	});
	socketIoClient.on('connect', function () {
		$$('#connected').addClass('on').find('strong').text('Online');
	});

	var image = $.trim($('#image').val());
	var service = $.trim($('#service').val());

    var $ul = $('#main_stream');

	socketIoClient.on('message', function(json) {
		var doc = JSON.parse(json);
        if (doc) {
            var $li = $(jade.templates["activity"]({activities: [doc]}));
            $ul.prepend($li);
        }
		if ($ul.children.count > 20) {
            $ul.children.last.remove();
        }
	});

Here are the steps we performed to run this application as-is on Cloud Foundry

Setup

  • Get a CloudFoundry.com account if you don’t have one yet.
  • Install vmc command line tool to deploy to Cloud Foundry.
  • Get Node.js running locally on your machine.
    • Install version 0.6.8 or later. NPM is the package manager which will be included.
  • Get Redis running locally.
  • Create Apps on Facebook, Twitter and GitHub for prod and local environments and note the keys.

Configure

Clone @mape‘s repo or fork it and clone your fork and install the dependencies

$ git clone git://github.com/mape/node-express-boilerplate.git
$ cd node-express-boilerplate

Edit package.json to include module cloudfoundry

{
  "name" : "node-express-boilerplate",
  "description" : "A boilerplate used to quickly get projects going.",
  "version" : "0.0.2",
  "author" : "Mathias Pettersson ",
  "engines" : ["node"],
  "repository" : { "type":"git", "url":"http://github.com/mape/node-express-boilerplate" },
  "dependencies" : {
    "cloudfoundry": ">=0.1.0",
    "connect" : ">=1.6.0",
    "connect-assetmanager" : ">=0.0.21",
    "connect-assetmanager-handlers" : ">=0.0.17",
    "ejs" : ">=0.4.3",
    "express" : ">=2.4.3",
    "socket.io" : ">=0.7.8",
    "connect-redis" : ">=1.0.7",
    "connect-notifo" : ">=0.0.1",
    "airbrake" : ">=0.2.0",
    "everyauth" : ">=0.2.18"
  }
}

Install the dependencies locally.

$ npm install

Copy to siteConfig.js

$ cp siteConfig.sample.js siteConfig.js

Edit siteConfig.js to use environment variables and the cloudfoundry module. Changes are detailed here.

Update server.js to use the new siteConfig.js settings as seen here.

Set environment variables for all services. Example in bash:

$ export twitter_consumer_key=2SXwj3HcMHsdsdsL4uuUBdjShw
$ export twitter_consumer_secret=UFamzEOAEhLUwewewDwwEoCI72hN0fl8
$ export facebook_app_id=5925695687264066
$ export facebook_app_secret=cce6f5edefa89f4686e5e036e3ea
$ export airbrake_api_key=63340934f6b376a001eacfc660d06205
$ export github_client_id='92df9d93813ab234e1'
$ export github_client_secret='fa64d10d3a02eee08d00cda3c2965caea2a4ce22'

Run locally

$ node server.js

Run on CloudFoundry

Install vmc if you have not already done so

$ sudo gem install vmc --pre

Deploy the app to Cloud Foundry
Specify you want Redis “redis-asms” bound to your app

$ vmc push --runtime=node06 --nostart

  Would you like to deploy from the current directory? [Yn]:
  Application Name: node-express-start
  Detected a Node.js Application, is this correct? [Yn]:
  Application Deployed URL [node-express-start.cloudfoundry.com]:
  Memory reservation (128M, 256M, 512M, 1G, 2G) [64M]: 128M
  How many instances? [1]:
  Bind existing services to 'node-express-start'? [yN]:
  Create services to bind to 'node-express-start'? [yN]: Y
    1: mongodb
    2: mysql
    3: postgresql
    4: rabbitmq
    5: redis
  What kind of service?: 5
  Specify the name of the service [redis-9bea7]: redis-asms
  Create another? [yN]: N
  Would you like to save this configuration? [yN]: Y
  Manifest written to manifest.yml.
  Creating Application: OK
  Creating Service [redis-asms]: OK
  Binding Service [redis-asms]: OK
  Uploading Application:
  Checking for available resources: OK
  Processing resources: OK
  Packing application: OK
  Uploading (305K): OK
Push Status: OK

Note that here I responded Yes to saving the configuration which will create a file called manifest.yml. A manifest.yml helps you quickly push and update apps. You can read more about it here.

Now you can run this command to add the keys from the services.

$ export APP_NAME=your_app_name
$ vmc env-add $APP_NAME airbrake_api_key=your_key
$ vmc env-add $APP_NAME github_client_id=github_id
$ vmc env-add $APP_NAME github_client_secret=github_secret
$ vmc env-add $APP_NAME facebook_app_id=fb_id
$ vmc env-add $APP_NAME facebook_app_secret=fb_secret
$ vmc env-add $APP_NAME NODE_ENV=production
$ vmc env-add $APP_NAME twitter_consumer_key=twitter_key
$ vmc env-add $APP_NAME twitter_consumer_secret=twitter_secret

To finish, run:

  vmc start

And that’s it! You are up and running with the boilerplate app as seen here. Please note that the app may not work to spec on IE, but works on Firefox, Safari and Chrome.

Observations so far

node-express-boilerplate is a great starting point on which to build an activity stream engine given that it addresses:

  • Robust real-time messaging between browser and server. Socket.io adapts to the protocols supported by the server and client
  • Performance via Asset Bundling and Minification
  • Provides SSO Support to major Social Networks
  • Handles scalable session management via Redis
  • Built on a great MVC framework

Also, it was good to see that @mape had abstracted the infrastructure details via the creation of a siteConfig.js. We enhanced this even further by using environment variables.

As you saw on the walkthrough all this was possible thanks to the open source community and using a robust platform as a service like CloudFoundry which had everything I needed. I was able to use @igo‘s “cloudfoundry” module to assist in parsing environment details in my app and thus made siteConfig.js even more straightforward.

In the next blog post, I will cover how to start the modification of this app into an Activity Stream engine. The tutorial will include how to create a Node.js module like activity-streams-mongoose and how to manage the persistance of the Activity Streams data on MongoDB as well as real time syndication across multiple app instances with Redis PubSub.

Signup for Cloud Foundry today, and start building your own cool app!

-Monica Wilkinson, Cloud Foundry Team

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | Leave a comment

Running Standalone Web Applications on Cloud Foundry

In this final post of the four-part series on deploying standalone apps to Cloud Foundry, we will explore how to build and deploy JVM-based web applications that aren’t packaged as traditional WAR files. This includes applications that are built on top of an NIO Framework like Grizzly or Netty (notable frameworks include Blue Eyes and vert.x) and applications that ship their own container, such as an embedded Jetty server.

Also in this series:

Deploying a Spray Application to Cloud Foundry

Spray is a suite of lightweight Scala libraries for building and consuming RESTful web services on top of Akka. Let’s deploy the Spray simple-http-server example that uses spray-can: a low-level, low-overhead, high-performance, fully asynchronous HTTP/1.1 server.

mycomp$: git clone git://github.com/spray/spray.git
mycomp$: cd spray/examples/spray-can/simple-http-server

We will use the sbt-package-dist plugin to package the app and all of its dependencies into a Zip file that we can push to Cloud Foundry. Therefore, we need to add the following files to the simple-http-server directory:

build.sbt:

import com.twitter.sbt._

seq(StandardProject.newSettings: _*)

packageDistZipName := "simple-http-server.zip"

organization := "cc.spray"

name := "simple-http-server"

version := "0.1.0-SNAPSHOT"

scalaVersion := "2.9.1"

resolvers ++= Seq(
  "Typesafe repo" at "http://repo.typesafe.com/typesafe/releases/",
   "spray repo" at "http://repo.spray.cc/"
)

libraryDependencies ++= Seq(
   "cc.spray" % "spray-server" % "1.0-M1",
   "cc.spray" % "spray-can" % "1.0-M1",
   "com.typesafe.akka" %   "akka-actor" % "2.0"
)

project/plugins.sbt:

addSbtPlugin("com.twitter" %% "sbt-package-dist" % "1.0.0")

resolvers += "twitter-repo" at "http://maven.twttr.com"

project/build.properties:

sbt.version=0.11.2

Next, we need to modify Main.scala to start the HTTP server on the host and port provided by Cloud Foundry:

server ! HttpServer.Bind(Option(System.getenv("VCAP_APP_HOST")).getOrElse("localhost"),
  Option(System.getenv("VCAP_APP_PORT")).getOrElse("8080").toInt)

Now we are ready to build and deploy the sample!

mycomp$: sbt clean compile package-dist
mycomp$: vmc push simple-http-server --path=dist/simple-http-server/simple-http-server.zip
Detected a Standalone Application, is this correct? [Yn]:
1: java
2: node
3: node06
4: ruby18
5: ruby19
Select Runtime [/java]:
Selected java
Start Command: java $JAVA_OPTS -jar simple-http-server_2.9.1-0.1.0-SNAPSHOT.jar
Application Deployed URL [None]: simple-http-server.${target-base}
Memory reservation (128M, 256M, 512M, 1G, 2G) [512M]:
How many instances? [1]:
Create services to bind to 'simple-http-server'? [yN]:
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: OK
Uploading Application:
Checking for available resources: OK 
Processing resources: OK
Packing application: OK
Uploading (248K): OK
Push Status: OK
Staging Application 'simple-http-server': OK
Starting Application 'simple-http-server': OK

So we’ve pushed the simple-http-server Zip file as a standalone app with a Java runtime. We gave the command “java $JAVA_OPTS -jar simple-http-server_2.9.1-0.1.0-SNAPSHOT.jar” to start the server, as sbt-package-dist creates an executable jar file. Notice the use of the JAVA_OPTS environment variable. When we deploy this app, Cloud Foundry will set JAVA_OPTS to a min and max heap size based on the memory reservation we provide. If we are running against Micro Cloud Foundry or a local vcap setup, remote debug options will also be added to JAVA_OPTS if we push or start the app with –debug. That’s right, you can remote debug your standalone JVM applications with your favorite IDE.

Since “simple-http-server” needs a web port, we provided a URL to use. Notice the use of the ${target-base} variable for the domain. This will allow us to reuse the generated manifest against multiple clouds (such as public or Micro Cloud Foundry). Let’s visit the web page and confirm that the app is up and running:

Looks like we are in business with spray! Note that you can access this complete example here.

Deploying an Embedded Jetty Server to Cloud Foundry

Since its launch, Cloud Foundry has allowed you to easily deploy a wide variety of web applications to Tomcat. We take care of configuring and starting the container, you bring the web app! However, sometimes you may want to bundle your own container or web server. Standalone app support allows you to do this. Let’s see an example using Unfiltered, a toolkit for servicing HTTP requests in Scala.

We will start by using giter8 to create a simple project template:

mycomp$: g8 softprops/unfiltered
This template generates an Unfiltered project. By default it depends on "unfiltered-jetty". For AJP support, set unfiltered_module to "unfiltered-jetty-ajp".
version [0.1.0-SNAPSHOT]:
name [My Web Project]:
cf-unfiltered-sample unfiltered_version [0.6.1]:
Applied softprops/unfiltered.g8 in cf-unfiltered-sample
mycomp$: cd cf-unfiltered-sample

We need to introduce the same sbt-package-dist build settings as the previous example. Add the following to the top of build.sbt:

import com.twitter.sbt._

seq(StandardProject.newSettings: _*)

packageDistZipName := "cf-unfiltered-sample.zip"

And create the plugins.sbt and build.properties files in the project directory as outlined above. Finally, we need to modify Example.scala to start Jetty on the port provided by Cloud Foundry:

val http = unfiltered.jetty.Http(Option(System.getenv("VCAP_APP_PORT")).getOrElse("8080").toInt)

And we need to modify avsl.conf to write the log file to a location relative to the app’s working directory:

[handler_h1]
...
path: log
...

Now we are ready to build and deploy the sample!

mycomp$: sbt clean compile package-dist
mycomp$: vmc push cf-unfiltered-sample --path=dist/cf-unfiltered-sample/cf-unfiltered-sample.zip
Detected a Standalone Application, is this correct? [Yn]:
1: java
2: node
3: node06
4: ruby18
5: ruby19
Select Runtime
[/java]

: Selected java Start Command: java $JAVA_OPTS -jar cf-unfiltered-sample_2.9.1-0.1.0-SNAPSHOT.jar Application Deployed URL [None]: cf-unfiltered-sample.${target-base} Memory reservation (128M, 256M, 512M, 1G, 2G) [512M]: How many instances? [1]: Create services to bind to 'cf-unfiltered-sample? [yN]: Would you like to save this configuration? [yN]: y Manifest written to manifest.yml. Creating Application: OK Uploading Application: Checking for available resources: OK Processing resources: OK Packing application: OK Uploading (248K): OK Push Status: OK Staging Application 'cf-unfiltered-sample': OK Starting Application 'cf-unfiltered-sample': OK

The answers we gave here are pretty much identical to those given in the first section. We provisioned a Java runtime, provided a start command that includes JAVA_OPTS, and supplied a URL.

Looks like the app is up!

You can check out this complete example here.

Conclusion

In this final installment of the four-part series, we introduced new support for standalone applications and showed some examples of common uses. We would love to hear your use cases and suggestions for enhancing this support. Please visit the Forums or JIRA, or submit a pull request. We look forward to seeing your new standalone apps!

- Jennifer Hickey
The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | 4 Comments

Running Workers on Cloud Foundry with Spring

In the two previous posts in this series, we discussed using Cloud Foundry’s new support for standalone apps to deploy worker processes. We looked at an example using Resque for Ruby apps. In this third installment, we explore using Spring to create workers in Java apps.

Also in this series:

Let’s walk through an example.

Deploying the Cloud Foundry Twitter Search Sample

Cloud Foundry Twitter Search includes two applications: a standalone Java application that periodically polls Twitter for tweets containing the word “cloud” and a Node.js web application that displays the results. The applications communicate via a shared RabbitMQ service. The worker publishes tweet information to a RabbitMQ exchange, and the web application consumes the tweets and pushes them to the browser using SockJS.

Let’s clone the sample app from Github:

mycomp:dev$ git clone https://github.com/cloudfoundry-samples/twitter-rabbit-socks-sample
mycomp:dev$ cd twitter-rabbit-socks-sample/twitter2rabbit

The worker app is written with Spring Integration. In fact, all of the worker’s logic is contained in a single Spring context file.

mycomp:twitter2rabbit$ more src/main/resources/org/springsource/samples/twitter/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:int-twitter="http://www.springframework.org/schema/integration/twitter"
    xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
    xmlns:rabbit="http://www.springframework.org/schema/rabbit"
    xmlns:cloud="http://schema.cloudfoundry.org/spring"
    xsi:schemaLocation="http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/integration/twitter http://www.springframework.org/schema/integration/twitter/spring-integration-twitter-2.1.xsd
		http://www.springframework.org/schema/integration/amqp http://www.springframework.org/schema/integration/amqp/spring-integration-amqp-2.1.xsd
		http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd
		http://schema.cloudfoundry.org/spring http://schema.cloudfoundry.org/spring/cloudfoundry-spring-0.8.xsd">

    <int-twitter:search-inbound-channel-adapter id="twitter" query="cloud">
        <int:poller fixed-rate="5000" max-messages-per-poll="10"/>
    </int-twitter:search-inbound-channel-adapter>

	<int:transformer input-channel="twitter" expression="payload.fromUser + ': ' + payload.text"  output-channel="rabbit"/>

	<int-amqp:outbound-channel-adapter id="rabbit" exchange-name="tweets"/>

	<rabbit:fanout-exchange name="tweets" durable="false"/>

	<rabbit:admin connection-factory="rabbitConnectionFactory"/>

	<rabbit:template id="amqpTemplate" connection-factory="rabbitConnectionFactory"/>

	<beans profile="default">
		<rabbit:connection-factory id="rabbitConnectionFactory"/>
	</beans>

	<beans profile="cloud">
		<cloud:rabbit-connection-factory id="rabbitConnectionFactory"/>
	</beans>

</beans>

Using Spring Integration, we’ve set up an Inbound Twitter Channel Adapter to query Twitter for the word “cloud” every five seconds. The user and text from each tweet is published to an AMQP exchange named “tweets.”  The connection to Rabbit is controlled by the choice of “default” or “cloud” profile. The cloud profile uses the cloud namespace provided by the cloudfoundry-runtime library to create a connection to a single Rabbit service bound to the app. The only code in this project is a single class that activates the cloud profile and bootstraps the ApplicationContext.

In order to run this example on Cloud Foundry, we’ll need to package up all of the dependencies. Enter the Maven Application Assembler Plugin.

<build>
	<plugins>
		<plugin>
			<groupId>org.codehaus.mojo</groupId>
			<artifactId>appassembler-maven-plugin</artifactId>
			<version>1.1.1</version>
			<executions>
				<execution>
					<phase>package</phase>
					<goals>
						<goal>assemble</goal>
					</goals>
					<configuration>
						<assembledirectory>target</assembledirectory>
						<programs>
							<program>
								<mainClass>org.springsource.samples.twitter.Demo</mainClass>
							</program>
						</programs>
					</configuration>
				</execution>
			</executions>
		</plugin>
	</plugins>
</build>

The generated start script, target/appassembler/bin/demo, uses the JAVA_OPTS environment variable to pass options to Java. When this app is deployed, Cloud Foundry will set JAVA_OPTS to a min and max heap size based on the memory reservation we provide. If we are running against a local cloud, remote debug options will also be added to JAVA_OPTS if we push or start the app with –debug. That’s right, you can remote debug your standalone Java applications with your favorite IDE.

Now we’ll do a “mvn package” and we’re ready to deploy to Cloud Foundry from our new distribution directory:

mycomp:twitter2rabbit$ vmc push twitter2rabbit --path=target/appassembler
Detected a Standalone Application, is this correct? [Yn]:
1: java
2: node
3: node06
4: ruby18
5: ruby19
Select Runtime [/java]:
Selected java
Start Command: bin/demo
Application Deployed URL [None]:
Memory reservation (128M, 256M, 512M, 1G, 2G) [512M]:
How many instances? [1]:
Create services to bind to 'twitter2rabbit'? [yN]: y
1: mongodb
2: mysql
3: postgresql
4: rabbitmq
5: redis
What kind of service?: 4
Specify the name of the service [rabbitmq-f7939]: twitter-rabbit
Create another? [yN]:
Would you like to save this configuration? [yN]: y
Creating Application: OK
Creating Service [twitter-rabbit]: OK
Binding Service [twitter-rabbit]: OK
Uploading Application:
 Checking for available resources: OK
 Processing resources: OK
 Packing application: OK
 Uploading (32K): OK
Push Status: OK
Staging Application 'twitter2rabbit': OK
Starting Application 'twitter2rabbit': OK

VMC has detected that twitter2rabbit is a standalone application, and we selected the Java runtime. We specify the command “bin/demo” to start the server using the generated script. We saved the manifest file for future deployments. The app should now be running and publishing tweets to an exchange on the twitter-rabbit service.

Now let’s deploy the front-end Node.js web application to display these tweets.

mycomp:twitter2rabbit$ cd ../rabbit2socks
mycomp:rabbit2socks$ npm install
mycomp:rabbit2socks$ vmc push mytwittersearch --runtime=node06
Detected a Node.js Application, is this correct? [Yn]:
Application Deployed URL [mytwittersearch.cloudfoundry.com]:
Memory reservation (128M, 256M, 512M, 1G, 2G) [64M]:
How many instances? [1]:
Bind existing services to 'mytwittersearch'? [yN]: y
1: twitter-rabbit
Which one?: 1
Create services to bind to 'mytwittersearch'? [yN]:
Would you like to save this configuration? [yN]: y
Creating Application: OK
Binding Service [twitter-rabbit]: OK
Uploading Application:
  Checking for available resources: OK
  Processing resources: OK
  Packing application: OK
  Uploading (18K): OK
Push Status: OK
Staging Application 'mytwittersearch': OK
Starting Application 'mytwittersearch': OK

The application is pushed and bound to the same twitter-rabbit service as the Java worker, twitter2rabbit. The app will consume tweets from this Rabbit service and push them to the browser using SockJS. Let’s launch the website and watch as tweets start popping up! Here’s a screenshot of the Twitter traffic when I ran my app.

And there you have it! The web page is dynamically updated with results from the Spring Integration-powered worker app. Clone the sample application and try it yourself. The readme also contains instructions on building and deploying with Gradle (using the Gradle Application Plugin to create a distribution) instead of Maven.

There are many other ways to use Spring to create worker apps, including using the Spring Task Scheduler abstraction or Spring Batch. For more examples of Spring workers on Cloud Foundry, check out Josh Long’s post on the SpringSource blog.

In the next and final post of the series, we will look at another category of standalone apps: self-executing web applications. With standalone application support, the possibilities are endless.

- Jennifer Hickey
The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | 3 Comments

Running Resque Workers on Cloud Foundry

We introduced Cloud Foundry’s new “standalone” applications feature in the first post in this four-part series. In this second installment, we will look at the most common use of a standalone application–the worker process. Workers can be used for all kinds of asynchronous background jobs, such as updating search indexes, emailing all users with a password reset approaching, performing a database backup to persistent storage, or uploading new customer data from external storage. In this post, we will walk through an example of deploying workers to Cloud Foundry using Resque.

Also in this series:

Resque Workers on Cloud Foundry

Let’s start by cloning the Resque Demo Example.

mycomp:dev$ git clone git://github.com/defunkt/resque.git
mycomp:dev$ cd resque/examples/demo
Let’s add a Gemfile to the example to ensure that Cloud Foundry can find all required gems.

source "http://rubygems.org"
gem 'sinatra'
gem 'resque'
gem 'rake'
gem 'json'

We’ll run “bundle install” and “bundle package” to package the gems in vendor/cache, and we’re ready to deploy.  The resque server is a Rack app, so we’ll deploy it to Cloud Foundry as such.

mycomp:demo$ vmc push resque-server
Would you like to deploy from the current directory? [Yn]:
Detected a Rack Application, is this correct? [Yn]:
Application Deployed URL [resque-server.cloudfoundry.com]: 
Memory reservation (128M, 256M, 512M, 1G, 2G) [128M]:
How many instances? [1]:
Create services to bind to 'resque-server'? [yN]: y
1: mongodb
2: mysql
3: postgresql
4: rabbitmq
5: redis
What kind of service?: 5
Specify the name of the service [redis-2a462]: redis-work-queue
Create another? [yN]:
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: OK
Creating Service [redis-work-queue]: OK
Binding Service [redis-work-queue]: OK
Uploading Application:
Checking for available resources: OK
Processing resources: OK
Packing application: OK
Uploading (21K): OK
Push Status: OK
Staging Application 'resque-server': OK
Starting Application 'resque-server': OK
Let’s have a look at the resque-server app and add some jobs to the queue:
Now that we have some jobs, it’s time to deploy some workers!  First, we need to rename the generated manifest.yml for the Rack app, so it won’t automatically be used in the push.  We can use it again later by doing a “vmc push –manifest server-manifest.yml”.  Now, let’s push the app again as a standalone worker app.
mycomp:demo$ mv manifest.yml server-manifest.yml
mycomp:demo$ vmc push resque-worker
Would you like to deploy from the current directory? [Yn]:
Detected a Rack Application, is this correct? [Yn]: n
1: Rails
2: Spring
3: Grails
4: Lift
5: JavaWeb
6: Standalone
7: Sinatra
8: Node
9: Rack
Select Application Type: 6
Selected Standalone Application
1: java
2: node
3: node06
4: ruby18
5: ruby19
Select Runtime [ruby18]:
Selected ruby18
Start Command: bundle exec rake VERBOSE=true QUEUE=default resque:work
Application Deployed URL [None]:
Memory reservation (128M, 256M, 512M, 1G, 2G) [128M]:
How many instances? [1]:
Bind existing services to 'resque-worker'? [yN]: y
1: redis-work-queue
Which one?: 1
Bind another? [yN]:
Create services to bind to 'resque-worker'? [yN]:
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: OK
Binding Service [redis-work-queue]: OK
Uploading Application:
Checking for available resources: OK
Processing resources: OK
Packing application: OK
Uploading (0K): OK
Push Status: OK
Staging Application 'resque-worker': OK
Starting Application 'resque-worker': OK

So we’ve pushed resque-worker as a standalone app with a Ruby runtime. We gave the command “bundle exec rake VERBOSE=true QUEUE=default resque:work” to start the worker. It is recommended to use bundle exec to ensure that all required gems are available. Since resque-worker does not have a web front-end, we selected “None” for URL.

Lastly, we bound the app to the same Redis service used by resque-server. If you’ve perused the resque demo example, you may have noticed that it is setup to connect to a local Redis service. However, we didn’t change the code before we pushed it. How will the app connect to the provisioned Redis service? Since we used the Ruby runtime provided by Cloud Foundry, the app will benefit from the new Ruby auto-reconfiguration support. Cloud Foundry will automatically replace the local Redis connection with a connection to the Redis service we bound to the application!

Let’s check the logs and see if the worker completed that job:
mycomp:demo$ vmc logs resque-worker
====> /logs/stdout.log <====

Loading Redis auto-reconfiguration.
*** Starting worker ubuntu:10245:default
Auto-reconfiguring Redis.
*** got: (Job{default} | Demo::Job | [{}])
Processed a job!
*** done: (Job{default} | Demo::Job | [{}])
*** got: (Job{default} | Demo::Job | [{}])
Processed a job!
*** done: (Job{default} | Demo::Job | [{}])
And we can verify that the worker has registered through the web interface:
We can even scale the workers up.
mycomp:demo$ vmc instances resque-worker +2
Scaling Application instances up to 3: OK
And now the web interface shows three workers:


And there you have it! We can now deploy Resque workers as standalone apps on Cloud Foundry. Clone the Cloud Foundry resque-sample and try it out for yourself!

Conclusion

Cloud Foundry now provides improved Resque support through standalone applications, as well as support for other Ruby worker libraries or apps. If you can package all the bits and provide a start command, you can run it on Cloud Foundry! In the next installment in this series, we will explore another example of workers in action using Spring integration. Stay tuned!

- Jennifer Hickey
The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | Comments Off

Cloud Foundry Improves Support For Background Processing

Cloud Foundry has significantly enhanced support for worker applications that perform background processing by allowing applications to run on CloudFoundry.com without the application container. Cloud Foundry applications are no longer limited to Web applications that respond to HTTP requests. Instead, they can be run as executable or “standalone” applications. A standalone application is one that does not require a provided framework or container.

Many developers create distributed applications that have workers to perform specific functions and communicate via a data or messaging system, such as those developed with Spring Batch, Spring Integration, Resque, or Delayed Job. Now Cloud Foundry supports running these worker components by allowing you to push a directory or single file without choosing a pre-defined framework. Simply provide the command required to run your script or executable, chose a runtime, and you’re done. Besides background processing functions, the standalone application support enables these other types of applications as well:

  1. Container-less non-Servlet applications, such as those developed with Netty or Grizzly
  2. Web apps that run with their own bundled containers, such as Jetty

In this blog series, we will walk through several example deployments of standalone apps. We will start with a simple Hello World to illustrate the deployment steps. In future posts, we will show examples of worker apps, distributed apps, and bring-your-own-container and container-less Web apps. While the apps may vary in use case and implementation, the deployment procedure remains the same.

All of these apps are meant to be long-running, as with any other app on Cloud Foundry (meaning they can be scaled, will be monitored for health, restarted if crashed, etc.). We do not yet have support for short-lived background tasks or scheduled tasks. However, we encourage you to keep watching this space!

Getting Started with Standalone Apps on Cloud Foundry

First, install or update your Cloud Foundry command line tool (‘VMC’) to the latest version using the following command:

gem install vmc

You can verify that you got the right version using:

vmc -v

which should show the version to be 0.3.17 or higher.

Let’s start by deploying a simple Hello World Ruby application.

mycomp:$ cd simple-ruby-app
mycomp:$ ls
hello-world.rb
mycomp:$ more hello-world.rb
loop {
  puts 'Hello world'
  sleep 5
}

Since we need a long-running application, this script will print “Hello World” every 5 seconds until stopped. Let’s push this to Cloud Foundry using vmc:

mycomp:$ vmc push helloworld
Would you like to deploy from the current directory? [Yn]:
Detected a Standalone Application, is this correct? [Yn]:
1: java
2: node
3: node06
4: ruby18
5: ruby19
Select Runtime [ruby18]:
Selected ruby18
Start Command: ruby hello-world.rb
Application Deployed URL [None]:
Memory reservation (128M, 256M, 512M, 1G, 2G) [128M]:
How many instances? [1]:
Create services to bind to 'helloworld'? [yN]:
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: OK
Uploading Application:
Checking for available resources: OK
Packing application: OK
Uploading (1K): OK
Push Status: OK
Staging Application 'helloworld': OK
Starting Application 'helloworld': OK

So, what just happened?
1. vmc detected that the app was a “Standalone Application” (due to the fact that no other Framework support was detected).
2. We were asked to provide a runtime. Since the app needs Ruby to run, we chose the “ruby18″ runtime (which vmc detected as default).
3. We provided a command to use for starting the application. Since we’ve chosen a Ruby 1.8 runtime, we don’t need to provide the fully qualified path to Ruby. Cloud Foundry will automatically add Ruby 1.8 to the application’s path.
4. We chose “None” for the application URL. This will run the application without a Web port or URL. There are times when we will want a URL and Web port for a standalone application, as we’ll see in a later blog post.
5. vmc pushed the entire contents of the working directory to Cloud Foundry. Since we only had hello-world.rb in the directory, we could have also executed “vmc push –path ./hello-world.rb”. The –path option comes in handy when working with distribution zip files, as we’ll see in an upcoming post.

Let’s have a look at the application’s logs:

mycomp:$  vmc logs helloworld
====> /logs/stdout.log <====

Hello world
Hello world

As you can see, helloworld can be managed just like any other Cloud Foundry application:

mycomp:$  vmc instances helloworld +2
Scaling Application instances up to 3: OK
mycomp:$ vmc instances helloworld

+-------+---------+--------------------+
| Index | State   | Start Time         |
+-------+---------+--------------------+
| 0     | RUNNING | 04/20/2012 04:47PM |
| 1     | RUNNING | 04/20/2012 04:48PM |
| 2     | RUNNING | 04/20/2012 04:48PM |
+-------+---------+--------------------+

Let’s look at the logs again for two of the instances:

mycomp:$  vmc logs helloworld --instance 0
====> /logs/stdout.log <====
Hello world
Hello world
mycomp:$  vmc logs helloworld --instance 1
====> /logs/stdout.log <====
Hello world
Hello world

Standalone app deployment manifest

Let’s take a look at the manifest file we generated with that vmc push:

mycomp:$ more manifest.yml
---
applications:
.:
name: helloworld
framework:
  name: standalone
  info:
     description: Standalone Application
     mem: 128M
runtime: ruby18
command: ruby hello-world.rb
url:
mem: 128M
instances: 1

Seems pretty straightforward. The app is deployed against a “standalone” framework, with a command and ruby18 runtime. To save time, we’ll be sure to save this manifest file for future deployments.

Tips and Tricks

You should now be able to deploy any long-running app that you can package, using any of Cloud Foundry’s provided runtimes. However, there are some tips and tricks to getting the best experience from Cloud Foundry:

1. Use the VCAP_APP_PORT environment variable if your application requires a web port.
2. Connect your application to Cloud Foundry services using provided libraries (see below) or the VCAP_SERVICES environment variable (value is in JSON).

JVM Applications

1. Package your application using a build plugin that creates a distribution zip file or directory.
Maven AppassemblerGradle Application Plugin, and SBT package-dist are good plugins for creating a distribution, and we’ll show examples of all of these in future posts. It is best not to package your entire application in a single jar file, as you will not be able to take advantage of Cloud Foundry’s incremental upload capability.
2. Always include $JAVA_OPTS in your Java start commands.
When you select your application’s memory reservation through VMC, Cloud Foundry will set the JAVA_OPTS environment variable with corresponding min and max heap sizes, therefore you should include $JAVA_OPTS in your Java start commands (for example, “java $JAVA_OPTS -jar main.jar”). The start scripts generated by Maven Appassembler and Gradle Application Plugin already include JAVA_OPTS. Using JAVA_OPTS will also allow you to start your app in debug mode on local clouds, using “vmc start –debug.”
3. Use the cloudfoundry-runtime library to connect your application to Cloud Foundry services.

Ruby Applications

1. Always include a Gemfile.lock to ensure that all application dependencies are resolved by Cloud Foundry.
2. While not required, we recommend running “bundle package” before deploying your application. This will improve your application start time, as Cloud Foundry will not need to check its cache or download gems from rubygems.org.
3. Standalone Ruby applications can take advantage of Ruby Auto-Reconfiguration.  To make your own connections to Cloud Foundry services, use the cf-runtime gem.

Conclusion

In this post, we used a simple example to get up and running quickly with standalone apps on Cloud Foundry. In the next installments of this four part series, we will have an in-depth look at deploying more complex standalone apps.

Also in this series:

- Jennifer Hickey
The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in Announcement, CloudFoundry, Media | Comments Off

Cloud Foundry Powers Data Sets for Mumbai

This is the third post of a series of guest blogs by application developers. We are featuring a use case by Romin Irani, an individual developer who built APIs for valuable data sets in the City of Mumbai as a public service and hosted them on Cloud Foundry.

Guest blog by Romin Irani, Mind Storm Software

Access to world-class infrastructure coupled with the pay-per-use model has been a dream come true for start-ups and individual developers. For an individual developer and entrepreneur like me, the way I develop and make my applications available for others to use or evaluate has been permanently transformed.

Mumbai Public Data APIs

It has always been difficult for me to get various data sets for the city that I live in, i.e., Mumbai, India. Mumbai has a population of about 20 million people living in 233 square miles (603 sq. km.). Like many urban centers in developing countries, the city is growing faster than its government is able to provide services and infrastructure for its citizens.

If provided some of the city’s public data sets with APIs for those data, developers can come up with a variety of applications to harness that information and build applications to benefit the city residents. So I took the small step of building out a few data sets, such as:

  1. Help lines - Essential services like hospital phone numbers with locations and police emergency numbers. Mumbai has no central emergency telephone number like 9-1-1, so essential service numbers are helpful to have in one place.
  2. Blood banks - Nearly 60 city blood banks with phone numbers which can be looked up by their location, although much of the stocking and inventory-keeping is still done manually.
  3. Taxi and auto rates – Taxi/auto rate card fares as published by the Mumbai Administration for residents and visitors to correctly determine their meter charges and fares.

City of Mumbai Public Data Sets on Cloud Foundry

This type of scenario works very well with MongoDB.  The application is written in Node.js, interacts with the Cloud Foundry MongoDB service and provides JSON data for the various Mumbai data sets. Over time, I hope to keep introducing new data sets. To develop their own web, desktop or mobile clients, developers can simply invoke the REST Endpoints for each data set.

The data set is exposed via a REST API that is hosted on CloudFoundry.com:  http://mumbaidata.cloudfoundry.com

Why is Cloud Foundry is my preferred PaaS?

The impetus to learn more about Cloud Foundry came via CloudSpokes, a community-driven marketplace where developers take up programming challenges and get paid for that work. I have submitted code for more than six challenges now including some winning entries–all on Cloud Foundry.

These include a Node.js stock ticker, a salesforce.com Login Component, a Web page PDF-to-Box bookmarklet, and a salesforce.com data exporter that generated Word files from salesforce.com data–all of which are hosted and running great on Cloud Foundry. Top reasons why Cloud Foundry is my preferred PaaS:

  • Cloud Foundry provides a non-intrusive model for my Java applications. When I want to run a Java Web application that uses my home-grown MVC framework or use the Spring framework, it is all supported. I am no longer looking for workarounds.
  • It is easy to use, especially with the STS plug-in for Eclipse which makes developing and deploying with Cloud Foundry a breeze. The fact that you can be in a single environment to develop and deploy to the cloud is very nice! That coupled with being able to start and stop the applications, inspect the logs and even deploy to the Micro Cloud Foundry definitely boosts productivity. This is in sharp contrast to moving in and out of multiple environments for each stage of developing, testing and deploying your applications.
  • Also, I have access to services like MongoDB, RabbitMQ and many others that I can quickly integrate into my applications, as well as use the programming stack that is appropriate for the job.

What’s next?

One of my goals over the last year has been to develop a hands-on cloud computing course and I have struggled with the choice of a PaaS platform that would allow programmers with different language skills to all come under one roof and go through the course. With its polyglot nature, I hope to build that course out soon with Cloud Foundry as the engine running all the samples. The fact that I can even run locally via Micro Cloud Foundry is a huge plus.

I truly believe that the polyglot programmer has arrived and an open PaaS like Cloud Foundry is a great enabler to making that a reality.

Signup for Cloud Foundry today, and start building your own cool app!

Romin is a published author of several books and articles, and contributes regularly to ProgrammableWeb, where he focuses on API news. He currently runs a startup, Mind Storm Software, which is focused on quality hands-on training on cloud computing platforms and mobile development.

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | 2 Comments

Using JRuby for Rails Applications on Cloud Foundry

JRuby Rails applications can be deployed to CloudFoundry.com today with simple configuration changes. JRuby applications are commonly deployed to servlet containers by creating a .war file that contains the Rails app. We will do the same for Cloud Foundry with some changes to the database configuration, so the application can also access a database service on CloudFoundry.com.

Changes needed for deploying JRuby on Rails Applications to Cloud Foundry

There are two tasks we need to accomplish in order to get a JRuby application running on CloudFoundry.com. First we need to configure the application to connect to the database service on CloudFoundry.com by modifying the database.yml file in the configuration directory. We also need to run the equivalent of ‘rake db:migrate', when we deploy the application so that the database tables are created. We can do this by adding an initializer in the config/initializers directory.

The information we need to configure the database connection is available in the environment variable, VCAP_SERVICES. We could either parse that variable programmatically or use the convenient Cloud Foundry run-time gem (see Using Cloud Foundry Services with Ruby: Part 2 – Run-time Support for Ruby Applications blogpost), which is what we will do here. To use this gem we need to include it in our Gemfile:

...
gem  'cf-runtime'
...

Now that we have added this gem, we can add some code snippets to the database.yml file to access the database service information for the production environment. The following is the production portion from a database.yml file, where we are using a MySQL database:

config/database.yml

production:
  adapter: mysql
  <% require 'cfruntime/properties' %>
  <% db_svc = CFRuntime::CloudApp.service_props('mysql') %>
  database: <%= db_svc[:database] rescue 'bookshelf_production' %>
  username: <%= db_svc[:username] rescue 'root' %>
  password: <%= db_svc[:password] rescue '' %>
  host: <%= db_svc[:host] rescue 'localhost' %>
  port: <%= db_svc[:port] rescue '3306' %>

As you can see, we added a require statement for cfruntime/properties, and then we get a hash of the service properties by calling the service_props method passing in the type of service we are using. If there is only one service of that type bound to the application, then there is no need to specify the actual name of the service. You will need to specify the actual service name if you bind multiple services of the same type to your app. The hash of service properties is stored in a variable called db_svc, and code extracts the corresponding values to be used for database, username, password, host, and port. Each of these statements have a rescue clause that provides values to use if we are not operating in a Cloud Foundry environment, in which case the db_svc would be nil.

Alternatively, the production portion of the database.yml file would look like this for PostgreSQL:

production:
  adapter: postgresql
  encoding: unicode
  <% require 'cfruntime/properties' %>
  <% db_svc = CFRuntime::CloudApp.service_props('postgresql') %>
  database: <%= db_svc[:database] rescue 'bookshelf_production' %>
  username: <%= db_svc[:username] rescue 'bookshelf' %>
  password: <%= db_svc[:password] rescue '' %>
  host: <%= db_svc[:host] rescue 'localhost' %>
  port: <%= db_svc[:port] rescue '5432' %>

Next, we turn our attention to the creation of the tables we need for our app. For this to happen, we need to add the following initializer to the config/initializers directory when we deploy the app. I named this initializer cf_db_migrate.rb:

config/initializers/cf_db_migrate.rb

require 'cfruntime/properties'

# Run the equivalent of rake db:migrate on startup
if CFRuntime::CloudApp.running_in_cloud?
  migrations = Rails.root.join('db','migrate')
  if migrations.directory?
    ActiveRecord::Migrator.migrate(migrations)
  end
end

We use cfruntime/properties again and check to see that we are running in the cloud. Next we check to see if the db/migrate directory exists and if it does we run the database migration using the migration files in the directory ( ActiveRecord::Migrator.migrate(migrations) ).

One additional change we have to make is to the warble configuration. It does not include the db/migrate directory in the generated war file by default, so we need to add this to the configuration by specifying config.includes = FileList["db/migrate/*"]. Here are the relevant contents of the config/warble.rb file:

config/warble.rb

# Warbler web application assembly configuration file
Warbler::Config.new do |config|

  # Application directories to be included in the webapp.
  config.dirs = %w(app config lib log vendor tmp)

  # Additional files/directories to include, above those in config.dirs
  config.includes = FileList["db/migrate/*"]

end

A complete example

This assumes that you have a working JRuby environment with Rails, Warbler and MySQL gems already installed.

We have seen above what changes are needed, so let’s quickly generate a Rails app and make the required changes and deploy the app to CloudFoundry.com. If you don’t already have JRuby installed a good place to start is Getting Started with JRuby.

Create the JRuby Rails App

First we create the new app and create the first domain object with full scaffolding.

jruby -S rails new bookshelf -d mysql
cd bookshelf
jruby -S rails generate scaffold Book title:string category:string published:integer price:decimal{10.2} isbn:string

Next we remove the generated public/index.html and modify the config/routes.rb to use ‘books’ as the root:

rm public/index.html
vi config/routes.rb

Here is the route that I added in config/routes.rb:

Bookshelf::Application.routes.draw do
  resources :books

  # You can have the root of your site routed with "root"
  # just remember to delete public/index.html.
  # root :to => 'welcome#index'
  root :to => 'books#index'

  # See how all your routes lay out with "rake routes"

end

Now we will run this app locally to make sure it works:

jruby -S rake db:create
jruby -S rake db:migrate
jruby -S rails server

The Rails empty list view of the Book entity shows that this is indeed working. Now I can add new books to my bookshelf.

Modify the JRuby Rails App for CloudFoundry deployment

Let’s start by making the following changes that we mentioned above:

  • add the gem cf-runtime to the Gemfile
  • modify the “production:” section of the config/database.yml file as shown above
  • add a file named config/initializers/cf_db_migrate.rb with the content shown above

Next we need to generate the Warbler config file so we run:

jruby -S warble config

Now we can:

  • modify the config/warble.rb to add the db/migrate directory as shown above

Those are all the changes needed and we are now ready to package and deploy this app.

Package and deploy the JRuby Rails App to CloudFoundry

We will use Warbler to package the app into a war and the CloudFoundry vmc command line utility to deploy it.

The process we use to package the application into a war file is a simple: bundle, pre-compile assets and run Warbler:

jruby -S bundle install
jruby -S rake assets:precompile
jruby -S warble

This creates a bookshelf.war in the root directory of our Rails app. At the moment there are some issues running the vmc command with JRuby but we are working on a fix for this. In the meantime we can move the war file to another directory, so that I can easier switch to use regular “C” Ruby. I’ll create a ‘deploy‘ directory and configure that to use Ruby 1.9.2-p290 (I’m using rbenv, but you could use RVM as well):

mkdir deploy
mv bookshelf.war deploy/.
cd deploy
rbenv local 1.9.2-p290
# (if you use RVM the command should be 'rvm ruby-1.9.2-p290')

Now we are ready to log in to CloudFoundry and deploy our application. For this part you need to have vmc installed.

vmc target api.cloudfoundry.com
vmc login cloud@mycompany.com
Password: *****
Successfully logged into [http://api.cloudfoundry.com]
vmc push bookshelf
Would you like to deploy from the current directory? [Yn]: Y
Application Deployed URL [bookshelf.cloudfoundry.com]: mybookshelf.cloudfoundry.com
Detected a Java Web Application, is this correct? [Yn]: Y
Memory reservation (128M, 256M, 512M, 1G, 2G) [512M]: 512M
How many instances? [1]: 1
Bind existing services to 'bookshelf'? [yN]: N
Create services to bind to 'bookshelf'? [yN]: Y
1: mongodb
2: mysql
3: postgresql
4: rabbitmq
5: redis
What kind of service?: 2
Specify the name of the service [mysql-a4fd7]: mysql-books
Create another? [yN]: N
Would you like to save this configuration? [yN]: N
Creating Application: OK
Creating Service [mysql-books]: OK
Binding Service [mysql-books]: OK
Uploading Application:
  Checking for available resources: OK
  Processing resources: OK
  Packing application: OK
  Uploading (707K): OK
Push Status: OK
Staging Application 'bookshelf': OK
Starting Application 'bookshelf': OK

The vmc commands are highlighted above. Most defaults have been accepted except for the URL and whether a service should be created. I used the URL ‘mybookshelf.cloudfoundry.com‘ instead of the default to avoid collision with existing bookshelf applications. I answered ‘Y‘ to the question of creating a new service and picked (2) mysql and gave it the name of ‘mysql-books‘.

We should now see the app running:

vmc apps

+-------------+----+---------+---------------------------------+---------------+
| Application | #  | Health  | URLS                            | Services      |
+-------------+----+---------+---------------------------------+---------------+
| bookshelf   | 1  | RUNNING | mybookshelf.cloudfoundry.com    | mysql-books   |
+-------------+----+---------+---------------------------------+---------------+

So we can now enter ‘http://mybookshelf.cloudfoundry.com/‘ and see the Bookshelf application come to life and add some books.

You can review and download the entire source used for this sample at cloudfoundry-samples/jruby-rails-bookshelf or if you just want to see the changes needed to deploy in Cloud Foundry look at this commit.

Conclusion

We have shown that it’s possible to deploy a simple JRuby on Rails application to cloudfoundry and use a MySQL service as the backing data store. All that is required is some modifications to the apps configuration of the database.

In a future post we’ll take a look at similar changes that we need to do for a JRuby Sinatra app that uses DataMapper for persistence.

- Thomas Risberg
The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry | 1 Comment

More than 2,000 Developers Attend Cloud Foundry China Open Tour

The first two stops of Cloud Foundry Open Tour at Beijing and Shanghai were huge successes! We had about 1000+ developers show up at each city for this one day event. 10 speakers from across the world delivered 15 high quality and deeply technical sessions to attendees.

Open Tour is not only a developers’ grand gathering to learn about Cloud Foundry, it’s also for partner executives and university professors to share their success story on Cloud Foundry, and online media to live broadcast the event and interview speakers.

Developers in China are extremely passionate about Cloud Foundry: attendees showed up at the venue before 7AM (for a conference that starts at 9AM); people were lining up for registration at 7:30AM. This phenomenon has only happened before at the Apple Store. There were developers flying to Beijing and Shanghai from south and west side of China just for this event, and every single session at the conference was standing room only.

Big THANKS to our team of speakers: Charlotte Yarkoni, Mark Lucovsky, Patrick Chanezon, Chris Richardson, Alan Ren, Victor Jieh, Stephen Hu, Bill Sun, Figo Feng and Long Wang from the Cloud Foundry global and China team! Our great appreciation and many thanks to all partner speakers: Lei Cong from Sina App Enginee, Tuoc Luong from SNDA Grand Cloud, and Guoxiong Dai from InGeek Cloud.


Staying ‘Till the End’

No developer left the conference before it was over. We had two keynotes delivered by Mark Lucovsky and Chris Richardson in the morning – Cloud Foundry Technical Overview and Bootcamp. Then the ballroom separated to 3 different breakout sessions for topics about languages and frameworks, cloud databases, and solution partners. The Open Tour is a purely developer conference. All sessions include our partners and are deep dives into the code level (which are developers’ favorite, right?). Our elite speakers and well-designed content are the keys to the success.

The keynotes were full of vision, mission and decorated slides, but most importantly they start from code! Mark’s keynote “Developer Perspective” clearly re-emphasized that the Open Tour is a developer conference. After a quick Cloud Foundry introduction, Mark switched to coding mode, he went through a complicated sample app which leveraged many of the key features of Cloud Foundry. He then shared his thoughts on the producer/consumer pattern, node.JS server, tunneling (“caldecott”), redis, and much more. Chris’ “Cloud Foundry Bootcamp” session led people deeper into Cloud Foundry. Chris used 100+ slides to give a very detailed introduction and demo to help developers with different backgrounds to get started with Cloud Foundry.

In the afternoon, Patrick Chanezon and Chris Richardson hosted the track for programing languages and frameworks. This was the most popular track. “Node.JS Introduction”, “Spring into the Cloud” and “Using Ruby in Cloud Foundry” gave developers a more clear understanding of the power of multi-framework support in Cloud Foundry. Chris, Victor and Long Wang contributed 4 very interesting sessions in the Cloud database track. “SQL, NoSQL, NewSQL? What’s a developer to do?”, “Using MongoDB in Cloud Foundry”, “Data Director” and “GemFire/SQLFire, the RAM DB in Cloud Foundry” gained a lot of attention.

Partner Showtime

Enabling partners and making them successful is an important pillar for Cloud Foundry. It is our great honor to invite three famous public cloud service providers, Sina App Engine, Shanda Grand Cloud & InGeek Cloud, to join the events and announce their partnership with VMware to promote adoption of Cloud Foundry. SINA App Engine (SAE), the largest Open Platform in China with 200,000 developers and 100,000 apps, launched its first Cloud Foundry based Ruby PaaS engine. InGeek, by leveraging the vSphere based IaaS cloud, launched a PaaS cloud with Cloud Foundry and vFabric Data Director integrated via Service Gateway. Three tier-1 universities in China, Tsinghua University, Fudan University & Shanghai Jiaotong University, also joined the event. They have formed partnership with VMware China R&D on university innovation programs to drive Cloud Foundry adoption via course ware, joint lab & EDU-PaaS private cloud.

Interesting Sidelights

A developer conference is about fun, we have some interesting sidelights to share:

Weibo: For some reason, there is no Twitter access in China, but we have SINA Weibo, the China version of Twitter with about 300+ million users. With the help of Google Translate, Mark, Patrick and Chris interacted with their Chinese fans at Weibo. They even registered their own Weibo account to start tweeting and win a lot of followers! Here are the links to their account: @大牛马克 for Mark, @快乐的法国极客 for Patrick and @温文尔雅的程序员大爷 Chris. Patrick’s name means “most joyous French geek”, and Chris’ name means “gentle programmer’s uncle”. Mark’s name means “Big Bull Mark”, the story is at below. These accounts were all getting developers feedback to their sessions.

From Chairman to Big Bull: Mark was famous for his chair story. He didn’t bring his chair for the China trip, but he won a lot of new fans in Beijing and Shanghai. He was surrounded by developers after he finished the keynotes, and  people even tried to ask him technical questions in the men’s room! In the Chinese developer community, the “Big Bull” is a kind of respectful title for a distinguished technician or developer, so we made a stone stamp logo (the red one) for Mark and named his Weibo account @大牛马克 (the Big Bull Mark). You will probably soon see this logo in Mark’s email signature.

Li Bai and Cloud: Patrick is a big lover of Chinese ancient poems. He started his node.JS session by quote Li Bai and Wang Wei, the two major Chinese poets of the Tang dynasty. These two sages use poems to describe beautiful clouds over 1200 years ago, but they probably couldn’t imagine that we will quote the poems in today’s Cloud computing era to make the perfect combination of art and technology.

Weibo Feedback

Developers kept track of their feedback to the Could Foundry Open Tour on Weibo, the following are some interesting quotes:

  • Look forward to see the 100% open source of Cloud Foundry, this will provide strong foundation for enterprise to build private cloud; this is the Linux in the Cloud. P.S., love to use MacOS for cloud development, recommend to all UNIX developers. From @乔布斯胡
  • Join the VMware Cloud Foundry event today, get a USB stick, T-shirt and a substantial buffet lunch. The event is good in general, the key advantage of Cloud Foundry is developers can use their familiar programming language and framework to build app, easy to use and config, love it. From @ArKiarX
  • The Cloud Foundry Open Tour is very gelivable, depth technical sessions, great speakers, and a good buffet lunch. From @忘了游泳的鱼ooO
  • The SINA guest speaker mentioned about eco-system, the open source based Cloud Foundry is building and developing the cloud eco-system. From @中国董永乐
  • Learnt quite a lot in Cloud Foundry Open Tour, feel more and more exciting about Cloud! From @奔跑的大兵
  • Patrick is the most joyous speaker of the day, he even trying to access Twitter. From雪中

The Open Tour is continuing across the world

Cloud Foundry Open Tour 2012 is a global series of one day developer events, Beijing and Shanghai are the first two stops. The team is heading to Kiev, Moscow and London. Come join us and feel the power of Cloud Foundry!

-The Cloud Foundry China Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in Announcement, CloudFoundry, Media, oss | Leave a comment

Cloud Foundry’s First Birthday: More Clouds, Code, Community and Partners

Today we celebrated Cloud Foundry’s first anniversary with additional multi-cloud deployment choices, new tools for operating large scale Cloud Foundry services, a new system for managing open source contributions and new partnerships.

More Clouds

In a recent post, we’ve explained why preserving multi-cloud choice and flexibility is so important in the cloud era. As an open platform as a service, Cloud Foundry is designed to run on a wide variety of clouds and cloud infrastructures.

In a live demo today we demonstrated how Cloud Foundry is making multi-cloud a reality with the deployment of an application to four different Cloud Foundry-based clouds within minutes without any code or configuration changes.

More Code

Today we introduced and open sourced Cloud Foundry BOSH, an open source tool chain for release engineering, deployment and lifecycle management of large scale distributed services.

Designed to enable the systematic and prescriptive evolution of services, BOSH facilitates the operation of production instances of Cloud Foundry. BOSH automates a variety of cloud infrastructure and allows targeted service updates with consistent results and minimal to no down time.

Proven in the course of operating CloudFoundry.com, BOSH is available under an Apache license from CloudFoundry.org and currently includes support for VMware vSphere as well as early support for Amazon Web Services.

Additional technical details on BOSH are available on GitHub.

More Community

Cloud Foundry has been an open source project from the day it was released. The project is active on GitHub and has seen broad and meaningful contributions from the developer community, including support for dozens of major developer frameworks and application services.

Today we unveiled the new CloudFoundry.org,  a new source code management system for Cloud Foundry. The new system converges Cloud Foundry source code to a single set of public code repositories on GitHub integrated with Gerrit for code reviews and Jenkins for continuous integration.  The new system enables developers to submit day-to-day change requests directly to the public repository. It simplifies community code contributions, improves code quality and offers greater visibility into code changes as they happen.

Additional details on how to contribute and participate are on the Cloud Foundry open source blog.

More Partners

There are a broad range of companies investing in and around Cloud Foundry, including development and deployment tools, public cloud operators, private cloud distributions, application service developers and ISVs.

Today five additional companies announced they are joining the Cloud Foundry ecosystem:

  • Cloud9’s browser-based integrated development environment now supports deployment to CloudFoundry.com.
  • Collabnet is making Cloud Foundry a core deployment platform for their suite of agile enterprise development tools.   
  • ServiceMesh has added policy-driven deployment and governance of Cloud Foundry to their enterprise Agility PlatformTM.
  • SOASTA’s CloudTest Lite® rapid test creation and real-time analytics now offers support for Cloud Foundry deployment targets.
  • X.commerce, eBay’s open, end-to-end commerce technology platform, is building upon Cloud Foundry.

We are in the midst of the Cloud Foundry Open Tour – a series of developer days across the globe attended so far by thousands of developers.

Upcoming dates include:

We are looking forward for an exciting second year with more code, more community, more partners and more clouds.

-The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in Announcement, CloudFoundry, Media, oss | 8 Comments

Introduction to Cloud Foundry Integration for Eclipse 1.0

Cloud Foundry Integration for Eclipse allows users to deploy applications to Cloud Foundry targets from either Eclipse IDE JEE Indigo or STS (SpringSource Tool Suite) 2.9.0 or higher.

Cloud Foundry Integration for Eclipse 1.0 is the first version of the integration to be open sourced under the Eclipse Public License  (EPL), and cannot be upgraded from earlier versions of Cloud Foundry Integration for Eclipse. Users wishing to install it must first uninstall any prior version of Cloud Foundry Integration for Eclipse.

Detailed steps on how to install the Cloud Foundry Integration for Eclipse can be found at:

http://start.cloudfoundry.com/tools/STS/configuring-STS.html

After installing the Cloud Foundry Integration for Eclipse, a Cloud Foundry target must first be created through the Eclipse New Server wizard, and URL and account information for either the public cloud (i.e., CloudFoundry.com) or your local cloud target needs to be specified. Create an account on CloudFoundry.com to deploy applications by going to:

https://my.cloudfoundry.com/signup

For debugging support, users are encouraged to obtain Micro Cloud Foundry from:

https://my.cloudfoundry.com/micro

Once a Cloud Foundry target is created, it appears in the Eclipse Servers view, and users can deploy applications simply by dragging and dropping them from the Project Explorer into the Cloud Foundry target.

During the drag and drop deployment, a wizard allows a user to set application details  like  memory limit,  mapped application URL, and optionally, also bind Cloud Foundry services  like MySQL and vFabric Postgres databases, or RabbitMQ messaging to the application. In addition, users can select whether to automatically start the application after deployment, or even debug it if deploying it to Micro Cloud Foundry that supports debugging.

After deployment, users can continue to edit application deployment details in the Applications tab of the Cloud Foundry server editor, which can be opened by double-clicking a Cloud Foundry target in the Servers view.

Additional services can be created and bound to the application. Services available in the Cloud Foundry target are listed under the Services pane, and can be dragged and dropped onto the Application Services pane to bind them to a specific application deployed in that target. Furthermore, applications can be stopped, and updated and restarted through editor controls. Update and Restart allows users to incrementally publish local changes in an application without having to manually stop or redeploy the application.

Java debugging can be enabled via the editor for Micro Cloud Foundry, which provides support for debugging. Users can restart applications in either debug or run mode, as well as connect applications already running in debug mode to the Eclipse debugger, if the application wasn’t already connected to the debugger.

Cloud Foundry Integration for Eclipse is fully integrated into Eclipse debugging functionality, and applications deployed to Micro Cloud Foundry with debug support can be debugged the same way as if they were debugged locally. Users can set break points, step through code, and suspend applications through the Eclipse Debug perspective.

Users can also view deployed Cloud Foundry resources through a Remote Systems View, including configuration and log files.

We welcome any questions or comments at:

http://support.cloudfoundry.com/

For developers, Cloud Foundry Integration for Eclipse is available at github:

https://github.com/SpringSource/eclipse-integration-cloudfoundry

In addition, we encourage users to raise any issues or suggest enhancements at:

https://issuetracker.springsource.com/browse/STS

Issues can be raised under the “Cloud Foundry” component in the STS project.

-The Cloud Foundry Team

Don’t have a Cloud Foundry account yet?  Sign up for free today

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Email
Posted in CloudFoundry, oss | Leave a comment