Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Wednesday, July 10, 2013

Execute complex Python or Ruby code inline within Bash

A lot of times when we write extensive shell code, using pipes, file descriptors etc, we eventually run into the limitations of shell and are forced to write an external helper to keep the whole pipe ninja thing moving forward. Well, what if I said you didn't have to?

Update: cannot be used with set -e

read -r -d '' VAR <<'EOF'
import sys,re
state = sys.stdin.read().rstrip('\n')
g = re.match('^([\w-]+)(\s[\w+\/]+)(, \w+ \d+)?',state).groups()
# if the last field exists, it's running
if g[-1] is not None:
  print 'running'
else:
  print 'stopped'
EOF

Upstart does lots of things right, except status, I mean...


tty2 start/running, process 738
udevtrigger stop/waiting
That's just not right, requiring a regular expression to get status. So I created this little snippet. read takes the heredoc and shoves it into VAR and then, it's no different than it having been in a file to begin with.

# initctl list
...

tty3 start/running, process 740
udev-finish stop/waiting
juju-daq-emitter-0 start/running, process 12022
hostname stop/waiting
mountall-reboot stop/waiting
mountall-shell stop/waiting
mounted-tmp stop/waiting



root@ip-10-147-220-141:~# initctl status tty3 | python -c "$VAR"
running
root@ip-10-147-220-141:~# initctl status udev-finish | python -c "$VAR"
stopped
root@ip-10-147-220-141:~# initctl status hostname | python -c "$VAR"
stopped
Much better.

Tuesday, June 18, 2013

Automating and encrypting duplicity backups using cron

Background

Having suffered data loss in the past and hacking on storage suggests that it's a good idea to have regular backups. I wanted redundancy in case my local server failed and I wanted to encrypt my backups using a password protected gpg key. The current solution uses a passphrase kept in plain text outside of the backup path. I plan to investigate moving the gpg key to a smartcard and using a pin key to unlock it instead. If anyone has any additional solutions please describe them in detail.

Persisting requisite environmental variables

Running anything from cron detaches it from your current environment, you lose all of the variables describing things like your ssh-agent gpg-agent, stuff you need to begin to communicate with the remote server. I took a simple approach, in my ~.bashrc I created the following.
cat > ~/.backenvrc << EOF
# used by crontab backup script
export SSH_AGENT_PID=$SSH_AGENT_PID
export SSH_AUTH_SOCK=$SSH_AUTH_SOCK
export GPG_AGENT_INFO=$GPG_AGENT_INFO
export GPGKEY=XXX-insert-your-gpg-key-here-XXX
EOF
and simply source this from the backup script referenced in my crontab, I merely need only login once to populate this file.

Setting up the Crontab

# crontab -l
# m h  dom mon dow   command
MAILTO=ppetraki@localhost
BACKUP=/home/ppetraki/Documents/System/Backup
#
0 0  * * *      /usr/bin/crontab -l  > $BACKUP/crontab-backup
0 0  * * *      /usr/bin/dpkg --get-selections > $BACKUP/installed-software
0 0  * * *      /usr/local/bin/ppetraki-backup.sh inc
0 0  * * Fri    /usr/local/bin/ppetraki-backup.sh full
Note that I am also backing up my crontab and my list of installed software, eventually I will move this into another script that also does things like
  1. backup my bookmarks from chrome and firefox
  2. backup mail in a non-binary format
The current cron format performs an incremental backup every night and a full backup every Friday.

Driver script

This wraps the invocation of duplicity and acquires the necessary environmental variables. Duplicity itself can be hairy with all the command line switches and even more of a burden if you have multiple targets. I have redundant backups, first to a local server and to a remote service provided by rsync.net (great customer support!). I found horcrux to be a wonderful, lightweight, duplicity wrapper to suit my needs. The driver script, which is external to my backup path, also contains my GPG passphrase to encrypt my backups. Eventually I wish to move to a smartcard driven system illustrated here
#!/bin/bash
# [/usr/local/bin/ppetraki-backup.sh]

export PATH=$PATH:/usr/local/bin
action=$1

export USER=XXX
export HOME=/home/$USER

source $HOME/.backenvrc

echo "verifying environment"
echo "gpg-agent: ${GPG_AGENT_INFO}"
echo "gpg-key:   ${GPGKEY}"
echo "ssh-agent-pid:   ${SSH_AGENT_PID}"
echo "ssh-auth-sock:   ${SSH_AUTH_SOCK}"

if [ -z $action ]; then
  echo "requires an action!"
  exit 1
fi

export PASSPHRASE=

[ -z $PASSPHRASE ] && exit 1

echo "begin"

for config in local_backup remote_backup
do
  horcrux clean   $config
  horcrux $action $config
done

Using horcrux to wrangle duplicity

Horcrux has the notion of profiles that takes all the complexity out of managing the duplicity CLI. Here's an example of a profile.
cat /home/ppetraki/.horcrux/local_backup-config
destination_path="rsync://192.168.1.XXX/backups/personal"
 cat ~/.horcrux/local_backup-exclude
- /home/ppetraki/Sandbox
- /home/ppetraki/Bugs
- /home/ppetraki/Downloads
- /home/ppetraki/Videos
- /home/ppetraki/.xsession-errors
- /home/ppetraki/.thumbnails
- /home/ppetraki/.local
- /home/ppetraki/.gvfs
- /home/ppetraki/.systemtap
- /home/ppetraki/.adobe/Flash_Player/AssetCache
- /home/ppetraki/.thunderbird
- /home/ppetraki/.mozilla
- /home/ppetraki/.config/google-googletalkplugin
- /home/ppetraki/.config/google-chrome
- /home/ppetraki/.cache
- /home/ppetraki/**[cC]ache*
I found it problematic to backup only sub directories of things like mozilla and google-chrome, instead I will write an additional script to cherry pick those files for backup. The main horcrux config file
cat ~/.horcrux/horcrux.conf 
source="/home/ppetraki/"          # Ensure trailing slash
encrypt_key=XXXXXX     # Public key ID to encrypt backups with
sign_key='-'             # Key ID to sign backups with (leave as '-' for no signing)

use_agent=false          # Use gpg-agent?
remove_n=3               # Number of full filesets to remove
verbosity=5              # Logs all the file changes (see duplicity man page)
vol_size=25              # Split the backup into 25MB volumes
full_if_old=30D         # Cause 'full' operation to perform a full
                         # backup if older than 360 days
backup_basename='backup' # Directory name for local backups (i.e., destination
                         # /Volumes/my_drive/backup/ or /media/my_drive/backup/)
dup_params='--use-agent' # Parameters to pass to Duplicity
This is great as it reduces a backup invocation to this:
 $ horcrux inc local_backup 

Monitoring

I defined MAILTO in my crontab and also installed mutt and the reconfigured postfix for local mail delivery. Every night I get a progress report on how the backups ran.

Conclusion

I've spent quite a bit of time determining how to automate this in and provide strong encryption. If you have a more secure way to encrypt the backups I would be happy to hear it.

Thursday, June 13, 2013

Determine machine size in juju programitcally

I wouldn't call this easy, but it works, and it keeps me out of python.
# on hpcloud

$juju status apache2 2>/dev/null | grep instance-id |
  awk '{split($0,array,":")} END{print array[2]}' | tr -d ' ' |
  xargs nova show | grep flavor |
  awk '{split($0,array,"|")} END{print array[3]}' | tr -d ' '

standard.xsmall

Friday, May 24, 2013

Zapping stale kernel images on Ubuntu

Spring cleaning time, I wanted to keep my current kernel and the one just installed by a recent upgrade. That argument could have been simplified by using $(uname -r)
dpkg -l | grep linux-image | egrep -v '3.2.0-4(3|4)-generic' | grep -v linux-image-generic | awk '{print $2}' | xargs apt-get remove -y

and the results

...
0 upgraded, 0 newly installed, 25 to remove and 0 not upgraded.
After this operation, 7,807 MB disk space will be freed.

Monday, April 1, 2013

Simple yet effective PDF content editing utility

Ever come across a PDF that you normally would print out and then fill in the form by hand? Well, there's a hard to find tool called flpsed that will edit any pdf and allow you put text anywhere you want it.
$ sudo apt-get install flpsed
$ flpsed foo.pdf

Position the cursor by mouse and just start typing. If you don't like the position you can use the arrow keys for fine movements or grab it with the mouse. It doesn't have the most attractive user interface but who cares, it delivers.

You can also save the modified pdf.

Creative uses include printing something as a pdf like a "html print form" and leveraging the medium with tools like flpsed.

Thursday, October 11, 2012

enabling modeline support in vim

If you ever wondered why
# vim:ts=4:sw=4:et:
Doesn't work by default is because it's been disabled at the distribution level for security reasons. To get around this add this snippet to your local vimrc or system wide if you're feeling bold.
if exists("+modelines") 
     " the following is required because of SuSE's paranoid /etc/vimrc 
     " and to force 'modeline' on even for root in Vim 7.0.237 and later 
     set modeline modelines=5 
     " the following disables a dangerous modeline in one helpfile 
     if has ('autocmd') 
         au BufReadPost ada.txt setl nomodeline ft=help 
     endif 
endif

crash utility dminfo extension hacking

I had done this a long time ago while triage of multipath based core dumps were a regular occurrence for me. Some of the extra plugins for crash are way out of date and require access to private data structures to reconstitute the view of the subsystem. Here's an example of porting the dminfo plugin for use with Linux 2.6.32.

https://code.launchpad.net/~peter-petrakis/ubuntu/oneiric/crash/dminfo-update

and the diffs

What I would like to do someday is figure out how to "mount" sysfs from crash context and use the device model to obtain these data structures in a deterministic manner. That would make these sort of plugins much more robust.

Thursday, September 27, 2012

Ubuntu PDF merge one liner

These are always the best

$ gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=output_file.pdf  `ls -x *pdf | sort`

The ls -x incantation ensures everything is on one line to be feed to gs. This really handy when scanning multipage documents so if it jams along the way your entire pdf isn't lost.