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

Sunday, May 12, 2019

Testing Lua "classes" speed

"Testing" is a bit too strong word for what I've done here, but numbers are still interesting.

I developed a "smart" reverse proxy recently where I decided to use OpenResty platform - it's basically Nginx + Lua + goodies. Lua is the first class language so theoretically you can implement anything with it.

After the couple of weeks I spent with Lua it strongly reminds me JavaScript 5 - while it's a complete language, it's very "raw" in a sense that while it has constructs to do anything there is no standard (as in "industry-standard") way to do many things, classes being one of them. Having a strong Python background I'm used to spend my time mostly on business logic and not googling around to find best 3rd-party set/dict/etc. implementation. Many praise Lua's standard library asceticism (which reminds me similar sentiments in JS 5 days), but most of the time I get paid to create products, not tools. Also, lack of uniform way to do common tasks results in quite non-uniform code-base.

Having said the above, I chose OpenResty. I already had Nginx deployed, so switching to OpenResty was a natural extension. It was exactly what I was looking for - a scriptable proxy - which is OpenResty's primary goal as a project. I didn't want to take a generic web-server and write middleware/plugin for it - it sounded a bit too adventurous and risky from security perspective. So getting back to JS 5 days using niche language like Lua was a good trade-off.

Eventually I liked Lua. There is a special cuteness to it - I often find myself smiling while reading Lua code. Particularly it provided a great relief from Nginx IF evilness I used before.

Let's get to the point of this post, should we? While imbuing my proxy with some logic I decided to check which class-like approaches in Lua is the fastest. I ended up with 3 contenders:

  • Metatables
  • Closures
  • pl.class - part of the excellent PenLight Lua library that aims to complement Lua with Python-inspired data types and utilities. This class implementation is also metatable-based but involves more internal boilerplate to support, e.g. inheritance.

I implemented class to test object member access, method invocation, and method chaining. The code is in the gist.

Let's run it

I used LuaJIT 2.1.0-beta3 that is supplied with the latest OpenResty docker image. pl.class documents two ways to define a class, hence I had two versions to see if there is any difference.

Initialization speed


Func:       815,112,512 calls/sec
Metatable:  815,737,335 calls/sec
Closure:      2,459,325 calls/sec
PLClass1:     1,536,435 calls/sec
PLClass2:     1,545,817 calls/sec

Initialization + call speed


Metatable:  816,309,204 calls/sec
Closure:      2,104,911 calls/sec
PLClass1:     1,390,997 calls/sec
PLClass2:     1,453,514 calls/sec

We can see that Metatable is as fast as our baseline plain func. Also with metatable, invoke does not affect speed - probably JIT is doing amazing job here (considering the code is trivial and predictable).

Closures are much slower and invocation has cost. penlight.Class, while most syntactically rich, is the slowest one and also takes hit from invocation.

Conclusions

Being myself a casual Lua developer, I prefer Closure approach:

  • It promotes composition
  • Easy to understand - no implicit self var
  • More importantly, it's unambiguous to use - no one needs to think whether you access something by dot or colon

Again, I'm casual Lua developer. Had I spent more time within I assume my brain would adjust to things like implicit self and may be my self-recommendation would change.

For pure speed metatable is the way, though I wonder what difference it will make in real application (time your assumptions).

Out of curiosity, I did similar tests in Python (where there is one sane way to write this code). The results were surprising:

CPython3.7


Benchmarking init
Func:      18,378,052 ops/sec
Class:      4,760,040 ops/sec
Closure:    2,825,914 ops/sec
Benchmarking init+ivnoke
Class:      1,742,217 ops/sec
Closure:    1,549,709 ops/sec

PyPy3.6-7.1.1:


Benchmarking init
Func:   1,076,386,157 ops/sec
Class:    247,935,234 ops/sec
Closure:  189,527,406 ops/sec
Benchmarking init+invoke
Class:  1,073,107,020 ops/sec
Closure:  175,466,657 ops/sec

On CPython if you want to do anything with your classes beside initializing them, there is no much difference between Class and Closure. "Func" aside, its performance is on par with Lua.

PyPy just shines - its JIT outperforms Lua JIT by a far cry. The fact that speed of init+invoke on Class is similar to raw Func benchmark tells something about their ability to trace code that does nothing :)

On the emotional side

Don't believe benchmarks - lies, damn lies, and benchmarks :)

Seriously though, before thinking "why didn't they embed Python", other aspects should be contemplated:

  • Memory. Lua uses much less of it. Array of 10 million strings 10 byte each weighs 400mb in Lua while 700+mb in CPython/PyPy.
  • Python was a synchronous language originally with async support introduced much later. Nginx is an async server, hence Lua fits there more naturally, but I'm speculating here.
  • Everyone says that Lua is much easier to embed.
Finally, both can do amazing things through FFI.

Friday, February 1, 2019

A warning about JSON serialization

I added caching capabilities for one of my projects by using aiocache with JSON serializer. While doing that I came over strange issue where I was putting {1: "a"} in cache, but received {"1": "a"} on retrieval - the 1 integer key came back as "1" string. First I thought it's an bug in aiocache, but maintainer kindly pointed out that JSON, being Javascript Object Notation does not allow mapping keys to be non-strings.

However there is a point here that's worth paying attention to - it looks like JSON libraries, at least in Python and Chrome/Firefox, will happily accept {1: "a"} for encoding but will convert keys to strings. This may lead to quite subtle bugs as in my earlier example - cache hits will return data different to original.


>>> import json
>>> json.dumps({1:"a"})
'{"1": "a"}'
>>> json.loads('{1:"a"}')
Traceback (most recent call last):
  File "", line 1, in 
  File "/home/.../lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/home/.../lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/home/.../lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Friday, September 21, 2018

Docker multi-stage builds for Python apps

Previously I highly regarded Multi-Stage Docker Image build approach, though it was not immediately clear how to apply it to Python applications.

In Python you install application dependencies and (preferably) the application itself using pip tool. When we run it during image build, pip just installs everything under /usr so there is no immediate way to copy artifacts (that is the app and its dependencies installed by pip) into the next build stage.

The solution that I came up with is to coerce pip to install everything into a dedicated directory. There are many ways of doing so, but from my experiments I found installing with --user flag and properly setting PYTHONUSERBASE as the most convenient way to install both Python libraries and app binaries (e.g. entrypoint scripts).

Eventually it's quite straight forward and I wonder why I didn't find any formal guides on this.

One caveat I came along later is if you have packages already installed in system as part of pip/pipenv/setuptools dependencies, pip will not reinstall them under /pyroot, hence there will be missing dependencies in production image - this is the reason for using --ignore-installed flag.

Without further ado, let's see how it can be done.

Setup

Lets use a sample Python Hello World project that contains a proper setup.py to install both the app's libs and the entrypoint script.

Note: I urge you to use setup.py even if you don't plan to distribute your app. Simply copying your Python sources into docker image will eventually break - you may end up copying __pycache__ directories, tests, test fixtures, etc. Having a working setup.py makes it easy to use your app as an installable component in other apps/images.

Let's setup our test environment:


git clone git@github.com:haizaar/python-helloworld.git
cd python-helloworld/
# Add some artificial requirements to make the example more real
echo pycrypto==2.6.1 > requirements.txt

The Dockerfile

All the "magic" is happening below. I've added inline comments to ease on reading.

FROM alpine:3.8 AS builder

ENV LANG C.UTF-8

# This is our runtime
RUN apk add --no-cache python3
RUN ln -sf /usr/bin/pip3 /usr/bin/pip
RUN ln -sf /usr/bin/python3 /usr/bin/python

# This is dev runtime
RUN apk add --no-cache --virtual .build-deps build-base python3-dev
# Using latest versions, but pinning them
RUN pip install --upgrade pip==19.0.1
RUN pip install --upgrade setuptools==40.4.1

# This is where pip will install to
ENV PYROOT /pyroot
# A convenience to have console_scripts in PATH
ENV PATH $PYROOT/bin:$PATH
ENV PYTHONUSERBASE $PYROOT

# THE MAIN COURSE #

WORKDIR /build

# Install dependencies
COPY requirements.txt ./
RUN pip install --user --ignore-installed -r requirements.txt
# Install our application
COPY . ./
RUN pip install --user .

####################
# Production image #
####################
FROM alpine:3.8 AS prod
# This is our runtime, again
# It's better be refactored to a separate image to avoid instruction duplication
RUN apk add --no-cache python3
RUN ln -sf /usr/bin/pip3 /usr/bin/pip
RUN ln -sf /usr/bin/python3 /usr/bin/python

ENV PYROOT /pyroot
ENV PATH $PYROOT/bin:$PATH
ENV PYTHONPATH $PYROOT/lib/python:$PATH
# This is crucial for pkg_resources to work
ENV PYTHONUSERBASE $PYROOT

# Finally, copy artifacts
COPY --from=builder $PYROOT/lib/ $PYROOT/lib/
# In most cases we don't need entry points provided by other libraries
COPY --from=builder $PYROOT/bin/helloworld_in_python $PYROOT/bin/

CMD ["helloworld_in_python"]

Let's see that it works:


$ docker build -t pyhello .
$ docker run --rm -ti pyhello
Hello, world

As I mentioned before - it's really straight forward. So far I've managed to pack one of our real apps with the approach and it works well so far.

Using pipenv?

If you use pipenv, which I like a lot, you can happily apply the same approach. It's a bit tricky to coerce pipenv to install into a separate dir, but this command does the trick:

# THE MAIN COURSE #

WORKDIR /build

# Install dependencies
COPY Pipfile Pipfile.lock ./
# --ignore-installed is vital to re-install packages that are already present
# (e.g. brought by pipenv dependencies) into $PYROOT
# Need to use pip eventually because of https://github.com/pypa/pipenv/issues/4453
RUN set -ex && \
    export HOME=/tmp && \
    pipenv lock -r | pip install --user --ignore-installed -r /dev/stdin
# Install our application
COPY . ./
RUN pip install --user .

Wednesday, September 19, 2018

Reducing docker image sizes

Several years ago I started a new greenfield project. Based on the state of technology affairs back then, I decided to go full time with container technology - Docker and Kubernetes. We head dived into all of the new technologies and had our application started pretty fast. Back then the majority of Docker Library was based on Debian and it resulted in quite a large images - our average Python app container image weights about 700-1000MB. Finally the time has come to rectify it.

Why do you care

Docker images are not pulled too often and 1GB is not too big of a number in the age of clouds, so why do you care? Your mileage may vary, but these are our reasons:
  • Image pull speed - on GCE it takes about 30 seconds to pull 1GB image. While downloads when pulling from GCR are almost instant, extraction takes a notable amount of time. When a GKE node crashes and pods migrate to other nodes, the image pull time adds to your application downtime. To compare - pulling of 40MB coredns image from GCR takes only 1.3 seconds.
  • Disk space on GKE nodes - when you have lots of containers and update them often, you may end up with disk space pressure. Same goes for developers' laptops.
  • Deploying off-cloud - pulling gigabytes of data is no fun when you try that over saturated 4G network during a conference demo.

Here are the strategies current available on the market.

Use alpine based images

Sounds trivial right? - they are around for quite some time already and the majority of the Docker Library has an -alpine variant. But not all alpine images were born the same:

Docker Library alpine variant of Python:


$ docker pull python3.6-alpine
$ docker images python:3.6-alpine --format '{{.Size}}'
74.2MB

DIY alpine Python:


$ cat Dockerfile
FROM alpine:3.8
RUN apk add --no-cache python3
$ docker build -t alpython .
$ docker images alpython --format '{{.Size}}'
56.2MB

This is %25 size reduction compared to Docker Library Python!

Note: There is another "space-saving" project that provides a bit different approach - instead of providing a complete Linux distro, albeit a smaller one, they provide a minimal runtime base image for each Language. Have a look at Distroless.

Avoid unnecessary layers

It's quite natural to write your Dockerfile as follows:

FROM alpine:3.8
RUN apk add --no-cache build-base
COPY hello.c /
RUN gcc -Wall -o hello hello.c
RUN apk del build-base
RUN rm -rf hello.c

It provides nice reuse of layers cache, e.g. if hello.c changes, then we can still reuse installation of build-base package from cache. There is one problem through - in the above example, the resulting image weights 157MB(!) through actual hello binary is just 10KB:


$ cat hello.c 
#include <stdio.h>
#include <stdlib.h>

int main() {
 printf("Hello world!\n");
 return EXIT_SUCCESS;
}
$ docker build -t layers .
$ docker images layers --format '{{.Size}}'
157MB
$ docker run --rm -ti layers ls -lah /hello
-rwxr-xr-x    1 root     root       10.4K Sep 18 10:45 /hello

The reason is that each line in Dockerfile produces a new layer that constitutes a part of the image, even-through the final FS layout may not contain all of the files. You can see the hidden "convicts" using docker history:


$ docker history layers
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
8c85cd4cd954        16 minutes ago      /bin/sh -c rm -rf hello.c                       0B                  
b0f981eae17a        17 minutes ago      /bin/sh -c apk del build-base                   20.6kB              
5f5c41aaddac        17 minutes ago      /bin/sh -c gcc -Wall -o hello hello.c           10.6kB              
e820eacd8a70        18 minutes ago      /bin/sh -c #(nop) COPY file:380754830509a9a2…   104B                
0617b2ee0c0b        18 minutes ago      /bin/sh -c apk add --no-cache build-base        153MB               
196d12cf6ab1        6 days ago          /bin/sh -c #(nop)  CMD ["/bin/sh"]              0B                  
<missing>           6 days ago          /bin/sh -c #(nop) ADD file:25c10b1d1b41d46a1…   4.41MB       

The last - a missing one - is our base image, the third line from the top is our binary and the rest is just junk.

Squash those squishy bugs!

You can build docker images with --squash flag. What is does is essentially leaving your image with just two layers - the one you started FROM; and another one that contains only files that are visible in a resulting FS (minus the FROM image).

It plays nice with layer cache - all intermediate images are still cached, so building similar docker images will yield in a high cache hit. A small catch - it's still considered experimental, though the feature available since Docker 1.13 (Jan 2017). To enable it, run your dockerd with --experimental or add "experimental": true to your /etc/docker/daemon.json. I'm also not sure about its support for SaaS container builders, but you can always spin your own docker daemon.

Lets see it in action:


# Same Dockerifle as above
$ docker build --squash -t layers:squashed
$ docker images layers:squashed --format '{{.Size}}'
4.44MB

This is exactly our alpine image with 10KB of hello binary:


$ docker inspect layers:squashed | jq '.[].RootFS.Layers'  # Just two layers as promised
[
  "sha256:df64d3292fd6194b7865d7326af5255db6d81e9df29f48adde61a918fbd8c332",
  "sha256:5b55011753b4704fdd9efef0ac8a56e51a552b237238af1ba5938e20e019f440"
]
$ mkdir /tmp/img && docker save layers:squashed | tar -xC /tmp/img; du -hsc /tmp/img/*
52K /tmp/img/118227640c4bf55636e129d8a2e1eaac3e70ca867db512901b35f6247b978cdd
4.5M /tmp/img/1341a124286c4b916d8732b6ae68bf3d9753cbb0a36c4c569cb517456a66af50
4.0K /tmp/img/712000f83bae1ca16c4f18e025c0141995006f01f83ea6d9d47831649a7c71f9.json
4.0K /tmp/img/manifest.json
4.0K /tmp/img/repositories
4.6M total

Neat!

Nothing is perfect though. Squashing your layers reduces potential for reusing them when pulling images. Consider the following:


$ cat Dockerfile
FROM alpine:3.8
RUN apk add --no-cache python3
RUN apk add --no-cache --virtual .build-deps build-base openssl-dev python3-dev
RUN pip3 install pycrypto==2.6.1
RUN apk del .build-deps
COPY my.py /  # Just one "import Crypto" line

$ docker build -t mycrypto .
$ docker build --squash -t mycrypto:squashed .
$ docker images mycrypto
REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
mycrypto            squashed            9a1e85fa63f0        11 seconds ago       58.6MB
mycrypto            latest              53b3803aa92f        About a minute ago   246MB

The difference is very positive - comparing the basic Python Alpine image I have built earlier, the squashed one here is just 2 megabytes larger. The squashed image has, again, just two layers: alpine base and the rest of our Python, pycrypto, and our code squashed.

And here is the downside: If you have 10 such Python apps on your Docker/Kubernetes host, you are going to download and store Python 10 times, and instead of having 1 alpine layer (2MB), one Python layer (~50MB) and 10 app layers (10x2MB) which is ~75MB, we end up with ~600MB.

One way to avoid this is to use proper base images, e.g. instead of basing on alpine, we can build our own Python base image and work FROM it.

Lets combine

Another technique which is widely employed is combining RUN instructions to avoid "spilling over" unnecessary layers. I.e. the above docker can be rewritten as follows:

$ cat Dockerfile-comb 
FROM alpine:3.8
RUN apk add --no-cache python3  # Other Python apps will reuse it
RUN set -ex && \
 apk add --no-cache --virtual .build-deps build-base openssl-dev python3-dev && \
 pip3 install pycrypto==2.6.1 && \
 apk del .build-deps
COPY my.py /

$ docker build -f Dockerfile-comb -t mycrypto:comb .
$ docker images mycrypto
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mycrypto            comb                4b89e6ea6f72        7 seconds ago       59MB
mycrypto            squashed            9a1e85fa63f0        38 minutes ago      58.6MB
mycrypto            latest              53b3803aa92f        39 minutes ago      246MB

$ docker inspect  mycrypto:comb | jq '.[].RootFS.Layers'
[
  "sha256:df64d3292fd6194b7865d7326af5255db6d81e9df29f48adde61a918fbd8c332",
  "sha256:f9ac7d1d908f7d2afb3c724bbd5845f034aa41048afcf953672dfefdb43582d0",
  "sha256:10c59ffc3c3cb7aefbeed9db7e2dc94a39e4896941e55e26c6715649bf6c1813",
  "sha256:f0ac8bc96a6b044fe0e9b7d9452ecb6a01c1112178abad7aa80236d18be0a1f9"
]

The end result is similar to a squashed one and now we can control the layers.

Downsides? There are some.

One is a cache reuse, or lack thereof. Every single image will have to install build-base over and over. Consider some real example which has 70 lines long RUN instruction. You image may take 10 minutes to build and changing a single line in that huge instruction will start it all over.

Second is that development experience is somewhat hackish - you resort from Dockerfile mastery to shell witchery. E.g. you can easily overlook a space character chat crept after trailing backslash. This increases development times and ups our frustration - we all are humans.

Multi-stage builds

This feature is so amazing that I wonder why it is not very famous. It seems like only hard-core docker builders are aware of it.

The idea is to allow one image to borrow artifacts from another image. Lets apply it for the example that compiles C code:


$ cat Dockerfile-multi 
FROM alpine:3.8 AS builder
RUN apk add --no-cache build-base
COPY hello.c /
RUN gcc -Wall -o hello hello.c
RUN apk del build-base

FROM alpine:3.8
COPY --from=builder /hello /

$ docker build -f Dockerfile-multi -t layers:multi .
$ docker images layers
REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
layers              multi               98329d4147f0        About a minute ago   4.42MB
layers              squashed            712000f83bae        2 hours ago          4.44MB
layers              latest              a756fa351578        2 hours ago          157MB

That is, the size is as good as it gets (even a bit better, since our squashed variant still has couple of apk metadata left by). It works just great for toolchains that produce clearly distinguishable artifacts. Here is another (simplified) example for nodejs:


FROM alpine:3.8 AS builder
RUN apk add --no-cache nodejs
COPY src /src
WORKDIR /src
RUN npm install
RUN ./node_modules/.bin/jspm install
RUN ./node_modules/.bin/gulp export  # Outputs to ./build

FROM alpine:3.8
RUN apk add --no-cache nginx
COPY --from=builder /src/build /srv/www

It's more tricky for other toolchains like Python where it's not immediately clear how to copy artifacts after pip-install'ing your app. The proper way to do it, for Python, it yet to be discovered (for me).

I will not describe other perks of this feature since Docker's documentation on the subject is quite verbose.

Conclusion

As you can probably tell there is no one ultimate method to rule them all. Alpine images are no-brainer; multi-stage provides nice & clean separation, but I lack RUN --from=...; squashing has its trade-offs; and humongous RUN instructions are still a necessary evil.

We use multi-stage approach for our nodejs images and mega-RUNs for Python ones. When I find a clean way to extract pip's artifacts, I will definitely move to multi-stage builds there as well.

Tuesday, November 3, 2015

Time your assumptions

This short post is sort of a reminder to myself not to get too lazy about assuming stuff.

Suppose you have a dictionary in Python. Millions of them actually, coming as a stream. You need to filter out dictionaries that have one or more of their values equal to None. So you start with the obvious

# dicts is a list of dictionaries
for d in dicts:
    if None in d.values():
        continue
    process(d)

Then you realize that d.values() returns list (or list-like in Python 3), and membership test in Python list costs you O(n) complexity, and that thought additionally backed up by the fact, that majority of the dictionaries in the stream do not have None in them, i.e. most of the time the code will scan and compare the whole list of values of every dictionary.

The next obvious step is to use the powers of set:

# dicts is a list of dictionaries
for d in dicts:
    if None in set(d.values()):
        continue
    process(d)

But then, some quiet bird in the back of your head keeps singing "Is it really worth it"? And then you slap your lob forehead - of course not! To build set one needs to scan the list anyway and that's already O(n); on top of that you need to build the set data structure itself and invoke membership testing, etc... Anyway, given a list of unknown values one needs to read each of them at least once for a membership testing.

In fact, micro-benchmarking shows exactly this

$ python -mtimeit "None in [1,2,3,4,5,6,7,8,9,10]"
1000000 loops, best of 3: 0.239 usec per loop
$ python -mtimeit "None in set([1,2,3,4,5,6,7,8,9,10])"
1000000 loops, best of 3: 0.535 usec per loop
I.e. the use of set, slows us down two times!

Python 3

It turns out that membership testing for a list in Python 3.4 is about 25-30% faster:
$ python3 -mtimeit "None in [1,2,3,4,5,6,7,8,9,10]"
1000000 loops, best of 3: 0.181 usec per loop

Friday, June 5, 2015

Do we really need to keep writing Python async adapters for every database?

I've entered the realm of async programming in Python about two years ago. I've started with Tornado framework and my first task was to design REST API against backend powered by ElasticSearch. Luckily, ElasticSearch speaks HTTP and Tornado comes with async http client - no worries. Later on, I needed to speak to Postgres and found Momoko project that wraps async functionality of psycopg2 for Tornado. It was a bit rusty and dusty, but with some patching worked well.

Next came MySQL... well, this is when I started to ask myself questions. The thing is that I did not find anything stable for MySQL. Tornado wiki lists couple of projects - first has unclear license and too many bold warnings, the other one did not had any releases since 2009. At the end I've ended up using ad-hock pooling software based on good old MySQLdb, plus ThreadExecutor from concurrent.futures package. Fortunately my project did go further then prototype.

Time went on as I decided to rewrite Momoko to use Tornado's new Future interface. After rewrite I run some benchmarks and the results were quite surprising. In fact async code introduces quite a bit of overhead. So if your database is very fast and you don't open huge amount of connections (less then 100), async code has actually more overhead then threaded code. And obviously you are not going to open hundreds of database connections from a single Tornado process. I.e. in real life, connection handling overhead will be negligible compared to database response.

So do we really need native async adapters for every SQL database? Looks like we don't. And that's probably why there are no any Tornado adapters for neither MSSQL nor Oracle.

What I really liked about Momoko is its connection pooling. It behaves like... well, like a good connection pooling that you get from SQLAchemy for example. So I think the ultimate solution for async connectivity to SQL databases would be async connection pool project that would expose native Future-based interface and use ThreadExecutor behind the scenes to utilize any Python DB2ABI driver. This will unleash async power to any of the existing DB2API modules.

Sounds like an idea for the next open source project. Unless there already exist one. Did I miss it?

Wednesday, April 22, 2015

Python functions - partial vs inline

When doing async programming it very natural to write a code like this:
def _connect_one(self, conn):
    future = Future()
    def on_connect(fut):
        # Do something useful here
        future.result(conn)

    self.ioloop.add_future(conn.connect(), on_connect)
    return future
I define a callback function, inline - and it allows me easy access to local closure variables. Another alternative is to factor out the callback to a separate method and to use partial to bind input arguments:
from functools import partial

def _on_connect(self, orig_future, conn, future):
    # Do something useful here
    orig_future.result(conn)

def _connect_one(self, conn):
    future = Future()
    self.ioloop.add_future(conn.connect(), partial(self._on_connect, future, conn))
    return future
To some this may look more elegant, especially if in real life your callbacks become large. However I was only interested to find out which way is faster. To test this, I've created this simple piece of code:
from __future__ import print_function
from functools import partial
import time

class Runner(object):
    def inline(self):
        a = "foo"
        b = "bar"
        def go():
            c = 2
            d = 3
            if c < d:
                e = a + b
        go()
 
    def go(self, a, b):
        c = 2
        d = 3
        if c < d:
            e = a + b

    def explicit(self):
        self.go("foo", "bar")

    def partial(self):
        partial(self.go, "foo", "bar")()

def run(what, count):
    start = time.time()
    c = count
    while c:
        c -= 1
        what()
    print("%s took %.2f seconds for %s iterations" % (what.__name__, time.time() - start, count))

runner = Runner()
run(runner.explicit, 10000000)
run(runner.inline, 10000000)
run(runner.partial, 10000000)
I've run it in Python 2, Python 3 and PyPy and here are the results:

Python 2.7.8
explicit took 3.02 seconds for 10000000 iterations
inline took 4.74 seconds for 10000000 iterations
partial took 4.90 seconds for 10000000 iterations
Python 3.4.2
explicit took 2.73 seconds for 10000000 iterations
inline took 3.84 seconds for 10000000 iterations
partial took 4.13 seconds for 10000000 iterations
PyPy 2.5.1
explicit took 0.03 seconds for 10000000 iterations
inline took 0.16 seconds for 10000000 iterations
partial took 0.15 seconds for 10000000 iterations
I was surprised that inline was actually faster then partial, considering that partial is implemented in C in CPython. It seems that it takes less time for Python to skim through existing function definition than to create a function wrapper. Explicit version is the fastest one obviously. But what matters most, is that all three versions are fast enough for real-life applications - any of them can do more than 2 million calls per second on my dusty laptop.

P.S. As usual, PyPy renders lots of micro-measurments like this to be not relevant :)

Monday, February 2, 2015

Python Singleton pattern - generic approach. Part II

This is the second part that talks about Python generic singleton pattern. In the first part I've talked about decorator approach and now we'll look into classmethod approach.

@classmethod approach

Another way to implement singleton is to prevent any actual instance creation and use our class itself as a singleton:
class SingletonClass(object):
    __initialized = False

    def __new__(cls, *args, **kwargs):
        if not cls.__initialized:
            cls.__init__(*args, **kwargs)
            cls.__initialized = True
        return cls

class MyClass(SingletonClass):
   @classmethod
   def __init__(cls, x, y):
       print "init is here"
            
   @classmethod
   def do(cls):
       print "doing stuff"

The downside is that we now have to decorate each of our methods with @classmethod which is inconvenient and defies my original desire that I could turn any existing class into singleton.

OK, so if we need to type @classmethod string before each and every method we define in MyClass, why don't we kindly ask Python do it for us? Metaclasses comes to mind - we actually want to convert all methods of the MyClass to classmethods. MyClass is created during its type __new__ stage, so lets hook in:

class SingletonClassMeta(type):
    def __new__(mcls, *args, **kwargs):
        cls = super(SingletonClassMeta, mcls).__new__(mcls, *args, **kwargs)
        for k, v in cls.__dict__.items():
            if isinstance(v, types.FunctionType):
                setattr(cls, k, classmethod(v))
        return cls

class SingletonClass(object):
    __metaclass__ = SingletonClassMeta
    __initialized = False
    ...

We just check that if MyClass has an attribute that is plain function, we convert this function to classmethod (decorators are just callables, so we are calling them :). Now the definition of MyClass is more elegant:

class MyClass(SingletonClass):
   def __init__(cls, x, y):
       print "init is here"
            
   def do(cls):
       print "doing stuff"

This is almost perfect. I write my class as usual, just need to inherit from SingletonClass. I say "almost", because given third-party class OtherClass I still can not convert it to singleton. The below will NOT make MyClass.do to behave as if MyClass was a singleton:

class OtherClass(object):
   def __init__(cls, x, y):
       print "init is here"
            
   def do(cls):
       print "doing stuff"

class MyClass(SingletonClass, OtherClass): pass

It does not do the trick because the metaclass's __new__ augments attributes defined in our class (MyClass that is) and in the later case, MyClass does not define any attributes at all - they all are in its base class OtherClass.

So how to solve this? Well, we could look through our MRO chain during metacalss __new__ and to augment attributes of our base classes, but that's quite a destructive process - we screw things up for other regular users of a particular base class.

To overcome this we need to hook in into attribute lookup mechanism of MyClass. Here is the revised metaclass:

import types
class SingletonClassMeta(type):
    def __getattribute__(cls, attr):
        val = super(SingletonClassMeta, cls).__getattribute__(attr)
        if isinstance(val, types.MethodType) and not val.__self__:
            val = types.MethodType(val.__func__, cls, type(cls))
            # the above is equivalent to:
            # val = val.__func__.__get__(cls, type(cls))
        return val

Here our metaclass overloads the attribute lookup machinery:

  • We are doing regular attribute lookup
  • Then we check that attribute value is an unbound method - by checking that it is a method and its self is None
  • If its an unbound methond, we construct new, bound method on the fly from the original function

There is one rather long but important point to note here:

  • Previously, code in __new__ method change attributes of the class before they were ever accessed. Attribute retrieval machinery is described here, but in very short it can be summed as "Look the __dict of instance, its class and its parents. If whatever you found has __get__ method, call it with current instance and its type and return result to the caller".
  • Every python function is a descriptor! That is, when you stuff any function in some class __dict__ and then try to retrieve it later as an attribute, descriptor protocol kicks in and returns bound/unbound methods instead.
  • Back to __new__ - when we set class attribute, it needs to be something that would play nice with attribute lookup protocol. We used classmethod which is a decorator object that remembers a function and then acts as descriptor converting remembered function to bound (to class) method when it get fetched. We could (almost) equally just do setattr(cls, k, functools.partial(v, cls)) - it would do the job as well, but would break semantics, because if someone would inspect our class methods it would see <functools.partial object... instead of <bound method..., that's why I prefer to use classmethod
  • In our last example, we took full responsibility for object retrieval. Thus if we try to just return classmethod(val.__func__) we'd fail with
    TypeError: 'classmethod' object is not callable
    
    We took the responsibility, so no one cares if we are returning a descriptor. That is, we need to build and return bound method by ourselves. Again, every function is a descriptor, i.e. every function has __get__ method. You can construct method from any function - it does not even have to belong to any particular class:
    >>> class C(object): pass
    ... 
    >>> def a(): pass
    ... 
    >>> a.__get__(C(), C) # instance method of C()
    >
    >>> 
    >>> a.__get__(C, type(C)) # class method of C
    >
    >>> 
    
    

Tuesday, January 27, 2015

Python Singleton pattern - generic approach. Part I

Today I was puzzled with implementing Singleton pattern in Python. I wanted instrumentational approach, i.e. not to write your class as singleton from ground up, but to take any existing class and turn it into singleton.

Simple as it may seem, I've ended with two part blog post series on the subject. This part talks about decorator approach and the next part talks about classmethod approach. Enjoy.

Decorator approach

Stackoverflow hinted a decorator approach, but that example breaks Python object model. Particularly, considering:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass(object):
    pass

Then the following would reasonably fail:

c = MyClass()
isinstance(c, MyClass)

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
Since in fact after decoration MyClass is a function and not a class.

To fix this, we'll rewrite decorator to return class instead. And to make sure that inheritance check works, we'll inherit from decorated class during decoration process.

def SingletonClass(cls):
    class Single(cls):
        __doc__ = cls.__doc__
        _initialized = False
        _instance = None
        
        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
            return cls._instance
                       
        def __init__(self, *args, **kwargs):
            if self._initialized:
                return
            super(Single, self).__init__(*args, **kwargs)
            self.__class__._initialized = True
    return Single

@SingletonClass
class MyClass(object):
    pass
Now isinstance does the right thing:
>>> c = MyClass()
>>> isinstance(c, MyClass)
True

We are sort of double-cheating here, since even c.__class__ == MyClass is true. I say cheating because both of them are actually <class 'Single'> and original MyClass class is lost during decoration.

And a final touch is to copy a doc string of course :)

Wednesday, December 31, 2014

Defining __str__ for class in Python

From time to time I use classes as enums:
class POLL_BASE(object): pass
class POLL_READ(POLL_BASE): pass
class POLL_WRITE(POLL_BASE): pass
No I can inspect whether function returns a final value or a hint that I need to poll its socket to wait for more data.
rv = work()
if issubclass(rv, p.POLL_BASE):
    print "work() returned %s" % rv
    # poll socket
else:
    # we are done!
Now while debugging it you'll notice that print statement above will output this:
work() returned <class '__main__.POLL_WRITE'>
The above is readable, but I wanted something more pretty. However trying to define __str__ method on POLL_BASE class did not help - in fact it will be invoked on POLL_BASE instances but not POLL_BASE itself.

Here is the trick: since __str__ is invoked on instances, then we need to define it on instance class. The "class" of POLL_BASE is type so we can define our own metaclass for POLL_BASE:

class POLL_META(type):
    # This is for fancy printing of POLL_* class names
    def __str__(cls):
        return cls.__name__

class POLL_BASE(object):
    __metaclass__ = POLL_META
Now our fancy printing will work:
work() returned POLL_WRITE

Wednesday, August 20, 2014

WAT in python

Finally found some WAT in Python as well. Here it is:
>>> ['a', 'b' 'c']
['a', 'bc']
WAT?? Implicit string concatenation? Yes, it is unfortunately. In configuration lists of strings it can be very harmful since it can silently do a wrong thing. There was PEP to remove it in Py3k, but the demand was not strong enough unfortunately.

Wednesday, February 26, 2014

dh-virtualenv - the ultimate way of deploying python apps

Its been a while since I've had to deploy a complete python application. This it not a web app - just stand-alone python daemon. Its not even online, so no AWS Beanstalk, Heroku or other frameworks are relevant.

There is a good old virtualenv + pip -r requirements.txt way. But it requires custom scriptology to roll out new code, run before/after update scripts and all that other tasks that we, programmers, like leave to "integration" stage of the project :). So I've googled to check whether is there any good news on this subject.

And there are! - dh-virtualenv. IMHO it is as good as it can be if you use Debian-based distro. In the nutshell, it wraps your whole virtualenv together with your code into one single deb package. So the deployment boils down to:

  • Copy resulting deb file to target machine
  • Run sudo dpkg -i mypackage.deb
  • Run sudo apt-get install -f - this one is to automatically install missing dependencies for your package
That's it. No need for any custom install/upgrade/uninstall tinkering - just make sure your Debian package behaves as a good citizen. And dpkg system already has tons of tools for system integration, like installing cron files, config files, creating directories, etc. If you have python script files installed through setup.py then after installation you can run them just like this:
/usr/share/python/<YOU PACKAGE NAME>/bin/myscript
And it will automatically use your venv's python and all your packages! Convenient, isn't it?

Using dh-virtualenv is straight-forward, especially if you have some background on Debian packaging. I've just followed the tutorial. However there are some quirks you better be aware of:

Caching pip downloads

Each time you'll run dpkg-buildpackage dh-virtualenv will download all of the packages from your requirements.txt. If you have a dozen packages that becomes really annoying and lengthens your build time significantly.

To make things worse, pip gets random Connection reset by peer errors. Its a lesser problem when installing packages interactively, because pip uses cache and install attempt usually succeeds from the second try. But if you hit this with dh-virtualenv, next time it will start from the beginning. I found myself running dpkg-buildpackage 6-7 times until download went successfully - definitely not an option.

The cure is to run your own, local and transparent PyPi mirror. I've used devpi - its sort of a transparent caching proxy daemon for PyPi. Just follow the setup steps in the above link and you'll have it running in no time. The next step is to make dh-virtualenv aware of it. Here are my debian/rules to introduce dh-virtualenv to devpi:

#!/usr/bin/make -f
%:
    dh $@ --with python-virtualenv

override_dh_virtualenv:
    dh_virtualenv --pypi-url http://localhost:3141/root/pypi/

(Note that this a Makefile and those spaces in the beginning of the lines should be tabs!)

Build your package on a server with similar Debian/Ubuntu version

For example, building your package on Ubuntu 13.10 and deploying it Ubuntu 12.04 LTS would not work if your code uses C extensions (even through imported packages). This issue is general to virtualenv and is not dh-virtualenv specific. For example if you create virtualenv and copy it to another, binary-incompatible server, then chances are that you'll be able to run python from this copied venv, but will NOT be able to import, say, ssl. This is because python executable is embedded into virtualenv, but standard libraries are not; and of course importing module compiled against other version of interpreter would not work.

The problem does not ends here - if you upgrade python on your production server (through apt) as part of security upgrade or similar, then it will break your virtualenv!

The bottom line - if you are going to deploy to a certain version of Debian/Ubuntu, then have another separate "builder" server with the same OS where you'll build your package and note:

  • If you run apt-get upgrade - run it on both servers
  • If you upgrade python as part of the upgrade - better rebuild and redeploy your app

Hooking your own post-build commands

If you custom operations performed before the deb file is being packed it may be not obvious where to hook them. Defining override_dh_install target will probably be not that helpful, because it runs before dh_virtualenv - your python files just will not be installed yet. So the solution I've found is to hook them into dh_virtualenv override:
#!/usr/bin/make -f
%:
    dh $@ --with python-virtualenv

override_dh_virtualenv:
    dh_virtualenv --pypi-url http://localhost:3141/root/pypi/
    # !! your commands go here !!

Final words

I think that this project is a big leap forward in deploying python packages in most convenient and dependency-managed manner. I hope you'll enjoy it as much as I do.

Tuesday, August 13, 2013

Python Enum on steroids

We all do love and remember enum type from C. And I have always been missing it for Python. You can get along with class definitions for starters:
class UserRoles(object):
    root = 10
    user = 20
    nobody = 30
But it quickly complicates:
def check_perms(role):
    if role != UserRoles.root:
        raise Exception("Access denied for group %s" % role)
The above will print something like Access denied for group 20 which is not very user friendly.

Thus over time, I've came to the following enum requirements that work for me:

  • Enum value should give easy access to its name
  • Enums should behave like native types they where assigned to. For example, integer enums should not differ from integers, when storing them in SQL datatabase
  • I should be able to assign descriptions to enums. I.e. print UserRoles.root.desc
  • I should be able to resolve enum by its name. I.e. role = UserRoles.__by_name__('admin')
  • I should be able to cast native type to enum. I.e. role = UserRoles(10)
So with a little help of metaclasses, I've managed to create a very useful enum class for myself. Lets see it in action first:
class UserRoles(Enum):
    root = 10
    user = 20
    user__desc = "Regular users"
    nobody = 30
>>> UserRoles.root
10
>>> UserRoles.root.name
'root'  # Wow, I have a name!
>>> UserRoles.user.desc
'Regular users'   # And even description 
>>> UserRoles.root == 10 
True    # I look and quack just like the native type I was assigned to
>>> role = UserRoles(10)   # Cast me! (with the value you get from DB for example)
>>> role
10
>>> role.name
'root'
>>> role == 10
True
>>> role == UserRoles.root
True
>>> role = UserRoles.__by_name__('root')    # Get me by name
>>> role
10
>>> role in UserRoles    # You can iterate us
True
>>> for role in UserRoles:
...   print "Role %s evaluates to %s" % (role.name, role)
... 
Role root evaluates to 10
Role user evaluates to 20
Role nobody evaluates to 30
>>> len(UserRoles)    # We are massive! :)
3
>>> 
Now if you like the above goodness, here is the implementations of Enum
class EnumMeta(type):
    __excludes__ = ()

    def __new__(mcs, name, base, d):
        cls = super(EnumMeta, mcs).__new__(mcs, name, base, d)
        cls.__values__ = set()
        cls.__members__ = dict()
        for k, v in cls.__dict__.items():
            if k in cls.__excludes__ or k.startswith("_") or k.find("__") > 0:
                continue

            pname = getattr(cls, k+"__name", k)
            pdesc = getattr(cls, k+"__desc", "")
            prop = type(type(v).__name__, (type(v),), {"name" : pname, "desc" : pdesc})
            p = prop(v)
            setattr(cls, k, p)
            cls.__values__.add(p)
            cls.__members__[v] = p

        return cls

    def __contains__(self, val):
        return val in self.__values__

    def __iter__(self):
        for i in self.__values__:
            yield i

    def __len__(self):
        return len(self.__values__)

    def __by_name__(self, name):
        if not hasattr(self, name):
            raise ValueError("%s has no property named %s" % (self.__name__, name))
        return getattr(self, name)

    def __call__(self, val):
        if val not in self.__members__:
            raise ValueError("%s has no property with value %s" % (self.__name__, val))
        return self.__members__[val]
                   
                   
class Enum(object):       
    __metaclass__ = EnumMeta  
One can notice that all of the heavy work is done during creation of enum class (i.e. when you import your code). After that you working with native types derivatives, thus performance penalty compared to using purely unorganized native types is mostly negligible. Here are some more explanations to the code:
  • Enum has __metaclass__ set. Metaclass is "a class of a class". In classic OOP we have Class → Object. In Python there is one more level: Type → Class → Object. Object is instance of its Class, similarly Class is instance of its Type
  • The __new__ method - when it belongs to a class, its called when a new instance is created. But when it belongs to metaclass, its called when class is created - Enum (sub)class in our case
  • So once module containing a class that inherits fromEnum is imported, we drop into process of new class creation
  • We inspect this class, iterating over all its members that do not start with _ and do not have have __
  • Now the magic type-type-type line - here what it actually does:
    • Identify a class of the defined property and create a new class that inherits from it
    • Then create new instance of this class based on original property (copy-constructor sort of)
    • On the go, we assign this class name and description attributes
  • To spice things up, the metaclass also defines all of the regular Python object model methods to make newly created enum class callable, iteratable, etc.

Friday, August 9, 2013

Python - Putting dot in the dict

One good thing about JavaScript is that one can access its dictionaries by dot notation. Well, JavaScript does not have dictionaries and people use object instead, but the point is that I've wanted to have data structure in Python that would allow me this:
>>> d = MagicDict({1: {2: 3}})
>>> d.a.b.c.d = "magic!"
>>> import json; print json.dumps(d, indent=2)
{
  "a": {
    "b": {
      "c": {
        "d": "magic!"
      }
    }
  }, 
  "1": {
    "2": 3
  }
}
>>>

Actually this small experiment inspired by DotDict found in pyes project.

So to make myself happy, I've bred DotDict and defaultdict to complete the picture:

from collections import defaultdict

class DefaultDotDict(defaultdict):
    def __init__(self, *args, **kwargs):
        super(DefaultDotDict, self).__init__(DefaultDotDict)
        if args or kwargs:
            dict.__init__(self, *args, **kwargs)

    def __getattr__(self, attr):
        if attr.startswith('_'):
            raise AttributeError  # Magic only works for key that do not start with "_"
        val = self.__getitem__(attr)
        if isinstance(val, dict) and not isinstance(val, DefaultDotDict):
            val = DefaultDotDict(val)
        self[attr] = val
        return val

    def __setattr__(self, attr, val):
        return self.__setitem__(attr, val)

    def __delattr__(self, attr):
        return self.__delitem__(attr)

    def __deepcopy__(self, memo):
        return DefaultDotDict(
                 [(copy.deepcopy(k, memo), copy.deepcopy(v, memo)) for k, v in self.items()])

Thursday, August 8, 2013

Onetime evaluation for Python object method

Following technique described in a previous post, another interesting problem can be solved.

I would like to delay object method evaluation until I access the method and I want to evaluate it only once.

In straight-forward approach, the following can be written:

class BigMath(object):
    def get_big_data(self):
        if hasattr(self, "_rv"):
            return self._rv
        self._rv = self._get_big_data()
        return self._rv
        
    def _get_big_data(self):
        print "working hard...."
        return 42
>>> m = d.BigMath()
>>> m.get_big_data()
working hard....
42
>>> m.get_big_data()
42
>>> 
Hard work is only done once as we can see. Additionally we can rename a get_big_data to big_data and make is property.

The above approach is simple and trivial. However reduplicating it from class to class and from method to method makes things boggy. I would like to have something reusable that I can apply on desired methods. Like this:

class BigMath(object):
    @OneTime
    def big_data(self):
        print "working hard...."
        return 42
Much more elegant, right? Now lets reveal that magic OneTime decorator.
class OneTime(object):
    def __init__(self, func):
        self.func = func

    def __get__(self, obj, cls):
        to_augment = obj or cls
        rv = self.func(to_augment)
        setattr(to_augment, self.func.__name__, rv)
        return rv
Its actually straight-forward if you are familiar with class-as-decorator technique:
  • Again, we create class that behaves both as decorator and descriptor
  • This is parameter-less decorator, so we need to implement only __init__ and not __call__
  • We records the method function
  • When method is accessed (i.e. __get__ gets invoked), we execute the function and cache its results by overriding ourselves.
Enjoy.

Tuesday, July 23, 2013

Delaying attribute initialization for Python class/object

I've found myself in need to delay initialization of a certain class/object attribute until I access for the first time.

For example, I have db module that has Connections class and this class in turn has two attributes - read_conn and write_conn. I did not want to create those these connections in advance - because the code may not even use them. Also I did not want each time I access db.Connection.read_conn to check whether I've already created this connection or not.

Now for simplicity of solution explanation, lets abstract from real-life example above to this: I have nursery module containing Mother class with several Baby attributes. Each baby is a instance of Baby. The trick is that I do not want babies to be "born" until they are accessed for the first time.

So we start with the following:

class Baby(object):
    def __init__(self, name):
        print "%s is born" % name
        self.name = name

class Mother(object):
    john = Baby("John")
The above of course does not do what I want - when I load this module, the john value is initialized right away:
>>> import nursery
John is born
To achieve what I want I need somehow to interfere in the process of accessing the john argument. Python has something called descriptors that can do just that. Lets use them:
class BabyDescriptor(object):
    def __init__(self, baby_name):
        self.baby_name = baby_name
        self.instance = None

    def __get__(self, obj, cls):
        if not self.instance:
            self.instance = Baby(self.baby_name)
        return self.instance
        
class Mother(object):
    john = BabyDescriptor("John")
>>> import nursery   # no babies are born!
>>> nursery.Mother.john
John is born
<nursery.Baby object at 0x7ffe909c4050>
>>> nursery.Mother.john
<nursery.Baby object at 0x7ffe909c4050>
>>> 
This is better! Babies are born on demand :) The only downside are:
  • nursery.Mother.john points to descriptor instance and not to the Baby instance
  • The descriptor checks every time if it has already created the object
To solve this, I need to reassign john attribute to point to the real Baby instance once I create it:
class BabyDescriptor(object):
    def __init__(self, baby_name, prop_name):
        self.baby_name = baby_name
        self.prop_name = prop_name

    def __get__(self, obj, cls):
        to_augment = obj or cls # To insure it works from both Mother.john and Mother().john
        instance = Baby(self.baby_name)
        setattr(to_augment, self.prop_name, instance)
        return instance
        
class Mother(object):
    john = BabyDescriptor("John", "john") # attribute name is specified twice :(
>>> import nursery
>>> nursery.Mother.john
John is born
<nursery.Baby object at 0x7fe7ab115cd0>
>>> nursery.Mother.__dict__['john']
<nursery.Baby object at 0x7fe7ab115cd0> # Yeehaw!! - Baby instance not BabyDescriptor!
>>>
This almost perfect! It does the job but missing some elegance - notably, I do not like the fact that I have to specify attribute name twice. Fortunately Python is flexible enough to figure it out "automagically". To achieve this I have to add some decorator functionality to BabyDescriptor:
class BabyDescDecotrator(object):
    def __init__(self, baby_name):
        self.baby_name = baby_name

    def __call__(self, prop):
        self.prop = prop
        return self # Important to return ourselves to keep functioning as descriptor

    def __get__(self, obj, cls):
        to_augment = obj or cls 
        instance = Baby(self.baby_name)
        setattr(to_augment, self.prop.__name__, instance) # extracting name form the prop
        return instance
        
class Mother(object):
    @BabyDescDecotrator("John")
    def john(self): pass
Lets see now how the john is constructed:
  • When loading module, Python sees that we have a decorated attribute. It also notes that this decorator takes parameters
  • So Python invokes BabyDescDecotrator("John")(john) and assigns the result to Mother's john attribute:
    • First __init__ is called recording desired baby name in the instance
    • Then resulting BabyDescDecotrator instance is __call__-ed recording the property it decorates
  • Then when we access john, Baby instance is created and Mother is augmented

Finally

Finally, below is the generic code that can proxy any class with any arguments:
class ProxyProperty(object):
    def __init__(self, *args, **kwargs):
        if not args:
            raise ValueError("Need at least to supply class object")
        self.klass = args[0]
        if not isinstance(self.klass, type):
            raise ValueError("Supplied argument does not look like a class")

        self.klass_args = args[1:]
        self.klass_kwargs = kwargs
        print self.klass, self.klass_args, self.klass_kwargs

    def __call__(self, prop):
        self.prop = prop
        return self

    def __get__(self, obj, cls):
        to_augment = obj or cls
        instance = self.klass(*self.klass_args, **self.klass_kwargs)
        setattr(to_augment, self.prop.__name__, instance)
        return instance
And here is how you use it:
    class Mother(object):
        @ProxyProperty(Baby, "Scott")
        def scott(self): pass

        @ProxyProperty(Baby, "John")
        def john(self): pass

Thursday, February 21, 2013

Tree traversal - the Python loop

Computer Science states that every recursive function can be reimplemented with just a loop. So how about rewriting the previous recursive example?

Lets recall our data structure first:

class TreeNode(object):
    def __init__(self, name):
        self.children = list()
        self.name = name

root = TreeNode("Root")
root.children.extend( (TreeNode("Fruits"), TreeNode("Berries")) )
root.children[0].children.extend( (TreeNode("Apple"), TreeNode("Peach")) )
root.children[1].children.extend( (TreeNode("Cherry"), TreeNode("Mullberry")) )
The task: Find all paths of the tree from root to leafs.

The looping solution

def traverse(node):
    to_crawl = deque()
    lastlevel = curlevel = 0
    to_crawl.append((curlevel, node))
    breadcrumb = list()

    while to_crawl:
        curlevel, curnode = to_crawl.popleft()
        while lastlevel and lastlevel >= curlevel:
            breadcrumb.pop()
            lastlevel -= 1
        breadcrumb.append(curnode.name)
        yield breadcrumb
        to_crawl.extendleft([ (curlevel+1, c) for c in curnode.children ])
        lastlevel = curlevel
The idea is to use excellent deque data structure, which can be thought of a list that can be efficiently appended/popped from both left and right.

Again, lets use it:

for breadcrumb in traverse(root):
    print breadcrumb
Which will print:
['Root']
['Root', 'Berries']
['Root', 'Berries', 'Mullberry']
['Root', 'Berries', 'Cherry']
['Root', 'Fruits']
['Root', 'Fruits', 'Peach']
['Root', 'Fruits', 'Apple']
Cautious reader will note that the tree is indeed traversed but in the reversed order. The reason is when one extends the deque from left, and consequently pops out items out (from left again) it creates LIFO order, effectively reversing the children processing order. The fix would be to originally insert the children to deque in the reverse order. So instead of:
to_crawl.extendleft([ (curlevel+1, c) for c in curnode.children ])
we can manually insert children in the reversed order like this:
to_crawl.extendleft([ (curlevel+1, curnode.children[i]) for i in xrange(len(curnode.children)-1, -1, -1) ])

Complexity

Time: O(n) - same as with recursion.

Memory: O(log n)K + O(log n). First O(log n) for recursion depth, second O(log n) path buffer. About K - its an average number of children per node - our crawling buffer holds reference to all of the children for each node we encounter, so we need to account for that.

Advantages
Same as with python recursion solution, but even better - no recursion here.

Disadvantages
The only disadvantage I can spot is the fact that we hold references to the children of the nodes we crawl. On extremely shallow and wide trees this can raise the memory footprint almost to O(n). The recursive solution however would still provide O(log n) in this extreme case.

Tuesday, February 12, 2013

Handling tmeouts with Amazon Elastic Load Balancer and autoscaling

Introduction

I've had to deploy scalable web service around application that our company developed. I've created a small Flask server to handler HTTP requests, pass through application and return the results. Now how to make it scale?

So here comes the lego:

  • Put Flask under WSGI container - uwsgi was chosen
  • Run that container on a single server with multiple processes/threads. I've also added nginx as a reverse proxy before uwsgi
  • Add servers when request rate goes up, remove servers when request rate goes down
  • Put this setup behind HTTP load-balancer to distribute requests
At the beginning Amazon Elastic Beantalk looked very appealing - like it has it all. But our application behind the flask is written in C++ and making it run on Elastic Beanstalk instance would be a serious challenge by itself; and using custom AMI basically defeats most of the benefits provided by this AWS service.

So I've went with a more custom scenario - AWS autoscaling group with my own instances and metrics + Elastic Load Balancer.

Bootstrap went smooth and the whole system was up in a couple of days. Instances went up and down depending on the load, but during stress testing we've run into weird connection timeout/drop issues that took a while to understand.

Now come the timeouts

Too many availability zones

It was tempting to enable all availability zones for the load balancer, although we keep only one instance online when the cluster is idle. I thought that load balancer will be smart enough to notice that it has only one instance and not try routing requests to other availability zones, that apparently do not have any of the servers. Well, for that matter, Amazon load-balancer is dumb - if you enable 5 availability zones, DNS end point will always resolve to 5 rotating IPs no-matter how many actually servers you have.

So the first advice is to make sure that number of enabled availability zones in ELB is at least as the number of minimum servers you keep online in scaling group.

Client app gets connections being closed in its face

The symptom was that our stress-load client got (random) "Got empty reply from server"-like errors from Python's urllib:
Failed connecting to web_api (): ('http protocol error', 0, 'got a bad status line', None)
On a server side we've got plenty of "SIGPIPE" errors from uwsgi:
write(): Broken pipe [proto/uwsgi.c line 145] during GET /.... (127.0.0.1)
IOError: write error

After pretty lot of digging, we found that connections are being dropped at two places:

First, ELB has internal "feature" of closing all incoming HTTP connections that do not get response within 60 seconds. I.e. if your client executes GET ... and waits for more then 60 seconds - ELB will close the connection. This timeout is currently unconfigurable through amazon API and even not advertised in Amazon docs. Rumors say that you can still adjust this timeout per load balancer by writing a mail to amazon support people.

Second "criminal" was uwsgi - it has default 30 second timeout for sockets it creates. I.e. after socket is idle for 30 seconds - kernel just closes it and when later uwsgi want to write long-awaited response to the socket - "oh my God! SIGPIPE! Socket closed! Client disconnected!". No, pal, I have news for you, its not a client, its your own socket you (uwsgi master process?) created. Fixed by passing --http-timeout 60 to uwsgi startup script (to actually match the timeout of load balancer).

And that is the story of load balancers, uwsgi and connection issues. Those default 60 and 30 second values are probably never noticed by majority of web apps that strive to get sub-second response times. Our application requests take long to process by their nature, so we hit them all.

Saturday, August 25, 2012

Tree traversal - the Python recursion

This is the second part of of my tree traversal series. In part I I've went through a classical recursion algorithm, and today I'll rewrite it "in a Python way".

Python recursion solution

Given the same tree structure as in part I:
def traverse_recursive(node, path=list()):
    path.append(node.name)
    yield path
    for n in node.children:
        for path in traverse_recursive(n, path):
            yield path
    if path:
        path.pop()

The key approach is to use python yield statement, which makes this function a generator. Here is in depth guide to generators, but in a nutshell, when python runs function which "yield"s instead of returning, two things happen:

  • When function is called, then none of the function code actually executes, just a generator object is returned
  • Each time generator object is iterated, function code runs until it yields - then yielded value is returned and function execution paused until the next iterator iteration
  • The important thing to note is that all of the function context persists between subsequent iterations

The beauty of this technique is that traversed paths are returned to the caller as soon as they are found. Additionally, if caller wants to pause parsing of tree paths, tree traversal pauses as well. Caller can even delegate results processing to another function at some later stage by simply passing generator object over.

Complexity

Time: O(n) - same as with classic recursion.

Memory: O(log n) + O(log n). First O(log n) for recursion depth, second O(log n) path buffer.

Advantages

  • Low memory footprint
  • Results are available immediately
  • Tree is traversed "as you(caller) go". Traversal can be paused/aborted any time.
Disadvantages
  • Recursion. On very deep trees one may have to change Python's max execution depth

Tuesday, August 14, 2012

Tree traversal - the classic recursion

Just a small exercise to myself how to traverse trees in Python. In this post - classic example with recursion.

So we have a simple tree structure below with some data filled in.

class TreeNode(object):
    def __init__(self, name):
        self.children = list()
        self.name = name

root = TreeNode("Root")
root.children.extend( (TreeNode("Fruits"), TreeNode("Berries")) )
root.children[0].children.extend( (TreeNode("Apple"), TreeNode("Peach")) )
root.children[1].children.extend( (TreeNode("Cherry"), TreeNode("Mullberry")) )
The task: Find all paths of the tree from root to leafs.

Classic recursion solution

import copy
def traverse_recursive(node, path=list(), pathes=list()):
    p = copy.deepcopy(path)
    p.append(node.name)
    pathes.append(p)
    for n in node.children:
        pathes = traverse_recursive(n, p, pathes) 
    return pathes

Lets use it:

for path in traverse_recursive(root):
    print path
Which will print:
['Root']
['Root', 'Fruits']
['Root', 'Fruits', 'Apple']
['Root', 'Fruits', 'Peach']
['Root', 'Berries']
['Root', 'Berries', 'Cherry']
['Root', 'Berries', 'Mullberry']

Complexity

Time: O(n)
Memory: O(log n) + O(nlog n). O(log n) for recursion depth, plus O(nlog n) since all paths the function returns are pre-buffered during tree traversal.

Advantages

  • Classic algorithm. Any computer science student can write this
  • The code looks almost the same on any language
Disadvantages
  • Recursion. On very deep trees one may have to change Python's max execution depth.
  • All found paths are accumulated in memory before returned to the caller. Can really bloat memory on large trees.