Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

2008-11-17

Tracing Python memory leaks

Tracing Python memory leaks.



2008-11-11

Simple inter-process locks

At LShift blog I wrote about simple inter process locks in Python.



2008-05-11

Shared Fridge Magnets - simple collaboration for GAE

Recently I read The ELC Community Blog with their example of sharing objects using red5.

The obvious task is to do the same without red5 and any flash.

So I created yet-another-example of the comet daemon service.

Just open the fridge example site in two browsers. You can move, resize (with shift) and upload images.



2008-05-07

Google App Engine: Ytalk like multiuser chat

This is a follow up on my last post describing missing services for AppEngine.

The idea is to help developers writing apps for AppEngine by providing them some common functionality missing and impossible to have on AppEngine and offer them as external services.

These services are accessible through a simple API over HTTP, and it is easy to call them from AppEngine applications using urlfetch methods.

The services available now are image resizing and comet.

Image resizing is built around a work queue, to which you can POST resize requests with a URL that will be called back when the resize is finished.

The comet service is much more interesting. It is a standalone comet server with properly implemented long running requests (not cheating with constant polling by the client) and allows many to many conversations using channels/chat rooms.

The comet server can notify your AppEngine application when users enter or leave channels, so your app can display updated presence info.

But the conversation can be going directly between client browsers and comet server, so it doesn't eat the precious AppEngine traffic limits.

As a demo of the comet server I have written a chat application modeled after an old-school unix program called ytalk.

The unique feature of the ytalk implementation is that it sends messages after every keystroke, rather than after end of line. That way you can see words not only being written, but being deleted too, letter by letter. It is quite funny to watch it specially when you realize the amount of all the HTTP traffic that happens in the background.

The biggest challenge is to maintain high speed of sending updates, which depends on the connection latency and on the speed of our server. The server is event driven, and is mainly multiplexing streams of bytes flowing through file descriptors, so the overhead here is small.

Summing up
Anyway, the point I want to stress is easy integration with external application. You can write your app in any framework and use the comet server as a service (via HTTP requests used only for control).

The service doesn't require any proxy server, as it is sometimes used in similar setups.

Of course the services are still in development, call it experimental version.


Here you can see my demos of AppEngine apps using the described services.

You can test the ytalk example, or take look at the video to see it in action (yes, in the movie there are two different browsers opened: left is firefox, right is opera):



2008-05-01

Missing services for Google App Engine (comet as a service!)




Google App Engine is a great product, but it lacks several features. I created few simple services to help GAE developers. Of course services aren't GAE specific, you can use them from any site.

The services are:

  • Image resizing
  • Cron service
  • Comet service

Image resizing
One can't easily resize image on Google architecture - they blocked PIL. This service just resizes images and uploads them back to your site.
Cron service
Sometimes you need to do something on regular intervals like collecting garbage or updating counters. This service just wgets your url at specified hour.

Comet daemon service
This is my favorite. I wondered if it's possible to create a web service that would allow developers to easily write comet sites. It wasn't easy but finally here it is. Now you don't have to have your own advanced comet server. You can use my service instead! Maybe someone will be interested in possibility to outsource comet servers.

During the work I solved many very interesting problems, but that's a topic for another post.

The only major limitation is that you have to own a domain. You can't build comet application and serve it from *.appspot.com.

Summary
Of course you can download the source code of my examples from Google App Engine.

I see it fascinating to use Google's infrastructure connected with other people (my?) services and create really advanced sites without touching the servers. That brings new possibilities. I'm really excited about it.


2008-04-08

Python is the winner.



Usually I don't comment the news on the web, but this one is in my opinion really important.

Google made App Engine. Now you can write web applications in Python and run them on Google infrastructore. The main advantages?

  • ultra scalability for renderer servers
  • ultra scalability for database
  • easy deploy
  • rather cheap
  • auto load-balancing
What they miss?
  • memcached / advanced cache
  • comet support
  • view layer integration (so you can easily plug in/out parts of your app)

I predicted this in June.

In my opinion Python got it's awaited killer app. We'll see, maybe tomorrow Google will add Rails support, it will change the game once more (and they will, the question is only when).


So what is going to happen next? Yahoo is out the game, Microsoft is not interested in web apps. Maybe Amazon will create their EC2 as platform for hosting web apps, or maybe Facebook will start to host php applications.

Google for sure is going to add new features and for now is winning the race. Google is really starting to own the web.


2008-03-08

How to deliver an event to multiple processes? - scaling django-evserver

The hardest problem I had to solve during my work on django-evserver, was how to efficiently propagate an event to multiple listener processes.

Python, because of GIL, doesn't scale across multiple processors. One process can only use one processor.

In django-evserver we have multiple python processes and some of them could wait for some specific event. The question is how to deliver an event only to the processes that wait for it.

Signals?
The simplest thing we could do when event occurs, is to send Unix signal (for example SIGUSR1) to every process. But that doesn't scale at all, not every process must be waiting for this event. We could use some kind of central server to manage events and send it only to proper listeners. But this needs quite complicated statefull server.

Multicast?
Next idea is to bind to specific udp port and listen for multicast packets. If a process waits for event 1, it will bind to port 10001. Theoretically multiple threads could listen on one multicast udp port. The problem with tcp/udp sockets is that we're limited to 64k unique event types for one machine. Which is not too much.

Can it be done easier?
Well. Reading from named fifo file (mkfifo) is definetelly blocking. The point is that multiple processes can read from one fifo. When some process will write to this fifo, every listener would be noticed. One reader will get the written message, all others will get information that they can't listen any more becaouse writer closed pipe. But that is good enough, every waiting process got an event.

Good points of that approach:

  • you could have millions of fifo's
  • as many processes could 'bind' to one fifo as you would like to
  • writer knows if someone is reading from the fifo - you could tell if the event was delivered to at least one reader
  • very easy to implement
  • very simple to understand

Bad points:
  • doesn't scale across multiple machines (but a daemon that would forward events to other machines is quite simple to implement)
  • it's based on specific fifo implementation, probably won't work on windows


2008-01-18

django-evserver - Asynchronous server for Django

I mentioned the idea in previous post about asychronous wsgi.

Now we have working example of simple chat application. The chat is nothing special, but it's made in Django! To make this possible I created special server, django-evserver. It's quite light wrapper to libevent http layer (several hundred of lines in python/ctypes).

Using this technology it's now possible to create asynchronous WSGI applications. Currently I implemented the Comet javascript library and some wrappers for Django views, to make easier writing comet applications in Django.

Here is how example chat application evserver-chat looks like:

The code is commited to code.google.com, maybe in future I'll write some more code and documentation. For example it could be interesting how I used named fifos (mkfifo) to pass events.



2007-12-16

Asynchronous Django responses (comet), yes, for WSGI

Comet on python?

I was looking for comet server implementation in python. There are many projects that claim to provide this, but none of them is working for me. Most of the projects are just proofs of concepts that never been deployed for real usage.

Here is the list of projects that my friend found:


The Orbited project looks like the thing I was looking for. The problem is that even the examples from official documentation aren't working. Sorry, I don't want to work with undocumented projects.

Next candidate is Twisted, but I'm not the fan of it for religious reasons.

Fapws project also is looking good, but it supports only basics, no possibility of deferring (preeptimg) request.

The problem

I want to do an ajax request from browser that will be finished only when some event occured at the server side. The connection should stall and wait for the server. (this idea, of pushing events from server to browser is called comet)

Next thing is to allow django applications to use this technology. As far as I know no one has ever done this before, probably because django is based on WSGI stack which is, unfortunetally, fully synchronous.

Even though I think it's possible to allow WSGI stack to support asynchronous responses without modifying the WSGI stack at all.

The solution

Author of FAPWS suggested that it's possible to use libevent directly from python using ctypes. Libevent proved to be very reliable and fast enough in most cases, so it should be good idea to use it.

Using libevent glued with ctypes I created simple WSGI server (William examples helped me much).

As I mentioned the idea was to allow Django to do async responses. For the proof-of-concept I created website that produces output in five chunks, separated by delays of one second. Sounds easy, but it's not so simple to do without freezing server process for the whole time.

Going straight to the example, here's the view.py file from sample django app:
# Url handler of the basic url.
# Headers only from this response are used.
# The same with status code, this function
# response status code is served to the client.
def comet_main(request):
response = HttpResponse('First content<br /> ') # return something
response.stage = 0
return defer_in_time(response,
1, '/stage/') # after one second run the '/stage/' url handler

@deferred_view()
def comet_stage(request, response_prev=None):
response = HttpResponse('stage%i<br /> ' % (response_prev.stage + 1) )
response.stage = response_prev.stage + 1
if response.stage < 3: # loop here three times
url = '/stage/'
else:
url = '/stage_last/' # than end the connection
return defer_in_time(response,
1, url) # after one second run the url

@deferred_view()
def comet_stage_last(request, response_prev=None):
# no magic here. just regular response
return HttpResponse('last_stage%i<br /> ' % (response_prev.stage +1))
Here is how it looks from the browser:


And what really happens on the wire (notice that Transfer-Encoding: chunked is used):


The sources are here.

What's next
The next thing to do is to create the example of full comet application.


2007-11-02

Libevent under python

So I want to write asynchronous tcp/ip server in python.

I really hate overblown twisted. The thing I like most in Python is simplicity and easiness to read. Well, twisted in my opinion doesn't have this attributes. It's of course my personal feeling, mostly because I don't know twisted. But such statements are making me sick, at first sight I really don't understand what are they for (from core twisted documentation):


internet.TCPServer(7779, IFingerFactory(f)).setServiceParent(
service.IServiceCollection(application))

I remember such cascades from Java rather than Python and I dislike Java especially for this way of programming.

Getting back to point. If not twisted than what? Lets try libevent. Stable C library, which is a production standard now. Memcached is using it, Tor is using it, IO also. It must be really professional asynchronous library.

There are also some other async linux libraries, like liboop. Wait a moment, libevent 500k google hits, liboop 25k. Sorry, the only asynchronous library for linux is libevent for now.
(btw. Liboop's api is in my opinion totally broken)

Are there any python wrappers for libevent? Google says about two: libevent-python and pyevent. Both seem abandoned.
I don't like exceptions inside libraries, so it didn't took long to eliminate pyevent:
    Traceback (most recent call last):
File "./tights.py", line 37, in
main()
File "./tights.py", line 34, in main
event.dispatch()
File "event.pyx", line 262, in event.dispatch
TypeError: exceptions must be strings, classes, or instances, not type

Update: Michael Carter writes in comments that this bug is the fault of pyrex rather than pyevent and that it shouldn't happen in python2.4(I use 2.5). I'll have to take a closer look at pyevent again.

Libevent-python seems to be working. Unfortunately this wrapper removed the concept of 'userdata' passed to callback in favor of class-based approach. The difference is that callback is not called with 'userdata' but it's called on specific class instance, so callback has 'self' object. I personally prefer the 'userdata' approach, but it's quite easy to switch.

Here's an example of simple libevent-python server, which is just printing every data it receives (something like standard echo_server.py example from libevent-python, but simpler)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket, signal, libevent

def callback_interrupt(signum, events, event_obj):
libevent.loopExit(0)

def callback_onconnect(fd, events, event):
# hack to avoid passing sock_srv from main()
sock_srv = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
sock, (host, port) = sock_srv.accept()
conn = Connection(sock, (host, port))

class Connection:
def __init__(self, sock, addr):
self.sock = sock
self.addr = addr
self.sock.setblocking(False)
libevent.createEvent(sock, libevent.EV_READ, self.callback_onread).addToLoop()

def callback_onread(self, fd, events, event_obj):
buf = self.sock.recv(4096)
if not buf: # just disconnect
self.sock.close()
return
# Yeah, print!
print "%r %r" % (self.addr, buf)
# reuse current event
event_obj.addToLoop()

if __name__ == '__main__':
# bind.
sock_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock_srv.setblocking(False)
sock_srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock_srv.bind(('0.0.0.0', 1111))
sock_srv.listen(5)

libevent.createSignalHandler(signal.SIGINT, callback_interrupt).addToLoop()
libevent.createEvent(sock_srv, libevent.EV_READ|libevent.EV_PERSIST, callback_onconnect).addToLoop()
libevent.dispatch()


UPDATE #1:
Here seems to be another way of connecting libevent with python, using raw ctypes: http://william-os4y.livejournal.com/3718.html.


2007-10-26

Set process name in python

How to set process name from inside it? I know that nmap can fake name, but the question is how to do this from python.
The code that is doing this magic in nmap:

# from nmap.cc
if (quashargv) {
size_t fakeargvlen = strlen(FAKE_ARGV), argvlen = strlen(argv[0]);
if (argvlen < fakeargvlen)
fatal("If you want me to fake your argv, you need to call the program with a longer name. Try the full pathname, or rename it fyodorssuperdedouperportscanner");
strncpy(argv[0], FAKE_ARGV, fakeargvlen);
memset(&argv[0][fakeargvlen], '\0', strlen(&argv[0][fakeargvlen]));
for(i=1; i < argc; i++)
memset(argv[i], '\0', strlen(argv[i]));
}
There are some possible ways of doing this from python. Some guys suggest using prctl ioctl. But it didn't worked for me. Also the module proctitle haven't done what I expected.
From time I found rtgraph3d project, I'm a fan of PyInline module. Here's my python code that's working (for me):
import PyInline, time

m = PyInline.build(code=r"""
#include <Python.h>
#include <stdio.h>
#include <string.h>

void set_argv(char *str){
int argc;
char **argv;
Py_GetArgcArgv(&argc, &argv);
strncpy(argv[0], str , strlen(str));
memset(&argv[0][strlen(str)], '\0', strlen(&argv[0][strlen(str)]));
}
""", language="C")

m.set_argv('very custom python process name')
time.sleep(100)
It looks funny from ps:
majek@tigger:~$ ps aux|grep very
majek 11688 2.6 0.4 7192 4360 pts/21 S+ 00:20 0:00 very custom python process name


2007-10-22

GNU pth instead of pthread: hardcore python tuning

Problem
I've been working on speed of an application written in python. While doing strace I found out that the most of syscalls were futex(). This futexes came from python's internal synchronization code. But the application never used any kind of threading!

Most of the users never actually realize that python is doing synchronization between threads even when threads aren't used. It's not so bad, those futex() calls are very quick about 7usecs one. But they are executed thousands times!
Sample "strace -c":

% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
67.62 0.000570 0 15192 futex
10.91 0.000092 0 896 sendto
7.00 0.000059 7 8 stat
5.34 0.000045 0 1936 poll
3.32 0.000028 0 1076 recvfrom
2.73 0.000023 1 28 open
2.02 0.000017 3 6 write
Workaround
To get rid of futex() calls one can compile python without support for threading (./configure --without-threads). The fall of this method is that some modules depend on threading, like postgresql wrapper psycopg.

There is also other method. It seems that python supports GNU pth library. This library emulates threads in userspace, using pthread compatible interface. The only non-trivial thing is to get rid of pthread and use pth while python compilation (even though pth should be supported by python out of the box).

Enabling pth is not easy, but doable. Here's the compilation procedure thanks to my friend Primitive:
$ sudo apt-get install libpth-dev
$ wget http://python.org/ftp/python/2.5.1/Python-2.5.1.tar.bz2
$ wget http://ai.pjwstk.edu.pl/~majek/dump/pyconfig.h.in-pth-patch.diff
$ tar xjf Python-2.5.1.tar.bz2
$ cd Python-2.5.1
Python-2.5.1$ cat ../pyconfig.h.in-pth-patch.diff|patch -p0
patching file pyconfig.h.in
Python-2.5.1$ ./configure --with-pth --prefix=/usr
Python-2.5.1$ find . -name Makefile -exec sed -i "s/-lpthread/-lpth/" {} \;
Python-2.5.1$ sed -i "s/-pthread//" Makefile
Python-2.5.1$ sed -i 's/$(srcdir)\/Python\/thread_pthread.h//' Makefile
Python-2.5.1$ make
Benchmarks
In corner case the time gained is about 25%-30%. The test program is not complicated at all. We know that importing modules needs synchronization. So let's do only imports:
#!/usr/bin/python
for i in xrange(1000000):
import os
Average results for standard python 2.5.1, using pthread:
real    0m2.061s
user 0m1.728s
sys 0m0.332s
Average results for patched python 2.5.1 using pth:
real    0m1.572s
user 0m1.560s
sys 0m0.008s
What's with those futexes?
Well, as I suggested futexes are gone when using pth. Here are strace results for python with pthreads:
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
99.99 1.014676 1 1000020 futex
0.01 0.000067 0 142 read
0.01 0.000057 0 4504 _llseek
And for fixed python with pth:
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00 0.000050 0 4504 _llseek
0.00 0.000000 0 142 read


2007-09-07

Python memory hack

Django and most of python frameworks eat a lot of RAM. To serve multiple pages in the same time there must be many running python processes (this is not like light www daemons which serve all requests from only one process, like lighttpd or nginx).

So every python process eats RAM. During it's live it imports many libraries and files. This imports are never freed by garbage collector. This imports are almost identical for every process, but the problem is that they are not shared between processes. If you import some library in django, it's going to be imported separately at every django process.

To reduce memory usage it's possible to import all used libraries actually before forking the python processes. Linux fork() uses copy-on-write technique, so we can think that preloaded libraries are going to be shared between python processes.

Unfortunately in python it doesn't work. That's because immutable and mutable data are stored in the same memory segment! For example header structure for immutable string is being often changed, because it contains reference counter.

I created quick memory hack for cpython. Python imports are mostly code objects, which contain code in string objects. I hacked string object, so that it allocates memory for immutable data in separate memory segment than mutable part. My hack allocates big memory segment in which immutable string data is stored. Except for storing new strings, that memory is not going to be changed during execution. I hope, that after fork(2), this memory segment will be successfully shared between threads. The bad side is that this memory is never freed.

Example usage:

x.py:
'a'.setmajekhack() # enable hack
# do some imports here
import sys,os,time
'a'.setmajekhack() # disable hack

Simple output, this time only 17KB of strings data were put to immutable segment:
MAJEKHACK enabled 0x2b6bc0c57000
MAJEKHACK disabled, allocated 17131 bytes


Unfortunately this hack doesn't give as good results as I thought. Although I think that python memory allocator could be highly optimized for similar cases and save our precious memory.


2007-04-18

Python wrappers for memcache

Jeśli szukasz modułu do pythona, którym połączysz się do memcached, to najprostszym będzie python-memcached. Jest on prosty, stabilny, i po prostu działa.

Problem zaczyna się później w memcache.py:_Host.readline()


def readline(self):
buffers = ''
recv = self.socket.recv
while 1:
data = recv(1)
[...]

Tak, tak. python-memcache czyta z socketa po jednym bajcie. To był główny powód zainteresowania wrapperem pythona do libmemcache, czyli cmemcache.

Niestety cmemcache jest trochę niedorobiony. Jest to wina libmemcache, który w niektórych przypadkach potrafi brutalnie wywołać exit(). A nie jest to miłe, gdy proces pythona zdycha od jakiegoś głupiego błędu na socketach. Napisałem patch do libmemcache.
Drugim problemem jest to, że api cmemcache jest troszeczkę inne niż python-memcached. Na przykład "set" zwraca -1 lub 0, zamiast 0 lub 1. Naprawiliśmy to banalnym patchem do cmemcache.


PS. W nowym python-memcached już nie robią recv(1), oto odpowiedni fragment kodu:

def readline(self):
buf = self.buffer
recv = self.socket.recv
while True:
index = buf.find('\r\n')
if index >= 0:
break
data = recv(4096)


2007-01-12

Why Django sucks

Django sucks. I tyle. Pytanie tylko czy istnieje jakiś framework, który mniej sucks. I tu odpowiedzi niestety nie znam.

Django ma sporo poważnych wad. Domyślny system templateów jest żałosny. Sorry, w nim nie da się odróżnić foo[bar] od foo.bar, nie da się zdefiniować funkcji czy nawet makra.
Kierowany chęcią uruchamiania normalnych pythonowych wyrażeń przesiadłem się na template genshi.
Genshi też nie potrafi wszystkiego, ma problemy np z zagnieżdżeniami komentarzy lub cudzysłowów. Jednak jest nieporównywalnie przyjemniejsze dla programisty niż cholerne djangotemplates.
W dalszej perspektywie przymierzam się do wypróbowania makotemplates. Wygląda na to, że te template nie mają tych wad co genshi. Choć nie mają też tych samych możliwości jak np xml z xpathem.

Inne z mechanizmów django, których nie da się używać to 'forms and manipulators' czyli obsługa formularzy htmlowych. Strasznie namieszali z nazewnictwem. W kodzie mylą pojęcia, trudno zorientować się czy 'field' to pole w sensie atrybutu na modelu czy widget, który wyświetla jakiegoś boxa htmlowego. Tym niemniej największą wadą djangowych formularzy jest kompletny brak możliwości zmiany ich zachowania.
Chciałem zmienić kilka widgetów, tak aby dodać im htmlowy atrybut 'readonly'. Oczywiście modyfikowanie źródeł django odpada, więc stosując monkey patching powolutku pozmieniałem zachowanie kolejnych widgetów (lub Fieldów w notacji django). Mój kod poprawek rósł i rósł. Z pomysłu na zmianę djangowych widgetów trzeba było w końcu zrezygnować.

Ostatecznie sam napisałem system widgetów. Jest prosty, czysty i ma spore możliwości. I co najważniejsze, nie jest sztywno związany z django. Integracja z django to zaledwie jedna funkcja, która robi mokey patching na modelu i kilka funkcji generujących widgety.

Po tych cięciach wychodzi na to, że jedyne cechy django, z których da się kożystać to ORM i cała logika http typu dekodowanie url i obsługa http request i responce. A to nie wiele jak na nowoczesny framework.