Online resizing BTRFS
pod kategorijami: btrfs filesystems linux

Every now and then a sysadmin or a developer comes into a situation where he wishes he had not created one big partition or deletes a partition and wishes to grow one file system over the next partition. Besides growing file system, btrfs also supports shrinking in a seemingly simple command. Because the filesystem and partition meddling is always a scary operation, I was wondering if the resize operation actually moves data on btrfs.

This simple test uses blktrace and seekwatcher to trace and visualize how has the file system actually been accessing the underlying block device.

For the test, I'm using kernel 4.9.20 and btrfs-progs 4.7.3.

Preparing test file system

To test this I set up a 2GB disk image and used blktrace on it, to record block device access:

/btrfs-test# dd if=/dev/zero of=btrfs.img bs=1M count=2048
2048+0 records in
2048+0 records out
2147483648 bytes (2.1 GB, 2.0 GiB) copied, 4.6457 s, 462 MB/s

Since blktrace can only operate on a block device (and not a file), we need to setup the image as a loop device:

/btrfs-test# losetup -f btrfs.img
/btrfs-test# losetup -a
/dev/loop0: [2051]:538617527 (/btrfs-test/btrfs.img)

Let's create a btrfs file system on it:

/btrfs-test# mkfs.btrfs --mixed /dev/loop0
btrfs-progs v4.7.3
See for more information.

Performing full device TRIM (2.00GiB) ...
Label:              (null)
Node size:          4096
Sector size:        4096
Filesystem size:    2.00GiB
Block group profiles:
  Data+Metadata:    single            8.00MiB
  System:           single            4.00MiB
SSD detected:       no
Incompat features:  mixed-bg, extref, skinny-metadata
Number of devices:  1
   ID        SIZE  PATH
    1     2.00GiB  /dev/loop0

Test scenario

Assuming the block allocation strategy is to allocate the blocks at the start of the device first, I put up a script that forces the filesystem to write in the second part of the file system, then removing padding files and issuing a resize operation to shrink the file system into half its previous size. This should move the data in latter blocks to first half of device.

This script makes two copies of Ubuntu server image at 829MB each, thus using roughly about 1660MB of (assuming) mostly the first part of disk. These two files serve as padding in order to force the file system to use the second half of disk, where it will (still assuming) place the mini.iso file. After this, the two bigger files are deleted in order to make space on device so the resize operation can actually complete. The script:


cp -v ubuntu-16.04.2-server-amd64.iso testmnt/server-iso1.iso
cp -v ubuntu-16.04.2-server-amd64.iso testmnt/server-iso2.iso

sleep 3

cp -v mini.iso testmnt/mini.iso

sleep 6

rm testmnt/server-iso*
sleep 3

btrfs filesystem resize 1G testmnt/

In another shell, I'm running blktrace:

/btrfs-test# blktrace -d /dev/loop0 -o trace1
^C=== loop0 ===
  CPU  0:                19029 events,      892 KiB data
  CPU  1:                27727 events,     1300 KiB data
  CPU  2:                28491 events,     1336 KiB data
  CPU  3:                28879 events,     1354 KiB data
  Total:                104126 events (dropped 0),     4881 KiB data

The ^C shows I've interrupted it after the test script completed. Blktrace outputs per-cpu data about which blocks were accessed. Seekwatcher takes these files and visualizes them:

/btrfs-test$ seekwatcher -t trace1.blktrace
using tracefile ././trace1
saving graph to trace.png

Test results

The following graph shows how the at the start of script (first 5 seconds) most of the disk is filled, when the two copies of ubuntu are placed on the drive. Then at 16 seconds, the mini.iso is placed almost at the end of drive. At about 26 seconds the resize operation is done, where the filesystem does actually move the mini.iso to another place on device. Yay!

Full seekwatcher graph

Besides disk offset, seekwatcher also displays throughput, seek count and IOPs, all nicely aligned by time so you can quickly see what is happening with disks when you need to, as seen in the whole graph below.

Single device data redundancy with BTRFS
pod kategorijami: btrfs filesystems linux

I've been playing a bit with BTRFS lately. The file system has checksums of both metadata and data so it can offer some guarantees about data integrity and I decided to take a closer look at it hoping I could see if it can keep any of the data that we people try keep on our unstable hardware.

Preparing test data

For data I'll be using a snapshot of raspbian lite root. I mounted the image and packed the root into a tar to reproduce test easily and also compute sha1 sums of all the files to be able to verify them:

# losetup -f 2017-03-02-raspbian-jessie-lite.img
# losetup -a
/dev/loop0: [2051]:203934014 (/home/user/rpi-image-build/2017-03-02-raspbian-jessie-lite.img)
# kpartx -av /dev/loop0
add map loop0p1 (254:0): 0 129024 linear 7:0 8192
add map loop0p2 (254:1): 0 2584576 linear 7:0 137216
# mkdir rpi_root
# mount /dev/mapper/loop0p2 rpi_root
# (cd rpi_root && tar zcf ../root.tar.gz . && find . -type f -exec sha1sum {} \; > ../sha1sums)
# umount rpi_root
# kpartx -dv /dev/loop0
del devmap : loop0p2
del devmap : loop0p1
# losetup -d /dev/loop0

This leaves us with root.tar.gz and sha1sums files.

Test challenge

The challenge is to find and repair (if possible) file system corruption. I created a python script that finds a random non-empty 4K block on device and overwrites it with random data and repeats this 100 times. Here's the

import os
import random

f = 'rpi-btrfs-test.img'
fd = open(f, 'rb+')
filesize = os.path.getsize(f)

print('filesize=%d' % filesize)
random_data = str(bytearray([random.randint(0, 255) for i in range(4096)]))

count = 0
loopcount = 0
while count < 100:
    n = random.randint(0, filesize/4096)*4096)
    block =

    if any((i != '\x00' for i in block)):
        print('corrupting block %d' % n)*4096)

        assert fd.tell() == (n+1)*4096
        count += 1

    loopcount += 1
    if loopcount > 10000:

Baseline (ext4)

To imitate a SD card I'll use a 4GB raw disk image full of zeroes:

dd if=/dev/zero of=rpi-btrfs-test.img bs=1M count=4096

Create a ext4 fs:

# mkfs.ext4 -O metadata_csum,64bit rpi-btrfs-test.img
mke2fs 1.43.4 (31-Jan-2017)
Discarding device blocks: done
Creating filesystem with 1048576 4k blocks and 262144 inodes
Filesystem UUID: c8c7b1cc-aebc-44a3-bb6d-790fb3b70577
Superblock backups stored on blocks:
        32768, 98304, 163840, 229376, 294912, 819200, 884736

Allocating group tables: done
Writing inode tables: done
Creating journal (16384 blocks): done
Writing superblocks and filesystem accounting information: done

Now we create a mount point, mount the file system and put some data on it:

mkdir mnt
mount -o loop rpi-btrfs-test.img mnt
(cd mnt && tar zxf ../root.tar.gz)

Lets look at the file system:

# df -h
/dev/loop0      3.9G  757M  3.0G  21% /home/user/rpi-image-build/mnt

Let the corruption begin:

umount mnt

Lets check if the file system has errors:

 # fsck.ext4 -y -v -f rpi-btrfs-test.img
 e2fsck 1.43.4 (31-Jan-2017)
 Pass 1: Checking inodes, blocks, and sizes
 Pass 2: Checking directory structure
 Directory inode 673, block #0, offset 0: directory has no checksum.
 Fix? yes

 ... lots of prinouts of error and repair info

 Pass 5: Checking group summary information

 rpi-btrfs-test.img: ***** FILE SYSTEM WAS MODIFIED *****

        35610 inodes used (13.58%, out of 262144)
           65 non-contiguous files (0.2%)
            7 non-contiguous directories (0.0%)
              # of inodes with ind/dind/tind blocks: 0/0/0
              Extent depth histogram: 30289/1
       226530 blocks used (21.60%, out of 1048576)
            0 bad blocks
            1 large file

        27104 regular files
         3038 directories
           54 character device files
           25 block device files
            0 fifos
          346 links
         5380 symbolic links (5233 fast symbolic links)
            0 sockets
        35946 files

OK, this filesystem was definitely borked! We should mount it:

mount -o loop rpi-btrfs-test.img mnt

What does sha1sum think:

# (cd mnt && sha1sum -c ../sha1sums | grep -v 'OK' )

... lots of files with FAILED

./usr/lib/arm-linux-gnueabihf/ FAILED
sha1sum: WARNING: 1 listed file could not be read
sha1sum: WARNING: 90 computed checksums did NOT match

Whoops, sha1sum as a userspace program was actually allowed to read invalid data. Uncool.

Btrfs Single test

Lets create a btrfs file system on it:

# mkfs.btrfs --mixed rpi-btrfs-test.img
btrfs-progs v4.7.3
See for more information.

Label:              (null)
Node size:          4096
Sector size:        4096
Filesystem size:    4.00GiB
Block group profiles:
  Data+Metadata:    single            8.00MiB
  System:           single            4.00MiB
SSD detected:       no
Incompat features:  mixed-bg, extref, skinny-metadata
Number of devices:  1
   ID        SIZE  PATH
    1     4.00GiB  rpi-btrfs-test.img

The --mixed switch is needed because the file system is smaller than 16GB and BTRFS is known to have some problems with small devices if it tries to have separate block groups (chunks) for data and metadata, which by default it does. This flag sets up the filesystem so it intermingles data and metadata on same chunks. Supposedly this helps avoid the notorious out of space errors.

Now we mount the file system and put some data on it:

mount -o loop rpi-btrfs-test.img mnt
(cd mnt && tar zxf ../root.tar.gz)

Lets look at the file system:

# df -h
/dev/loop0      4.0G  737M  3.3G  18% /home/user/rpi-image-build/mnt

Let the corruption begin:

umount mnt

Lets check the file system:

# mount -o loop rpi-btrfs-test.img mnt
# btrfs scrub start mnt/
scrub started on mnt/, fsid a6301050-0d88-4d86-948d-03380b9434d4 (pid=27478)
# btrfs scrub status mnt/
scrub status for a6301050-0d88-4d86-948d-03380b9434d4
    scrub started at Sun Apr 30 10:17:12 2017 and was aborted after 00:00:00
    total bytes scrubbed: 272.49MiB with 37 errors
    error details: csum=37
    corrected errors: 0, uncorrectable errors: 37, unverified errors: 0

Whoops, there goes data: 37 uncorrectable errors.

What does sha1sum say:

# (cd mnt && sha1sum -c ../sha1sums | grep -v 'OK' )
sha1sum: ./usr/share/perl5/Algorithm/ Input/output error
./usr/share/perl5/Algorithm/ FAILED open or read

... lots more of terminal output similar to above

sha1sum: WARNING: 99 listed files could not be read

Data was lost, but at least the OS decided it will not allow garbage to propagate.

Btrfs Dup test

BTRFS has a way to tell it to make redundant copies of data by using DUP profile. DUP makes a duplicate copy on same device in case the first copy goes bad.

Defining the profile is most easily done at the time of creating the file system:

# mkfs.btrfs --data dup --metadata dup --mixed rpi-btrfs-test.img
btrfs-progs v4.7.3
See for more information.

Label:              (null)
Node size:          4096
Sector size:        4096
Filesystem size:    4.00GiB
Block group profiles:
  Data+Metadata:    DUP             204.75MiB
  System:           DUP               8.00MiB
SSD detected:       no
Incompat features:  mixed-bg, extref, skinny-metadata
Number of devices:  1
   ID        SIZE  PATH
    1     4.00GiB  rpi-btrfs-test.img

The DUP denotes that file system will store two copies of data on same device.

Again we put some data on it:

mount -o loop rpi-btrfs-test.img mnt
(cd mnt && tar zxf ../root.tar.gz)

Lets look at the file system:

# df -h | grep mnt
/dev/loop0      2.0G  737M  1.3G  36% /home/user/rpi-image-build/mnt

The file system appears only 2GB of size, because there are two copies to be stored on underlying device.

Again we corrupt the file system:

umount mnt

Lets check the file system:

# mount -o loop rpi-btrfs-test.img mnt
# btrfs scrub start mnt/
scrub started on mnt/, fsid 12ffd7a2-b9c4-46ca-b16a-cd07d94d6854 (pid=27863)
# btrfs scrub status mnt/
scrub status for 12ffd7a2-b9c4-46ca-b16a-cd07d94d6854
    scrub started at Sun Apr 30 10:27:31 2017 and finished after 00:00:00
    total bytes scrubbed: 1.41GiB with 99 errors
    error details: csum=99
    corrected errors: 99, uncorrectable errors: 0, unverified errors: 0

Hey, corrected errors, looks like this could work ... checking the sha1sums:

# (cd mnt && sha1sum -c ../sha1sums | grep -v 'OK' )

Looks fine. Need to check how this works on real hardware.

KVM tricks
pod kategorijami: qemu kvm linux

Did you know KVM has a way to enable discard pass thru? I did, but then I forgot and had to google again.

This is how you do it:

kvm -drive discard=unmap,file=debian.qcow2,id=ff,if=none \
    -device virtio-scsi-pci -device scsi-disk,drive=ff

When booted, you have to make sure your fs is mounted with discard option, and can then do:

fstrim /

And the image on the host should be significantly smaller. Use du or ls -alsh, not just ls, because ls does not display actual disk usage if you don't pass -s:

1,4G -rw-r--r--  1 root root 4,0G apr  7 17:22 debian.img

Now you know.

Did you know you can start kvm with vnc disabled and then attach it in monitor? And change CD or save vm snapshot?

Simple moving objects database with Postgres
pod kategorijami: moving-objects-database temporal postgres tutorial

"Moving objects" or "spatio-temporal database" is a database, which stores data with temporal and spatial aspects. One example is keeping a database of how real estate changes through time, another a bit more interactive is, say, tracking location and movement of vehicles through time and keeping the history in database.

What we want to be able to answer is such questions as:

  • where have the tracked objects been over time,
  • check whether an tracked object has passed through a checkpoint,
  • check if two tracked objects have crossed paths,
  • if two tracked objects have crossed paths, where and at what time has this happened?

To achieve this, we will combine two PostgreSQL's features: builtin range data types and operators, and spatial data types and operators provided by PostGIS extension.

For the example here, we will use GPX track exports of some of my runs. First we need to import GPX data into a table we create:

    id integer,
    filename text,
    lat numeric,
    lon numeric,
    ts timestamptz);

I created a small Python script, which reads GPX XMLs in current dir and outputs CSV with coordinates out stdout. This is then directly usable in psql's \COPY command:


COPY 17549
Time: 617,839 ms

Modeling spatial aspects

Postgres supports spatial data types via PostGIS extension. I will not go into full detail about PostGIS here, for now it suffices to know it works by adding a geometry column to our table and that it allows us to index this column, which enables fast lookups. In my example we will model the distance the object covered with line geometry. Besides linestrings (lines), there are also points and polygons.

Modeling temporal aspects

Postgres supports ranged types, and among them are also time ranges. daterange is a range between two dates and tstzrange is a range between two timestamptz values. Ranges in Postgres are canonically represented in included-excluded notation, meaning the start of the range is included and the end of the range is excluded but marks the boundary and all values less than that are included. Example:

 SELECT '[2016-01-01, 2016-06-30]'::daterange;
 (1 row)

With this, we created a date range for the first half of this year, that is between first of January inclusive and last of June inclusive. We can see Postgres normalizes this into 1st January inclusive and 1st July exclusive.

A table for tracking objects

For tracking objects, lets create a new table. Table needs to have a few fields: a serial for identifying each segment, an object identifier to know which object the time and location belongs to, and, of course, time period and corresponding location of the object:

    id serial,
    object_id integer,
    timeslice tstzrange);

You will notice the location is missing! The geometry columns are added via a special function AddGeometryColumn. We need to provide a number of parameters. Table name and column name are obvious. Next we need to provide spatial reference ID, which uniquely identifies a number of parameters required for correctly interpreting spatial data - here we use ID 4326, which denotes the WGS84 world geodetic system. Geometry type we'll be using is LINESTRING and the last parameter is number of dimensions, which is two:

SELECT AddGeometryColumn('tracks', 'geom', 4326, 'LINESTRING', 2);

Now we want to convert GPX data into tracks. Tracks will have temporal intervals in field timeslice and lines in field geom.

With following query we can convert numerical values in table gpx to real point data type. We use ST_MakePoint to create a point and ST_SetSRID, to set spatial reference system on geometry so PostGIS knows how to interpret it:

--- example
SELECT id, ts, ST_SetSRID(ST_MakePoint(lon, lat), 4326) pt FROM gpx;

Having points, we can use "lead" window function to pair current timestamp and point with timestamp and point in the next row:

--- example
    lead(ts) OVER (PARTITION BY id ORDER BY ts ASC) next_ts,
    lead(pt) OVER (PARTITION BY id ORDER BY ts ASC) next_pt
FROM points;

Having such two timestamps and points in the same row, all we have to do now is join them into ranged types. Here we must be careful to exclude the last row, since the next_pt and next_ts are both NULL and will not generate correct geometry and time range:

--- example
    id AS object_id,
    ST_MakeLine(pt, next_pt) geom,
    tstzrange(ts, next_ts) timeslice
FROM twopoints

Now we can create a pipeline and join above three queries into one using WITH statement and insert resulting data into tracks table:

    points AS (
        SELECT id, ts, ST_SetSRID(ST_MakePoint(lon, lat), 4326) pt FROM gpx),
    twopoints AS (
            lead(ts) OVER (PARTITION BY id ORDER BY ts ASC) next_ts,
            lead(pt) OVER (PARTITION BY id ORDER BY ts ASC) next_pt
        FROM points),
    segments_and_timeslices AS (
            id AS object_id,
            ST_MakeLine(pt, next_pt) geom,
            tstzrange(ts, next_ts) timeslice
        FROM twopoints
        WHERE next_pt IS NOT NULL ORDER BY id, ts ASC)
INSERT INTO tracks (object_id, timeslice, geom)
SELECT object_id, timeslice, geom FROM segments_and_timeslices;

INSERT 0 17543
Time: 413,548 ms

There. In table tracks, we now have all we need to get meaningful results to the questions above. To make it speedy, we need to add a few more indexes:

modb=# CREATE INDEX tracks_timeslice_idx ON tracks USING GIST (timeslice);
Time: 250,054 ms
modb=# CREATE INDEX tracks_geom_idx ON tracks USING GIST (geom);
Time: 96,496 ms

Answering the questions

Now we can check where an object has been on 7th May this year between 13h and 14h. We do this by using && overlap operator with tstzrange:

FROM tracks A
    A.timeslice && '[2016-05-07 13:00:00+02,2016-05-07 14:00:00+02)'::tstzrange
    AND A.object_id = 0;

   id   | object_id |                                            geom
 117576 |         0 | 0102000020E610000002000000D0B4C4CA681C2D40B2D6506A2F044740AE4676A5651C2D40E84B6F7F2E044740
 117577 |         0 | 0102000020E610000002000000AE4676A5651C2D40E84B6F7F2E0447408CD82780621C2D408F34B8AD2D044740

Check if any two objects have crossed paths. In geometry, there's also && overlap operator, but it checks if the bounding boxes of compared geometries overlap, not the actual geometries. This is why we have to use another function here, ST_Intersects, which is exact:

SELECT A.object_id, B.object_id,,
FROM tracks A, tracks B
    ST_Intersects(A.geom, B.geom)
    AND A.timeslice && B.timeslice
    AND !=
    AND A.object_id < B.object_id;

 object_id | object_id | id | id
(0 rows)

Time: 1032,741 ms

Obviously, since all the tracks are from me, I can't cross paths with myself. But we can use postgres to time travel one of my runs forward in time exactly the right amount to make it cross another:

UPDATE tracks
    timeslice = tstzrange(
        lower(timeslice) + interval '302 days 20:33:37',
        upper(timeslice) + interval '302 days 20:33:37',
WHERE object_id = 5;

Time: 164,788 ms

And now, if we repeat above query:

SELECT A.object_id, B.object_id,,
FROM tracks A, tracks B
    ST_Intersects(A.geom, B.geom)
    AND A.timeslice && B.timeslice
    AND !=
    AND A.object_id < B.object_id;

 object_id | object_id |   id   |   id
         4 |         5 | 129396 | 133243
(1 row)

Time: 1099,215 ms

In this query it is enough to go through half of returned rows, since we are comparing all the tracks with all of the other and including only one permutation is enough. That's why we limit the query with A.object_id < B.object_id.

Checking if an object has passed a checkpoint then means specifying a line denoting checkpoint and looking up intersections with it in tracks table - an exercise left for the reader.

Modeling moving objects with ranges and lines is just one way. Your database representation might vary a lot depending on questions the users will be asking about the data.

Hopefully this tutorial has made a case how ranged data types in postgres can make otherwise very intensive task - finding intersections in both spatial and temporal dimensions - relatively simple.

BBC micro:bit - še en izobraževalni mini računalnik
pod kategorijami: slovenija it racunalnistvo izobrazevanje

Prejšnji teden sem bil v Bilbau, na konferenci EuroPython 2016. Na konferenci smo obiskovalci brezplačno dobili mini računalnik BBC micro:bit.

BBC micro:bit je poleg Raspberry Pi še eden izmed mini računalnikov, posebej namenjenih izobraževanju mladih, da se pobliže spoznajo s samim delovanjem računalnikov, ne samo s površnega klikanja z miško in dotikanja s prstom po uporabniških vmesnikih. Spoznajo do te mere, da se naučijo osnov kako računalniki razumejo zelo osnovna navodila, ki jim jih posredujejo ljudje, ter se naučijo računalnike uporabljati kot kreativno orodje, ne zgolj kot (pasivno) sredstvo za konzumacijo (multi-) medijskih vsebin.

Micro:bit je posebej namenjen izobraževanju: na ploščici je poleg procesorja še 25 rdečih LED lučk in dva gumba, s tem pa se da že marsikaj zanimivega naredit. Poleg lučk in gumbov sta še dva senzorja, pospeškomer (akcelerometer) ter magnetometer (kompas), s katerima se da zaznavati orientacijo ploščice ter orientacijo oz. tudi bližino kovine. Ploščica se lahko povezuje z drugimi ploščicami bodisi preko žic, bodisi preko brezžične povezave z uporabo Bluetooth Low Energy.

Zakaj se imenuje BBC micro:bit? Ker je nastala v sodelovanju z BBC v okviru programa digitalne pismenosti, cilj britancev pa je napravo zastonj podarit milijonu otoških osnovnošolcev z željo, da bi se čim več mladih prijelo tudi nekaj računalniškega znanja.

Delo s ploščico je sila enostavno, za delo je dovolj osebni računalnik, ploščica in povezovalni kabel. Za pričetek programiranja je dovolj kar uporaba spletnega urejevalnika, ki je dostopen na, čeprav je res, da je (vsaj za Python) tam nekoliko zastarela koda. Spletni urejevalnik omogoča, da kar v brskalniku sprogramiramo željeno funkcionalnost, z gumbom "Download" pa potem prenesemo program, ki ga shranimo na microbit, ki se računalniku predstavi kot USB ključek. Microbit bo to zaznal, naložil program in ga začel izvajat in napravica bo zaživela.

Poleg uradne strani sta na voljo še dva urejevalnika, pri prvem - Code the microbit - se program sestavlja z grafičnimi bloki, ki precej poenostavijo sestavljanje programa. Ponuja tudi "predvajanje" programa, da je takoj vidno delovanje. Programiranje deluje enako, program prenesemo prek spleta in ga odložimo na microbit, ki se osebnemu računalniku predstavi kot USB ključek.

Mu je namenski urejevalnik za MicroPython kodo, ki ga prenesemo in poženemo na osebnem računalniku. Ta omogoča naprednejše programiranje v Pythonu in neposredno zazna microbit, tako da ni potrebno ročno kopirati datotek.

Oba urejevalnika omogočata sestavljanje kompleksnih opravil, ki so zamejena predvsem z domišljijo, tem pa (vsaj otrokom) ne zmanjka. S tako cenovno dostopno napravico - stane približno 15 eur - verjamem, da se da delat zabavne delavnice.

PostgreSQL tutorial: Efficient color similarity search
pod kategorijami: colors postgres

I've previously blogged about colors and PostgreSQL here. In this post I will cover some insight into custom GiST index, which enables efficiently looking up similar colors.

Color distance measures

There are several revisions of Delta E color distance measure, each more accurate and more complicated. The first revision is called CIE 1976. After further research in (human) color perception it became clear the CIE 1976 has deficiencies and revised versions CIE 1994 and later CIE 2000 were released.

Numerically, CIE 1976 is just euclidean, straight line distance between points in L*a*b color space, as this color space was defined such to have this property. The CIE 2000 Delta E is far more complex and non uniform and lacks this property, so we can't use CIE 2000 with vanilla PostgreSQL 9.6.

So let's see how you can implement CIE 1976 color similarity search with PostgreSQL 9.6.

PostgreSQL cube extension

Cube contrib extension is a custom PostgreSQL data type, with which you can represent N-dimensional vectors. It also supports indexes, so you can efficiently look up values based on column of this data type.

Let's load the extension:

colorsdb=# create extension cube;

Okay, quick overview how cube works! We can create a sample point and check it is a point:

 colorsdb=# select '(1,2,3)'::cube;
  (1, 2, 3)
 (1 row)

 colorsdb=# select cube_is_point('(1,2,3)'::cube);
 (1 row)

Or we can create a 3x3x3 cube and check its size:

 colorsdb=# select '(1,2,3),(4,5,6)'::cube;
  (1, 2, 3),(4, 5, 6)
 (1 row)

 colorsdb=# select cube_is_point('(1,2,3),(4,5,6)'::cube);
 (1 row)

 colorsdb=# select cube_size('(1,2,3),(4,5,6)'::cube);
 (1 row)

Cube data type is perfectly suited for color space representation. You can store the colors as 3-dimensional points in space, where point is a special case of cube - it has zero volume and has both upper right and lower left points equal.

You can get euclidean distance with cube_distance:

 colorsdb=# select cube_distance('(1,2,3)'::cube, '(1,2,6)'::cube);
 (1 row)

In upcoming PostgreSQL 9.6 version, this extension will also support distance operators. Here, <-> is an euclidean distance operator:

 colorsdb=# select '(1,2,3)'::cube <-> '(1,2,6)'::cube;
 (1 row)

Let's create an test table with 500.000 records:

create table colors (color cube);

with random_colors as (
        random() * 100 as l,
        random() * 255 - 128 as a,
        random() * 255 - 128 as b
    from generate_series(1, 500000) x)
insert into colors select cube(array[l,a,b]) from random_colors;

And we can now select 5 closest colors to (1,2,3):

colorsdb=# select '(1,2,3)'::cube <-> color, color from colors order by 1 asc limit 5;
     ?column?     |                            color
 1.61559798496189 | (1.89253129065037, 1.71048436127603, 1.68480973271653)
 2.55645225973282 | (3.37235750630498, 1.64988295687363, 3.88588152406737)
 2.55950246687413 | (2.91422470472753, 1.19065871741623, 4.493908747565)
 2.85963596867927 | (1.00834178738296, 4.51141274580732, 4.3675724142231)
 3.11127226552722 | (1.72140300273895, 3.04948928579688, 0.161309270653874)
(5 rows)

What is the cost for this:

 colorsdb=# explain analyze select '(1,2,3)'::cube <-> color, color from colors order by 1 asc limit 10;
                                                         QUERY PLAN
  Limit  (cost=20734.28..20734.30 rows=10 width=40) (actual time=151.844..151.846 rows=10 loops=1)
    ->  Sort  (cost=20734.28..21984.46 rows=500072 width=40) (actual time=151.843..151.845 rows=10 loops=1)
          Sort Key: (('(1, 2, 3)'::cube <-> color))
          Sort Method: top-N heapsort  Memory: 25kB
          ->  Seq Scan on colors  (cost=0.00..9927.90 rows=500072 width=40) (actual time=0.014..88.199 rows=500000 loops=1)
  Planning time: 0.054 ms
  Execution time: 151.864 ms
 (7 rows)

You can see PostgreSQL is doing a sequential scan and it takes 151 ms to get 5 nearest colors. Without index, that is. Since 9.1, PostgreSQL supports returning nearest items with use of GiST index. Let's try indexing colors (building index takes a while):

colorsdb=# create index colors_color_idx on colors using gist (color);

And check the query now:

 colorsdb=# explain analyze select '(1,2,3)'::cube <-> color, color from colors order by 1 asc limit 10;
                                                                 QUERY PLAN
  Limit  (cost=0.29..1.20 rows=10 width=40) (actual time=0.236..0.565 rows=10 loops=1)
    ->  Index Scan using colors_color_idx on colors  (cost=0.29..45996.29 rows=500000 width=40) (actual time=0.235..0.562 rows=10 loops=1)
          Order By: (color <-> '(1, 2, 3)'::cube)
  Planning time: 0.051 ms
  Execution time: 0.585 ms
 (5 rows)

Yay, 0.6 ms, which is about 250-times faster for a table with 0,5 million records.

Benchmarking Python in PostgreSQL
pod kategorijami: postgres python colors

I've been learning a lot about PostgreSQL recently. A trigger for this was a Stack overflow question I came about some time ago, featuring a fairly complex equation for calculating color similarity. I've been obsessing over it ever since and I've used it as a test case for a number of things. Hopefully, this will be one of several articles about how I used it and what I learned along.

This article is a benchmark of different implementations of same function in PostgreSQL. The function in question is difference between colors, and the implementations are in SQL, C, and several variants of Python: pure, numpy, numba and Cython.

Delta E color difference is a measure of color difference. The L*a*b color space was designed with intention to represent colors in a perceptually uniform way, meaning some change in value should result in equal or very similar change in perception. Since the color space was designed with this intention, the original CIE 1976 Delta E was just cartesian distance between two point in color space. Along with more research it became clear the CIE 1976 had some deficiencies and was followed by improved version CIE 1994 Delta E. The latest revision is CIE 2000 Delta E and is far from being a simple equation. For the reader to understand the rest of the post, it is enough to know this equations is math intensive, accepts two 3-dimensional vectors, and returns a single scalar value.

So, with the CIE 2000 Delta E standard no longer being a simple calculation, implementing it in SQL became cumbersome. Jaza, author of the SO question, managed to implement it in SQL (kudos!), but even with CTEs the code is still incomprehensible. And the code is slow, too. SQL just wasn't made for this.

In an effort to speed this up, I tested several approaches. I tested Jaza's SQL implementation, plpgsql implementation and my custom PostgreSQL C extension (more about this in another post). PostgreSQL officially supports Python as a server side procedural language, so this is also something to evaluate. Python is diverse and offers several options for implementation, depending on your needs for performance: pure Python, numpy, numba, cython.

For testing I used several configurations: pure SQL function (as written by Jaza), plpgsql function, my PostgreSQL C extension, pure Python function, Python function using NumPy, then I used Python module as a container for functions, and additionally tried to see if I can make numba JIT work on the server side.

The results are interesting, but first the setup.


SQL, plpgsql and C implementations are just functions and there's not much wiggle room.

There are several Python implementations:

  • inline pure
  • inline pure jitted
  • inline numpy
  • inline numpy jitted
  • module pure
  • module pure jitted
  • module numpy
  • module numpy jitted
  • cython module

"Inline" or "module" defines if the function body is defined inline in CREATE FUNCTION statement or in a separate Python module, which is imported at execution.

"Numpy" or "pure" signifies the functions uses colormath code (which in turn uses numpy) or a pure Python implementation.

"Jitted" signifies the use of numba jitting capabilities.


I created the test database:

dropdb colors
createdb colors
psql colors -c 'create table color (rgb_r double precision, rgb_g double precision, rgb_b double precision, lab_l double precision, lab_a double precision, lab_b double precision);'

I then generated random test dataset and used the colormath module to convert the RGB colors to Lab colorspace in order for the values to represent a valid RGB value.


For benchmark I created a table with 20.000 random RGB colors, converted them to Lab color space and stored in database. Test case consists of running the distance function on whole table, comparing with a fixed value, in my case it was L=42.041, a=-9.105, b=-13.873. Each implementation was called 10 times on an idle laptop.

Reusing connections

First run was with connection reuse:

Implementation Minimum Average Maximum Speedup
SQL 11.3849 11.8725 12.5735 1.0
plpgsql 0.8482 0.8786 0.9386 13.5
C extension 0.0550 0.0593 0.0715 200.3
Py inline pure 0.5735 0.6166 0.6651 19.3
Py inline pure JIT 0.8567 1.2102 3.8561 9.8
Py inline pure JIT cached 0.8730 0.9800 1.2758 12.1
Py inline numpy 6.2782 6.5544 6.8891 1.8
Py module pure 0.6055 0.6445 0.6936 18.4
Py module pure JIT 0.2837 0.4468 1.7373 26.6
Py module pure JIT cached 0.2878 0.4241 1.4920 28.0
Py module pure cython 0.4944 0.5123 0.5600 23.2
Py module numpy 6.0890 6.4830 7.7312 1.8
Py module numpy JIT 6.0668 6.5032 7.5097 1.8
Py module numpy JIT cached 6.0912 6.5865 7.3711 1.8

SQL is slowest with 11 seconds for 20k rows. C extension is fastest, with 55 to 72 miliseconds and offers a speedup of 200x.

In between there's Python. All numpy implementations are a bit less than 2x faster than SQL. Using numpy in plpython is slow, since the data needs to be copied to numpy array before it is processed. This is a costly operation and it shows. Inline numpy with numba JIT took far longer that SQL against which I am comparing so I didn't test it at all.

Pure Python implementations do better and are about 19x faster than SQL. By defining function inline instead of in module it was 4% faster, but that can make logic harder to maintain. However, when using numba JIT, defining function inline slows down execution to 12x faster, and defining function in module speeds it up to 28x faster. Apparently defining function inline makes JIT less effective. All numba decorated functions also have an initialization penalty, where the first run is significantly slower, most obvious with pure jit module.

Caching with numba does not seem to help. It does have one extra requirement, since the server process needs write permissions on directory next to python module in order to write cached data to disk.

I also tested a Cython implementation, at 23x it was faster than pure Python, but slower than numba.

New connections

Second run was with new connection for every execution:

Implementation Minimum Average Maximum Speedup
SQL 11.5494 12.0963 12.7010 1.0
plpgsql 0.9093 1.0696 1.2528 11.3
C extension 0.0977 0.1129 0.1325 107.2
Py inline pure 0.6567 0.7199 0.8560 16.8
Py inline pure JIT 1.2135 1.3678 1.6060 8.8
Py inline pure JIT cached 1.1845 1.2449 1.3095 9.7
Py inline numpy 6.0845 6.4325 6.7866 1.9
Py module pure 0.6414 0.6754 0.7062 17.9
Py module pure JIT 1.4029 1.4491 1.5507 8.3
Py module pure JIT cached 1.4275 1.5280 1.6158 7.9
Py module pure cython 0.5374 0.5874 0.6513 20.6
Py module numpy 7.1427 7.3657 7.5970 1.6
Py module numpy JIT 7.2352 7.4535 7.7606 1.6
Py module numpy JIT cached 7.3986 7.5940 7.9226 1.6

When including connection overhead there are significant reductions in performance. It is important to understand how PostgreSQL implements plpython and server processes in general. After connecting, PostgreSQL forks a process for client. If you run any plpython functions, this process then loads Python interpreter, also adding some overhead.

SQL implementation stays almost the same, numpy is slightly slower with 1.6-1.9x speedup.

All implementations with numba are significantly slower. Where numba was previously 28x faster, it is now always hitting initialization on first request, and the speedup drops to 7.9x. Best numba enabled implementation is 9.7x faster, down from 12.1x. Both are slower than pure Python.

A couple of implementations stand out here: pure Python, both inline and as module, and also Cython, have approximately the same speedup as before, meaning they are a stable implementation and do not incur significant initialization overhead.

Lessons learned

Compared by performance we get three clusters of implementations:

  • SQL and numpy are in the same order of magnitude (slow),
  • plpgsql and pure Python implementations are an order of magnitude faster and
  • C function is two orders of magnitude faster.

In plpython, you don't want to use numpy, which is slow because each row is processed individually. You might want to use numba if you're reusing connections, but care should be taken, since it can have unpredictable performance. Cython is okay, though it probably won't help much over pure Python. Functions, written in C, are fast.

Zablode postsocializma?
pod kategorijami: slovenija slovencologija

Zablode postsocializma je še razmeroma sveža (lanskoletna) knjiga Vesne Vuk Godina, ki želi govoriti o tem kje je Slovenija (in tudi druge postsocialistične države) zašla na poti v klub razvitih družb zahodnega tipa. Vesna Vuk Godina je antropologinja, predava na mariborski Filozofski fakulteti in ljubljanski Fakulteti za družbene vede in ne dvomim o njeni strokovnosti ali usposobljenosti. Tematika, ki jo knjiga obravnava, je zanimiva, žal pa sem bil nad izvedbo nekoliko razočaran in se mi zdi, da je knjiga šla morda malo prehitro v tisk.

Knjiga obsega približno 330 strani, ki so razdeljena v 4 poglavja, dolga po odokativno 50, 120, 150 in 5 strani. Kateri bedak šteje strani poglavij, se vprašate? Število poglavij res nima nekega vpliva na vsebino, pa vendar velja, da človek z napačnim orodjem zelo težko doseže določene cilje - tako se z vilico zelo težko poje juho.

Obsežna poglavja so kot velik petkilski kos govejega mesa, ki ga je kuhar v enem kosu dal v pečico: hrana bo navzven izgledala pripravljena, medtem ko bo v sredini še surova. Podobno je s to knjigo: poglavja so predolga, napisana v zelo enakomernem ritmu, zelo številni citati pa ta ritem še poudarijo do te mere, da poglavja spominjajo na daljšo seminarsko nalogo, kjer želi študent profesorja preobremeniti z obsegom pisanja, da se ubogi revež ne bi pretirano ukvarjal z vsebino. Zaradi dolžine poglavij je zato težko slediti rdeči niti, citati pa avtoričino misel še dodatno razbijajo in redčijo, namesto, da bi služili kot argumenti za zaključno misel posameznega (krajšega) poglavja.

Ob branju tega sem se spraševal katero ciljno publiko je možno nagovoriti s tako obliko, zaradi katere je knjiga težje prebavljiva, kot bi morala biti. Zaradi notranje nerazdelanosti daje občutek, da ni namenjena širši publiki in ne kot gradivo za študente, obojim bi namreč bila bolj razdelana struktura v veliko pomoč.

No, ne gre pa razumeti, da je vse katastrofalno. Sam smatram kulturo, podobno kot tudi avtorica, kot eno izmed ključnih pogojev oz. okoliščin, pomembnih za delovanje skupnosti. Vsebina zato nudi v razmislek precej zanimivih idej, ki niso radikalno nove, so pa nanizane v zametek nečesa smiselnega.

Osebno mi je kot arhetip slovenskega gospodarskega organiziranja všeč ideja domačije, ki pa ni mišljena slabšalno (ne v smislu "po domače"), ampak kot jasno začrtano skupnost, ki ne obsega zgolj družine, ampak tudi druge ne-sorodstveno povezane posameznike, ki prebivajo na domačiji. Avtorica tudi dobro predstavi motivacijo in vrednote, ki so v tovrstni skupnosti pomembne za tisto, kar najbolj šteje - preživetje.

Verjamem, da se bo knjiga v Sloveniji zelo dobro prodajala, na tujino pa lahko pozabimo, to ni Gladwell. Vsebina in ideja je pomembna, a knjiga je, morda nekoliko ironično, dober primer slovenskega domačijskega načina razmišljanja, ki ne vidi dlje od domačije, torej od avtorja in založbe oz. spremljevalnih akterjev. Ne vidi in ne upošteva bralca, zato knjiga ni material za mednarodni bestseller in bi, preden lahko začne razmišljati, da bi to postala, morala biti v pretežnem delu še nekajkrat prestrukturirana in prepisana.

Nekatere druge recenzije:

Knjiga, ki bi jo moral prebrati vsak Slovenec (Boštjan M. Zupančič)

Zablode Vesne Vuk Godina (Peter Rak)

Iz kje izvira konflikt med mladimi in starimi
pod kategorijami: slovenija mladi

"Kako smo prišli do debate o tem, da ljudje po celem življenju garanja niso več upravičeni do dostojanstvene starosti ali pa mladi do socialne varnosti?"

Tako se Miha Blažič - N'toko sprašuje v Mladini s 14. novembra, kjer se je razpisal o konfliktu med mladimi in starejšimi v slovenski družbi. Starejše poimenuje za "zaščitene medvede", saj so zaradi redne zaposlitve nedotakljivi. Ugotavlja, da imamo mladi frustracije in odpor do starejših, da imamo "tisoč in en razlog", da jih sovražimo. Do tega po Blažičevem mnenju prihaja, ker država spodbuja konkurenčnost in ne varnosti. Na koncu pride do zaključka, da je smiselna rešitev krajšanje delovnega časa.

Menim, da se Miha Blažič moti.

Stara mama je upokojena skoraj tako dolgo, kot sem sam na svetu. Privoščim ji, morda sem ob tem tudi nekoliko zavisten, saj se zavedam, da česa takega ne bom doživel. A ko v pogovoru navrže, da je nam mladim lahko, saj imamo še celo življenje pred seboj, me prežame jeza. Od kje upokojencu, ki že več desetletij uživa pokojnino, predrznost, da mi zavida še mojo mladost? Upokojenih, ki so se po vseh standardih upokojili mladi, stari tam okoli pedeset let, v Sloveniji ni malo in takega človeka ne morem šteti kot izgaranega. Nek drug tak prejemnik pokojnine kot hobi vodi dejavnost, pri kateri nekega drugega mladega človeka mimo vseh davčnih postopkov plačuje z gotovino, v popoldanskem času pa prenavlja drugo stanovanje, ki ga namerava oddajati. Ne dvomim, da se bojo vselili mladi.

Z družbenim statusom ni nič narobe, kadar so uživalci do njega utemeljeno upravičeni, takrat ima status legitimnost. Večina teh primerov pa legitimnosti nima. Dopuščanje zgodnjega upokojevanja je bila neodgovorna poteza pri vodenju državne politike, saj dela zmožen človek ne bi smel posedati v brezdelju. Dobrodošlo je, da upokojenec pri močeh vodi dejavnost, a naj vendar ne bo tako brez časti, da z izogibanjem plačevanja davka mladega ropa njegovih pravic - zavarovanja in delovne dobe. Tako dejanje je za mlade žalitev. Neprimerno je tudi, da upokojena oseba pozabi, da uživa nekaj tako neverjetnega, kot je več deset let prejemanja državne pokojnine. Moja generacija tega ne bo izkusila.

Hud vir konfliktov je tudi lastništvo nepremičnin. Starejši so si lahko po zaslugi Jazbinškovega zakona od države pridobili stanovanja z ugodnim odkupom, bistveno pod tržno ceno, mnogi tudi več njih. Ti sedaj uživajo pravice zaposlenih in upokojenih. Na drugem polu si mora mlad človek v Sloveniji iz meseca v mesec iskati delo - do zaposlitve ponavadi ne pride -, da lahko plačuje previsoko najemnino najemodajalcu, ki je stanovanje pridobil z oškodovanjem državnega premoženja, torej spet nelegitimno. V službi starejšega človeka tipično srečuje kot redno zaposlenega in nadrejenega, za katerega opravi svoje in često še dobršen del njegovega dela, saj redno zaposleni v svojem udobju ne sledi več razvoju. Takega nadrejenega mlad človek zopet ne more vzeti za vzor, ampak ga utemeljeno prezira.

Študentsko delo je ena najbolj neodgovornih stvari, ki se je pripetila slovenski družbi na sploh. Uvedeno je bilo leta 1994, s časom pa se je izrodilo v sistematično zlorabo mladih. Mladim je odvzelo možnost redne zaposlitve znotraj organizacij, stabilno gradnjo kariere ter delovno dobo. Delodajalcem je nudilo polkvalificirano delovno silo za ceno bureka in za obljube delovnih izkušenj, kar pa ni prišlo brez stranskih učinkov. Študentski delavci so se naučili biti potrošna roba in popolnoma vseeno je bilo, ko se niso zglasili na delu. Pač niso dobili plačano, na delo pa je stopil naslednji. S takim odnosom se eni študentski delavci niso mogli priučiti odgovornosti in zanesljivosti, drugi pa so ugotovili, da jim tovrstno samostojno delo pravzaprav bolj ustreza in se odpravili na pot samostojnega podjetništva. Izigravanje in izrinjanje mladih se danes nadaljuje z neplačanimi pripravništvi in z Zakonom o uravnoteženju javnih financ, ki prepoveduje zaposlovanje v javnem sektorju.

Mladi ne rabimo socialne varnosti, ampak priložnost, da se izkažemo. Vse to toleriramo in tudi požremo, ker vidimo priložnosti in želimo marsikaj doseči. A največji pljunek v obraz je odrekanje priznavanja dosežkov. Ko mladim uspe kaj neverjetnega, so deležni kake lepe besede, pri tem pa se že konča. S strani starejših in nadrejenih ne dobijo priznanja z dejanji.

To so glavni viri slovenskega trenja med mladimi in starimi: starejši so si pridobili nadvlado nad mladimi, ki je mlajši ne moremo smatrati za legitimno, saj večina njihovih pridobitev ni bila ustvarjena z delom in sposobnostjo. Mlade sistematično in sistemsko izigravajo in ropajo z oblikami dela, ki ne nudijo predvidljive varnosti in so brez pravic, hkrati pa jim še pol tega, kar zaslužijo, poberejo z davčno utajevanimi najemninami. Ob vsem tem pa veselo ignorirajo dosežke mladih. Ljudi, ki imajo do tebe tak odnos, je res težko ne sovražiti!

Skrajševanje delovnega časa ne reši poglavitnega, saj vsi vzroki nastalih zamer ostajajo. Največji del konflikta bi razrešili, če bi začeli priznavati dosežke mladih z dejanji, ne zgolj z besedami. Torej, da bi jih ob prizadevnosti in doseganju kakovostnih rezultatov nagradili s finančno stabilnostjo in ne tako, kot se je nekdanji glavni urednik Večera spraševal o Jaši Lorenčiču: “Zakaj te damo Jaši 100 evrov za koncert? Daj mu 20, saj bo itak šel, saj vidiš, kako je zagnan.” Zakaj vrtnine pridno in izdatno zalivamo, ko spomladi ženejo, mlade in perspektivne delavce pa izsušujemo?

Finančna varnost in stabilnost je osnova za kvalitetno delo, izjemni dosežki se ustvarjajo le, ko nudimo sposobnemu človeku varnost, da dan za dnem niza majhne korake naprej. Vsa velika podjetja in podvigi so zrastli iz majhnih. Tako je npr. Dnevnikova ekipa, ki ustvarja vizualizacije v rubriki Objektivno, v treh letih prišla do mednarodnega priznanja, do katerega so se priborili v boju z medijskimi velikani, ki so nekaj velikostnih razredov večji od Dnevnika. Menite, da bodo vodje prepoznali ta dosežek kot nekaj, kar si zasluži finančno stabilnost in nadaljnje vlaganje?

Koliko je takšnih med redno zaposlenimi, ki so sposobni toliko empatije in vodstvenega uvida, da si aktivno prizadevajo, da bi honorarne sodelavce, ki so v organizaciji pravzaprav ustvarili pomembna znanja, obdržali ne z izsiljevanjem, npr. z izjavami, "da je drugje enako ali še slabše" ter da "naj bodo veseli, da imajo delo", ampak raje s priznanjem, da delajo dobro?

Izjemni dosežki zahtevajo nekaj sreče, a niso naključja. Ker taki posamezniki dokazujejo, da delajo dobro, jim je potrebno pripustiti, da sodelujejo pri odločitvah o svojem delu in tudi širše znotraj organizacije. Sprva kot opazovalce in posvetovalce, da lahko v intimi pogovora na štiri oči pretehtajo hipotetične odločitve in vrednotijo boljše in slabše.

Sčasoma taki posamezniki razvijejo nov, bistveno boljši pristop k reševanju dane težave. Takrat jim moramo dovoliti, da svoje ideje udejanijo. Zelo pomembno je, da idejo udejani avtor, saj je to nova priložnost za njegovo rast in nadaljno zvestobo mentorju ter organizaciji.

Miha Blažič žal ne razume, da mladi, ki so jezni zaradi privilegijev starejših, vendarle niso najboljša stvar, ki se je gospodarstvu kadarkoli zgodila. Nobena gospodarska družba ne potrebuje internega razslojevanja na bolj in manj priviligirano kasto zaposlenih, ker je to resna ovira na poti k temu, da bi vsi stremeli k istemu cilju. Slovensko gospodarstvo nujno potrebuje kvalitetno vodenje, ki bo pripoznavalo dosežke in jim dajalo veljavo ne samo z besedami, ampak tudi z dejanji, hkrati pa bo od vseh zaposlenih zahtevalo, da ostajajo na svojem področju na tekočem, saj bodo le na ta način konkurenčna podjetja in tudi zaposleni.

E-knjigarne v Sloveniji
pod kategorijami: slovenija software eknjige

Samo Rugelj se je nedavno razpisal o Amazonu, v svojem prispevku pa je omenil tudi dve slovenski eštacuni z eknjigami, Biblos in e-emko. Med ogledom emke sem našel knjigo, ki me je pritegnila - emka omogoča spletni ogled prvih nekaj strani knjige. Gre za Čeferinovo Moje odvetniško življenje, ki se začne z zanimivo prigodo s prvim obiskom sodišča v odvetniški vlogi. Kasneje sem na Biblosu našel slovenski prevod Cicerovega O dolžnostih (De Officiis). Ta je sicer v angleščini na voljo brezplačno na, saj je knjiga že "precej" stara, tako da se najdejo tudi stari prevodi, katerim so avtorske pravice že potekle, ni pa mi ravno bilo za brati angleški prevod.

No, tako sem imel dve eknjigi, od katerih je bila vsaka na voljo na eni spletni trgovini. Priročno za hitri test. Test je osredotočen na delovanje spletnih trgovin, predvsem z vidika uporabniške prijaznosti in varnosti s končnim ciljem preverit, če je možno knjige brati tudi na Kindlu.


Biblos je spletna knjigarna z e-knjigami, ki v sodelovanju s knjižnicami omogoča tudi izposojo e-knjig. Če prav razumem, si uporabnik v knjižnici izposodi napravo, na kateri so izbrane e-knjige. Upravlja jo Beletrina, so pa menda na voljo tudi knjige drugih založb.

Za izposojo ali nakup je potrebna prijava, ki zahteva kar dosti podatkov - ok, naslov in email, ampak zakaj telefon? Praznega človeku seveda ni dovoljeno pustiti ... S tega vidika moram pohvaliti spletno trgovino založbe Primus, kjer za nakup (celulozne) knjige nisem potreboval ustvariti računa. Pri vpisu e-poštnega naslova in izbiri gesla sem opazil, da sistem brez problema sprejme epoštni naslov, ki vsebuje "+" (koristno za označevanje v GMailu), z veseljem sprejme vsaj 20 znakovna gesla, uporabniškega imena pa ni oziroma je uporabniški identifikator kar e-poštni naslov.

Aja, po e-pošti sem prejel pozdravno pismo (samo v HTML obliki), ki ga je GMail uvrstil med neželeno pošto, v njem pa so mi poslali prvo in zadnjo črko gesla, vmesni znaki pa so bili zatemnjeni z zvezdico. Dobro, pri 20 znakih to morda niti ni tako velik problem. Znana dolžina gesla sicer poenostavi problem iskanja za 50%. Napisali so tudi, da so gesla v sistemu shranjena v šifrirani obliki.

Prijava - zmedena. Za prijavo je potrebno izbrati knjižnico, vpisati e-pošto ter geslo. Brez izbire knjižnice prijava ne uspe, a kaj naj s knjižnico, če knjigo kupujem? (Naknadno sem opazil, da omogoča tudi prijavo samo z e-poštnim naslovom in geslom, ta način prijave pa je pri neprijavljenem uporabniku skrit za dodatnim klikom.) No, po prijavi si sistem tudi ni zapomnil katero knjigo sem si ogledoval. Presenetil me je vmesnik za prijavo (za izposojo), ki se prikazuje pri vrhu strani, in to tudi kadar sem že prijavljen. Popolnoma nepotrebna zmeda.

Nakup knjige je relativno enostaven. Knjigo dodamo v košarico, gremo na blagajno, tam pa me je pričakala dobra in slaba novica. Slaba: v nešifrirano spletno stran je vstavljen IFRAME, ki se povezuje na šifrirano spletno stran, v katero naj bi vpisal podatke o kreditni kartici. Ta rešitev dopušča napad, kjer lahko zlobnež vstavi kodo, ki pravi vmesnik zamenja z zlobnim, ki lahko pokrade podatke. Izvajalec plačilnih storitev ima ob pisanju tega srednje varno šifrirano povezavo. Dobra novica je, da je na voljo tudi PayPal.

Po uspelem nakupu sem imel na voljo prenos e-knjige v epub. Hja, no, v ACSM formatu, ki ga pozna Adobe Digital Editions. Knjiga se je uspešno uvozila v Adobeov program, ki dela tudi na Linuxu prek Wine, z nekaj akrobacije pa je možno knjigo brati tudi na Kindlu.

Ocena spletne knjigarne: 3,5 od 5.

  • knjigarna je uporabna,
  • ne potrebujem uporabniškega imena,
  • sistem podpira vsaj 20 znakov za geslo,
  • sistem sprejme epoštni naslov v obliki email+znač,
  • uporablja standardne rešitve: PayPal, Adobe Digital Editions, epub;
  • uporabniški vmesnik je zmeden, sploh prijava,
  • ne uporablja HTTPS,
  • z nekoliko akrobacije omogoča tudi branje na Kindlu.

Če Beletrina doda še HTTPS ter nekoliko popravijo uporabniški vmesnik, bo to že dostojna spletna knjigarna. Mimogrede, iščejo tudi avtorje, ki bi svoje knjige želeli objaviti prek knjigarne Biblos.


E-emka je, kot že ime namiguje, spletna knjigarna Mladinske knjige. Želeno knjigo sem neprijavljen dodal v košaro, za nakup pa je sistem zahteval prijavo oz. ustvarjanje novega računa. Uf. Prvo presenečenje: potrebujem uporabniško ime. Šele tu sem se zavedel, da ga pri Biblosu sploh nisem potreboval. Dalje: gesla so lahko dolga največ 15 znakov in ... ne smejo vsebovati presledkov ter enojnih narekovajev. Slabo znamenje, kar se varnosti tiče, saj to namiguje, da nekdo ne zna pravilno uporabljati podatkovne baze. Prav tako mi sistem ni sprejel e-pošte, ki je vsebovala znak +, kar spet namiguje, da nekdo ne ve kaj vse je lahko veljaven e-poštni naslov.

Slabe varnostne prakse se nadaljujejo: po registraciji sem po epošti prejel geslo v čitljivi obliki. Brez komentarja. E-pošta je bila tudi tokrat le v HTML obliki.

Po prijavi sem - če prav razumem je bilo to namenjeno izdaji računa - moral še enkrat navesti ime in priimek ter epoštni naslov, ki sem ju že navedel. Poleg tega pa seveda še druge podatke - naslov, telefon ter občino in kraj. Občino, WTF? Ja, in seveda ni na voljo letos ustanovljene občine Ankaran, niti ni občine Mirna, ki je bila ustanovljena že leta 2011. Kot bi izpolnjeval obrazec za nek državni urad.

Za plačilo sem moral vpisati številke Vise. K sreči je bila povezava tokrat šifrirana v celoti, a kaj ti to pomaga, če spletni strežnik (vsaj v času pisanja tega) podpira tudi zastarel in nevaren šifrirni protokol SSL2. Plačilo s PayPalom ni podprto, čeprav je bilo iz grafičnega vmesnika sklepati, da plačilo gre prek PayPala. Tečno še enkrat pretipkovat vse tiste cifre, še malo bolj tečno, da mi je brskalnik ponudil, da si te številke zapomni.

Po nakupu je knjiga na voljo za ogled preko spleta, no, ne preko spleta, ampak preko Flash aplikacije, kar je nekoliko nerodno, saj ne uporabljam Flasha. Alternativa je iOS ali Android aplikacija, kjer so me komentarji resno prestrašili. Čitalnica knjig, ki potrebuje root dostop do telefona? Veliko negativnih ocen.

No, zaenkrat kaže, da bom nakup storniral ter raje vzel fizično kopijo.

Ocena spletne knjigarne: 1 od 5.

  • knjigarna je zelo štorasta,
  • iz sistema kričijo slabe varnostne prakse: geslo prek e-pošte v čitljivi obliki, največ 15 znakov z omejitvami;
  • izvajalec plačilnih storitev ima neustrezen nivo šifriranja,
  • dvojno vnašanje že istih podatkov,
  • čemu so potrebni podatki o občini?!,
  • ni PayPala (ali pa ga nisem našel),
  • nestandardne rešitve,
  • aplikacija, ki se je ne upam namestit,
  • Kindle? Ne.