<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Segmentation Fault! &#187; Shell Scripting</title>
	<atom:link href="http://www.segmentationfault.es/category/programacion/shell-scripting/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.segmentationfault.es</link>
	<description>La formulación de un problema es más importante que su solución.</description>
	<lastBuildDate>Tue, 29 Jun 2010 19:45:33 +0000</lastBuildDate>
	<language>es</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>How to backup your server to Amazon S3</title>
		<link>http://www.segmentationfault.es/2010/06/how-to-backup-your-server-to-amazon-s3/</link>
		<comments>http://www.segmentationfault.es/2010/06/how-to-backup-your-server-to-amazon-s3/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 19:39:27 +0000</pubDate>
		<dc:creator>Christopher Vallés</dc:creator>
				<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[7z]]></category>
		<category><![CDATA[amazon s3]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[s3cmd]]></category>

		<guid isPermaLink="false">http://www.segmentationfault.es/?p=1725</guid>
		<description><![CDATA[This post is a HowTo about backups to Amazon S3 using some tools like 7z, s3cmd and a couple of bash scripts.]]></description>
			<content:encoded><![CDATA[<p>Since a few months ago I&#8217;m taking care of three ubuntu servers with different services like svn, mysql, websites, etc. and for sure I want to provide a flexible, secure and cheap backup system to my customers.</p>
<p>I started playing around with <a href="http://s3tools.org/s3cmd" target="_blank">s3cmd</a> command line utility and I realize that is really powerful so, I decide to write my own scripts to be able to backup automatically all the important files of my servers to the cheaper and easy to use <a href="http://aws.amazon.com/s3/" target="_blank">Amazon S3</a> service.</p>
<p>The whole system is based on two bash scripts, the crontab and a few extra applications like <a href="http://p7zip.sourceforge.net/" target="_blank">7zip</a> and s3cmd. I will explain step by step how I build up the system and at the end I&#8217;ll provide the full code of the scripts.</p>
<h4>Requirements</h4>
<p>The first step is to be sure that you have installed the 7zip and s3cmd tools, in my case I&#8217;m using ubuntu so, for me the command to install the tools is:</p>
<pre class="brush: bash;">
sudo apt-get install p7zip s3cmd
</pre>
<h4>Basic setup</h4>
<p>Now we can follow with the basic setup, I created a folder in the root of the filesystem called backups, the inside this folder I create serveral folders, at the end the structure is like follow:</p>
<pre class="brush: bash;">
/backups
    /compressed
    /data
        /db
        /svn
        /www
    /scripts
</pre>
<p>The compressed folder is used at the end of the script to compress all the files to one .7z file, in the data folder we will copy the information we want to backup and in the scripts folder we will store as it&#8217;s name says the two scripts we will use.</p>
<h4>Backup script</h4>
<p>Now, let&#8217;s have a look at those scripts. The first one is to do the backup, in my case I&#8217;m doing a backup of the subversion, mysql and files under /var/www.</p>
<p>The script starts with the following block:</p>
<pre class="brush: bash;">
echo `date '+%F %T'`: Starting the backup

#Dumping the repos
echo `date '+%F %T'`: Starting the dump of the repos
for i in /user/local/svn/*/; do
    repo=`basename $i`
    echo `date '+%F %T'`: Dumping repo $repo
    /usr/bin/svnadmin dump /usr/local/svn/$repo &gt; /backups/data/svn/$repo.dump
    echo `date '+%F %T'`: Repo $repo dumped
done
</pre>
<p>We suppose that the svn folder is located at /usr/local/svn, basically here we are going through each folder inside /usr/local/svn/ and we call svnadmin dump to dump that repository in one file, that file is stored in /backups/data/svn/.</p>
<pre class="brush: bash;">
#Dumping the DB
echo `date '+%F %T'`: Starting the dump of the DataBases
for i in /var/lib/mysql/*/; do
    db=`basename $i`
    echo `date '+%F %T'`: Dumping DB $db
    /usr/bin/mysqldump -uroot -p$db_password $db &gt; /backups/data/db/$db.sql
    echo `date '+%F %T'`: Database $db dumped
done
</pre>
<p>In this second block we are doing more or less the same thing, we are going through each folder on /var/lib/mysql/ and calling mysqldump to export each DB in one file stored at /backups/data/db/.</p>
<pre class="brush: bash;">
#Copy all the websites
echo `date '+%F %T'`: Starting the dump of websites
for i in /var/www/*/; do
    site=`basename $i`
    echo `date '+%F %T'`: Dumping site $site
    /usr/bin/7z a -mx6 -t7z /backups/data/www/$site.7z -p$compression_password /var/www/$site
    echo `date '+%F %T'`: Site $site dumped
done
</pre>
<p>In the third block we are dumping the websites, I have the websites stored at /var/www folder and each site is inside a folder with the domain as folder name. Basically we are doing the same, loop through /var/www/ and compressing each site individually in a .7z file with a compression level of 6 and secured with a password.<br />
I store each site in a separate file because if I have to restore a site I don&#8217;t need to uncompress all the sites, just the main file and then the compressed site.<br />
I was playing with different compression levels and 6 is the most suitable to maintain a good compression ratio without wasting a lot of time.</p>
<pre class="brush: bash;">
#Compressing all the data
echo `date '+%F %T'`: Compressing the info
filename=$(date +%Y%m%d)
/usr/bin/7z a -mx6 -t7z /backups/compressed/$filename.7z -p$password /backups/data/*
echo `date '+%F %T'`: Info compressed
</pre>
<p>Now with all the information we want to backup in place we will compress all together in one single file, that&#8217;s the purpose of this block of code, the final filename is a timestamp of today using the date command.</p>
<pre class="brush: bash;">
#Upload to Amazon S3
echo `date '+%F %T'`: Uploading to Amazon S3
/usr/bin/s3cmd put --no-progress /backups/compressed/$filename.7z s3://BUCKET_NAME/$filename.7z
echo `date '+%F %T'`: Upload completed
</pre>
<p>Ok, we have the compressed file and one of the final steps is upload this file to Amazon S3. For that task we are using the s3cmd tool passing the parameter &#8211;no-progress to avoid an &#8220;interactive&#8221; output of the upload status.</p>
<pre class="brush: bash;">
#Delete the local backups
echo `date '+%F %T'`: Cleaning up
rm -Rf /backups/data/svn/*
rm -Rf /backups/data/db/*
rm -Rf /backups/data/www/*
rm -Rf /backups/compressed/*
echo `date '+%F %T'`: Clean completed
echo `date '+%F %T'`: Backup completed
</pre>
<p>And the final block of code is just a clean up, after the upload to amazon we delete all the files we have generated inside the /backups folder.</p>
<p>Ok, seems complex but is pretty strightforward, also if you take a look you&#8217;ll see that all the messages contains a timestamp, with that information we are able to determine how many time we spend in each task.<br />
One disadvantage of this script is that we are not checking if the file was uploaded correctly to Amazon, maybe this will be a future improvement.</p>
<h4>Maintenance script</h4>
<p>Now let&#8217;s take a look at the other script, the purpose is just delete old backups based on a timestamp, in my case we&#8217;re storing the backups for one month, it&#8217;s very affordable with the Amazon prices. </p>
<pre class="brush: bash;">
for filename in `s3cmd ls s3://$bucket`; do
    if [[ $filename =~ ([0-9]*)\.7z ]]; then
        timestamp=${BASH_REMATCH[1]}
        echo `date '+%F %T'` - Reading metadata of: $filename
        echo -e &quot;\tFilename: $filename&quot;
        echo -e &quot;\tTimestamp: $timestamp&quot;
        if [[ $timestamp -le $limit ]]; then
            let &quot;total=total+1&quot;
            echo -e &quot;\tResult: Backup deleted\n&quot;
            /usr/bin/s3cmd del $filename
        else
            echo -e &quot;\tResult: Backup keeped\n&quot;
        fi
    fi
done
</pre>
<p>This is the only code block we have in the maintenance script, the idea is to retrieve the list of files we have in the bucket with s3cmd, then we check if the gived part contains the pattern ([0-9]*)\.7z (because the command s3cmd ls gives more information rather than just the filenames).<br />
If we detect a segment that matches the regex we get the filename without the extension (the timestamp of the backup), and we check in this case if the timestamp is older than one month (the timestamp of one month ago is stored in the $limit variable). If the backup is older we remove it calling the s3cmd del command.</p>
<p>If you need to store the files more time just change the $limit variable and that&#8217;s it.</p>
<p>Wow, seems a large process, ok, now let&#8217;s have a look at the last step to let this work, the cronjobs.<br />
I created to cronjobs and redirected the output of them to the stdout because I want to receive an email after the backup, my crontab look like this:</p>
<pre class="brush: bash;">
# m h  dom mon dow   command
MAILTO=YOUR_EMAIL_ADDRESS_HERE
00 22 * * * /backups/scripts/s3backup 2&gt;&amp;1
00 23 * * * /backups/scripts/s3backup-maintenance 2&gt;&amp;1
</pre>
<p>Just put there the values you want to run the crons and don&#8217;t forget to put at the end 2>&#038;1.</p>
<h4>Conclusion</h4>
<p>With this system you&#8217;ll have your backups in a safe and cheap place without headaches and with a full report in you email every time the script runs. For sure these scripts can be impoved with a few checks and you can extend it to fit your needs.<br />
I hope you have enjoyed this HowTo and begin to use this scripts! For sure improvements are welcomed, don&#8217;t hesitate to comment!.</p>
<h4>Source code</h4>
<p>Grab the full source code of the <a href="http://pastie.textmate.org/1023939" target="_blank">backup script</a> and the <a href="http://pastie.textmate.org/1023947" target="_blank">maintenance script</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.segmentationfault.es/2010/06/how-to-backup-your-server-to-amazon-s3/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Instalador automatizado de CodeIgniter</title>
		<link>http://www.segmentationfault.es/2009/05/instalador-codeigniter/</link>
		<comments>http://www.segmentationfault.es/2009/05/instalador-codeigniter/#comments</comments>
		<pubDate>Sat, 16 May 2009 08:50:05 +0000</pubDate>
		<dc:creator>Christopher Vallés</dc:creator>
				<category><![CDATA[Programación]]></category>
		<category><![CDATA[Shell Scripting]]></category>
		<category><![CDATA[Trucos]]></category>
		<category><![CDATA[CodeIgniter]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.segmentationfault.es/?p=893</guid>
		<description><![CDATA[Todos estos días de sequía tienen un motivo... A parte de mejorar el blog para permitir multiples autores en un post, Gabi y yo hemos estado desarrollando una herramienta que para muchos programadores les será un alivio de trabajo importante. Todos los que usamos el framework CodeIgniter sabemos que hay que modificar el .htaccess, crear las carpetas auxiliares que necesitamos, instalar el TinyMCE, bajar prototype y scriptaculous y demás.]]></description>
			<content:encoded><![CDATA[<p>Todos estos días de sequía tienen un motivo&#8230; A parte de mejorar el blog para permitir multiples autores en un post, Gabi y yo hemos estado desarrollando una herramienta que para muchos programadores les será un alivio de trabajo importante. Todos los que usamos el framework CodeIgniter sabemos que hay que modificar el .htaccess, crear las carpetas auxiliares que necesitamos, instalar el TinyMCE, bajar prototype y scriptaculous y demás.</p>
<p>Hemos creado una herramienta, que en su versión beta funciona por terminal, que nos va a ayudar en este proceso, básicamente las funciones que realiza son:</p>
<ol>
<li>Descarga e instala la última versión de CodeIgniter desde la página oficial.</li>
<li>Aplica el parche de idioma en castellano a CodeIgniter.</li>
<li>Descargar e instala la última versión del editor WYSISYG TinyMCE desde la página oficial.</li>
<li>Instala también la versión comprimida del editor TinyMCE.</li>
<li>Descarga la última versión de Prototype desde la página oficial.</li>
<li>Descarga la última versión de Script.aculo.us desde la página oficial.</li>
<li>Crea el fichero robots.txt con el contenido por defecto para los bots de búsquedas.</li>
<li>Crea la carpeta css.</li>
<li>Crea la carpeta img.</li>
<li>Crea la carpeta js.</li>
<li>Crea la carpeta swf.</li>
<li>Crea el fichero .htaccess con las directivas necesarias para que funcione CodeIgniter con mod_rewrite y permite el acceso a todas las carpetas creadas.</li>
</ol>
<p>Las características que esperamos tener en la versión estable a parte de las existentes son:</p>
<ol>
<li>Selección del idioma a instalar con CodeIgniter.</li>
<li>TinyMCE, Prototype y Script.aculo.us pasarán a ser instalaciónes opcionales (podremos escogerlo en el momento de la instalación).</li>
<li>En caso de instalar TinyMCE podremos escoger el idioma que queremos instalar así como la versión, estándar o comprimida.</li>
<li>Posibilidad de nombrar a las carpetas de imágenes, css, js y swf de la manera que nosotros queramos (se decide en el momento de la instalación).</li>
<li>Integración en el propio sistema operativo (Solo para Linux y MacOS de momento), es decir desde el terminal escribiremos <em><strong>installci</strong></em> y automáticamente se ejecutará el script.</li>
<li>Integración con el Finder de MacOS.</li>
</ol>
<p>Para ejecutar el script hay que crear una carpeta dónde vamos a ir metiendo nuestros ficheros, copiar ahí el script <em><strong>installci.sh</strong></em> otorgar permisos con <em><strong>chmod 777 ./installci.sh</strong></em> y ejecutar dicho script con <em><strong>./installci.sh</strong></em>.</p>
<p>De momento y hasta que esté disponible la versión estable aquí os dejamos el enlace para <a href="http://www.segmentationfault.es/wp-content/2009/05/installci.zip">descargar la versión beta</a>. Esperamos vuestras sugerencias y opiniones en los comentarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.segmentationfault.es/2009/05/instalador-codeigniter/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
<!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->