Skip to content. | Skip to navigation

Personal tools
Sections
You are here: Home Topics tutorials
Navigation
 

tutorials

Dec 06, 2011

SSH tips and tricks: how to save time configuring properly SSH

by Alessandro Pisa — last modified Dec 06, 2011 04:35 PM
Filed Under:

This blog post is about ssh client configuration. Configuring ssh is a really good practice both for saving time and keeping organized your connections data. Even though the blogosphere is full of posts like this, I think it is worth repeating because the practice of keeping an up to date ssh configuration is not so diffused.

In my daily activity I find myself connecting to a lot of servers and it is hard to remember for each of them the correct hostname or IP and the related credentials.

To speed up my work I try to keep has much as possible updated my .ssh/config file.

Let's say, for example that one of our clients, let's say ACME :), gives us access to a fictitious server with the IP address 999.999.999.999. 

They give us the access that server with the username bugs and ssh is listen to port 2222.

As soon as I am authorized to connect to a new server I insert a new section to the file like this:

# The new acme server
Host acme
HostName 999.999.999.999
Port 2222
User bugs

 This way instead of typing:

ssh -p2222 bugs@999.999.999.999

I can just type:

ssh acme

with the same effects.

The benefits of that go beyond the use of ssh, because the same configuration file has effect on other ssh related programs like scp, rsync and sshfs.

In addition .ssh/config is parsed by bash completion scripts so I can save further keystrokes (holy laziness)!

This is good, more than for today, for tomorrow because time passes and I can forget the username, the server IP or the port, but I would hardly forget I worked for ACME and to get those info quickly reading .ssh/config is enough.

Of course I can add many hosts sections to the .ssh/config like I am showing in this example:

## List of ACME servers ##
# The staging server
Host acme-staging
HostName staging.example.com
User bugs
# The production server
Host acme-production
HostName production.example.com
User bunny

## Another customer ##
Host demo
HostName 10.0.1.100
User donald

# I can also setup a tunnel to a port
Host demo-debug
HostName 10.0.1.100
User root
LocalForward 8080 localhost:8080

As you can see each section starts with the Host declaration and the settings are effective only for that specific Host.

In the last example we make a tunnel forwarding the 8080 port to localhost, useful in case the server firewall filters direct connections from outside.

With this configuration the command:

ssh demo-debug

is equivalent to:

ssh root@10.0.1.100 -L 8080:localhost:8080

 

Further readings

Beyond the nice manual page about ssh configuration:

man ssh_config

you could find very useful those links to

A note to KDE users

I found out that also sftp and fish KIO slaves are aware of ssh configuration, with the difference that fish overrides the User directive, i.e., using the example before, to connect to the acme server as bugs I have to point dolphin to either fish://bugs@acme or to sftp://acme

.

 

Nov 18, 2011

Modulistica PDF online: popolamento automatico via Python

by Federica D'Elia — last modified Nov 18, 2011 05:00 PM

Un suggerimento per aggiungere testo a un file pdf comune, come ad esempio un banale modulo del censimento, utilizzando alcune delle librerie Python in circolazione

La creazione di pdf è spesso richiesta quando si sviluppa un'applicazione. Ma ci dobbiamo destreggiare in un mare di librerie Python

Per lo sviluppo di un'applicazione mi sono trovata a dover generare un pdf il cui contenuto consiste in un modulo, ad esempio il modulo del censimento, compilato con i dati degli utenti dell'applicazione presi run-time dal sistema.

Avrei impiegato troppo tempo a disegnare il modulo insieme ai dati dell'utente, in più, per certi moduli (come il modulo censimento) sono già forniti i pdf.

Pensare di caricare il modulo come immagine di sfondo non è fattibile. Prima di tutto per la qualità scarsa del pdf finale e poi perché le dimensioni del file di output aumentano molto a causa dell'immagine usata come sfondo.

Il file da ottenere è un modulo già fornito in versione pdf, ma a cui ho bisogno di aggiungere testo.

La soluzione, a mio avviso migliore, è stata quella di usare ReportLab per disegnare un pdf fatto unicamente dei dati dell'utente per poi fare un merge del primo con il pdf contente il modulo, usando PyPDF.

L'unica difficoltà in questo approccio è creare il pdf contenente i dati di riempimento. Infatti questi dati devono essere nella posizione giusta, prioprio come se stessimo compilando il modulo.

La soluzione è: merge e righello alla mano

Per superare questo ostacolo agilmente ho usato uno screen ruler. Io ho preferito "Free Ruler" per Mac OS X tra i vari righelli che ho trovato in rete, soprattutto per il suo tick mark interattivo che permette di fare una misura abbastanza accurata.

Ho aperto il pdf con il modulo da compilare, e poi ho misurato con il righello i punti in cui inserire i dati. Per creare il pdf con i dati di riempimento ho usato ReportLab che consente di scrivere stringhe di testo in un punto esatto, utilizzando le coordinate x e y.

Ecco la MIA ricetta

Passo 1

Aprire il pdf che rappresenta la base del nostro impasto, ovvero  il modulo da compilare, usando la classe PdfFileReader di pyPdf.

import codecs
from pyPdf import PdfFileWriter, PdfFileReader

input1 = PdfFileReader(codecs.open(path_modello_censimento, "rb"))

 

Passo 2

Preparare il pdf con i nostri canditi: i dati di riempimento. Qui entra in gioco ReportLab.

import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm

packet = StringIO.StringIO()
can = canvas.Canvas(packet)
...
textobject = can.beginText()
textobject.setTextOrigin( 11.94*cm, 20.12*cm)
textobject.textLine('hello world')
...
can.drawText(textobject)
can.showPage()
can.save()
packet.seek(0)

Come unità ho usato i centrimenti, sia nel fissare l'origine di ogni striga di testo inserita, sia quando ho misurato con il righello. 11.94 e 20.12 sono due esempi di coordinate.

Tenere presente che l'orgine si trova in basso a sinistra. Ma con l'istruzione seguente possiamo spostare l'orgine in alto.

can.translate(cm, cm)

 

Passo 3

Aprire il pdf creato sopra con PdfFileReader.

input2 = PdfFileReader(packet)

 

Passo 4

Aprire il pdf finale, che conterrà il merge dei due pdf precedenti con la classe PdfFileWriter di pyPdf.

output = PdfFileWriter()

 

Passo 5

Adesso la parte più divertente: "Impastare".

page0 = input1.getPage(0)
page0.mergePage(input2.getPage(0))
output.addPage(page0)

Dopo aver unito i due pdf pagina per pagina si arriva finalment al punto 6..

Passo 6

Adesso abbiamo il nostra risultato finale "output" che può essere memorizzato ovunque si voglia, io lo scrivo in un file temporaneo per completare l'esempio:

import tempfile
temp_file_name = tempfile.mktemp()
outputStream = codecs.open(temp_file_name, mode="wb")
output.write(outputStream)
outputStream.close()
os.unlink(temp_file_name)

 

L'elaborazione richiede un po' di tempo, ma il risultato finale è buono. Buon appetito!

May 06, 2011

Varnish purge after article rate

by Andrew Mleczko — last modified May 06, 2011 10:04 AM

For one of the projects we are using a very aggressive Varnish configuration. We are caching also html (not for long but still) for anonymous users. It could be a problem if you have some dynamical features - like rating. 

But not any more. Using this simple vcl add-on you can purge article view after making a vote:

sub vcl_recv {
...
   if (req.http.Cookie && req.http.Cookie ~ "statusmessages=") { 
       purge("req.url ~ " req.url);
       pass;
   }
...
}

 

It simply checks if you have a statusmessages cookie in request (after rating an article Plone is displaying confirmation status message) and purge current url from cache. Simple, clean and it works!

Apr 12, 2011

Plone and Pyramid talk proposed for EuroPython

by Andrew Mleczko — last modified Apr 12, 2011 04:22 PM

I have proposed a talk "How to build complex web applications having fun?" for this year's EuroPython.

This year, EuroPython is in Florence, Italy, which is ca. 140km from where I live now. It couldn't get easier to attend and propose a talk:

Web development is a complexity challenge nowadays. Growing number of functionalities results in customer expectations increase which makes project design more difficult. Using proper tools that suite your customer needs is essential.

In this talk I would like to present two successful stories using closely together Pyramid and Plone. Basing on these examples I wished to highlight the main reasons for using Plone as a CMS only and letting Pyramid do the rest (vertical application). Moreover, I will underscore good and bad practices during integration process and how to make farsighted architectural decisions in a right moment.

This year, everyone who has bought EuroPython ticket can vote. So If you have one and you'd like to see this talk, vote for it directly from abstract page.

Mar 17, 2011

Munin timeout

by Andrew Mleczko — last modified Mar 17, 2011 03:53 PM
Filed Under:

I had recently problems with one of munin plugins - it disappear from munin graphs. In my munin-node.log I have a lot of:

[21134] Service 'temperature' timed out.


How to change munin timeout value? There is nothing about it in munin documentation. But if you look into source code you will find that it exists. Adding:

timeout 60


to munin-node.conf or your plugin specific configuration does the tick!

Jun 01, 2010

Sorrento Sprint Summary - collective.amberjack progress report

by Andrew Mleczko — last modified Jun 01, 2010 11:56 AM

RedTurtle is participating each year in Sorrento's Plone sprints. We were there also last week. It was an amazing time of brainstorming and coding. I will try to make a summary of what we have archived.

Symposium

We have started collective.amberjack presence in Sorrento with Massimo's presentation at the European Plone Symposium

 


Sprint

Then we had two sprinting days. We have started day one with brainstorming. We had three objectives/questions:

  • collective.amberjack sandbox
  • refactoring the code - how to simplify collective.amberjack tour definition and registration
  • translations - how to manage tour/steps translations

thanks to a fruitful discussion (garbas, dukebody, gborelli, miziodel, shywolf9982, sorry if I forgot your name ;-) we have right now answers to all of our dilemmas.


SanDbox

First idea of having a sandbox for collective.amberjack came up at last Plone Conference in Budapest. We have collected a lot of ideas for different use cases. We have had also some internal brainstorms in RedTurtle about it. Finally after confronting all the concepts - during Sorrento brainstorming - we will have a simple solution which should satisfy most of the users:

  • simple Plone site deployment (like demo.plone.org)
  • open registration for all users
  • collective.amberjack preinstalled and ready to use
  • user will try-out Plone using amberjack in his member folder
  • nightly restart with fresh Data.fs


Code refactoring

We have started refactoring collective.amberjack. There are 3 areas of interests: javascript, tour definition and tour registration. Luca was doing a great job trying to simplify javascript part. He also prepare a good startup for future enhancements. I was refactoring tour part. We have decided to use a 

configuration baseD tour definition,

which looks like that:

[amberjack]
steps = 
        0_create-a-new-folder
        1_fill-out-the-fields
        2_publish-the-folder
        3_all-done
title = Add and publish a Folder

[0_create-a-new-folder]
blueprint = collective.amberjack.blueprints.step
title = Create a new folder
url = /
text = Folders are one of ....
validators = 
        python: isManager
        python: isNotFolderCreated
microsteps = 
        0_0_microstep
        0_1_microstep
        0_2_microstep

[0_0_microstep]
blueprint = collective.amberjack.blueprints.microstep
description = If you don't want to perform the ...
automatically done by your browser.

[0_1_microstep]
blueprint = collective.amberjack.blueprints.microstep
idstep = menu_add-new
description = Click the [Add new...] drop-down menu.

[0_2_microstep]
blueprint = collective.amberjack.blueprints.microstep
idstep = new_folder
description = Select [Folder] from the menu.

This concept is well known across the community. I hope it will be also more human readable comparing to python dictionary ;-). We have a working version in the trunk. For new tours we have also 

new tour registration 

- comparing to old approach (registration only using ZCML) you can now use also TTW registration. Other important change is that tour doesn't need to be a python package any more. Because it's a simple .cfg file right now you can simply zip it into an archive (zip, tar) and register it. We have a working implementation for web source and local file system registration (which you can find in the trunk). Archive file can be shipped with multiple tours and with


translationS

which right now are still just a concept that need to be implemented. We would like to make a use of i18ndude tool but because it was designed for ZPT this could be a wrong approach. Overall idea is to keep all the files (tour and the translations) together, something like:

- mytours.zip
  |- tour1.cfg
  |- tour1_en.po
  |- tour1_it.po
  |- tour1.pot
  |- tour2.cfg
  |- tour2_en.po
  ...

 

Fixing bugs

Mirco and Federica were working together and did an enormous job fixing most of the 1.1a release bugs. Thanks to Rob we have solved also some TinyMCE problems that we have had. We have still some open issues, like 'new portlet creation' tour that need some attention so we still need your help!


What's next?

The current development focus is on 1.1 release, which includes:

  • new tour definition (python dictionary based tour will still work until 1.2)
  • new tour registration (old registration will still work until 1.2)
  • finish translation implementation
  • fix last bugs
  • deploy sandbox probably on demo.plone.org
  • collective.amberjack.windmill - which should become default interface for creating and editing tours; we have right now something more then just proof of concept:

May 31, 2010

Sorrento Sprint: collective.amberjack

by Massimo Azzolini — last modified May 31, 2010 03:30 PM

Come ogni anno da 4 anni abbiamo partecipato al Sorrento Sprint. Quest'anno abbiamo deciso di andare in forze (8 persone) allo scopo di portare avanti lo sviluppo di amberjack di cui ci siamo presi carico nei confronti della comunità.

Gli obiettivi

Abbiamo una milestone da raggiungere: quella del rilascio della versione 1.1a. Questa comprendeva:

  • la risoluzione di alcuni bug o problemi di interfaccia
  • il refactoring del codice javascript
  • il brainstorming su come evolvere il sistema

Abbiamo risolto i bug, introdotti ulteriori miglioramenti all'interfaccia e rifattorizzata buona parte del codice javacript. Rimane qualcosa da finire, nel complesso è stato un successo. 

Inoltre, sono stati introdotti cambiamenti strutturali alla definizione del tour.

Luca, Federica, Mirco ed Andrew hanno fatto un gran lavoro.

Il punto focale però è stato il confronto con la comunità. Avevamo preso alcune decisioni che ci è sembrato opportuno sottoporre al vaglio dei presenti e abbiamo ottenuto ottimi suggerimenti e conferme sulla strada intrapresa.

Windmill

Windmill diventerà l'interfaccia principale di creazione di un tour. E' il modo più semplice per crearlo, aggiornarlo, tradurlo. E' di enorme efficacia sia per un end-user in quanto servirà poco addestramento che per uno sviluppatore che potrà creare al tempo stesso un tutorial per i suoi add-on e un test funzionale che verifichi che l'introduzione di modifiche non inficino il comportamento generale del sistema.

Questa conferma ha portato ad alcune riflessioni e variazioni di indirizzo.

formato dei tour

Il formato cambia. Non più complessi dizionari scritti in python, ma file di configurazione altamente leggibili. qualcosa del tipo:

[amberjack]
steps = 
        0_create-a-new-folder
        1_fill-out-the-fields
        2_publish-the-folder
        3_all-done
title = Add and publish a Folder


[0_create-a-new-folder]
blueprint = collective.amberjack.blueprints.step
title = Create a new folder
url = /
text = Folders are one of ....
validators = 
        python: isManager
        python: isNotFolderCreated
microsteps = 
        0_0_microstep
        0_1_microstep
        0_2_microstep


[0_0_microstep]
blueprint = collective.amberjack.blueprints.microstep
description = If you don't want to perform the ...
automatically done by your browser.


[0_1_microstep]
blueprint = collective.amberjack.blueprints.microstep
idstep = menu_add-new
description = Click the [Add new...] drop-down menu.


[0_2_microstep]
blueprint = collective.amberjack.blueprints.microstep
idstep = new_folder
description = Select [Folder] from the menu.

Sarà ovviamente possibile salvare i tour, in questo nuovo formato, direttamente dall'interfaccia di Windmill.

Ovviamente è necessario avere un sistema di conversione dei vecchi tour: è stata creata l'utility "tour_converter" (in collective.amberjack.core) che migra vecchi dict-based tour in nuovi cfg-based tour.

I tour saranno quindi semplici file. Questo significa che la sorgente da cui verranno "pescati" non sarà più un package scaricabile da pypi, ma potrà essere salvato in locale, messo su un server condiviso, scaricato da sorgenti eterogenee (svn, http server, ftp, ecc.). Ovviamente abbiamo una registrazione "classica" via zcml oppure una più "cool" via pannello di controllo di plone.

E' già pronta e funzionante una versione experimental che funziona con questo nuovo approccio e i 12 plonetour sono stati già convertiti e pronti per l'uso.

Un discorso a parte per le traduzioni: dobbiamo reimplementare il meccanismo in quanto ora non abbiamo più file .py. Contiamo di definire una modalità di traduzione simile alla precedente, ma in qualche modo occorrerà effettuare qualche variazione al sistema di generazione dei file .po.

sandbox

Il brainstorming pre-serale in giardino è stato molto utile anche in questo caso. 

L'idea che ne è scaturita è quella di fornire un folder personale dedicato ai tour all'interno del quale l'utente abbia tutti i diritti necessari per poterli eseguire completamente. Questo copre il 90% delle situazione secondo le previsioni della maggior parte dei presenti.

Con questa sandbox 1.0 si potrà già creare un "demo.plone.org": chiunque potrà provare Plone senza doverlo scaricare.

Inoltre è semplice per ogni sviluppatore di add-on montare un'istanza in cui includere il proprio tour ed eventualmente richiedere alla foundation il dominio: "demo.myaddon.plone.org"

Assolutamente semplice sarà fornire un sistema che ogni notte ripristini il portale ad una situazione "pulita".

Non sembra interessare, almeno in questa fase, un sistema che automaticamente crei un'istanza on-the-fly che permetta all'utente di provare plone in completa autonomia. quel 10% di target-user possono tranquillamente utilizzare un comodo UnifiedInstaller

May 17, 2010

rilasciato collective.amberjack 1.0

by Massimo Azzolini — last modified May 17, 2010 08:45 AM

Questa è la prima versione per Plone 4

abbiamo un team di supporto!

Dalla 1.0x RedTurtle ha deciso di supportare il progetto. 

Le attività non saranno più semplicemente volontaristiche e nel tempo libero, ma schedulate nel tempo, supportate e seguite in modo professionale.

Questo non significa che collective.amberjack sta diventando un progetto aziendale, ma semplicemente che avremo un team che ne porterà avanti lo sviluppo.

Il team, oltre a me, è composto da Mirco Angelini, Federica D'Elia, Andrew Mleczko e Luca Fabbri. All'ultimo sprint a Ferrara abbiamo avuto il supporto di Jacopo Deyla e il ritorno di Giacomo Spettoli (tra i primi contributori) entrambi della Regione Emilia Romagna.

Ora, sei ancora di più il benvenuto se vorrai partecipare allo sviluppo, supportare l'iniziativa o semplicemente utilizzare il sistema. Il tuo contributo sarà ancora più utile ora che qualcuno lo porterà avanti sistematicamente.

what's new? 

Questa prima release 1.0x supporta completamente Plone 4:

  • i 12 tour sono stati completamente rivisti
  • è stato introdotto il supporto per TinyMCE
  • abbiamo un piano di battaglia

what next?

Dicevo di un piano di battaglia. Il piano prevede che al prossimo sprint a Sorrento si concludano le operazioni che ci porteranno ad una versione 1.1 rifattorizzate e ulteriormente migliorata. 

Nel frattempo predisporremo una serie di step che ci porteranno ad avere un sistema più solido, usabile e soprattutto estensibile.

Contiamo di introdurre Windmill come tool di creazione di tour via web. I primi tentativi sono molto promettenti. Andrea Benetti sta portando avanti la parte di studio che verrà integrata successivamente in collective.amberjack.

Dove puoi seguire il progetto?

Se sei interessato a partecipare, i posti dove ci incontriamo sono questi:

  • launchpad, per la gestione del progetto (blueprint, bug, ecc.)
  • coactivate, ci è utile per documentare il tutto attraverso il suo wiki e per gestire la mailing list
  • il codice è tutto rilasciato su collective.

Se, viceversa, vuoi utilizzare il sistema, pypi è il tuo amico:

collective.amberjack 1.0 released

by Massimo Azzolini — last modified May 17, 2010 08:45 AM

This is the first plone 4 compliant release

we have a support team!

Starting from 1.0 release, RedTurtle decided to support the project providing a 4 person team.

Activities won't be no more based on a voluntary participation and in the spare time. They are going to be supported and scheduled in a more stable way.

It doesn't mean that collective.amberjack is going to be company branded - quite the contrary - it means that we have a stable team that is going to enhance and mantain the tool.

Except me, the team contains: Mirco Angelini, Federica D'Elia, Luca Fabbri e Andrew Mleczko. During the last Ferrara' sprint, we were glad to have Jacopo Deyla's contribution and the Giacomo Spettoli's return (former contributor) both of them from Regione Emilia Romagna.

You are even more then welcome to participate in the development, in supporting the initiative or just in using and testing the tool. Your contribution will be more useful since, from now, there will be someone that will take care of it.

WHAT'S NEW? 

This 1.0 release supports Plone 4:

  • the 12 tours has been completely revised
  • the TinyMCE support has been added
  • we have a battle plan

WHAT NEXT?

I talked about a roadmap. It assumes that during next Sorrento sprint we'll complete the tasks that will refactore the code and improved 1.1 release.

In the meanwhile we're going to schedule a set of steps that move collective.amberjack in a more solid, usable and mostly, extensible tool.

We are also confident to introduce Windmill as the TTW tool for creating tutorials. Andrea Benetti from University of Ferrara is starting to extend it. Then we'll integrate it into a collective.amberjack.windmill package.

how could you get involved inTO the project?

If you are interested in contribution, the places where we meet are these:

  • launchpad, for the project management (blueprints, bugs, etc.)
  • coactivate, extremely useful for documentation through its wiki and for the mailing lists
  • the code is obviously release on collective.

Otherwise, if you just want to use the system, pypi is your friend:

May 04, 2010

New collective.funkload releases

by Andrew Mleczko — last modified May 04, 2010 03:40 PM

I have recently released a new version of collective.funkload and collective.recipe.funkload. There is one major improvment - funkload recorder is now working properly with collective.funkload scripts.

Here @RedTurtle we are heavily using funkload for acceptance and benchmarking tests. We have started using it in 2008 just after Bristol Performance Sprint. We have found even more useful with buildout recipe. The only missing part was the recorder. It's built-in Funkload itself, but it was not enabled in the recipe. Well - now it is ;-)

/ If you want to know how to include funkload in buildout project - check my previous blog /

Starting a recorder is quite easy:

$ ./bin/funkload record -p 8080 MyTest


for full usage call:

$ ./bin/funkload record --help


This will start proxy on 8080 port and save all your browser requests to MyTest funkload scenario. Now open your browser, change proxy configuration to localhost:8080 and click-through test case. When you finish - stop the proxy with Ctrl-C. Funkload will generate a test_MyTest.py file and notify you where you can find it. It should be now collective.funkload compatible - you can lunch:

$ ./bin/funkload test /path/to/test_MyTest.py


To test it.

Another small improvement is a PloneFLTestCase. It extends default funkload test case, implementing two additional methods helping with Plone content creation. Right now instead of using this approach:

folder_portal_factory = self._browse(server_url + "/coreloadtests/Members/" + self.user_id +"/createObject?type_name=Folder",
                                             method='get', 
                                             follow_redirect=False,
                                             description = 'Get folder portal factory')

folder_edit_url = folder_portal_factory.headers.get('Location')        
folder_id = folder_edit_url.split('/')[-2]

folder_created = self.post(folder_edit_url, params=[
    ['id', folder_id],
    ['title', 'folder'],
    ['description', ''],
    ['description_text_format', 'text/plain'],
    ['subject_existing_keywords:default:list', ''],
    ['last_referer', 'http://localhost:8080/coreloadtests/Members/' + self.user_id + '/view'],
    ['form_submit', 'Save']],
    description="Post /coreloadtests/Members/user...280843853/atct_edit")

new_folder_id = folder_created.url.split('/')[-2]

 

you can just do:

new_folder_id = self.addContent(
        server_url, 
        portal_type='Folder', 
        params=[['id', 'id'],
                ['title', 'testing title'],
                ['description', 'testing description'],
                ['description_text_format', 'text/plain'],
                ['form.submitted', '1'],
                ['last_referer', ''],
                ['form_submit', 'Save']], 
        description='Create folder')

 

It doesn't do much, but for sure it helps you keep you test case readable.