Posted by kohsuke
on September 29, 2008 at 6:41 PM PDT
I wrote a little program that can host any executable (Java included) as a Windows service, and made it available in the BSD license.
I reported earlier that Hudson can now install itself as a Windows service ,
and behind this technology is the reusable Windows service wrapper code I wrote, which is separately reusable and available in the "winsw" project.
Now, I think the first question that people would ask is, why another, when there's Java Service Wrapper project already available. The main reason for writing my own was the license — Java Service Wrapper project is in GPL (so that they can sell their commercial version in a different license), and that made it difficult for Hudson (which is under the MIT license) to use it.
Functionality-wise, there's really not much that's worth noting; the problem of wrapping a process as a Windows service is so well defined that there aren't really any room for substantial innovation. You basically write a configuration file specifying how you'd like your process to be launched, and we provide programmatic means to install/uninstall/start/stop services. Another notable different is that winsw can host any executable, whereas Java Service Wrapper can only host Java apps. Whether you like this or not depends on your taste, so I wouldn't claim mine is better. It's just different.
You write the configuration file that defines your service. This is the one I use for Hudson:
This service runs Hudson continous integration system.
-Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\hudson.war" --httpPort=8080
You'll rename winsw.exe into something like hudson.exe, then you put this XML file as hudson.xml.
The executable locates the configuration file via this file name convention. You can then install the service like:
... and you can use the exit code from these processes to determine whether the operation was successful. There are other commands to perform other operations, like uninstall.
This project is available on Kenai (which is the new forge Sun is doing), along with a complete documentation, the source code, and the binary.
The code is implemented in C# (which makes it super-easy to implement something like this, compared to doing so in C++.) I use a java.lang.reflect.Proxy-like technique so that I can perform WMI operations elegantly. It's been a while I've done .NET development, so this was fun. C# got several really nifty language features that make the code terse (which I'd love to see in Java), but OTOH the library still sucks — for example, the Proxy capability is not a part of the core library.
On a related note, projects like com4j and JNA make it probably possible to do this entirely in Java. I think this would be an interesting hobby project for someone, so that people can avoid forking processes, which is always awkward.