Wednesday, 3 June 2015

Setting up an SAP Hybris Cluster with Jenkins

Minimum requirements

1 Jenkins server
1 Apache server (working as load balancer) with IP 192.168.0.1
2 Hybris servers (one working as importer and application server and the other one working only as application server) with IPs 192.168.0.2 and 192.168.0.3

Steps needed

Setting firewall unlocks between Jenkins and Apache/Hybris servers.
Create a "jenkins" user on all servers.
Set up SSH access for "jenkins" user on all nodes.
Create configuration files and push them into any code repository of your choice  (SVN, Mercurial, Git, etc.). Note: this example is using Mercurial.

Create Apache "httpd.conf" file

To use the HTTP Apache server as load balancer we need a configuration file like the described below:
Listen 80
Header add Set-Cookie: "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED 
<Proxy balancer://mycluster>
   BalancerMember http://192.168.0.2:9001 route=node1
   BalancerMember http://192.168.0.3:9001 route=node2
</Proxy> 
ProxyPass / balancer://mycluster/ stickysession=ROUTEID
ProxyPassReverse / balancer://mycluster/ 
<Location /balancer-manager>
   SetHandler balancer-manager
   Order Deny,Allow
   Deny from all
   Allow from all
</Location>
This load balancer server will use sticky sessions, because Hybris says that it improves the response time.
Save that content into a file called "httpd.conf" and push it into a code repository, this file will be used inside Jenkins job later (all configuration files should be compressed into config.tar.gz file).

Setting up SSH access in Jenkins

First of all, you need to load every server information into "SSH remote hosts" section, to do this you need to be Jenkins admin and go to
Jenkins -> Manage Jenkins -> Configure System

Create a new View tab

To organize the related cluster jobs, we will create a new view using the + button shown in the image below
We will call it "My-Cluster" and choose the "List View" option.
After that point you can add a description and click on OK button.

Create the "Load-Balancer" job

Click now on "New Item" to create your first Jenkins job and call it "Load-Balancer". After that choose the "Freestyle project" option and click on OK button.

After that choose the "Execute shell" option

Add in the Command area the text below and save it
sshpass -p "jenkins-password" scp -o StrictHostKeyChecking=no config.tar.gz jenkins@192.168.0.1:/home/jenkins/
Where "config.tar.gz" has the httpd.conf file to be used later.

Install SSH Jenkins plugin

Go to 
Jenkins -> Manage Jenkins -> Manage Plugins
Click on "Available" tab and filter by "SSH", after that choose the "SSH plugin" and click on "Download now and install after restart"

Execute a shell script on remote host

Edit the "Load-Balancer" job and add a new build step
After that, choose the SSH site and add the text below inside Command section
#!/bin/bash
echo "Enable Apache modules"
sudo a2enmod rewrite
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_ajp
sudo a2enmod proxy_balancer
sudo a2enmod proxy_connect
sudo a2enmod headers

echo "Stopping Apache"
sudo /etc/init.d/apache2 stop

echo "Extract config files"
sudo tar -xzf config.tar.gz

echo "Copy files into Apache available sites"
sudo cp -r config/apache-conf/node1/* /etc/apache2/sites-available

echo "Copy static content"
sudo cp -r config/apache-conf/www/* /var/www

echo "Remove old files"
rm -rf config
rm config.tar.gz

echo "Enable Apache sites"
sudo a2ensite my-shop.com
sudo a2ensite hybris

echo "Starting Apache"
sudo /etc/init.d/apache2 start
Save it and run this Jenkins job. If no errors were found, check your Apache server content.

Create the Hybris build job

Now we'll create a new Jenkins job, who will be responsible for building the Hybris platform. We will call it "Hybris-build" job.
To complete this step we need to install the "Mercurial" plugin (because I use this kind of code repository).
After the installation you can add the Mercurial repository in your "Hybris-build" job like the image below

Add also a shell build step with the information below
# get local.properties for jenkins build
mv config/properties/JENKINS_local.properties config/local.properties 
# link hybris platform zips to avoid copying them to speed up build
mkdir -p temp
ln -s -f /opt/ftp/hybrisplatform/* temp/ 
# copy hybris platform
cd config/env_build
printf '1\n' | ant -lib lib/jsch-0.1.50.jar 
# setup project structure
mkdir -p hybris
cp -R bin hybris/
cp -R config hybris/ 
# clean up workspace
rm -R bin
rm -R config
if [ -d "temp" ]; then
   rm -R temp
fi
After that we need an "Invoke Ant"  step, look at the image to have an idea
Add another shell build step with:
# replace jenkins path before Hybris zip the whole files
find . -name '*.java' -or -name '*.conf' -or -name '*.properties' -or -name '*.xml' | xargs perl -pi -e 's/opt\/jenkins\/jobs\/Hybris-build\/workspace/opt/g'
sed -i -e 's|/opt/jenkins/jobs/.*/workspace/hybris|/opt/hybris|g' $WORKSPACE/hybris/bin/platform/tomcat-6/conf/server.xml
Add another "Invoke Ant" and "Execute shell" steps like the image below:
As the last step, you need to archive the results to be used from the deploy job, to do this you need to add a "post-build action", checkout the image below
And fill it in with:


Create the deploy job

The last step in this process is to create the job responsible to stop the Tomcat server, deploy and start Tomcat again.
First, create a new freestyle Jenkins job called "Hybris-deploy".
Inside the Hybris-deploy job, you need to create a boolean parameter to update the database if it's needed.
To fulfil this step, we need to install first the "Copy Artifact" plugin using the Plugin Manager and restart Jenkins.
After Jenkins restart, we can add the copy artifact step
And then give in the build job name
Now we will copy the artifact content into the Hybris servers, for that reason we need a new "Execute shell" step with the content below
echo "Copy all files into Hybris node 1"
sshpass -p "jenkins-password" scp -o StrictHostKeyChecking=no hybrisServer-AllExtensions.zip hybrisServer-Platform.zip jenkins@192.168.0.2:/opt
sshpass -p "jenkins-password" scp -o StrictHostKeyChecking=no config.tar.gz jenkins@192.168.0.2:/opt/hybris/ 
echo "Copy all files into Hybris node 2"
sshpass -p "jenkins-password" scp -o StrictHostKeyChecking=no hybrisServer-AllExtensions.zip hybrisServer-Platform.zip jenkins@192.168.0.3:/opt
sshpass -p "jenkins-password" scp -o StrictHostKeyChecking=no config.tar.gz jenkins@192.168.0.3:/opt/hybris/
And now a new "Execute shell script on remote host using SSH" with the next script:
#!/bin/bash
echo "Stop tomcat in NODE_01"
sudo /etc/init.d/hybristomcat stop
### go to /opt ###
cd /opt
### extract new code ###
sudo unzip -o hybrisServer-Platform.zip
sudo unzip -o hybrisServer-AllExtensions.zip
sudo unzip -o hybrisServer-Config.zip
### provide proper local.properties ###
sudo cp -r hybris/config/P_NODE_01_local.properties hybris/config/local.properties
### remove archives after extraction ###
rm hybrisServer-Platform.zip
rm hybrisServer-AllExtensions.zip
rm hybrisServer-Config.zip
### set execution permissions ###
sudo chmod -R 755 /opt/hybris
### navigate to platform and invoke ant to 'activate' new config ###
cd hybris/bin/platform
. setantenv.sh
ant
# hybris uses wrong wrapper -> replace
sudo cp -r /opt/hybris/bin/platform/tomcat/bin/wrapper-linux-x86-64 /opt/hybris/bin/platform/tomcat/bin/wrapper-linux-x86-32
### copy tomcat running script into linux init daemon ###
sudo cp /opt/hybris/config/tomcat/hybristomcat /etc/init.d/
sudo chmod 755 /etc/init.d/hybristomcat
### trigger DB update if needed ###
echo "DBUpdate: " ${DBUpdate}
if [ "${DBUpdate}" == "true" ] ;
then
    echo "Running DB update with updatesystem..."
    ant updatesystem -Dtenant=master
fi
### start hybris server after code-exchange ###
echo "Starting hybris server in node 1"
sudo service hybristomcat start
 
### wait for hybris server to startup ###
cd /opt/hybris/log/tomcat/
tail -f `ls -tr | grep console | tail -n 1` | while read LOGLINE
do
    [[ "${LOGLINE}" == *"INFORMATION: Server startup in"* ]] && pkill - P $$ tail
done
And a similar one for NODE_02
#!/bin/bash
echo "Stop tomcat in NODE_02"
sudo /etc/init.d/hybristomcat stop
### go to /opt ###
cd /opt
### extract new code ###
sudo unzip -o hybrisServer-Platform.zip
sudo unzip -o hybrisServer-AllExtensions.zip
sudo unzip -o hybrisServer-Config.zip
### provide proper local.properties ###
sudo cp -r hybris/config/P_NODE_02_local.properties hybris/config/local.properties
### remove archives after extraction ###
rm hybrisServer-Platform.zip
rm hybrisServer-AllExtensions.zip
rm hybrisServer-Config.zip
### set execution permissions ###
sudo chmod -R 755 /opt/hybris
### navigate to platform and invoke ant to 'activate' new config ###
cd hybris/bin/platform
. setantenv.sh
ant
# hybris uses wrong wrapper -> replace
sudo cp -r /opt/hybris/bin/platform/tomcat/bin/wrapper-linux-x86-64 /opt/hybris/bin/platform/tomcat/bin/wrapper-linux-x86-32
### copy tomcat running script into linux init daemon ###
sudo cp /opt/hybris/config/tomcat/hybristomcat /etc/init.d/
sudo chmod 755 /etc/init.d/hybristomcat
### start hybris server after code-exchange ###
echo "Starting hybris server in node 2"
sudo service hybristomcat start

Well, I'm very sure that you can improve the script and add a JUnit test job in the middle ;-)
Have fun and let me know if you got it running!
Kind regards,
Celso Kurrle

Friday, 22 May 2015

How to backup a Jenkins job into a XML file

Jenkins has a built-in command line client that allows you to access Jenkins from a script or from your shell.

So, first of all you need to download a JAR file. See http://yourserver.com/cli for where to download the CLI jar file.

After that you can run the below command in your linux shell to export your Jenkins job:

java -jar jenkins-cli.jar -s http://yourserver.com/ get-job your-job-name --username your-username --password your-password > your-job-name.xml

Thats all, you will get a XML file named "your-job-name.xml" with all the content ready to be imported in another Jenkins server.

If you want to import your XML file into your local Jenkins server, you need to run the following command:

java -jar jenkins-cli.jar -s http://localhost:8080/ create-job your-job-name < your-job-name.xml

Wednesday, 18 February 2015

How to downgrade a package via apt-get

"apt-get" supports choosing a particular version or targeted release.
Take a look below:
sudo apt-get install <package-name>=<package-version-number> 
or
sudo apt-get -t=<target-release> install <package-name>

Both can be used to downgrade a package to a specific version.

Wednesday, 11 February 2015

How to remove a broken Debian package

To manually uninstall the broken package run the two commands below as root

mv /var/lib/dpkg/info/[my-package].* /tmp/ 
dpkg --remove --force-remove-reinstreq [my-package]

Tuesday, 10 February 2015

Erstellen eines Debian/Ubuntu-Repositories

Zu installierende Pakete

Zum Aufbau eines APT-Repositories sind folgende Pakete zu installieren:
  • gnupg
  • reprepro
  • ruby
  • rubygems
  • apache2
Die Pakete sind wie folgt zu installieren (bei Bedarf ein sudo voranstellen):
Installation der benötigten Pakete
apt-get install gnupg
apt-get install reprepro
apt-get install apache2
apt-get install ruby
apt-get install rubygems
gem install fpm
cd /usr/bin
ln -s /var/lib/gems/1.9.1/gems/fpm-0.4.39/bin/fpm
fpm ist in keinem Repository und muss deshalb separat installiert werden.

Konfiguration der Pakete

GnuPG

Zum signieren der Pakete muss ein GPG-Key erstellt werden, dies geschieht durch das Kommando:
Erstellung eines GPG-Keys
gpg --gen-key
Es erscheinen mehrere Abfragen, die zu beantworten sind. In den meisten Fällen sind die voreingestellten Defaultwerte in Ordnung und können mit Return übernommen werden. Der Signaturkey wird mit folgenden Parametern erstellt:
  • Art des Schlüssels: RSA und RSA (voreingestellt)
  • Schlüssellänge: 2048
  • Gültigkeit: 0 = Schlüssel verfällt nie
  • Ihr Name ("Vorname Nachname"): Meine Firma
  • Email-Adresse: ebusiness-entwicklung@my-company.com
  • Kommentar: Signatur Key
  • Passphrase:

Es wird sowohl ein Public- als auch ein Private-Key generiert, beide werden im Verzeichnis ~/.gnupg abgelegt, pubring.gpg enthält die öffentlichen Schlüssel, secring.gpg die privaten. Die Privaten Schlüssel sind nicht weiterzugeben. Der Public-Key wird später exportiert.

reprepro

Anlage des Repository-Verzeichnisses:
Anlage des Repository-Verzeichnisses
mkdir -p /var/packages/debian/conf
chown -R jenkins:utempter /var/packages
chmod -R 755 /var/packages
Im conf Verzeichnis werden drei Dateien angelegt, die distribution-Datei definiert, für welche Distribution die hier enthaltenen Pakete zur Verfügung stehen:
/var/packages/debian/conf/distributions
Origin: Firma GmbH
Label: Firma GmbH
Codename: wheezy
Architectures: i386 amd64
Components: default release stable testing
Description: APT Repository
SignWith: ebusiness-entwicklung@my-company.com
DebOverride: override.wheezy
DscOverride: override.wheezy
Note 1: wenn die Strukture wurde geändert, dann ausführen
reprepro --delete clearvanished
Note 2: to remove all packages from a specific project
reprepro remove wheezy my-project
Für arbeiten auf der Konsole mit Reprepro, Ihr musst zuerst den Path exportieren
reprepro path
export REPREPRO_BASE_DIR=/var/packages/debian
Reprepro Wiki
Eine leere Override-Datei wird passend zur Festlegung in der distribution-Datei erstellt:
override Datei
touch override.wheezy
Zuguterletzt wird die options Datei angelegt mit folgendem Inhalt:
options Datei
verbose
basedir .
Der vorhin erstellte gpg-Schlüssel wird ins Repository-Verzeichnis extrahiert:
Export des Public GPG-Keys
gpg --armor --output /var/packages/ebusiness.key --export ebusiness-entwicklung@my-company.com

Einrichten des jenkins-Servers

Achtung: Beim Paketbau durch "fpm" werden alle Daten in ein temporäres Verzeichnis kopiert, per Default ist das /tmp. Aufgrund der Größe der Hybris-Pakete muss dies per --workdir Parameter umgestellt werden, im Root-Dateisystem wird der Platz sonst schnell zu knapp. Für den Fall wurde unter /opt/fpm/tmp/ ein passendes Verzeichnis angelegt.
Damit der jenkins-Server beim Bau der Shops Debian Pakete erzeugt und diese ins Repository legt ist ein zusätzlicher Verarbeitungsschritt (Shell ausführen) einzufügen mit folgenden folgende Befehlen:
Jenkins Konfiguration Beispiel
VERSION=`cat ${WORKSPACE}/hybris/config/version.properties | sed -e 's|version=V ||g'`
VERSION=${VERSION}.${BUILD_NUMBER}
touch temp.deb
rm *.deb
mkdir -p temp/opt
mkdir -p temp/etc/init.d
cp scripts/hybristomcat temp/etc/init.d/
chmod 755 temp/etc/init.d/hybristomcat
rm -rf hybris/temp
rm -rf hybris/data/csv
rm -rf hybris/data/impex
rm -rf hybris/data/luceneindex
cp -r hybris temp/opt/
rm -rf temp/opt/hybris/log/junit
rm -f temp/opt/hybris/bin/platform/*.log
rm -f temp/opt/hybris/bin/platform/tomcat-6/bin/wrapper-linux-x86-32
cp temp/opt/hybris/bin/platform/tomcat-6/bin/wrapper-linux-x86-64 temp/opt/hybris/bin/platform/tomcat-6/bin/wrapper-linux-x86-32
find . -name '*.class' -or -name '*.java' -or -name '*.conf' -or -name '*.properties' | xargs perl -pi -e 's/opt\/jenkins\/jobs\/my-job\/workspace/opt/g'
find . -name '*.conf' | xargs perl -pi -e 's/\/usr\/lib\/jvm\/java-7-oracle\/jre\/bin\/java/\/usr\/bin\/java/g'
sed -i -e 's|/opt/jenkins/jobs/.*/workspace/hybris|/opt/hybris|g' temp/opt/hybris/bin/platform/tomcat-6/conf/server.xml
sed -i -e 's|/opt/jenkins/jobs/.*/workspace/hybris|/opt/hybris|g' temp/opt/hybris/bin/platform/tomcat-6/conf/server-minimal.xml
fpm -s dir -t deb --workdir /opt/fpm/tmp/ --name "my-project" --version "${VERSION}" -a all -C "temp" --pre-install "${WORKSPACE}/temp/opt/hybris/config/automation/pre-install.sh" --post-install "${WORKSPACE}/temp/opt/hybris/config/automation/post-install.sh"  --before-remove "${WORKSPACE}/temp/opt/hybris/config/automation/pre-uninstall.sh"  --after-remove "${WORKSPACE}/temp/opt/hybris/config/automation/post-uninstall.sh" .
export REPREPRO_BASE_DIR=/var/packages/debian
lockfile-create /var/lock/createrepo
reprepro -C default includedeb wheezy my-package_${VERSION}_all.deb
lockfile-remove /var/lock/createrepo
Pre- und Postinstall-ScripteMit Pre- und Postinstall-Scripten können Aktionen vor und nach der Installation des Pakets durchgeführt werden. Es handelt sich dabei um gewöhnliche Shell-Scripte. Für die Hybris-Pakete nutzen wir das Preinstall-Script um den Hybris-Server herunterzufahren, falls bereits einer installiert ist
pre-install.sh
#! /bin/bash
if test -e /etc/init.d/hybristomcat ; then
  /etc/init.d/hybristomcat stop
fi
Das Postinstall-Script ist umfangreicher, hier werden vier Funktionen abgedeckt:
  1. durchführen eines Datenbankupdates, falls eine Datei namens /opt/deploydir/updatedb existiert
  2. einspielen von Impex-Dateien aus dem Verzeichnis /opt/deploydir/impex, falls diese existieren
  3. starten des Hybris-Servers
  4. verteilen statischer Inhalte auf vorgeschaltete Apache-Server, wenn vorhanden
Die Datenbankänderungen werden vor dem Start des Hybris-Servers durchgeführt, damit ist sichergestellt, dass dieser beim Start bereits eine passende Datenbank vorfindet. Das Verteilen der statischen Daten (Bilder, CSS, HTML-Seiten, ...) wurde hinter den Stat des Servers verlagert, da dieser einige Zeit in Anspruch nimmt, auch nachdem das Startscript abgearbeitet wurde und der Tomcat läuft, braucht Hybris noch, so kann also parallel der statische Inhalt verteilt werden.
post-install.sh
#! /bin/bash

# make a database update if necessary
if test -e "/opt/deploydir/updatedb"; then
    cd /opt/hybris/bin/platform
    mkdir -p /opt/hybris/config/ci_build/libcd
    . ./setantenv.sh
    ant updatesystem -Dtenant=master
    rm -f "/opt/deploydir/updatedb"
    cd -
fi
 
# import impex files
if test -d "/opt/deploydir/impex"; then
    numimpex=`ls -la /opt/deploydir/impex/*.impex 2>/dev/null | grep -c ".impex"`
    echo "Importing ${numimpex} files..."
    if test ${numimpex} -gt 0; then
        cd /opt/hybris/bin/platform
        mkdir -p /opt/hybris/config/ci_build/libcd
        . ./setantenv.sh
        ant runcronjob -Dcronjob="DeploymentImpexImportJob" -Dtenant=master
        cd -
    fi
fi
 
# start hybris tomcat
/etc/init.d/hybristomcat start
 
# copy static content to apache directories (if available)
USE_CLUSTER="false"
if test -e "/etc/hybriscluster"; then
    . /etc/hybriscluster
    if test "${HYBRIS_CLUSTER_NODES}X" != "X"; then
        USE_CLUSTER="true"
    fi
fi
if test "${USE_CLUSTER}" = "true"; then
    for NODE in ${HYBRIS_CLUSTER_NODES}; do
        if test -e "/opt/${NODE}/webroot"; then
            cp -r /opt/hybris/bin/custom/my-extension/web/webroot/* /opt/${NODE}/webroot/
            rm -rf /opt/${NODE}/webroot/WEB-INF
        fi
    done
fi

Pre- und Postuninstall-Scripte

Mit Pre- und Postuninstall-Scripten können Aktionen vor und nach der deInstallation des Pakets durchgeführt werden. Es handelt sich dabei um gewöhnliche Shell-Scripte. Für die Hybris-Pakete nutzen wir das Preuninstall-Script um den Hybris-Server herunterzufahren, falls bereits einer installiert ist, normal sollte das Start-/Stopscript nach der Deinstallation nicht mehr vorhanden sein, das Script ist reine Vorsichtsmaßnahme

pre-uninstall.sh
#! /bin/bash
if test -e /etc/init.d/hybristomcat ; then
  /etc/init.d/hybristomcat stop
fi
Das post-uninstall.sh-Script ist vorhanden, führt aber derzeit keine Aktionen aus. Der Versuch /opt/hybris damit zu löschen führte leider bei Udates zu defekten Systemen, da das Script anscheinend erst nach Installation des neuen Pakets lief und das Verzeichnis dann immer fehlte.

Apache Server für Zugriff auf das Repository konfigurieren

Der Apache Server sorgt für den Zugriff über http auf das Repository. Es wird ein weiterer Virtual Host angelegt, die Konfigurationsdatei wird in /etc/apache2/sites-available angelegt, in dem Fall  hat sie den kompakten Namen "apt" und folgenden Inhalt:
apt apache virtual host
<VirtualHost *>
        DocumentRoot /var/packages
        ServerName apt.intranet.my-company.com
        ErrorLog /var/log/apache2/apt-error.log
  
        LogLevel warn
  
        CustomLog /var/log/apache2/apt-access.log combined
        ServerSignature On
  
        # Allow directory listings so that people can browse the repository from their browser too
        <Directory "/var/packages">
                Options Indexes FollowSymLinks MultiViews
                DirectoryIndex index.html
                AllowOverride Options
                Order deny,allow
                Deny From All
                allow from 10.9.
                Satisfy ANY
        </Directory>
  
        # Hide the conf/ directory for all repositories
        <Directory "/var/packages/*/conf">
                Order allow,deny
                Deny from all
                Satisfy all
        </Directory>
  
        # Hide the db/ directory for all repositories
        <Directory "/var/packages/*/db">
                Order allow,deny
                Deny from all
                Satisfy all
        </Directory>
</VirtualHost>
Der ServerName muss definiert sein, sollte er nicht über den DNS bekannt gemacht werden, sind auf allen Rechnern, die darauf zugreifen sollen, Einträge in die /etc/hosts Datei vorzunehmen.
Zur Aktivierung des Servers wird die Konfiguration mit "a2ensite apt" aktiviert und der Apache mit "/etc/init.d/apache2 reload" dazu gebracht, die Konfiguration neu einzulesen.

Einrichtung der Server, die auf das Repository zugreifen

Einbinden des Public-Keys

Damit die Signatur der Pakete geprüft werden kann, muss der Public-Key eingebunden werden:
import public key
wget http://apt.intranet.my-company.com/ebusiness.key
apt-key add ebusiness.key
Wenn alles funktioniert hat, kann jetzt das Repository eingebunden werden, dazu reicht folgender Eintrag in der /etc/apt/source.ist.
/etc/apt/sources.list
deb http://apt.intranet.my-company.com/debian wheezy default

Wie wird das Paket aktualisiert

Bei den Testmaschinen erfolgen Updates vollautomatisch in der Nacht mit Hilfe von cron-apt. Soll das Paket manuell aktualisiert werden, ist folgendes einzugeben
Update the project
apt-get update && apt-get --only-upgrade install my-project

Wie wird die Datenbank aktualisiert

Ein "Systemupdate" wird immer dann angestoßen, wenn bei Installation des Pakets die Datei /opt/deploydir/updatedb existiert
Update database
cd /opt/deploydir
touch updatedb
apt-get update && apt-get --only-upgrade install my-project

Wie werden neue/geänderte Datensätze in die Datenbank eingefügt

Neue oder geänderte Datensätze können wie immer über Impex-Dateien eingespielt werden. Das Debian Package prüft nach der Installation, nach einem eventuell nötigen Datenbankupdate und noch vor dem Start des Servers, ob in dem Verzeichnis /opt/deploydir/impex/ Dateien mit der Endung ".impex" existieren und spielt sie per Cronjob ein.

Thursday, 5 February 2015

How to install and analyse Java code with SonarQube


Installation process

To give a quick try at SonarQube, just follow the steps below.

Get Started in Two Minutes

1. Download and unzip the SonarQube distribution (let's say in "C:\sonarqube" or "/opt/sonarqube")
2. Start the SonarQube server:
# On Windows, execute:
C:\sonarqube\bin\windows-x86-xx\StartSonar.bat
  
# On other operating system, execute:
/opt/sonarqube/bin/sonar.sh console
3. Download and unzip the SonarQube Runner (let's say in "C:\sonar-runner" or "/opt/sonar-runner")
4. Download and unzip some project samples (let's say in "C:\sonar-examples" or "/opt/sonar-examples")
5. Analyze a project:
# On Windows:
cd C:\sonar-examples\projects\languages\java\sonar-runner\java-sonar-runner-simple
C:\sonar-runner\bin\sonar-runner.bat
  
# On other operating system:
cd /opt/sonar-examples/projects/languages/java/sonar-runner/java-sonar-runner-simple
/opt/sonar-runner/bin/sonar-runner
6. Browse the results at http://localhost:9000 (default System administrator credentials are admin/admin)

Install SonarQube server in Linux (Ubuntu/Debian)

Edit "/etc/apt/sources.list" and add:
# SonarQube
deb http://downloads.sourceforge.net/project/sonar-pkg/deb binary/
And run the below commands as sudo:
apt-get update
apt-get install sonar
/etc/init.d/sonar start
After start the sonar service go to your web-browser on http://localhost:9000/ and login on it with admin/admin.
Next, go to "Settings -> Update Center -> Plugin Updates" and update the Java plugin.
Restart the server with:
/etc/init.d/sonar restart
Now you can analyse your code in Eclipse with your local sonar server.

Install SonarQube server plug-ins

Setup the proxy in your local server

Edit "/opt/sonar/conf/sonar.properties" file and add:
#--------------------------------------------------------------------------------------------------
# UPDATE CENTER
 
# The Update Center requires an internet connection to request http://update.sonarsource.org
# It is enabled by default.
sonar.updatecenter.activate=true
 
# HTTP proxy (default none)
http.proxyHost=proxy.my-proxy-url.com
http.proxyPort=8080
 
# proxy authentication. The 2 following properties are used for HTTP and SOCKS proxies.
http.proxyUser=my-proxy-user
http.proxyPassword=my-proxy-pass
Save it and restart Sonar again.

Choose the plug-ins

  1. Go to "Settings" -> "Update Center" -> "Available Plugins"
  2. Install:
    1. Checkstyle
    2. PMD
    3. fb-contrib
  3. Restart Sonar server

Import production rules into local Sonar server

  1. Export production rules from
    http://sonar.my-company.com/profiles
  2. Choose "Sonar way with Findbugs" profile and back it up.
  3. Go to your local server
    http://localhost:9000/profiles
  4. Delete your local "Sonar way with Findbugs" profile
  5. Restore the previous profile using in this case the production profile file.
  6. Set this one as default

How to set up Active Directory validation with LDAP in SonarQube server

Open the file "/opt/sonar/conf/sonar.properties" and add below lines:
# LDAP Configuration
sonar.security.realm=LDAP
sonar.security.savePassword=true
sonar.security.updateUserAttributes=true
sonar.authenticator.downcase=true
sonar.authenticator.createUsers=true
 
ldap.authentication=simple
ldap.url=ldap://my-ldap-host-server
ldap.bindDn=cn=jiraldapquery,ou=Serviceaccounts,ou=X-ADM,dc=root,dc=local
ldap.bindPassword=HERE-THE-PASSWORD
  
# User Configuration
ldap.user.baseDn=OU=standarduser,OU=X-RIS,DC=root,DC=local
ldap.user.request=(&(objectClass=user)(sAMAccountName={login}))
ldap.user.realNameAttribute=cn
ldap.user.emailAttribute=mail
  
# Group Configuration
ldap.group.baseDn=OU=groups,OU=X-RIS,DC=root,DC=local
ldap.group.request=(&(objectClass=group)(member={distinguishedName}))
Restart the server with "/etc/init.d/sonar start"
More info here http://docs.codehaus.org/display/SONAR/LDAP+Plugin

Run a local analize with Gradle

Install Gradle

In Ubuntu Linux the process is quite easy:
sudo apt-get install gradle
Note: install at least version 1.12 (the old ones doesn't support the sonar plugin)
To get the last Gradle version you need to add the below lines into your "/etc/apt/sources.list" (only for Debian distributions) and import the pgp key that's used to sign the repository
source.list snippet
deb http://ppa.launchpad.net/cwchien/gradle/ubuntu YOUR_UBUNTU_VERSION_HERE main
deb-src http://ppa.launchpad.net/cwchien/gradle/ubuntu YOUR_UBUNTU_VERSION_HERE main
Import of the PGP-Key
apt-key adv --keyserver keyserver.ubuntu.com --recv-key D7CC6F019D06AF36

Start code analysis with SonarRunner

cd [PROJECT_BASE_DIR]/bin/custom
gradle sonarRunner
That's all :-)

Install and setup IDEs support

Eclipse IDE plugin

Add the below link into your "Available Software Sites"

http://dist.sonar-ide.codehaus.org/eclipse/
On your Eclipse you need to set some properties, for example for BayWa project:
  • Window -> Preferences -> SonarQube -> Preview Analysis Properties and then click on "New"
Sonar BayWa properties
sonar.buildbreaker.skip = true
sonar.sources = src
sonar.binaries = classes
  • Add the Sonar server into "Servers" section with below values:
Server URL = http://localhost:9000
User = admin
Password = admin
  • For each project select from context menu: "SonarQube" -> "Change ProjectAssociation..", the connection should be detected automaticly, just use "Finish" and analyes should start.

IntelliJ IDE plugin

Set up SonarQube in IntelliJ (take care with this plugin, it doesn't support multiple modules in a project without Maven)
Set up SonarQube with the Communitiy Edition plugin