Search Results: "Chris Lamb"

27 July 2011

Chris Lamb: Official Redis packages for Debian "squeeze"

Due to high demand I have prepared official Redis packages for Debian "squeeze":
  1. Add the following line to /etc/apt/sources.list:

    deb http://backports.debian.org/debian-backports squeeze-backports main
    
  2. Update your local package lists:

    sudo apt-get update
    
  3. Install redis-server with:

    sudo apt-get -t squeeze-backports install redis-server
    
The current version number in this repository may be found here. Bugs should be reported in the usual way. For the sections of the web community who insist on hitting problems solved years ago, here is why you should use these packages over installing Redis manually:

24 July 2011

Chris Lamb: Calculating requests per second with pv

Miss apachetop under nginx or lighttpd? You can use pv to get a quick-and-dirty readout for almost any daemon:
sudo tail -F /var/log/nginx/access.log   pv -lr >/dev/null
[54.7/s ]
grep can naturally be used to filter the results.

3 July 2011

Rog rio Brito: Installing Meego on the N900

My last cellphone was a dumb phone. I seem to remember that it was called something like Samsung Voicer. It didn't have those hip things like SIM cards. OK. Fast forward to December of 2010, and after a long hiatus, I decided to get a new phone. It was this shiny Nokia N900. The biggest thing that made me want this one was that some people at DebConf 10 were praising it for having a Debian-like distribution in it, and that it worked very well. I saw that Phil Hands was enthusiastically talking about the bargain of getting one in New York and that it would have cost him many pounds in the UK and, so, he was happy with it. Ot vio Salvador also got one in NY and during one of the nights of that DebConf with him, Tiago Vaz, Daniel Baumann, and Chris Lamb, I asked him to call my parents here in Brazil and he let me use his N900. I had more time with it and played a little bit with the command line, opened the stock media player and played a beautiful trailer of 9 (2009 film), leaving me a very good impression. I bought one, and, indeed, it is a very good machine that can even make phone calls. The ability to run Linux on it (even if it contains some non-free pieces of software) was decisive in me getting it. It runs this distribution called Maemo 5 which is loosely based on Debian. But now, Maemo is not the "cool thing" to run, regarding Linux on these portable devices. Meego is. But with the advent of many Internet forums has brought many people writing some long, convoluted howto documents for things that would be better done as, say, providing a script or, better yet, preparing a package. In the case of getting Meego running on the N900, only three things are required:
  1. Install uboot-pr13 while in Maemo.
  2. Uncompress the MeeGo 1.2 Community Edition for Nokia N900 image to a SD card.
  3. Turn the phone off, plug in the SD card, and PUT THE BACK COVER on the phone.
The last bit of the third step is crucial, as, otherwise, the SD card won't be detected and you will get kernel panics with the device trying to mount the root filesystem from a device that is not there. As an aside, the official documentation tells us one should uncompress the available pre-made images and write them with dd to the device. In my experience, it is completely unnecessary to use it and, in fact, it is so 6 times slower than using a simple shell redirection. That is, instead of:
bzip2 -d < mg-handset-armv7nhl-n900-whateverwhatever-mmcblk0p.raw.bz2   dd bs=4096 of=/dev/mmcblk0
you can get better results with the simpler:
bzip2 -d < mg-handset-armv7nhl-n900-whateverwhatever-mmcblk0p.raw.bz2 > /dev/mmcblk0
I actually used lbzip2 instead of bzip2, but that shouldn't matter. The use of the small block size for the dd command is probably the culprit, but I don't see the need to write the uncompressed data in chunks this small. If there is a problem, I would love to be informed of that. As trying it with uboot and a SD card doesn't mess with your "safe" Maemo installation, this is a good way to play with the successor of Maemo. Perhaps, if we give good feedback to the project, we can influence the direction that it is taking. It will surely be nice to learn about this new "consumer-oriented" distribution.

8 September 2010

Chris Lamb: irccat plugin for supybot

Like irccat but for when you are already running a Supybot instance.
import supybot
from twisted.internet import reactor, protocol
from twisted.protocols import basic
class IRCCatProtocol(basic.LineOnlyReceiver):
    delimiter = '\n'
    def lineReceived(self, text):
        irc = self.factory.irc
        for channel in irc.state.channels:
            irc.queueMsg(supybot.ircmsgs.notice(channel, text))
class IRCCat(supybot.callbacks.Plugin):
    def __init__(self, irc):
        super(IRCCat, self).__init__(irc)
        factory = protocol.Factory()
        factory.protocol = IRCCatProtocol
        factory.irc = irc
        self.server = reactor.listenTCP(12345, factory)
    def die(self):
        self.server.stopListening()
Class = IRCCat
You can then post messages with:
$ echo hai2u   nc -q0 hostname 12345

3 August 2010

Rog rio Brito: First post from DebConf 10

Even though I am late with this post, it is nice to say that I am writing here from this year s DebConf10, in NYC. Today (well, yesterday) was the day of the Cheese and Wine party and I think that it was cool, at least for the moments that I were there. This post, though, isn t technical in any sense. I only talks shortly about my impressions of the community, as this is my first DebConf ever (despite the fact that I have been using Debian since the late nineties). I was very pleased to have met Bdale Garbee. I saw him the other day arriving with Keith Packard, but I just didn t want to disturb them at that point. We only talked for, say, 2 minutes, and his was one of the nicest receptions that I had here. And there were some other people that were equally easy to approach, nice to talk with and, to my surprise, knew my name after some brief moments (yes, this does make a difference, especially when you are in a strange country, when you don t know anybody with whom you have worked for some years). Being involved in the organization stuff, one would think that Jimmy Kaplowitz would be so busy, but he was so kind. I had longer conversations with T ssia Cam es, Tiago Vaz (as always) and some other people that I had not yet had the pleasure of meeting in person. In particular, Daniel Baumann (who apparently is now crazy about our FISL and wants to drink all Guaran that he can get :-) ), Chris Lamb and Ot vio Salvador and his mom. Those people are so cool and it is nice to discuss some legal issues among different continents in the lounge of their building at late night. :-) Too bad that I am allocated to the other building. :-) I am forgetting many other people (hey, it is 2 am here in NYC), but I would feel guilty if I had not mentioned at least three people more: Martin Michlmayr, Phil Hands, and Reinhard Tartler (who is uploading lame to the debian repository, as the patents regarding it are expiring or expired already). Thanks! P.S.: I just created an account on flickr that I hope to populate with some photos that I took here. And even with a nice squirrel. :-)

2 August 2010

Chris Lamb: Debian Live Studio

http://chris-lamb.co.uk/wp-content/2010/live_studio.png
Over the last couple of days I have been creating Debian Live Studio, a web-based service for creating Debian Live systems. After choosing between various options, you wait a few minutes and the server generates an ISO or USB stick image for download. I have a list of features I plan to implement but have put the service live so I can respond to feedback throughout DebConf. Please grab me. Regarding the current server infrastructure, I'm hosting this on a $15 virtual machine which will fill up in a few hours. If anyone can donate more serious hosting for this service please get in touch. You can check it out at: http://studio.debian.net.

1 August 2010

Chris Lamb: screen-message prompt for Awesome

The following snippet adds a screen-message prompt to the Awesome window manager:
mypromptbox = widget( 
  type = "textbox",
  name = "mypromptbox",
  align = "left"
 )
globalkeys = awful.util.table.join(
  -- [..]
  awful.key(  "Mod1"  , "F6", function ()
    awful.prompt.run(
        prompt = "Msg: "  ,
      mypromptbox,
      function (msg)
        awful.util.spawn_with_shell(
          'echo ' .. msg .. '   sm - -b Black -f White'
        )
      end
  ) end)
)
root.keys(globalkeys)
(The default colour scheme of black-on-white is painful.)

24 July 2010

Chris Lamb: Four men in a mine

kumbunterland posed this question in the park yesterday:
There are four men in a coal mine. This exit is narrow so that no more than 2 men can exit at the same time. In addition, there is only one torch and they can't leave the mine without it. Each man walks at a different speed. The first man takes one minute to exit the mine the bridge distance, the second takes two minutes, the third takes five, and the fourth takes eight minutes. If two men walk together they must walk at the slower speed. For example, if person #1 and person #3 go together, they will leave the mine in 5 minutes. Then, person #1 could return back to return the torch to the others (taking another one minute) so they can use it to exit again. The coal mine will collapse in exactly 15 minutes; you must find a way to allow all the men to leave the mine within this time.
Unfortunately, swi-prolog is broken on the N900, so I wasn't able to solve it right then:
solution(Men, Bound, Out) :-
    torchInside(Men, [], [], Log),
    totalDuration(Log, 0, Duration), Duration =< Bound,
    swritef(Out, '%w  (%w minutes)', [Log, Duration]).
% We use torch Inside,Outside  predicates like a state machine.
torchInside(A, B, Log, X) :-
    % Move two people from inside -> outside the mine
    combination(2, A, S), subtract(A, S, A1), append(S, B, B1),
    torchOutside(A1, B1, [S Log], X).
torchOutside([], _, Log, Log).
torchOutside(A, B, Log, X) :-
    % Move someone from outside -> inside the mine
    combination(1, B, S), subtract(B, S, B1), append(S, A, A1),
    torchInside(A1, B1, [S Log], X).
% Utilities:
totalDuration([], X, X).
totalDuration([H T], Acc, X) :-
    max_list(H, Max), NewAcc is Acc + Max,
    totalDuration(T, NewAcc, X).
combination(0, _, []).
combination(N, [H T], [H Comb]) :-
    N > 0, N1 is N - 1, combination(N1, T, Comb).
combination(N, [_ T], Comb) :-
    N > 0, combination(N, T, Comb).
?- solution([1, 2, 5, 8], 15, X).
X = "[[2, 1], [2], [5, 8], [1], [1, 2]]  (15 minutes)" ;
X = "[[1, 2], [1], [5, 8], [2], [1, 2]]  (15 minutes)" ;
false.
I'm fun at parties.

12 July 2010

Chris Lamb: 10K Challenge: Week 1

Wasn't the best start this week, unfortunately.
http://chris-lamb.co.uk/wp-content/2010/10k_schedule_1.png

5 July 2010

Chris Lamb: 10K Challenge: Week 0

On Sunday 5 September I will be entering a 10K running event, probably the Middlesex 10K in Victoria Park. This will be my first running event, so I've put together a training schedule based on a few sources on the web. Whilst nine weeks preparation appears quite conservative I have been running for about 5 weeks already I will be in North America for about a month of that with an unpredictable schedule. Below is what I'm currently shooting for. Units are in miles, a hyphen indicates a rest day and "cross" stands for cross-training. I haven't decided what I'm going to do for that yet although swimming is tempting.
http://chris-lamb.co.uk/wp-content/2010/10k_schedule.png
Tasks for this week:

7 June 2010

Chris Lamb: Distributing locking with Python and Redis

This is already possible with Memcache, but if you are already drinking the Koolaid...
import time
class Lock(object):
    def __init__(self, key, expires=60, timeout=10):
        """
        Distributed locking using Redis SETNX and GETSET.
        Usage::
            with Lock('my_lock'):
                print "Critical section"
        :param  expires     We consider any existing lock older than
                             expires  seconds to be invalid in order to
                            detect crashed clients. This value must be higher
                            than it takes the critical section to execute.
        :param  timeout     If another client has already obtained the lock,
                            sleep for a maximum of  timeout  seconds before
                            giving up. A value of 0 means we never wait.
        """
        self.key = key
        self.timeout = timeout
        self.expires = expires
    def __enter__(self):
        timeout = self.timeout
        while timeout >= 0:
            expires = time.time() + self.expires + 1
            if redis.setnx(self.key, expires):
                # We gained the lock; enter critical section
                return
            current_value = redis.get(self.key)
            # We found an expired lock and nobody raced us to replacing it
            if current_value and float(current_value) < time.time() and \
                redis.getset(self.key, expires) == current_value:
                    return
            timeout -= 1
            time.sleep(1)
        raise LockTimeout("Timeout whilst waiting for lock")
    def __exit__(self, exc_type, exc_value, traceback):
        redis.delete(self.key)
class LockTimeout(BaseException):
    pass
One common use case for distributed locks in web applications is to prevent clients dog-piling onto an expensive cache key:
def cache_without_dogpiling(key, cb, cache_expiry=None, *args, **kwargs):
    val = cache.get(key)
    if val is not None:
        return val
    # Cache miss; gain the lock to prevent multiple clients calling cb()
    with Lock(key, *args, **kwargs):
        # Check cache again - another client may have set the cache
        val = cache.get(key)
        if val is None:
            val = cb()
            cache.set(key, val, cache_expiry)
        return val
def slow():
    print "Inside slow()"
    return 1 + 1 # Python is slow
>>> cache_without_dogpiling('my_key', slow, 60 * 10)
Inside slow()
2
>>> cache_without_dogpiling('my_key', slow, 60 * 10)
2
As a bonus, if you don't want your test or development environment to rely on Redis, you can replace it with a no-op lock:
import contextlib
@contextlib.contextmanager
def Lock(*args, **kwargs):
    yield

1 June 2010

Chris Lamb: Appending the request URL to SQL statements in Django

import sys
from django.http import HttpRequest
from django.db.backends import BaseDatabaseWrapper, util
class URLCursor(util.CursorDebugWrapper):
    def execute(self, sql, *args):
        f = sys._getframe()
        while f:
            request = f.f_locals.get('request')
            if isinstance(request, HttpRequest):
                sql += ' -- %s' % repr(request.path)[2:-1].replace('%', '%%')
                break
            f = f.f_back
        return self.cursor.execute(sql, *args)
fn = BaseDatabaseWrapper.cursor
BaseDatabaseWrapper.cursor = lambda self: URLCursor(fn(self), self)
Now your SQL statements look like:
SELECT "auth_user"."id", [..] WHERE "auth_user"."id" = 1 -- /login
This allows you to quickly go from a misbehaving query in your production environment to the view that is executing it.

4 May 2010

Chris Lamb: Rotating email into your inbox using imapfilter

I'm not a fan of "life hacks", but I have the adopted the following automated processing of my email inbox: if I don't want to deal with a message today, I move it to (eg.) Mail.DELAYED.4 and it will reappear in my inbox automatically in 4 days. It is inspired by the Inbox Zero, tickler files and the Debian DELAYED queue. My implementation uses imapfilter. You'll need to tweak the move_messages syntax for lenny's version; the following works fine in squeeze and sid:
mbox = IMAP  
    server = 'mail.server.net',
    username = 'username',
    password = 'password',
    ssl = 'ssl3'
 
num = 14
dst = 'INBOX'
prefix = 'Mail.DELAYED.'
for x = num, 1, -1 do
    mbox[prefix .. x]:select_all():move_messages(
        mbox[x == 1 and dst or prefix .. (x - 1)]
    )
end
The messages are moved when I'm (hopefully) asleep:
# m h dom mon dow command
  0 6 *   *   *   imapfilter -c /path/to/delayed.lua >/dev/null

22 April 2010

Chris Lamb: Locating source for any Python module

When I'm too lazy to find API documentation I just read the source code. To make this slightly easier in Python, here's what I use in my ~/.$ SHELL rc:
cdp ()  
  cd "$(python -c "import os.path as _, $ 1 ; \
    print _.dirname(_.realpath($ 1 .__file__[:-1]))"
  )"
 
For packages, this takes you to the corresponding source directory:
$ cdp twisted.web
$ pwd
/usr/share/pyshared/twisted/web
$ ls
_auth/  domhelpers.py  html.py  iweb.py  resource.py
[..]
The realpath and [:-1] hackery follow any python-support symlinks. For "standalone" .py (or .so) modules, cdp will take you to the directory it resides in:
$ cdp subprocess
$ pwd
/usr/lib/python2.5
$ ls subprocess.py
subprocess.py

17 March 2010

Chris Lamb: Per-channel BTS bot filtering

Just a short announcement that my Debian BTS IRC bot which hangs out on #debian-devel-changes can now spam your favourite subproject's channel with specific bug activity and uploads. Filtering is done with a regular expression tested against the package name. /msg me with your (channel, regex) tuples (in Python re format, please).

27 December 2009

Chris Lamb: Readline tab completion using Django models

The following snippet allows readline-style tab completion backed onto Django models. I am using this in management commands in preference to specifying primary keys as arguments.
class QuerySetCompleter(object):
    def __init__(self, qs, field):
        self.qs = qs
        self.field = field
        self.prefix = None
    def __call__(self, prefix, index):
        if prefix != self.prefix:
            qs = self.qs.values_list(self.field, flat=True)
            if prefix:
                qs = qs.filter(** 
                    '%s__startswith' % self.field: prefix,
                 )
            self.matching = list(qs)
            self.prefix = prefix
        try:
            return self.matching[index]
        except IndexError:
            return None
Example usage:
import readline
from mymodels import MyModel
completer = QuerySetCompleter(MyModel.objects.all(), 'name')
readline.set_completer(completer)
readline.parse_and_bind("tab: complete")
readline.set_completer_delims('')
while 1:
    print repr(raw_input(">>> "))
Pressing <tab> at this >>> prompt will complete from the name field of the MyModel model just like a regular shell would. We call readline.set_completer_delims as our items may contain word delimeters - otherwise readline would attempt a seperate completion of (eg) "Bar" if one of our items was "Foo Bar".

11 December 2009

Tim Retout: Moving

I'm now a Debian Developer. :) My thanks go to Ben Hutchings, gregor herrmann, Chris Lamb, Christoph Berg, Steve McIntyre, Brad Smith, Jonny Lamb, Chris Boyle, everyone at credativ, and everyone else who helped me with Debian over the last... almost six years? Actually, I've been a DD since the weekend, but have been too absorbed to write about it. In other news, I'm moving house today... I'm more or less packed now. My internet access may be intermittent at home for the next few weeks. (Home is now Southampton, UK.)

19 November 2009

Chris Lamb: Transparent directory replacement with zsh

Under UNIX, it is possible to get into a position where your shell's working directory is pointing to an inode that no longer exists, but a "newer" directory with the same name exists. The easiest way of reproducing this scenario is as follows:
$ cd $(mktemp -d)
$ rm -rf $PWD
$ mkdir $PWD
However, as concrete example, imagine you are debugging something deep inside a generated code tree if you ran make clean and then make again from another shell, your debugging shell would be left pointing to an inode that does not exist (as it was removed by make clean), yet the make call would have made an identically named directory in its place. Shells behave rather unintuitively in this situation; ls will (correctly) return no results, but attempting to do anything useful results in curious error messages. I use the following zsh precmd hook to transparently fix this for me:
precmd ()  
  # "DOS emulation mode"
  if [ "$(stat -c %i . 2>/dev/null)" != \
                 "$(stat -c %i -- "$ PWD " 2>/dev/null)" ]
  then
    OLDOLDPWD="$ OLDPWD "
    if ! cd -- "$ PWD " >/dev/null 2>&1
    then
      echo "W: $ PWD  does not exist anymore"
      return 1
    fi
    OLDPWD="$ OLDOLDPWD "
  fi
 
The cost of the stat calls seem justified by the convenience and are in any case insignificant compared to the other things I am doing in my precmd. If you are using zmodload zsh/stat, then replace stat -c %i with stat +inode. (My previous experience with zsh tricks is that the functionality invariably exists already in some obscurely named builtin. Here's hoping.)

5 November 2009

Chris Lamb: Confusing bugs

I love bugs that are just confusing and/or break your mental model of how you think the software works. Here is a good example: Given the following HTML in Gecko, what happens when a user clicks the button?
<form method="POST" action="/form-action">
  <a href="/anchor-target">
    <input type="button" value="harro">
  </a>
</form>
GET /anchor-target HTTP/1.1
GET /anchor-target HTTP/1.1
2 GET requests? Okay, perhaps some sort of event bubbling problem; it's relatively common in GUI internals. But what about:
<form method="POST" action="/form-action">
  <a href="/anchor-target">
    <input type="image" src="http://upload.wikimedia.org/wikipedia/en/7/75/LHC5.jpg">
  </a>
</form>
POST /form-action HTTP/1.1
GET /anchor-target HTTP/1.1
GET /anchor-target HTTP/1.1
Wait, this time it POSTs the form and makes 2 GET requests? Answers in a Bugzilla report, thanks.

10 October 2009

Stefano Zacchiroli: RC bugs of the week - week 6

RCBW - week #6 RC bugs squashed this week by yours truly: This week I've cheated for at least two reasons:
  1. the first 4 entries in the list above are bugs of "mine", since within the Debian OCaml Maintainers team we migrated to a new package toolchain called dh_ocaml (with a lot of advantages I've anticipated before my summer break). The migration to that triggered (thanks, Lucas! :-) ) more than 30 FTBFSs which had to be dealt with. So, even if not cheating, it is at least breaking the NMU tradition of RCBW, but they were still RC bugs looking for a fix! All in all, I'm impressed by the fact that in about a week we dealt with most of them.
  2. the lxml fix above is severity "important" and as such, not RC. I attacked that because I intended to help out with the Python 2.6 transition which is still, at the time of writing, 41 bugs away from hitting unstable. I confess I did not find the task particularly fun (which is a requirement for me when I work on packages which are not mine) yet, we'll see next week ...
The feeling of the week I've to share is that I'm more and more impressed to not have received any complaint about my NMU activity, and I'm approaching the 50 NMUs. Actually I've received several "thank you" replies (you rock guys and you know who you are). On one hand this is probably a good indication that I haven't (yet) done any serious mistake; I do love peer-review! On the other hand, and more importantly, this is dispelling inside me the folklore / cultural block we have in Debian that "NMU is bad", while NMUing should become a way to help each other routinely. Really.

Next.

Previous.