Tuesday, June 27, 2006

Ruby.NET Compiler Passes test.rb

Queensland University of Technology's Ruby.NET project has achieved a major milestone: their Ruby to .NET compiler is able to run and pass all the test.rb samples in the C Ruby distribution. They've got plenty more work to do to be "Ruby compatible" in any sense of the words, but they're making very good progress.

I'm going to stay involved with this project to help in any way I can, be it discussions on implementation challenges or helping to debug and write tests. The .NET CLR is an impressive piece of technology, and I'd certainly like to see Ruby gain traction in the .NET world as well.

At any rate, kudos to the QUT folks for their hard work. I'm also glad to see they have a very liberal license and all source available online. Once I confirm I won't be tainted in any way I'll be reviewing their code and compiler...I'll report back on what I find.

It's amazing what financial backing from a major software company can do for an open-source project :)

Thursday, June 15, 2006

Mongrel in JRuby?

I'm going to try to post more frequent, less-verbose entries to break up the time between longer articles. This is the first.

For those of you unfamiliar with it, Mongrel is a (mostly) Ruby HTTP 1.1 server, designed to escape the perils of cgi/fcgi/scgi when running web frameworks like Rails or Camping. From what I hear it's very fast and very promising. Think of it as a Ruby equivalent to Java's servlet/web containers like Jetty and Tomcat.

Deploying Rails apps under JRuby currently has only two reasonable outlets:

- You can wrap all the Rails-dispatching logic into a servlet, deploying as you would a web application.
- You can (mostly) run the "server" script, which starts up Rails in WEBrick, Ruby's builtin lightweight server framework.

The first option would obviously provide the best integration with existing Java code and infrastructure. The second is good for development-time testing.

However, with JRuby rapidly becoming production-usable, there will be many folks who want a third option: deploying Rails--just Rails--in a production environment without a meaty servlet engine. For Ruby, that's where Mongrel comes in.

Mongrel is by the developer's own admission "mostly" Ruby code. The one big area where it is not Ruby is in its HTTP parser library (there's also a native ternary search tree, but that's no big deal to reimplement). Using Mongrel, require 'http11' pulls in a C-based HTTP 1.1 parser and related utilities. Ruby is notoriously slow for parsing work, so this native code is not unreasonable. However, it would be a barrier to running Mongrel within JRuby; we would need our own native implementation of the http11 library.

So, any takers? If I had a nickle for every JRuby sub-project I want to work on I'd have a fistful of nickles. This one will probably be pretty far back in the queue.

Known possibilities for lightweight HTTP 1.1 support (really all that's needed for Mongrel is an HTTP1.1 library, but that can probably be used alone):

- Jetty
- Simple

For those of you that say "Why not just wire Rails into [Tomcat|Jetty|Simple] and be done with it" I have this answer: Rubyists are not particularly fond of Java libraries. My aim of late is working toward supporting both Ruby/Java folks who will happily marry the two and pure Ruby folks that simply want another runtime to use. Mongrel is bound to become a very popular choice for web serving Ruby applications, and we would be remiss if we did not attempt to support it.

Wednesday, June 14, 2006

Unicode in Ruby, Unicode in JRuby?

The great unicode debate has started up again on the ruby-talk mailing list, and for once I'm not actively avoiding it. We have been asked many times by Java folks why JRuby doesn't suport unicode, and there's really been no good answer other than "that's the way Ruby does it".

For the record, Ruby does support utf8, but not multibyte. Internally, it usually assumes strings are byte vectors, though there are libraries and tricks you can usually use to make things work. The array of libraries and tricks, however, is baffling to me.

So here, now, I open up this question to the Java, JRuby, and Ruby communities in general as I did on the ruby-talk and rails-core mailing lists:

Every time these unicode discussions come up my head spins like a top. You should see it.

We JRubyists have headaches from the unicode question too. Since JRuby is currently 1.8-compatible, we do not have what most call *native* unicode support. This is primarily because we do not wish to create an incompatible version of Ruby or build in support for unicode now that would conflict with Ruby 2.0 in the future. It is, however, embarrassing to say that although we run on top of Java, which has arguably pretty good unicode support, we don't support unicode. Perhaps you can see our conundrum.

I am no unicode expert. I know that Java uses UTF16 strings internally, converted to/from the current platform's encoding of choice by default. It also supports converting those UTF16 strings into just about every encoding out there, just by telling it to do so. Java supports the Unicode specification version 3.0. So Unicode is not a problem for Java.

We would love to be able to support unicode in JRuby, but there's always that nagging question of what it should look like and what would mesh well with the Ruby community at large. With the underlying platform already rich with unicode support, it would not take much effort to modify JRuby. So then there's a simple question:

What form would you, the Ruby [or JRuby or Java] users, want unicode to take? Is there a specific library that you feel encompasses a reasonable implementation of unicode support, e.g. icu4r? Should the support be transparent, e.g. no longer treat or assume strings are byte vectors? JRuby, because we use Java's String, is already using UTF16 strings exclusively...however there's no way to get at them through core Ruby APIs. What would be the most comfortable way to support unicode now, considering where Ruby may go in the future?


So there it is, blogosphere. Unicode support is all but certain for JRuby; its usefulness as a JVM language depends on it. What should that support look like?

Saturday, June 10, 2006

Bringing RubyGems to JRuby OR The Zen of Slow-running Code

JRuby now supports RubyGems, and gems install correctly from local and remote. That's a huge achievement, especially considering the extra work that was required around YAML to get to this point. However, I'll start off with the caveats this time.

JRuby is very slow to install gems. You'll see what I mean in a moment, but it's so slow that something's obviously broken. That's perhaps the good news. Even on a high-end box, it's so intolerably slow that there's got to be a key fault keeping the speed down. We believe there are a couple reasons for it.

headius@opteron:~/rubygems-0.8.11$ time jruby gem install rails --include-dependencies
Attempting local installation of 'rails'
Local gem file not found: rails*.gem
Attempting remote installation of 'rails'
Updating Gem source index for: http://gems.rubyforge.org
Successfully installed rails-1.1.2
Successfully installed rake-0.7.1
Successfully installed activesupport-1.3.1
Successfully installed activerecord-1.14.2
Successfully installed actionpack-1.12.1
Successfully installed actionmailer-1.2.1
Successfully installed actionwebservice-1.1.2
Installing RDoc documentation for rake-0.7.1...
Installing RDoc documentation for activesupport-1.3.1...
Installing RDoc documentation for activerecord-1.14.2...
Installing RDoc documentation for actionpack-1.12.1...
Installing RDoc documentation for actionmailer-1.2.1...
Installing RDoc documentation for actionwebservice-1.1.2...

real 63m16.575s
user 55m5.939s
sys 0m25.547s


Ruby in Ruby

I'll tackle the simpler reason first: we still have a number of libraries implemented in Ruby code.

At various times, the following libraries have all been implemented in Ruby code within JRuby: zlib, yaml, stringio, strscan, socket...and others irrelevant to this discussion. This provided us a much faster way to implement those libraries, but owing to the sluggishness of JRuby's interpreter, this also meant these libraries were slower than we would like. This is actually no different from C Ruby; many of these intensive libraries are implemented in C code in Ruby, with no Ruby code to be seen.

Some, such as zlib, yaml, and stringio are on their way to becoming 100% Java implementations, but they're not all the way there yet. This is generally because Ruby code is so much simpler and shorter than Java code; completing the conversion to Java is painful in many ways.

Ola's work on the zlib and yaml libraries have been a tremendous help. He provided the first ruby implementation of zlib, and has provided incremental improvements to it, generally by sliding it closer and closer to 100% java. Ola also ported a fast YAML parser from Python, first to Ruby and now increasingly to JRuby, resulting in his RbYAML and JvYAML projects. Our old, original Ruby 1.6 yaml.rb parser was extremely slow. The new parsers have made YAML parsing speed many orders of magnitude faster. Tom and Ola have both worked to improve stringio. stringio provides an IO-like interface into a string, much like Java's StringBuffer/StringBuilder classes. In Ruby, understandably, this is implemented entirely in C. Our version, while slowly becoming 100% Java, is still quite a bit slower than it ought to be.

The continued porting of these hot-spot libraries from Ruby to Java will have perhaps the largest effect on gem install performance. However, there's another cause for alarm.

Fun with Threads

Threading in Ruby has a somewhat different feel from threading on most other languages and platforms. Ruby's threads are so easy to use and so lightweight that calling them "threads" is a bit misleading. They can be stopped, killed, and terminated in a variety of ways from outside themselves. They are trivial to launch: Thread.new { do something }. C Ruby also implements them as green threads, so no matter how many threads you spawn in Ruby, you're looking at a single processor thread to execute them. That means considerably less overhead, but practically no multi-core or multi-threading scalability at all. In short, Ruby's threads allow you to use and manipulate them in ways no other platform or language's threads allow while simultaneously giving you only a subset of typical threading benefits. For sake of brevity, I will refer to them as rthreads for the rest of this article.

The increased flexibility of rthreads mean that kicking off an asynchronous job is trivial. You can spin off many more threads than could be expected from native threading, using them for all manner of tasks where a parallel or asynchronous job is useful. The rthread is perhaps more friendly to users of the language than native threads: most of the typical benefits of threading are there without many of the gotchas. Because of this, I have always expected that Ruby code would use rthreading in ways that would horrify those of us with pure native threading. Therefore, I decided during my early redesign that supporting green threading--and even better, m:n threading--should be a priority. Our research into why gems are slow seems to have confirmed this is the right path.

RubyGems makes heavy use of the net/http package in Ruby. It provides a reasonably simple interface to connect, download, and manipulate http requests and responses. However, it shows its age in a few ways; other implementations of client-side http are around, and there are occasional calls to replace net/http as the standard.

net/http makes heavy use of net/protocol, a protocol-agnostic library for managing sockets and socket IO. It has various utilities for buffered IO and the like. It also makes use of Ruby's "timeout" library.

The timeout library allows you to specify that a given block of code should only execute for a given time. As you might guess, this requires the use of threading. However, you might be surprised how it works:


from lib/ruby/1.8/timeout.rb
  def timeout(sec, exception=Error)
return yield if sec == nil or sec.zero?
raise ThreadError, "timeout within critical session" if Thread.critical
begin
x = Thread.current
y = Thread.start {
sleep sec
x.raise exception, "execution expired" if x.alive?
}
yield sec
# return true
ensure
y.kill if y and y.alive?
end
end


It's fairly straightforward code. You provide a block and an optional timeout period. If you specify no timeout, just execute the block. If we're in a critical section (which prevents more than one thread from running), throw an error. Otherwise, start up a thread that sleeps for the timeout duration and execute the block. If the timeout thread wakes up before the block is complete, interrupt the working thread. Otherwise, kill the timeout thread and return.

With rthreads, this is a fairly trivial operation. It gives Ruby's thread scheduler one extra task...starting up a lightweight thread and immediately putting it to sleep. Now it can be argued that this is a waste of resources, creating a thread every time you want to timeout a task. I would agree, since a single thread-local "timeout worker" would suffice, and would not require launching many threads. However, this sort of pattern is not unexpected with such a simple and consumable threading API. Unfortunately, it's a larger problem under JRuby.

JRuby is still 1:1 rthread:native thread, which means the timeout code above launches a native thread for every timeout call. Obviously this is less than ideal. It becomes even less ideal when you examine more closely how timeout is used in net/protocol:

from lib/ruby/1.8/net/protocol
    def read(len, dest = '', ignore_eof = false)
LOG "reading #{len} bytes..."
read_bytes = 0
begin
while read_bytes + @rbuf.size < len
dest << (s = rbuf_consume(@rbuf.size))
read_bytes += s.size
rbuf_fill
end
dest << (s = rbuf_consume(len - read_bytes))
read_bytes += s.size
rescue EOFError
raise unless ignore_eof
end
LOG "read #{read_bytes} bytes"
dest
end
...
def rbuf_fill
timeout(@read_timeout) {
@rbuf << @io.sysread(1024)
}
end


For those of you not as familiar with Ruby code, let me translate. The read operation performs a buffer IO read, reading bytes into a buffer until the requested quantity can be returned. To do this, it calls rbuf_fill repeatedly to fill the buffer. rbuf_fill, in order to enforce a protocol timeout, uses the timeout method for each read of 1024 bytes from the stream.

Here's where my defense of Ruby ends. Let's dissect this a bit.

First off, 1024 is nowhere near large enough. If I want to do a buffered read of a larger file (like oh, say, a gem) I will end up reading it in 1024-byte chunks. For a large file, that's hundreds or potentially thousands of read calls. What exactly is the purpose of buffering at this point?

Second, because of the timeout, I am now spawning a thread--however green--for every 1024 bytes coming out off the stream. Because of the inefficiency of net/protocol and timeout, we have a substantial waste of time and resources.

Now translate that to JRuby. Much of JRuby is still implemented in Ruby, which means that some calls which are native in Ruby are much slower in JRuby today. Socket IO is in that category, so doing a read every 1024 bytes greatly increases the overhead of installing a gem. Perhaps worse, JRuby implements rthreads with native threads, resulting in a native thread spinning up for every 1024 bytes read. For a 500k file, that means we're reading 500 times and launching 500 timeout threads in the process. Not exactly efficient.

We will likely try to submit a better timeout implementation, or a protocol implementation that reads in larger chunks (say 8k or 16k), but we have learned a valuable lesson here: rthreads allow for and sometimes make far easier threading scenarios we never would have attempted with native threads. For that reason, and because we'll certainly see this in other libraries and applications, we will continue down the m:n path.

Coolness Still Abounds

As always, despite these obstacles and landmines, we have arrived at a huge milestone in JRuby's development. RubyGems and Ruby go hand-in-hand like Java and jarfiles. The ability to install gems is perhaps the first step toward a really usable general-purpose Ruby implementation. Look for a release of JRuby--with a full complement of Ruby libraries and RubyGems preinstalled--sometime in the next week or two.

Friday, June 09, 2006

Preparing for 0.9.0

Yes, I had intended to post at least once a week. Things have been moving along pretty fast with JRuby since JavaOne. Here's a quick update...I'll post a more detailed one soon.

  • RubyGems now installs perfectly, and works correctly. This is due in large part to Ola Bini's work on RbYAML and JvYAML, Ruby and Java YAML parsers which we are integrating into JRuby.
  • Gems install correctly from local files or from the network. They're a little slow, due to some bottlenecks we're ironing out, but they work. Ola's post shows it in action.
  • The "rails" script for generating a base application works. This is the first step in Rails development, and it ended up just kinda working without any additional effort.
  • Tom and I have been working on performance, putting in 5-10% speedup fixes here and there. There's a lot more to do, but we're making great progress.
  • We have gotten approval from matz to include the full complement of Ruby's .rb libraries in the next release of JRuby. This means all you will need for a working JRuby install is the release archive. We will also likely pre-install rubygems, so we're on par with a typical Ruby install in that regard.
  • Due to networking and IO fixes from Evan Buswell (especially his work to make 'select' function) we are very close to running Webrick in JRuby. Along with this would come the "server" script in Rails, which allows you a simple development deployment for Rails development and testing.
  • We will be making the ActiveRecord JDBC connector available to the public concurrent with this release. It is unknown yet whether it will be a gem, a Rails plugin, or whether we can get the Rails guys to include it in the main release.
  • A number of people are interested in beginning work to make Rake work well in JRuby for doing Java builds. I am one of those people, and time permitting I will start trying to make this happen.
  • I am also interested in implementing the win32ole library in JRuby. There are various plugins for Java that allow calling OLE components, and it should not be difficult to wrap one of those libraries. This would allow things like WATIR to work seamlessly in JRuby.

And here's a little funny that Tom just pointed out: Ed Burnette's JRuby Photo

Tom is on the left, looking into the future, and I'm on the right, staring down the camera.

Wednesday, May 24, 2006

JavaOne Wrap-up

It was a great JavaOne for JRuby! Now that Tom and I are back home and I've recuperated from a long and busy week, here's an update on the great JRuby JavaOne Adventure.

The Press Conference

Tim Bray continues to support and promote the JRuby project, along with other alternative JVM languages. He set up a press conference on Tuesday the 16th for us along with Sam Heisz from Caucho (presenting Quercus, Caucho's GPLed PHP implementation for the JVM) and Roberto Chinnici from Sun (presenting Phobos, a scripting-language-based web framework for JSR223-compatible languages). Sam presented first, then us, then Roberto.

My rough count puts the number of journalists and interested parties at 15-20 (some came in late or left early).

We were given ten minutes to make our case for JRuby. Tom kicked it off with a quick overview of what Ruby and JRuby are, and I made a quick statement about Ruby's potential on the JVM. Then I demoed building a tiny Swing app through IRB in under two minutes before handing it back to Tom for his JRuby on Rails demo.

I think both demos were well-received. With the press Ruby and Rails have been getting, JRuby tends to sell itself.

The inevitable questions about performance and business cases were mostly deflected by Tim, and for that I thank him. Comparing performance is somewhat pointless at this point in JRuby's development, since we've only recently begun to explore optimizations. The business case for JRuby is also simply the business case for Ruby; if the language suits your problem, JRuby is a good option.

There were also questions asking us to compare JRuby to the other languages and implementations out there. These we mostly punted on, avoiding a fight. Folks seem to really want the alternative languages implementors to fight, and this became a recurring theme during the week.

At the end of the press conference, a number of Sun folks talked to us about building a community around JRuby, and possibly having a presence on java.net. We're very enthusiastic about growing the JRuby community and will weigh the various options for some minimal java.net presence.

Presentation for InfoQ.com

InfoQ.com is a new online tech magazine currently launching. We were invited by Floyd Marinescu and Obie Fernandez to participate in the launch by presenting our JRuby talk, sans live demos and JavaOne branding, to be videotaped and published on the InfoQ site. This talk we gave on Wednesday the 17th at noon.

Floyd is one of the original founders of TheServerSide, and we were happy to help him kick off this new venture--especially given its broad acceptance of alternative development and web technologies like Ruby and Rails.

The presentation took place in the upstairs theater of the Thirsty Bear, a typical conference-goer's hangout near the Moscone convention center. The room was set up with rows of chairs, a projector, a podium, and a video camera. Upon starting, we had only a few attendees, but several more trickled in during our presentation. According to the InfoQ guys, we had the best turnout of any talks so far that morning.

A number of good questions came up, which Tom and I answered on camera. It was a great dry-run for our "real" JavaOne presentation later that day.

Look for the final presentation to be posted on the InfoQ site within the next week.

The Main Event

Some time before the InfoQ presentation I stopped practicing. I'm not one for scripted presentations; I do better with a general presentation outline and a couple practice rehearsals. I approached my RubyConf presentation this way and it worked out well, so I followed the same pattern for JavaOne.

In total, I think I rehearsed my part of the presentation only 4 times. I ran through the IRB demo many times, however, to make sure I had the sequence of commands memorized.

All that said, I spent the early afternoon relaxing. I hung out in the pavilion for a while, relaxed in the gaming area, and then attended the Groovy talk around 2:45. The basics of the Groovy presentation seemed much like in past years. The slides were mostly the same, and the content seemed to vary only slightly. There was an extensive demo using ActiveX to control an Excel document; I was not quite sure whether this was intended to be a Groovy demo or an ActiveX demo, since the same operations could be done by Java or any other scripting languages just as easily. At any rate, it was a good prep for our presentation which came immediately after.

I was obviously there early, and Tom showed up well ahead of time as well. We got mic'ed up, talked a bit on how ready we were, and then relaxed while folks streamed into the auditorium. I estimate it was perhaps 70% full, for around 700 people, but we'll get an official count sometime soon.

We decided on the following order for the presentation:

Introductions and opening words: Me
Agenda, intro to JRuby and Ruby: Tom
IRB demo: Me
Rails demo: Tom
JRuby in the Wild, JRuby's Future, and Conclusion: Me
Q/A: Tom and Me

Up until Wednesday morning, I had no plans for the introduction. I knew I wanted to ask a few introductory questions, and eventually settled on the following two:

- How many of you have heard of Ruby or Ruby on Rails? (Perhaps 75-80% of the attendees raised their hands
- How many of you heard of them for the first time in the past year? (Almost all the same hands)

"That's momentum. That's the momentum behind Ruby and Rails right now".

I proceeded to hold up the current Dr Dobbs Journal, with a cover story "Ruby on Rails: Java's Successor?". Most of the audience chuckled at the title, and I agreed that perhaps it wasn't the right question. I mentioned that the article described Rails as a potential tipping point in web development patterns and called out the fact that several new frameworks had sprung up in the Java world aping Rail's design. Then I handed off to Tom.

Tom gave a very quick and clean introduction to Ruby, JRuby, and features of both. I've read on several blog postings about the presentation that this intro was welcomed by attendees; though many had heard about Ruby, most had no experience with the code. The JRuby features also called out Java integration scenarios, which are the obvious reason why you'd want to run JRuby in the first place. Tom did a great job on these slides, which you can imagine were not terribly exciting for us to present. Then it was my turn.

The IRB demo was our first really cool thing to show off. I started off demonstrating some of the basic of Ruby and IRB, entering basic statements, defining a method, defining a class. Then I went straightaway into the fun stuff: building that little Swing app. Tom commented after the press conference and again after this presentation how impressive he thought it was, and there were certainly murmurs, gasps, and nods from the attendees. It really provided a good feel for how easy it is to call Java code from Ruby.

Tom came next, providing the "big surprise" for JavaOne attendees: a fully working Rails app, running under JRuby and using JDBC for database access. The wow factor was not as apparent here, since it just looked like a web application; however, several folks in the audience with more than a basic knowledge of Rails were notably impressed. Through follow-up questions and later blog posts, the gravity of this milestone has begun to be felt.

I gave a quick overview of RDT, RadRails, JEdit, and DataVision, four apps that make use of JRuby internals. Then I ran through the various plans and future milestones for JRuby, adjusting them based on recent developments (since our original slides were submitted in March, and mountains have moved since then).

We finished with about fifteen minutes to go, which I think was refreshing for most of the attendees. We covered everything we wanted to cover, and we knew people were having difficulty moving from session to session. We also wanted plenty of time for Q/A.

Questions ranged from performance to rails to "can I run normal Ruby code" to "can I use Java objects in Ruby scripts". We patiently answered all questions as well as possible; there was a lot of interest in using JRuby for its Java integration abilities.

Both Tom and I thought the presentation went extremely well. We were very happy with the turnout and we're excited to take the next steps with JRuby.

Sunday, May 14, 2006

JRuby Meet-up, San Francisco, May 19 4:00PM

UPDATE: The correct date is May 19th

After a crazy week at JavaOne, Tom and I will be settling in at the Chieftain in San Francisco to unwind. We'd love to have any JRuby enthusiasts stop by and chat a bit. Tom's blog has all the details. RSVP if you like, so we we'll know to look for you, but show up regardless!

Friday, May 12, 2006

And They Said JRuby was Dead...

Things are looking very good for JavaOne.

The past several months have been a period of furious development on the JRuby project, with milestone after milestone flying by. Four months ago we couldn't run most basic Ruby apps and were still wrestling with basic 1.8 compatibility issues. Since that time we've gotten IRB working, Rake running, RubyGems almost working, and then managed to process a simple Rails request. All the while, our existing libraries have grown in stability and completeness, and we've attracted many new contributors to the project. This stone is gathering no moss.

JavaOne is a going to be a big event for us, but we wanted something more. What would the week before a major conference be without some buzz-worthy announcements to make?

Hold on to your hats.

Where We've Been

JRuby has been around for around five years. It was originally based on Ruby 1.6 C code, and was pretty much a direct port from C to Java. Over those years, up until Fall of 2005, the focus was mainly on basic compability issues, updating libraries and language semantics to 1.8 levels, and generally just making things work well enough for use. All told, it was a pretty good port, but there was a long way to go. There were a few Java apps that used it for scripting, but the tide was turning away from JRuby with the release of ever-more-complex Ruby applications that were increasingly difficult to run on a partial implementation.

Starting this past Fall, and really gaining steam since the start of 2006, our focus shifted from simple 1.8 compatibilities and interpreter tweaks to much more ambitious goals. We began to tackle the killer apps for Ruby one by one, fixing what broke and getting a much more intimate knowledge of both Ruby and JRuby internals than we had before. First came early runs of Rake. They worked, but required changes to the way external scripts launched. Then something a bit more lofty: I disappeared into my office for a week to get IRB working...and work it eventually did. Then we realized that RubyGems would be a great target; while it's not yet working 100%, it's now really close.

Then came Rails.

The Big Ticket

There is little doubt that Rails is the app that's selling Ruby today. Ruby has become, in many circles, synonymous with Ruby on Rails. While there's a discussion to be had about whether a single killer app should hold so much sway, it's impossible to argue that Ruby would be where it is today without Rails dragging it into the spotlight. Rails has, more than any other app, brought Ruby to the world.

We just had to get a bite of that apple.

Getting Rails to run in JRuby is a very challenging task. For those of you that know what Rails does, imagine the code that's required to do that. Think of all the magic necessary to get things so slick and transparent. Look at the size of the Rails codebase which, while far smaller than a beastly Java library, is positively enormous compared to the typical Ruby app. If you've ever seen the code, you know what kinds of tricks and traps there are in the Rails code, and how many dark alleys you might venture down when debugging a problem deep within its guts.

Now imagine running it on an interpreter that breaks in weird and indeterminate ways.

We have fixed hundreds of issues on the road to getting Rails working. Every step of the way, we have had to pore through the Rails code, digging for that one irreducible test case that demonstrates a bug, sometimes sifting through tens of files, thousands of lines of code. It has been an extreme challenge. However...

What Would You Do With JRuby on Rails?

Today, we can announce that a simple end-to-end Rails application has successfully run under JRuby.

As reported on Tom's blog, a little CRUDified cookbook application can now deliver a form and process submissions correctly. Using an ActiveRecord-to-JDBC adapter (yes, you read that right) donated by Nick Sieger, the app is able to generate a form, display a table of results, and process creates and deletes. All this magic, all working on JRuby. We're ecstatic.

Can It Truly Be?

See for yourself. It's even wrapped in a little servlet that invokes Rails FastCGI-style, keeping it loaded in memory for additional requests. It's the culmination of all our experiments, bug fixes, and hard work over the past several months. And it sure feels good.



Onward and Upward

Of course this demo is slightly canned. We coded to the test, and the average Rails app still isn't going to work out of the box. There's plenty of little things missing, like reliable session management, more ActiveRecord magic, and various rendering flaws, to list a few we know about. But as a technology preview, running Rails essentially unmodified--even on a simple end-to-end app--is our biggest milestone yet.

With the recent successes, we plan to target the end of summer for full, general-purpose Rails support. With more contributors and more time to work, that timetable could move up, but there's also the compiler work that has begun in earnest. It's going to be a great summer for coding, and a great year for dynamic(-typed) lanaguages on the JVM.

Oh, and one last note for the perennial skeptics and naysayers out there: Rails on the JVM is coming sooner than you think.

A Few Other Updates

Here's another couple items to hold you off until the next round of milestones:

IRB glitches resolved
A remaining IRB bug that caused declared classes to be scoped under Kernel (as in class A would be scoped as Kernel::A) has been resolved. I had to get this fixed to demo IRB at JavaOne

RubyGems works, sorta
Tom discovered that if a known good RubyGems install (from a C Ruby installation, for example) was copied into JRuby's dirs, gems would require and load correctly. So although our RubyGems and gem install code isn't quite there yet, actually using gems seems to be working. Huzzah!

Improved codegen DSL
John Lam, of the RubyCLR project, pointed me to a nice little eval trick that has helped simplify my code-generation DSL a bit. By eliminating most of the block params, it's a bit less verbose and certainly prettier:

class_bytes = ClassBuilder.def_class :public, "FooClass" do
def_constructor :public do
call_super
return_void
end

def_method :public, :string, "myMethod", [:void], [:exception] do
call_this GenUtils.array_cls(:string), "getStringArr"
call_this :string, "getMessage"
return_top :ref
end

def_method :private, :string, "getMessage", [:void] do
construct_obj :stringbuffer, [:string] do
constant "Now I will say: "
end

call_method :stringbuffer, "append", :string, :stringbuffer do
constant "Hello CodeGen!"
end
call_method :string, "toString", :void, :stringbuffer
return_top :ref
end

def_method :public, GenUtils.array_cls(:string), "getStringArr" do
construct_array :string, 5 do |i|
constant "string \##{i}"
end

array_set 2, :string do
constant "replacement at index 2"
end

return_top :ref
end
end
I'll be going full-speed-ahead on compilation after JavaOne, you can count on that.

YAML parser improved?
One of our favorite contributors, Ola Bini, now has a working version of a YAML 1.1-compliant parser which is able to load fairly large files. There's still some work to do, but if all goes well we may be able to migrate to it in the near term.

Dynamic languages press conference
The JRuby team (Tom and I) will be part of a JavaOne Day-1 press conference on the future of dynamic languages on the JVM. Along with the Quercus guys from Caucho (PHP for the JVM) and Roberto Chinnici from Sun (doing cool stuff with JSR223), we'll have our own ten minutes to show the press how cool JRuby really is. It oughta be a fun time, and should help get JRuby a bit wider exposure.

This is just too much fun.

Scripting and services top Sun software chief's list

Scripting and services top Sun software chief's list:

"Support for scripting languages in Java, squeezing revenue from a set of long-promised - but strangely MIA - services, and more open source initiatives are among top priorities for Sun Microsystems' newly appointed software chief.…"

Seems like a good time to be working on an open-source "scripting" language implementation, no?

Tuesday, May 09, 2006

A DSL for Bytecode Generation

Having discovered the power and magic of bytecode generation, it occurred to me that none of the existing libraries have the subtle elegance that most code generation tasks really deserve. I believe there's a simple reason for this: they're written in Java. Some of them really try to make things easier, and perhaps come close to succeeding, but they're all still cumbersome, clunky, and very, very verbose.

I have been writing JRuby's compiler in pure ruby by calling out to a Java-based bytecode generation library. My initial attempts were fairly straightforward calls: push this, call that, pop the other. Very linear, very boring, very verbose, and not a great deal simpler than the equivalent Java code. It seemed such a shame to waste an expressive language like Ruby on such a menial task, I've decided to build a domain-specific language for Java bytecode generation.

A short sample of what works today (basically the operations I needed for my test compiler):

class_bytes = ClassBuilder.def_class :public, "FooClass" do |c|
c.def_constructor :public do |con|
con.call_super
con.return_void
end

c.def_method :public, :string, "myMethod", [:void], [:exception] do |m|
m.call_this GenUtils.array_cls(:string), "getStringArr"
m.call_this :string, "getMessage"
m.return_top :ref
end

c.def_method :private, :string, "getMessage", [:void] do |m|
m.construct_obj :stringbuffer, [:string] do |p|
p.constant "Now I will say: "
end

m.call_method :stringbuffer, "append", :string, :stringbuffer do |p|
p.constant "Hello CodeGen!"
end
m.call_method :string, "toString", :void, :stringbuffer
m.return_top :ref
end

c.def_method :public, GenUtils.array_cls(:string), "getStringArr" do |m|
m.construct_array :string, 5 do |p,i|
p.constant "string \##{i}"
end

m.array_set 2, :string do |p|
p.constant "replacement at index 2"
end

m.return_top :ref
end
end


This approach has a number of advantages over others:

  • The structure of the generator is very similar to that of the generated code
  • Method parameters and array initializers (or the code to make them available) are logically associated with the eventual call or array they'll apply to
  • The builders maintain some internal state, and will be able to count stack depth, validate typing, automatically attempt casts, and automatically return the correct types
  • It's far easier to read
  • It's far more fun
Some notes on the code above:
  • The param-building blocks (with |p| params) are in all cases optional. If omitted, method calls will assume you have prepared all params, array creation will create an empty array, and array sets will assume the value is already present on the stack.
  • The core bytecode operations (dup, etc) are still present and callable on the MethodBuilder m. This allows you to fall back to linear-style when necessary.
  • Various classes (perhaps eventually all classes) from java.lang are aliased as symbols like :string and :object. At the ClassBuilder level, it is also possible to "import" classes, as in c.import "javax.swing.JFrame", :jframe and use the aliased symbol throughout this generation (much like import in a .java file)
  • I'm looking for a better way to handle arrays. GenUtils is only used internally except for array types, and I'd like to hide it completely.

I'm tossing this working snippit out to the world for comments and critique...and perhaps as a little teaser of things to come. I'm planning to add a few more operations and port the early v1 compiler over to this soon...then both will develop together. I see this DSL/library as having huge potential for other projects that want a simple, elegant way to do bytecode generation.

Thoughts? Comments?

My JavaOne Calendar

I've entered all the sessions I'm planning to attend into Google Calendar, available at the following URLS:

- RSS
- ICal
- You can search for "Headius at JavaOne" in GCal too.

These are negotiable if there's folks out there that want to grab a lunch, dinner, or 30 minutes and a cup of coffee. Do let me know: email

I'm arriving late Monday and leaving late Saturday...the rest is on the calendar.

Sunday, April 30, 2006

More v1 Compilation Experiments

Since it's turned out to be so easy to generate bytecodes based off the Ruby AST, I tackled another trouble spot for us: literal array creation.

The current interpreter, in order to follow a generic, iterative model, has a large overhead for instantiating literal arrays. For example, to create the following array:

['this', 'is', 'an', 'array', 'of', 'strings']

There are at least seven AST nodes to process: the array node and six nodes for the elements (technically, there's more that one node for each element, but we'll call it one for simplicity). The recursive way to process these nodes would be to visit the array node, and then recurse to process each of the elements. However, we're trying to escape recursion, so a different model was necessary.

The current interpreter avoids recursion by maintaining its location in the AST on a stack. As nodes are encountered, they are pushed onto that stack, and their instructions--rather than recursing--expand the subnodes by also pushing them onto the stack. Once the expansion reaches a termination point (such as a literal value or the last element in a block), the expanded nodes are processed one at a time.

The instructions associated with each node perform whatever JRuby operations are required to process that node. They instantiate classes, define methods, assign variables. For this reason, they actually are of the type Instruction internally, and this is where we can plug in the compiler.

Compiler Design Version One: Microcompilation

Because the interpreter simply traverses the AST, retrieving and caching instructions as each node is encountered, we can short-circuit this process by pre-populating the appropriate instruction for a parent node with a compiled instruction based on its children. When the interpreter reached that node and sees an instruction has been prefetched, it executes that rather than continuing to traverse. As a result, we can selectively compile branches of the AST for targetted speed gains. I call this microcompilation.

The benefit to this approach is that the compiler can be written a piece at a time, tested incrementally as those pieces come together. It also has the huge benefit of allowing compiled code to run within the existing interpreter engine without any modifications to JRuby.

There is, however, a downside to my current approach. Instead of pushing toward a green-threadable and continuation-able iterative model, this simple compiler will still deepen the stack. However, given that no applications we are currently working to support seem to require continuations or threads, I believe this is a good initial approach. It may also prove true that this simpler compiler is fastest (while perhaps not the most Ruby-compliant), and for many embedded Ruby applications it will continue to be useful into the future.

Processing The Array


So back to our six-element array. In order to handle it iteratively, rather than recursing to process each element, a complicated transformation happens. The instructions elements of the array are mixed with instructions for aggregating the results, and another instruction is added at the end to finally build the array. So the sequence of instructions processed, after initially processing the array node, goes something like this:

String Node: 'this'
Aggregate (push down result accumulator)
String Node: 'is'
Aggregate
String Node: 'an'
Aggregate
String Node: 'array'
Aggregate
String Node: 'of'
Aggregate
String Node: 'strings'
Build Array (deaggregates all results and constructs a ruby array)

For more complex elements, this approach also works; if one element requires a method call or a variable lookup, that branch of the AST is processed inline, with the end result placed on the top of the accumulator stack. Processing then continues with the next element.

The added overhead of this approach is not without reason. Yes, it would have been possible to modify the interpreter engine to understand arrays and handle them specially, but my goal originally was to create a generic iterative interpreter (and perhaps to prove that all nodes could be processed in this way). However, that design mostly proven out, it is now time to address its deficiencies.

Compiling The Array

Compiling the array turns out to be a simple matter, especially considering that the only element type supported by the compiler right now is a literal string. The compiled code instantiates a new IRubyObject[] of the appropriate size, then visits the compilers for each of the elements. The String node compiler I wrote for the "foo" test is reused here, and as each element is encountered bytecodes are generated to construct ruby String objects and insert them into the array. Finally, an operation is added to construct the ruby array instance, and our work is done.

During this round of work, it has also become apparent that although we make heavy use of JRuby internals from the compiled code, large portions of the interpreter itself can go away: for example, with a handy-dandy operand stack available in bytecode mode, we would no longer need to maintain state on a separate result accumulator. The "v1" compiler is turning out to be a fun and easy affair.

The Numbers

The results of these little microcompilations are perhaps anti-climactic...after all this noise I post a handful of numbers for you to look at. Even if the numbers are great, it's a small payoff for listening to my rambling. Sorry! That's how it is!

The test methods take the same form:

def foo_arr; ['this', 'is', 'an', 'array', 'of', 'strings']; end

The foo_arr method is our compiled version, and bar_arr is the uncompiled version. And so after another 1_000_000.times { foo_arr } and { bar_arr } we have:

foo_arr time: 32.628
bar_arr time: 93.31700000000001

This equates to a roughly 60% speedup from what is, again, a fairly simple operation even in the current interpreter.

Coming up in future posts: more v1 microcompilation and numbers, v2 and v3 compiler designs, and more...

Friday, April 28, 2006

In The Beginning: Early Returns on JRuby Compilation

I'll put a big fat disclaimer here stating that these results are extremely preliminary, and mean practically nothing. I'm just very tired and very excited that after seven hours of work, I've already made some progress...I sorta, kinda compiled some Ruby code to Java bytecodes. Yes, I've been up all night. Yes, I have to work tomorrow. Yes...I wish I could work on this during the day. C'est la vie!

The Contenders

In order to soften any growing excitement you may be feeling, I must first introduce the scripts in question. The script to be compiled is quite a whopper:

def foo; 'bar'; end

Hey now, everything has to have a beginning. Even the above script is not the whole story; the only code actually being compiled are the four AST nodes that make up the method's body: a Newline (to start the line), a DStr (dynamic string), another DStr, and a Str (the actual string), all nested one inside the other.

Now as anti-climactic as that may sound, this is early proof-of-concept work here...I don't intend to write a compiler for all of Ruby at the same time. This was the smallest non-trivial script I thought I could handle in a first attempt. I do not compile the nodes that define the foo method, nor do I compile any dispatches to the foo method. I just compile the body.

In order to have an uncompiled version, we have another identical method:

def bar; 'baz'; end

The bar method functions exactly as the foo method, but we will not compile this one. It will be the control.

Now since only a portion of the AST nodes are being compiled, it seemed appropriate to measure a method that does nothing, so that the cost of dispatching could be isolated, further narrowing the test. For that, we have baz:

def baz; end

By running the same tests against baz, we can get a better idea how much compilation is helping. There are also other interpreter bits and pieces that will skew the results a bit, but early results are early results; we want to know whether it will be worth the effort.

The Tools

For this round, I chose to use ObjectWeb's ASM bytecode generation library. It seemed best suited to the visitor pattern we use to traverse the AST (since it folows the visitor pattern itself), and it's itty bitty.

Now for the fun part: I wrote the compiler in Ruby using JRuby's Java integration support. Some time ago, Tom added the ability to parse a string and get back a reference to the AST within a Ruby script under JRuby. Since we already have visitor interfaces for the interpreter, and since JRuby does such a bangup job of implementing interfaces, I figured I'd do the whole thing in Ruby. Naturally, if we continue down this route, we would hope to eventually compile the compiler and add "self-hosting" to our list of buzzwords. However, I digress.

The basic model was simple: parse foo, retrieve the body node from the AST, convert the body to bytecodes, and replace the body with the newly-compiled . This allows our interpreter to continue doing its normal interpretation, but execute this one method's body natively. During my interpreter redesign last Fall we hoped to make this legerdemain invisible...and it seems we've succeeded thusfar.

The foo method's body was transformed into a class with one method, execute, implementing the same Instruction interface we use in the interpreter. The difference, of course, is that we would now have one bytecode-based instruction rather than four.

It's also worth pointing out that this model does not turn a Ruby class or a Ruby method into an accessible Java class or method. It turns snippits of Ruby code into tidbits of Java code...and that Java code continues to live as part of the interpreter. This is the most digestable model of compilation for Ruby, and has been followed by most other projects of merit. We may be able to take things further in the future (especially with the potential dynamifying of the JVM), but this level of compilation has massive potential right now.

The Test

Given that the scripts are so simple, the test should be equally simple:

1_000_000.times { foo }

...and equivalent tests for bar and baz. These tests are parsed, processed, and timed in the exact same way (other than the compilation step):

require 'java'
require 'jruby'
include_class "org.jruby.Ruby"

my_ruby = Ruby.default_instance

foocode = JRuby.parse("def foo; 'bar'; end")
#compilation done here
footest = JRuby.parse("1_000_000.times {foo}")

my_ruby.eval(foocode)
t = Time.now
my_ruby.eval(footest)
p Time.now - t


And again, equivalent tests for bar and baz. That's all folks! Have a nice weekend!

...

Ok, ok. You'd like to know what the times are. That's fair. I've led you this far, and you'd like some payoff for reading my technojargon gobbledygook.

Naturally I wouldn't be writing this if the results were poor.

The Results

Now did I mention these are very early, very preliminary numbers? Don't go off half-cocked talking about JRuby's new compiler, ok?

The bare method baz demonstrated that a large amount of time is spent dispatching in JRuby; perhaps an inordinate amount of time. We have plans to correct this, and have a few optimizations being tossed about.

The baz method took 3.8s to invoke one million times on this machine (Opteron 2.6GHz, Gentoo Linux 2.6.15). That may not seem bad, but of course it wasn't doing anything. Also, C Ruby does the same million dispatches in about 3 tenths of a second. An order of magnitude worse, we are.

The bar method, which represents the uncompiled foo, clocked in at 12.5s to complete a million calls. Now you start to see the real cost from traversing all those AST nodes. Adding only four nodes to the mix (and the side effects that result, of course) quadrupled the amount of time. Minus the method invocations, the body took roughly 8.7s, about 70% of the total run.

As you might expect, foo did better than bar. One million invocations of foo, our bar-with-a-compiled-body, took only 6.5s, almost 50% faster than bar. Subtract the method invocation hit and we're looking at around 2.7 seconds, a 60% improvement over bar.

baz: 3.8 seconds
bar: 12.5 seconds, or 8.7 seconds excluding method invocation
foo: 6.5 seconds, or 2.7 seconds excluding method invocation

So there you have it.

If we only get a 60% improvement I would be very pleased. However, given that Newline, DStr, and Str nodes are some of the least interpreter- and processor-intensive nodes in the AST, I'm certain we'll do far better.

Thursday, April 27, 2006

JRuby Compiler Will Happen

Things have really been clicking along on JRuby. Tom has been knocking down Rails unit tests left and right, and more and more stuff is working. I found a nice little performance booster that gives us as much as 30-40% speed increase when starting up. Other folks have been working on updated YAML parsers, ActiveRecord-to-JDBC connectors, and in general helping us test JRuby in more and more scenarios. The future looks pretty good.

However...

I am still far from satisfied with the performance of JRuby. Even with recent cleanup and minor optimizations, a basic CGI-servlet Rails request takes a second or two to process. Much, much longer than it should have to, especially considering we're not hitting a persistent store yet. With JRuby moving ever closer to its goal of C Ruby 1.8 compatibility, why not start looking at those performance issues in more depth?

First Time for Everything

I will admit, I've never written a compiler. Heck, until JRuby, I'd never worked on a language interpreter, much less written one. Of course, a lot has changed in a year, and I'm now one of the two people in the world who know the most about JRuby's internals. It has been quite a lesson in interpreter, language, and VM design...a lesson I've wanted to learn for the better part of my life.

I believe it is time for us to start exploring options for compiling JRuby to intermediate "JRuby bytecode" or to Java bytecode in many cases. Other dyn-typed langages for the JVM continue to hold their compilers up as a reason to choose something other than JRuby. I think JRuby's time has come.

I have been studying Ruby's AST, JRuby's implementation of its interpreter and core libraries, and the C Ruby code, and I am now confident we can do some level of compilation in the short term. The redesign of the core interpreter I committed last Fall has opened the door for more flexible traversal of the AST, including the ability to partially compile some scripts.

And So It Begins...

With Rails, Spring, Swing, IRB, and our other demos for JavaOne basically ready to go (ahead of schedule!), I will be spending the next week or two researching and exploring options for a preliminary Ruby compiler. I believe I can have something by JavaOne; something primitive, sure, but perhaps something that can provide numbers to go on. Stay tuned!

Wednesday, April 19, 2006

JRuby on Rails

After seeing David Heinemeier Hansson ask the "Groovy on Rails" project not to use that moniker (since it isn't Ruby, it isn't Rails, and it has a completely separate codebase), I figured I'd play it safe and ask him directly whether "JRuby on Rails" would be acceptable. We intend to run Rails unmodified, and we're trying to be as "Ruby" as possible, so it seemed to me that since JRuby on Rails is the same under the covers, the extra "J" wasn't that big a deal. David agreed:


As long as Rails remains virtually unaltered and fully functional, I suppose JRuby on Rails isn't too bad. I'm a tad protective of the term Ruby on Rails, though, and I want to make sure that there's no confusion about what it refers to. But I can't immediately see any confusion points here.

So the JRuby on Rails name should stick, and we have cautious approval from the Rails creator himself to use it. Huzzah!

Eclipse UnsatisfiedLinkError: libswt-pi-gtk-3139

I ran into this a bit ago and found no solutions online. I figured it was my duty to provide at least one posting on how I solved it, since there seems to be a lot of frustrated people out there. My eventual solution was to run with 1.5 instead of 1.4.

Upon starting Eclipse 3.1.1 or higher (or other SWT-based apps, it seems) under AMD64-based Linux, many people have reported the following error:

!ENTRY org.eclipse.osgi 2006-04-08 13:53:48.407
!MESSAGE Application error
!STACK 1
java.lang.UnsatisfiedLinkError: /usr/local/src/eclipse/configuration/org.eclipse.osgi/bundles/85/1/.cp/libswt-pi-gtk-3139.so: /usr/local/src/eclipse/configuration/org.eclipse.osgi/bundles/85/1/.cp/libswt-pi-gtk-3139.so: cannot open shared object file: No such file or directory
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1586)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1495)
at java.lang.Runtime.loadLibrary0(Runtime.java:788)

...etc

The .so in question is present, but it seems that when running under Sun's JDK 1.4.2, which does not provide an AMD64 version, this library can't be successfully loaded. I'm not saying this is a Java issue or an Eclipse issue, but I resolved it by running Eclipse under Sun's JDK 1.5 built for AMD64.

Hopefully this helps anyone else out there searching for a solution.

Tuesday, April 18, 2006

A Personal Blog

I've decided to add a personal blog, since many other tech writers do the same (and it seemed like a good idea).

Pop over to Headius@Home.

Thursday, April 13, 2006

The Beginning of JRuby on Rails

It must be something of a debate in the blogosphere as to whether titles should be descriptive, possibly giving away a great secret hidden within an entry's text, or whether titles should only hint at the truth, enticing a curious and diligent reader to venture onward. The former perhaps produces a better tagline for newsfeeds, where a less-descriptive title may not be as attention grabbing. The latter is certainly more suspenseful, allowing a careful author to draw readers toward a mounting climax. I prefer the former, and so this entry's title once again gives away the Big Secret:

Today, Rails handled a simple request under JRuby.

Now perhaps this monumental event deserves uproarious fanfare, and perhaps it does not. I will let you be the judge.

We really WERE close!

For several weeks now, Tom and I have been saying back and forth to each other that we thought Rails was very close to working. Developer optimism, perhaps, but we've poured a lot of effort into fixing the last interpreter issues preventing Rails from running successfully. In the process, we've accomplished many peripheral goals like getting IRB running, improving RubyGems support, reparing untold interpreter and core class bugs, and getting a round education in the internals of Rails. I've personally traced through more Rails code than I ever hoped to, and committed patches upon patches to achieve success. Tom has also been cranking out fixes, and our growing community of contributors have sent some amazing enhancements our way. In short, there's real momentum behind JRuby right now, and we had a feeling Rails was almost there.

The last time I really burned the midnight oil was probably over a week ago. With SourceForge CVS down for an entire weekend, family business to attend to, and a pre-JavaOne presentation at the Minnesota Object Technology Users Group's Java Special Interest Group (whew!), there hasn't been a lot of time for late-night coding jags. That changed today.

With all other distractions behind me (the Java SIG presentation was last night), I set out today to finally accomplish our biggest goal

I resolved that by night's end, Rails on JRuby would handle a request.

Expecting a long night, I put on some music (somafm.com is excellent...listen and donate), grabbed a few snacks and beverages, and dug in.

How did I do it?

Now I know that should probably say how did "we" do it. Tom has obviously put in a substantial amount of time on JRuby, and our contributors deserve their props. My intent here is just to describe the final steps leading up to Rails working, to allow you to better judge our success and to document steps necessary for others to replicate my work.

Step 1: Apply all outstanding patches

Over the past several weeks, a number of core bugs have been resolved. In many cases, we had not yet committed those changes to CVS, preferring to review and clean them up. I committed several such fixes this evening:

- A patch to allow Kernel#system and backquote calls to stay in-process if executing a Ruby script. Previously, this caused a new interpreter to be launched (in a new JVM), which was obviously a bad thing for a Java app to do. This fix is hopefully a temporary modification, pending a better solution in RCR 328.
- A rejiggering of the Main and CommandlineParser classes in JRuby to better allow Multi-VM support in the future. These two classes originally used System.x input and output streams and called System.exit on error. For an interpreter that's intended to run in controlled environments, these obviously had to be fixed. The new versions won't kill off a VM and will only use the streams provided to them.
- A small fix for String#split to allow for splitting on ? characters (kinda important for URLs, no?). I have an improved fix for split to be committed tomorrow.
- A new ENV implementation that takes advantage of Java5's new System.getenv method, and falls back to other hacks on earlier Java versions. Originally, without any way to retrieve env vars, JRuby had an empty ENV hash. This fix was necessary in order to run Rails in my preferred test configuration. (Can you guess why?)
- Process#times was not implemented (because it can't be supported under Java). I added it to return a Tms with all zeros.
- File#flock was not implemented. I added it, using java.nio file locking support.

A few of these fixes came out of my playing with Rails this evening, and I stopped when Rails started working.

Step 2: Set up Rails in the most traditional way

Rails is a very CGI-style web framework. In its simplest form, it is a basic CGI script, and all hacks to improve its performance build around that idea. Given that Rails wanted to be CGI, it made sense to set it up that way...with JRuby executing it.

dispatch.cgi is the main CGI script for Rails. There's also a .fcgi version for FastCGI. Eventually, JRuby will provide a "CGI servlet" of some kind to wrap Rails requests, as well. For now, default.cgi was the order of the day.


#!C:/jrubywork/jruby/bin/jruby.bat

require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)

# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"

ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) ifFile.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch



Yes, running a Java interpreter on each CGI hit is gross. No, I don't expect anyone to run like this in production. It was simply the easiest way to get this working. Now we can go forward.

Step 3: Configure Apache

I'll admit, working in application servers from dawn to dusk I don't have to tweak Apache configs much. This config probably isn't the most spectacular thing in the world, but it does what it needs to. The biggest change from a standard Rails config is the env vars provided for JRuby.


DocumentRoot "C:/rails-1.0.0/public"

<Directory "C:/rails-1.0.0/public">
SetEnv JRUBY_HOME C:\\jrubywork\\jruby
SetEnv JAVA_HOME C:\\j2sdk1.5.0_06
Options Indexes ExecCGI FollowSymLinks
AddHandler cgi-script .cgi
AllowOverride all
Allow from all
</Directory>



Step 4: Turn off what doesn't work

Ok, you knew there had to be a catch. Since there's still a lot of work to be done on Rails, there was at least one area I discovered that wasn't going to work correctly today. To save myself staying up all night, I disabled session support; with it enabled, the script got stuck in a neverending loop somewhere I didn't feel like investigating. For the sake of this test, I added the following line to rails_info_controller.rb:


module Controllers #:nodoc:
class RailsInfoController < ApplicationController
session :disabled => true



We'll circle around to session management and get it working, so don't fret.

Step 5: Finally, test out our very narrow, very basic request

As you've probably gathered, the request I got Rails to handle was a simple info dump. Calling /rails_info/properties on a standard Rails install just dumps some version numbers and path information. It does, however, exercise the full Rails request handling and dispatching mechanism. Having it working is a big deal...it means that Rails is actually able to handle requests and display a result.

(as an aside, during the final stages of debugging I also saw the default error page come up, fully rendered and containing stack traces and error info...so even that's pretty cool).

On my system, /rails_info/properties outputs:

Ruby version1.8.2 (java)
Rails version1.0.0
Active Record version1.13.2
Action Pack version1.11.2
Action Web Service version1.0.0
Action Mailer version1.1.5
Active Support version1.2.5
Application rootC:/rails-1.0.0/public/../config/..
Environmentdevelopment
Database adaptermysql

The (java) up there represents the first time you or anyone else has seen Rails running in a JVM. Mark this day on your calendar.

Where to now?

It is may or may not be safe to say that Rails "runs" on JRuby. There's obviously a number of other subsystems to get working, and without sessions a web app would be pretty dumb. Saying that Rails works, except X and except Y, basically means it doesn't work without a whole bunch of asterisks--but handling an end-to-end request of any kind represents a major milestone.

What would be safe is to say that this represents the birth of Rails on JRuby. This is the first time a request has successfully been handled by Rails in a JVM. The next steps are obviously to get all normal use cases working, get the rest of the Action Pack functioning, and as always, speed JRuby up to be a viable deployment option.

To all those out there who have supported us and believed in us, we on the JRuby team give our thanks. This milestone would not have been possible without you.

To all those out there interested in Ruby, Rails, JRuby, or any combination of the three, I say this: You ain't seen nothing yet.

Thursday, March 30, 2006

A Ruby in the Rough

Feeling More and More Ruby with Gems

Things are speedily moving along. We have been continuing our work on Rails, but because of an unusually active JRuby community, we recently changed direction for a bit. We decided to tackle RubyGems.

RubyGems, if you are unfamiliar with it, is a packaging system for bundling up and installing Ruby applications into your local Ruby distribution. It works with both file-based and name-based installs, so that you can either "gem install rails-x.x.x.gem" or "gem install rails" and it will fetch the appropriate archive for you. It manages depedencies and updates seamlessly. It basically does for Ruby what apt-get and rpm do for Linux.

There's not a terribly high level of complexity to the RubyGems code, like there is with IRB or Rails, but it exercises many APIs the former two do not. In our case, the biggest issue was Zlib.

Ruby of course has full Zlib support, with gzip, inflate, checksums, and a nice stream-like API. However, as with many other bit, byte, or math-intensive libraries, Ruby's Zlib is implemented in C code. This certainly speeds up the processing of compressed archives, but it presents a continuing problem for JRuby: we can't inherit *all* of Ruby's libraries just by copying over the lib/ruby/1.8 dir. In this case, luckily, we can do what Ruby does.

Java has included java.util.zip, support for compressed archives, since the 1.1 release, with streams for zip, gzip, and deflate compression and decompression. It also includes the same checksums Ruby includes, CRC32 and Adlter32. It provides probably 90% of what we need in Ruby's Zlib library.

The availability of a pure-Java implementation of a Ruby library certainly cuts down our workload. Since we already have significant capabilities for calling Java code from Ruby, there's usually only a bit of Ruby code required. However everything takes time, and since Rails has been our primary focus we had not spent much time getting Zlib implemented.

Enter our new friend Ola. Ola recently appeared on the jruby-devel mailing list, interested in helping out with JRuby and contributing fixes whereever possible. He also expressed an interest in making RubyGems work. We rattled off a couple items, with Zlib in the list explicitly because it was the major roadblock for RubyGems, and within about a day Ola returned with a preliminary Zlib implementation. I was personally very impressed.

Now it goes without saying that his implementation wasn't perfect the first time, but this really got us going. We switched gears for a few days and worked back and forth with Ola to get Zlib and RubyGems working more smoothly. I think I spent 12 hours on Saturday hacking through Zlib, YAML, and RubyGems code digging for failures. The end result was RubyGems's setup.rb install script running to completion, but it wasn't quite there. Ola came to the rescue to resolve a few more minor issues, Tom committed some additional fixes today, and although we didn't get RubyGems working in time for the 0.8.3 release, we did get a lot done.

At this point, we are able to successfully install RubyGems into the JRuby distribution directory. Huzzah!

Now of course you knew there would be caveats.

Java as a Platform

When running Ruby, there are a number of constants pre-set for you. Among these is RUBY_PLATFORM, which identifies the underlying platform on which Ruby is running. Ruby under Windows reports "mswin". Under linux it reports "linux", unsurprisingly. For JRuby, it made sense to report "java", since we do not match any other platform exactly. Java is its own platform.

The availability of the RUBY_PLATFORM constant allows scripts to change their behavior depending on the platform. Since Windows doesn't directly support symbolic links, discovering a RUBY_PLATFORM of "mswin" means you shouldn't try to create them. Discovering a platform of "linux" means you probably shouldn't generate externally-consumed file paths using backslash characters. Given that even a cross-platform language and implementation must interact with its host environment, these cases make sense.

Unfortunately, Ruby's libraries only know about the platforms that the C implementation supports. Hence, there's a problem when running under JRuby. Since we report our platform as "java", any code that uses RUBY_PLATFORM to turn off unsupported features does not have any effect. The specific case I ran into was within the fileutils library.

fileutils provides a number of convenience methods for manipulating or querying files. There's methods like cp for copying files, uptodate? to check if a file or files' modification times are later than another specified file, and other similar functions. It is with cp that JRuby ran into problems.

fileutils' cp implementation copies one or more source files to a target file or directory. During this process, it also checks whether the target file is equivalent to the source file. This it does in one of two ways:

- On a UNIX variant, fileutils compares the device and inode for the file, using File::Stat#dev and #ino
- On a Windows variant, where device and inode have no real meaning, fileutils compares absolute paths

In order to know which method to use, RUBY_PLATFORM comes into play:


def fu_windows?
/mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM
end

The fu_windows? method obviously returns true on a Windows platform or on any platform where dev and ino will not be available. Notice that Java is not in that list?

Device and inode have even less meaning in Java, which abstracts away the concept of a "file" into the most generic definition possible. In order to keep Java code running the same on all platforms--without platform checks or code changes--Java's File must cater to the lowest common denominator. That's great for Java code, but for us poor suckers trying to get Ruby to run in Java, it's an issue. We need Ruby's libraries to understand that Java doesn't support the same things a UNIX variant does, and doesn't support other things that a Windows variant does. In short, we need Ruby to understand the Java platform's capabilities.

Now we aren't going to be able to solve that issue today. It would be a little unusual for Ruby to include a "java" platform whereever platform is being queried, and I don't doubt we'd get some pushback on that. We're kicking around possible solutions, ranging from implementing our own versions of those libraries that use RUBY_PLATFORM extensively to including modified Ruby libraries in the base JRuby distribution. In the short term, we chose to locally modify fileutils as follows:

def fu_windows?
/mswin|mingw|bccwin|wince|emx|java/ =~ RUBY_PLATFORM
end

With this change, RubyGems is able to successfully install and copy all required files to the JRuby distribution dir. It's not perfect, but it's a start.

Installation != Working

Aside from the very simple case of installing the sources gem, RubyGems is not quite working correctly in JRuby. With RubyGems installed, previously-functional Rails scripts start breaking in new and exciting ways. Network-based gems do not install, owing to our bare-minimum Socket implementation and our lack of marshalling code for appropriate Ruby classes. File-based gems attempt to install, but get "stuck" somewhere during processing. All are frustrating issues, but we're very close.

Small Moves

Along with RubyGems nearly working, it was a very productive week. A lot of the contributions for RubyGems will be helpful in many other areas, and we have continued work on Rails as well.

- We now have a working Zlib library.
- We have made more progress toward getting Rails to work, by running dispatch.rb/cgi and fixing as we go.
- We finally got out a new release after a long delay.
- We are fairly confident we'll be able to demo everything we want at JavaOne.

Things are looking great, and I'm very excited.

Monday, March 27, 2006

Ultra

It seems that JRuby is more than just an entertaining and challenging project; it's also getting attention from folks that matter at Sun Microsystems.

Tim Bray, Sun Web Technologies director and XML specification co-editor, has recently taken an interest in JRuby. He's corresponded by email with both Tom and myself, and has offered useful insight here and there. It's good to know people are watching JRuby and wishing us well.

Of course, a couple free machines never hurts either.

Tim managed to "jar loose" a couple beautiful Sun Ultra 20 machines, one each for Tom and I. I can't speak for Tom, but considering the dismal condition of my home data center, the new machine is a welcome addition.

I generally have nothing but good things to say about the Ultra 20. We received the base "Large" model as listed on Sun's store; I'll save you a click and paste specs here:

Sun Ultra 20 Workstation
1 AMD Opteron Model 152 Processor
1-MB On-Chip L2 Cache
2-GB Memory
1 250-GB 7200 RPM SATA Disk Drive
1 Quadro FX 1400 Graphics Card
1 DVD-Dual Drive
1 10/100/1000 BaseT Ethernet Port
6 USB Ports
2 IEEE 1394a Ports
1 PCI-Express x16 Slot
2 PCI-Express x1 Slots
4 Conventional PCI Slots (32-Bit/33-MHz)
Sun Studio Software Pre-Installed
Sun Java Studio Creator Software Pre-Installed
Sun Java Studio Enterprise Software Pre-Installed
Solaris 10 Operating System Pre-Installed
3 Year Warranty, 3 Year Parts Exchange

Any review I might give would be impossibly biased by my complete lack of experience with recent hardware. Before the Ultra 20, my fastest machine was my 1.6GHz Pentium M Dell laptop, which overheated when running unit tests too vigorously (producing no end of colorful metaphors from yours truly). I had no desktop, having converted my poor old 1GHz Celeron homebuilt into the headius.com server. Suffice it to say that the Ultra 20 is by far the fastest, quietest, and most impressive workstation I've had the pleasure of using.

Before this machine, the stories of AMD chips trouncing the top-end Intel equivalents were merely anecdotal. Now I get it. The Intel machines I use most days almost seem broken in comparison. Given that AMD topping Intel only means Intel will work harder to create more competitive chips, this bodes extremely well for the next crop.

My only disappointment was that my old 17" Mitsubishi monitor, the only remaining working monitor in my house (don't ask about the 21" Viewsonic that met its untimely demise at the hands of a leaky basement window) was unable to work out-of-the-box with the pre-installed Solaris 10. I was keen to give it a shot, but it seems it will have to wait until I upgrade to a better screen. Hopefully, that will happen in the next week or two.

I would whole-heartedly recommend this machine (or even one of the lower models) to anyone that needs a new box. Even the base "Small" model is still far faster of a machine than I've ever used, and it seems to be priced well. Again, take my star-struck (Sun-struck?) opinion with a grain of salt, but having a powerful, inexpensive computer with a Sun logo on the front seems like a pretty sweet deal to me. YMMV.

In the end, however, a blazing fast machine means faster development, faster test runs, and faster progress on JRuby. Who knows, perhaps I'll even have time for the other 9000 projects I'd like to tackle.

Thank you Tim Bray, and thank you Sun Microsystems.