Friday, 2 May 2025
Affinity-for-mermaid
Sunday, 30 March 2025
Upgrading to the Mikrotik RouterBoard RB2011, Part 2 - DHCP
Monday, 23 October 2023
Markdown (and Mermaid) on Blogger in 2023
Sunday, 28 November 2021
Importing/capturing digital video (DV) for FREE on a Mac in 2021
Like many others, I have a giant box of Mini DV video cassettes from 10+ years ago that I fairly-urgently need to get onto a more long-term-safe medium. As it's a pretty tedious job I have tended to do this in batches, when I can be bothered getting all the necessary bits together. Fortunately my trusty 2012 MacBook Pro has Thunderbolt ports that with just a couple of cheap adapters, can connect to the 4-pin Firewire port of my still-functional Panasonic NV-GS27 camcorder and do the job.
But while the hardware is willing, sometimes the software is not. It's all too easy to get on the upgrade treadmill and forget about applications you only use once every couple of years. In the past I used Vidi, which was minimal but $0, and thus excellent. But it won't work on 64-bit MacOS and appears unmaintained so I needed something new.
All I needed was something that could capture the raw data from each cassette and dump it into a .dv file that I can stash away on a hard drive.After a very dismaying tour through Google and YouTube made me think I'd either need to pay for a software package, or kludge something together using libdc1394 (which would be massive overkill) I finally found what I needed by searching Github directly: vrecord by AMIA Open Source.
vrecord works beautifully on my Catalina (OSX 10.15) MacBook Pro - follow the Basic Usage guide and you'll be capturing those precious memories in no time.
Sunday, 13 September 2020
Micro-optimisation #9725: Checkout the mainline
Very soon (October 1, 2020) Github will be making main the default branch of all new repositories instead of master. While you make the transition over to the new naming convention, it's handy to have an abstraction over the top for frequently-issued commands. For me, git checkout master is one of my faves, so much so that I've already aliased it to gcm. Which actually makes this easier - main and master start with the same letter...
Now when I issue the gcm command, it'll check if main exists, and if not, try master and remind me that this repo needs to be migrated. Here's the script
~/bin/checkout-main-or-master.sh:
#!/bin/bash
# Try main, else master and warn about outdated branch name
MAIN_BRANCH=`git branch -l | grep main`
if [[ ! -z ${MAIN_BRANCH} ]]; then
git checkout main
else
echo "No main branch found, using master... please fix this repo!"
git checkout master
fi
I run it using this alias:
alias gcm='~/bin/checkout-main-or-master.sh'
So a typical execution looks like this:
mymac:foo john$ gcm No main branch found, using master... please fix this repo! Switched to branch 'master' Your branch is up to date with 'origin/master'. mymac:foo john$
Monday, 24 August 2020
Micro-optimisation #6587: Git push to Github
I've said it before; sometimes the best automations are the tiny ones that save a few knob-twirls, keystrokes or (as in this case) a drag-copy-paste, each and every day.
It's just a tiny thing, but I like it when a workflow gets streamlined. If you work on a modern Github-hosted codebase with a Pull-Request-based flow, you'll spend more than a few seconds a week looking at this kind of output, which happens the first time you try to git push to a remote that doesn't have your branch:
mymac:foo john$ git push
fatal: The current branch red-text has no upstream branch.
To push the current branch and set the remote as upstream, use
git push --set-upstream origin red-text
mymac:foo john$ git push --set-upstream origin red-text
Counting objects: 24, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (16/16), done.
Writing objects: 100% (24/24), 2.79 KiB | 953.00 KiB/s, done.
Total 24 (delta 9), reused 0 (delta 0)
remote: Resolving deltas: 100% (9/9), completed with 9 local objects.
remote:
remote: Create a pull request for 'red-text' on GitHub by visiting:
remote: https://github.com/my-org/foo/pull/new/red-text
remote:
To https://github.com/my-org/foo.git
* [new branch] red-text -> red-text
Branch 'red-text' set up to track remote branch 'red-text' from 'origin'.
The desired workflow is clear and simple:
- Push and set the upstream as suggested
- Grab the suggested PR URL
- Use the Mac open command to launch a new browser window for that URL
#!/bin/bash
# Try and push, catch the suggested action if there is one:
SUGG=`git push --porcelain 2>&1 | grep "git push --set-upstream origin"`
if [[ ! -z ${SUGG} ]]; then
echo "Doing suggested: ${SUGG}"
URL=`${SUGG} --porcelain 2>&1 | grep remote | grep new | grep -o "https.*"`
if [[ ! -z ${URL} ]]; then
echo "Opening URL ${URL}"
open $URL
else
echo "No PR URL found, doing nothing"
fi
fi
I run it using this alias:
alias gpgh='~/bin/push-to-github.sh'
So a typical execution looks like this:
mymac:foo john$ gpgh Doing suggested: git push --set-upstream origin mybranch Opening URL https://github.com/my-org/someproject/pull/new/mybranch mymac:foo john$
Friday, 31 January 2020
OpenHAB Broadlink Binding situation report
After #dadlife, #newjob and #otherstuff got in the way for a while last year, I got back into my role as maintainer of the OpenHAB Broadlink device binding. My first priority was to create a binding JAR that would actually work with the newly-published OpenHAB version 2.5. As the Broadlink binding is still not part of the official OpenHAB binding repository, it doesn't "automagically" get the necessary changes applied when the upstream APIs change. Luckily, it wasn't too much work.
My priorities for 2020 for this binding remain unchanged; get it to a high-quality state, make it pass the (extremely strict) linter guidelines for OpenHAB code, and get it merged into the official codebase. For me to consider it high-quality, there are still the following tasks to do:
- Get a solid chunk of it covered by unit tests to prevent regressions; and
- Redesign the device-discovery and identification areas of the code, to make adding new devices easier
Unit Tests
Prior to OpenHAB 2.5, bindings/addons that wished to define tests had to create an entire second project that shadowed the production code and could only be run via a strange incantation to Maven which did horrible OSGi things to run integration-style tests. Essentially, OpenHAB addons were not unit-testable by conventional means. Which given most addons are developed by unpaid volunteers, naturally meant that hardly any addons had tests.
Fortunately, one of the major changes in the 2.5 architecture has been a move towards more Java-idiomatic unit testing. Finally, classic JUnit-style unit testing with Mockito mocking will be available for fast, reliable testing within the binding. I'll be shooting for at least 60% test coverage before I'll consider submitting a PR to OpenHAB.
Discovery redesign
I've been told that new versions of some popular Broadlink devices will be arriving in 2020. In anticipation of that, I want to make it much easier to add a new device. At the moment it requires defining a new subclass of BroadlinkBaseThingHandler (which is par-for-the-course for OpenHAB, being a pretty standard Java app), but also adding "magic numbers" in a number of places to assist in looking-up and identifying devices during "discovery" and also when they boot up. I want to consolidate this such that everything needed to support a device is located within one .java file - i.e. adding support for a new device will require exactly two changes in Git:
- The new .java file containing all the required information to support the new device; and
- Adding a reference to this class somewhere to "pick it up".
Thanks for all the kind words from users/testers of this binding - it's very rewarding to hear people using it with great success!
Friday, 8 June 2018
A New Old Thing; Building a retro game with React.js. Part 1 - Background and Setup
At the risk of being immodest, I'm comfortable with those concepts - Design Patterns from waaaay back and the functional paradigms from my five-year (and counting) love affair with Scala. What I wanted to explore was - what would happen if I built a React app by myself, endeavouring to write the cleanest, purest software based upon the best starting-point we currently have? How productive could I be? How long would it take to build a working full app? How would maintenance go? How quickly could I add a new feature?
As my day job is basically building CRUD apps, I wanted to do something a lot more fun for this side-project. And what could be more fun than a game? (Mental note: ask people working at Electronic Arts...) There's also a pleasing circularity in building a game and documenting how I did it - back in my earliest days of having a computer, aged about 7, I would buy magazines with program listings and laboriously enter them, line-by-line, while marvelling at how anyone could really have been good enough to know how to do this.
The Game
I'll admit, I've never built a non-trivial game before, but I think attempting an 8-bit home computer game I remember fondly from my childhood, on top of 2018's best front-end technologies, should be about the right level of difficulty.The game I'll be replicating is called Frenzy; a Micro Power publication for the BBC B, Acorn Electron and Commodore 64. My machine was the Electron - basically a low-cost little brother to the mighty Beeb; highly limited in RAM and CPU, titles for this platform usually needed substantial trimming from their BBC B donor games, despite using the same BBC BASIC language.
Check out the links above for more details and screenshots, but the game is basically a simplified version of "Qix" or "Kix" where the object is to fill in areas of the screen without being hit by one or more moving enemies.
Just for the hell of it, I'm going to place this game front-and-centre on my homepage at http://www.themillhousegroup.com, which I just nuked for this purpose. The page is now a React app being served off a Play Scala backend as per my new-era architecture, and the key technologies I'm using so far are:
- React via Create-React-App
- react-game-kit for game secret-sauce
- react-emotion for component styling
Initial Development
To develop the game, I decided to start from the start. The welcome page would need to be suitably old-skool but would force me to consider a few things:- What screen size should I be working to?
- Can I get a suitably chunky, monospaced font?
- Press Space to start sounds easy, but how do I make that actually work?
Decisions
The original Frenzy must have operated in the BBC's graphical MODE 1 because it used a whopping 4 colours and the pixels were square. So that means the native resolution was 320x256. While it would be tempting to stick to that screen size and thus have it fit on every smartphone screen, I've decided to double things and target a 640x512 effective canvas.Some searching for 8-bit fonts led me to "Press Start 2P" which, while intended to honour Namco arcade machines, is near enough to the chunky fonts I remember fondly from my childhood home computer that I can't go past it:
As a tiny nod to the present, the "screen" is actually slightly transparent and has a drop shadow - showing how far we've come in 34 years!
The final piece of the welcome screen was achieved by mounting the FrenzyGame component in a React-Game-Kit Loop and using the KeyListener to subscribe to the keys I care about - a quick perusal of the demo game showed me how to use it:
class FrenzyGame extends Component {
constructor(props) {
super(props);
this.keyListener = new KeyListener();
this.state = {
gameOver: true
};
}
componentDidMount() {
this.loopSubscriptionId = this.context.loop.subscribe(this.update);
this.keyListener.subscribe([
this.keyListener.SPACE
]);
}
componentWillUnmount() {
this.context.loop.unsubscribe(this.loopSubscriptionId);
this.keyListener.unsubscribe();
}
update() {
if (this.state.gameOver) {
if (this.keyListener.isDown(this.keyListener.SPACE)) {
this.setState({ gameOver: false });
}
}
};
...
render() {
return this.state.gameOver
? this.renderWelcomeScreen()
: this.renderGame();
}
}
Saturday, 31 March 2018
Green Millhouse - Fixing the OpenHAB BroadLink Binding (part 1)
I've been building and testing locally with my A1 Air Quality Sensor, and since fixing some shared-state issues in the network layer, haven't yet experienced any of the reliability problems that plagued the original binding.
For reasons that aren't clear (because I'm working from a decompiled JAR file), the original binding was set up like this in the base Thing handler (which all Broadlink Things inherit from):
public class BroadlinkBaseThingHandler extends BaseThingHandler {
private static DatagramSocket socket = null;
static boolean commandRunning = false;
...
}
As soon as I saw those static members, alarms started ringing in my head - especially when combined with an inheritance model, you've got a definite "fragile base class" problem at compile-time, and untold misery at runtime when multiple subclasses start accessing the socket like it's their exclusive property!
An attempt to mitigate the race-conditions which must have abounded, the commandRunning boolean only complicated matters:
public boolean sendDatagram(byte message[])
{
try
{
if(socket == null || socket.isClosed())
{
socket = new DatagramSocket();
socket.setBroadcast(true);
}
InetAddress host = InetAddress.getByName(thingConfig.getIpAddress());
int port = thingConfig.getPort();
DatagramPacket sendPacket = new DatagramPacket(message, message.length, new InetSocketAddress(host, port));
commandRunning = true;
socket.send(sendPacket);
}
catch(IOException e)
{
logger.error("IO error for device '{}' during UDP command sending: {}", getThing().getUID(), e.getMessage());
commandRunning = false;
return false;
}
return true;
}
public byte[] receiveDatagram()
{
try {
socket.setReuseAddress(true);
socket.setSoTimeout(5000);
} catch (SocketException se) {
commandRunning = false;
socket.close();
return null;
}
if(!commandRunning) {
logger.error("No command running - device '{}' should not be receiving at this time!", getThing().getUID());
return null;
}
try
{
if(socket != null)
{
byte response[] = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(response, response.length);
socket.receive(receivePacket);
response = receivePacket.getData();
commandRunning = false;
socket.close();
return response;
}
}
catch (SocketTimeoutException ste) {
if(logger.isDebugEnabled()) {
logger.debug("No further response received for device '{}'", getThing().getUID());
}
}
catch(Exception e)
{
logger.error("IO Exception: '{}", e.getMessage());
}
commandRunning = false;
return null;
}
So we got a pseudo-semaphore that is trying to detect getting into a bad state (because of shared-state), but itself is shared-state, thereby experiencing the same unreliability.
Here's what the new code looks like:
public class BroadlinkBaseThingHandler extends BaseThingHandler {
private DatagramSocket socket = null;
...
public boolean sendDatagram(byte message[], String purpose) {
try {
logTrace("Sending " + purpose);
if (socket == null || socket.isClosed()) {
socket = new DatagramSocket();
socket.setBroadcast(true);
socket.setReuseAddress(true);
socket.setSoTimeout(5000);
}
InetAddress host = InetAddress.getByName(thingConfig.getIpAddress());
int port = thingConfig.getPort();
DatagramPacket sendPacket = new DatagramPacket(message, message.length, new InetSocketAddress(host, port));
socket.send(sendPacket);
} catch (IOException e) {
logger.error("IO error for device '{}' during UDP command sending: {}", getThing().getUID(), e.getMessage());
return false;
}
logTrace("Sending " + purpose + " complete");
return true;
}
public byte[] receiveDatagram(String purpose) {
logTrace("Receiving " + purpose);
try {
if (socket == null) {
logError("receiveDatagram " + purpose + " for socket was unexpectedly null");
} else {
byte response[] = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(response, response.length);
socket.receive(receivePacket);
response = receivePacket.getData();
// socket.close();
logTrace("Receiving " + purpose + " complete (OK)");
return response;
}
} catch (SocketTimeoutException ste) {
logDebug("No further " + purpose + " response received for device");
} catch (Exception e) {
logger.error("While {} - IO Exception: '{}'", purpose, e.getMessage());
}
return null;
}
A lot less controversial I'd say. The key changes:
- Each subclass instance (i.e. Thing) gets its own socket
- No need to track commandRunning - an instance owns its socket outright
- The socket gets configured just once, instead of being reconfigured between Tx- and Rx-time
- Improved diagnostic logging that always outputs the ThingID, and the purpose of the call
The next phase is now stress-testing the binding with a second heterogeneous device (sadly I don't have another A1, that would be great for further tests), my RM3 Mini IR-blaster. I'll be trying adding and removing the devices at various times, seeing if I can trip the binding up. The final step will be making sure the Thing discovery process (which is the main reason to upgrade to OpenHAB 2, and is brilliant) is as good as it can be. After that, I'll be tidying up the code to meet the OpenHAB guidelines and hopefully getting this thing into the official release!
Sunday, 25 February 2018
Green Millhouse - Temp Monitoring 2 - Return of the BroadLink A1 Sensor!
Here's the relevant OpenHAB forum post - it includes a link to a Beta-quality OpenHAB binding, which I duly installed to my Synology's OpenHAB 2 setup, and it showed itself to be pretty darn good. Both my A1 and my new BroadLink RM3 Mini (wifi-controlled remote blaster) were discovered immediately and worked great "out of the box".
However, I discovered that after an OpenHAB reboot (my Synology turns itself off each night and restarts each morning to save power) the BroadLink devices didn't come back online properly; it was also unreliable at polling multiple devices, and there were other niggly little issues identified by other forum members in the above thread. Worst of all, the original developer of the binding (one Cato Sognen) has since gone missing from the discussion, with no source code published anywhere!
Long story short, I've decided to take over the development of this binding - 90% of the work has been done, and thanks to the amazing JAD Decompiler, I was able to recover the vast majority of the source as if I'd written it myself. At the time of writing I am able to compile the binding and believe I have fixed the multiple-device problems (the code was using one shared static Socket instance and a shared mutable Boolean to try and control access to it...) and am looking at the bootup problems. And best of all, I'm doing the whole thing "in the open" over on Github - everyone is welcome to scrutinise and hopefully improve this binding, with a view to getting it included in the next official OpenHAB release.
Thursday, 25 January 2018
OpenShift - the 'f' is silent
After almost-exactly four years of free-tier OpenShift usage for Jenkins purposes, I have finally had to throw up my hands and declare it unworkable.
The first concern was earlier in 2017 when, with minimal notice, they announced the end-of-life of the OpenShift 2.0 platform which was serving me so well. Simultaneously they dropped the number of nodes available to free-tier customers from 3 to 1. A move I would have been fine with if there had been any way for me to pay them down here in Australia - a fact I lamented about almost 2 years ago.
Then, in the big "upgrade" to version 3, OpenShift disposed of what I considered to be their best feature - having the configuration of a node held under version control in Git; push a change, the node restarts with the new config. Awesome. Instead, version 3 handed us a complex new ecosystem of pods, containers, services, images, controllers, registries and applications, administered through a labyrinth of somewhat-complete and occasionally-buggy web pages. Truly a downgrade from my perspective.
The final straw was the extraordinarily fragile and flaky nature of the one-and-only node (or is it "pod"? Or "application"? I can't even tell any more) that I have running as a Jenkins master. Now this is hardly a taxing thing to run - I have a $5-per-month Vultr instance actually being a slave and doing real work - yet it seems to be unable to stay up reliably while doing such simple tasks as changing a job's configuration. It also makes "continuous integration" a bit of a joke if pushing to a repository doesn't actually end up running tests and building a new artefact because the node was unresponsive to the webhook from Github/Bitbucket. Sigh.
You can imagine how great it is to see this page when you've just hit "save" on the meticulously-detailed configuration for a brand new Jenkins job...
So, in what I hope is not a taste of things to come, I'm de-clouding my Jenkins instance and moving it back to the only "on-premises" bit of "server hardware" I still own - my Synology DS209 NAS. Stay tuned.
Tuesday, 29 August 2017
Don't Fetch What You Don't Need
GraphQL is a work-in-progress. The data type primitives are very limiting (how can I represent a UNIX/JavaScript timestamp with just an Int?), and always POSTing to the server seems like a backward step to the bad-old-days of SOAP. But as with all things in the JavaScript world, it's improving at a truly breakneck pace.
Something that I immediately saw as valuable was being able to save bandwidth by not including fields in the desired response - it also felt familiar, and yesterday I realised why - in MongoDB it's trivially easy to do this whenever you write a query. This excellent feature was sadly not exposed in my Mondrian library for Scala; something I've now rectified in the 0.6.x release.
Some quick tests involving documents that had large arrays of heavyweight fields showed that dropping them using a projection typically saved 50ms of latency, even on very small collections of documents. This has worked out very well for the use case of my current top-secret side project, where upon arrival at the front page, we need to quickly fetch a "summary" version of the most-recent 10 documents. The page visitor can then browse these and we can paginate for more summaries, or, if they are interested in a particular summary, we perform a findById and get the full "heavy" object.
Saturday, 8 July 2017
The CRAP Stack, Part 3 - Front-End Routes with a Play server
http://myapp.com/foo/barwhere there is no explicit entry for GET /foo/bar in Play's routes and nor is there a physical asset located in /public/foo/bar for the Assets controller to return to the client, as we set up in the last instalment:
# Last of all, fall through to the React app GET / controllers.Assets.at(path="/public",file="index.html") GET /*file controllers.Assets.at(path="/public",file)What we'd like is for the React application at index.html to be served up, so that it can then consume/inspect/route from the original URL via the Window.location API.
As it stands, the last line of routes will match, the Assets controller will fail to find the resource, and your configured "client error handler" will be called to deal with the 404. This is not what we want for a "front-end route"!
We want requests that don't correspond to a physical asset to be considered a request for a virtual asset - and hence given to the React app. And after a bit of fiddling around, I've come up with a FrontEndServingController that gives me the most efficient possible way of dealing with this. The Gist is available for your copy-paste-and-improve pleasure, but the key points are:
The fall-through cases at the bottom of routes become:
GET / controllers.FrontEndServingController.index GET /*file controllers.FrontEndServingController.frontEndPath(file)Those methods in FrontEndServingController just being:
val index = serve(indexFile)
def frontEndPath(path: String) = serve(path)
private def serve(path: String) = {
if (physicalAssets.contains(path)) {
logger.debug(s"Serving physical resource: '$path'")
assets.at(publicDirectory, path, true)
} else {
logger.debug(s"Serving virtual resource: '$path'")
// It's some kind of "virtual resource" -
// a front-end "route" most likely
assets.at(publicDirectory, indexFile, true)
}
}
We're still using Play's excellent built-in AssetsController to do the hard work of caching, ETags, GZipping (all the classic webserver jobs) - we have injected it as assets using Dependency Injection - composition FTW. That true argument tells it to use "aggressive caching" which is ideal for this scenario where the bundle files we're serving up already have a cache-busting filename.
And now the "clever" bit being a recursive scan of the /public directory when we start up, assembling a definitive (and immutable!) Set[String] of what's actually a physical asset path:
lazy val physicalAssets:Set[String] = {
val startingDirectory = new File(physicalPublicDirectory)
deepList(startingDirectory)
}
private def deepList(f: File): Set[String] = {
val these = f.listFiles.toSet
val inHere = these.filter(_.isFile).map { f =>
f.getPath.replace(physicalPublicDirectory, "")
}
val belowHere = these.filter(_.isDirectory).flatMap(deepList)
inHere ++ belowHere
}
Friday, 26 February 2016
Making better software with Github
This solved my problem, in that I no longer ran out of PermGen on my build slave. But the repercussions were far-reaching. Any decent public-facing library needs documentation, and Github's README.md is an incredibly convenient place to put it all. I've lost count of the number of times I've found myself reading my own documentation up there on Github; if Arallon was still a hodge-podge of classes within my application, I'd have spent hours trying to deduce my own functionality ...
Of course, a decent open-source library must also have excellent tests and test coverage. Splitting Arallon into its own library gave the tests a new-found focus and similarly the test coverage (measured with JaCoCo) was much more significant.
Since that first library split, I've peeled off many other utility libraries from private projects; almost always things to make Play2 app development a little quicker and/or easier:
- play2-reactivemongo-mocks - Mocking out a ReactiveMongo persistence layer
- play2-mailgun - Easily send email via MailGun's API
- pac4j-underarmour - Integrates UnderArmour (aka MapMyRun) into the pac4j authentication framework
- mondrian - A super-simple CRUD layer for Play + ReactiveMongo
As a shameless plug, I use yet another of my own projects (I love my own dogfood!), sbt-skeleton to set up a brand new SBT project with tons of useful defaults like dependencies, repository locations, plugins etc as well as a skeleton directory structure. This helps make the decision to extract a library a no-brainer; I can have a library up-and-building, from scratch, in minutes. This includes having it build and publish to BinTray, which is simply just a matter of cloning an existing Jenkins job and changing the name of the source Github repo.
I've found the implied peer-pressure of having code "out there" for public scrutiny has a strong positive effect on my overall software quality. I'm sure I'm not the only one. I highly recommend going through the process of extracting something re-usable from private code and open-sourcing it into a library you are prepared to stand behind. It will make you a better software developer in many ways.
* This is not a criticism of OpenShift; I love them and would gladly pay them money if they would only take my puny Australian dollars :-(
Friday, 12 December 2014
Walking away from CloudBees Part 5 - Publishing and Fine-Tuning
Publishing private artefacts to a private Nexus repository
As per my new world order diagram, I decided to use my third and final free OpenShift node as a Nexus box, and what a great move that turned out to be. Without a doubt the easiest setup of a Nexus box I've ever experienced:- Log in to OpenShift
- Click theAdd Application... button
- Scroll down to the Code Anything heading, and paste http://nexuscartridge-openshiftci.rhcloud.com/ into the URL textbox
- Click Next, nominate the URL for the box, and wait a few minutes
Publishing open-source artefacts to a public repository
As all of my open-source efforts are now written in Scala with SBT as the build tool, it was a simple matter to add the bintray-sbt plugin to each of them, allowing publication to BinTray, or more specifically, The Millhouse Group's little corner of it.The only trick here was SSHing into the Jenkins Build slave (one time) and adding an ${OPENSHIFT_DATA_DIR}/.bintray/.credentials file so that an sbt publish would succeed.
Deployment of webapps to Heroku
As with most things open and/or free, someone has been here before - this blog post, together with the Heroku Jenkins Plugin README were a very good starting point for getting this all working.In brief, the steps are:
- Install the Heroku and Git Publisher Jenkins plugins
- Grab your Heroku API key from your Account Settings page, and put it into Manage Jenkins -> Configure System -> Heroku -> API Key
- Grab the details of the Heroku remote from your .git/config in your local repo, or from the "Git URL" in the Info on your app's Settings page on Heroku.
- Set this up as an additional Git repo in your Jenkins build, and name it heroku. For safety, I like to name my other repo (i.e. the one holding the source that triggers builds) appropriately as well; it avoids confusion.
- Actual example:
- I name my source repo bitbucket
- Thus my Branch Specifier is bitbucket/master
- Add a new Git Publisher Post-Build Action, that pushes to heroku/master when the build succeeds
Fine-tuning the OpenShift build setup
Having to do "Layer-8" timezone conversion when reading build logs is just annoying so put the slave node into your local time zone by navigating to (Manage Jenkins -> Manage Nodes -> Slave -> Configure icon -> Launch Method -> Advanced -> JVM Options) (phew!) and setting it to:
-Duser.home=${OPENSHIFT_DATA_DIR} -Duser.timezone="Australia/Melbourne" -XX:MaxPermSize=1M -Xmx2M -Xss128k
(You might need to consult the list of Java timezone ids)
The final pieces of the puzzle were the configuring the "final destinations" of my private artifacts (my gets sent to BinTray courtesy of the bintray-sbt plugin). Details follow.
After that, a little bit of futzing around to get auto-triggered builds working from both GitHub and BitBucket, and I had everything back to normal, or possibly, even better - I now have unlimited app slots on Heroku versus four on CloudBees - and I'm somewhat insulated from outages of a single provider. Happy!
Tuesday, 4 November 2014
Walking away from CloudBees Episode 4: A New Hope
The OpenShift Free Tier gives you three Small "gears" (OpenShift-speak for "machine instance"), and there's even a "cartridge" (OpenShift-speak for "template") for a Jenkins master!
There are quite a few resources to help with setting up a Jenkins master on OpenShift, so I won't repeat them, but it was really very easy, and so far, I haven't had to tweak the configuration of that box/machine/gear/cartridge/whatever at all. Awesome stuff. The only trick was that setting up at least one build-slave is compulsory - the master won't build anything for you. Again, there are some good pages to help you with this, and it's nothing too different to setting up a build slave on your own physical hardware - sharing SSH keys etc.
The next bit was slightly trickier; installing SBT onto an OpenShift Jenkins build slave. This blog post gave me 95 percent of the solution, which I then tweaked to get SBT 0.13.6 from the official source. This also introduced me to the Git-driven configuration system of OpenShift, which is super-cool, and properly immutable unlike things like Puppet. The following goes in .openshift/action_hooks/start in the Git repository for your build slave, and once you git push, the box gets stopped, wiped, and restarted with the new start script. If you introduce an error in your push, it gets rejected. Bliss.
cd $OPENSHIFT_DATA_DIR
if [[ -d sbt ]]; then
echo “SBT installed”
else
SBT_VERSION=0.13.6
SBT_URL="https://dl.bintray.com/sbt/native-packages/sbt/${SBT_VERSION}/sbt-${SBT_VERSION}.tgz"
echo Fetching SBT ${SBT_VERSION} from $SBT_URL
echo Installing SBT ${SBT_VERSION} to $OPENSHIFT_DATA_DIR
curl -L $SBT_URL -o sbt.tgz
tar zxvf sbt.tgz sbt
rm sbt.tgz
fi
The next hurdle was getting SBT to not die because it can't write into $HOME on an OpenShift node, which was fixed by setting -Duser.home=${OPENSHIFT_DATA_DIR} when invoking SBT. (OPENSHIFT_DATA_DIR is the de-facto writeable place for persistent storage in OpenShift - you'll see it mentioned a few more times in this post)
But an "OpenShift Small gear" build slave is slow and severely RAM-restricted - so much so that at first, I was getting heaps of these during my builds:
... Compiling 11 Scala sources to /var/lib/openshift/which is actually Jenkins losing contact with the build slave, because it has exceeded the 512Mb memory limit and been forcibly terminated. The fact that it did this while compiling Scala - specifically while compiling Specs2 tests - reminds me of an interesting investigation done about compile time that pointed out how Specs2's trait-heavy style blows compilation times (and I suspect, resources) out horrendously compared to other frameworks - but that is for another day!/app-root/data/workspace/ /target/scala-2.11/test-classes... FATAL: hudson.remoting.RequestAbortedException: java.io.IOException: Unexpected termination of the channel hudson.remoting.RequestAbortedException: hudson.remoting.RequestAbortedException: java.io.IOException: Unexpected termination of the channel at hudson.remoting.RequestAbortedException.wrapForRethrow(RequestAbortedException.java:41) at hudson.remoting.RequestAbortedException.wrapForRethrow(RequestAbortedException.java:34) at hudson.remoting.Request.call(Request.java:174) at hudson.remoting.Channel.call(Channel.java:742) at hudson.remoting.RemoteInvocationHandler.invoke(RemoteInvocationHandler.java:168) at com.sun.proxy.$Proxy45.join(Unknown Source) at hudson.Launcher$RemoteLauncher$ProcImpl.join(Launcher.java:956) at hudson.tasks.CommandInterpreter.join(CommandInterpreter.java:137) at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:97) at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66) at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20) at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:756) at hudson.model.Build$BuildExecution.build(Build.java:198) at hudson.model.Build$BuildExecution.doRun(Build.java:159) at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529) at hudson.model.Run.execute(Run.java:1706) at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43) at hudson.model.ResourceController.execute(ResourceController.java:88) at hudson.model.Executor.run(Executor.java:232) ...
If you are experiencing these errors on OpenShift, you can actually confirm that it is a "memory limit violation" by reading a special counter that increments when the violation occurs. Note this count never resets, even if the gear is restarted, so you just need to watch for changes.
A temporary fix for these issues seemed to be running sbt test rather than sbt clean test; obviously this was using just slightly less heap space and getting away with it, but I felt very nervous at the fragility of not just this "solution" but also of the resulting artifact - if I'm going to the trouble of using a CI tool to publish these things, it seems a bit stupid to not build off a clean foundation.
So after a lot of trawling around and trying things, I found a two-fold solution to keeping an OpenShift Jenkins build slave beneath the fatal 512Mb threshold.
Firstly, remember while a build slave is executing a job there are actually two Java processes running - the "slave communication channel" (for want of a better phrase) and the job itself. The JVM for the slave channel can safely be tuned to consume very few resources, leaving more for the "main job". So, in the Jenkins node configuration for the build slave, under the "Advanced..." button, set the "JVM Options" to:
-Duser.home=${OPENSHIFT_DATA_DIR} -XX:MaxPermSize=1M -Xmx2M -Xss128k
Secondly, set some more JVM options for SBT to use - for SBT > 0.12.0 this is most easily done by providing a -mem argument, which will force sensible values for -Xms, -Xmx and -XX:MaxPermSize. Also, because "total memory used by the JVM" can be fairly-well approximated with the equation:
export SBT_OPTS="-Duser.home=${OPENSHIFT_DATA_DIR} -Dbuild.version=$BUILD_NUMBER"
export JAVA_OPTS="-Xss128k"
# the -mem option will set -Xmx and -Xms to this number and PermGen to 2* this number
../../sbt/bin/sbt -mem 128 clean test
This combination seems to work quite nicely in the 512Mb OpenShift Small gear.
Saturday, 1 November 2014
Walking away from Run@Cloud Part 3: Pause and Reflect
As CloudBees seem to have gone "Enterprise" in the worst possible way (from my perspective) and don't have any free offerings any more, I was now looking for:
- Git repository hosting (for private repos - my open-source stuff is on GitHub)
- A private Nexus instance to hold closed-source library artifacts
- A public Nexus instance to hold open-source artifacts for public consumption
- A "cloud" Jenkins instance to build both public- and private-repo-code when it changes;
- pushing private webapps to Heroku
- publishing private libs to the private Nexus
- pushing open-source libs to the public Nexus
I did a load of Googling, and the result of this is an ecosystem that is far more "diverse" (a charitable way to say "dog's breakfast") but still satisfies all of the above criteria, and it's all free. More detail in blog posts to come, but here's what I've come up with:
Tuesday, 25 June 2013
Publishing from SBT to CloudBees
SBT is a nice tool for developing Scala, and will happily publish to a Nexus or other such Maven/Ivy repository, but CloudBees is a little trickier than that, because it's best suited to hosting CloudBees-built stuff (i.e. the output of their Jenkins-In-The-Cloud builds).
Their support for uploading "external" dependencies is limited to the WebDAV protocol only - a protocol that SBT doesn't natively speak. Luckily, some excellent person has minimised the yak-shaving required by writing a WebDAV SBT plugin - here's how I got it working for my build:
In project/plugins.sbt, add the WebDAV plugin:
resolvers += "DiversIT repo" at "http://repository-diversit.forge.cloudbees.com/release"
addSbtPlugin("eu.diversit.sbt.plugin" % "webdav4sbt" % "1.3")
To avoid plastering your CloudBees credentials all over Github, create a file in ~/.ivy2/.credentials:
realm={account} repository
host=repository-{account}.forge.cloudbees.com
user={account}
password=
Where {account} is the value you see in the drop-down at the top right when you login to CloudBees Grand Central. Don't forget the Realm, this is just as important as the username/password!
Next, add this to the top of your build.sbt:
import eu.diversit.sbt.plugin.WebDavPlugin._and this later on:
credentials += Credentials(Path.userHome / ".ivy2" / ".credentials")
seq(WebDav.globalSettings : _*)
publishTo := Some("Cloudbees releases" at "https://repository-{account}.forge.cloudbees.com/"+ "release")
What this does: The first line tells SBT where to find that credentials file we just added.
The second line makes the webdav:publish task replace the default publish task, which is most-likely what you want. If it's not, use WebDav.scopedSettings and invoke the task with webdav:publish.
The third line specifies where to publish to, replacing all other targets. I found if I used the notation in the WebDAV plugin documentation:
publishTo <<= version { v: String =>
val cloudbees = "https://repository-diversit.forge.cloudbees.com/"
if (v.trim.endsWith("SNAPSHOT"))
Some("snapshots" at cloudbees + "snapshot")
else
Some("releases" at cloudbees + "release")
}
...SBT would attempt to upload my artifact to not-just CloudBees, but any other extra repository I had configured with the resolvers expression higher up in build.sbt, and hence try and upload to oss.sonatype.org, which I'm not ready for just yet! "Releases" is sufficient for me, I don't need the "snapshots" option.
And with that, it should just work like a charm:
> publish
[info] WebDav: Check whether (new) collection need to be created.
[info] WebDav: Found credentials for host: repository-{account}.forge.cloudbees.com
[info] WebDav: Creating collection 'https://repository-{account}.forge.cloudbees.com/release/net'
[info] WebDav: Creating collection 'https://repository-{account}.forge.cloudbees.com/release/net/foo'
[info] WebDav: Creating collection 'https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2'
[info] WebDav: Creating collection 'https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2/0.1'
[info] WebDav: Done.
...
[info] published bar_2.9.2 to https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2/0.1/bar_2.9.2-0.1.pom
[info] published bar_2.9.2 to https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2/0.1/bar_2.9.2-0.1.jar
[info] published bar_2.9.2 to https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2/0.1/bar_2.9.2-0.1-sources.jar
[info] published bar_2.9.2 to https://repository-{account}.forge.cloudbees.com/release/net/foo/bar_2.9.2/0.1/bar_2.9.2-0.1-javadoc.jar





