Slide 1

Slide 1 text

a sermon on reusability Let them configure!

Slide 2

Slide 2 text

Łukasz Langa ambv at #python-dev (FreeNode IRC) @llanga on Twitter [email protected] as a last resort

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

Click icon to add picture Robert M. Pirsig • „The solutions all are simple – after you have arrived at them. • But they're simple only when you know already what they are.”

Slide 7

Slide 7 text

four desirable characteristics of configuration

Slide 8

Slide 8 text

COMPOSABLE

Slide 9

Slide 9 text

READABLE

Slide 10

Slide 10 text

EXCHANGEAB LE

Slide 11

Slide 11 text

DISCOVERAB LE

Slide 12

Slide 12 text

COMPOSABLE READABLE EXCHANGEABLE DISCOVERABLE

Slide 13

Slide 13 text

configuration format whirlwind tour

Slide 14

Slide 14 text

Easy-ish formats [user] email = [email protected] name = Łukasz Langa [push] default = current [color] branch = auto diff = auto interactive = auto status = auto [diff] external = git_vimdiff [pager] diff = [core] excludesfile = ~/.gitignore • INI • Apache • nginx • JSON

Slide 15

Slide 15 text

Easy-ish formats Listen 80 User apache Group apache DocumentRoot "/var/www/vhosts/root" Options FollowSymLinks AllowOverride None Options Indexes FollowSymLinks MultiViews ExecCGI AllowOverride All • INI • Apache • nginx • JSON

Slide 16

Slide 16 text

Easy-ish formats Listen 80 User apache Group apache DocumentRoot "/var/www/vhosts/root" Options FollowSymLinks AllowOverride None Options Indexes FollowSymLinks MultiViews ExecCGI AllowOverride All • INI • Apache • nginx • JSON What’s the difference: Options +Indexes Includes MultiViews Options Indexes Includes MultiViews

Slide 17

Slide 17 text

Easy-ish formats server { listen 80; server_name d.com *.d.com; rewrite ^ http://www.d.com $request_uri? permanent; } server { listen 80 default; server_name www.d.com; index index.html; root /home/d.com; location /forum { rewrite forum(.*) http:// forum.d.com$1 • INI • Apache • nginx • JSON

Slide 18

Slide 18 text

Easy-ish formats { "production":{ "phpSettings":{ "display_startup_errors": false, "display_errors": false }, "includePaths":{ "library": "APPLICATION_PATH/../library" }, "bootstrap":{ "path": "APPLICATION_PATH/Bootstrap.php ", "class": "Bootstrap" }, • INI • Apache • nginx • JSON

Slide 19

Slide 19 text

Easy-ish formats • INI • Apache • nginx • JSON WHAT ABOUT TOML?

Slide 20

Slide 20 text

Easy-ish formats # This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder\n& CEO" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. [servers.alpha] ip = "10.0.0.1" # inline comments [servers.beta] ip = "10.0.0.2" [clients] data = [ ["gamma", "delta"], [1, 2] ] • INI • Apache • nginx • JSON • TOML?

Slide 21

Slide 21 text

Easy-ish formats # This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder\n& CEO" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. [servers.alpha] ip = "10.0.0.1" # inline comments [servers.beta] ip = "10.0.0.2" [clients] data = [ ["gamma", "delta"], [1, 2] ] • INI • Apache • nginx • JSON • TOML? Strings are single-line values surrounded by double quotes encoded in UTF-8. vs. \xXX - byte (0x00-0xFF)

Slide 22

Slide 22 text

Easy-ish formats # This is a TOML document. Boom. title = "TOML Example" [owner] name = "Tom Preston-Werner" organization = "GitHub" bio = "GitHub Cofounder\n& CEO" dob = 1979-05-27T07:32:00Z [database] server = "192.168.1.1" ports = [ 8001, 8001, 8002 ] connection_max = 5000 enabled = true [servers] # You can indent as you please. [servers.alpha] ip = "10.0.0.1" # inline comments [servers.beta] ip = "10.0.0.2" [clients] data = [ ["gamma", "delta"], [1, 2] ] • INI • Apache • nginx • JSON • TOML?

Slide 23

Slide 23 text

Complex formats

Slide 24

Slide 24 text

Complex formats application: myapp version: 1 runtime: python27 api_version: 1 threadsafe: true handlers: - url: / script: home.app - url: /index\.html script: home.app - url: /stylesheets static_dir: stylesheets - url: /(.*\.(gif|png|jpg)) static_files: static/\1 upload: static/(.*\.(gif|png| • XML • YAML

Slide 25

Slide 25 text

Turing complete formats DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/project.db', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } • Python

Slide 26

Slide 26 text

Awkward formats Feature: Addition In order to avoid mistakes As a math slouch I want to be told the sum of two numbers Scenario: Add two numbers Given I have entered 50 into the calc And I have entered 70 into the calc When I press add Then the result should be 120 • Domain-Specific Languages • SQLite • Windows registry

Slide 27

Slide 27 text

Awkward formats class davids_black_co_at { hosting::user { rztt: realname => "Gerhard Schmitt", uid => 2001, admin => true; conny: realname => "Conny Schmitt", uid => 2002; oma: realname => "Oma Schmitt", uid => 2003; } # Install git.black.co.at include git::daemon • Domain-Specific Languages • SQLite • Windows registry

Slide 28

Slide 28 text

Awkward formats # main.cf ... alias_maps = sqlite:/etc/postfix/sqlite- aliases.cf ... # sqlite config file for # local(8) aliases(5) lookups dbpath = /path/to/sqlite_database query = SELECT forw_addr FROM mxaliases WHERE alias='%s’ • Domain-Specific Languages • SQLite • Windows registry

Slide 29

Slide 29 text

Awkward formats sqlite> .tables directory handler log proxy server statistic filter host mimetype route setting sqlite> select * from host; 1|1|0|localhost|localhost sqlite> select count(*) from mimetype; 850 sqlite> select * from server; • Domain-Specific Languages • SQLite • Windows registry

Slide 30

Slide 30 text

Awkward formats sqlite> .tables directory handler log proxy server statistic filter host mimetype route setting sqlite> select * from host; 1|1|0|localhost|localhost sqlite> select count(*) from mimetype; 850 sqlite> select * from server; • Domain-Specific Languages • SQLite • Windows registry # get s list of the available servers to run m2sh servers -db tests/config.sqlite # see what hosts a server has m2sh hosts -db tests/config.sqlite -server test # find out if a server named 'test' is running m2sh running -db tests/config.sqlite -name test # start a server who's default host is 'localhost' m2sh start -db tests/config.sqlite -host localhost

Slide 31

Slide 31 text

Awkward formats • Domain-Specific Languages • SQLite • Windows registry

Slide 32

Slide 32 text

The worst format ever Your own format

Slide 33

Slide 33 text

YOU WILL IMPOSE A LEARNING CURVE ON YOUR USERS

Slide 34

Slide 34 text

YOUR DESIGN DECISIONS WILL BE UNINTUITIVE

Slide 35

Slide 35 text

YOU WILL FAIL AT PARSING

Slide 36

Slide 36 text

PEOPLE WILL START DEPENDING ON THE PARSER

Slide 37

Slide 37 text

CONFIGURATION WRITTEN ONCE HAS TO BE SUPPORTED FOREVER

Slide 38

Slide 38 text

Seeking balance one-size-fits-all vs. tweakable-beyond- recognition

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

ambv@arrakis:~ $ wget -O - "https://www.dropbox.com/download? plat=lnx.x86_64" | tar xzf - --2012-10-20 11:24:22-- https://www.dropbox.com/download? plat=lnx.x86_64 Resolving www.dropbox.com... 199.47.217.171, 199.47.216.170, 199.47.216.171, ... Connecting to www.dropbox.com|199.47.217.171|:443... connected. HTTP request sent, awaiting response... 302 FOUND Location: https://dl-web.dropbox.com/u/17/dropbox-lnx.x86_64- 1.4.17.tar.gz [following] --2012-10-20 11:24:23-- https://dl-web.dropbox.com/u/17/dropbox- lnx.x86_64-1.4.17.tar.gz Resolving dl-web.dropbox.com... 174.129.197.250, 174.129.199.91, 107.20.174.220, ... Connecting to dl-web.dropbox.com|174.129.197.250|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 19090076 (18M) [application/x-tar] Saving to: `STDOUT' 100% [=============================================================>] 19,090,076 1.23M/s in 17s

Slide 41

Slide 41 text

ambv@arrakis:~ $ wget -O - "https://www.dropbox.com/download? plat=lnx.x86_64" | tar xzf - 100%[======>] 19,090,076 1.23M/s in 17s ambv@arrakis:~ $ ./.dropbox- dist/dropboxd This client is not linked to any account... Please visit https://www.dropbox.com/cli_link?

Slide 42

Slide 42 text

COMPOSABLE READABLE EXCHANGEABLE DISCOVERABLE

Slide 43

Slide 43 text

Excerpts from >>> import this Beautiful is better than ugly. Simple is better than complex. Flat is better than nested. Readability counts. There should be one (and preferably only one) obvious way to do it.

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

Side note. Go to: http://make-everything-ok.com/

Slide 47

Slide 47 text

CONFIG != DATA

Slide 48

Slide 48 text

Hard coding • An anti-pattern • Like hardwiring circuits • Configuration embedded in source code

Slide 49

Slide 49 text

Reverse hard coding • Source code embedded in configuration • Also an anti-pattern

Slide 50

Slide 50 text

CONFIG != CODE

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

Practical configurability DJANGo: settings.py

Slide 53

Slide 53 text

Django settings.py Django mixes different kinds of settings • Framework behaviour • Application behaviour • Deployment-specific configuration • databases • caches • logging • paths • ADMINS • MANAGERS • DEBUG • Sensitive data • passwords • SECURE_KEY • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 54

Slide 54 text

Django settings.py # settings.py # ... TIME_ZONE = 'Europe/Zurich' LANGUAGE_CODE = 'en-us' SECRET_KEY = 'secret' # ... from settings_local import * • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 55

Slide 55 text

Django settings.py # settings/__init__.py # ... TIME_ZONE = 'Europe/Zurich' LANGUAGE_CODE = 'en-us' SECRET_KEY = 'secret' # ... try: from .local import * except ImportError: pass • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 56

Slide 56 text

Django settings.py Alternative approach • settings.py is never used • settings_base.py defines the base configuration • settings_prod.py, settings_dev.py, etc. import settings_base.py at the beginning • run with DJANGO_SETTINGS_MODULE = proj.settings_prod • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 57

Slide 57 text

Django settings.py # settings.py import os.path import glob conffiles = glob.glob( os.path.join( os.path.dirname(__file__), 'settings', '*.conf’ ) ) conffiles.sort() for f in conffiles: execfile(os.path.abspath(f )) • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 58

Slide 58 text

Django settings.py # settings.py import os.path import glob conffiles = glob.glob( os.path.join( os.path.dirname(__file__), 'settings', '*.conf’ ) ) conffiles.sort() for f in conffiles: execfile(os.path.abspath(f )) • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration $ ls settings/ 10-base.conf 20-engines.conf 30-site.conf ...

Slide 59

Slide 59 text

Django settings.py from configurations import Settings class Base(Settings): TIME_ZONE = 'Europe/Berlin' class Dev(Base): DEBUG = True TEMPLATE_DEBUG = DEBUG class Prod(Base): TIME_ZONE = 'America/New_York’ • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 60

Slide 60 text

Django settings.py from configurations import Settings class FullPageCaching(object): USE_ETAGS = True class Base(Settings): TIME_ZONE = 'Europe/Berlin' class Dev(Base): DEBUG = True TEMPLATE_DEBUG = DEBUG class Prod(Base, FullPageCaching): • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 61

Slide 61 text

Django settings.py export DJANGO_CONFIGURATION=Dev or python manage.py runserver --settings=mysite.settings --configuration=Dev • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 62

Slide 62 text

Django settings.py [database] DATABASE_USER = db-user DATABASE_PASSWORD = db-secret DATABASE_HOST = 127.0.0.1 DATABASE_PORT = 3306 DATABASE_ENGINE = mysql DATABASE_NAME = example TESTSUITE_DATABASE_NAME = test_example [secrets] SECRET_KEY = 12345678... CSRF_MIDDLEWARE_SECRET = 12345678... [debug] • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 63

Slide 63 text

Django settings.py # production environment prod.ini [database] DATABASE_PASSWORD = db-secret [secrets] SECRET_KEY = 12345678... CSRF_MIDDLEWARE_SECRET = 12345678... [debug] DEBUG = false TEMPLATE_DEBUG = false VIEW_TEST = false INTERNAL_IPS = 127.0.0.1 SKIP_CSRF_MIDDLEWARE = false • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 64

Slide 64 text

Django settings.py >>> c = ConfigParser() >>> c.read([‘config-base.ini', ‘config- prod.ini']) You can do a hierarchy like: 1. site-packages/project/config- defaults.ini 2. /etc/project/config.ini 3. /etc/project.d/10-config.ini 4. /etc/project.d/20-config.ini 5. ~/.project/config.ini 6. ENVIRONMENT_VARIABLE • The problem • from settings import * • Ordered incremental execfile • django- configurations • INI based configuration

Slide 65

Slide 65 text

Practical configurability mixing file-based configuration with command-line overrides

Slide 66

Slide 66 text

Mixing file-based configuration with command-line overrides • Use configglue • Checkout out ConfArgParse • Whatever you do, name your command-line arguments on par with the file configuration settings

Slide 67

Slide 67 text

configparser the real reason to switch to python 3

Slide 68

Slide 68 text

An example file cfg = """ [DEFAULT] host = localhost port = 8080 [user] name = ambv email = [email protected] """

Slide 69

Slide 69 text

The old way import ConfigParser cp = ConfigParser.SafeConfigParser() from cStringIO import StringIO sio = StringIO(cfg) cp.readfp(sio)

Slide 70

Slide 70 text

The old way import ConfigParser cp = ConfigParser.SafeConfigParser() from cStringIO import StringIO sio = StringIO(cfg) cp.readfp(sio)

Slide 71

Slide 71 text

The old way import ConfigParser cp = ConfigParser.SafeConfigParser() from cStringIO import StringIO sio = StringIO(cfg) cp.readfp(sio)

Slide 72

Slide 72 text

The new way from configparser import ConfigParser cp = ConfigParser() cp.read_string(cfg)

Slide 73

Slide 73 text

The old way cp.readfp(sio) if cp.has_section('user'): print(cp.get('user', 'email')) cp.set('user', 'password', 'secret') cp.set('user', 'jabber', '% (email)s') print(cp.get('user', 'jabber'))

Slide 74

Slide 74 text

The old way cp.readfp(sio) if cp.has_section('user'): print(cp.get('user', 'email')) cp.set('user', 'password', 'secret') cp.set('user', 'jabber', '% (email)s') print(cp.get('user', 'jabber')) This reminds me of: >>> import string >>> string.split('hakuna matata') ['hakuna', 'matata'] >>> {}.has_key('to your heart') False >>> bool('Yuck') True

Slide 75

Slide 75 text

The old way if cp.has_section('user'): print(cp.get('user', 'email')) cp.set('user', 'password', 'secret') cp.set('user', 'jabber', '% (email)s') print(cp.get('user', 'jabber'))

Slide 76

Slide 76 text

The new way if 'user' in cp: user = cp['user'] print(user['email']) user['password'] = 'secret' user['jabber'] = '%(email)s' print(cp['user']['jabber'])

Slide 77

Slide 77 text

The old way for option in cp.options('user'): print(option, end=", ") print()

Slide 78

Slide 78 text

The new way for option in cp[‘user’]: print(option, end=", ") print()

Slide 79

Slide 79 text

The old way if cp.has_option('user', 'host'): print(cp.get('user', 'host'))

Slide 80

Slide 80 text

The new way user = cp[‘user’] if 'host' in user: print(user['host'])

Slide 81

Slide 81 text

The new way print(user.get('host’, fallback=None))

Slide 82

Slide 82 text

Configuration from a string cfg = """ [DEFAULT] host = localhost port = 8080 [user] name = ambv email = [email protected] """

Slide 83

Slide 83 text

Configuration from a dictionary cfg = dict( DEFAULT = dict( host = 'localhost', port = '8080’, ), USER = dict( name = 'ambv', email = '[email protected]’, ), )

Slide 84

Slide 84 text

Configuration from a dictionary cp = ConfigParser() cp.read_dict(cfg) cp2 = ConfigParser() cp2.read_dict(cp) assert cp == cp2

Slide 85

Slide 85 text

Creating sections from a dictionary cp['ui'] = { 'askusername': 'yes', 'fallbackencoding': 'utf-8', 'ignore': '~/.hgignore', } print(cp['ui'].items())

Slide 86

Slide 86 text

Creating sections from a dictionary cp['ui'] = { 'askusername': 'yes', 'fallbackencoding': 'utf-8', 'ignore': '~/.hgignore', } print(cp['ui'].items()) The output: [('ignore', '~/.hgignore'), ('askusername', 'yes'), ('fallbackencoding', 'utf-8'), ('host', 'localhost'), ('port', '8080')]

Slide 87

Slide 87 text

Buildout-inspired interpolation from configparser import ConfigParser,\ ExtendedInterpolation cp = ConfigParser(interpolation= ExtendedInterpolation()) cp.read_string(""" [general] project_dir = /opt/epic_project debug = False [cms] path = ${general:project_dir}/cms debug = ${general:debug}

Slide 88

Slide 88 text

Buildout-inspired interpolation from configparser import ConfigParser,\ ExtendedInterpolation cp = ConfigParser(interpolation= ExtendedInterpolation()) cp.read_string(""" [general] project_dir = /opt/epic_project debug = False [cms] path = ${general:project_dir}/cms debug = ${general:debug} Transitive interpolation: >>> cp['cms-plugin'].items() [('path', '/opt/epic_project/cms/plugin’), ('debug', 'False')]

Slide 89

Slide 89 text

Highly customizable!

Slide 90

Slide 90 text

Highly customizable!

Slide 91

Slide 91 text

Highly customizable!

Slide 92

Slide 92 text

Highly customizable!

Slide 93

Slide 93 text

Highly customizable!

Slide 94

Slide 94 text

Highly customizable!

Slide 95

Slide 95 text

Still stuck on Python 2.7?

Slide 96

Slide 96 text

Still stuck on Python 2.6?

Slide 97

Slide 97 text

Still stuck on Python 2.6? pip install configparser

Slide 98

Slide 98 text

Questions? ambv at #python-dev (FreeNode IRC) @llanga on Twitter [email protected] as a last resort