June 27th, 2008
I was vaguely aware that the copy of sys/queue.h on Linux systems was old. However, I’d forgotten it actually lacks some important features of the modern version shipped with BSD systems. There is a very common pattern of usage with linked lists, which the Linux version of queue.h doesn’t support too easily - iterating over a list and selectively removing elements, without invalidating the list.
It is unsafe, for example, to iterate over a TAILQ using the TAILQ_FOREACH macro if you are going to then do a TAILQ_REMOVE on certain elements within the TAILQ_FOREACH. The idiom suggested in the OpenBSD queue(2) manual page is:
for (var = LIST_FIRST(head); var != LIST_END(head); var = nxt) {
nxt = LIST_NEXT(var, entry);
if (some_condition) {
LIST_REMOVE(var, entry);
some_function(var);
}
}
Note the need for LIST_END macro as the loop guard. Since LIST_END, TAILQ_END, etc are all missing from the Linux version of sys/queue.h, this code will fail to compile on Linux systems. So it is necessary to bundle the BSD version. Fortunately, this isn’t a problem - the license is of course extremely liberal and you just drop it in your source directory and forget about it. It is annoying to stumble upon though. Why haven’t they updated their copy?
Tags: bsd, C, data structures, Linux
Posted in Technical | No Comments »
April 5th, 2008
UPDATE: An informative email thread which I started on the Python BayPiggies email list, can be found here.
One of the things I like most about Python is the “batteries included” philosophy. The standard library is comprehensive. One of the things which I dislike most about Python is the documentation. While superficially comprehensive, it leaves out many important details.
A case in point is the urlopen() function from the urllib2 module. This is very useful for fetching HTTP resources and allowing you to process the results trivially. Unfortunately it has some strange behaviours. The documentation claims “Raises URLError on errors”. One would imagine that this means one simply needs to catch the URLError exception, to successfully handle errors. This is incorrect. I have written a number of Python programs which are long-lived in nature (run indefinitely - over months) which use this function over the Internet. I want these programs to be robust and to recover from individual urlopen() failures. In the course of running these programs I have found the following exceptions are in fact thrown (note that I operate only on HTTP URLs):
- urllib2.HTTPError
- urllib2.URLError
- httplib.BadStatusLine
- httplib.InvalidURL
- ValueError
- IOError
Of course none of these are mentioned in the documentation. It is also unclear if it is the intention of the API designers that these exceptions should bubble up to the urlopen() caller. For example, certain httplib errors are caught by urllib2 and raised as a URLError, but obviously many are not. In my opinion, the documentation should either be clear that the caller needs to check for various underlying library exceptions, or urllib2 should be modified to convert all these errors into URLError.
To this effect, I intend to bring this issue up for discussion on some Python lists and if consensus is reached, I will propose a patch to handle at least those httplib exceptions which I have encountered.
Tags: python exceptions, urllib2
Posted in Python, Technical | No Comments »
March 21st, 2008
I started taking Yoga classes at the SF Krav Maga centre a few months ago and have been doing it pretty regularly since - usually I do two hours a week, in addition to other training. I must admit that for some time I had a negative attitude toward yoga - the association with New Age wishy-washy mumbo-jumbo for one thing, and also that it wasn’t clear to me what yoga actually did for you, what its benefits were.
I mean, you compare yoga with boxing - its pretty obvious what you are getting out of training in boxing. Some serious cardiovascular conditioning and practical fighting techniques. But what is yoga all about? A few stretches and poses and stuff - talking a load of New Age rubbish while barely breaking a sweat - just the pretense of physical fitness? That was my initial bias. However I have since revised my opinion about yoga.
I should mention that I don’t know what kind of yoga my instructor subscribes to, I must ask her. I’ve read that there are many different things which claim to be yoga. In fact I’ve read that what westerners know as “yoga” is a subset of a much larger Indian tradition. So I preface this with a clear admission that “your mileage may vary”.
The yoga class I attend focuses on two areas: core strength and flexibility. Personally I have had quite poor shoulder flexibility for a long time and the desire to improve my flexibility was one of my main motivators for trying yoga in the first place. The yoga core exercises are very intense - in fact more intense than any other abdominal exercise I’ve ever done. Think of ab bicycles but considerably more difficult. Of course core strength is very important, especially to prevent back problems and not least in any kind of fighting situation where you want to protect the internal organs to avoid getting knocked out by a shot to the body.
So what benefits have I noticed from doing yoga then? My flexibility has increased considerably, although I still have plenty of room for improvement. My core strength is pretty good - definitely much better with the addition of the yoga training. Furthermore I think I have a generally increased connection with my body and my balance is better. The breathing exercises have helped with my pacing in cardio activities.
Overall I think yoga is an excellent adjunct to more intense activity. It certainly is relaxing, increases core strength and improves flexibility. There may be other benefits along the lines of reduced stress, increased energy levels, and so on - but those are much more difficult to quantify and are clearly highly subjective. I would recommend a bit of yoga as an excellent addition to a training regime although I would hesitate to practice yoga exclusively.
Tags: Martial-Arts, yoga
Posted in Health | 2 Comments »
March 18th, 2008
Over at the Peer to Peer Research Institute, we have performed analysis on over 128,959 film torrents. From this data, we were able to extract the most torrented films of 2007. Without futher ado, here is the list:
- Harry Potter and the Order of the Phoenix
- 300
- Transformers
- Ghost Rider
- Ratatouille
- Shrek The Third
- The Simpsons Movie
- Sunshine
- I am Legend
- I now pronounce you Chuck and Larry
You can expect more interesting data extracted from the dynamic world of P2P file sharing on this blog in the future.
Posted in BitTorrent, Technical | No Comments »
March 17th, 2008
This evening I was trying to select entries within a specific date range, for example, all torrents for films which had been released in 2007. My query looked something like:
SELECT name FROM table WHERE date > 2007-01-01 AND date < 2008-01-01
PostgreSQL consistently returned very odd results. As far as it was concerned, Transformers was not a 2007 release, furthermore Batman Begins - which I distinctly remember going to see about three years ago - was.
Any relatively experienced SQL hacker is no doubt chuckling, having immediately seen my error. Of course, PostgreSQL is treating the un-quoted dates as arithmetic expressions and evaluating them numerically. When you think about it, 2005 - 05 - 05 = 1995. This is a perfectly valid arithmetic expression, its just that it happens to look like a definitive calendar date to my brain.
I found this mistake on my part absolutely hilarious.
Posted in Database, Technical | No Comments »
March 16th, 2008
After a year of Association for Computing Machinery “professional-level” membership ($200 / year) I’ve decided not to renew. Why not? A number of things really rubbed me up the wrong way about the ACM.
First of all, I had been looking forward to having an @acm.org email alias which I could use as a neutral and professional contact address on personal cards. Unfortunately, the ACM gave me a completely useless address which included an apostrophe in it! Yes, RFC 821 allows this, but such an alias is horribly prone to mis-typing and is difficult to remember. It simply wouldn’t work on a business card. There was no way, as far as I could see, to change the alias. I could have called them up and shouted at them to change it I suppose, but I really didn’t have time to bother with that sort of thing.
Secondly, they had the nerve to mail me ads for dental insurance. I assumed since I had received a letter from the ACM - a supposedly serious and useful professional organisation - that it would be something of actual value - such as perhaps an invitation to a conference or something of that nature. Nope - they are trying to sell me dental insurance. I already had dental insurance, and even if I hadn’t, I wouldn’t have appreciated the spam from an organisation which is supposed to be helping my career as a computer scientist, not flogging on insurance. I found it incredibly cheeky that after paying them $200, they would send me such garbage.
Thirdly, their publications are terrible. “Communications of the ACM” literally makes me nauseous. Its chocked full of industry advertisements and vapid, content-free articles. For a publication which is supposed to be of practical value, its pages are surprisingly full of utter trash - titles straight out of some Sokal hoax paper such as “amoeba-based neurocomputing with chaotic dynamics”. Come on. Their other magazine, “Queue” is similarly full of rubbish, but of a slightly different nature. Its articles are criticism-free, glorified adverts for various large computer vendors. Vendors get to trot out all sorts of insane new technologies, sure to be “the next big thing” while puppy-dog like interviewers stare wide-eyed.
Overall, the ACM reeks of an organisation which was once probably authentic, and useful, but has now utterly sold out to industry and become effectively an advertising racket specifically targetting professionals in computer-related fields. Not only do they provide very little content (beyond their digital library, which can be accessed from various public libraries for free in any case) but they are over-priced and actively engage in cheeky, rude maneuvers like trying to sell on insurance. Sorry ACM, but you won’t be getting any more of my money.
Posted in Technical, Writing | No Comments »
January 7th, 2008
I have just tagged, packaged and announced version 0.4 of my BitTorrent implementation, Unworkable.
Here are the release notes:
- Implemented sending peer keep-alives.
- Trace log now contains timestamps.
- Make us more tolerant of intermittent tracker failures.
- Added support for Arch Linux.
- Fixed an off-by-four bug which could cause segfaults on some platforms.
- Fix zero padding in peer id generation.
- Overall code reduction and re-factoring plus improvements to documentation.
Tags: BitTorrent, C, OpenBSD, Python, Unworkable
Posted in BitTorrent, Python, Technical | No Comments »
December 29th, 2007
The world’s oldest known playable audio recording was in fact engraved on a lead cylinder sometime in 1878 or so. It was made by a man called Frank Lambert who also invented the typewriter.
In any case, this very early recording is speculated to have been made as work towards building a talking clock. An mp3 of the recording is available, where you can hear a series of unintelligible noises, followed by silence, followed by Lambert counting out the time from one o’clock to twelve o’clock, although ten o’clock is mysteriously absent. Finally, the last section of the recording is more unintelligible sound, thought to perhaps have been recorded backwards.
I find this all quite fascinating - a particularly eerie audio experience, particularly to hear that voice, and the fact that ten o’clock is ominously missing!
Tags: phonograph, talking clock, vintage audio
Posted in Music | 1 Comment »
December 27th, 2007
To follow up on my last post on the bittorrent end-game, I’m going to write about a strategy to bootstrap a torrent download. I am talking here about the case where you start a download with no existing data, in other words, from scratch. As I described in one of my earlier articles about the basics of the BitTorrent protocol, torrents are divided into units called pieces. The torrent meta data contains the SHA-1 checksums for each piece, so that we can hash each piece once we have downloaded it, for verification purposes. Pieces are downloaded on a block-by-block basis - typically the block size is sixteen kilobytes (16KB).
Another important thing to understand is that BitTorrent peers use a “tit-for-tat” transfer scheduling algorithm. That is, peers will be rewarded by other peers for uploading data to them. It is therefore important that a bootstrapping peer have at least a small number of complete pieces as soon as possible, in order to share them, and hence be rewarded by the “tit-for-tat” algorithm. The bootstrapping peer wants to get at least a few pieces to share as soon as possible.
Additionally, pieces are usually downloaded in rarest-first order. This ensures that rare pieces are replicated sufficiently so that holes do not appear in the torrent as peers leave the swarm. One of the design considerations of BitTorrent - vs other distributed data mechanisms - is to have as reliable replication as possible. It is highly undesirable in BitTorrent for even a single piece to disappear, as this could render the final file(s) completely unusable. This contrasts heavily with a file distribution system such as Amazon’s Dynamo, where it may be quite acceptable for data to disappear - is it really a huge deal if a user loses the contents of their shopping cart in an outage?
In any case, the desire to ensure replication of the rarest pieces in a torrent is overridden by the need to get a small number of pieces as a peer is bootstrapping. To this end, the initial pieces are downloaded in random order as opposed to rarest-first order. In practice this means the bootstrapping peer should get its initial data quite a bit faster. The number of pieces to download before switching to rarest-first order is suggested to be four.
As a general point, the peer will aim to complete a piece fully before requesting blocks belonging to another piece. Alternately put, if the peer has a few blocks in one piece, it will concentrate on downloading the remaining blocks belonging to that piece before starting on another piece.
Tags: BitTorrent, p2p, Unworkable
Posted in BitTorrent, Technical | No Comments »
December 26th, 2007
Downloads in BitTorrent take place according to a number of strategies, which map to stages. Initiating a torrent download has one strategy, normal operation has another strategy, and finally pulling down the last remaining pieces has yet another strategy.
The End Game is the name for the final download strategy - there is a tendency for the last few pieces of a torrent to download quite slowly. To avoid this, many BitTorrent implementations issue requests for the same remaining blocks to all its peers. When a block comes in from one peer, you send CANCEL messages to all the other peers requested from, in order to save bandwidth. Its cheaper to send a CANCEL message than to receive the full block and just discard it.
However, there is no formal definition of when to enter End Game Mode. In my BitTorrent implementation, Unworkable, I quite stupidly used a percentage-based threshold. When only 5% of the torrent download was incomplete, Unworkable would enter End Game Mode. I didn’t notice how stupid this was until I got around to testing with a large torrent download, a Fedora Core 8 DVD image which is 4G in size or so. It turns out that 5% of 4G is quite a bit of data, and requesting each bit of it from every single peer is extremely inefficient. So I did some more research to find a more effective way to detect when to enter End Game.
I found two popular definitions:
- All blocks have been requested
- Number of blocks in transit is greater than number of blocks left, and no more than 20
I didn’t understand the choice of the number 20 in method 2, so I decided to go with option 1), which I did understand. In Unworkable CVS HEAD (and in the 0.4 release, coming in a week or two), the ill-informed percentage-based threshold is gone and End Game Mode is entered when all blocks are requested.
Tags: BitTorrent, p2p
Posted in BitTorrent, Technical | 1 Comment »