Some Bits: Nelson's log

24 posts in January 2012

Energy usage notes

My electricity bill is just terrible now, $500 / month. Since we moved in we’re using 800-1200 kWh / month, or about 1400W average usage all day every day. We’re both home all day and use computers, so I expect our power usage to be high, but that’s absurd. Where’s it going?

Now that we have a Smart Meter, PG&E has an awesome “My Energy” site where you can see hourly energy usage for your house, per day. Here’s a typical day, Tuesday January 24, 2012. We tend to be awake from 7am to 10pm. (I also have a private graph for the whole month.)

Looking at this, it’s clear turning the lights on in the morning and at night has a big impact. Our house has terrible lighting design, a lot of light wasted in ceiling cans. Also still all incandescent bulbs, although on fancy dimmers that should lower power usage.

What really surprises me is the constant usage of 700W all the time, even when we’re asleep. We turn the lights out at night! And sometimes it’s worse, up to 1000W. Fixing that nighttime usage seems like a good place to start.

Here’s a quick audit of things I know take constant power.

  • 150W Wine cooler (450W when active)
  • 50W Refrigerator (average)
  • 120W My computer (when in use)
  • 200W Ken’s computer (constant)
  • 50W Linux server (constant)
  • 80W A/V rack (when idle)

That’s 650W right there, all the time. We can easily turn off my computer and Ken’s computer, that’d cut about 300W out of the wasteage. My computer already goes down to 30W when idle but I can make that 1W. Ken’s computer is awful; it never goes to low power mode and the monitors constantly wake up in the middle of the night. I don’t know why, it’s a Windows 7 box.

I just unplugged the wine cooler. It’s really not necessary in winter. It’s insane that it runs one third of the time even when it’s cool outside; the manual says something about maintaining humidity. Paying $40 / month to keep my wine at 54F instead of 65F seems stupid. It may be more power than that, btw, the Kill-a-Watt registers 450W but 750VA. The website says it draws 6 amps when running, which is more like 660 kWh/hour, yes?

It’d be nice to shut down the A/V rack. But the Tivo is actively doing something useful, and that’s half the power. The other half is keeping a bunch of Sonos units running at 5W each. Probably not worth the bother to buy a timer or something.

Other ideas

It’d be awfully nice to get the usage data in real time off my meter and not have to wait 2 days for it to show up on the website. The buzzword for this is “Home Area Network” and PG&E, of course, is slow to deploy. No doubt in part because they have to worry about the insane people with imaginary diseases. Anyway, here’s some info on a HAN trial.

It’d be nice to install a solar panel on my roof. SF Solar Map estimates I have 1300 sq ft of space for panels which is good for 5kW. At 4.5 hours of sunlight / day that’s 6324 kWH / year, or about half my electricity usage for the year. A 5kW system costs $32,000, but after incentives the cost to me is $21,000. It’d save me about $2600 / year so I’d break even in roughly 8 years. A 2kW system would cost $7400 and break even in about 7 years. (Cost estimate assume $6.50 / W-dc, which may be optimistic.)

Surround sound formats

Theory

All this TV setup makes me curious; am I getting proper surround sound? I have 5.1 speakers connected to a Denon AVR-2309CI and everything HDMI, is it actually working?

The Denon receiver can decode the following formats via HDMI. I barely know what most of these are, but here’s a useful reference, also wikipedia.

  • 2 channel linear PCM (16, 20, or 24  bit samples, 32-192 kHz), also multi-channel.
  • Dolby Digital (5.1), DD Plus (7.1), Dolby TrueHD (7.1 high quality). Also known as AC3.
  • DTS (5.1) and DTS-HD (7.1)

When playing back a 2 channel audio source, my Denon supports a bunch of playback modes to fake out surround sound (“matrixed”). I believe the sound has to have been mixed this way for this to actually work.

  • Dolby Pro Logic II (fake 5ch) and IIx (fake 7.1)
  • DTS Neo:6 (fake 6.1) and “Neural” (XM HD Surround)

Looking at the random video files I have on my hard drive, most have audio in MP3 2.0 or AAC 2.0. One is DTS 5.1 and a couple are Dolby Digital 5.1. I don’t think there’s any way to tell if any of those 2.0 files are matrix encoded fake surround, probably not.

Playback

That’s all the theory, what happens in practice?

The good news is my new AppleTV seems to correctly play back 5.1 sources, via both Netflix and PLEX. In particular the receiver seems to autodetect DTS or Dolby Digital and if I stand next to a rear speaker it does sound differentiated. Yay! It may help I told PLEX my receiver can decode AC3 (aka Dolby Digital).

The confusing news is for all these stereo sources I don’t really know what receiver setting is best to use. I have no idea how common this matrixed audio stuff is or whether it’s worth the effort to decode it. I’ve got a button on my remote labelled “Movie Sound” that cycles the various matrix modes but can’t really hear much difference in a quick test.

Testing

After a bit of looking I found a test suite, the charmingly named “AC3 Dolby digital 5 1ch Sound Test”. It’s available around the net in various places, like filestube. (Or watch it in 2.0 on Youtube.)

This file plays back fine via PLEX on my Apple TV. I also played with using Handbrake to encode it in various ways. Sounds great in true Dolby Digital 5.1. Also sounded surprisingly good in matrixed Dolby PLII; the rear channel separation worked well, although the subwoofer was silent. HandBrake also supports a “6-channel discrete” mode which didn’t really work right on my A/V system.

TV remote success

My A/V rack is controlled by a UniversalRemote MX 900 with a Univeral MRF-350 RF Base Station. It’s not going to win any UI awards but when we were shopping for this stuff three years ago this came in as the most capable and flexible system. So sad the A/V guy I hired to set it up, money well spent: he did an excellent job. My whole system is controlled from a single remote that’s not awful to use.

And as of today, now the new Apple TV is, too. I reprogrammed the remote myself. It turned out to be relatively easy..

  1. Get a copy of the programming software MX_900Setup.zip (23,290,684 bytes); the official source requires a password they only give to resellers.
  2. Run it on a windows box and plug the remote in via Mini-USB
  3. Select “Communication / Upload” to get a copy of the current remote configuration from the remote itself.
  4. Save that file away for safekeeping.
  5. Edit. The manual is essential because the paradigm is weird. Most things are driven by the Program menu. Macros are recorded by clicking simulated remote buttons on the emulator. Codes can be imported via a database, and there’s a learning mode I fortunately didn’t have to use.
  6. Download back to remote. Done!

The hardest part turned out to be digging through boxes to find a spare IR emitter on a cable. The IR Blaster in the front of my base station didn’t seem to be enabled, probably to help prevent crosstalk. It’s 2012 and we still use infrared and little cables to control A/V devices, it’s terrible.

 

Linux options for faster disk access

All these new computers have me interested in improving throughput. I’ve suddenly got gigabit ethernet, a huge amount of RAM, fast CPUs with many cores.. What’s missing is fast I/O. The hard drive’s 30 megabyte/second throughput is often a limiting factor for me. What are my options?

  • Put my data on an SSD. Appealing, but I don’t trust consumer SSDs not to fail. Also I hate having multiple disks with different capacity; I can never decide what to put on the SSD, what to put on platters. IE: right now I’m doing a lot of work with 300 gigs of music files and would like that to be fast, but it’d be stupid and expensive to leave those on an SSD forever (at 2012 prices).
  • Use an SSD as a writeback cache for hard drive. Very appealing option, and there’s three options. My Z68 motherboard includes support for Intel Smart Response Technology but sadly there’s no Linux support. There are two Linux projects that do something similar: Flashcache and Bcache. But both seem pretty bleeding edge and require lots of manual setup. The Bcache release notes a few months ago included a comment about “slow silent data corruption” that put me right off.
  • Hardware RAID. This Z68 motherboard has Intel RAID right on the motherboard, perfect! Only it turns out this kind of RAID is what’s known as fakeRAID; the operating system does most of the work. Linux can support fake RAID but if you’re going that route most people suggest just using Linux software RAID. (The advantage of motherboard RAID is the BIOS can help boot your OS).
  • Software RAID. It’s been awhile since I checked in on the state of Linux RAID and sadly, it’s in disarray. Docs on the net are all randomly out of date, talking about 2.6 kernels or 3 year old versions of Ubuntu. I think the systems are pretty stable, being based on md, just poorly documentd. These 9.10 docs are the best I’ve found. The Ubuntu installer will create a RAID array for you or you can go low level with mdadm. Apparently GRUB 2 understands Linux software RAID so you can boot right off the RAID disk.

Of course there are many flavors of RAID. I’m mostly interested in speed, not reliability, so RAID 0 seems like the obvious choice except everyone says that’s nuts because you double your chance of a disk failure destroying everything. Fun!

bash 4.2 $variable expansion bug

bash-4.2 (default on Ubuntu) has a super annoying bug.

d=/usr/bin
ls $d/ssh-keyg[user presses tab]
ls \$d/ssh-key

In a nutshell, bash “helpfully” adds a backslash to escape the dollar sign because the user must have meant the literal character $. Previous to bash-4.2 it would have expanded the variable, so we would have seen “ls /usr/bin/ssh-keygen” instead. Which is way more useful

A quick search online finds the usual set of incorrect explanations and cargo-cult changes to bash-completion. (A popular fix is to use complete to make it so that the “cd” command works, leaving expansion broken for every other command.)

The actual truth is that this expansion is intended behavior in 4.2. Chet Ramey himself said so. He also recognizes this is awkward and has written a patch to add a new shopt called “direxpand” that will restore the desired, pre-4.2 behavior. Sadly that patch hasn’t made its way into Ubuntu’s Oneiric distribution yet.

One workaround for now is to press ESC C-e before hitting tab; that forces the command line to expand everything first.

Unlocking AppleTV notes

I’m trying to unlock a new AppleTV 2 so I can use XBMC or Plex to play videos from my home network on my PC. It’s been seven years since I first ran XBMC on a hacked Xbox and it’s still way too hard to get low power hardware to play your own TV.

AwkwardTV seems like a useful reference.

Some notes on the jailbreak process:

  • Apple firmware is signed via some online process. You need a “shsh” signature to bless firmware to run, even on already jailbroken systems. In general Apple only signs the most recent firmware, so it’s very hard to downgrade firmware.
  • There’s a program called TinyUmbrella that will generate shsh for firmware you have already. However, it’s mostly not useful except generating a shsh for a current version. My AppleTV out of the box had 4.3 but I was “too late” to get a shsh for it, despite it running. TinyUmbrella is evil software that modifies /etc/hosts and does god knows what else as root. There’s a competitor called iFaith, which may get shsh even for old firmwares, but it’s Windows only.
  • Seas0npass is the preferred jailbreaking software. Their guide is quite good. Don’t be fooled that it’s dated a year ago; they keep updating the jailbreak software.
  • Jailbreaking really boils down to putting the AppleTV in DFU mode and reflashing the firmware with some funky thing. All the weirdness around Seas0npass is creating that firmware and then scripting iTunes to install it.
  • If something goes wrong this Seas0npass troubleshooting guide is great. In particular I had the problem of iTunes saying “This device isn’t eligible for the requested build”. Turns out TinyUmbrella had evilly rewritten my /etc/hosts and was breaking the iTunes update process; telling TinyUmbrella not to do that fixed it.
  • It took about seven tries, but I now have an Apple TV 2 running 4.4.4 (3330), but jailbroken. Ie: I can run my own software and the hardware I purchased.

Now what? Well simple thing is log in as root with the default password “alpine”. Hey, look, it’s like a Unix box! It’s even got apt-get, plus a bunch of apt sources of dodgy software.

First thing up is to install Plex, a media player that works by streaming video from a transcoding server. There are many sets of conflicting instructions on how to install Plex. This forum thread seems up to date as of January 2012. Conceptually...

  • Install Python via apt
  • Download this scary installer(a zip file)
  • Change your root password back to the default “alpine”
  • Run the scary installer
  • It reboots the Apple TV, and now you have Plex!
  • Run Plex, go to Settings / Security and disable tracking.
Plex Media Server is awfully finicky about finding files. It desperately wants to match video filenames to a poorly documented naming system; if files don’t match, they just don’t show up. And it tries to cache the scan so simply renaming files doesn’t really force a rescan. There’s no “scan everything” option in the web UI (there is in the native client). Oh, and the Web UI is terribly buggy and you have to reload it every time you change the folder list.

Next thing would be to install XBMC, but I’m already feeling bruised from dealing with all this poorly packaged hackerware. Full props to the folks making media software on unauthorized devices, but man is usability a challenge.

BTW, two crappy things about the Apple TV:

  • There’s no HDMI cable in the box
  • The remote is IR only

New kernel fail

I decided to build a custom Linux kernel on my Ubuntu 10.10 Oneiric box. 3.0.0 feels awfully old, and I’ve been having trouble with a couple of things (well documented here). I was hoping a modern 3.2 kernel from Ubuntu precise would fix both my ethernet driver problem and, by building specifically for a modern Intel CPU, enable sched_mc_power_savings. No such luck.

Building a Linux kernel has gotten remarkably complex. I mostly quit trying myself back in 2.2 or so; once loadable kernel modules got reliable there was little reason for a top end developer like me to muck with the kernel. These Ubuntu-specific instructions got me there, although it’s a long winded and complex thing involving a lot of configuration management.

Then I got it built and installed and rebooted and miracle! It worked. Only with the same old bugs. 10+ seconds to initialize the ethernet, and that power savings sysctl still missing. I gave up and removed my custom kernel. I’ll wait for the Ubuntu release to upgrade.

 

Cyberpower pwrstatd notes

I bought a Cyberpower UPS for my Linux server. I mostly like it, but the Linux software they include for it (pwrstat and pwrstatd) is comically bad. Network UPS Tools supports this UPS hardware too, if I weren’t so invested in this software already I’d try it instead.

Here are some bugs:

  1. There’s no source code available, just two little ELF binaries pwrstat and pwrstatd
  2. pwrstatd has to run as root, not a big surprise since it can shutdown the machine, but see bug #1. Also pwrstat (the userspace program) has to run as root, even to get the UPS status! It seems to mmap() itself into pwrstatd :-(
  3. The default configuration is to shut down your machine after 60 seconds of power failure, then shut the whole UPS off after 10 minutes. That’s awfully aggressive.
  4. Once a Linux box is shutdown, the ACPI system means it won’t reboot itself again when power is restored. Wake-on-LAN is the right way to fix this, I don’t know a quick and dirty way.
  5. The various utility shell scripts /etc/pwrstatd-*.sh are very poorly written. The mail program assumes /bin/mail has a -r flag (mine doesn’t). One script has a test for ENABLE_EMAIL being “YES”, the other tests for it being “yes”. None of the test arguments are quoted so missing variables throw shell syntax errors.
  6. Did I mention all the real work is done in pwrstatd, which runs as root, and for which there is no source code provided?

The cool thing about the UPS is the status report it gives over the USB includes a bunch of data, including how many watts the UPS is driving right now. I wrote a little Munin script and now I have a fancy graph of my server’s power consumption.

That graph above includes me unplugging the UPS and letting it run to zero. Original estimate was 82 minutes of runtime, actually got about 70. Oddly the power drain went up 10W after unplugged; the inefficiency of the AC generation?

This UPS seems to consume 10W of its own even when fully charged, and about 20W when charging. Not happy about that 10W. Also the “battery capacity” value is totally bogus during charging; it only updates when I force the UPS to run off battery or run a self-test.

Here’s my Munin plugin (first ever!)

#!/usr/bin/env python

"""
pwrstat - Plugin to monitor Cyberpower UPS via pwrstat

by Nelson Minar <nelson@monkey.org>, placed into the public domain

Unfortunately this plugin must run as root, because pwrstat requires
root to even read data from the UPS.
"""

import sys, subprocess

# config
if len(sys.argv) > 1:
 if sys.argv[1] == "config":
 print """
graph_title Cyberpower UPS Status
graph_category UPS
graph_vlabel value

inV.label Utility Voltage
inV.min 0
inV.max 200
inV.warning 100:130

outV.label Output Voltage
outV.min 0
outV.max 200
outV.warning 100:130

battery.label Battery Capacity (Percent)
battery.min 0
battery.max 100
battery.warning 35:105

runtime.label Remaining Runtime (Minutes)
runtime.min 0
runtime.max 200
runtime.warning 10:200

loadWatts.label Load (Watts)
loadWatts.min 0
loadWatts.max 1000
loadWatts.warning 30:150

loadPct.label Load (Percent)
loadPct.min 0
loadPct.max 100
loadPct.warning 0:75
"""
 sys.exit(0)
 else:
 sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
 sys.exit(0)

# fetch

output = subprocess.check_output(("/usr/sbin/pwrstat", "-status"), shell=False)
output = output.split('\n')
data = {}
for datum in output[10:-2]:
 name = datum[:29].strip('.').strip()
 value = datum[31:].strip()
 data[name] = value

print "inV.value", data["Utility Voltage"].split()[0]
print "outV.value", data["Output Voltage"].split()[0]
print "battery.value", data["Battery Capacity"].split()[0]
print "runtime.value", data["Remaining Runtime"].split()[0]
print "loadWatts.value", data["Load"].split()[0]
print "loadPct.value", data["Load"].split()[1].split('(')[1]

sys.exit(0)

# This is the pwrstat format that we parse. Note, it contains tabs.
# Comes from pwrstat version 1.2
exampleOutput="""
The UPS information shows as following:

Properties:
 Model Name................... UPS CP1000AVRLCD
 Firmware Number.............. BFC7101.4K1
 Rating Voltage............... 120 V
 Rating Power................. 600 Watt

Current UPS status:
 State........................ Normal
 Power Supply by.............. Utility Power
 Utility Voltage.............. 125 V
 Output Voltage............... 124 V
 Battery Capacity............. 100 %
 Remaining Runtime............ 77 min.
 Load......................... 54 Watt(9 %)
 Line Interaction............. None
 Test Result.................. Passed at 2012/01/25 01:39:47
 Last Power Event............. None
"""

New server power consumption

Power consumption of various computers, as measured with the handy Kill-o-Watt
  • 2012 Linux server. 50W - 120W
  • 2011 iMac. 50W - 210W
  • 2010 Windows PC. 120W (always!)
  • 2003 Linux server. 50W

I like how the iMac numbers line up. The iMac has a GPU and a large LCD, so it maxes out higher, but when idle it’s about the same as the Linux server. It’s a very similar motherboard and the same CPU, so that all makes sense.

I don’t quite understand why the idle Linux box is using 50W and not, say, 10W. I don’t think the Intel CPUs will completely shut down a core when idle, that’s part of it.

Update: some useful notes from Intel and on SuperUser. Taking cpus offline via /sys/devices/system/cpu/cpu3/online didn’t save me any power. Either idle CPUs take very little power (unlikely) or the comment on SuperUser is right that this doesn’t halt the processor. The /sys/devices/system/cpu/sched_smt_power_savings also didn’t save me any power. I think sched_mc_power_savings would be useful, but it’s missing on my system. Apparently I need to rebuild the kernel with my processor family to enable it.

Update2: according to this article at low power an i7-2600 uses about 5W. Their measured idle system power (whole computer) is about 70W, so my 50W is in line. Where does it all go?!

At $0.33276/Kwh, every extra watt costs me $0.25 a month.

Python script to find Amazon store MP3 files

I’m working on rationalizing my MP3 collection.  Here’s a Python script to print out the names of all songs that seem to have been bought from Amazon MP3. It uses the presence of “Amazon” in the ID3v2 comment tag. It’s not entirely reliable; songs I bought in 2007, 2008 are missing that tag.

#!/usr/bin/python

"""Print out names of MP3 files that are from Amazon.
Works by looking for the Amazon ID3v2 comment tag with a song ID.
This method is not complete: some early Amazon sales don't have this."""

import sys, os
from mutagen.id3 import ID3

def isAmazon(fn):
  "Return the Amazon comment if it's an Amazon MP3, else None"
  id3=ID3(fn)
  for c in id3.getall('COMM'):
    if "Amazon" in str(c):
      return str(c)
  return None

for dirpath, dirnames, files in os.walk('.'):
  for name in files:
    if name.endswith(".mp3"):
      fn = os.path.join(dirpath, name)
      try:
        if isAmazon(fn):
          print fn
      except:
        pass # ignore errors

sys.exit(0)

Realtek ethernet drivers: r8169 vs r8168

Update Jan 2013: this driver issue was fixed in Ubuntu 12.04 / kernel 3.2.0-14 or so.

Ubuntu doesn’t work out of the box with my ethernet adapter. The ethernet interface is very slow to come up after boot, taking 10-120 seconds. The problem is the Realtek 8111 or 8168, a very common motherboard ethernet adapter. The motherboard docs say it’s a Realtek 81111E. The Linux drivers are broken. Apparently this is a common problem across many Linux variants and people report other problems, too, packet loss and dropped packets. It’s a four year old bug in Ubuntu! How to fix it? (Other than buying a new NIC; Realtek NICs are not well loved.)

I did a lot of research. One proposed fix is to get a different device driver, from Realtek, not the Linux kernel sources. (More notes). Another suggestion is to enable Wake-on-LAN (via Windows), but I don’t really believe that will work. A third option is to upgrade kernels, there’s some possibility that the mainline Linux driver is better. (Most recent Ubuntu bug is 864196).

I decided to try Realtek’s driver. r8168-8.027.00. md5sum:
98155ce1ad5c248eeb7a93c9954d8344  /tmp/r8168-8.027.00.tar.bz2

Sadly, it doesn’t fix my problem. The NIC still takes 10-200 seconds to come up after boot. I also tried enabling wake-on-lan (via Linux, ethtool) and that didn’t fix it either. No surprise but I thought I’d give it a shot. I’m left with the conclusion there is no fix for this bug right now, despite the superstitions about Wake-on-LAN, or r8168 drivers, or whatever.

BTW, the autorun.sh script that comes with the r8168 driver from Realtek is pure evil. First, it unloads your ethernet driver. Completely killing your machine if you’re logged in via ssh and don’t have physical access! Then it goes and rewrites a bunch of stuff in /lib/modules and rebuilds your initram disk. It seems to get this right, but it’s awfully intrusive. I finally removed r8168.ko by hand and did an “apt-get install --reinstall  linux-image-3.0.0-15-server” to set things back.

I’m going to try living with this bug; I never reboot the box anyway. The first time I experience massive packet loss, or the ethernet doesn’t come up after boot, I’m getting a real NIC and putting it in a PCI slot. And never again buying a motherboard with a Realtek NIC for Linux use.

Details from lspci -v from stock Ubuntu, before I tried adding the r8168 driver:

03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 06)
 Subsystem: ASUSTeK Computer Inc. P8P67 and other motherboards
 Flags: bus master, fast devsel, latency 0, IRQ 45
 I/O ports at e000 [size=256]
 Memory at d0004000 (64-bit, prefetchable) [size=4K]
 Memory at d0000000 (64-bit, prefetchable) [size=16K]
 Capabilities: <access denied>
 Kernel driver in use: r8169
 Kernel modules: r8169

Configuring lm-sensors for Asus P8Z68-M-Pro

The temperature, fan, and voltage sensors in my fancy new Asus P8Z68-M-Pro motherboard weren’t recognized right out of the box. I fixed it by installing a custom kernel module and then telling the sensors(8) program to ignore some bogus readings.

The motherboard has two sets of sensors. coretemp-isa-0000, from the Intel chip, and nct-6776-isa-0290, from the motherboard. That second chip requires a custom kernel modules which I got from Guenter Roeck: w83627ehf. Easy to build and install, and afterwards sensors(8) shows lots of data.

Some of the data is bogus (see  this github issue), so I fixed it by dropping the following file in /etc/sensors.d:

# Configs by nelson to hide bogus values on my ASUS P8Z68-M PRO motherboard,
# which uses an nct6776-isa-0290 chip.

chip "nct6776-*"
 # These are not configured in sensors3.conf
 ignore in1
 ignore in4
 ignore in5

# Fans I don't have plugged in
 ignore fan1
 ignore fan3
 ignore fan4
 ignore fan5

# ignore CPUTIN and AUXTIN; bogus values
 ignore temp2
 ignore temp3

Those in and temp sensors are returning meaningful data, but they’re not configured correctly in the default /etc/sensors3.conf and I’m too lazy to track down exactly what they might mean. One of those fan sensors probably is for the chassis fan, but mine isn’t plugged in to my motherboard.

Disk and data transfer rates

All these disks and stuff have me confused about what fast transfer rates are. Here’s some numbers, mostly practical rates, not theoretical. All numbers are Megabits / second. See also the Wikipedia List of device bit rates.

  • 168,000: RAM for an i7-2600 (theoretical) (ref)
  • 10,000: HDMI v1.3
  • 6400: PCI (64 bit, 100MHz)
  • 5000: USB 3.0 (theoretical)
  • 4800: 6.0Gbit SATA
  • 2400: 3.0Gbit SATA
  • 800-4000: SSD drives (ref)
  • 1000: 7200 rpm hard drive disk-to-buffer (ref)
  • 1000: gigabit ethernet
  • 800: IDE, UDMA 5 aka Ultra ATA/100 (ref)
  • 250-480: USB 2.0 hard drive (ref)
  • 100: 100M ethernet
  • 30: fast US home Internet
  • 20: 802.11g wifi (ref)
  • 12: USB 1.0
  • 6: my crappy home DSL
  • 1: AT&T 3G downloads (ref)
  • 0.05: old acoustic modems
Bottom line: USB 2.0 is a little slower than a desktop hard drive. And SATA is significantly faster than a hard drive. I wish I could narrow the SSDs down, I think performance on those things varies quite a bit. My friend Lars just built a RAID 5 array of SSDs that’s showing about 10,000 Mbit/sec.
Some practical tests on my brand new Sandy Bridge server with 7200 RPM disks plugged into SATA/6 and formatted ext4fs. All numbers are Megabits/second
  • 1000: hdparm -t, testing disk read throughput from the platter
  • 110,000: hdparm -T, testing read from RAM cache (ie: never touching SATA or disk)
  • 1088: writing 16 gigs of zeroes
    dd if=/dev/zero of=zeros bs=1M count=16384
  • 440: copying 16 gigs of zeroes on a single drive
    dd if=zeros of=zeros3 bs=1M
  • 872: copying 16 gigs of zeroes from one drive to another. Parallelism!
    dd if=zeros2 of=/tmp/zeros bs=1M
  • 570: rsyncing 300 gigs of files from a FAT32 drive over USB-3 to an SATA/6 drive.
  • 20,000: writing 1 gig of zeroes. ext4fs must fully cache this before commit
    dd if=/dev/zero of=zeros5 bs=1M count=1024
  • 88: creating a file of random bits from /dev/urandom. I had no idea that driver was that slow.
These tests are all for big files. Linux gets a lot slower when dealing with lots of little files. Running rsync from a USB 2 disk copying to an SATA disk I’d see a factor of 10 difference in disk throughput between giant files and lots of tiny files.

The new Linux server

Here’s the parts I’m getting for my new server. Many thanks to Adam for sharing his system build of a few months ago. This system’s remarkably similar to a new iMac, albeit without the SSD. By all accounts this Sandy Bridge stuff is terrific.

1 of: Antec 380 Watt Power Supply Mid Tower Case NSK4482B (Black) $89.99
2 of: Western Digital 1 TB Caviar Blue SATA III 7200 RPM 32 MB Cache Bulk/OEM Desktop Hard Drive - WD10EALX $129.08
1 of: Intel Core i7-2600 Processor 3.4GHz 8 MB Cache Socket LGA1155 $295.00
1 of: ASUS SATA 6 Gb/s DisplayPort Intel Z68 Micro ATX DDR3 2200 Intel LGA 1155 Motherboards P8Z68-M Pro $119.99
1 of: Corsair 16 GB (4x4GB) Vengeance Blue Low Profile 1600mhz PC3-12800 240-pin Dual Channel DDR3 Memory Kit 16 Dual Channel Kit - CML16GX3M4A1600C9B $89.99

Junky case and very simple disk system. I won’t even run RAID, don’t trust it. No SSDs either, don’t trust those consumer parts. Just simple spinning platters. Some of the details matter. The i7-2600K is more popular because it’s overclockable. But I never overclock, and it turns out the i7-2600 has some virtualization capabilities that the i7-2600K doesn’t. It’s clear the Z68 chipset is the best motherboard, and I went with ASUS just because I always have. But they make like 6 Z68 motherboards and I can’t really tell one from the next. (After building this I learned the Realtek ethernet chip in the P8Z68 M Pro doesn’t work well in Linux. The P8Z68-V boards have Intel ethernet chips, may be a better choice.)

I told myself years ago I’d never build another computer from parts. Yet here I am. The local screwdriver shops are charging too high a premium, and then it’s a struggle to get them to understand you really want no graphics card, no OS, really just the simple server. “Oh, a server? How about this $4000 2U rackmount?”

At least I already know all about Ubuntu server.

IDE, the obsolete standard

My home Linux server died. We had an ugly power outage and when the power came back up and when I turned on the computer, out came the magic smoke. I hope that just the power supply fried, or maybe the motherboard, because I don’t have a backup of the data on the hard drives. 15 years of data, programming, photos, financial records, email, writing. It’s very unlikely that the data is gone; worst case, I send the platters to a data recovery service. But it sucks.

I’ve ordered the parts to build a fancy new computer. It’ll be an awesome fast upgrade based around Sandy Bridge parts. My plan was to install Ubuntu on the fancy new SATA drives, get things sort of working, then plug in the old IDE/PATA drives to copy the data over.

The motherboard doesn’t even have IDE ports.

When did that happen? When did IDE become so obsolete they don’t even put ports for it on a motherboard? I mean, the motherboard still has PS/2 keyboard, old school serial, parallel. No IDE. Ugh. I’ve ordered a USB adapter to get data off the old drive. Amazon is full of these jobbies for $7, complete with 10+ one star reviews saying “the power supply is junk and fried my drive”. Awesome. The one I picked has the most reviews and almost all are positive.

I’m not so stupid as to not have any sort of backups of the data. I have a complete rsnapshot mirror. On a second drive, in the dead machine, the one that might have sent a surge of death through every plugged in component. Yeah, didn’t think through all failure modes. I am committed to doing real offsite backup of all my computers now. I have CrashPlan on the Mac already; something for Linux will be coming.

While I’m waiting for the adapter I tried playing with an old USB drive enclosure I had lying around, thinking I could put the drives in and plug them into my Mac to reassure myself the data is still there. Turns out mounting ext3fs on MacOS is a clusterfuck. fuse-ext2 is the recommended way but MacFuse doesn’t work on Lion and is abandoned and all the Fuse folks have scattered every which way. This blog post claims that OSXFuse + Fuse-ext2 will work on Lion, but I don’t have enough confidence in all this jury rigging to bother trying it. I’m much more comfortable recovering data in a Linux system.

Organizing all my git

I use git enough now that my repositories are getting a bit messy. I decided to centralize them all in one place so I can access them over the network. (You know, the distributed part of DVCS). There’s lots of options, I settled on just using a bunch of bare repositories on a host I can ssh to.

Alternatives I considered.. Dropbox is a good alternative for the central git repository but I’ve got my own server so I’m using that. The git:// protocol seems like unnecessary complication. As for hosting and web frontends.. GitHub is too expensive for my 10+ private repos,, charging per repo. Sites like repositoryhosting, gitorious, codeplane, and bitbucket have cheap or free options, but I don’t really need a centralized host since I’m mostly working alone. I could also have gotten fancy and installed something like gitolite to have a webapp front end, but that’s overkill for me now. Maybe I’ll set up gitweb at some point.

Here’s how I migrated my exisiting ad-hoc repos to one canonical gitrepos directory on a server. I found a lot of conflicting and incomplete info on how to do this, for instance these notes, this blog post, and this stackoverflow post. Correctly getting all branches into the new canonical repo and then patching up the config of the old ad-hoc repo is not straightforward. I’m not confident this is really correct, either, but it seems to work for simple things.

Find all the .git repos. Still have to hand-edit this list.
$ find ~ -type d -name .git | egrep -v '/d3|polymaps/'

Create a new bare repo in my new ~/gitrepos directory, based on code from ~/src/dotfiles.
$ cd ~/gitrepos
$ git clone --bare ~/src/dotfiles dotfiles
$ # is this a good idea? necessary?
$ # cd dotfiles; git remote rm origin

Change my old ad-hoc repo to consider this bare repo as its origin.
$ git remote add origin ~/gitrepos/dotfiles
$ git push
$ git branch --set-upstream master origin/master

That bit about pushing and then setting the upstream is 100% black magic for me, I have no idea what it does. It seems to be necessary to create the magic so that later “git status” will tell you if your local branch is ahead of the canonical copy in ~/gitrepos.  The push is necessary for some git config reason, even though there’s nothing to push. I find it confusing how git uses branches to track remote repos.

Also useful: “git remote -v” for seeing what remotes are configured, and “git branch -avv” for seeing more about git’s local view of various branches and remotes.

None of those examples above use a really remote repository, it’s all just Unix file paths. You can so name repositories like “nelson@example.com:~/gitrepos/dotfiles” and it will ssh to example.com and everything just works.

About this blog

A few folks have subscribed to this blog recently. Welcome! I am not writing for you. I am truly, only, writing work notes for myself. Stuff I learn and don’t want to forget. You’re welcome to read along, comment, share, whatever. But this post is probably the last time I’ll ever think about what you think, dear reader.

My real blog was also intended to be written for myself but somewhere along the way became a publication medium. When I write there I care to be clear, grammatical, concise, interesting. Here, not so much.

 

A place where bzip2 is useful

I almost always regret using uber-compressor bzip2. It generally compresses to, oh, 90% of the size of gzip but takes 10x as long to compress and 2x as long to decompress. Not worth it, bad space/time tradeoff.

The exception is Apache access log files. Something about the terribly repetitive text of these things is really good for bzip2. Here’s a quick test on a 26 meg access.log (using bzip2 1.0.5 and gzip 1.4 on Debian i686)

gzip: 10.8%, 860ms to compress, 160ms to decompress

bzip2: 5.7%, 12700ms to compress, 1600ms to decompress

The bzip2 is literally half the size of the gzip. That’s a lot. Too bad it took 15x as much time to generate it and 10x as much time to decompress it again. A quick Google suggests most people find bzip2 about 3x-5x slower, not sure why it’s so bad for me. Maybe because my sample is also unusually good at compressing!

Some other fast compression options: pigz, pbzip2, threadzip for parallel compressors, or snappy for Google’s very-fast-but-not-as-tight compressor.

Here’s the sample data I tested:

207.46.13.138 - - [04/Jul/2010:06:32:55 +0000] "GET /robots.txt HTTP/1.1" 301 329 "-" "msnbot/2.0b (+http://search.msn.com/msnbot.htm)"
207.46.13.138 - - [04/Jul/2010:06:32:55 +0000] "GET /robots.txt HTTP/1.1" 200 107 "-" "msnbot/2.0b (+http://search.msn.com/msnbot.htm)"
61.135.216.105 - - [04/Jul/2010:06:32:55 +0000] "GET /weblog/index.atom HTTP/1.1" 304 - "-" "Mozilla/5.0 (compatible;YoudaoFeedFetcher/1.0;http://www.youdao.com/help/reader/faq/topic006/;2 subscribers;)"

Ubuntu server cron jobs

Here’s all the cron jobs on my relatively vanilla Ubuntu Server setup. I’ve added Apache and a few other minor things to the default install.

Daily:

  • htcacheclean, for Apache’s mod_cache disk cache
  • apport, cleans up old reports in /var/crash
  • apt, cache management
  • aptitude, making logs of what’s installed
  • dpkg, also making logs of what’s installed
  • popularity-contest, telling Ubuntu what people installed
  • bsdmainutils, managing user’s ~/calendar files
  • logrotate
  • man-db, managing the man page database
  • mlocate, an efficient implementation of good ol’ locate for fast finds
  • ntp, managing ntpstats (which aren’t enabled by default)
  • passwd, making backups of /etc/passwd and friends. (wtf?)
  • standard, the “standard daily maintenance script”. backs up /etc/passwd (again?) and looks for lost+found files. Dumb script, and redundant
Weekly:
Logrotate is configured to back up weekly and keep 4 weeks worth of logs and, surprisingly, not compress old logs. Apache overrides this to keep 52 weeks of logs and to compress them. I’m pleased to see the Ubuntu logrotate has a dateext and dateformat option to name logfiles like “access.log-20120108” rather than “access.log.3” and then renaming that to “access.log.4” the next week. That should be the default behavior but apparently that option isn’t available in older versions of logrotate.

Ubuntu and FQDNs

Setting the fully qualified domain name on an Ubuntu host is way too hard. The Internet is full of confusing advice. Most people first seem to notice the FQDN isn’t right when setting up Apache, but it’s a broader problem than that. (You can fix Apache just by giving an explicit ServerName directive.) “hostname -f” should return the right thing.

My solution:

  • /etc/hostname contains just the system name, “wi”
  • /etc/hosts contains an entry like this:
    208.110.64.210  wi.nelson.monkey.org wi
  • /etc/resolv.conf contains an entry like this:
    domain nelson.monkey.org

And now “hostname” returns “wi”, “hostname -f” returns “wi.nelson.monkey.org”. Note I don’t have a reverse DNS entry for that IP address. (I do have forward DNS so wi.nelson.monkey.org resolves, but I don’t think it’s used.)

Part of the confusion is a lot of people (and Ubuntu by default) want you to do something like

127.0.1.1 wi.nelson.monkey.org wi

This kind of works, despite the odd loopback address number. But it’s not really correct: your FQDN should resolve to a routeable IP address, not a loopback.

 

 

Ubuntu server notes from an old Debian user

I’m setting up a new Linux server and using Ubuntu for it for the first time. I’ve been a Debian guy for a long time now (and before then, Red Hat), so Ubuntu is both new and old. I switched to it because it’s got a faster upgrade cycle than Debian, but I like all the extra tools they’ve added, too.

Here’s some of the new things in Ubuntu I’ve learned about. The Ubuntu server docs are an excellent place to start.

  • upstart, a replacement for SysV init scripts that runs things in parallel. The configuration files live in /etc/init. There’s still old SysV stuff in /etc/rc2.d and /etc/init.d being run. The new service command is nice, ie “service --status-all”. There’s plans for upstart to replace cron and at, too. Docs: UbuntuBootupHowto, original rationale, upstart tutorial, and cookbook. (Ubuntu does not use systemd, another modern init replacement).
  • plymouth, the graphic splash boot screen. For some reason this is complicated and intertwined with upstart.
  • ureadahead (aka Über-readahead), a clever system to improve boot times by reading all necessary user files off of disk in one big transfer at the beginning of boot. The boot image is kept in /var/lib/ureadahead and there’s clever stuff to invalidate and re-write the files when new things are installed. It seems to save a few seconds on boot for me, not positive. More info here.
  • ext4fs is the default filesystem. It has various incremental improvements to ext3fs, many of them aimed at efficiently handling big files and disks.
  • AppArmor, a security mechanism. It lets the kernel restrict what access various programs have. For instance, ntpd is only allowed to write to certain log files so if there’s ever an exploit against ntpd it won’t go writing random files as root. It seems like a fairly limited security mechanism given how big the attack surface of Linux is, but also harmless and potentially useful.
  • ufw, Uncomplicated Firewall, is a friendlier interface for firewall rules than iptables.
  • Automatic software updates. The setup process is embarrassingly manual, but you can have Ubuntu install security updates (or all updates) automatically.
  • pam_motd, the absurd thing that makes /etc/motd show current system stats. It seems to update on login. If it ever breaks I will be very angry if I can’t log into my system.
  • JeOS is a stripped down Ubuntu server for running as a guest in a virtualization environment. I have no need for this now, but it’s a good idea.
  • Bacula, a fancy backup system. I will probably stick with rsnapshot and rsync.
  • Launchpad, a website where many Ubuntu projects are hosted. Bug tracking, etc.

One thing they haven’t improved is libresolv; it still queries nameservices serially, one at a time. Worse, the first entry in /etc/resolv.conf for me named 192.168.1.100 as the nameserver, a bogus entry from the initial setup in a different DHCP environment. So every DNS query was waiting 5 seconds for that to time out. I fixed it by putting Google’s 8.8.8.8 as the first nameserver.

My next project is to automate all my deployment of my own stuff to the server using Puppet or maybe Chef Solo. I’m trying to avoid the thing where my servers become an irreproducible rat’s nest of random crap I’ve collected over time. OTOH, I can tell already it’s going to be a lot of work for one little personal projects server.

 

METAR parsing libraries

METAR, the weather observation format, is a great little text format

KOAK 032353Z 00000KT 5SM BR SCT200 11/08 A3029 RMK AO2 SLP256 VIS SE 1 1/2

It’s also not a very standardized format, making parsing a bit of an art. Here’s a few different METAR parsing libraries I’ve found:

  1. Tom Pollard’s python-metar, (sourceforge, github). This is what I used to prepare windhistory.com and it’s pretty good.
  2. Joe Yates’ metar-parser for Ruby. Has some test coverage. Also references other Ruby implementations.
  3. METAR decoding software from NWS. The closest thing to official code, written by Eric McCarthy, now on SourceForge. It’s 12,000+ lines of C code (!), albeit with a lot of comments, unit tests, etc. Has some interesting code for interpreting the meaning of METARs, like whether it codes for a tornado or the like.

There’s lots of other parsers for various languages: PHP, .NET, etc.

 

Full-height HTML divs

I keep forgetting the right way to make a DIV take up the full height of the web browser. For, say, a full screen map. Chrome and Safari default to filling the whole container but Firefox prefers to calculate a minimum height div. Long story short, here’s what to do:

html, body, div#map { height: 100% }

I’m not entirely sure this is correct but it seems to work and is in line with advice on this StackOverflow discussion. It’s not enough to set the div’s height, you have to set the containers too. There’s also something about using min-height instead but it seems unnecessary. What I don’t know is how to set the height of a div to be 100% minus 100px or the like; something that leaves room for a header or footer.