Archive for category Programming

Gitorious and Fully Qualified Domain Names (FQDN)

When you want to install your own version of gitorious, a lot of people seem to run into issues where they don’t have a real DNS name for their servers. This breaks the session code of gitorious.

I just ran a ‘git diff’ on my gitorious tree, and here are the changes I made to make it work:


diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb
index 7384f93..2409810 100644
--- a/config/initializers/session_store.rb
+++ b/config/initializers/session_store.rb
@@ -8,7 +8,8 @@ gitorious_yaml = YAML::load_file(File.join(Rails.root, "config/gitorious.yml"))[
 ActionController::Base.session = {
   :key    => '_gitorious_sess',
   :secret => gitorious_yaml['cookie_secret'],
-  :domain => ".#{gitorious_yaml["gitorious_host"]}",
+#  :domain => ".#{gitorious_yaml["gitorious_host"]}",
+  :domain => "10.80.21.73",
   :expire_after => 3.weeks,
 }

And also:

diff --git a/app/models/repository.rb b/app/models/repository.rb
index c4fd612..1df689c 100644
--- a/app/models/repository.rb
+++ b/app/models/repository.rb
@@ -226,7 +226,7 @@ class Repository < ActiveRecord::Base
   end

   def http_clone_url
-    "http://git.#{GitoriousConfig['gitorious_host']}/#{gitdir}"
+    "http://#{GitoriousConfig['gitorious_host']}/#{gitdir}"
   end

   def http_cloning?

If you change 10.80.21.73 to whatever your ip is, all of your troubles should go away.

Tags: , , ,

Automatically Backup Blogs / Websites to Amazon S3

I maintain several personal websites, and felt they should be backed up in case my Xen host has issues.

Step 1

Create an Amazon S3 account at http://aws.amazon.com/s3/.  Once your account is created, you will need to create ‘credentials’, which will allow us to authenticate with S3.  You can access this by going to the “Amazon -> Account -> AWS Identity and Access Management” then clicking ‘Security Credentials’ on the left, and then creating a ‘Access Key’.  These keys are composed of 2 parts: a public portion, called the ‘Access Key ID’, and a private portion (never to be shared) called the ‘Secret Access Key’.

Amazon Security Credentials

Step 2

We need to install a program called ‘s3cmd’.  This will allow us to interface with Amazon S3 via the command line.  On Ubuntu:

sudo apt-get install s3cmd

Step 3

Now we need to setup s3cmd to save settings about our setup.  Make sure you have the Access Key ID and the Secret Key.  Run the following command to get started:

s3cmd --configure

From here you will get an interactive prompt:

Enter new values or accept defaults in brackets with Enter.
Refer to user manual for detailed description of all options.

Access key and Secret key are your identifiers for Amazon S3
Access Key: 231231232
Secret Key: 213123123

Encryption password is used to protect your files from reading
by unauthorized persons while in transfer to S3
Encryption password: ubuntu
Path to GPG program [/usr/bin/gpg]: 

When using secure HTTPS protocol all communication with Amazon S3
servers is protected from 3rd party eavesdropping. This method is
slower than plain HTTP and can't be used if you're behind a proxy
Use HTTPS protocol [No]: yes

New settings:
  Access Key: 231231232
  Secret Key: 213123123
  Encryption password: ubuntu
  Path to GPG program: /usr/bin/gpg
  Use HTTPS protocol: True
  HTTP Proxy server name:
  HTTP Proxy server port: 0

Test access with supplied credentials? [Y/n]

I chose to pick “Use HTTPS protocol”, which will upload it via a secure method. This is a good idea, although will slightly impact performance and may use slightly more traffic. In addition, s3cmd also will encrypt the files using gpg, which means that if someone broke into your s3 account, they would still need that pass phrase to decrypt your data.

Step 4
We can now test s3cmd and try to upload a file. You will need to create a ‘bucket’, which is where our files for this project are stored. You can have many buckets, so if you want to separate your projects you could create additional ones for each one. When we make a bucket name, they are globally visible in S3, so you will want to pick something not likely to be taken:

s3cmd mb s3://sharms.org-wordpress-blog

If that command runs successfully, we now have a new bucket called ‘sharms.org-wordpress-blog’. If not, pick a different name and try again. Now we can test uploading a file:

s3cmd put /home/sharms/testfile.txt s3://sharms.org-wordpress-blog

# Verify its where we think it is
s3cmd ls s3://sharms.org-wordpress-blog

Step 5
Using bash, we can automate this, and backup all of our files, daily, weekly, monthly etc. Here is an example, which I put at ‘/usr/local/bin/backup_blog_to_s3.sh’:

bucket="s3://sharms.org-wordpress-blog"

logger -t backup_blog_to_s3.sh "Backing up sharms.org blog to S3"
cd /var/www
tar -cf sharms.org.tar blog
bzip2 -9 sharms.org.tar
s3cmd put sharms.org.tar.bz2 ${bucket}
rm /var/www/sharms.org.tar.bz2

logger -t backup_blog_to_s3.sh "Backing up MySQL database to S3"
mysqldump sharms-wordpress -u databaseuser -p databasepassword -a -r sharms-wordpress.sql
bzip2 -9 sharms-wordpress.sql
s3cmd put sharms-wordpress.sql.bz2 ${bucket}
rm sharms-wordpress.sql.bz2

You can see from the example that we backup all of the files in the ‘blog’ directory, and export all of our data out of a MySQL database. You can even change the file names so they have the date when they were backed up:

tar -cf sharms.org-wordpress-$(date +%d%m%y) blog

Running Automatically
If we wanted to backup the system every day, this is very easy:

sudo cp /usr/local/bin/backup_blog_to_s3.sh /etc/cron.daily
sudo chmod 755 /etc/cron.daily

Security Notes
When considering this setup, you are most vulnerable to someone obtaining access to your server, and getting your Amazon keys. You can always revoke them from the Amazon Webservices Control Panel, but you don’t want an attacker using your S3 account for nefarious means. Beyond the scope of this document, you could setup a user called ‘backups’, and make the file ‘~backups/.s3cmd’ with the permissions ’600′, to stop other users from looking at it’s contents.

On Why Open Source Developers Run Mac OS X

A common trend among many of the best developers is to see them posting screenshots running OS X. Many of the best developers, some my personal ‘developer heroes’, have made the switch to OS X.

It’s All About the Mentality
I respect and admire programmers like @migueldeicaza, @mitsuhiko, mandrake, @dhh for all they have accomplished. One thing they all have in common, present day, is running OS X. Mandrake cowrote Enlightenment (which is the original really cool window manager for Linux), Miguel started Gnome, and the majority of code both Mitsuhiko (wrote almost every useful Python library ever) and DHH (Ruby on Rails) write run on Linux backends to say the least.

What are they most known for? Problem solving skills mixed with actually producing / releasing.

Linux is Open Source
And this, I believe, is why great developers tend to move towards OS X (yes, there are plenty of exceptions). A critical piece of writing software is focus. When a problem solver uses a Linux desktop, they are immediately confronted with the possibility of being able to modify every part of their system. When a problem solver runs OS X, their options are severely limited, by design.

I think all of us are guilty for hunting down PPAs to get a backported browser, or running ‘./configure && make && make install’ at some point. And when you have programming skills, source code can turn into a detriment to productivity when you start modifying projects outside of what you intended to accomplish. All of a sudden you start hacking a project for a few minutes, and wake up days later in a coding haze with all of that time lost.

Personally I have had experience with this while using old Linux distributions. We have SLES 9 systems and SLES 10 systems here at work, and in the past year I have spent countless hours hacking Sprint 3G wireless drivers, USB over IP, Firefox 3 and countless others to work on these older systems. Why? Not because they are the primary goal, but because I could, which in turn took up time from things I actually “wanted” to do.

Time is Valuable
Watching one of Miguel’s presentations, he mentions that he does not have enough years left to “worry about memory management” and that they leave that to the younger folks. This is the crux of the argument. For programmers, there is far too much opportunity for distraction at every avenue. We don’t know how long we will be here for, but certainly we know that nothing we care about will get done as long as our focus is spread so thin across the spectrum of Linux.

Summary
This is all just food for thought, not a judgement against any form of desktop or usage pattern. For reference, I am still running Ubuntu on my desktop, and being wildly unproductive on the tasks I want to finish.

Tags: , ,

Programming using IOCTL to interface with Linux kernel drivers

IOCTL is a function call that allows you to interface with kernel drivers, allowing you to adjust settings or set parameters from code without compiling a new module.

From a programming perspective, having the linux kernel source is a prerequisite. In this example, I cloned the main kernel:

git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git linux

Once I had the source, I specifically wanted to see exactly how I could interface with the driver called usblp. I was using a USB to parallel port converter, and wanted to see if there was any way to force it to operate differently as we needed a non-printer device to work with it.

After opening the kernel source, I found the driver file itself which was under /drivers/usb/class/usblp.c. In this file I found a section of information about which IOCTLs it supported, and put them in a header file for my program called usblp-hack.h:

#ifndef USBLP_HACK_H
#define USBLP_HACK_H

#include <linux/ioctl.h>

/* ioctls: */
#define IOCNR_GET_DEVICE_ID     1
#define IOCNR_GET_PROTOCOLS     2
#define IOCNR_SET_PROTOCOL      3
#define IOCNR_HP_SET_CHANNEL        4
#define IOCNR_GET_BUS_ADDRESS       5
#define IOCNR_GET_VID_PID       6
#define IOCNR_SOFT_RESET        7
/* Get device_id string: */
#define LPIOC_GET_DEVICE_ID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_DEVICE_ID, len)
/* The following ioctls were added for http://hpoj.sourceforge.net: */
/* Get two-int array:
 * [0]=current protocol (1=7/1/1, 2=7/1/2, 3=7/1/3),
 * [1]=supported protocol mask (mask&(1<<n)!=0 means 7/1/n supported): */
#define LPIOC_GET_PROTOCOLS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_PROTOCOLS, len)
/* Set protocol (arg: 1=7/1/1, 2=7/1/2, 3=7/1/3): */
#define LPIOC_SET_PROTOCOL _IOC(_IOC_WRITE, 'P', IOCNR_SET_PROTOCOL, 0)
/* Set channel number (HP Vendor-specific command): */
#define LPIOC_HP_SET_CHANNEL _IOC(_IOC_WRITE, 'P', IOCNR_HP_SET_CHANNEL, 0)
/* Get two-int array: [0]=bus number, [1]=device address: */
#define LPIOC_GET_BUS_ADDRESS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_BUS_ADDRESS, len)
/* Get two-int array: [0]=vendor ID, [1]=product ID: */
#define LPIOC_GET_VID_PID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_VID_PID, len)
/* Perform class specific soft reset */
#define LPIOC_SOFT_RESET _IOC(_IOC_NONE, 'P', IOCNR_SOFT_RESET, 0)
#endif

There are plenty of hints on usage here, and I was able to grab a little more info after searching for some of those defines in google code search. Using these IOCTLs I wanted to know exactly which modes the USB to parallel converter supported, and try to set it in mode 3, which I hoped would give me more options for talking to the device.

Here is my usblp-hack.c which was able to probe and update these settings, although in my case mode 3 didn’t work, but shows an example of exactly how to do it:

#include "usblp-hack.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>		/* open */
#include <unistd.h>		/* exit */
#include <sys/ioctl.h>		/* ioctl */

main()
{
	int fd;
	int twoints[2];

	fd = open("/dev/usblp0", O_RDONLY | O_NONBLOCK);
	if (fd < 0) {
		printf("Cannot open device.\n");
		exit(-1);
	}

	if(ioctl(fd, LPIOC_GET_PROTOCOLS(sizeof(int[2])), &twoints) >= 0)
		printf("Great success: %d / %d\n", twoints[0], twoints[1]);
	else {
		printf("Fail!\n");
		exit(-1);
	}

	if(ioctl(fd, LPIOC_SET_PROTOCOL, 2) >= 0)
		printf("set protocol to version 2\n");
	else {
		printf("Fail!\n");
		exit(-1);
	}

	if(ioctl(fd, LPIOC_GET_PROTOCOLS(sizeof(int[2])), &twoints) >= 0)
		printf("Great success: %d / %d\n", twoints[0], twoints[1]);
	else {
		printf("Fail!\n");
		exit(-1);
	}

	if(ioctl(fd, LPIOC_SOFT_RESET) >= 0)
	{
		printf("Success reset device\n");
	} else {
		printf("Could not reset device\n");
		exit(-1);
	}

	close(fd);
	exit(0);
}

You can compile the above example just using gcc:

gcc -o usblp-hack usblp-hack.c

You can see in the example above I was able to probe the device to see what mode it was currently in and supports (LPIOC_GET_PROTOCOLS), attempt to set the device mode (LPIOC_SET_PROTOCOL), and soft reset the device (LPIOC_SOFT_RESET).

So in the end, nothing here too complex or mind blowing, but if you are just getting your feet wet it might take you a minute to dig this sort of information up.

Java

It has always been trendy to make fun of Java, and wax poetic about how superior someone’s language of choice is. The fact of the matter is, whether or not you wish to acknowledge it, more users run Java applications on Linux than any other language1.

In the past few years, I have had the opportunity to code multiple enterprise web applications in any language I chose. I made a few in Symfony (php), Django (python), and recently I used Play (java). All of them were fantastic frameworks and languages in their own respect (the only thing people make fun of more than Java is PHP, again generally baseless).

I have used vim for as long as I can remember, but for the Play project I switched over to Eclipse, and that was also a great IDE. A lot of nice features where it would automated a lot of typing, and I found managing multiple files slightly easier.

Point being the language and the tools around it are there, well tested, and ready for prime time. Given the right coder, they are just as effective as any of the trendy languages, and to dismiss that based on outright false statements on most comment threads is absurd.

Performance: Java in no way, in any application I wrote, was limited by the language or jvm in performance. This is generally affected entirely by the coder, not the language.

Adoption: Java is all over my business, and is the clear leader in the enterprise technology stack2

Tools: Tools for Java are abundant, feature rich, and more than adequate to develop complex projects

Criticisms: The only valid criticism is that Java apps are slow to load up initially, for user apps. I think with the innovation we see with respect to JVM performance improvements (JIT compilation etc)3 continuously make that point not even legitimate, but clearly you can make applications load slowly. With that in mind, I have the ability to write a C app that loads slow also.

This post more than anything is to encourage breaking the mold of the group think, “None of us is as dumb as all of us” mentality. No matter how many points you get on reddit for a snarky comment, those points won’t pay your bills, nor give you respect among legitimate coders.

  1. http://www.electronista.com/articles/10/05/26/admob.april.2010.study.has.android.near.even/ []
  2. http://www.forrester.com/rb/Research/of_strategic_languages%2C_javas_adoption_is_highest/q/id/37356/t/2 []
  3. http://www.h-online.com/open/news/item/Android-s-Dalvik-to-be-JIT-boosted-861870.html []

Tags: ,

Pygoocanvas, pygtk etc

I was reading a post about PyGoocanvas, and decided to take a look at some code and see what fun could be had. I haven’t done much yet, but this screenshot of it is pretty entertaining in it’s own right:

A thousand passwords

In this day and age of the internet, we have more content and interaction than ever before. This access generally comes with a price: everything requires a username and password. How does a mere mortal remember their credentials to login to thousands of websites? More importantly, I am not always on the same computer, how do I access my passwords from all of them?

The long term solution would be to see 100% adoption of OpenID. Inevitably many sites will always be behind the curve, so until that day comes, I recommend Revelation.

Revelation is an easy to use, secure and lightweight password manager for Linux. It is written in GTK so those running the GNOME desktop (the default for Ubuntu) will be right at home. You can have several different folders to help organize your passwords, and define actions based on the type of password being stored.

A picture is worth a thousand words, so here is a screenshot of Revelation in action:
revelation

What makes this great is that all of your passwords are stored encrypted. This means if someone takes your computer, without your master password your passwords would be useless. This also means we can store our password using Ubuntu One or Dropbox.

If you are curious about Dropbox I wrote a post with screenshots showing exactly how it works. Simply save your Revelation password file there, and all of your systems that have Dropbox will now have access to those passwords (once you unlock it for that session of course).

Under the preferences window in Revelation you can also adjust your default password size (when you use Revelation you simply randomly generate a new password for each website) for as long as you need, with the longer the better.

If you are running Ubuntu, you can install Revelation by clicking Applications -> Ubuntu Software Center and searching for Revelation. If you would prefer the command line version:

# sudo apt-get install revelation

There are many alternatives out there, but if you are running Linux and just need a simple, no-hassle password manager Revelation is worth five minutes to try it out.

Tags: , ,

Installing Play Framework on OpenBSD 4.6

OpenBSD
OpenBSD is a free, reliable and secure operating system. From a configuration standpoint it is both minimal and simple, which is great for those who want to get started quickly. For the purposes of this tutorial, it is assumed the user has already installed OpenBSD. If not, check out openbsd101.com for guides on installation etc.

Play Framework
The Play Framework is a java based web programming system, that includes the enterprise features of java with the methodology of Ruby on Rails or Django. You can view an introductory screencast at their website which shows just how easy and powerful it is.

Allow your user to sudo
Since this blog is aggregated on many Ubuntu sites, we will use the sudo facility to run commands instead of root. To enable sudo the same way Ubuntu does:

  1. su – # Get root
  2. visudo
  3. Uncomment the line “%wheel ALL=(ALL) SETENV: ALL”

Install packages
For the play framework the launch scripts are in python. Zsh is installed for a better shell, and vim is installed for a full featured editor.

export PKG_PATH=ftp://ftp.openbsd.org/pub/OpenBSD/4.6/packages/i386/
sudo pkg_add zsh jre-1.7.0.00b59p0 wget python-2.6.2p0 vim-7.2.190p1-no_x11 unzip
sudo ln -sf /usr/local/bin/python2.6 /usr/bin/python
sudo ln -sf /usr/local/bin/python2.6-config /usr/bin/python-config
sudo ln -sf /usr/local/bin/pydoc2.6  /usr/bin/pydoc

Install Play Framework

cd /usr/local
sudo wget http://download.playframework.org/releases/play-1.0.zip
sudo unzip play-1.0.zip

Start your project

cd /var
sudo /usr/local/play-1.0/play new ourappname
sudo chown -R ourusername ourappname
cd ourappname
# Set java home -- you can set this permanently in /etc/login.conf or in a startup script
export JAVA_HOME="/usr/local/jre-1.7.0/"
/usr/local/play-1.0/play run

Done
Your test app is now listening on port 9000 of the systems IP. That is all there is to it. Make sure to check out the excellent documentation available for the Play Framework.

play

Tags: , ,