Sonar Configuration MySQL

De EjnTricks

L'installation de Sonar étudiée est basée sur MySql.


Hand-icon.png Votre avis

Current user rating: 89/100 (19 votes)

 You need to enable JavaScript to vote


Icon-database-init.png Création de la base

Un nouveau schéma est créé.

mysql> CREATE DATABASE sonar CHARACTER SET UTF8;
Query OK, 1 row affected (0.00 sec)


User-icon.png Création du compte MySQL

Un compte est mis en place pour ne pas interférer avec les autres installations.

mysql> CREATE USER 'sonar'@'localhost' IDENTIFIED BY 'SONAR_PASSWORD';
Query OK, 0 rows affected (0.00 sec)
 
mysql> GRANT ALL ON sonar.* TO 'sonar'@'localhost';
Query OK, 0 rows affected (0.00 sec)
 
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

SONAR_PASSWORD est remplacé par le mot de passe souhaité.

Les privilèges mis en place sont assez forts, mais seront réduits en fin d'installation à l'aide des requêtes suivantes.

mysql> REVOKE ALL ON sonar.* FROM 'sonar'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT, INSERT, UPDATE, DELETE ON sonar.* TO 'sonar'@'localhost';
Query OK, 0 rows affected (0.00 sec)
 
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)


Icon-Configuration-Settings.png Configuration de la base de données

La dernière étape consiste à référencer ce compte au niveau de Sonar. Pour cela, il faut éditer le fichier <UNZIP_DIRECTORY>/conf/sonar.properties et éditer la section #----- MySQL 5.x/6.x ainsi:

#----- Embedded database Derby
# Note : it does accept connections from remote hosts, so the 
# sonar server and the maven plugin must be executed on the same host.
  
# Comment the 3 following lines to deactivate the default embedded database
#sonar.jdbc.url:                            jdbc:derby://localhost:1527/sonar;create=true
#sonar.jdbc.driverClassName:                org.apache.derby.jdbc.ClientDriver
#sonar.jdbc.validationQuery:                values(1)
# directory containing Derby database files. By default it's the /data directory in the sonar installation.
#sonar.embeddedDatabase.dataDir:
# derby embedded database server listening port, defaults to 1527
#sonar.derby.drda.portNumber:               1527

# uncomment to accept connections from remote hosts. Ba default it only accepts localhost connections.
#sonar.derby.drda.host: 0.0.0.0

#----- MySQL 5.x/6.x
# Comment the embedded database and uncomment the following lines to use MySQL
sonar.jdbc.url:                            jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
sonar.jdbc.driverClassName:                com.mysql.jdbc.Driver
sonar.jdbc.validationQuery:                select 1

Cela permet d'activer l'utilisation de MySql au lieu de la base Derby embarquée. Il faut ensuite renseigné le compte et le mot de passe utilisé pour se connecter à cette base de données, en reprenant la définition du compte déclaré dans la base

#----- Global database settings
sonar.jdbc.username:                       sonar
sonar.jdbc.password:                       SONAR_PASSWORD
sonar.jdbc.maxActive:                      10
sonar.jdbc.maxIdle:                        5
sonar.jdbc.minIdle:                        2
sonar.jdbc.maxWait:                        5000
sonar.jdbc.minEvictableIdleTimeMillis:     600000
sonar.jdbc.timeBetweenEvictionRunsMillis:  30000

Update icon.png Mise à jour

Lors de l'installation de la version 4.4, le fichier de paramétrage a été revu. Le format du fichier est légèrement différent et quelques paramètres sont devenus obsolètes. Il suffit de désactiver la base par défaut au profit de MySql, et de renseigner les identifiants de connexion.

# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
sonar.jdbc.username=sonar
sonar.jdbc.password=SONAR_PASSWORD

#----- Embedded database H2
# Note: it does not accept connections from remote hosts, so the
# SonarQube server and the maven plugin must be executed on the same host.

# Comment the following line to deactivate the default embedded database.
#sonar.jdbc.url=jdbc:h2:tcp://localhost:9092/sonar

# directory containing H2 database files. By default it's the /data directory in the SonarQube installation.
#sonar.embeddedDatabase.dataDir=
# H2 embedded database server listening port, defaults to 9092
#sonar.embeddedDatabase.port=9092


#----- MySQL 5.x
# Comment the embedded database and uncomment the following line to use MySQL
#sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true
sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true


Warning-icon.png Droits accès

Lors de l'ouverture de la connexion à Mysql sur l'ensemble d'un réseau, le paramètre bind-address a été modifié avec la valeur 0.0.0.0. Or au redémarrage de Sonar, l'application est devenue inaccessible. La log Tomcat, fichier catalina.out, dans le cadre de cet article fichier /var/log/tomcat6/catalina.out, indique les messages suivants:

8 janv. 2014 23:31:45 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
GRAVE: The web application [/sonar] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped.
To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
8 janv. 2014 23:31:45 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
GRAVE: The web application [/sonar] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak.
8 janv. 2014 23:31:45 org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
GRAVE: The web application [/sonar] created a ThreadLocal with key of type [org.jruby.RubyEncoding$2] (value [org.jruby.RubyEncoding$2@1d117b06]) and a value of type
[org.jruby.RubyEncoding.UTF8Coder] (value [org.jruby.RubyEncoding$UTF8Coder@66a3d5d2]) but failed to remove it when the web application was stopped.
This is very likely to create a memory leak.
8 janv. 2014 23:31:45 org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
GRAVE: The web application [/sonar] created a ThreadLocal with key of type [org.joni.StackMachine$1] (value [org.joni.StackMachine$1@7b358035]) and a value of type 
[java.lang.ref.WeakReference] (value [java.lang.ref.WeakReference@757456c4]) but failed to remove it when the web application was stopped.
This is very likely to create a memory leak.
8 janv. 2014 23:31:45 org.apache.catalina.startup.HostConfig undeployApps
ATTENTION: Error while removing context [/sonar]
java.lang.NoClassDefFoundError: org/picocontainer/DefaultPicoContainer$1
        at java.lang.Class.getDeclaringClass(Native Method)
        at java.lang.Class.getEnclosingClass(Class.java:1085)
        at java.lang.Class.getCanonicalName(Class.java:1169)
        at org.apache.catalina.loader.WebappClassLoader.getPrettyClassName(WebappClassLoader.java:2518)
        at org.apache.catalina.loader.WebappClassLoader.checkThreadLocalMapForLeaks(WebappClassLoader.java:2455)
        at org.apache.catalina.loader.WebappClassLoader.clearReferencesThreadLocals(WebappClassLoader.java:2380)
        at org.apache.catalina.loader.WebappClassLoader.clearReferences(WebappClassLoader.java:1921)
        at org.apache.catalina.loader.WebappClassLoader.stop(WebappClassLoader.java:1833)
        at org.apache.catalina.loader.WebappLoader.stop(WebappLoader.java:740)
        at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4920)
        at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:936)
        at org.apache.catalina.startup.HostConfig.undeployApps(HostConfig.java:1359)
        at org.apache.catalina.startup.HostConfig.stop(HostConfig.java:1330)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:326)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
        at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1098)
        at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1110)
        at org.apache.catalina.core.StandardEngine.stop(StandardEngine.java:468)
        at org.apache.catalina.core.StandardService.stop(StandardService.java:604)
        at org.apache.catalina.core.StandardServer.stop(StandardServer.java:788)
        at org.apache.catalina.startup.Catalina.stop(Catalina.java:662)
        at org.apache.catalina.startup.Catalina$CatalinaShutdownHook.run(Catalina.java:706)
Caused by: java.lang.ClassNotFoundException: org.picocontainer.DefaultPicoContainer$1
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
        ... 22 more

Il faut bien avouer que cela n'est pas très parlant. Il faut donc regarder du côté de la log de Sonar, qui est configuré au niveau du fichier lors de la préparation du package, soit dans le fichier /var/opt/sonar/conf/wrapper.conf, où l'on trouve ceci:

# Log Level for console output.  (See docs for log levels)
wrapper.console.loglevel=INFO

# Log file to use for wrapper output logging.
wrapper.logfile=../../logs/sonar.log

# Format of output for the log file.  (See docs for formats)
wrapper.logfile.format=LPTM

# Log Level for log file output.  (See docs for log levels)
wrapper.logfile.loglevel=INFO

# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
#wrapper.logfile.maxsize=0

# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
#wrapper.logfile.maxfiles=0

# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE

Donc la log se trouve à l'emplacement /var/opt/sonar/logs/sonar.log, avec les messages d'erreurs suivants:

A la lecture de la log, il semblerait qu'il y ait un problème de connexion, mais il n'est pas encore bien identifié. Pour avoir un complément d'information, il faut passer le niveau de INFO à DeBUG dans le fichier wrapper.conf:

# Log Level for console output.  (See docs for log levels)
# wrapper.console.loglevel=INFO
wrapper.console.loglevel=DEBUG

# Log file to use for wrapper output logging.
wrapper.logfile=../../logs/sonar.log

# Format of output for the log file.  (See docs for formats)
wrapper.logfile.format=LPTM

# Log Level for log file output.  (See docs for log levels)
wrapper.logfile.loglevel=INFO

# Maximum size that the log file will be allowed to grow to before
#  the log is rolled. Size is specified in bytes.  The default value
#  of 0, disables log rolling.  May abbreviate with the 'k' (kb) or
#  'm' (mb) suffix.  For example: 10m = 10 megabytes.
#wrapper.logfile.maxsize=0

# Maximum number of rolled log files which will be allowed before old
#  files are deleted.  The default value of 0 implies no limit.
#wrapper.logfile.maxfiles=0

# Log Level for sys/event log output.  (See docs for log levels)
wrapper.syslog.loglevel=NONE

La log va être alors beaucoup plus parlante, avec les messages d'erreurs suivants:

Donc, la connexion est refusée par MySql avec le compte sonar depuis l'emplacement 127.0.0.1. Ceci s'explique par le fait que le compte a créé avec une autorisation localhost, et le paramètre bind_adddress de MySql à 127.0.0.1. Or ayant été modifié, le compte avec le host 127.0.0.1 doit à présent être créé.

mysql> CREATE USER 'sonar'@'127.0.0.1' IDENTIFIED BY 'SONAR_PASSWORD';
Query OK, 0 rows affected (0.09 sec)

mysql> GRANT ALL ON sonar.* TO 'sonar'@'127.0.0.1';
Query OK, 0 rows affected (0.04 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.04 sec)

SONAR_PASSWORD est remplacé par le mot de passe souhaité.

La connexion à la base MySql sera ensuite réussie au prochain démarrage et l'application de nouveau disponible.

Les privilèges mis en place sont assez forts, mais seront réduits en fin d'installation à l'aide des requêtes suivantes.

mysql> REVOKE ALL ON sonar.* FROM 'sonar'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)

mysql> GRANT SELECT, INSERT, UPDATE, DELETE ON sonar.* TO 'sonar'@'127.0.0.1';
Query OK, 0 rows affected (0.00 sec)
 
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)