systemd, lircd, mceusb, xbmc and Arch Linux

After migrating my Arch based media center to systemd, my IR mceusb remote stopped working with lircd.

I needed to do the following steps in order to make it function again.

1. Copy /usr/lib/systemd/system/lirc.service to /etc/systemd/system/lirc.service (service files in /etc/systemd/system always takes precedence to files located in /usr/lib/systemd/system).

2. Edit /etc/systemd/system/lirc.service accordingly:

[Unit]
Description=Linux Infrared Remote Control

[Service]
EnvironmentFile=/etc/conf.d/lircd.conf
ExecStartPre=/usr/bin/ln -sf /dev/lirc0 /dev/lirc
ExecStartPre=/usr/bin/ln -sf /run/lirc/lircd /dev/lircd
ExecStart=/usr/sbin/lircd --pidfile=/run/lirc/lircd.pid
Type=forking
PIDFile=/run/lirc/lircd.pid

[Install]
WantedBy=multi-user.target
diff /etc/systemd/system/lirc.service /usr/lib/systemd/system/lirc.service
5,6d4
< EnvironmentFile=/etc/conf.d/lircd.conf
< ExecStartPre=/usr/bin/ln -sf /dev/lirc0 /dev/lirc

The creation of the symlink to /dev/lirc eliminates lircd errors like this:

could not get file information for /dev/lirc
default_init(): No such file or directory

There may be more “correct” ways of fixing this, but creating the symlink satifies lircd.

3. Now adjust variables in /etc/conf.d/lircd.conf:

LIRC_DEVICE="/dev/lirc0"
LIRC_DRIVER="mceusb"
LIRC_EXTRAOPTS=""
LIRC_CONFIGFILE="/etc/lirc/lircd.conf"

My /etc/lirc/lircd.conf looks like this and works with a mceusb based RC:

#
# brand:                        HP
# model no. of remote control:  TSGH-IR01
# devices being controlled by this remote: HP Slimline S3100y
#
# RC-6 config file
#
# source: http://home.hccnet.nl/m.majoor/projects_remote_control.htm
#         http://home.hccnet.nl/m.majoor/pronto.pdf
#
# used by: Philips
#
#########
#
# Philips Media Center Edition remote control
# For use with the USB MCE ir receiver
#
# Dan Conti  dconti|acm.wwu.edu
#
# Updated with codes for MCE 2005 Remote additional buttons
# *, #, Teletext, Red, Green, Yellow & Blue Buttons
# Note: TV power button transmits no code until programmed.
# Updated 12th September 2005
# Graham Auld - mce|graham.auld.me.uk
#
# Radio, Print, RecTV are only available on the HP Media Center remote control
#
#
# Updated with codes for MCE 2007 Remote additional buttons
# Visualization, Aspect, SlideShow, Eject
# Note:
# Renamed some buttons: DVD->DVDMenu, More->MoreInfo, Star->Asterisk, Hash->Pound
# Note:
# Blue, Yellow, Green, Red, and Teletext buttons do not exist on the HP remote

begin remote

  name        mceusb
  bits                 16
  flags  RC6|CONST_LENGTH
  eps                  30
  aeps                100

  header       2667   889
  one           444   444
  zero          444   444
  pre_data_bits        21
  pre_data        0x37FF0
  gap              105000
  toggle_bit           22
  rc6_mask    0x100000000


      begin codes

#seen on HP Pavilion dv3t remote  --Tim Mann, 3 Nov 2009
        Media         0x00007b7f
        PlayPause     0x00007b91


#unused by HP remote
        Blue          0x00007ba1
        Yellow        0x00007ba2
        Green         0x00007ba3
        Red           0x00007ba4
        Teletext      0x00007ba5

#ba6 - bae unused
        BA6           0x00007ba6
        BA7           0x00007ba7
        BA8           0x00007ba8
        BA9           0x00007ba9
        BAA           0x00007baa
        BAB           0x00007bab
        BAC           0x00007bac
        BAD           0x00007bad
        BAE           0x00007bae

        Radio         0x00007baf
        Print         0x00007bb1

#bb2 - bb4 unused
        BB2           0x00007bb2
        BB3           0x00007bb3
        BB4           0x00007bb4

        Videos        0x00007bb5
        Pictures      0x00007bb6
        RecTV         0x00007bb7
        Music         0x00007bb8
        TV            0x00007bb9

#bba - bbf unused
        BBA           0x00007bba
        BBB           0x00007bbb
        BBC           0x00007bbc
        BBD           0x00007bbd
        BBE           0x00007bbe
        BBF           0x00007bbf
#bc1 - bca unused
        BC1           0x00007bc1
        BC2           0x00007bc2
        BC3           0x00007bc3
        BC4           0x00007bc4
        BC5           0x00007bc5
        BC6           0x00007bc6
        BC7           0x00007bc7
        BC8           0x00007bc8
        BC9           0x00007bc9
        BCA           0x00007bca

        Eject         0x00007bcb
        SlideShow     0x00007bcc
        Visualization 0x00007bcd

#bce - bcf unused
        BCE           0x00007bce
        BCF           0x00007bcf
#bd1 - bd7 unused
        BD1           0x00007bd1
        BD2           0x00007bd2
        BD3           0x00007bd3
        BD4           0x00007bd4
        BD5           0x00007bd5
        BD6           0x00007bd6
        BD7           0x00007bd7

        Aspect        0x00007bd8
        Guide         0x00007bd9
        LiveTV        0x00007bda
        DVD           0x00007bdb
#NoGap
        Back          0x00007bdc
        OK            0x00007bdd
        Right         0x00007bde
        Left          0x00007bdf
        Down          0x00007be0
        Up            0x00007be1
#NoGap
        Star          0x00007be2
        Hash          0x00007be3
#NoGap
        Replay        0x00007be4
        Skip          0x00007be5
        Stop          0x00007be6
        Pause         0x00007be7
        Record        0x00007be8
        Play          0x00007be9
        Rewind        0x00007bea
        Forward       0x00007beb
#NoGap
        ChanDown      0x00007bec
        ChanUp        0x00007bed
        VolDown       0x00007bee
        VolUp         0x00007bef
#NoGap
        More          0x00007bf0
        Mute          0x00007bf1
        Home          0x00007bf2
        Power         0x00007bf3
#NoGap
        Enter         0x00007bf4
        Clear         0x00007bf5
#NoGap
        Nine          0x00007bf6
        Eight         0x00007bf7
        Seven         0x00007bf8
        Six           0x00007bf9
        Five          0x00007bfa
        Four          0x00007bfb
        Three         0x00007bfc
        Two           0x00007bfd
        One           0x00007bfe
        Zero          0x00007bff
      end codes

end remote
#
# this config file was automatically generated
# using lirc-0.8.4a(default) on Mon Feb 23 23:55:04 2009
#
# contributed by
#
# brand:                       Hauppauge
# model no. of remote control:
# devices being controlled by this remote: PVR-150 Remote (MCE kit)
# SMK dongle 0609:031d
#

begin remote

  name  mceusb_hauppauge
  bits           13
  flags RC6|CONST_LENGTH
  eps            30
  aeps          100

  header       2674   870
  one           455   427
  zero          455   427
  pre_data_bits   24
  pre_data       0x1BFF82
  gap          106288
  min_repeat      1
  toggle_bit_mask 0x8000
  rc6_mask    0x100000000

      begin codes
          TV                       0x1BB9
          Music                    0x1BB8
          Pictures                 0x1BB6
          Videos                   0x1BB5
          Power                    0x1BF3
          Stop                     0x1BE6
          Record                   0x1BE8
          Pause                    0x1BE7
          Play                     0x1BE9
          Rewind                   0x1BEA
          Foward                   0x1BEB
          Replay                   0x1BE4
          Skip                     0x1BE5
          Back                     0x1BDC
          More                     0x1BF0
          Up                       0x1BE1
          Left                     0x1BDF
          Right                    0x1BDE
          OK                       0x1BDD
          Down                     0x1BE0
          VolUp                    0x1BEF
          VolDown                  0x1BEE
          Home                     0x1BF2
          ChanDown                 0x1BED
          ChanUp                   0x1BEC
          Mute                     0x1BF1
          RecTV                    0x1BB7
          Guide                    0x1BD9
          LiveTV                   0x1BDA
          DVD                      0x1BDB
          One                      0x1BFE
          Two                      0x1BFD
          Three                    0x1BFC
          Four                     0x1BFB
          Five                     0x1BFA
          Six                      0x1BF9
          Seven                    0x1BF8
          Eight                    0x1BF7
          Nine                     0x1BF6
          Star                     0x1BE2
          Zero                     0x1BFF
          Hash                     0x1BE3
          Clear                    0x1BF5
          Enter                    0x1BF4
      end codes

end remote


#
# this config file was automatically generated
# using lirc-0.8.4a(default) on Tue Mar 10 19:27:09 2009
#
# contributed by
#
# brand:  SIIG Vista MCE remote
# model no. of remote control:
# devices being controlled by this remote:
#

begin remote

  name  vista_mce
  bits           16
  flags RC6
  eps            30
  aeps          100

  header       2654   889
  one           427   427
  zero          427   427
  pre_data_bits   21
  pre_data       0x37FF0
  gap          69850
  toggle_bit_mask 0x8000
  rc6_mask    0x100000000

      begin codes
          Power                    0xEBF3
          Pictures                 0x6BB6
          Radio                    0xEBAF
          Videos                   0x6BB5
          Music                    0xEBB8
          Rec                      0x6BE8
          Pause                    0xEBE7
          Stop                     0x6BE6
          Skipback                 0xEBE4
          Play                     0x6BE9
          Skipfwd                  0xEBE5
          Rwd                      0x6BEA
          Fwd                      0xEBEB
          Start                    0x6BF2
          Back                     0xEBDC
          More                     0x6BF0
          Volup                    0xEBEF
          Voldown                  0x6BEE
          Chup                     0xEBED
          Chdown                   0x6BEC
          Up                       0xEBE1
          Down                     0x6BE0
          Left                     0xEBDF
          Right                    0x6BDE
          Mute                     0xEBF1
          Rectv                    0x6BB7
          Guide                    0xEBD9
          Livetv                   0x6BDA
          Dvdmenu                  0xEBDB
          1                        0x6BFE
          2                        0xEBFD
          3                        0x6BFC
          4                        0xEBFB
          5                        0x6BFA
          6                        0xEBF9
          7                        0x6BF8
          8                        0xEBF7
          9                        0x6BF6
          *                        0xEBE2
          0                        0x6BFF
          #                        0xEBE3
          Clear                    0x6BF5
          Enter                    0xEBF4
      end codes

end remote

4. Disable lircd conflicting kernel modules by creating a blacklist file /etc/modprobe.d/blacklist_mce.conf containing:

# Disabling kernel modules for mce
install ir_rc6_decoder /bin/false
install rc_rc6_mce /bin/false
install ir_rc5_decoder /bin/false

Reboot or remove these modules using modprobe -r.

5. Reenable lirc.service:

# systemctl reenable lirc.service
# systemctl start lirc.service
# systemctl status lirc.service

Performance reporting with bash, gnuplot and LaTex

In an earlier earlier blog post I demonstrated how to create a simple CPU performance graph using the TiKz LaTeX class. I soon found out that generating graphs for longer periods and for many servers using TiKz took a very long time to compile and I started to look for other solutions – GNUplot with the gnuplottex class proved to be the right solution.

It all starts out by collecting data on the individual servers using the following bash script as a cronjob, which saves the data to a NFS share:

#!/bin/bash
# Sarcopy script by Rasmus Edgar Joergensen 2012.05
sardir=/path/to/nfsshare/sardata/$HOSTNAME
cpudir=$sardir/cpu
iodir=$sardir/io
memdir=$sardir/mem
# Check if host dir has been created, create if not present
if [ ! -d $sardir ]; then
	mkdir -p $sardir/{cpu,mem,io}
fi
saday=$(ls -c /var/log/sa/sa[0-9][0-9] | head -n 1)
sadf -d -- -u $saday | cut -d';' -f3- > $cpudir/$(uname -n)-$(date '+%Y-%m-%d')-cpu.csv
sadf -d -- -r $saday | cut -d';' -f3- > $memdir/$(uname -n)-$(date '+%Y-%m-%d')-mem.csv
sadf -d -- -b $saday | cut -d';' -f3- > $iodir/$(uname -n)-$(date '+%Y-%m-%d')-io.csv

The reason it is run locally on the server is because sar data files are not backwards compatible with earlier versions of sadf and vice-versa.

This cron job runs every day a 23:55 :

# Copy sardata for perf reports - Rasmus 2012.05
55 23 * * * /path/to/script/sarcopy > /dev/null 2>&1

Since I need to create graphs for many servers using SAR data extracted from the servers I created the following template:

% REGJ - 20120113
\documentclass{article}
\usepackage[danish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{palatino}
\pdfcompresslevel=0
\pdfobjcompresslevel=0
\usepackage{fancyhdr}
\usepackage[left=1.5in, right=1in, top=1in, bottom=1in, includefoot, headheight=13.6pt]{geometry}
\setlength{\headheight}{0.6in}
\fancyheadoffset[LE,RO]{1cm}
\fancyhead[L]{Performance plots for SERVERNAME - TIME}% empty left
\fancyhead[R]{ % right
   \includegraphics[height=0.43in]{$HOME/bitmaps/logo.eps}
}
\fancyfoot[L] {\tiny Written by Rasmus Edgar Fink Jørgensen in \LaTeX/bash.}
\usepackage{tikz,pgfplots}
\usepackage{eurosym}
\usepackage{gnuplottex}
\usepgfplotslibrary{dateplot}
\pagestyle{fancy}
\begin{document}
\begin{figure}
\begin{gnuplot}[terminal=epslatex,terminaloptions={color colortext solid size 15.4cm,9.35cm}]
set datafile separator ";"
set ylabel 'CPU/wait time \% used'
set xdata time
set autoscale x
set yrange [0:100]
set timefmt "%Y-%m-%d %H:%M:%S"
set xrange ["DATEMIN":"DATEMAX"]
set style line 11 lc rgb '#808080' lt 1
set border 3 ls 11
set key box opaque vert right top
set tics
set style line 12 lc rgb'#808080' lt 0 lw 1
set grid back ls 12
set style line 1 lc rgb '#F33600' lt 1 lw 2.5 # Orange
set style line 2 lc rgb '#0DF300' lt 1 lw 2.5 # Green
set style line 3 lc rgb '#0005FD' lt 1 lw 2.5 # Blue
plot "/tmp/SERVERNAME-concatcpu.csv" using 1:3 title '\%user' w lines ls 1, '' using 1:5 title '\%sys' w lines ls 2, '' 
using 1:6 title '\%iowait' w lines ls 3
\end{gnuplot}
\end{figure}
\begin{itemize}
\item{user:}
Percentage of CPU utilization that occurred while executing at the user level (application).
\item{iowait:}
Percentage  of  time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
\end{itemize}
\newpage
\begin{figure}
\begin{gnuplot}[terminal=epslatex,terminaloptions={color colortext solid size 15.4cm,9.35cm}]
set datafile separator ";"
set autoscale ymax
set format y "%.f"
set xdata time
#set autoscale x
set ylabel "Mem. in KB"
set timefmt "%Y-%m-%d %H:%M:%S"
set xrange ["DATEMIN":"DATEMAX"]
set style line 11 lc rgb '#808080' lt 1
set border front 3 ls 11
set style line 12 lc rgb'#808080' lt 0 lw 1
set grid back ls 12
set key box opaque vert right top
set style fill
set style line 1 lc rgb '#F33600' lt 1 lw 2.5 # Orange
set style line 2 lc rgb '#0DF300' lt 1 lw 2.5 # Green
set style line 3 lc rgb '#0005FD' lt 1 lw 2.5 # Blue
set style line 4 lc rgb '#9B438E' lt 1 lw 2.5 # Purple
set tics
plot "/tmp/SERVERNAME-concatmem.csv" using 1:3 title 'kbmemused' w filledcurve x1 ls 1, '' using 1:6 title 'kbcached' w 
filledcurve x1 ls 2, '' using 1:2 title 'kbmemfree' ls 3 with filledcurve x1, '' using 1:5 title 'kbbuffers' w filledcur
ve x1 ls 4
\end{gnuplot}
\end{figure}
\begin{itemize}
\item{kbmemused:}
Amount  of used memory in kilobytes. This does not take into account memory used by the kernel itself.
\item{kbcached:}
Amount of memory used to cache data by the kernel in kilobytes.
\item{kbmemfree:}
Amount of free memory available in kilobytes.
\item{kbbuffers:}
Amount of memory used as buffers by the kernel in kilobytes.
\item{Extra info:}
Linux treats unused memory as a wasted resource and so uses as much RAM as it can to cache process/kernel information.
\end{itemize}
\newpage
\begin{figure}
\begin{gnuplot}[terminal=epslatex,terminaloptions={color colortext solid size 15.4cm,9.35cm}]
set datafile separator ";"
set ylabel "Transfers/request /s"
set format y "%.f"
set xdata time
set autoscale x
set yrange [0:*]
set timefmt "%Y-%m-%d %H:%M:%S"
set xrange ["DATEMIN":"DATEMAX"]
set style line 11 lc rgb '#808080' lt 1
set border 3 front ls 11
set key box opaque vert right top
set tics
set style line 12 lc rgb'#808080' lt 0 lw 1
set grid back ls 12
set style line 1 lc rgb '#F33600' lt 1 lw 2.5 # Orange
set style line 2 lc rgb '#0DF300' lt 1 lw 2.5 # Green
set style line 3 lc rgb '#0005FD' lt 1 lw 2.5 # Blue
plot "/tmp/SERVERNAME-concatio.csv" using 1:2 title 'tps' w lines ls 1, '' using 1:2 title 'rtps' w lines ls 2, '' using
 1:3 title 'wtps' w lines ls 3
\end{gnuplot}
\end{figure}
\begin{itemize}
\item{tps:}
Total number of transfers per second that were issued to physical devices.  A  transfer
is  an I/O request to a physical device. Multiple logical requests can be combined into
a single I/O request to the device.  A transfer is of indeterminate size.
\item{rtps:}
Total number of read requests per second issued to physical devices.
\item{wtps:}
Total number of write requests per second issued to physical devices.
\item{bwrtn/s:}
Total amount of data written to devices in blocks per second.
\end{itemize}
\newpage
\begin{figure}
\begin{gnuplot}[terminal=epslatex,terminaloptions={color colortext solid size 15.4cm,9.35cm}]
set datafile separator ";"
set ylabel "Transfers,Blocks /s"
set format y "%.f"
set xdata time
set autoscale x
set yrange [0:*]
set timefmt "%Y-%m-%d %H:%M:%S"
set xrange ["DATEMIN":"DATEMAX"]
set style line 11 lc rgb '#808080' lt 1
set border 3 front ls 11
set key box opaque vert right top
set tics
set style line 12 lc rgb'#808080' lt 0 lw 1
set grid back ls 12
set style line 1 lc rgb '#F33600' lt 1 lw 2.5 # Orange
set style line 2 lc rgb '#0DF300' lt 1 lw 2.5 # Green
plot "/tmp/SERVERNAME-concatio.csv" using 1:5 title 'bread/s' w lines ls 1, '' using 1:6 title 'bwrtn/s' w lines ls 2
\end{gnuplot}
\end{figure}
\begin{itemize}
\item{bread/s:}
Total number of transfers per second that were issued to physical devices.  A  transfer
is  an I/O request to a physical device. Multiple logical requests can be combined into
a single I/O request to the device.  A transfer is of indeterminate size.
\item{bwrtn/s:}
Total amount of data written to devices in blocks per second.
\end{itemize}
\end{document}

This template gets filled out, the data handled and the PDFs compiled by the following script:

#!/bin/bash
basedir=$(pwd)
csvpath=${basedir}/csv
outpath=${basedir}/out
texpath=${basedir}/texfiles
pdfpath=${basedir}/pdfs
datetex=$(date +'%Y-%m')
sarmin="2012-08-01"
sarmax="2012-08-31"
sarserver=$2
srvnamecut=$(echo $sarserver | awk -F"." '{print $1}')sar$(date +'%Y%m%d').tex

# Clean up

rm -f $outpath/*
rm -f $pdfpath/aux/*
rm -f $pdfpath/log/*

sartex() {
                sed -e 's/SERVERNAME/'"$sarserver"'/
                        s/DATEMIN/'"$sarmin"'/
			s/TID/'"$datetex"'/
                        s/DATEMAX/'"$sarmax"'/' $texpath/sarplot.tpl > \
                $outpath/$srvnamecut
}


sargen() {
        # Concatentate sar data
        cat /path/to/csvdata/$customer/linux/$sarserver/cpu/*cpu* > /tmp/$sarserver-concatcpu.csv
        cat /path/to/csvdata/$customer/linux/$sarserver/mem/*mem* > /tmp/$sarserver-concatmem.csv
        cat /path/to/csvdata/$customer/linux/$sarserver/io/*io*  > /tmp/$sarserver-concatio.csv

        sartex

}

case $1 in

-sar)
        sargen
        ;;
*)
        echo "Please specify -sar"
        exit 1

esac

# Generate plot

cd $outpath ; latexmk -f -pdfdvi -e '$latex=q/latex --shell-escape %O %S/' -outdir=$outpath $srvnamecut > /dev/null 2>&1

cp $outpath/*.pdf $pdfpath

Which creates graphs that looks like this:

testservergraph (PDF)

Convert PCF to PSF (Console font)

Here is the quick and dirty howto on converting PCF fonts to PSF using Gohufont as an example:

First get the bdf2psf from here: http://packages.debian.org/sid/all/bdf2psf/download
and the bdf version of gohufont: http://font.gohu.eu/gohufont-bdf-2.0.tar.gz

Extract gohufont-bdf-2.0.tar.gz

Extract bdf2psf_1.54_all.deb with:

bsdtar -xf bdf2psf_1.54_all.deb data.tar.gz && tar xvf data.tar.gz

It will extract in your current directory as usr/{bin,share}.

cd to ./usr/bin

Run

./bdf2psf --fb gohufont-uni-11.bdf /whateverpath/current/usr/share/bdf2psf/standard.equivalents \\
/whateverpath/usr/share/bdf2psf/required.set+/whateverpath/usr/share/bdf2psf/useful.set 512 \\
/path/to/gohufont-uni-11.psf

Now get to a console using CTRL+ALT+F1 .

Log in as root. Cd to dir containing the gohu psf font. Run:

setfont gohufont-uni-11.psf

Evidence:
Console with gohufont

Link to my original howto:

Arch Linux Post on Console fonting

Screenshot tool for repetitive screenshotting

My daily job sometime entails doing an amazing amount of documentation with screen shots in HP Quality Center.

I became tired of manually renaming screen shots so I created a semi-automatic script to ease the process.

The script uses ImageMagick and Xorg tools.

The features are:

  • Automatic numbering of screenshot.
  • Automatic insertion of time stamp.
  • Options for setting font and color for the time stamp.
#!/bin/bash
# Screenshot tool for TIMS.
#
# -------------------------
#
# By regj 2012.05
#
# -------------------------
#
# Check for config file create if needed with sane defaults then exit.
if [ ! -f $HOME/.scrotter ]; then
	echo "Creating scrotter config file ${HOME}/.scrotter"
	echo "scrotfldrbase=${HOME}/Desktop/scrots" > $HOME/.scrotter
	echo "fontsize=14" >> $HOME/.scrotter 
	echo "fillcolor=white" >> $HOME/.scrotter 
	echo "whiteterm=yes" >> $HOME/.scrotter
	echo "subw=130" >> $HOME/.scrotter
	echo "subh=5" >> $HOME/.scrotter
	echo "fontpath=/usr/share/fonts/dejavu/DejaVuSansMono.ttf" >> $HOME/.scrotter
	if [ $? = 0 ] ; then
		echo -e "Config file succesfully created. Adjust values if needed in ~/.scrotter.\nIf you use a black term background set whiteterm to no."
		echo "Current values:"
		cat $HOME/.scrotter
		echo "Rerun scrotter with --server-id if initial run"
		exit 0
	else
		echo "Something went wrong"
		exit 1
	fi
fi

# Source config file
source $HOME/.scrotter

# convert functions for white or black terminal
conv_black () {
convert -pointsize $fontsize \
	-font $fontpath \
	-fill $fillcolor \
	-draw "text ${xyplace} \"$(date "+%Y.%m.%d %H:%M"|sed -e ' s/\"/\\\"/g' )\"" \
	$scrotfldr/$srvid-$count.png $scrotfldr/$srvid-$count.png 
}

conv_white () {
convert -pointsize $fontsize \
        -font $fontpath \
        -fill $fillcolor \
	-stroke black \
	-strokewidth 1 \
        -draw "text ${xyplace} \"$(date "+%Y.%m.%d %H:%M"|sed -e ' s/\"/\\\"/g' )\"" \
        $scrotfldr/$srvid-$count.png $scrotfldr/$srvid-$count.png
}
	

# Options
case $1 in

--server-id) echo "Setting srvid" ; echo $2 > /tmp/${USER}-scrot-srvid ; exit 0;;
--reset-count) echo "0" > /tmp/$USER-scrot-count ; exit 0;;
--clean-up) rm -f $scrotfldr/*.png ; rm -f /tmp/${USER}-scrot-* ; exit 0 ;;
--help) echo "Options are:
		--server-id: Set servername used in test.
		--reset-count: Reset counter for enumerating png's.
		--clean-up: Delete png's in current serverfolder and reset counters and serverid.
		--help: This info." 
		exit 0;;

# Uncomment below if you want to remove everything in your scrot folder with this script
#--clean-all) if [ -z $scrotfldrbase ]; then 
#		echo "Exiting .." ; exit 1
#	     fi 
#		echo "NB: $scrotfldrbase will be removed recursively!"  
#		rm -rI $scrotfldrbase/*  
#		rm -f /tmp/${USER}-scrot-*
#		exit 0 ;;

esac

# Check if serverid is defined, use if yes
if [ -s /tmp/${USER}-scrot-srvid ]; then
	srvid=$(cat /tmp/${USER}-scrot-srvid)
	scrotfldr=$HOME/Desktop/scrots/$srvid
else
	echo "Please set server id with --server-id option. # scrotter --server-id <servername>"
	exit 1
fi

# Check if root, exit if yes.
if [ $(id -u) = 0 ]; then
	echo "Do not run as root!"
	exit 1
fi

# Create count file
if [ ! -f /tmp/${USER}-scrot-count ]; then
	echo "0" > /tmp/$USER-scrot-count
fi

# Create Screenshot folder if not present
if [ ! -d $scrotfldr ];  then
	mkdir -p $scrotfldr
fi

# Get active window ID
activewin=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)")
activewinid=${activewin:40}

# Get geometry of window
geowinw=$(xwininfo -id ${activewinid} | awk '/Width/ {print $2}')
geowinh=$(xwininfo -id ${activewinid} | awk '/Height/ {print $2}')

# Define X,Y placment of date text
xyplace="$(($geowinw - $subw)),$(($geowinh - $subh))"

# Get current count
count=$(cat /tmp/${USER}-scrot-count)

# Take screenshot
import -window "$activewinid" $scrotfldr/$srvid-$count.png

# Insert date stamp into screenshot use xyplace variable to adjust placement
if [ $whiteterm = yes ] ; then
	conv_white
else
	conv_black
fi

# Increment counter
echo $(($count+1)) > /tmp/$USER-scrot-count

Matéspresso

I enjoy maté as a substitute for coffee. The best way for me to prepare Maté is not by using the traditional bombilla and gourd, but instead I prefer to use a Moka Pot.

This produces a rather concentrated Maté brew which can be mixed with milk or drunk as is.

Something I have been thinking about is to pulverize the coarse Maté in a coffee grinder before brewing as a way to extract more. I’ll update this post with the results.

Not nix related, but this is a blog.

Update:

As expected, the resulting brew from finely ground maté is very strong, bitter (as I like it) and has dark green color (almost black). The coffeine and theobromine levels should be higher as well, considering the extra surface area with finely ground plant material. This approach is recommended.

100% CPU load with XBMC 11 Eden

The best media box software out there has been released in a new version – XBMC 11 Eden.

Initially I was very pleased with this update until I noticed the amount of CPU used while XBMC was idling. 100+% of CPU usage of one core.

After fiddling around with settings like Dirty Regions and not having success – I opted for a more systematic approach.

I went to system settings and immediately noticed a drop in CPU load. I switched between a couple of skins, but the high load began as soon as I entered the main menu.

What differentiated the main menu from the system menu? The RSS news feed in the bottom of the screen!

See here for reference: XBMC Apperance Settings

Turning this off immediately dropped the load to 3-4% when XBMC was idling in the main menu, but reappeared when any kind of GPU work was to be done.

I later found out that this was due to XVBA not being enabled on the XBMC build I was using (I have an ATI card). So, after installing a XVBA enabled build: xvba-xbmc my problem was completely solved.

XVBA is said to be dead (no further development), but it is probably the best solution for ATI owners who use XBMC at the moment.

Unix performance reporting with tikz/pgfplot

I became tired using excel to create performance reports and decided to invest some time in creating a template in LaTeX using the fabulous pgfplots package. Since I couldn’t find a suitable example anywhere on the net I’ve decided to share mine here.

Each month I receive bundle of performance statistics from 15 vmware servers which I convert to data looking like this:

2011-12-02 02:00:00, 14.43
2011-12-02 04:00:00, 4.49
2011-12-02 06:00:00, 12.33
2011-12-02 08:00:00, 4.23
2011-12-02 10:00:00, 2.49
2011-12-02 12:00:00, 2.26
2011-12-02 14:00:00, 2.32
2011-12-02 16:00:00, 0.99
2011-12-02 18:00:00, 8.85
2011-12-02 20:00:00, 14.81
...

The extract above is cpu usage of the server every second hour for a month.

\documentclass{minimal}
\usepackage[danish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{palatino}
\usepackage{filecontents}
\usepackage{tikz,pgfplots}
\usepgfplotslibrary{dateplot}
\definecolor{NNITRed}{RGB}{140,0,0}
\definecolor{pengreen}{RGB}{180,204,168}
\begin{document}
\pgfplotstableread[col sep=comma]{/home/regj/code/pyx/data/csv/server.cpud3}
\cputable
\begin{center}
\begin{tikzpicture}
\begin{axis}
[
title=CPU usage,
axis background/.style={fill,bottom color=gray!50,top color=white},
grid=major,
grid style={dotted,black},
width=15cm,
height=8cm,
date coordinates in=x,
date ZERO=2011-12-02 02:00:00,
xmin =2011-12-02 02:00:00,
xmax =2011-12-31 20:00:00,
xtick=,
ymax=100,
ylabel=CPU used \%,
xticklabel style={rotate=90, anchor=near xticklabel}
]
\addplot[blue] table[ y index = 1] from \cputable ;
\addlegendentry{CPU}
\end{axis}
\end{tikzpicture}
\end{center}
\end{document}

Which produces a graph (a very nice one at that IMO):
cpuplot simple

A simple inotify script to control rtorrent

So, I only want rtorrent to start when a torrent is available for download. I came up with the following script:

while inotifywait -qq -e create /path/to/torrentdir; do
  if pgrep rtorrent > /dev/null; then
     continue
  elif echo /path/to/torrentdir/* | grep torrent; then
     screen -d -m -S rtorrent rtorrent
done

Creating a fail2ban proxy filter

I recently discovered the usefulness of fail2ban whilst researching a way to block proxyheader.php requests on my LAMP server.

The request always came from the same location and the same IP’s:
58.218.199.147
58.218.199.250
58.218.199.227

A whois on these IP’s reveal that they’re based in China – Bejing to be exact – and are probably searching for proxy servers to implement in to the Great FW of China

I’m not sure, but their requests annoyed me and I wanted to block them.

I found this filter: Apache Proxy filter , but I found the jail.conf entry did not work and needed to be updated.

Here’s the filter and working jail.conf entry for fail2ban v0.8.4 …

Filter:
# Fail2Ban configuration file
#
# Author: James Roe
# Use in apache access logs
[Definition]
# Matches lines such as:
# 192.168.1.1 - - "GET http://www.infodownload.info/proxyheader.php ...
failregex = ^(?:(?![0-9\.]* -.*"[A-Z]* (/|.*HTTP/1\.[0-9]" (301|302))))
ignoreregex =

Place the filter in /etc/fail2ban/filter.d/apache-proxy.conf.

/etc/fail2ban/jail.local entry:
[apache-proxy]
enabled = true
filter = apache-proxy
action = iptables-multiport[name=PROXY,port="http,https",protocol=tcp]
logpath = /var/log/httpd/*access_log
maxretry = 0
findtime = 604800
bantime = -1

LVM2 partitioning on an Arch Linux Linode

The default image that comes with an Arch Linux linode install is at the time of writing not fully compatible with LVM2. Slash var, usr, and tmp failed when mounted as LVM2 at boot and some very weird errors when creating new LV’s.

I had to do the following to get it to work properly.

  1. Create a small partition for the standard linode Arch image at around 1024Mb.
  2. Create a disk using the remaining space.
  3. Boot the default partition and install base-devel and init-scripts.
  4. wget https://aur.archlinux.org/packages/li/linux-xen/linux-xen.tar.gz or another xen-kernel of your choice.
  5. tar xvf linux-xen.tar.gz && cd linux-xen && makepkg –asroot
  6. Add lvm2 to HOOKS and xen_blkfront to MODULES in /etc/mkinitcpio.conf.
  7. If compilation is successful install: pacman -U linux-xen-
  8. Install grub and edit /boot/grub/menu.lst as such:

    # (0) Arch Linux
    title Arch Linux [/boot/vmlinuz-linux]
    root (hd0)
    kernel /boot/vmlinuz-linux-xen root=/dev/xvda ro
    initrd /boot/initramfs-linux-xen.img

    Notice that root is on hd0. In Xen boot can not exist on separate partition AFAIK.
  9. In your main profile set kernel to: pv-grub-x86_64 and set “no” on Xenify distro in order to enable proper console access in Arch and change the following line in /etc/inittab:
    c0:12345:respawn:/sbin/agetty 38400 tty0 linux
    to
    c0:12345:respawn:/sbin/agetty 38400 hvc0 linux
  10. Reboot to test if your kernel works – if yes – boot into finnix recovery and create your LVM partitioning the way you see fit. Format your lv’s with ext3 or ext4.
  11. Then:
    mkdir /mnt/root
    mkdir -p /new/{var,srv,home,tmp,usr}
    mount /dev/xvda /mnt
    mount your lv's to /new/
    cp -a /mnt/root/var/* /new/var/ (do this for each new mount point)
    rm -rf /mnt/var/* (remove data from each of the directories you transferred to your new lv's)
  12. Adapt your /etc/fstab for your new mount points. Example:
    # /etc/fstab: static file system information.
    #
    #
    proc /proc proc defaults 0 0
    /dev/xvda / ext3 noatime,errors=remount-ro 0 1
    /dev/xvdb none swap sw 0 0
    /dev/mapper/vglino-lvvar /var ext3 noatime 0 1
    /dev/mapper/vglino-lvtmp /tmp ext3 noatime 0 1
    /dev/mapper/vglino-lvhome /home ext3 noatime 0 1
    /dev/mapper/vglino-lvsrv /srv ext3 noatime 0 1
    /dev/mapper/vglino-lvbck /data/backup ext3 noatime 0 1
    /dev/mapper/vglino-lvusr /usr ext3 noatime 0 1
  13. Reboot … profit.