Some Bits: Nelson's log

49 posts about macos

MacOS third party graphics drivers

I did something I never thought I’d do and installed third party graphics drivers for my Mac, which has an NVIDIA GeForce GTX 660M graphics card. I was motivated to do that because the new game Stellaris was crashing frequently. The cargo cult advice for another game from the same publisher was that the third party drivers seem to have helped and I’ll be damned, they do.

NVIDIA couldn’t make it more confusing what these drivers are for, saying “This driver update is for Mac Pro 5,1 (2010), Mac Pro 4,1 (2009) and Mac Pro 3,1 (2008) users.” I don’t have some ancient Mac Pro with a video card, I have a modern iMac with a stock apple GPU. But the fine print indicates that really these drivers are for pretty much any Mac with an NVIDIA GPU. Also it’s called the “Web Driver”, which is an insane name for a kernel module. Note that there’s no index for all NVIDIA releases; you have to go this reseller page to find all the versions. And don’t be confused by the CUDA drivers; those are for high end number crunching, not graphics and gaming.

The installer seems well behaved. Worked fine on reboot for me, and the drivers have only seemed to be an improvement so far. Also it includes a control panel where you can switch back to the default MacOS drivers or uninstall the NVIDIA stuff entirely.

No idea what’s going on with Apple and MacOS that the stock El Capitan drivers aren’t good enough. Or with Paradox, the game publisher, that their games are sold for Macs without testing on standard machine configs. The whole point of paying the Apple premium is this stuff is supposed to work out of the box.

Update Dec 2016: the NVidia drivers are responsible for some graphics lag in League of Legends. With them installed, when Thresh drops a lantern my FPS drops from a solid 60 to 45 FPS or so. With the stock OS X drivers there’s no FPS drop. I don’t know if this is a bug in LoL or the drivers or an unfortunate interaction between the two. It may also be related to vsync.

MacOS unzip is ancient and busted

Tracked down an OpenAddresses problem with our primary data product, a 3GB zip file. MacOS unzip can’t unzip it, producing errors like this:

skipping: us/il/macon.vrt         need PK compat. v4.5 (can do v2.1)

The underlying problem is MacOS El Capitan (10.11.4) distributed the ancient unzip version UnZip 5.52 of 28 February 2005. This version does not work correctly on files > 2GB big. The usual recommended solution is to install p7zip via Homebrew and use that to unzip the big archive. A lower impact option is to install the Homebrew dupe for unzip, which is UnZip 6.00 of 20 April 2009. That’s a bit awkward since being a dupe, Homebrew won’t symlink the binaries by default.

This is not the first time I’ve wasted working around Apple’s awkward user space tools. The less file reader is also an outdated version, and last I checked was compiled with weird options like not respecting the LESSKEY environment variable.

I really should just stick to Ubuntu.

MacOS 10.9 to 10.11 upgrade

I upgraded my 2011 iMac from Mavericks to El Capitan. Partly on a whim, partly because a lot of apps no longer work with 10.9. Mostly pleased with the result, Apple really does a nice job on not breaking systems on upgrades, migrations, etc. Still some notes:

  • Apple removed my fucking software. As part of the new security model Apple decided it was OK to delete all my files in /usr it didn’t approve of. Including my Homebrew install. Thanks, Apple! I found my purloined programs in /Library/SystemMigration/History/. I was going to rebuild Homebrew anyway because reasons, so meh, but... Weird to also find stuff from /System put there, stuff I never created.
  • MenuMeters broke. No surprise, it was using a weird hack. There’s a port of MenuMeters to 10.11 which works fine and no longer needs the hack, at the expense of losing the ability to rearrange the menu bar.
  • Seil didn’t break! That’s a funky kernel driver that lets me override CapsLock, was sure it was going to stop working.
  • I can no longer move the Dock to a corner. Thanks Apple.
  • The alt-tab popup  now shows on my secondary monitor. Apparently it shows up where the Dock is. I want the Dock on my secondary, but the Alt-Tab on my primary along with the menu bar. Sources: 1, 2
  • League of Legends isn’t running completely smoothly. I see occasional 0.1s pauses. It’s not unplayable, but it’s not right. It’s mysterious, not easy to reproduce / isolate.
  • Ever since my iMac got a hardware repair something made noise in the case when high contrast stuff scrolled on the screen. Weird, I know, I assumed it meant something wasn’t properly shielded anymore and EM was leaking into the speakers. That problem is now gone!?
  • Every time I plug in my phone to charge it, the unwanted Photos app launches. Found a solution which requires running the photos app enough to uncheck a thing. Remember when Microsoft used to exploit their operating system to promote their other products and everyone got angry, up to the federal government? Why does Apple get away with even more aggressive self-promotion?
  • my sshd stopped running. I had to renable it via Sharing Preferences
  • Despite the trend to flat design, Yosemite added some tacky transparency effect that makes menus harder to read. Here’s how to disable it.

Homebrew. For my own notes, the output of “brew leaves” from my old system. I’m installing fewer of these things; in particular no octave or gcc. Installing this time to /usr/local/homebrew. I don’t like it installing in /usr/local/bin, etc; been burned by that going wrong.

bash-completion bcrypt clens cloc cloog duti exiftags fdupes ffmpeg
homebrew/fuse/fuse4x gcc homebrew/science/ggobi gist git grc icu4c
iftop iperf iperf3 jbig2dec jq homebrew/dupes/less homebrew/dupes/libpcap
libvo-aacenc mg mobile-shell mp4v2 mtr nmap node homebrew/science/octave
optipng ossp-uuid p7zip par2 pgdbf postgis pv pyqt python python3
q homebrew/dupes/rsync s3cmd homebrew/fuse/s3fs sshuttle unison
unrar wget wireshark

Packages to install this time:

bash-completion bcrypt exiftags ffmpeg gist git grc iftop iperf iperf3 jq homebrew/dupes/less mg mp4v2 mtr nmap optipng p7zip par2 pgdbf postgis pv homebrew/dupes/rsync s3cmd unison unrar wget

Everything installed with no drama except for postgresql (and postgis). It has some bug building in Homebrew related to libreadline and doesn’t seem to build with just the command line tools. Installing the full Xcode via the App Store fixed it.

osxfuse and sshfs didn’t install right via brew cask; simpler to download the installers and run them myself.

Mac sound capture, take 2

Awhile ago I wrote up some notes on recording League of Legends videos using OBS. I still mostly follow that horribly manual workflow, but I was having a hard time getting sound to work reliably. I think I have it sorted out now.

  1. Install Matt Ingalls’ SoundFlower 2.0b2 from GitHub
  2. Reboot. Not clear this is necessary, but I think it may be.
  3. Follow these instructions for configuring audio. However, Soundflowerbed is no longer included. Fortunately you can ignore that if you Audio MIDI Setup yourself (standard Mac software)

The key thing here is you use Audio MIDI Setup to create a new “Multi-Output Device”. That’s a virtual sound device that can send output to more than one place, in this case both “Built-in Output” (your speakers) and “Soundflower (2ch)” (the capture device).

Then you use the Sound preference panel to tell the Mac to play output to that new Multi-Output Device. Now every sound your Mac plays will both come out the speakers and be sent to SoundFlower.

Then you set up OBS to accept audio input from the SoundFlower device.

Unfortunately setting the default sound output to Multi-Output Device will break the volume control from the Mac keyboard. You can still set the volume for each output in the Sound panel though, just be sure to leave Multi-Output Device selected when you’re done. You want to modulate actual volume using Internal Speakers’ control. Set the Soundflower and Multi-Output Device volume to maximum, so that sound is passed through at full volume to OBS.

In previous versions of this setup I found cases where OBS could record audio correctly, but only if it was launched after the program playing the sound. No idea what that was about. I don’t think that’s happening any more.

If you’re serious about doing more fancy audio routing, the commercial Loopback program is pretty good. At $75 though it’s a bit pricy for what I’m doing.

Mac screen capture: creating League of Legends highlights

I felt like a huge nerd today and wanted to record a video highlight from a League of Legends. Lots of steps here to capture the game itself, capture video and audio on the Mac to a file, convert it to something usable, then upload it. Here’s all the steps.

Generate content: record game replay

The service replay.gg will record all your League of Legends games for you. It’s terrific! Using it you can watch one of your games later in the observer client. I use this to get the exact game scene I want to capture.

Capture content: video and audio capture

The Mac does not make it easy to capture full screen video and audio. I used to use the commercial product Screenflick to do this but it’s pretty buggy. So this time I did the capture with Open Broadcaster Software, which is a free. The UI is a bit more hackerware but for my purposes it’s perfect.

OBS records video pretty much right out of the box. I tinkered with the Advanced Output settings to record at the bitrate of 10,000 (overkill) using the faster preset. Note that OBS is doing h.264 encoding live while you go, so it’s taking CPU power. The “slow” preset definitely interfered with my game framerate. (Screenflick records with a very fast, disk intensive codec and then re-encodes later, which is kind of nice.)

Audio is a problem. Update: see this second post about sound. OBS recommends WavTap but I couldn’t make it work. Instead I installed SoundFlower, which also works well with OBS. Basically SoundFlower installs a kernel module that’s a new loopback audio device. You use the Sound control panel to tell the Mac to make SoundFlower 2ch the default audio device. SoundFlower then passes that through to your actual headphones or whatever, while also making the sound stream available to apps. Note that starting with Yosemite it’s getting very hard to run custom kernel drivers in MacOS. Thanks a lot, Apple.

Now I have OBS recording movie files to my hard drive of whatever is on my screen. Yay!

Edit content

The next challenge is editing the capture down to what you want to share. I’m allergic to iMovie, and AFAIK there is still no good free simple “let me cut 15 seconds out of my video” GUI tool for Macs. I ended up using ffmpeg to do this with these instructions. ffmpeg lets you pick to the nearest millisecond, but irritatingly VLC won’t show you milliseconds in playback, so precise cuts suck.

Here’s the command I used to cut from 00:02 to 00:19 of my recording and re-encode it at decent quality. Unfortunately you can’t just use “-copy” in ffmpeg because that doesn’t properly trim the audio for some reason; you have to reencode.

ffmpeg -i obs.flv -c:v libx264 -preset slow -crf 20 -ss 00:00:02 -to 00:00:19 out.mp4

Man I’d like a simple GUI program that lets me watch the movie and set a start time, an end time, and press a button to do this cut for me.

Share content

Now you have an ordinary MP4 movie file you can share anywhere. I uploaded it to Streamable, a lightweight hosting / sharing service for video that plays nicely with Reddit and friends. They re-encoded it to a 2260 kbps vp8+vorbis file which still looks pretty good. In particular I think they kept my 60 frame per second source, much appreciated.

MacOS directory permissions

Macs have this weird problem where the Unix file permissions for things get corrupted. Not just a couple of top level directories either. Things like the Finnish localization file for iBooks, an app I have literally never run, is marked group writeable and shouldn’t be. How does this happen?

The thing that’s most alarming is my root directory, /, is mode 0777. World writeable. And owned by my user account, not root. Literally any program running on my computer can come in and hijack the whole system because of that. Not the first time that’s happened either. I’ve read somewhere that a bunch of bad Mac install scripts like to just recursively make things world writeable “to make it work” and they work their way up to /. Also there was that one time when iTunes kept making /Users world writeable. Quality programming there, Apple.

The problem is so common Disk Utility has a special GUI app just to “repair permissions” by comparing the filesystem to records of what should be there left behind by installers. Only that’s a little scary because what if it breaks something? Helpfully there’s an audit mode just to see what’s changed. Run from the GUI or via diskutil verifyPermissions /.

At the bottom of the page is the audit of what all the tool finds wrong on my Mac after filtering out 3000+ lines of iBooks.app garbage. Mostly not too scary, although libruby.dylib being world writeable sure seems like a potential security disaster. The most terrifying one is

Warning: SUID file “System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent” has been modified and will not be repaired

What, a setuid root executable that’s part of a remote management system that’s been modified? Why that’s not suspicious at all! But have no fear: Apple itself says that’s one of roughly 100 messages from the audit you can “safely ignore”. So yes, the security audit tool prints a lot of false positives. Fucking garbage.

Note that the root directory is not one of the reports in the audit.

I felt lucky and ran the tool and it changed a bunch of things. Then ran the audit again and it found three problems, including the setuid root file I’m supposed to ignore.

It did not repair my root directory. I manually set that to 0755, owned by root.wheel.

Started verify/repair permissions on disk0s2 Macintosh HD
Permissions differ on "System/Library/CoreServices/Feedback Assistant.app"; should be drwxr-xr-x ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Permissions differ on "usr/lib/libruby.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Warning: SUID file "System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/MacOS/ARDAgent" has been modified and will not be repaired
Permissions differ on "Applications/Safari.app/Contents/Resources/Safari.help/Contents/Resources/index.html"; should be lrwxr-xr-x ; they are -rw-r--r-- 
Group differs on "Library/Printers"; should be 80; group is 0
Group differs on "Library/Printers/Icons"; should be 80; group is 0
Group differs on "Library/Printers/InstalledPrinters.plist"; should be 80; group is 0
Permissions differ on "Library/Printers/InstalledPrinters.plist"; should be -rw-rw-rw- ; they are -rw-r--r-- 
Group differs on "Library/Java"; should be 0; group is 80
Permissions differ on "Library/Java"; should be drwxr-xr-x ; they are drwxrwxr-x 
Group differs on "Library/Preferences/SystemConfiguration/com.apple.Boot.plist"; should be 80; group is 0
Group differs on "Library/Preferences/com.apple.alf.plist"; should be 80; group is 0
Group differs on "Library/Printers/PPDs"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents"; should be 80; group is 0
Group differs on "Library/Printers/PPDs/Contents/Resources"; should be 80; group is 0
Permissions differ on "System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/libruby.2.0.dylib"; should be lrwxrwxrwx ; they are lrwxr-xr-x 
Group differs on "private/var/db/GPURestartReporter"; should be 0; group is 80
Permissions differ on "private/var/db/GPURestartReporter"; should be drwxr-xr-x ; they are drwxrwx--- 
Finished verify/repair permissions on disk0s2 Macintosh HD

New Mac logic board: system identity

I brought my 2011 iMac in for repair, to replace a video card under an extended warranty program specific to my hardware configuration. (Reading between the lines, a cooling problem.) Once they got it on the testbench the tech decided to replace the system board as well because it tested faulty. At no charge! Despite the machine being a year+ out of warranty. Nice of them.

Anyway, a new system board means a new CPU, a new ethernet MAC, and a bunch of other small things. Which changed my machine’s identity for various things. I had to re-log in to all Apple online services. Time Machine also expressed concern but offered to “inherit” the backup I had, which seems to have worked. Had to set up a new IP assignment on my router for the MAC address of course.

I’d also logged Chrome out of Google and wiped all local state, for my security. Happy to report that logging back in to Chrome restored everything pretty well. I got all my Chrome extensions back but lost the extension configuration state. Also my browser link history is gone forever, I’d sort of hoped that would sync through Google too.

2011 iMac crash: vertical lines on screen

My iMac just crashed hard. Watching a video in VLC one second, dead machine with mostly black screen the next. Some strange light colored vertical lines.

Googling around this is apparently a known problem, a hardware failure of the GPU. This Apple support page notes a particular known problem for exactly my model of video card and CPU. (2011 iMac, AMD Radeon HD 6970M GPU, 3.4GHz i7 CPU). Sounds like they have a repair program.

Cyberduck is responsible for my bad SSL certificate

I figured out what put the rogue SSL certificate on my system, the one that breaks MacOS Mavericks. It came back yesterday 2015-04-27 between 15:38:32 and 16:41:02. The system Console helped me narrow it down to the application Cyberduck, version 4.6.3. I use it sporadically to browse S3 buckets. It’s just the right kind of unusual application that would cause a bug like this that some small group of users on the Internet finds but not everyone.

Cyberduck 4.6.3 placed a bunch of errors in the console, including the smoking gun “4/27/15 3:42:05.621 PM Cyberduck[54126]: Error adding certificate to Keychain”. I also manually verified the login keychain entries show up again as soon as I run Cyberduck after deleting them. (For completeness I should add Cyberduck also complains about an SSL hostname mismatch when connecting to S3, but I think that’s a legitimate and expected error and unrelated to the Verisign certs.)

Version 4.7 (17432) is the latest version of Cyberduck. It doesn’t cause the problem any more. There was a reported and fixed bug in Cyberduck. I’m not sure the Cyberduck authors understand the magnitude of the problem though, or that users of old versions now have broken Macs. We now have a bug report on file, my report text below.

I also don’t understand the root cause of the problem. Cyberduck says they were taking a certificate offered by the server; Amazon S3, in this case. Were they verifying it was a valid cert first? If so, then why is it no longer a valid cert? And why did MacOS security update 2015-004 break it? I’m content to let that all remain a mystery, but I’m curious.

Update: this AWS discussion contains complaints about S3’s SSL certificate. Apparently it’s a key that is weakly signed and various software is deciding it’s no longer valid as they update to stricter requirements. That may explain why 2015-004 changed things.

For the search engines: one of the two bad certificates placed on my keychain by Cyberduck was “VeriSign Class 3 Public Primary Certification Authority – G5”

Bug report for Cyberduck

Prior to version 4.7, Cyberduck had code where it wrote some SSL certificates to the user login keychain. This behavior is documented in ticket #8741 and the code was changed to no longer do that.

However, the certificates old versions of Cyberduck wrote to the Keychain are now causing fairly serious problems with MacOS. Affected Macs can no longer verify Verisign-signed SSL certs in any application. Symptoms are the App Store refuses to load, MacOS software updates won’t get installed, Chrome refuses to load websites and Safari throws errors. It’s pretty bad. The problem seems to be triggered by Mavericks security update 2015-004 (released last week).

The fix is pretty simple: manually delete the spurious entries in the login keychain (so that the system entries are used instead). But users aren’t going to figure that out on their own. There’s no indication to the user there’s a problem with their keychain or that Cyberduck was the app that created the problematic entry. I only figured it out thanks to some lucky timing and a message on the system console.

While Cyberduck 4.7 no longer causes the problem, anyone who used an older version of Cyberduck may still have a broken Mac. Could Cyberduck do something to notify affected users? Maybe a new version of Cyberduck that checks for the bad entries and warns the user, pointing them to a help page?

It’d also be nice to figure out exactly what entries Cyberduck might have written. For me and a bunch of other users it’s two Verisign certs, one named “VeriSign Class 3 Public Primary Certification Authority – G5”. They seem to have come from Amazon S3.

Some references:

http://apple.stackexchange.com/questions/180570/invalid-certificate-after-security-update-2015-004-in-mavericks

https://discussions.apple.com/thread/6984765

https://trac.cyberduck.io/ticket/8741

https://nelsonslog.wordpress.com/2015/04/25/mavericks-security-update-2015-004-has-a-serious-ssl-bug/

Mavericks security update 2015-004 has a serious SSL bug

My Mac suddenly started throwing SSL errors when connecting to various sites, like search.twitter.com or support.apple.com. The App Store application refused to load content, too. Long story short, MacOS Mavericks 2015-004 has a bug where an incorrect certificate named “VeriSign Class 3 Public Primary Certification Authority - G5” is placed on the user’s login keychain. The fix is to run Keychain Access and remove it. Note: remove the one in the login keychain, not the System Roots.

Update 2: 2015-004 doesn’t put the entry on the login keychain, something else put it there earlier. 2015-004 does seem to change something though that triggers the verification problem. The fix is still to remove the key from the login keychain, I just don’t know what put it there in the first place.

Update 3: turns out it’s Cyberduck that’s writing the certificate entries.

This error seems really serious to me. Macs that are affected can’t get new software updates. Also Chrome will refuse to load any websites with SSL certs signed by that VeriSign certificate, including Apple’s own sites. Safari will load the site but will display SSL errors. Apparently Chrome is more strict in enforcing SSL security.

(I thought it was particularly interesting that it was impossible to get Chrome to visit Twitter. Twitter only serves HTTPS, not HTTP. And they have HSTS enabled which means Chrome will refuse to load a page without a working SSL certificate. Well that all succeeded, but boy was that a bad experience.)

Here’s some links with more discussion: Ask Different, Security StackExchange, Apple forums. I exported the two Verizon certs that were on my login keychain that were the problem, there’s a zip file here along with some screenshots of failed SSL certs. (That file won’t be online forever.)

I seem to be hitting a serious bug like this in MacOS every couple of months. Along with some broken-by-design things like their SMB client and I really am tempted to try going back to a Windows desktop. Or maybe Linux, if it weren’t so damn ugly.

Update 1: thanks to Ned’s suggestion in the comments I tried figuring out how those VeriSign certificates got in my keychain in the first place. I still don’t know, but looking at backups in Time Machine I can see it was placed there sometime between 2015-01-17 and 2015-02-23 13:48 (the two backups I have from before and after.)
$ grep -i verisign */Macintosh\ HD/Users/nelson/Library/Keychains/login.keychain

The Mac was turned off from 2015-01-08 until 2015-01-17 and again for 2015-01-21 until 2015-02-23. It seems likely the VeriSign entry ended up on my keychain when I turned the Mac back on. But it would have happened quickly; I entered the house at 13:42 and it’s in the keychain at 13:48. And my network is very slow. It could also have happened sometime between 2015-01-17 and 2015-01-21.

FWIW there’s a bunch of updates that installed a few hours after the keychain update, 2015-02-24 04:00 AM, including Security Update 2015-001 and Safari. But the keychain entry precedes those. Between 2015-01-17 and 2015-02-23 I only have a bunch of updates from “Google Voice and Video” and one from Seil, a keyboard kernel hack. Also FWIW I’m not given to manually tampering with my keychain nor blindly approving requests to manipulate it.

Mac fan control

My ~3.5 year old iMac is making noise. Just a small noise, but it’s high pitched and annoying. Something mechanic, presumably a fan bearing. So I started trying to isolate the source of noise. It isn’t the internal spinning drive, you can turn it off by unmounting all the volumes. I’m not using the optical drive. So maybe a fan?

The tool to test a Mac’s fans is smcFanControl, a simple tool to read the temperature and fan speed settings and alter fan speed. When you run it it requires root access, then goes into your menubar. You can set the minimum fan speed for each fan separately. It works pretty well. I used it to run each fan at full speed and crikey, my Mac sounds like a vacuum cleaner. Never heard those fans run before! Didn’t really notice a change in the sound but it’s hard to be sure. Maybe my optical drive fan is to blame. Unfortunately you can’t set turn the fans off entirely; the apps docs say this is possible but not enabled for safety. A quick search didn’t turn up any easy hacks, either.

On a side note, apparently there’s no good CPU/GPU/Memory burn-in tool for Macs. At least not a free one. The #1 suggestion from Google searches is “run yes > /dev/null”. Which, well, that works a tiny bit but it’s not even exercising the whole core of a single CPU, much less the whole system. There’s a bunch of good tools that run under Windows, too bad no one’s bothered to port one. The core load generator doesn’t need to change (much?) but the GUI is a problem.

MacOS security update only for Yosemite

Apple designed MacOS with an API that lets you escalate privileges from any user to root without proper authentication. No, really. This leads to CVE-2015-1130, details not yet published. It’s a pretty severe bug from the looks of it; not quite a remote exploit, but once an attacker can run code on your system they are root. Apple pushed a patch for it this week. But only to Yosemite.

The shape of the bug is really ugly too. It looks like Apple put in some weird backdoor API for stuff to escalate to root, so you can run Preferences or the like as a normal user. And they tried to lock that down in various ineffectual ways, like userspace binaries checking if they are running as root, but left the API in the kernel. Ugh.

Ubuntu on a Mac Mini

I finally gave up on MacOS for a Mac mini server I have and wiped it and installed Ubuntu 14.04LTS. It mostly went pretty smoothly, Ubuntu makes bootable images for Mac hardware that work fine off of USB keys. And I just wiped the whole disk and removed any vestiges of the MacOS boot loader, I imagine it’s a bit trickier if you care to preserve MacOS.

The one real problem I ran into was the new system hung at boot right after adding swap. That error is a red herring though; really it’s hanging trying to change video modes. Dumb, particularly the lack of a useful console message. The solution is to add nomodeset to the kernel command line in GRUB.

Also a few minor problems. The WiFi adapter doesn’t work, of course, although maybe the non-free drivers I was advised I could install fix that. Ubuntu’s automagic partitioner doesn’t give you a way to resize the swap partition, you’re stuck with it being the size of system RAM. And it did enough other magic things on repartitioning I was afraid to try to roll my own.

I’m pretty unimpressed with how slow this Mini is, now that I have an OS I understand on it. The Plex server seems OK, and it can transcode 1080p video at 5x real time or better. But trying to rsync 300GB of files over gigabit ethernet to it basically pegged the machine; the poor SSH process with the network connection was using 50% CPU even after I told it to use arcfour encryption, supposedly the fastest available. And terminal responsiveness was like 10 seconds at a time, although maybe it’s partly the Linux scheduler to blame for that. Anyway the system has a i5-3210M CPU which apparently is pretty weak, despite having 2 honest cores in it. Will be fine for a file server but I’m glad I built a beefy compute server for real work.

MacOS sshfs: improving Finder performance

I’ve been using sshfs to access a Linux volume about 30ms away from where I am. I don’t expect this to be lightning-fast, but Finder was acting very slowly. Like 10 seconds to open $HOME, a directory with 143 files in it. Every directory took a few seconds the first time it was opened in Finder, even though network traffic was tiny. Presumably lots of little synchronous reads.

Long story short, the solution is:

-o noappledouble,noapplexattr

Using this in OSXFUSE sshfs is a lot faster. Maybe 2 seconds for that Finder window, not 10. The key feature is “noappledouble”. This tells sshfs to completely deny all access to any ._ and .DS_Store files. Not only does that keep this garbage out of your Linux filesystem, it avoids lots of network round trips as Finder tries to open them. (Not sure why a client cache doesn’t fix that, but oh well.) That option can cause Mac system calls to fail, and while I’m not certain I think the noapplexattr may help with that.

The advice to use these options is scattered all over the net, most of it seems to be a cargo cult inspired by this 2008 post. I did not find good docs for what we should be doing here in 2015, the best I could find are these old docs for MacFUSE which at least explain what the options do. I’m too lazy to read the source.

 

NFS: Ubuntu server, MacOS client

I’m finally fed up with Mavericks broken SMB implementation. It’s appalling how bad it is. For awhile I had it working by forcing SMB 1 via cifs:// share naming, but that stopped working. Suddenly SublimeText and TextEdit were creating files with mode 0764, god knows why. MacOS touch was creating 0644 as expected. Anyway, fed up, it’s broken, so I’m going back to NFS. (Apparently Yosemite is shipping a new SMB 3 stack, maybe that’s better? Yosemite is broken in so many other ways though...)

I used NFS 3 years ago and those notes still apply. However, some changes.

Ubuntu server: as simple as can be. The wrinkle is that unless you want to get all fancy with Kerberos or idmapd or something user IDs don’t get mapped. Last time I just changed my numeric IDs on my Mac to match the Linux server. This time I’m trying something new, this cheese in /etc/exports:

/home/nelson 192.168.0.0/24(rw,insecure,async,no_subtree_check,all_squash,anonuid=30193,anongid=30193)

I’m abusing NFS anonymous ID mapping to force all requests to look like user ID 30193 and group ID 30193, my personal IDs on my Ubuntu box. It looks wrong on the Mac client, and it’s not appropriate for a multiuser server. But it gets the basic job done.

Mac client: more confusing now. Mavericks removed the graphical NFS configuration tool that I used to use. However the default automounter setup is not so bad. The path /net/ub/home/nelson is magically the NFS share ub:/home/nelson and seems to automount usefully. I think it’s using NFSv3. Haven’t needed to tune any parameters yet.

It wasn’t my primary goal, but as a bonus I get better speed out of NFS. The SMB 1 implementation seemed limited to about 10 megabits / second when writing to the server. NFS is running at the full 100 megabit link speed.

MacOS: sshfs and FUSE

When I first started using Macs the situation with FUSE, the user-space filesystem shim, was a mess. But it’s stabilized now and it appears OSXFUSE is the winner. Their binary packages for OSXFUSE and sshfs work just great. Here’s some very n00b friendly instructions.

sshfs -C ub:/home/nelson /Volumes/ub

I’m not sure if it’s possible to automount. sshfs needs my ssh credentials which aren’t available at login. probably not worth the hassle.

Unfortunately git prompt does not work well with sshfs; if you’re in a git-controlled directory it tries to do a whole bunch of file stats over sshfs, which is slow even though sshfs has some caching.

unset PROMPT_COMMAND

Even better, I use liquidprompt which lets you disable git in certain paths via LP_DISABLED_VCS_PATH, for just this reason.

The other drawback with sshfs is Finder is very slow. MacOS seems to do a lot of work on every single file, even when all it ends up displaying is the filename.

Did MacOS 10.9.5 break SMB again?

I had Samba working more or less right between a Linux server and a Mac client. But recently all the files are showing up as permission 700 on the mac client, creating symlinks makes bogus files on the server, etc.

Unfortunately I don’t know what broke it. I upgraded Ubuntu 12.04 to 14.04 and kept my old smb.conf file. I also updated to MacOS 10.9.5. Either could have broken it.

On the Linux box, I started with a clean fresh default config file from 14.04 and just added some minimal stuff for myself. The old config file had some cruft like “map archive” that may or may not have been good. I mean, it used to work, but who knows. Anyway the new config file looks correct, but with Samba you can never be sure.

On the Mac, 10.9.5 includes an ominous patch note “improves the reliability of accessing files located on an SMB server.” Given how badly Apple has broken their Samba client in the past, I don’t trust any changes.

My work around now is to mount the fileshare as “cifs://ub/” on the Mac instead of “smb://ub/”. Apparently this forces MacOS to use an earlier protocol and implementation that’s not as broken in Mavericks.

Windows is worse than MacOS

I bitch about MacOS a lot, complaining about the rough edges in what is mostly a good product. But MacOS really is bad at one thing: desktop gaming. Some times I’m tempted to switch back to Windows just so I can play game. This week I was desperate to play Civilization: Beyond Earth before the Mac port is finished. So I booted my Bootcamp partition into Windows for the first time in two years.

Wow, what a terrible experience. Pretty much all the badness centers on software management, installs and upgrades. I was prepared for the initial thing to take forever; it was a two year old Windows 7 image, after all. Some 60+ updates and a few reboots later and all was set up. That wasn’t so bad really.

What was bad was installing software with Steam. In particular, the way you have to “install VC redist”. Steam makes the wise choice to require a separate install for every game, basically the 2014 solution to the 1995 problem of DLL hell. But the installers are fucking ridiculous. It takes 30+ seconds to do the install. What the hell is it doing? Copy a few files, maybe update a registry key or two, and you should be done. And for some reason I had to install like 15 of these for Steam the first time, then another 4 for Civ:BE.

The Bootcamp experience is not good either. The display drivers don’t work perfectly, for instance the sleep mode doesn’t shut the back light off. And I’m scared to try updating the 3 year old driver. You can’t use the vendor display driver, you have to use Apple’s, and all Apple ships is one giant install disc every once in awhile. Two, actually, you have to pick the release based on knowing what model iMac you own. Only iMac’s don’t have model numbers, so you have to remember the year you bought the thing instead.

Windows itself is still mostly, well, Windows. It’s funny how much I’m used to the Mac way of doing things now. I miss my menu bar. I can never tell if Chrome is running and just has no windows, or what. I even hacked the registry to enable reverse mouse wheel. And the stupid system is still prompting me for urgent reboots by switching me out of my full screen game, interrupting me with a popup dialog.

MacOS file sharing and CPU usage

Why does MacOS file sharing take so much CPU? I’m rsyncing 30GB of files from one Mac to another. Using MacOS file sharing, 10.9.4 server and 10.9.2 client. The client is a MacBook Air and the fan is whirring away. Some kernel_task associated with the copy is taking 50% of one CPU; the rsync processes are taking another 13%. It’s not awful, but that’s a shitton of CPU for doing something that should be low impact. The iMac server is using 15% of a CPU to serve the files too.

MacOS dd timings

I need to clone a 2TB USB disk on my Mac. Going to use dd. What’s the right block size?

The bigger the better, apparently, but there are diminishing returns. “bs=128k” is good; reading from USB and writing to /dev/null that gives me 38Mbytes / second, which IIRC is about the rate for a 5400 RPM disk. 16384 gives about 20Mbytes / second. The default 512 byte blocks gives 1.2Mbytes / second.

I love that the default is 30x slower than maximum. The legacy of SysV’s 512 byte disk blocks is never going to end.

$ dd if=/dev/rdisk2 of=/dev/null bs=128k count=10000 skip=1m
10000+0 records in
10000+0 records out
1310720000 bytes transferred in 34.233990 secs (38287094 bytes/sec)

Update: that was for timing disk reads. Disk writes were slower, a test copy from one USB disk to another on my iMac showed 17 MB/s, which would take 32 hours to copy a 2TB disc. I thought at first that was because writes are slow but then I remembered the iMac is USB 2.

My Linux box has USB 3 and can read the disk at 100 MB/s. Shouldn’t have trusted my memory about disk speeds! And a copy from disk to disk on my Linux box is showing 117 MB/s, or about 5 hours to do the copy. Bonus: I trust Linux not to be doing something weird behind my back with the disks.

The full 2TB copy ended up taking about 6.5 hours, for an average rate of 85 MB/s. I forget slow the end of a disk is.

softwareupdated (MacOS sucks)

I’ve lost track of all the confusing ways MacOS updates itself. But one of them that keeps biting me is that it insists on updating iTunes. I don’t want iTunes, I’ve set it to mode 000, I don’t want to waste my limited bandwidth downloading copies of it. Sometimes a popup appears in the upper right saying “updates available Install?” and there’s no way to see what it will install. So as a sucker I click Install, and suddenly here I am downloading iTunes.

The best part of all this is there’s no way clean to cancel the update. The App Store program will show the update progress bar, but the Cancel button does nothing. Using MacOS’ excellent Activity Monitor I can see the process doing all the downloading is softwareupdated. It ignores or catches ordinary kill signals. My only option seems to be a kill -9. Awesome.

WebGL vs Shutdown (MacOS sucks)

I went to a WebGL test page that warned it might crash your machine by drawing lots of polygons. Boy it wasn’t kidding. Locked up Chrome, locked up the Mac graphical shell. I could log in via ssh and the machine was fine, not even anything spinning CPU, but couldn’t kill the Chrome processes. kill -9 did nothing. So then I rebooted. It didn’t reboot either, the best MacOS could do was to shut down sshd so I couldn’t even log into my machine.

It’s pretty awful that some Javascript can kill all of MacOS. Chrome should know better. V8 should know better. WebGL should know better. OpenGL should know better. The Mac graphical shell should know better. The Mac kernel really should know better, because you really can’t count on anything else to. All fail.

Remote file system bad display (MacOS sucks)

Finder’s access to remote filesystems will sometimes show stale data. I’m copying a 2.5GB file to an SMB share (Linux samba). While copying I look at a folder, then click the little down arrow to open the subfolder in the window. It shows no contents, it must be an empty folder! So go to delete, and then it pauses saying “deleting 5 items”. Ha  ha, joke’s on me. Cancel the delete, try again. This time wait 3–5 seconds for the file content to list, and poof there are the files now. At least I cancelled the delete in time.

I’m not complaining that the remote filesystem is slow, particularly when a big copy is happening. No. I’m complaining that Finder is showing incorrect information.

 

Directory symlinks (MacOS sucks)

Try this on a Mac

cd /tmp
ln -s ~/Docum <press TAB>
ln -s ~/Documents/ .
ln: ./: File exists

Trollface

 

Yes, MacOS “ln” is too stupid to understand that if something has a trailing slash you probably meant to symlink the directory with that name, not the implicit “Documents/.” name. And bash completion is just helpfully providing slashes because 99% of the time you want them when talking about directories. Of course this works fine on Linux; another legacy of MacOS being based in SysVile.

(To be fair the with/without trailing slash thing has always been ambiguous in Unix. rsync even assigns different semantics to the two names, confusing me every single time.)

 

Steam (MacOS sucks)

The Steam client on MacOS has always been terrible. I mean it’s badly designed as a product, but then also the implementation is terrible. Basically it’s 90% just showing a web page, but that’s always been slow and cranky and broken.

But today takes the cake. Because running Steam has brought my whole system to its knees. Beachball cursors, 10 second delay switching apps, 20 second delay to launch Console.app. Total trash. And as bad as Steam is, the real blame falls on MacOS for freezing because one app is badly behaved. I don’t see anything obviously wrong running top or activity monitor. Is the graphical shell single threaded or something? Steam wasn’t even doing much, just sitting there showing me a web page and downloading an update in the background.

To be fair, I think part of the problem was memory. When I killed Steam and relaunched it a bunch of memory freed up and things are better. So maybe that’s a Steam bug afterall. No Unix kernel schedules memory contention well.

 

 

MacOS finder is garbage

I’m looking at a Finder window for the folder /Applications/League of Legends.app/Contents/LOL/Logs/Network Logs. It looks like this

Screen Shot 2014-05-18 at 8.18.07 PM

Then I open a shell in that folder and run ls -l. It looks like this

Screen Shot 2014-05-18 at 8.18.16 PM

Notice how there are files from May 18 that don’t show up in Finder? Yes, the fucking Mac interface can’t even list the files in a local folder correctly. I see this garbage all the time, the Finder window caches some sort of state and doesn’t resync correctly. There’s not even a Refresh option. Perhaps in this case it’s complicated by the fact that some game is writing new files to the directory, maybe it’s using some odd API? But then that’s what the Unix kernel is for; one single creat() system call. And Apple can’t get it right.

Forcing a Finder relaunch fixes it, of course.

Fundamental stuff in MacOS is broken. It’s really awful.

 

go on Mac makes static binaries!

I’ve complained a bunch about how MacOS doesn’t let you compile static binaries; you absolutely must dynamically link libc.

go doesn’t have that problem. go doesn’t use libc. The binaries “go build” creates appear to be truly statically linked, at least according to “otool -L”. Although apparently there’s another compiler “gccgo” that does link with glibc, or else I misunderstand.

Bonus fact: if you strip a Mac go binary, it segfaults when you run it.

Why does Apple hate Unix?

I upgraded an iMac to Mavericks, just so I could share binaries with the other Mac I have. Now I’m undoing the damage the upgrade did.

I have to download and reinstall the compiler. With the mysterious “xcode-select --install”. Because according to Apple, Unix computers don’t come with compilers. And if you have one they go in and delete it on upgrade. At least there’s a standalone command line compiler now, it’s better than having to get the whole Xcode IDE bloat.

I have to download and reinstall the X server. I don’t begrudge Apple not shipping X11 by default, it’s pretty awful and dated. But I have a fully working XQuartz on my system. Why delete it when I upgrade?

I’m starting to flirt with the idea of giving up on MacOS on my desktop. It’s bad at games, and it’s bad at Unix development. It is good at ordinary consumer use though, web browsers. I kind of wish I had a way to run Windows for games, ChromeOS for web browsing, and Linux for development. All on one machine with transparent interaction.

MacOS binary incompatibility

I keep forgetting this; MacOS binaries are not compatible with earlier MacOS versions. I built a bunch of Homebrew stuff on 10.9 and copied the binaries to a 10.8 machine. And get awesome errors like

dyld: lazy symbol binding failed: Symbol not found: ___strlcpy_chk
Referenced from: /usr/homebrew/bin/rsync
Expected in: /usr/lib/libSystem.B.dylib

Some sort of library / linker design choice, I guess. It’s as baffling as Apple’s decision not to allow static linking, because the kernel API may change so you must dynamically link to libc to mediate.

Homebrew has a way to build with --universal, but I think that’s more for 32 bit compatibility than minor OS revisions.

 

Homebrew observations

You can’t move a Homebrew binary directory. I installed Homebrew in /usr/homebrew2 and then renamed that to /usr/homebrew and a bunch of stuff broke because it had the path /usr/homebrew2 baked into it. bash-completion, also python.

Many Homebrew packages don’t compile cleanly. I ran into three: mg, unison, and ggobi. I filed bugs and got prompt responses (and a patch for ggobi in 12 minutes!), which is pretty great. OTOH it feels to me like Homebrew doesn’t have any sort of automated build-and-test setup for packages, these were all really simple bugs that anyone installing the code would hit. Some basic integration testing would go a long way.

I’m very grateful to Homebrew but the whole project feels pretty ad hoc and brittle to me. No surprise since it started out being such a simple thing. And simple is good! But I think at this point it’s evolved into needing to be a serious package manager, but hasn’t yet evolved all the serious package management. I wish we’d just use dpkg on MacOS instead. Fink is exactly that, but my experiences with it have been bad.

Starting anew with a clean homebrew install. Note I’ve already set PATH and BREW to use /usr/homebrew, the non-standard location

sudo mkdir /usr/homebrew
sudo chown nelson /usr/homebrew
cd /usr/homebrew

git clone https://github.com/Homebrew/homebrew.git
mv homebrew/* homebrew/.git* .
rmdir homebrew

brew tap homebrew/dupes
brew install atk autoconf automake bash-completion cairo clens cloog faac ffmpeg fontconfig freetype freexl gdal gdbm gdk-pixbuf geos gettext gfortran ggobi giflib git glib gmp gobject-introspection gpp graphicsmagick grc gtk+ harfbuzz icu4c iftop isl jpeg jq json-c lame less libffi libgeotiff liblwgeom libmpc libpng libspatialite libtiff libtool libxml2 lzlib makedepend mp4v2 mpfr nmap node objective-caml openssl optipng ossp-uuid p7zip pango pgdbf pixman pkg-config postgis postgresql proj pv python readline rsync sqlite texi2html unrar wget x264 xvid xz yasm

brew install mg
brew install unison

QGIS install on Mac

It takes roughly 60 UI actions to install QGIS on a Mac. And then you only get QGIS 2.0, not the latest 2.2. The problem is the official install is KyngChaos’ packages. They’ve done a great job over the years packaging Python and GIS software for Macs, but it’s seriously old school stuff. 4 different framework libraries have to be installed first by hand, each one individually packaged in a PKG installer script inside a DMG, then you install QGIS itself. Each installer takes many mouse clicks to install and also requires the root password.

In some sense KyngChaos is doing this right; the libraries he installs are useful for other projects, and this way you see all the license and components. But it’s really user unfriendly. It’d be nice if someone built a single self-contained QGIS.app that could just be dragged and run anywhere.

Mavericks broke SMB

Apple broke file sharing in MacOS Mavericks. I started finding the problem when I got a new iPhone and was going through the hell of setting up music on it via iTunes. Nothing worked and I finally started over with a new iTunes library, only to find I couldn’t add songs from my SMB network share (an Ubuntu box running Samba). The files showed up fine in Finder, and if I copied them to my desktop I could add them to iTunes. But trying to add them right off the fileshare resulted in nothing happening; no errors, no console logs, nothing.

A lot of research later and I learned that Mavericks has a brand new SMB2 implementation, and apparently it’s broken. In complex and subtle ways, maybe worse using Samba as a server than Windows. Awesome! As usual there’s a lot of cargo cult thinking for bugs like this, but this Apple discussion and this ZDNet article were particularly useful.

The recommended fixes are two ways to fake out MacOS to not use the new broken SMB2 implementation and instead fall back to the slower-but-stable SMB1 implementation. I found I also had to add “log level = 0” to my SMB server configuration to make this work (previously no log level configured). Yeah, there’s no way that makes sense, but it only started working when I had debug logs on (level 2) and then if I removed the line entirely it stopped working, but level 0 works. I’m too angry to spend more time trying to figure out what’s really going on.

It is so, so frustrating when Apple breaks basic Unix services that have been working in the past. Doubly so if there’s absolutely no error logging, and triply if the bug only shows up in some awful piece of client software like iTunes. Just terrible all around.

Building unison on homebrew/mac

I thought I’d try Unison out, it’s a directory sync system that’s a bit like rsync but specifically targeted at keeping filesystems in sync in both directions. May solve my problem trying to keep two Macs together with no reasonable Internet to just Dropbox or whatever. OTOH, Unison hasn’t had much development in years. And it’s written in OCaml, oy.

Anyway, it doesn’t build right in Homebrew. Turns out the Makefile is trying to be clever with the variable $NAME and it was picking up my shell environment variable. A simple “unset NAME” before installing seems to have fixed it. Details at https://github.com/mxcl/homebrew/issues/11862

MacOS ._* garbage

MacOS has this terrible habit of littering filesystems with ._ files (for the search engines: “dot underscore files”). Apparently Apple uses these files for some sort of extended metadata, extending Apple’s track record of overcomplicating file systems that goes back to the bad old days of Resource Forks. (Remember BinHex? Good times.)

OK, to be fair, having some out of the way place to put extra data around files is sometimes useful. What I hate is the way the ._ garbage breaks other tools. My latest example is rsync --delete; it won’t delete a directory with a ._ file in it. Somehow in my trying to sync up directories between two Macs via a USB disk I’ll end up with some stray ._ files that then escalate to whole stray directories full of ._ files.

 

MacOS doesn’t support static binaries

clang -static -g -o dump1090 dump1090.o anet.o -L/tmp/rtl-sdr/build/src/ -L/usr/homebrew/Cellar/libusb/1.0.9/lib/ -lrtlsdr -lpthread -lm
ld: library not found for -lcrt0.o
clang: error: linker command failed with exit code 1 (use -v to see invocation)

/sadtrombone. Or what’s the emotion for “Apple’s kernel team is laughing at you”?

Apple has a reasonable explanation:

A statically linked binary assumes binary compatibility at the kernel system call interface, and we do not make any guarantees on that front. Rather, we strive to ensure binary compatibility in each dynamically linked system library and framework.

So basically they moved the guarantee of compatibility from the kernel interface down into the library interfaces. I guess that sort of makes sense, only it’s different from every other Unix ever and makes simple things hard. Too bad. I have some 10 year old Linux binaries I can still run because I thought to statically link them at the time.

Next best thing is to statically link everything but the system library.

$ otool -L dump1090
dump1090:
	/tmp/rtl-sdr/build/src/librtlsdr.0.dylib (compatibility version 0.0.0, current version 0.0.0)
	/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

OK, so librtlsdr was dynamically linked. I’m not sure how to tell clang to statically link just this library. I bashed around listing .a files on the linker command line and ended up here:

$ clang -g -o dump1090 dump1090.o anet.o /tmp/rtl-sdr/build/src/librtlsdr.a /usr/homebrew/Cellar/libusb/1.0.9/lib/libusb-1.0.a
Undefined symbols for architecture x86_64:
  "_CFDictionaryCreateMutable", referenced from:
      _usb_setup_device_iterator in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)
  "_CFDictionarySetValue", referenced from:
      _usb_setup_device_iterator in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)
...
  "_objc_registerThreadWithCollector", referenced from:
      _event_thread_main in libusb-1.0.a(libusb_1_0_la-darwin_usb.o)

Apparently linking by naming the .a suppresses the linker’s walking of library dependencies, so now I’m not getting some of the basic system stuff expected by libusb. I tried exploring what libraries were needed with otool -l and failed. I’m doing this wrong.

MacOS broken build between versions

Well this is fun; MacOS binaries built on MacOS 10.8 don’t necessarily run on 10.7. I tried copying some homebrew binaries between machines and got the useless error message “Illegal Instruction: 4”.

Turns out this is working as intended; by default clang is happy to build binaries that only work on the current OS, not older versions. Good discussion here. The fix is to build with -mmacosx-version-min=10.5 (or however far back you need to go). Homebrew doesn’t build with this flag, I imagine because their idea is you recompile code on every machine. That gets tedious with multiple macs on a slow network.

Breaking binary compatibility is a stupid thing.

 

Uninstalling Evernote on a Mac

The official uninstall instructions for Evernote on a Mac are incomplete. They just say “trash the Application”. But that leaves behind a launchd entry that every 10 seconds tries to launch EvernoteHelper, now missing, and spams the syslog and creates lots of useless crash reports.

Anyway, the fix is to run launchctl remove com.evernote.EvernoteHelper as the user you installed Evernote as. (Not root!)

launchctl/launchd is a total mystery to me. It seems awfully complicated. “launchctl list” and “launchctl bstree” are helpful commands for inspecting the state of what’s trying to launch.

MacOS bullshit

I just had to reboot my Mac because a remote filesystem mount failed. I mounted a disk on my iMac via AFP from another Mac last night, over my WiFi network. Then my iMac went to sleep. This morning the remote disk was still mounted, so I went to open it and then Finder locked up, the lovely spinning wheel of death. (Do they still say “beachball”?) But at least all my other apps were working. Then I tried to force quit Finder (er, relaunch), and the entire fucking Mac locked up.

The big fail here is that Finder still has its talons in the graphical shell of the Mac, and file system browsing can lock up the whole machine. The small fail is it’s nearly 2013 and we still don’t have remote filesystems that are robust to failure. I miss the async option on NFS; it caused some problems, but at least it didn’t lock up your whole computer.

Update: after rebooting I remounted the file system and then copied a single 800 megabyte file over by dragging it in finder. I then tried to drag a second file over and had to wait, mouse button held down, for 45 seconds while Finder’s little wheel spun. Because apparently the entire UI locks up while waiting for some buffer to drain in a bulk, low priority file copy. Apple’s handling of remote mounts, even AFP mounts from other Macs, is absolutely terrible.

 

Setting default print options on a Mac

My mostly-nice color inkjet has two tanks of black ink; a big one for B&W documents, a small one for color documents. By default my Mac sends all its jobs in color and the printer isn’t smart enough to realize that the whole document is monochrome so really, the cheaper big tank will work just fine. I want to default printing to grayscale.

Irritatingly, you can’t do this with the obvious way in a Mac. You can create new printer option sets and save them as new profiles, but there’s no way to change the default profile.

But there is a way, via the CUPS web interface hiding underneath MacOS. It never occurred to me that this would be there! The instructions in the linked blog post worked just great for me, I even have the same kind of printer. Two wrinkles.. I had to choose the second of the two printers, the first had no print options associated with it. And the “Greyscale Printing” option appears twice, I had to set both to make it work.

This may save me literally dollars a year.

 

MacOS top: “stuck” means “uninterruptible”

MacOS’ version of “top” reports a weird process state; “stuck”. According to top many of my processes are “stuck” including Postgres while it’s completing a table scan, and Growl, and many Google Chrome subprocesses. But checking the top sources indicates “Stuck” really means TH_STATE_UNINTERRUPTIBLE, which I believe is what ps reports as process state “U”. I’m guessing this is what Linux calls “D” for “Device Wait”. In which case, in most cases the process is fine, it’s waiting for some I/O to complete.

While I’m here, is there any good reason MacOS top defaults to sorting by process ID? I have to type “ocpu” every time to get it to sort by cpu.

 

Trying out Riak on MacOS with Homebrew

Homebrew install notes

I decided to try out Riak on MacOS, using Homebrew to install. Here’s some rough notes.

“brew install riak” worked. However, it didn’t leave you the Makefile you need to do “make devrel” in order to set up the 3 node test cluster. So I interrupted Homebrew during the install, copied the patched sources, did “make all rel devrel” in my own source tree, then copied the “dev/dev?” directories off. Still using the Homebrew binaries. Lot of work for 4 lousy config files :-P

The Python client you want is riak-python from Basho. Unfortunately “pip install riak” doesn’t quite work, because Pip first tries to install protobuf and there’s a three year old bug open on Google’s protobuf client about how it doesn’t install right in Python. Some helpful soul forked Google’s library and his version can be installed witih pip install “git+http://github.com/rem/python-protobuf.git@v2.4.1#egg=protobuf”

With that you have a working Riak and Python environment that you can use to work with the tutorials online.

Insert notes

Trying to insert my weather data: millions of rows of 4 tuples: (station name, timestamp, speed, direction). Testing with 3 Riak nodes running on my single fast iMac. This data is not a good match for document oriented stores: I already learned that Mongo was not good and expect Riak not to be, either. Still, it’s real data I have and I want to try it.

Wow, is Riak slow if you just use it as a naive user. 3 node cluster running on a fast iMac, inserting 45,000 records one at a time with a store() between each took 120 seconds.

Some write optimization.. there appears to be no batch insert in the Python library I’m using (although see this). Riak’s exposure of consistency via the W parameter is really neat, but what I need is to commit 10,000 records at once. I’ve tried optimizing my writes (ie: windData.store(w = 0, dw = 0, return_body = False)). Switching from HTTP to Protocol Buffers gives about a 4x increase. Still, no matter what I do, I can’t do better than 1900 records / second. Compare Mongo’s 30,000 records / second or Postgres’ 10,000 rows a second. Am I doing something terribly wrong?

Sadly, I get a 10% speed increase (from 1900 to 2100 records / second) if I only have one node in the cluster. Not useful in the real world, but interesting.

With just a single node running Riak seems to use about 1 kilobyte / document (650,000 rows, 720 megs on disk). Not good, since the docs themselves are like 20 bytes of data. Compare about 50 bytes / row for both Postgres and Mongo. With 3 nodes the combined disk usage is about the same size; I’m surprised, I thought the default config was three copies of all data.

I sure miss the ability to drop a whole bucket. I don’t really have a way to reset my database while testing.

Query Notes

Once again I petulantly note that raw map/reduce is awfully low level if you just want a damn SQL function. Of course it gets wonderful when you want to query using 100 machines and a distributed data store.

Trying to list 50,000 keys in a bucket (via /keys?keys=true) kills both Chrome and curl: they complain the HTTP header returned is too big. Also the docs warn you to never do this in production. In other words, queries over the whole dataset are difficult. I think you need to use links or some extra indexing system to do queries. Riak has a search capability, btw, but it looks more full text oriented than simple data iteration.

I wrote some simple mapreduce code to do “select count(*) from bucket” and “select count(*) from bucket where parameter > 30”. It takes 16 seconds to run over 60,000 rows, that’s just unacceptable. Also the answer it gives is wrong; 43561 instead of 59072. Huh. While it’s cool I could run this query while nodes were dropping out, it’s uncool that the answer it gave varied as data was moved around.

I don’t think I have a bug in my query code, but you never know... Here it is.

import riak

client = riak.RiakClient(port=8081, transport_class=riak.RiakPbcTransport)

# select count(*) from KSFO
query= client.add('KSFO')
query.map("function(v) { return [1] }")
query.reduce("Riak.reduceSum")
for result in query.run(): print result

query = client.add('KSFO')
query.map('''function(v) {
    var data = JSON.parse(v.values[0].data);
    if (data[1] > 20) {
        return [1];
    } else {
        return [];
    }}''')
query.reduce("Riak.reduceSum")
for result in query.run(): print result

Evaluation

I knew this data was a poor match for Riak and now I’m doubly sure. The 1k / row is the real problem. I don’t think Riak is bad or anything, quite the opposite. Just curious how it feels to try it out on some data.

I really admire how Riak is distributed to the core. Most datastores design for a single server, then later add replication and partitioning. It’s a total mess. Riak started distributed, and if they did it right it should be significantly more robust for real network usage. Also for parallel data analysis. I also think it’s freaking amazing how you can do “riak-admin join” and “riak-admin leave” and the data transparently repartitions while the cluster is still up and serving write requests.

I wonder how robust Riak is in recovering if a node drops offline without a clean shutdown, then joins later with inconsistent data? The docs on CAP mention some voting and validation protocols, so they’ve thought about it. More a question of convenience than usability.

Postgres 9.0 to 9.1 upgrade with Mac / Homebrew

I just had a terrible time trying to upgrade PostgreSQL 9.0 to 9.1. I finally gave up and am still running the old one.

pg_upgrade is the recommended upgrade path. It’s pretty ugly, and among other things requires you have the old server binaries around. But it looks like it’d do the job. I had a few minor problems, like I ran “--check” and the check failed but left something around that made Postgres think a server was running. (Fortunately pg_ctl start just ignored that and started a server anyway, then pg_ctl stop fixed it.)

Then I hit a bigger problem: PostGIS I’ve got that installed in my 9.0. I *think* it’s installed in 9.1, too, but I can’t be sure with Homebrew. In any event pg_upgrade doesn’t think it’s there so I’m SOL for now.

An alternative is to do pg_dump on the old server, then pg_restore on the new. I suspect that’s what pg_upgrade does behind the scenes anyway. And I still have to resolve my PostGIS problem.

Notes on getting TileStache renders working on MacOS

Personal work notes for this project I’m working on. Mac DLL hell included. Unlikely to be of interest to any unfortunate reader who found this post.

I’m trying to run some tile generation software that generates odd TIFFs. The TIFFs have two separate images in one single file. This is a legitimate TIFF but it’s unusual and I’m having a hard time producing it on my Mac. The exact same end code works fine on Linux.

There’s a bunch of software involved here. Python, gdal, boost, MapNik, Cairo, swig, TileStache, ... When it’s all mashed up the code I’m running is basically a Python program with a lot of bindings to geo and image C libraries, using boost and swig. Ie: a big fucking hairball.

If I use MacOS Lion’s version of libtiff, the code all runs fine but the images it produces are corrupted. Same error as this discussion. gdalinfo can’t load them:

gdalinfo out/10/000/163/000/395.tiff
ERROR 1: out/10/000/163/000/395.tiff:Failed to allocate memory for to read TIFF directory (0 elements of 12 bytes each)
ERROR 1: TIFFReadDirectory:Failed to read directory at offset 52744
gdalinfo failed - unable to open 'out/10/000/163/000/395.tiff'.

If I use homebrew’s default libtiff (3.9.5) the code hangs. Poking at it with gdb I see the program is spinning at 100% CPU deep inside some error binding between libtiff, Python, and either Boost or Swig. Yuck!

If I build my own tiff-4.0.0beta7 in homebrew and use it, it runs and produces the same corrupted TIFFs as Lion. (To build in Homebrew, you have to edit the libtiff.rb formula and add an option to configure, “--x-includes=/usr/X11/include”. Otherwise, it can’t find some of the GLheader files when compiling.). tiff-4.0.0beta5 is no better.

A big confounding issue has been getting the Python environment right in Homebrew. More notes on that here. I think everything’s working anyway, various Python and gdal programs do, but you never know.

Another confounding issue has been compiling things correctly. The transition in C compilers on Lion makes a mess. Homebrew gamely tries to use LLVM but some stuff only works with gcc-4.2 (including Numpy). I was worried that mixing the two compilers might have been causing problems, so finally rebuilt everything with just gcc using this environment:

export HOMEBREW_USE_GCC=true
export CC=gcc-4.2
export CXX=g++-4.2
export FFLAGS=-ff2c
export HOMEBREW_BUILD_FROM_SOURCE=true

Extra notes: “man dyld” is very useful for manipulating shared libraries. In particular the DYLD_INSERT_LIBRARIES and DYLD_PRINT_LIBRARIES environment variables let you see and control which versions of libraries are being used.

The size of an empty Mac app

I created my first Macintosh application today, following Apple’s excellent docs. I didn’t write any code yet, just the default Cocoa application template. I’m always fascinated what the size of empty apps is; it often indicates how simple and clean the underlying architecture is.

I did “Build for Run” and stripped the binary. The compiled app is 44k. The binary is 14k, the NIB is 26k. It takes 10M of memory (80+M if you count shared).

Xcode created 13 files in my source directory: 14,000 lines of source totalling some 400k. Almost all of that is an XML bloated NIB file I’ll never look at as text. There’s 51 lines of ObjC code in 3 files. Pretty much all that is boilerplate; the important bits are

int main(int argc, char *argv[]) {
    return NSApplicationMain(argc, (const char **)argv);
}
@interface TrackMixAppDelegate : NSObject &lt;NSApplicationDelegate&gt; {
    NSWindow *window;
}
@property (assign) IBOutlet NSWindow *window;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
}

It’s certainly nicer than the 400+ lines of unmaintainable garbage that Visual Studio’s wizard generates doing a similar task. I’m optimistic that the NIB system will work out well. MacApp’s version of this was a fucking disaster in the OS 6 days, but NextStep Interface Builder was always pretty impressive.