Making a time-lapse in Debian

Make a script like this called “save”. Make it executable.

#!/bin/sh

ct=0
if [ -f "ct" ]; then
ct=`cat ct`
fi

ct=`expr $ct + 1`

mv snap.jpg snap-$ct.jpg
echo $ct > ct

Run “uvccapture -x648 -y480 -c./save -t20″ to take a photo every 20 seconds.

Then you can use a script like this to continually re-encode it and send it to your webserver:
#!/bin/sh

while true
do
rm out.mpg
cat snap-*.jpg | ./ffmpeg -f image2pipe -r 1 -r 20 -vcodec mjpeg -i - out.mpg
scp out.mpg jeff_allen@nella.org:nella.org/jra/geek/3d
done

You can get ffmpeg from here, and not deal with all the problems of library compatibility, if “apt-get install ffmpeg” doesn’t just work.

What I want: a Chrome plugin to report spelling errors

Here’s what I want to do:

  1. See an error on a web page
  2. Select it and right click
  3. In the popup, choose “report a spelling error”.
  4. Have a box come up with three fields and a pair of ok/cancel buttons. The three fields are
    “change from”, “change to”, and Twitter id. The “change from” and Twitter id are auto-populated. The “change to” could be auto-populated using a web service that suggests spelling corrections.

When I click on “OK”, it sends a Tweet announcing to the world that:

  1. The author can’t be bothered to spell check.
  2. I’m a pedant who likes publicly shaming people.

I’m OK with that.

I have the context menu working, and it can get the selected text. I’m not very interested in figuring out the Twitter-auto-guessing. Seems like a good first step would be to look for Twitter Cards, for example on the Gigaom site that finally annoyed me enough to look into this, I found:

<meta name="twitter:site" value="@structureblog"/>
<meta name="twitter:creator" value="@gigastacey"/>

Double take

The nicest thing happened to me on the way home from work… I got one of those movie-perfect double takes from a guy I passed.

Of course, it was probably due to the pretty rainbow umbrella I was carrying, while cruising along on my unicycle. Years ago I realized that if it’s a grey rainy day it is nice to have bright colours overhead. Black umbrellas should be outlawed!

A Dinosaur Story

Once upon a time, long ago, long long ago… no… long long long ago, lived two dinosaurs. They had a wonderful life to themselves, since they came after the plants but before the humans. They had a land full of plants with no humans to bug them. They had clouds and rainbows and rivers and waterfalls. And they had plants. Lots of plants.

Which was a good thing, because Bobby the Brontosaurus loved eating plants. He ate like this: “omm nom nom” and he even ate while he talked like this. (Add omm nom nom’s into your talking. If your kid laughs, your doing it right. Then again, if he laughs he won’t go to sleep, so you might not be doing it right afterall.)

Bobby the Brontosaurus didn’t have any friends because all he did all day was eat plants. He liked it that way. He said “I have all the plants I need and I love eating them.” (Mix in lots of omm nom nom’s in there.) But Ptommy the Pteradactyl didn’t agree. He thought it would be nice to have a friend. Ptommy could fly far above the valley and look at the rainbows and clouds and waterfalls and plants. He wanted to talk about them with Bobby, but all Bobby was interested in was his plants. Bobby never even looked up at Ptommy, he just kept eating and eating. But if Bobby never looked up, how would Ptommy ever get Bobby to see the wonderful things?

One day, Ptommy discovered a place where the pants grew right up to the edge of a cliff, which dropped away, and below were waterfalls and rainbows and clouds. He told Bobby he’d help him find more plants to eat. Bobby liked that plan, and so Ptommy said “eat over to the left a bit”. Then Ptommy said, “eat up ahead a bit”. Every time Ptommy gave Bobby a direction to eat, Bobby found good stuff, and Bobby started to realize having a friend wasn’t so bad afterall. But Ptommy was laughing to himself all the time, because he was leading Bobby where he wanted him to go! And finally, Ptommy said, “eat that nice bush there in front of you”. Bobby did, gladly, (omm nom nom) and then he was shocked, because now he could see out over the cliff. For the first time ever, Bobby the Brontosaurus saw clouds and rainbows and waterfalls and mountains.

He stopped eating (he’d never done that before!). He looked left and right. He looked again. He was amazed.

“Ptommy,” said Bobby, “that’s really pretty.” (no omm nom nom’s here!) “But do you think you could tell me where to find more plants?”

Prommy rolled his eyes. “Sure thing, buddy. Just eat a little bit more to your right…” said Ptommy, smiling.

This story is based loosely on On Top, by Marilyn MacGregor.

Sugru

I had a great first Sugru experience! I scratched my finger on the way to work on my unicycle. I thought, dammit, I’m gonna fix that! So I bought some from my phone on the train. Cool!

A few days later, it arrived in the post. I was having a hard time explaining why I was so excited about it to my wife. So I sat down, cut open my first packet and started fixing. My wife got interested, fast! She asked, would this stick to the door handle to make a bumper? I said, go try! And off she ran with my Sugru, leaving me grinning and cutting open a new packet…

Thanks, Sugru, for our new door bumper and unicycle seat bolt covers! You made two new happy fixers.

Correction: Three new fixers, including Elio, age 2 and a half:

Two more stories

Here’s two stories that worked their charm on a not-very-sleepy little boy, turning him into a sleepy one.

Bep and the Giant Pumpkin: It is October, the official start of pumpkin season in our house. That means it is time to start talking about pumpkins and where we get them. So mommy, daddy, Elio and Emma got in Bep and went for a drive. They drove up up up to the top of Lausanne and then up up up to Mont sur Lausanne, then up up up more to the little self-service vegetable stand above it. Everyone went in and chose their pumpkins one by one. Emma got a little pumpkin because she needed to hold it between her feet in her maxi-cosi. Elio got a bigger pumpkin because he’s strong (Elio e forte!). Mami chose a good pumpkin for soup because she makes the best pumpkin soup. And daddy chose one to make a yummy pumpkin curry. Daddy was about to pay and go, but Elio asked, “What about Bep?” So they looked but none of the pumpkins were big enough for Bep. They went out back and found a perfect pumpkin, 1 meter across, 3.14 meters around and weighing 200 kg! They went to get Bep and asked, “can you carry it?” Bep said “beep beep vroom vroom, no problem” and drove the whole family home, each with their pumpkin on their lap (except mami, who was driving) and Bep with his pumpkin right in the middle.

The Little Red Robot: Once upon a time, there was a little red robot. (Elio was wearing his red robot pj’s.) This little red robot could do everything the master programmer taught him. He could dress himself, go poo poo, feed himself, read books, etc etc. He even knew how to initiate the food processing unit decontamination procedure (teeth brushing) and the light delumination protocol (turning off the bathroom light by head butting it). But each night, when the little red robot went into sleep mode, something magical happened. He got to do things he never did in the day. He ran programs for flying on clouds, climbing in trees, (around this point Elio interrupted and asked that the story should include a “motoschlitta”: snowmobile), and ride lunar snowmobiles across the moon through craters and over the horizon, far from the robot base. That night, the little red robot ran the snow mobile program in his processing unit all night. In the morning when he woke up, he went to Central Dispatch and found that his job that day was to go drive lunar snowmobiles for real! And so he did.

Once upon a time…

My son now needs a bedtime story, whispered in the dark, to go to sleep. My wife and I both love good story telling. She even took a course on it once, and told a story to an audience as the final project. We go to le Nuit des Contes every year here in Lausanne, and I’ve picked up some tips from watching the (literally) professionals there. A key to oral story telling, certainly for small children, is to use a structure with repeating sounds and phrases that they can get wrapped up in.

In order to have these some day to look back at, I’m going to start writing down summaries of stories I tell. If one is good enough to develop and retell, perhaps one day I’ll tell it at the Nuit des contes!

Our 1974 VW Type 2 camper van (“Bep” is his name) would be the star of every story if Elio got to choose. Instead, we offer him a choice of three characters and then go from there. The key, I find, is to start slowly, describing the character, throwing in some fun details right away. This gives you time to race ahead in your mind and choose a rough storyline. The easiest is to choose the end state first, so you know where you are trying to get to. Then, like a dot to dot painting, you need to fill in a few intermediate hops along the way. These are attempts the character makes at achieving the goal, or increasingly dire straights the character finds himself in. These stretch out the story, but more importantly, give it a verse/chorus/verse/chorus/verse structure, which is where the real magic comes from. And the rhythm necessary to put a fidgety 2-year old kid to sleep, as well, which is the point afterall!

What do I mean by verse/chorus? The chorus is the catch-phrase, the repeated element that signals another loop around. It gives the story rhythm and momentum. The verses carry the story forward, so that you get to where you are trying to go and you get that nice satisfying conclusion.

So here are several stories that I’ve told so far:

  • Bep and the Doubting Family: A story from real life, about a little camper that joined a new family and though it had been crossing the passes of Switzerland all its life, the mom and dad were worried it couldn’t do it (a family version of the Little Engine that Could). For each pass: Daddy said, “I don’t know if he can make it”, and Mommy said, “I’m afraid he can’t make it!”, and Elio said, “Go Bep, Go!”, and Bep said, “beep beep, vroom vroom, I know I can make it… I know I can make it… I knew I could make it!”.
  • Bep and the Big Campers: Big campers at a campground are making fun of Bep (“He’s only got 4 cylinders!”, “No fuel injection!”, “He doesn’t even run on diesel!”, “He’s got no toilet!”, “His exhaust stinks: che sputzza di benzina!”). Bep says he’s as good as other campers, but they demand proof. He names all the passes he’s done, and the bigger campers say, “Wait, they let you do that pass? I’m not allowed on it because I’m too big!”. The Dutch camper says, “My owners drive me all night long on the autoroute here, and go through all the tunnels to save time!”. The big-ass bus starts crying because he’ll never get to see Passo del Lucomagno because he’s too long. Bep makes him feel better by reminding him that he can drive all night from Barcelona and his owners don’t even have to go pee at the gas station. All the campers are friends after that.
  • Bunny and the Giant Carrot. A little bunny tells her mom that she loves carrots. She loves them so much she wants to grow up and be a farmer and grow carrots. She’ll sell them all around the forest. She’ll sell them by the big rock, and past the oak tree, etc, etc, etc. (This was inspired by Elio’s cousin, who told us this summer of a plan to be a farmer and sell his produce all around Switzerland in order to get out and see the country. Good plan, if you ask me!) She tells her mother the same thing every night, each night adding one more place she’ll sell her carrots, and naming all the others. One night, her mother reminds her that tomorrow is a special day, her birthday. She receives a single carrot seed, but it’s magic. The next morning, she has a regular carrot in her plot. But her mom convinces her to wait another night (and another and another, as many as it takes to make your fidgity 2 year old tired). Then it goes to seed and gives her all the seeds she’ll need to achieve her dream of being a carrot farmer.
  • Bep and the Apple. On a long trip, the daddy stops the car at a fruit stand. (Based on real life, and my fond memories of driving from San Francisco to Arnold as a child). He buys an apple for everyone (mommy, daddy, Elio and Emma). Each person crunches their apple, except Emma who coos because she knows she’ll get her apple cooked for snacktime later. Bep complains that he didn’t get an apple, and daddy explains to Bep that he can’t eat them, Bep eats gas. But daddy promises to make it up to Bep by getting him an apple anyway. Bep goes su, su, su! the pass, turning left and right and left and right and a moto goes by and goes zoom! (Repeat for as many switchbacks and/or passes as necessary until kidlet is cuddling and knodding off.) Bep is running out of gas and worried that daddy won’t fill him in time. But just when he’s sure he can’t go another kilometer, around the corner comes a giant sign with an apple on top. It’s Apple Gas, where Bep gets his gas, just as daddy promised!
  • The Lonely King. The king of a country with one citizen (the king himself) is lonely. On the plus side, all his subjects follow his orders, but having more people to play with would be nice. So he tries everything he can think of to get more citizens. He plants flowers on his castle, but the tourists just take pictures. He makes a decree that all the women of the kingdom (i.e. zero) must marry him, but that doesn’t work because there are none and because women don’t like to be told what to do like that anyway. He tries giving away cookies, but he runs out and no one moves in anyway. One day, a nice lady goes out picking mushrooms. She goes up up up the mountain until she finds herself in the kingdom. She asks the king if he’d like to look for mushrooms with her, and they laugh and have fun until sunset. She comes back for more mushrooms, day after day. After two weeks, the are in love. After two months, they are married. After two years, they have a family. And when the king and his queen had a happy family in the kingdom, other people came to join the happy kingdom and the king was no longer lonely (though he was likely exhausted from staying up late into the night telling stories to his kids).

Zero Downtime upgrades of TCP servers in Go

A recent post on the golang-nuts mailing list mentioned that Nginx can upgrade on the fly without ever stopping listening to it’s listen socket. The trick is to unset close-on-exec on the listen socket, then fork/exec a new copy of the server (on the upgraded binary) with an argument to tell it to use the inherited file descriptor instead of calling socket() and listen(s).

I wanted to see if I could achieve the same thing with Go, and what changes would be necessary to the standard libraries to make this possible. I got it working, without changing the standard library, so I wanted to explain what I did here.

The code for this post is here.

There are several interesting things I’d like to point out in this program. Twice, I used the pattern of “implement an interface in order to intercept method calls”. This is an important pattern in Go that I don’t think is widely understood and documented.

When I started thinking about this job I knew one of my problems would be to dig down inside of http.(*Server).Serve in order to get it to stop calling Accept() when the old server should shutdown gracefully. The problem is that there’s no hooks in there; the only way out of the loop (“accept, start go routine to process, do it again”) is for Accept to return an error. But if you think of Accept as a system call, you might think, “I can’t get in there and inject an error”. But Accept() is not a system call: it’s a method in the interface net.Listener. Which means that if you make your own object which satisfies net.Listener, you can pass that in to http.(*Server).Serve and do what you want in Accept().

The first time I read about embedding types in structures I got lost and confused. And when I tried it, I had pointers in the mix and I had lots of unexplained nil pointer errors. This time, I read it again and it made sense. Type embedding is essential when you want to interpose one of the methods of an interface. It lets you inherit all the implementations of the underlying object except for the one that you redefine. Take a look at stoppableListener in upgradable.go. The net.Listener interface requires three methods including Accept, Close, and Addr. But I only defined one of those, Accept(). How is it that stoppableListener still implements net.Listener? Because the other two methods “show through” from where they were embedded in it. Only Accept() has a more precise definition. When I wrote Accept(), then I needed to figure out how to talk to the underlying object, in order to pass on the Accept() call. The trick here is to understand that embedding a type creates a new field in your structure with the unqualified name of the type. So I can refer to the net.Listener inside of stoppableListener sl as sl.Listener, and I can call the underlying Accept() as sl.Listener.Accept().

Next I started wondering how to handle the “stopped” error code from Serve(). Immediately exiting with os.Exit(0) isn’t right, because there can still be go routines servicing HTTP clients. We need some way to know when each client is done. Interposition to the rescue again, since we can wrap up the net.Conn returned by Accept() and use it to decrement a count of the number of currently running connections. This technique of interposing the net.Conn object could have other interesting uses. For example, by trapping the Read() or Write() calls, you could enforce rate limiting on the connection, without needing the protocol implementation to know anything about it. You could even do other zany things like implement opportunistic encryption, again without the protocol knowing it was happening.

Once I knew that I would be able to stop my server gracefully, I needed to figure out how to start the new one on the correct file descriptor. Rog Peppe pointed me to the net.FileListener object, which one can construct from an *os.File (which you can make from a raw file descriptor in an int using os.NewFile).

The final problem is that net always sets the close-on-exec flag on file descriptors for sockets it opens. So I needed to turn that off on the listen socket, so that the file descriptor would still be valid in the new process. Unfortunately syscall.CloseOnExec does not take a boolean to tell it what you want (do close or don’t close). So instead, I pulled out the stuff from syscall that I needed and put it directly in upgradable.go. Not pretty, but nicer than hacking the standard library. (This is a nice thing about Go: there’s almost always a way to do what you want, even if you have to hack around just a bit.)

I tested that it works manually (using command-line GETs from another window). I also tested it under load using http_load. It is really cool to be able to set up a load test for 20 seconds and get 3937 fetches/sec, then do the test again, adding in a few “GET http://localhost:8000/upgrade” from another window and still getting 3880 fetches/sec, even as I replaced the running binary a few times during the load test!