Adding a MogileFS proxy

As noted previously, I’m using MogileFS as the data store for some high(-ish)-performance computing. So far, it does the job without complaints. I haven’t benchmarked it, but I’m not asking that much.

One issue is that it uses its own proprietary access protocol … sortof. A simple Mogile read goes something like:

  1. Computer A decides it wants a file from the Mogile cluster. It contacts one of the trackers using the Mogile protocol. [Computer A needs to know the hostnames of the tracker(s) in advance.]
  2. The tracker has a think, checks the database, and returns the path to the requested file on one of the storage hosts. This path is a normal URL. It passes this URL back to the client.
  3. Computer A uses HTTP to get the file from that URL on the storage host.

The fly in the ointment, of course is that the original client needs to speak Mogile to the tracker. I’m using a hacked version of SeattleRB’s Mogile-client Ruby gem in all of my various programs and clients to access Mogile directly.

One of those programs is a web front-end for browsing the data. When it wants to insert a Mogile asset into a web page (an image, typically), it will contact the tracker, get the storage URL, and insert it directly into the page, so you end up with HTML that contains code like:


<img src="http://my.mogile.storaged:7500/dev1/0/000/405/0000405859.fid">

The problem is that all of my Mogile trackers and storage nodes are behind a firewall (as they should be). When I’m on campus, this works fine, as my desktop can see both the web server and the storage nodes.

When I work off campus, I can use an SSH tunnel to get to the web server, but all of the storage node paths break terribly.

I’d like to add a web proxy, preferably running on the same web server as my web app, which can handle the Mogile requests. Instead of returning raw Mogile URLs, the web app can pass paths to the proxy, the proxy can get the data from Mogile, and send it back as HTTP. As my web app is mostly for browsing, the proxy can even be read-only.

How I did it

As a first attempt, I was more interested in getting a solution running than any sense of performance. As my web app is in Rails 3, I knew I could basically delegate a path to a separate, self-contained Rack server. The Resque control panel does this, for example.

As a sketch, then, I want any path of the form:


http://webserver.com/mogproxy/some/key/something

to return whatever Mogile has stored under the key /some/key/something

The first step was to add a route to the application in routes.rb:

I put my application code at lib/mogproxy/ which resulted in a bit of a search on autoloading files and require paths. The solution I arrived at looked something like this in application.rb

It may be possible to do away with the require through clever use of the autoload path, but I didn’t feel the automatic-ness was really worth it. Note the require has to go at the end after the autoload_path is set.

The application below is written in Sinatra because I’ve used it before and it’s handy. It’s pretty simple — take whatever path comes in and look it up in Mogile. Return the result.

[Yes, I know, my regexp-fu is weak…]

As a side note, the MogileModule::Mogilable and mog bits are code I wrote to make a class (*cough* global) variable Mogile client instance, which can be configured once and used throughout the application.

It’s hardly efficient because it loads the asset from Mogile then spits it back out at the client. And the error checking is basically absent. But it works.

On the other side, I then rewrote my client code to return “/mogproxy/….” paths instead of looking up the mog paths themselves.

A small MSP430 board

I couple of months back I acquired a TI Launchpad, their loss-leader development board for their MSP430 family of microprocessors. I’ve had a long-term interest in the MSP430 as an alternative in the realm of 8-/16- bit micros.

Out of the box, I was able to the set up the mspgcc toolchain, and the other installation details were amalgamated from the interwebs. I believe the msp toolchain is now in the Ubuntu repositories, so all of the compilation la-di-da is a thing of the past.

Sadly, I was without an application.

The next week my coworker asked me where he could find a signal generator — I made the mistake of inquiring and it turned out he needed a 30Hz (later 25Hz) synchronization pulse for a cluster of computer vision cameras. Clearly a signal gen would be massive overkill (and would tie up the generator for months to come), so I offered to make a signal generator for him.

My first version was built on the Launchpad, and worked fine. Last week I finally got around to constructing a self-contained version.



Total time to first prototype was perhaps four hours, though I went through three iterations of the clocks — first using the internal very-low power oscillator (VLO), then the internal digitally-controlled oscillator (DCO), and finally using an external 32.768 kHz watch crystal. Each step was an attempt to find a little bit more timing accuracy.

For the curious, the schematics are here

It’s not the minimum number of components to run an MSP430, but close enough. Nor is it the smallest MSP that would do that job. But the G2211 came with the Launchpad.

The USB port only provides power (it’s convenient and there’s no chance of getting the voltage or polarity wrong). The C connecting reset to ground is recommended, but I’m not sure it’s mandatory. It should provide a little highpass filtering on the reset line. As built there’s no in-circuit programming, hence the socketed processor. It wouldn’t be too hard to add an ISP but I didn’t see the point.

The code is as follows (or here)

/******************************************************************************
 * 25Hz flasher.  Ripped unashamedly from the Launchpad demo app.
 * This version is targeted at the 430G2211 with a watch crystal
 ******************************************************************************/

//#include   <-taken care of by includeing io.h and setting -mmcu=msp430x2012 in cflags
#include 
#include 


#define     LED0                  BIT0
#define     LED1                  BIT6
#define     LED_DIR               P1DIR
#define     LED_OUT               P1OUT

// The Launchpad has two LEDs
// but the app board has just one
#undef      TWO_LEDS

#define     TA_OUT0               BIT2
#define     TA_DIR                P1DIR

void main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT

  TA_DIR |= TA_OUT0;
  P1SEL  |= TA_OUT0;                        // Should set Pin 1.2 to TimerA out1

#ifdef TWO_LEDS
  LED_DIR |= LED0 + LED1;
  LED_OUT &= ~LED1;
#else
  LED_DIR |= LED0;
#endif
  LED_OUT |= LED0;                          // To enable the LED toggling effect
  // Use a 32.768 KHz watch crystal
  BCSCTL1 = XT2OFF;
  BCSCTL2 = SELM_3 | SELS;                   // MCLK = SMCLK = LFXT1CLK
  BCSCTL3 &= ~(LFXT1S_3);                    // Clear LFXT1Sx for 32678 crystal on LFXT1
  BCSCTL3 |= XCAP_3;                      // Set ~12 pF capacitance 

  // As set up, MC_1 means count to CCR0
  // OUTMOD_7 means reset at CCR1, set at CCR0
  // ISR make the LEDs behave similarly -- RED on at CCR1, GREEN on at CCR0
  //
  // Uses toggle mode, OUT1 toggles every time TimerA == TACCR1
  // And TimerA is in Up mode, so it counts 0->TACCR0, then resets
  // So the half-period of the output is set by TACCR0
  //
  // 32768 / 655 = 50.02
  // 
  // So ~655 for 25MHz
  TACCR0 = 655;                             // By calibration
  TACTL = TASSEL_1 |  MC_1;                  // TACLK = SMCLK, Up Mode
  TACCTL0 = CCIE;
  TACCTL1 = OUTMOD_4;                // Toggle mode
  TACCR1 = 0;

  WRITE_SR(GIE);                     // Enable interrupts

  /* Main Application Loop */
  while(1) {
    __bis_SR_register(LPM3_bits + GIE);          // LPM0 with interrupts enabled
    //nop();
  }

}

interrupt(TIMERA0_VECTOR) ta0_isr(void)
{
  static unsigned int count = 0;

  TACCTL0 &= ~CCIFG;

  if( ++count >= 25 ) {
#ifdef TWO_LEDS
    LED_OUT ^= (LED0 | LED1);
#else
    LED_OUT ^= LED0;
#endif
    count = 0;
  }

}

Not the tidiest code in the world. The 25Hz square wave is driven by the TimerA, while the flashing LEDs (the Launchpad board has two blinkenlights, while my board has just one) are driven my a more conventional counter-in-an-ISR. I’m quite sure I could fix it up so the LED is controlled by a timer as well, but I haven’t bothered.

Resistor search in Ruby

Here’s a short snippet I wrote the other day. I think it’s a good illustration of Ruby’s potential for short scripts.

I needed to set the resistor divider to get 5.4V out of an adjustable LDO regulator (a REG102-A). The output voltage is set as:

V_{out} = left( 1 + frac{R1}{R2}right) V_{ref}

For the REG102, V_{ref} = 1.26V, and the bias current was about right if R1 and R2 were both in the order of 1-10K.

On the other hand, I had a big bag of completely unsorted SMD resistors. Somewhere in there was a nice combination that would give me the voltage I wanted.

The script reads a list of resistor values (one per line) from a file (by default ‘r.txt’). The output looks like:

Have these resistors: 0.91, 2.2, 4.7, 6.81, 8.06, 10.0, 11.5, 15.0, 22.0, 24.9, 30.0, 33.0, 35.7, 40.2, 42.2, 47.0, 51.0, 53.6, 56.0, 68.0, 100.0, 215.0, 226.0
Searching for Vtarget = 5.4
R1	R2	vout	error
24.90	8.06	5.15	-0.05
68.00	22.00	5.15	-0.05
6.81	2.20	5.16	-0.04
35.70	11.50	5.17	-0.04
47.00	15.00	5.21	-0.04
215.00	68.00	5.24	-0.03
15.00	4.70	5.28	-0.02
22.00	6.81	5.33	-0.01
33.00	10.00	5.42	+0.00
226.00	68.00	5.45	+0.01
100.00	30.00	5.46	+0.01
51.00	15.00	5.54	+0.03
40.20	11.50	5.66	+0.05

The code loads the resistors from the file, and removes duplicates, then calculates Vout for every permutation. It then deletes any permutations which don’t get within 5% of the desired voltage, and sorts and prints the results.

As a side note, it doesn’t matter than the resistors are given in Kohms (or Ohms, or MOhms, etc) because they’re divided in the script, as long as they’re in the same units.

Yes, it’s non-optimized because it does build an enormous list of possibilities, then throws the vast majority away. Even a simple permutation like not calculating Vout if R2 > R1 would eliminate many possible pairings.

But, there you go.

#!/usr/bin/env ruby

TARGETV = 5.4

filename = ARGV.pop || "r.txt"
r = ($File.open( filename ) { |f| f.readlines.map { |l| l.to_f } }).sort.uniq

puts "Have these resistors: " + r.join(', ')
puts "Searching for Vtarget = #{TARGETV}"

vals =  r.permutation(2).map { |res|
  vout = 1.26 * (1 + res[0]/res[1])
  error = (vout-TARGETV)/TARGETV 
  res+[vout, error]
}.delete_if { |res| (res[3]).abs > 0.05
}.sort { |a,b| a[2] <=> b[2] }


puts %w( R1 R2 vout error ).join("t")
vals.each { |v|
  puts "%.2ft%.2ft%.2ft%+.2f" % v
}

Disabling shutdown when the power button is pressed

I run a pretty sparse Linux installation on my desktop. It’s based on Xubuntu 11.04 (right now), but typically I use musca in preference to the full xfce4 experience.

By default, if no other power management software (like xfce4-power-manager) is running, pressing the power button will initiate a machine shutdown. I turn my desktop off most evenings, but when I do leave it on, I’d always stumble in the next morning, stab the power button … and watch it shutdown.

Here’s the quick fix. When the power button is pressed, acpid loads the event at /etc/acpi/events/powerbtn. By default this calls the script /etc/acpi/powerbtn.sh.

This script checks to see if any power management programs (again, gnome-power-manager, kpowersave, xfce4-power-manager, etc) are running. If they are, it just exits. If not, it gets to the last line:

# If all else failed, just initiate a plain shutdown.
/sbin/shutdown -h now "Power button pressed"

Well there’s the problem. I commented out the shutdown, reloaded acpid (this probably isn’t necessary), and away I went.

Allowing Ruby Benchmark reports to return values

I’ve recently started using Benchmark to record basic timings. It’s hardly profiling, more just a running record of where the time goes.

One annoyance (for me) was that Benchmark::report returns timing information, not the return value from the block being benchmarked. This means adding benchmarking to a function like:

def a_function
  a = an_expensive_function
  b = another_expensive_function
  c = a_third_function(a,b)
  puts c
end

Requires pre-defining a,b,c outside of the report blocks … otherwise they get scoped out:

require 'benchmark'

def a_function
  Benchmark.bm do |bm|
    a = b = c = nil

    bm.report("A") { a = an_expensive_function }
    bm.report("B") { b = another_expensive_function }
    bm.report("C") { c = a_third_function(a,b) }
    puts c
  end
end

which is an annoyance.

I’ve redefined Benchmark::report as:

module Benchmark
  class Report
    def report( label="", *format, &blk )
      retval = nil
      item( label, format ) { retval = blk.yield }
      retval
    end
  end
end

Which lets you do the (slightly more intuitive):

def a_function
  Benchmark.bm do |bm|
    a = bm.report("A") { an_expensive_function }
    b = bm.report("B") { another_expensive_function }
    c = bm.report("C") { a_third_function(a,b) }
    puts c
  end
end

Reconsidering my foolishness

I took a few minutes to try option B on this serial-to-network problem.

Here’s a much simpler option.

On the Ministation, run a script like (this is the lightly tarted up version):

#!/bin/sh

PORT=/dev/ttyACM0
SERVER=localhost
SERVER_PORT=1234

stty -F $PORT 57600

while [ true ];
do
cat $PORT | nc $SERVER $SERVER_PORT
sleep 1
done

The client netcat (nc) will die if it can’t connect to the server, hence the while loop. The sleep prevents flapping in that case. [Though as I discovered below, this only works as long as bits are coming into the serial port…]

And on the other end:

#!/bin/sh

PORT=1234
OFILE=/tmp/ofile.txt

nc -kl $PORT >> $OFILE

Time to try it out, I think…

Update:

Here’s an even more tarted up version which lets you send data back out the serial port by poking it to the server through a FIFO.

Client:

#!/bin/sh

PORT=/dev/ttyUSB0
SERVER=localhost
SERVER_PORT=1234

stty -F $PORT 57600

while [ true ];
do
cat $PORT | nc $SERVER $SERVER_PORT > $PORT
sleep 1
done

Server:

#!/bin/sh

PORT=1234
OFILE=/tmp/ofile.txt
OUTFIFO=/tmp/foofifo

if [ ! -p $OUTFIFO ]
then
mkfifo $OUTFIFO
fi
tail -f $OUTFIFO | nc -kl $PORT >> $OFILE

This seems pretty robust to most combinations of server or client problems except if the client can’t reach the server and there’s no data coming in the serial port. The client’s nc will die but the associated cat won’t die till it tries to write to the broken pipe.

Does this matter? Yes. If the client starts and can’t connect to the server, the nc will die, and if the widget is mis-configured to not output any data on the serial port, the (FIFO)->(server’s nc)->(client’s nc)->(serial port) redirection won’t work because the client’s nc is dead, but because the cat is still running, the while(1) won’t cycle. There’s probably a clever way around this, but I’ve definitely reached the limits of my shell scripting abilities.

Of course, if you have a network connection you could always SSH to the client and poke the serial port manually.

Ah, and these scripts will require old-skool logfile rotation:

cp ofile.txt ofile.txt.2 && cat /dev/null > ofile.txt

I assume logrotate can handle that elegantly.

2nd side-note. The Ministation SDK doesn’t build busybox’s stty by default. You’ll probably want that for setting the baud rate on the serial port. It’s easily added by changing the relevant line in conf/xs2/busybox.config to:

CONFIG_STTY=y

ser2syslog

For the weather buoy project we need a way to take data in over our Ministation’s serial port and push it upstream over the network. As the ministation is pretty limited in flash and ram, I assumed a compiled (as opposed to scripted) solution would be best.

I think my ideal system would be store-and-forward, with the serial port as a “push,” something along the lines of:

  1. Open the serial port.
  2. Forever:
    1. Read an buffer the data.
    2. When you have one “line” of data, try to poke it out over a network interface.
    3. If you succeed, forget that line of data.
    4. If you fail, save it to try next time. When you reach some maximum amount of backlog, start dropping the older messages.

Where the other end of the conversation would be a network-to-disk server:

  1. Open a network port
  2. As data comes in, write it to a file.

It sounds like a simple brief, but I couldn’t find a canned solution which does the job.

One obvious choice is ser2net, though it’s actually designed the other way around. As a “server,” it listens on a network connection (many, actually), opening serial ports as necessary when a connection comes in.

I’m a bit rusty on Linux network programming, so as an interim, I thought I’d try a serial-to-syslog gateway, operating as above but pushing data to syslog (who can then handle the network forwarding).

It’s not a terrible solution, with a couple of caveats:

  • It only really works because our data is read-only, and it’s NMEA-like strings, so it’s ASCII, nicely delimited into lines. Syslog wouldn’t work with binary data, I don’t think.
  • The Ministation SDK runs busybox’s syslogd, which only supports UDP forwarding, not TCP. OK, so it would only provide one additional ACK of security, not true store and forward, but it’s would be a start.

On the other end of the connection, I’ll have a full-fat computer running rsyslogd which can handle a bit of store and forward to servers off in the cloud.

In any case, I wrote a ser2syslog. I won’t pretend it’s polished, but works for me. As per the README, I was originally going to build it from the framework of ser2net, but given ser2net is a mature, featureful product, and arranged backwards (as above), I stripped 95% of the ser2net code out. I believe (hope!) the copyright and attribution are correct.

Next up is testing it on a Ministation.

Update:

Hm. I just realized I could do the same thing very simply on the command line. Something like:

$ cat /dev/ttyS0 | logger -p local7.info -t “/dev/ttyS0”

And I could probably achieve what I need network-wise with netcat. Sigh….

PhD Proposal

As part of my studies, I’m required to submit a research proposal at about 6 months into my program. I did that long ago, then subsequently binned that topic.

Since January, I’ve been working on a new proposal, which I’ve posted here.

I’ll fully admit it’s too vague, and too long. But it’s also submitted and out of my hair.

Building custom Ubiquiti firmwares

As noted previously, I’m mucking about with a Ubiquiti Ministation2 as a networked SBC for a project. The Ministation2 is Linux-based, and Ubiquiti provide an SDK for rolling your own firmware. I wanted a mechanism for introducing my own customizations while also keeping the tarball downloads from Ubiquiti at arms length.

After a bit of iteration, I ended up with the a project I’ve posted at Github. It’s a kind of reverse-patch-and-overlay environment, and no, I’m not a shell and Makefile genius, so I accept there’s lots of room for improvement.

Basically, you check out the the Remix,

$ git clone git://github.com/amarburg/Ubiquiti-SDK-Remix.git

then:

$ cd Ubiquiti-SDK-Remix
$ ./bootstrap.sh

This will download the SDK from Ubiquiti (the version is currently hardcoded in bootstrap.sh), expand it on top of itself, and patch the SDK’s files as appropriate. You end up with a hybrid of the original SDK with the Remix’s improvements.

The Remix won’t check that you have the relevant tools, so make sure you’ve installed the MIPS toolchain and other dependencies. Then:

$ make clean xs2

as before.

The remix currently includes just one new package — ser2net-2.7 (it builds, but totally untested on the Ministation), but it provides a good template for how to include other packages in apps/local/.

Custom firmware on the Ubiquiti Ministation


We’re using a Ubiquiti Ministation as wifi-enabled SBC for a weather station project. There’s a lot to like, and a few things lacking. It has a single 802.11b/g interface, a single ethernet port, and a single console/serial port. Like? Most everything. Dislike? The single serial port, as we want to use it as a serial-to-network gateway, which means sacrificing the console. It also runs a custom Linux installation, which we can hack it to our devious needs.

Instructions for rebuilding the system are out there, but pretty brief. Here’s my experiences.

Ubiquiti provide the SDK as a tarball, as well as a MIPS toolchain as a i386 deb. That’s fine with me as I’m running Ubuntu, though sadly I’m running 64-bit, so I built up a small VirtualBox machine for development. Not optimal, but nothing wrong with it. It’s noted here that you could also build the MIPS compiler with buildroot. your mileage may vary.

So:

  1. Download the SDK and toolchain from here, selecting the Ministation2 as the model. As of right now, the current firmware is v3.6.1.
  2. Install the toolchain on a i386 Debian/Ubuntu system.
  3. You’ll also need a few other packages. I got this list from here, so I can’t verify it’s correctness.

    $ sudo apt-get install sharutils fakeroot zlib1g-dev patch lzma flex bison

    If a package is missing, you’ll notice pretty quickly when the compile blows up.

  4. Unpack the SDK someplace convenient:

    $ mkdir ministation
    $ cd ministation
    $ tar -xjvf ~/SDK.UBNT.v3.6.1.4873.tar.bz2
    $ cd SDK.UBNT.v3.6.1.4873

First, let’s see how the SDK works out of the box. Note, I already have my ministation up, running, and configured properly. So what happens when I “upgrade” my ministation with a filesystem I’ve built myself.

First, build it:

$ make xs2

And go get a refreshing drink.

The resulting package will end up in a directory with a name like rootfs/XS2.ar2316.v3.6.1.unknown.110707.1210 which gives the Ubiquiti model (XS2), the chip (ar2316), version number (v3.6.1) and a date/timestamp (110707.1210). The unkown is where Ubiquiti puts a patch number (like 4873 in this case), not sure why that doesn’t make it through.

Conveniently, they also symlink in rootfs/XS2.ar2316.v3.6.1.latest which points to the latest build.

In that directory are a number of intermediate results, as well as a few .bin packages:

$ ls -al
total 38976
drwxr-xr-x 2 aaron aaron 4096 2011-07-14 16:17 .
drwxr-xr-x 14 aaron aaron 4096 2011-07-14 16:22 ..
-rw-r–r– 1 aaron aaron 678439 2011-07-14 16:17 bzImage
-rwxr-xr-x 1 aaron aaron 2605056 2011-07-14 16:17 squashfs.bin
-rwxr-xr-x 1 aaron aaron 493554 2011-07-14 16:17 vmlinux.lzma
-rwxr-xr-x 1 aaron aaron 25055859 2011-07-14 16:17 vmlinux.notstripped
-rw-r–r– 1 aaron aaron 3099018 2011-07-14 16:17 XS2.ar2316.v3.6.1.unknown.110714.1614-8M.bin
-rw-r–r– 1 aaron aaron 3099018 2011-07-14 16:17 XS2.ar2316.v3.6.1.unknown.110714.1614.bin
-rw-r–r– 1 aaron aaron 4858567 2011-07-14 16:17 XS2.ar2316.v3.6.1.unknown.110714.1614.debug_binaries.notstripped.tgz

Comparing XS2.ar2316.v3.6.1.unknown.110714.1614.bin to the “stock” Ubiquiti filesystem:

$ ls -l
total 9856
-rw-r–r– 1 amarburg amarburg 3244841 2011-07-19 10:50 MiniStation2-v3.6.1.build4866.bin

my version is a bit smaller. Hmm. Well, never mind.

Install the new version of the s/w through the the web interace. Luckily, the Ministation warns me I’m about to break things:



Well, let’s go. I monitored the process on the serial console (which is a separate topic).

Writing ‘FIS directory ‘ to /dev/mtd4(FIS directory ) … [[1300398.770000] Restarting system.
+Ethernet eth0: MAC address 00:15:6d:a4:14:ed
IP: 0.0.0.0/255.255.255.0, Gateway: 0.0.0.0
Default server: 0.0.0.0

RedBoot(tm) bootstrap and debug environment [ROMRAM]
Ubiquiti Networks certified release, version 0.9.00483.1103151313 – built 13:14:44, Mar 15 2011

Copyright (C) 2000, 2001, 2002, 2003, 2004 Red Hat, Inc.

Board: Ubiquiti Ubiquiti AR2315/6/7/8 based board (Ubiquiti PicoStation2 detected)

Arch: ar2316
RAM: 0x80000000-0x82000000, [0x80040b80-0x80fe1000] available
Flash: 0xbfc00000-0xbfff0000, in 64 blocks of 0x00010000 bytes each
== Executing boot script in 1.000 seconds – enter ^C to abort
RedBoot> cache off
RedBoot> fis load -d -e kernel
Trying LZMA decompression…
Image loaded from 0x80041000-0x801df23c
Entry point: 0x80196040, address range: 0x80042000-0x801bf000
RedBoot> go
[ 0.000000] CPU revision is: 00019064
[ 0.000000] Primary instruction cache 16kB, physically tagged, 4-way, linesize 16 bytes.
[ 0.000000] Primary data cache 16kB 4-way, linesize 16 bytes.
[ 0.000000] Linux version 2.4.27-ubnt0 (aaron@moa) (gcc version 3.3.3) #2 Tue Jul 19 10:55:22 NZST 2011

Much to my surprise, it worked. And, much to my surprise, my configuration has been maintained. Sweet.