SlideShare a Scribd company logo
Fabric al PyCon 5 di Firenze
Taa taa chi trova fabric non lo lascia più…
$ fab taskA taskB
from fabric.api import run, env

env.hosts = ['host1', ‘host2']
def taskA():

run(‘ls')
def taskB():

run('whoami')
$ fab mytask:roles=role1
from fabric.api import env
env.roledefs = {

'web': ['www1', 'www2', 'www3'],

'dns': ['ns1', ‘ns2']
}
def mytask():

run('ls /var/www')
$ fab mytask:roles=role1,exclude_hosts="a;c"
from fabric.api import env, hosts, roles, run
env.roledefs = {'role1': ['b', ‘c']}
@hosts('a', ‘b')
@roles(‘role1')
def mytask():

run('ls /var/www')
$ fab migrate update
from fabric.api import run, roles
env.roledefs = {

'db': ['db1', 'db2'],

'web': ['web1', 'web2', ‘web3'],
}
@roles(‘db')
def migrate():

# Database stuff here.

pass
@roles(‘web')
def update():

# Code updates here.

pass
fab deploy
from fabric.api import run, roles, execute
def deploy():

execute(migrate)

execute(update)
migrate on db1
migrate on db2
update on web1
update on web2
update on web3
$ fab deploy:app or $ fab deploy:db
from fabric.api import run, execute, task
from mylib import external_datastore
def do_work():

run("something interesting on a host”)
@task
def deploy(lookup_param):

host_list = external_datastore.query(lookup_param)

execute(do_work, hosts=host_list)
$ fab set_hosts:app do_work
from fabric.api import run, task
from mylib import external_datastore
@task
def do_work():

run("something interesting on a host")

@task
def set_hosts(lookup_param):

env.hosts = external_datastore.query(lookup_param)
Combining stdout and stderr
run("cmd", pty=False, combine_stderr=True):
run("cmd", pty=False, combine_stderr=False):
run("cmd", pty=True, combine_stderr=False):
$ fab -H host1,host2,host3 runs_in_parallel runs_serially
from fabric.api import *

@parallel
def runs_in_parallel():

pass
def runs_serially():

pass
runs_in_parallel on host1, host2, and host3
runs_serially on host1
runs_serially on host2
runs_serially on host3
$ fab -P -z 5 heavy_task
from fabric.api import *

@parallel(pool_size=5)
def heavy_task():

# lots of heavy local lifting or lots of IO here
@task(alias=’short’)
from fabric.api import task, run

@task
def mytask():

run("a command")



@task(alias=‘dwm’)
def deploy_with_migrations():

pass
Submodule deploy.py
@task(default=True)
def full_deploy():

pass
$ fab --list
Available commands:
deploy
deploy.full_deploy
deploy.migrate
Class Task
class MyTask(Task):

name = "deploy"

def run(self, environment, domain="whatever.com"):

run("git clone foo")

sudo("service apache2 restart")

instance = MyTask()
VS

@task
def deploy(environment, domain="whatever.com"):

run("git clone foo")

sudo("service apache2 restart")
Colors
from fabric.colors import green
print(green("This text is green!"))
fabric.colors.blue(text, bold=False)
fabric.colors.cyan(text, bold=False)
fabric.colors.green(text, bold=False)
fabric.colors.magenta(text, bold=False)
fabric.colors.red(text, bold=False)
fabric.colors.white(text, bold=False)
fabric.colors.yellow(text, bold=False)
Context managers
def mytask():

with cd('/path/to/app'), prefix('workon myvenv'):

run('./manage.py syncdb')

run('./manage.py loaddata myfixture')



with cd('/var/www'):

run('ls') # cd /var/www && ls

with cd('website1'):

run('ls') # cd /var/www/website1 && ls



with hide('running', 'stdout', 'stderr'):

run('ls /var/www')



# Map localhost:6379 on the server to localhost:6379 on the client,

# so that the remote 'redis-cli' program ends up speaking to the local

# redis-server. 

with remote_tunnel(6379):

run("redis-cli -i")
Contrib
Django Integration
Rsync Project
Upload Project
Console Confirm y/n
Files and Directory
So… what is Fabric?
● Deploy
● Manage multiple server
● Clustering
● Multiplatform
● Parallel
● Testing
● SSH Authentication
SSH + Bash Power + Python = Rocks**3 = Fabric
fab release:master
…
django integration
from fabric.contrib import django

django.settings_module(‘myproject.settings')
from django.conf import settings
def dump_production_database():

run(pg_dump -U %s -w %s > /bck/prod-db.sql' % (

settings.DATABASE_USER,

settings.DATABASE_NAME

))
fab deploy
@hosts('user@example.com')
def deploy():

with cd("/opt/myproject"):

run("git pull")

run("django-admin.py collectstatic --noinput")

run("django-admin.py migrate --noinput")

run("/etc/init.d/uwsgi stop || echo 'done'")

run("/etc/init.d/uwsgi start")
fab backup_and_publish
@task
@hosts('www-data@example.com')
def backup_and_publish():



run('''tar cjvf /var/wwwbackups/www.%s.tar.bz2
--exclude=/var/www/download
—exclude=/var/www/backup* /var/www'''
% today().strftime("%Y%m%d%H%M%S"))



run('rsync -avz --checksum --ignore-times
/var/wwwstage/ /var/www') #--delete
fab static_generation
@task
def static_generation():

execute(remote_generation)



local("wget --user=admin --password=rootme --recursive --page-requisites --html-
extension --convert-links --restrict-file-names=windows --domains example.com --
no-parent http://wwwstage.example.com/ -o dump.log || echo 'Looking for 404 on
wwwstage.example.com'")



local("cat dump.log | grep -B 2 '404 Not Found' | grep 'http://
wwwstage.example.com/' || echo 'OK no 404 found...'")
fab upload_release_note:2.10.0
@task
@hosts('install@example.com')
def upload_release_note(version):

release_note_file_name = "RELEASE_NOTE_%s.TXT" % version

with open(release_note_file_name,"w") as out_file:

notes = jira.Query().render(version=version)

out_file.write(notes.encode('ascii', 'ignore'))

out_file.close()

put(release_note_file_name, "/cygdrive/d/%s/" % version)
fab cleanup_nexus:10.0.2-RC2
@task
def cleanup_nexus(version):

for module in [

"core-api",

"core-client-rest",

"core-manual",

"core-web"]:


local("curl -X DELETE -u user:rootme http://nexus.example.com:
8180/nexus/service/local/repositories/releases/content/example/%s/
%s/" % (module, version))
LOCK_FILE = “~/.lockfile.release.core.lock"
class Lock():

def __enter__(self):

if os.access(os.path.expanduser(LOCK_FILE), os.F_OK):

pidfile = open(os.path.expanduser(LOCK_FILE), "r")

pidfile.seek(0)

old_pid = pidfile.readline()

print "There is an already a process running with pid: %s," % old_pid

sys.exit(1)



pidfile = open(os.path.expanduser(LOCK_FILE), "w")

pidfile.write("%s" % os.getpid())

pidfile.close



def __exit__(self, type, value, traceback):

os.remove(os.path.expanduser(LOCK_FILE))
Locks
fab send_email_candidate:2.12,me@...
@task
def send_mail_candidate(version, *receivers):

sender = 'development@geniusbytes.com'



body = """From: Core Team <noreply@example.com>To: Development
<development@example.com>Subject: New Release CANDIDATE %(version)snNew
Release CANDIDATE %(version)savailable on: * smb://example.com/myproject/%
(version)s """ % dict(version=version)

try:

message = smtplib.SMTP('example.com')

message.sendmail(sender, receivers, body)

print "Successfully sent email"

except smtplib.SMTPException:

print "Error: unable to send email"
XML parser
@task
def get_pom_version():

src=os.path.dirname(__file__)

pom_file=os.path.abspath(os.path.join(src, 'pom.xml'))

from xml.dom.minidom import parse

pom = parse(pom_file)

version = pom.getElementsByTagName("version")[1].firstChild.nodeValue

find = re.compile(r'^d+.d+.d+-([a-zA-Z-]+)d*-SNAPSHOT$').findall(version)

if not find:

abort(version + " is not a valid development version")

versions = re.compile(r'd+').findall(version)

if len(versions) is 3:

versions.append(1)

if len(versions) is not 4:

abort(version + " is not a valid development version")

versions.extend(find)

return versions
fab sed_poms_version:2.13
@task
def sed_poms_version(new_version):

major, minor, patch, rev, rc = get_pom_version()


version = "%s.%s.%s-%s%s-SNAPSHOT" %
(major, minor, patch, rc, rev)

local("sed -i '' 's@%s@%s@g' pom.xml */pom.xml" %
(version, new_version))
fab create_manuals:2.10
ACTIVATE="source /home/installer/.sphinx_env/bin/activate"



@hosts('installer@example.com')def create_manuals(version):

with cd(DEPLOY_DIR + "/myproject"):

name = "manual-%s-doc" % version

run("wget http://nexus.example.com:8180/nexus/service/local/repo_groups/public/content/com/
myproject/manual/%s/%s.zip" % (version, name))



with cd(name):

run(ACTIVATE + "&& make docs")

run("mv target/en/latex/MyProject*.pdf docs/" % version)

run("tar cjvf docs/MyCDDS-en-%s.tar.bz2 target/docs/" % version)

run("scp -r docs install@example.com:/cygdrive/d/%s/docs" % version)
fab create_installer:2.10 (innosetup)
@hosts('install@example.com')def create_installer(version):

name = "installer-%s-app" % version

run("wget http://nexus.geniusbytes.com:8180/nexus/service/local/repo_groups/public/content/
myproject/installer/%s/%s.zip" % (version, name))



with cd(name):

run("tar xjvf /cygdrive/d/%(version)s/MyCDDS-en-%(version)s.tar.bz2" % dict(version=version))



run(ANT)

run("mkdir -p /cygdrive/d/%s" % version)

run("cp build/*.exe /cygdrive/d/%s/" % version)

run("cp build-update/*.exe /cygdrive/d/%s/" % version)



run("rm -rf %s" % name)
fab release_core:master,2.10,2.11
@hosts('installer@ecample.com')
def release_core(branch, version, next_version):

with cd(CORE_DEPLOY_DIR):



run('git clone ssh://i@example.com/srv/git/myproject.git')

with cd(CORE_DEPLOY_DIR + "/myproject"):

run("git checkout %s" % branch)

run("mvn clean install")



run("mvn --batch-mode release:clean release:prepare
-DreleaseVersion=%s -DdevelopmentVersion=%s" %
(version, next_version))

run("mvn release:perform")
fab release:master
def release(branch):

with Lock():

major, minor, patch, rev, rc = check_current_version(branch)

if 'RC' != rc:

abort("RC not found, not possible release a final version")



version = "%s.%s.%s" % (major, minor, patch)

next_version = "%s.%s.%s-RC%s-SNAPSHOT" % (major, minor, int(patch)+1, 1)



puts("preparing to release %s (next will be %s)" % (version, next_version))

execute(release_core, branch, version, next_version)

execute(create_manuals, version)

execute(create_installer, version)

execute(upload_release_note, version)

execute(send_mail_final_release, version, 'me@ex.com', 'dev@ex.com')

local("git pull")

execute(labels.missing_translations, 'me@ex.com')
fab cluod_remote_control
...
EC2 Testing with 200 micro server
EC2 + Fabric + Funkload
● EC2 use all ubuntu standard AMI
● Fabric as remote control, move files, aggregate.
● Funkload in order to stress an internet application. (not on
EC2)
Performance Testing Architecture
Target
Cloud
CTRL
Tester
Target
Target
FunkLoad
Fabric
(nmon+pefmon)
Fabric +
EC2
Fabric +
EC2
Testing phases
I. Prepare Monitoring
II.Prepare Cloud
1. Start Monitoring
2. Start Parallel Testing
3. Collecting Test Results
4. Collecting Perf Results
5. Reporting
Target
Cloud
CTRL
Tester
Target
Target
FunkLoa
d
Fabric
(nmon+pefmon)
Fabric +
EC2
Fabric +
EC2
Testing Console
fab prepare_monitoring
fab prepare_cloud
fab start_monitoring
fab start_testing:ciccio,100,5000
fab collecting_test_results:ciccio
fab collecting_perf_results:ciccio
fab reporting:ciccio

More Related Content

What's hot

Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
Shmuel Fomberg
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworksdiego_k
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
Salaudeen Rajack
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
Marcus Ramberg
 
Any event intro
Any event introAny event intro
Any event intro
qiang
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
Leon van der Grient
 
Refactoring Infrastructure Code
Refactoring Infrastructure CodeRefactoring Infrastructure Code
Refactoring Infrastructure Code
Nell Shamrell-Harrington
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
Matt Follett
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webclkao
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
bpmedley
 
Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
hendrikvb
 
Puppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick BuckleyPuppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick Buckley
Christian Mague
 
Follow the White Rabbit - Message Queues with PHP
Follow the White Rabbit - Message Queues with PHPFollow the White Rabbit - Message Queues with PHP
Follow the White Rabbit - Message Queues with PHP
Eric Rodriguez (Hiring in Lex)
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用Felinx Lee
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
Wallace Reis
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
xSawyer
 
More tips n tricks
More tips n tricksMore tips n tricks
More tips n tricks
bcoca
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
Anatoly Sharifulin
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
Luca Mearelli
 
Modern Perl
Modern PerlModern Perl
Modern Perl
Dave Cross
 

What's hot (20)

Perl: Coro asynchronous
Perl: Coro asynchronous Perl: Coro asynchronous
Perl: Coro asynchronous
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
Any event intro
Any event introAny event intro
Any event intro
 
Testing Backbone applications with Jasmine
Testing Backbone applications with JasmineTesting Backbone applications with Jasmine
Testing Backbone applications with Jasmine
 
Refactoring Infrastructure Code
Refactoring Infrastructure CodeRefactoring Infrastructure Code
Refactoring Infrastructure Code
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
 
Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
 
Puppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick BuckleyPuppet Node Classifiers Talk - Patrick Buckley
Puppet Node Classifiers Talk - Patrick Buckley
 
Follow the White Rabbit - Message Queues with PHP
Follow the White Rabbit - Message Queues with PHPFollow the White Rabbit - Message Queues with PHP
Follow the White Rabbit - Message Queues with PHP
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
More tips n tricks
More tips n tricksMore tips n tricks
More tips n tricks
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 

Viewers also liked

Dossier de presentación Addenda 2012
Dossier de presentación Addenda 2012Dossier de presentación Addenda 2012
Dossier de presentación Addenda 2012Addenda
 
How to be successful on LinkedIn
How to be successful on LinkedInHow to be successful on LinkedIn
How to be successful on LinkedIn
SOWEB Inc.
 
comidas sanas y no sanas
comidas sanas y no sanascomidas sanas y no sanas
comidas sanas y no sanas
iarahure
 
Army Enterprise Email Training: TechNet Augusta 2015
Army Enterprise Email Training: TechNet Augusta 2015Army Enterprise Email Training: TechNet Augusta 2015
Army Enterprise Email Training: TechNet Augusta 2015
AFCEA International
 
Presentación Sumando Contactos
Presentación Sumando ContactosPresentación Sumando Contactos
Presentación Sumando Contactos
Andrés Romero
 
The European Collaboration with a Swiss twist
The European Collaboration with a Swiss twistThe European Collaboration with a Swiss twist
The European Collaboration with a Swiss twist
Belsoft
 
Mite de Dafne
Mite de DafneMite de Dafne
Mite de DafneRapsodos
 
Nomadic Marketing March 2009
Nomadic Marketing March 2009Nomadic Marketing March 2009
Nomadic Marketing March 2009
Justin Hartman
 
Mother's day Gifts Ideas
Mother's day Gifts IdeasMother's day Gifts Ideas
Mother's day Gifts Ideas
Ariane Leanza Heinz
 
BOclassic 2015 Flyer
BOclassic 2015 FlyerBOclassic 2015 Flyer
BOclassic 2015 Flyer
Alberto Stretti
 
Emergencias Quirúrgicas en el RN
Emergencias Quirúrgicas en el RNEmergencias Quirúrgicas en el RN
Emergencias Quirúrgicas en el RN
Jazmin Gomez
 
Red azul-de-solidaridad-07
Red azul-de-solidaridad-07Red azul-de-solidaridad-07
Red azul-de-solidaridad-07
fundacionemilie
 
Proyecto estudio de labranza conservacionista
Proyecto estudio de labranza conservacionista Proyecto estudio de labranza conservacionista
Proyecto estudio de labranza conservacionista
sarilitmaita
 
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
Jeh718
 
Taller liderazgo interior
Taller liderazgo interiorTaller liderazgo interior
Taller liderazgo interior
M Angeles Marín Martín
 
PresentacióN Esp Interwine China 2010
PresentacióN Esp Interwine China 2010PresentacióN Esp Interwine China 2010
PresentacióN Esp Interwine China 2010
Alamesa
 

Viewers also liked (20)

Dossier de presentación Addenda 2012
Dossier de presentación Addenda 2012Dossier de presentación Addenda 2012
Dossier de presentación Addenda 2012
 
How to be successful on LinkedIn
How to be successful on LinkedInHow to be successful on LinkedIn
How to be successful on LinkedIn
 
Posada la desmera
Posada la desmeraPosada la desmera
Posada la desmera
 
comidas sanas y no sanas
comidas sanas y no sanascomidas sanas y no sanas
comidas sanas y no sanas
 
Army Enterprise Email Training: TechNet Augusta 2015
Army Enterprise Email Training: TechNet Augusta 2015Army Enterprise Email Training: TechNet Augusta 2015
Army Enterprise Email Training: TechNet Augusta 2015
 
Presentación Sumando Contactos
Presentación Sumando ContactosPresentación Sumando Contactos
Presentación Sumando Contactos
 
The European Collaboration with a Swiss twist
The European Collaboration with a Swiss twistThe European Collaboration with a Swiss twist
The European Collaboration with a Swiss twist
 
Mite de Dafne
Mite de DafneMite de Dafne
Mite de Dafne
 
Nomadic Marketing March 2009
Nomadic Marketing March 2009Nomadic Marketing March 2009
Nomadic Marketing March 2009
 
Mother's day Gifts Ideas
Mother's day Gifts IdeasMother's day Gifts Ideas
Mother's day Gifts Ideas
 
BOclassic 2015 Flyer
BOclassic 2015 FlyerBOclassic 2015 Flyer
BOclassic 2015 Flyer
 
Emergencias Quirúrgicas en el RN
Emergencias Quirúrgicas en el RNEmergencias Quirúrgicas en el RN
Emergencias Quirúrgicas en el RN
 
BES Radithupa CV
BES Radithupa CVBES Radithupa CV
BES Radithupa CV
 
Red azul-de-solidaridad-07
Red azul-de-solidaridad-07Red azul-de-solidaridad-07
Red azul-de-solidaridad-07
 
Proyecto estudio de labranza conservacionista
Proyecto estudio de labranza conservacionista Proyecto estudio de labranza conservacionista
Proyecto estudio de labranza conservacionista
 
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
Legal Research For The Legal Assistant: How To Find Statutes (Federal & New Y...
 
Taller liderazgo interior
Taller liderazgo interiorTaller liderazgo interior
Taller liderazgo interior
 
El Celrè 83
El Celrè 83El Celrè 83
El Celrè 83
 
PresentacióN Esp Interwine China 2010
PresentacióN Esp Interwine China 2010PresentacióN Esp Interwine China 2010
PresentacióN Esp Interwine China 2010
 
CURRICULOS NIVEL III
CURRICULOS NIVEL IIICURRICULOS NIVEL III
CURRICULOS NIVEL III
 

Similar to Fabric Python Lib

DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
Simone Federici
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slidesharetomcopeland
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
Leonardo Soto
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
Deepak Garg
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
ChengHui Weng
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
Lindsay Holmwood
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
Deployment with Fabric
Deployment with FabricDeployment with Fabric
Deployment with Fabricandymccurdy
 
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf Conference
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
Arto Artnik
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011Nick Sieger
 
Test driven infrastructure
Test driven infrastructureTest driven infrastructure
Test driven infrastructure
Skills Matter Talks
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
LumoSpark
 
Docker in Action
Docker in ActionDocker in Action
Docker in Action
Simon Su
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
Jakub Zalas
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Rajmahendra Hegde
 
Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36
Halil Kaya
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
Daniel Cukier
 

Similar to Fabric Python Lib (20)

DevOps with Fabric
DevOps with FabricDevOps with Fabric
DevOps with Fabric
 
Railsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshareRailsconf2011 deployment tips_for_slideshare
Railsconf2011 deployment tips_for_slideshare
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
Bangpypers april-meetup-2012
Bangpypers april-meetup-2012Bangpypers april-meetup-2012
Bangpypers april-meetup-2012
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Deployment with Fabric
Deployment with FabricDeployment with Fabric
Deployment with Fabric
 
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
ZFConf 2012: Capistrano для деплоймента PHP-приложений (Роман Лапин)
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Test driven infrastructure
Test driven infrastructureTest driven infrastructure
Test driven infrastructure
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)Web development automatisation for fun and profit (Artem Daniliants)
Web development automatisation for fun and profit (Artem Daniliants)
 
Docker in Action
Docker in ActionDocker in Action
Docker in Action
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36Infrastructure as code - Python Saati #36
Infrastructure as code - Python Saati #36
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 

More from Simone Federici

What is kanban
What is kanbanWhat is kanban
What is kanban
Simone Federici
 
What is xp
What is xpWhat is xp
What is xp
Simone Federici
 
Django productivity tips and tricks
Django productivity tips and tricksDjango productivity tips and tricks
Django productivity tips and tricks
Simone Federici
 
Python enterprise vento di liberta
Python enterprise vento di libertaPython enterprise vento di liberta
Python enterprise vento di liberta
Simone Federici
 
Java o non java
Java o non javaJava o non java
Java o non java
Simone Federici
 
Django in enterprise world
Django in enterprise worldDjango in enterprise world
Django in enterprise world
Simone Federici
 
Anti pattern se lo conosci lo eviti
Anti pattern se lo conosci lo evitiAnti pattern se lo conosci lo eviti
Anti pattern se lo conosci lo eviti
Simone Federici
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
Simone Federici
 
Django per non credenti
Django per non credentiDjango per non credenti
Django per non credenti
Simone Federici
 
Terracotta Torino Javaday
Terracotta Torino JavadayTerracotta Torino Javaday
Terracotta Torino JavadaySimone Federici
 
Terracotta Springmeeting
Terracotta SpringmeetingTerracotta Springmeeting
Terracotta SpringmeetingSimone Federici
 
Javaday Performance 2009
Javaday Performance 2009Javaday Performance 2009
Javaday Performance 2009
Simone Federici
 

More from Simone Federici (16)

What is kanban
What is kanbanWhat is kanban
What is kanban
 
What is xp
What is xpWhat is xp
What is xp
 
Django productivity tips and tricks
Django productivity tips and tricksDjango productivity tips and tricks
Django productivity tips and tricks
 
Python enterprise vento di liberta
Python enterprise vento di libertaPython enterprise vento di liberta
Python enterprise vento di liberta
 
Java o non java
Java o non javaJava o non java
Java o non java
 
Django in enterprise world
Django in enterprise worldDjango in enterprise world
Django in enterprise world
 
Anti pattern se lo conosci lo eviti
Anti pattern se lo conosci lo evitiAnti pattern se lo conosci lo eviti
Anti pattern se lo conosci lo eviti
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Django per non credenti
Django per non credentiDjango per non credenti
Django per non credenti
 
Opensource Aziende
Opensource AziendeOpensource Aziende
Opensource Aziende
 
Maven Eclipse
Maven EclipseMaven Eclipse
Maven Eclipse
 
Terracotta Torino Javaday
Terracotta Torino JavadayTerracotta Torino Javaday
Terracotta Torino Javaday
 
Jipday Portletjsr168
Jipday Portletjsr168Jipday Portletjsr168
Jipday Portletjsr168
 
Spring20 Javaday
Spring20 JavadaySpring20 Javaday
Spring20 Javaday
 
Terracotta Springmeeting
Terracotta SpringmeetingTerracotta Springmeeting
Terracotta Springmeeting
 
Javaday Performance 2009
Javaday Performance 2009Javaday Performance 2009
Javaday Performance 2009
 

Recently uploaded

AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
RicletoEspinosa1
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptxTOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
nikitacareer3
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 

Recently uploaded (20)

AIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdfAIR POLLUTION lecture EnE203 updated.pdf
AIR POLLUTION lecture EnE203 updated.pdf
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptxTOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
TOP 10 B TECH COLLEGES IN JAIPUR 2024.pptx
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 

Fabric Python Lib

  • 1. Fabric al PyCon 5 di Firenze Taa taa chi trova fabric non lo lascia più…
  • 2. $ fab taskA taskB from fabric.api import run, env
 env.hosts = ['host1', ‘host2'] def taskA():
 run(‘ls') def taskB():
 run('whoami')
  • 3. $ fab mytask:roles=role1 from fabric.api import env env.roledefs = {
 'web': ['www1', 'www2', 'www3'],
 'dns': ['ns1', ‘ns2'] } def mytask():
 run('ls /var/www')
  • 4. $ fab mytask:roles=role1,exclude_hosts="a;c" from fabric.api import env, hosts, roles, run env.roledefs = {'role1': ['b', ‘c']} @hosts('a', ‘b') @roles(‘role1') def mytask():
 run('ls /var/www')
  • 5. $ fab migrate update from fabric.api import run, roles env.roledefs = {
 'db': ['db1', 'db2'],
 'web': ['web1', 'web2', ‘web3'], } @roles(‘db') def migrate():
 # Database stuff here.
 pass @roles(‘web') def update():
 # Code updates here.
 pass
  • 6. fab deploy from fabric.api import run, roles, execute def deploy():
 execute(migrate)
 execute(update) migrate on db1 migrate on db2 update on web1 update on web2 update on web3
  • 7. $ fab deploy:app or $ fab deploy:db from fabric.api import run, execute, task from mylib import external_datastore def do_work():
 run("something interesting on a host”) @task def deploy(lookup_param):
 host_list = external_datastore.query(lookup_param)
 execute(do_work, hosts=host_list)
  • 8. $ fab set_hosts:app do_work from fabric.api import run, task from mylib import external_datastore @task def do_work():
 run("something interesting on a host")
 @task def set_hosts(lookup_param):
 env.hosts = external_datastore.query(lookup_param)
  • 9. Combining stdout and stderr run("cmd", pty=False, combine_stderr=True): run("cmd", pty=False, combine_stderr=False): run("cmd", pty=True, combine_stderr=False):
  • 10. $ fab -H host1,host2,host3 runs_in_parallel runs_serially from fabric.api import *
 @parallel def runs_in_parallel():
 pass def runs_serially():
 pass runs_in_parallel on host1, host2, and host3 runs_serially on host1 runs_serially on host2 runs_serially on host3
  • 11. $ fab -P -z 5 heavy_task from fabric.api import *
 @parallel(pool_size=5) def heavy_task():
 # lots of heavy local lifting or lots of IO here
  • 12. @task(alias=’short’) from fabric.api import task, run
 @task def mytask():
 run("a command")
 
 @task(alias=‘dwm’) def deploy_with_migrations():
 pass
  • 13. Submodule deploy.py @task(default=True) def full_deploy():
 pass $ fab --list Available commands: deploy deploy.full_deploy deploy.migrate
  • 14. Class Task class MyTask(Task):
 name = "deploy"
 def run(self, environment, domain="whatever.com"):
 run("git clone foo")
 sudo("service apache2 restart")
 instance = MyTask() VS
 @task def deploy(environment, domain="whatever.com"):
 run("git clone foo")
 sudo("service apache2 restart")
  • 15. Colors from fabric.colors import green print(green("This text is green!")) fabric.colors.blue(text, bold=False) fabric.colors.cyan(text, bold=False) fabric.colors.green(text, bold=False) fabric.colors.magenta(text, bold=False) fabric.colors.red(text, bold=False) fabric.colors.white(text, bold=False) fabric.colors.yellow(text, bold=False)
  • 16. Context managers def mytask():
 with cd('/path/to/app'), prefix('workon myvenv'):
 run('./manage.py syncdb')
 run('./manage.py loaddata myfixture')
 
 with cd('/var/www'):
 run('ls') # cd /var/www && ls
 with cd('website1'):
 run('ls') # cd /var/www/website1 && ls
 
 with hide('running', 'stdout', 'stderr'):
 run('ls /var/www')
 
 # Map localhost:6379 on the server to localhost:6379 on the client,
 # so that the remote 'redis-cli' program ends up speaking to the local
 # redis-server. 
 with remote_tunnel(6379):
 run("redis-cli -i")
  • 17. Contrib Django Integration Rsync Project Upload Project Console Confirm y/n Files and Directory
  • 18. So… what is Fabric? ● Deploy ● Manage multiple server ● Clustering ● Multiplatform ● Parallel ● Testing ● SSH Authentication
  • 19. SSH + Bash Power + Python = Rocks**3 = Fabric
  • 21. django integration from fabric.contrib import django
 django.settings_module(‘myproject.settings') from django.conf import settings def dump_production_database():
 run(pg_dump -U %s -w %s > /bck/prod-db.sql' % (
 settings.DATABASE_USER,
 settings.DATABASE_NAME
 ))
  • 22. fab deploy @hosts('user@example.com') def deploy():
 with cd("/opt/myproject"):
 run("git pull")
 run("django-admin.py collectstatic --noinput")
 run("django-admin.py migrate --noinput")
 run("/etc/init.d/uwsgi stop || echo 'done'")
 run("/etc/init.d/uwsgi start")
  • 23. fab backup_and_publish @task @hosts('www-data@example.com') def backup_and_publish():
 
 run('''tar cjvf /var/wwwbackups/www.%s.tar.bz2 --exclude=/var/www/download —exclude=/var/www/backup* /var/www''' % today().strftime("%Y%m%d%H%M%S"))
 
 run('rsync -avz --checksum --ignore-times /var/wwwstage/ /var/www') #--delete
  • 24. fab static_generation @task def static_generation():
 execute(remote_generation)
 
 local("wget --user=admin --password=rootme --recursive --page-requisites --html- extension --convert-links --restrict-file-names=windows --domains example.com -- no-parent http://wwwstage.example.com/ -o dump.log || echo 'Looking for 404 on wwwstage.example.com'")
 
 local("cat dump.log | grep -B 2 '404 Not Found' | grep 'http:// wwwstage.example.com/' || echo 'OK no 404 found...'")
  • 25. fab upload_release_note:2.10.0 @task @hosts('install@example.com') def upload_release_note(version):
 release_note_file_name = "RELEASE_NOTE_%s.TXT" % version
 with open(release_note_file_name,"w") as out_file:
 notes = jira.Query().render(version=version)
 out_file.write(notes.encode('ascii', 'ignore'))
 out_file.close()
 put(release_note_file_name, "/cygdrive/d/%s/" % version)
  • 26. fab cleanup_nexus:10.0.2-RC2 @task def cleanup_nexus(version):
 for module in [
 "core-api",
 "core-client-rest",
 "core-manual",
 "core-web"]: 
 local("curl -X DELETE -u user:rootme http://nexus.example.com: 8180/nexus/service/local/repositories/releases/content/example/%s/ %s/" % (module, version))
  • 27. LOCK_FILE = “~/.lockfile.release.core.lock" class Lock():
 def __enter__(self):
 if os.access(os.path.expanduser(LOCK_FILE), os.F_OK):
 pidfile = open(os.path.expanduser(LOCK_FILE), "r")
 pidfile.seek(0)
 old_pid = pidfile.readline()
 print "There is an already a process running with pid: %s," % old_pid
 sys.exit(1)
 
 pidfile = open(os.path.expanduser(LOCK_FILE), "w")
 pidfile.write("%s" % os.getpid())
 pidfile.close
 
 def __exit__(self, type, value, traceback):
 os.remove(os.path.expanduser(LOCK_FILE)) Locks
  • 28. fab send_email_candidate:2.12,me@... @task def send_mail_candidate(version, *receivers):
 sender = 'development@geniusbytes.com'
 
 body = """From: Core Team <noreply@example.com>To: Development <development@example.com>Subject: New Release CANDIDATE %(version)snNew Release CANDIDATE %(version)savailable on: * smb://example.com/myproject/% (version)s """ % dict(version=version)
 try:
 message = smtplib.SMTP('example.com')
 message.sendmail(sender, receivers, body)
 print "Successfully sent email"
 except smtplib.SMTPException:
 print "Error: unable to send email"
  • 29. XML parser @task def get_pom_version():
 src=os.path.dirname(__file__)
 pom_file=os.path.abspath(os.path.join(src, 'pom.xml'))
 from xml.dom.minidom import parse
 pom = parse(pom_file)
 version = pom.getElementsByTagName("version")[1].firstChild.nodeValue
 find = re.compile(r'^d+.d+.d+-([a-zA-Z-]+)d*-SNAPSHOT$').findall(version)
 if not find:
 abort(version + " is not a valid development version")
 versions = re.compile(r'd+').findall(version)
 if len(versions) is 3:
 versions.append(1)
 if len(versions) is not 4:
 abort(version + " is not a valid development version")
 versions.extend(find)
 return versions
  • 30. fab sed_poms_version:2.13 @task def sed_poms_version(new_version):
 major, minor, patch, rev, rc = get_pom_version() 
 version = "%s.%s.%s-%s%s-SNAPSHOT" % (major, minor, patch, rc, rev)
 local("sed -i '' 's@%s@%s@g' pom.xml */pom.xml" % (version, new_version))
  • 31. fab create_manuals:2.10 ACTIVATE="source /home/installer/.sphinx_env/bin/activate"
 
 @hosts('installer@example.com')def create_manuals(version):
 with cd(DEPLOY_DIR + "/myproject"):
 name = "manual-%s-doc" % version
 run("wget http://nexus.example.com:8180/nexus/service/local/repo_groups/public/content/com/ myproject/manual/%s/%s.zip" % (version, name))
 
 with cd(name):
 run(ACTIVATE + "&& make docs")
 run("mv target/en/latex/MyProject*.pdf docs/" % version)
 run("tar cjvf docs/MyCDDS-en-%s.tar.bz2 target/docs/" % version)
 run("scp -r docs install@example.com:/cygdrive/d/%s/docs" % version)
  • 32. fab create_installer:2.10 (innosetup) @hosts('install@example.com')def create_installer(version):
 name = "installer-%s-app" % version
 run("wget http://nexus.geniusbytes.com:8180/nexus/service/local/repo_groups/public/content/ myproject/installer/%s/%s.zip" % (version, name))
 
 with cd(name):
 run("tar xjvf /cygdrive/d/%(version)s/MyCDDS-en-%(version)s.tar.bz2" % dict(version=version))
 
 run(ANT)
 run("mkdir -p /cygdrive/d/%s" % version)
 run("cp build/*.exe /cygdrive/d/%s/" % version)
 run("cp build-update/*.exe /cygdrive/d/%s/" % version)
 
 run("rm -rf %s" % name)
  • 33. fab release_core:master,2.10,2.11 @hosts('installer@ecample.com') def release_core(branch, version, next_version):
 with cd(CORE_DEPLOY_DIR):
 
 run('git clone ssh://i@example.com/srv/git/myproject.git')
 with cd(CORE_DEPLOY_DIR + "/myproject"):
 run("git checkout %s" % branch)
 run("mvn clean install")
 
 run("mvn --batch-mode release:clean release:prepare -DreleaseVersion=%s -DdevelopmentVersion=%s" % (version, next_version))
 run("mvn release:perform")
  • 34. fab release:master def release(branch):
 with Lock():
 major, minor, patch, rev, rc = check_current_version(branch)
 if 'RC' != rc:
 abort("RC not found, not possible release a final version")
 
 version = "%s.%s.%s" % (major, minor, patch)
 next_version = "%s.%s.%s-RC%s-SNAPSHOT" % (major, minor, int(patch)+1, 1)
 
 puts("preparing to release %s (next will be %s)" % (version, next_version))
 execute(release_core, branch, version, next_version)
 execute(create_manuals, version)
 execute(create_installer, version)
 execute(upload_release_note, version)
 execute(send_mail_final_release, version, 'me@ex.com', 'dev@ex.com')
 local("git pull")
 execute(labels.missing_translations, 'me@ex.com')
  • 36. EC2 Testing with 200 micro server EC2 + Fabric + Funkload ● EC2 use all ubuntu standard AMI ● Fabric as remote control, move files, aggregate. ● Funkload in order to stress an internet application. (not on EC2)
  • 38. Testing phases I. Prepare Monitoring II.Prepare Cloud 1. Start Monitoring 2. Start Parallel Testing 3. Collecting Test Results 4. Collecting Perf Results 5. Reporting Target Cloud CTRL Tester Target Target FunkLoa d Fabric (nmon+pefmon) Fabric + EC2 Fabric + EC2
  • 39. Testing Console fab prepare_monitoring fab prepare_cloud fab start_monitoring fab start_testing:ciccio,100,5000 fab collecting_test_results:ciccio fab collecting_perf_results:ciccio fab reporting:ciccio