About Me

My photo
I know the last digit of PI

Monday, May 30, 2011

FC15 post installation steps

Gnome shell 3

Showing date in taskbar

gsettings set org.gnome.shell.clock show-date true

Showing date in taskbar

gsettings set org.gnome.shell.calendar show-weekdate true

Show week numbers in calendar

gsettings set org.gnome.shell.calendar show-weekdate true

Show minimize, maximize buttons

gconftool-2 -s -t string /desktop/gnome/shell/windows/button_layout "menu:minimize,maximize,close"

Always show power off in menu

yum install gnome-shell-extensions-alternative-status-menu
More info about available extensions can be found here

Tweak-tool

yum install gnome-tweak-tool
Then use start it go to Desktop and enable "Have file manager handle the desktop"

Taskbar

yum install tint2
Then use gnome-session-properties utility to add tint2 to gnome auto start programs (/usr/bin/tint2)

Nautilus

Show hidden files

gsettings set org.gnome.nautilus.preferences show-hidden-files true

Show address bar instead of buttons for file path

gsettings set org.gnome.nautilus.preferences always-use-location-entry true

Configurations

Additional repositories

Add RPM fusion repos:
su -c 'yum localinstall --nogpgcheck http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm'

Admin rights

Add sudo capabilities to current user:
usermod -a -G wheel `whoami`

Startup theme

Change the startup theme:
sudo yum install plymouth-theme*

sudo plymouth-set-default-theme --list

sudo plymouth-set-default-theme solar -R

Keyboard mappings

Install gconf-editor:
sudo yum install gconf-editor
Now open gconf-editor from command line and do following modifications:

windows + D to show desktop

Find the key "/apps/metacity/global_keybindings/show_desktop" and set the value to "<mod4>D"

windows + R to run command

Find the key "/apps/metacity/global_keybindings/panel_run_dialog" and set the value to ""<mod4>R"

windows + L to lock screen

Find the key "/apps/metacity/global_keybindings/run_command_1" (or any other number and set the value to ""<mod4>L". Find the key "/apps/metacity/keybinding_commands/command_1" and set the value to "gnome-screensaver-command -l"

Windows aliases

notepad

sudo alternatives --install /usr/bin/notepad notepad /usr/bin/gedit 1

explorer

sudo alternatives --install /usr/bin/explorer explorer /usr/bin/nautilus 1

cmd

sudo alternatives --install /usr/bin/cmd cmd /usr/bin/gnome-terminal 1

Installing additional software

Music player - XMMS

sudo yum install xmms xmms-faad2 xmms-mp3 xmms-pulse xmms-skins

Video players

mplayyer

sudo yum install mplayer gecko-mediaplayer mplayer-gui mencoder

VLC

sudo yum install vlc

Gnome-tweak-tool

sudo yum install gnome-tweak-tool
It can be used to change variety of options. Go to "Windows" and change "Current theme" to "Crux". Go to "File manager" and change "Have file manager handle desktop" to "Yes".

MS fonts

sudo yum install rpm-build cabextract ttmkfdir wget xfs

sudo rpm -ih http://dl.atrpms.net/all/chkfontpath-1.10.1-2.fc14.x86_64.rpm

sudo wget http://corefonts.sourceforge.net/msttcorefonts-2.0-1.spec

sudo rpmbuild -ba msttcorefonts-2.0-1.spec

sudo yum install --nogpgcheck /root/rpmbuild/RPMS/noarch/msttcorefonts-2.0-1.noarch.rpm

Chrome

Go to www.google.com/chrome and follow instructions

Flash

Go to Adobe flash and choose linux 64 (Step1) and YUM 64 (Step2) Install the downloaded RPM it will add the adobe YUM repos. Install the real flash player with:
yum install flash-plugin nspluginwrapper.x86_64 nspluginwrapper.i686 alsa-plugins-pulseaudio.i686 libcurl.i686
Now Firefox should be able to play flash video (try it with youtube) In order to make Chrome playing flash videos executes following commands:
mkdir /opt/google/chrome/plugins
ln -s /usr/lib64/mozilla/plugins/libflashplayer.so /opt/google/chrome/plugins/libflashplayer.so

Skype

Go to http://www.skype.com/intl/en/get-skype/on-your-computer/linux/downloading.fedora and follow instructions

Show system information as background - conky

sudo yum install conky
Then use gnome-session-properties utility to add conky to gnome auto start programs (/usr/bin/conky)A simple configuration file /etc/conky/conky.conf
alignment top_right

background no

border_width 1

cpu_avg_samples 2

default_color white

default_outline_color white

default_shade_color white

draw_borders no

draw_graph_borders yes

draw_outline no

draw_shades no

use_xft yes

xftfont DejaVu Sans Mono:size=12

gap_x 5

gap_y 60

minimum_size 5 5

net_avg_samples 2

no_buffers yes

out_to_console no

out_to_stderr no

extra_newline no

own_window_transparent yes

own_window yes

own_window_class Conky

own_window_type desktop

stippled_borders 0

update_interval 1.0

uppercase no

use_spacer none

show_graph_scale no

show_graph_range noTEXT

#${scroll 32 $nodename - $sysname $kernel on $machine | }

$nodename - $sysname $kernel

$hr

${color grey}Uptime:$color $uptime

${color grey}Frequency (in GHz):$color $freq_g

${color grey}RAM Usage:$color $mem/$memmax - $memperc% ${membar 4}

${color grey}Swap Usage:$color $swap/$swapmax - $swapperc% ${swapbar 4}

${color grey}CPU Usage:$color $cpu% ${cpubar 4}

${color grey}Temperature:$color $acpitemp% ${color grey}Fan speed:$color $acpifan

${color grey}Processes:$color $processes  ${color grey}Running:$color $running_processes

$hr

${color grey}File systems:

/ $color${fs_used /}/${fs_size /} ${fs_bar 6 /}

${color grey}Networking:

Up:$color ${upspeed eth0} ${color grey} - Down:$color ${downspeed eth0}

$hr

${color grey}Name              PID   CPU%   MEM%

${color lightgrey} ${top name 1} ${top pid 1} ${top cpu 1} ${top mem 1}

${color lightgrey} ${top name 2} ${top pid 2} ${top cpu 2} ${top mem 2}

${color lightgrey} ${top name 3} ${top pid 3} ${top cpu 3} ${top mem 3}

${color lightgrey} ${top name 4} ${top pid 4} ${top cpu 4} ${top mem 4}

All the information is found by googling. You can find some very useful tips here and here and here
Thanks guys!

Tuesday, March 29, 2011

VNC server under F14

1) Install the vnc server by suing following command:
yum install tigervnc tigervnc-server


2) Under the user that will be used to login execute:
vncpasswd

This is the password that you will use to connect to the server

3) Configure the displays by editing /etc/sysconfig/vncservers
nano /etc/sysconfig/vncservers

Make sure that you have something like this
VNCSERVERS="1:the_user_that_is_used_for_vnc"
VNCSERVERARGS[1]="-geometry 1280x1024"


4) Then start the service for the first time:
service vncserver start


5) And make sure that the service is starting everytime you restart your machine:
chkconfig vncserver on


6) also don't forget to add firewall rules - use gnome tools from System / Administration / Firewall... Allow connections to port 5901

7) Now you can connect to the VNC server with ip and the display number e.g.: 192.160.0.254:1

Tuesday, March 01, 2011

How to list registered EJB beans in Glassfish

http://www.myeclipseide.com/PNphpBB2-viewtopic-t-18850.html

1) Open the Glassfish Admin Console
2) Select the "Application Server" tree node
3) In the "General" tab under "General Information" choose JNDI browsing
4) Under the "ejb" tree you can find all registered EJB beans

Saturday, February 26, 2011

How to enable Remote Desktop on remote machine

http://oreilly.com/windows/archive/server-hacks-remote-desktop.html
1) connect on the machine using regedit.exe (from File / Connect Network Registry)
2) Go to the key HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server
3) Change fDenyTSConnection from 1 (Remote desktop disabled) to 0 (Remote desktop enabled)
4) Restart the system by using the command
shutdown -m \\ -r

Thursday, February 17, 2011

Installing OpenId-server on mysql

1) Download the JosID war file.
wget http://mirrors.redv.com/pub/jos/jos-1.2.1/jos-webapp-1.2.1.war
2) Deploy it on tomcat server
cp jos-webapp-1.2.1.war /usr/share/tomcat7/webapps/josid.war
3) start tomcat and stop it in order to extract the war content.
5) Copy the context.xml from the WAR to the tomcat/conf dir
cp /usr/share/tomcat7/webapps/josid/META-INF/context.xml /usr/share/tomcat7/conf/Catalina/localhost/josid.xml
6) Edit /usr/share/tomcat7/conf/Catalina/localhost/josid.xml and change the jdbc/jos resource and the Hybernate dialect:


<Resource
name="jdbc/jos"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/jos"
username="jos"
password="secret" />

<Environment
name="hibernate.dialect"
type="java.lang.String"
value="org.hibernate.dialect.MySQL5Dialect" />

Also change the password
<Environment
name="domain.configurator.password"
type="java.lang.String"
value="secret"
override="false" />

7) Download the mysql-connector and put it in tomcat/lib directory
8) Create the mysql database
CREATE USER 'jos'@'localhost' IDENTIFIED BY 'secret';
CREATE DATABASE jos;
GRANT ALL ON jos.* TO 'jos'@'localhost';
FLUSH PRIVILEGES;
9) start tomcat
10) open the josid URL and use the password previously configured in josid.xml

Maven on F14

1) wget http://apache.online.bg//maven/binaries/apache-maven-3.0.2-bin.tar.gz
2) tar -zxvf apache-maven-3.0.2-bin.tar.gz
3) cp -R apache-maven-3.0.2 /usr/share/
4) ln -s /usr/share/apache-maven-3.0.2/ /usr/share/maven
5) update-alternatives --install /usr/bin/mvn mvn /usr/share/maven/bin/mvn 1
6) update-alternatives --config mvn
Just to make sure that it is using the correct path.

Wednesday, February 16, 2011

Tomcat 7 on Fedora 14

First let install tomcat6 so we have some template from where to copy the scripts:
0) yum install tomcat6

Now lets configure the service:
1) cp -R /etc/init.d/tomcat6 /etc/init.d/tomcat7
2) Edit /etc/init.d/tomcat7 and change all occurrences of tomcat6 to tomcat7


Now lets configure the script that actually starts the tomcat:
3) cp -R /usr/sbin/tomcat6 /usr/sbin/tomcat7
4) Edit /usr/sbin/tomcat7 and change all occurrences of tomcat6 to tomcat7


Next let's make the configuration & log directories:
5) mkdir /etc/tomcat7
6) mkdir /var/log/tomcat7

Now download the tomcat archive distribution:
7) Download tomcat7.tar.gz and extract it into /usr/share/tomcat7

Copy the configuration files in Fedora standart config dir:
8) cp -R /usr/share/tomcat7/conf /etc/tomcat7
9) rm -Rf /usr/share/tomcat7/conf
10) ln -s /etc/tomcat7 /usr/share/tomcat7/conf

Make the tomcat7 to use the standard Fedora log directory:
11) rm -Rf /usr/share/tomcat7/logs
12) ln -s /var/log/tomcat7 /usr/share/tomcat7/logs

Configure the tomcat7 options:
13) cp /etc/tomcat6/tomcat6.conf /etc/tomcat7/tomcat7.conf
14) Edit /etc/tomcat7/tomcat7.conf and change all occurrences of tomcat6 to tomcat7

Specify temp & work dirs:
15) mkdir -p /var/cache/tomcat7/work
16) mkdir -p /var/cache/tomcat7/temp
17) rm -Rf /usr/share/tomcat7/work
18) rm -Rf /usr/share/tomcat7/temp
19) ln -s /var/cache/tomcat7/work /usr/share/tomcat7/work
20) ln -s /var/cache/tomcat7/temp /usr/share/tomcat7/temp

Fix the permissions:
21) chgrp -R tomcat /usr/share/tomcat7
22) chmod -R ug+rwx /usr/share/tomcat7
23) chgrp -R tomcat /var/log/tomcat7
24) chmod -R ug+rwx /var/log/tomcat7
25) chgrp -R tomcat /var/cache/tomcat7
26) chmod -R ug+rwx /var/cache/tomcat7

Add administrator user so you can manage the server:
27) Edit /etc/tomcat7/tomcat7.conf and following lines
<role rolename="admin"/>
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<role rolename="manager"/>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user name="admin" password="adminadmin" roles="admin,manager,admin-gui,admin-script,manager-gui,manager-script,manager-jmx,manager-status" />



Now start the service and everything should works fine:
28) service tomcat7 start

Finally you can start the service on everyboot
29) chkconfig tomcat7 on

Sunday, February 13, 2011

NVidia driver F14 x86_64

По default F14 идва с nouveau драйвер зa видео картата. Ако искате да сложите нов дравер направете следното:
1. Сваляне на драйвера от www.nvidia.com (NVIDIA-Linux-x86_64-260-19.36.run)
2. Reboot и по време на GRUB избирате опция за допълнителни параметри към kernel (от менюто избирате 'a'). Добавяте параметъра single накрая на реда.
3. Когато се стартира системата, няма да ви иска парола.
Изпълнявате init 3
4. Логвате се с root
5. Изпълнявате NVIDIA-Linux-x86_64-260-19.36.run. Най-вероятно ще излезе грешка, че nouveau е активен.
6. Изберете yes за modprobe disable стъпката.
7. Изпълнете 2-5 отново. Ако пак възникне грешка, тогава трябва да се направи едно от двете:
7а. Редактирате /boot/grub/grub.conf и на реда в който започва с kernel накрая добавяте параметъра rdblacklist=nouveau (това е същия ред който редактирате от GRUB-a)
7b. Променяте initramfs като изпълните командите
mv /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r)-nouveau.img
dracut /boot/initramfs-$(uname -r).img $(uname -r)
8. Повтаряте стъпките от 2-5 и този път не трябва да ви даде грешка за nouveau. Избирате да инсталирате opengl32 и да конфигурирате X средата

Как да инсталираме skype под F14

http://yunustj.wordpress.com/2010/07/18/how-to-install-skype-on-to-fedora-13-x86_64/


yum whatprovides


ни дава информация кой пакет да инсталираме за да имаме дадената библиотека.


E: skype: error while loading shared libraries: libasound.so.2: cannot open shared object file: No such file or directory
S: yum install alsa-lib.i686

E: skype: error while loading shared libraries: libXv.so.1: cannot open shared object file: No such file or directory
S: yum install libXv.i686

E: skype: error while loading shared libraries: libXss.so.1: cannot open shared object file: No such file or directory
S: yum install libXScrnSaver.i686

E: skype: error while loading shared libraries: libQtDBus.so.4: cannot open shared object file: No such file or directory
S: yum install qt.i686

E: skype: error while loading shared libraries: libQtGui.so.4: cannot open shared object file: No such file or directory
S: yum install qt-x11.i686


На стъпката с libQtDBus.so.4 имах доста проблеми, защото имаше конфликти с вече инсталирани пакети. Това което си спомням, че направих е да инсталирам qt.x86_64, т.е.:


yum install qt.x86_64
yum install qt.i686


И по някакъв магически начин след това нямаше конфликти :-)

Sunday, January 09, 2011

Активни транзакции в Oracle

Ето и едно скрипче което показва активните транзакции в Oracle.


SELECT
s.osuser, vp.spid as os_pid, S.BLOCKING_SESSION blocker,
S.SID, S.SERIAL#, S.USERNAME, S.MACHINE,
Q.SQL_FULLTEXT cur_sql, PQ.SQL_FULLTEXT prev_sql,
vt.used_urec, vt.start_date
FROM
v$session S
LEFT JOIN v$sqlarea Q on S.SQL_ID = Q.SQL_ID
LEFT JOIN v$sqlarea PQ on S.PREV_SQL_ID = PQ.SQL_ID
LEFT JOIN v$process vp on s.paddr = vp.addr
LEFT JOIN v$transaction vt on s.saddr = vt.ses_addr
WHERE
vt.start_date < SYSDATE - (5/1440)
-- AND
-- s.machine = 'machine.name'
ORDER BY
S.SID
;

Thread dump на Glassfish

Понякога се налага да се проверят разни продъкшан системи защо забиват и т.н.
Един добър начин това да се направи, е чрез използването на JMX менидмънт бийновете.

Ot \bin се пуска jconsole въвежда се следния remote process
service:jmx:rmi:///jndi/rmi://127.0.0.1:8686/jmxrmi
и се въвеждат администраторските пароли за glassfish-а.

След това се следва туторияла за jconsole-ата
http://download.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html

Интересното е таба Threads и отдолу има списък с тредовете и техния stacktrace

Пълно форматиране на харда от Windows 7 DVD

Може би някои са забелязали, новият инсталатор нa Windows вече няма full format, а само quick. Това супер, ако все пак не се нуждаете от проверка за лоши сектори или искате тотално да затриете информацията. Следната процедура позволява пълно форматиране

1. Започнете инсталиране от DVD-то
2. На екрана "Where do you want to install Windows" изтрийте всичките партишъни и създайте нов празен.
3. Форматирайте го - това е quick формата
4. Натиснете Shift + F10 (ще се отвори конзола)
6. От команд промпта напишете "format c:". Параметъра /P:<число> ще занули съдържанието на секторите.

Wednesday, June 23, 2010

Show available disks drives under Linux (Fedora)

Somebody wondering how to show all attached hard disks / CD DVD drives under Linux?

Here is a small program that do just that. It works perfectly under Fedora 13. Copy/Past the text in file called /usr/bin/lshdd
#!/bin/bash
if [ "$1" == "-v" ]; then
  verbose="true"
else
  verbose="false"
fi

lshal | awk -v verbose=$verbose 'BEGIN {
  name=""
}
{
  if ($0~"^udi = ") {name=""}
  if ($0~"^udi = ./org/freedesktop/Hal/devices/storage_serial_.*") {
    match($3, "/org/freedesktop/Hal/devices/storage_serial_(.*).", arr);
    name=arr[1]
  }
  if ($0~"^udi = ./org/freedesktop/Hal/devices/storage_model.*") {
    match($3, "/org/freedesktop/Hal/devices/storage_model_(.*).", arr);
    name=arr[1]
  }
  if (name!="" && $0~"block.device") {
    match($3, "(/dev/.*).", arr);
    if (verbose~"true") {
      print arr[1] " = " name
    } else {
      print arr[1]
    }
    name = ""
  }
}'
Change the file permissions:
chmod a+x /usr/bin/lshdd
Then you can list your hard & dvd drives:
lshdd -v
and the output looks like:
/dev/sr0 = DVD__RW_TS_L632D
/dev/sdb = WDC_WD50_00AAVS_00ZTB0_D577A3503523_0_0
/dev/sda = SAMSUNG_HM400LI_S1PSJ10Q710844

You can easily find the partitions of specific drive
fdisk -l /dev/sdb



P.S. It is my first awk script, so it really looks ugly, I know ;-)

Wednesday, June 09, 2010

Fedora startup theme

Федора ползва plymouth за да покаже анимацията по-време на бутването, преди да се е заредло Х-а. Готиното е, че plymouth може да се наглася и да се слагат различни теми ;-)

yum install plymouth-theme*
plymouth-set-default-theme --list
plymouth-set-default-theme solar -R
#plymouth-set-default-theme solar --rebuild-initrd

Sunday, June 06, 2010

Mount-ване на windows shares

sudo mount -t cifs -o username=myuser,password=secret,uid=myuser,gid=mygroup //10.1.52.25/c$ /mnt


Параметри са:
username,password са Windows credential
uid,gid потребителят и групата на owner-а на /mnt

Част от параметрите може и да се пропуснат:
sudo mount -t cifs -o username=myuser,uid=myuser //10.1.52.25/c$ /mnt

Nautilus address bar

Nautilus може да показва пътят до файла като бутони или като стринг. По подразбиране се ползват бутони. За да се промени тази настройка трябва да се промени стойността на полето (unchecked)
/apps/nautilus/preferences/always_use_location_entry от gconf-editor.

Ако gconf-editor, трябва да се инсталира с yum install gconf-editor*

Show desktop


След като си инсталирах новата Fedora 13 ми се прииска да си имам любимият Show Desktop бутон, който да показва десктопа. В самата дистрибуция има такъв бутон, но логиката му е странна и не ми харесва - първо първо натискане прави restore all hidden windows, второто натискане hide all windows. Това което на мене ми трябва е: при натискане да показва десктопа.

Ето как става това:

1. yum install wmctrl*
2. Right click on the panel and choose Add to panel > Custom application launcher
3. Type: Application,
Name: Show Desktop
Command: wmctrl -k on
4. choose the icon
5. click OK.

Saturday, May 08, 2010

Инсталиране на Sun JDK на Fedora

1) Сваляте Sun-ското JDK от java.sun.com като bin файл
2) chmod a+x на bin файла и го стартирате
3) копирате съдържанието на разархивираната директория (например jdk1.6.0_20) в /usr/lib/jvm/jdk-1.6.0_20-sun (която трябва да създадете)
4) използвате командата update-alternatives за да добавите новата java
5) update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-1.6.0_20-sun/bin/java 1
6) update-alternatives --config java
и избирате нововъведения път
7) изпълнявате java -version и проверявате дали е правилната java на Sun

Friday, August 28, 2009

Как да си направим backup на диска под Линукс

Въпреки, че хардовете в днешно време са доста надеждни (поне на мен лично не ми е горял хард все още), не е зле човек да се потдотви и да си прави бакъпи редовно.
Понеже основната ми машинка която ползвам за SCM, Continuous integration, Issue trackig и т.н. е под линукс, затова реших да си напиша няколко скриптчета с които да си правя бакъпите. Изискванията ми не са кой знае какви - просто трябва да мога да си възтановя SCM и issue tracking даните без загуби и много труд. При евентуален срив и загуба на хард не очаквам да мога да възтановя цялата система. Пък и какъв е смисълът? Така никога няма да седна да инсталирам нова версия на софтуера! Всъщност от тази гледна точка сривовете са даже нещо много полезно... помагат ти да си разчистиш старите данни и боклуци, които са се насъбрали с години, кара те да качиш нови програмки и т.н. :-D Просто трябва да се случват в подходящ момент :-) когато имаш достатъчно време да си сетъпнеш нова система!...
Та да се върнем на въпроса - скриптът за бакъп трябва да може да копира някои директории, да ги архивира и да пази копия на тях. Също така е хубаво да може да се следи и история...случайно, ако се прецакат някакви настройки да могат да се проверят кога са променени, и да се възтановят правилните конфигурации. Та скрипта трябва да може да пази архив на старите бекъпи. В основата на всичко е rsync, която се използва за създаване на самите файлове. За да сработи скрипта трябва да се създаде една директория /etc/backup където са всички конфигурации включително и самият скрипт:

#!/bin/sh

VERBOSE=0
SCOPE=""
CONFIG="/etc/backup/backup.conf"

# Outputs the help message how to use the script
print_help()
{
echo "Usage: backup [-v | --verbose] <-s | --scope> " >&2
echo " -v or --verbose switch verbose mode on" >&2
echo " -s or --scope reads the list of directories to backup for " >&2
echo " the from the /etc/backup.conf " >&2
}

# Parses the passed command line and defines the backup scope, verbose mode, etc.
parse_command_line()
{
PREV_SCOPE=0
for p in "$@"; do
if [ $PREV_SCOPE -eq 1 ]; then
SCOPE=$p
PREV_SCOPE=0
else
if [ '--verbose' == $p -o '-v' == $p ]; then
VERBOSE=1
fi

if [ '--scope' == $p -o '-s' == $p ]; then
PREV_SCOPE=1
fi
fi
done
}

# Outputs message to the console if the verbose mode is selected
print()
{
if [ $VERBOSE -eq 1 ]; then
echo "$1"
fi
}


read_configuration()
{
# @author Michael Klier
match=0

while read line; do
# skip comments
[[ ${line:0:1} == "#" ]] && continue

# skip empty lines
[[ -z "$line" ]] && continue

# still no match? lets check again
if [ $match == 0 ]; then

# do we have an opening tag ?
if [[ ${line:$((${#line}-1))} == "{" ]]; then

# strip "{"
group=${line:0:$((${#line}-1))}
# strip whitespace
group=${group// /}

# do we have a match ?
if [[ "$group" == "$1" ]]; then
match=1
continue
fi

continue
fi

# found closing tag after config was read - exit loop
elif [[ ${line:0} == "}" && $match == 1 ]]; then
break

# got a config line eval it
else
eval $line
fi

done < "$CONFIG"
}


#
#
# The main script starts here
#
#

START_TIME=`date +%s`

# Parse the command line parameters
parse_command_line $@

if [ -z $SCOPE ]; then
print_help
echo $"Please enter the name of the backup scope" >&2
exit 1
fi

# Read LIST variable from the configuration file
read_configuration $SCOPE

# Example how the LIST variable should looks like
# LIST="etc root usr home var"

# Waits at 1 seconds, so if the user starts the script too fast the TIME_STAMP directory will be different
sleep 1

BACKUP_DIR="/backup/$SCOPE"

# Output the configuration information
print "Backup scope: $SCOPE"
print "Backup directory list: $LIST"
print "Exclude file: $EXCLUDE_FILE"
print "Backup dir is $BACKUP_DIR"

# Creates the backup directory
if [ ! -d $BACKUP_DIR ]; then
mkdir $BACKUP_DIR
fi

#
#
# Rotate backups, so we keep only the last 100
#
#

# Maximum number of backups to keep
maxInd=20

# Gets the oldest backup canonical path (it is a symbolic link to a time-stamped tar file)
REAL_PATH=`readlink -f $BACKUP_DIR/b.$maxInd.tar.gz`

# Remove the oldest backup
if [ -e $REAL_PATH ]; then
print "Removing tar file $REAL_PATH"
rm -rf $REAL_PATH
fi

# Remove the symbolic link
rm -rf $BACKUP_DIR/b.$maxInd.tar.gz


# Rotate backups from $ind to $ind+1
for ((ind = $maxInd-1; ind >= 0; ind--)); do
let nextInd=$ind+1
if [ -e $BACKUP_DIR/b.$ind.tar.gz ]; then
print "Rotating $BACKUP_DIR/b.$ind.tar.gz to $BACKUP_DIR/b.$nextInd.tar.gz"
mv $BACKUP_DIR/b.$ind.tar.gz $BACKUP_DIR/b.$nextInd.tar.gz
fi
done

# Delete the first backup (it must already be rotated, but just to be sure that the file doesn't exists)
rm -f $BACKUP_DIR/b.0.tar.gz

# Generate new timestamp for the new backup
TIME_STAMP=`date "+%F_%H-%M-%S"`

# Create the backup folder using the timestamp
mkdir $BACKUP_DIR/$TIME_STAMP

# Backup all files in the backup-list
for d in $LIST; do
print "Backuping /$d/ to $BACKUP_DIR/$TIME_STAMP/$d/"
mkdir -p $BACKUP_DIR/$TIME_STAMP/$d/
if [ $VERBOSE -eq 1 ]; then
rsync -vv -a --delete --exclude-from=$EXCLUDE_FILE /$d/ $BACKUP_DIR/$TIME_STAMP/$d/
else
rsync -a --delete --exclude-from=$EXCLUDE_FILE /$d/ $BACKUP_DIR/$TIME_STAMP/$d/
fi


done

# Go to the backup directory, so we could tar the content
pushd $BACKUP_DIR/$TIME_STAMP > /dev/null

# Archive the entire directory into single tar file
tar -c -z -f $BACKUP_DIR/$TIME_STAMP.tar.gz .

# Restore the current directory
popd > /dev/null

# Remove the backup directory
rm -rf $BACKUP_DIR/$TIME_STAMP

# Create a symbolic link to the directory
ln -s $BACKUP_DIR/$TIME_STAMP.tar.gz $BACKUP_DIR/b.0.tar.gz

FINISH_TIME=`date +%s`

FILE_SIZE=`ls -lrt $BACKUP_DIR/$TIME_STAMP.tar.gz | awk '{print $5}'`

printf "Completed! Execution time: $((FINISH_TIME - START_TIME)) seconds. Backup file size: $FILE_SIZE bytes."
printf "\n"




И така този скрипт се ползва по следния начин:
/etc/backup -s SCOPE_NAME

SCOPE_NAME се чете от конфигурационият файл /etc/backup.conf в който се описват кои директории да се копират. Ето и примерен такъв:
#
# In order to define a new scope of backup items uncomment following lines
#
#
#
# scope_name {
# LIST="etc root usr home var"
# EXCLUDE_FILE="/etc/backup/backup.excludes"
# }
#
# No leading ot trailing / in the directory names.
# The directories are sub directories of the /


weekly {
LIST="etc root usr home var"
EXCLUDE_FILE="/etc/backup/backup.excludes"
}

daily {
LIST="etc usr/red5/conf usr/red5/webapps usr/share/tomcat6/conf usr/share/tomcat6/webapps var/svn var/trac"
EXCLUDE_FILE="/etc/backup/backup.excludes"
}


Всеки scope си има списък от директории (LIST) и EXCLUDE_FILE в който се описват, коит файлове от тези директории да се пропуснат. Примерен backup.excludes:
#Excluding subdirs from /usr/

/bin/***
/java/***
/games/***
/kerberos/***
/sbin/***
/libexec/***
/lib/***
/tmp
/tmp/***
/include/***

# Excluding subdirs from /var/

/tmp/***


Така целият скрипт очаква, че ще има директория /backup (която е добре да моунтната на друг хард диск)

Хубаво е да се направят и cron task-ове които да правят дневен или седмичен бекъп.
Ето няколко примерни такива:

/etc/cron.daily/backup_daily
#!/bin/bash

TIME_STAMP=`date "+%F_%H-%M-%S"`

echo "Starting daily backup $TIME_STAMP" > /var/log/backup/$TIME_STAMP.log

/usr/bin/backup --verbose --scope daily > /var/log/backup/$TIME_STAMP.log 2> /var/log/backup/$TIME_STAMP.err



/etc/cron.weekly/backup_weekly
#!/bin/bash

TIME_STAMP=`date "+%F_%H-%M-%S"`

echo "Starting weekly backup $TIME_STAMP" > /var/log/backup/$TIME_STAMP.log

/usr/bin/backup --verbose --scope weekly > /var/log/backup/$TIME_STAMP.log 2> /var/log/backup/$TIME_STAMP.err



И така това е целият скрипт. Успех!

~Киро :-)

Many thanks to Michael Klier for his article
Parsing Simple Config Files In Bash

Friday, January 09, 2009

Red5 service за Линукс

Red5 е едно много хубаво сървърче за флаш. Инсталацията му под Windows е елементарна - има си setup.exe, което прави всичко. Под линукс обаче нещата не са толкова лесни - разархивираш tar файл, слагаш на необходимото място, инсталираш Sun-ска Java и т.н. Има доста форуми по въпроса. Единствения проблем е, ако трябва Red5 да се пуска като service. За Fedora 10 това се прави по следния начин:
1) добавя се един файл /etc/init.d/red5
2) chmod a+rx /etc/init.d/red5
3) съдържанието му е:



#! /bin/sh
#
# red5
#
# chkconfig: - 80 20
#
# Author: Kiril Arabadzhiyski
#
### BEGIN INIT INFO
# Provides: red5
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Default-Start:
# Default-Stop:
# Description: Red5 - Open Source Flash Server
# Short-Description: start and stop red5
### END INIT INFO
#
# File location: /etc/init.d/red5
#
#
RED5_DIR=/usr/red5
test -x $RED5_DIR/red5.sh || exit 5

RED5_USER=red5
RED5_LOG_DIR=/var/log/red5

STDERR_LOG=$RED5_LOG_DIR/stderr.log
STDOUT_LOG=$RED5_LOG_DIR/stdout.log

if [ -r /lib/lsb/init-functions ]; then
. /lib/lsb/init-functions
else
exit 1
fi

function startCmdExec() {
su -s /bin/bash -c "${RED5_DIR}/red5.sh >> ${STDOUT_LOG} 2>> ${STDERR_LOG} &" ${RED5_USER}
}

function stopCmdExec() {
su -s /bin/bash -c "${RED5_DIR}/red5-shutdown.sh > /dev/null 2> /dev/null &" ${RED5_USER}
}

function start() {
echo -n "Starting Red5:"
cd $RED5_DIR

pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
if [ -z "$pid" ]; then
startCmdExec
sleep 2
pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
fi

if [ -n "$pid" ]; then
log_success_msg
else
log_failure_msg
fi
}



function stop() {
echo -n "Stopping Red5:"
echo -n " "
cd $RED5_DIR
stopCmdExec
sleep 5
pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
if [ -z "$pid" ]; then
log_success_msg
else
log_failure_msg
fi
}

function killIt() {
echo -n "Killing Red5:"
echo -n " "
su -s /bin/bash -c "killall -q -u ${RED5_USER} java" ${RED5_USER}
sleep 2
pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
if [ -z "$pid" ]; then
log_success_msg
else
log_failure_msg
fi
}

function status() {
pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
if [ -n "$pid" ]; then
echo "Red5 (pid ${pid}) is running..."
RETVAL="0"
else
echo "Red5 is stopped"
fi
}

function restart() {
stop
pid="$(pgrep -u ${RED5_USER} -G ${RED5_USER} java)"
if [ -n "$pid" ]; then
killIt
fi
start
}

case "$1" in
start)
start
;;
stop)
stop
;;
kill)
killIt
;;
restart)
restart
;;
status)
status
;;
esac



4) chkconfig --add red5
5) chkconfig red5 on
6) service red5 start

Ха честито!