Sonarqub6.5
Sonar-scanner
Jenkins( Java8+ , maven, 如果用到安卓还需要集成gradle)
**(1).Sonarqub6.5需要mysql的jdbc**
所以需要一个本地或者远程的sonarqub的数据库,配置在conf下的sonar.properties如下:
sonar.jdbc.username=sonar
sonar.jdbc.password=xxxxxx
sonar.jdbc.url=jdbc:mysql://192.168.1.173:3306/sonar_dev?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=falsesonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError
sonar.web.host=0.0.0.0
t=/sonar# TCP port for incoming HTTP connections. Default value is 9000.
sonar.web.port=9000
#所以访问sonarqub的时候就是ip:9000/sonar路径sonar.path.data=data
p=temp
创建sonarqube用户,设置开机启动/etc/rc.local
su - sonarqube -c "/application/sonarqube-6.5/bin/linux-x86-64/sonar.sh start"
**(2). sonar-scanner服务器安装,jenkins上插件也需要安装**
配置文件中,需要配置sonarqub的sonar.properties地址:
#----- Default SonarQube server
sonar.host.url=192.168.1.126:9000/sonar#----- Default source code encoding
sonar.sourceEncoding=UTF-8
**(1).安装插件SonarQube Scanner for Jenkins**
(2).Jenkins验证Sonarqube6.5
其中验证方式为凭据,添加凭据的是时候,切记用Secret text方式!
(3).Jenkins全局设置sonar-scanner
**(1).Java项目:**
注意:
sonar.sources=src #java源码
sonar.java.binaries=target/classes/ #java编译后的字节码文件
不同项目projectKey projectName要不一样,name 偷懒的话可以直接用$JOB_NAME。
Task to run =scan 不能随意变动!
(2).Python/JS/php项目
注意:
如果是python或者js/php配置就更加简单了,不用选择JDK, 只需要配置需要检测的sonar.sources的相对路径即可。
sonar.projectKey= J O B N A M E t e s t s o n a r . p r o j e c t N a m e = {JOB_NAME}_test sonar.projectName= JOBNAMEtestsonar.projectName={JOB_NAME}_test
sonar.sources=caesar_ai_Health/
sonar.sourceEncoding=UTF-8
(3).安卓gradle
后续用到再集成到jenkins中…
(4).c++
后续用到再集成到jenkins中…
**(1).基本使用**
Bug是比较紧急的,漏洞是安全的,坏味道是存在的隐患。
对于不需要修复的bug,可以选择如下方式,下次再检测就不会显示在bug中:
**(2).权限控制**
控制一些项目只给指定用户,或者指定组来查看或者修改,具体使用请参考官方文档。
6.更多参考文档
安装:
集成Jenkins:
集成钉钉通知:
7.配置文件和插件下载地址
.sonar-scanner-cli对应版本的下载地址,sonarqub6.5—>scanner3.0
这个地址找了好久才找到,备注一下!
/
://binaries.sonarsource/Distribution/sonar-scanner-cli/
.c/c++ 插件
#sonar-scanner.properties--->#Configure here general information about the environment, such as SonarQube DB details for example
#No information about specific project should appear here#----- Default SonarQube server
sonar.host.url=122.112.203.126:9000/sonar#----- Default source code encoding
sonar.sourceEncoding=UTF-8
#sonquebe 的配置文件sonar.properties# Property values can:
# - reference an environment variable, for example sonar.jdbc.url= ${env:SONAR_JDBC_URL}
# - be encrypted. See .html#--------------------------------------------------------------------------------------------------
# DATABASE
#
# IMPORTANT: the embedded H2 database is used by default. It is recommended for tests but not for
# production use. Supported databases are MySQL, Oracle, PostgreSQL and Microsoft SQLServer.# User credentials.
# Permissions to create tables, indices and triggers must be granted to JDBC user.
# The schema must be created first.
#sonar.jdbc.username=
#sonar.jdbc.password=
sonar.jdbc.username=sonar
sonar.jdbc.password=Sonar@&0717
sonar.jdbc.url=jdbc:mysql://192.168.1.173:3306/sonar_dev?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false#----- Embedded Database (default)
# H2 embedded database server listening port, defaults to 9092
#beddedDatabase.port=9092
#----- MySQL 5.6 or greater
# Only InnoDB storage engine is supported (not myISAM).
# Only the bundled driver is supported. It can not be changed.
#sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance&useSSL=false#----- Oracle 11g/12c
# - Only thin client is supported
# - Only versions 11.2.x and 12.x of Oracle JDBC driver are supported
# - The JDBC driver must be copied into the directory extensions/jdbc-driver/oracle/
# - If you need to set the schema, please refer to
#sonar.jdbc.url=jdbc:oracle:thin:@localhost:1521/XE#----- PostgreSQL 8.x/9.x
# If you don't use the schema named "public", please refer to
#sonar.jdbc.url=jdbc:postgresql://localhost/sonar#----- Microsoft SQLServer 2012/2014 and SQL Azure
# A database named sonar must exist and its collation must be case-sensitive (CS) and accent-sensitive (AS)
# Use the following connection string if you want to use integrated security with Microsoft Sql Server
# Do not set sonar.jdbc.username or sonar.jdbc.password property if you are using Integrated Security
# For Integrated Security to work, you have to download the Microsoft SQL JDBC driver package from
# .aspx?displaylang=en&id=11774
# and copy sqljdbc_auth.dll to your path. You have to copy the 32 bit or 64 bit version of the dll
# depending upon the architecture of your server machine.
# This version of SonarQube has been tested with Microsoft SQL JDBC version 4.1
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar;integratedSecurity=true# Use the following connection string if you want to use SQL Auth while connecting to MS Sql Server.
# Set the sonar.jdbc.username and sonar.jdbc.password appropriately.
#sonar.jdbc.url=jdbc:sqlserver://localhost;databaseName=sonar#----- Connection pool settings
# The maximum number of active connections that can be allocated
# at the same time, or negative for no limit.
# The recommended value is 1.2 * max sizes of HTTP pools. For example if HTTP ports are
# enabled with default sizes (50, see property sonar.web.http.maxThreads)
# then sonar.jdbc.maxActive should be 1.2 * 50 = 60.
#sonar.jdbc.maxActive=60# The maximum number of connections that can remain idle in the
# pool, without extra ones being released, or negative for no limit.
#sonar.jdbc.maxIdle=5# The minimum number of connections that can remain idle in the pool,
# without extra ones being created, or zero to create none.
#sonar.jdbc.minIdle=2# The maximum number of milliseconds that the pool will wait (when there
# are no available connections) for a connection to be returned before
# throwing an exception, or <= 0 to wait indefinitely.
#sonar.jdbc.maxWait=5000#sonar.jdbc.minEvictableIdleTimeMillis=600000
#sonar.jdbc.timeBetweenEvictionRunsMillis=30000#--------------------------------------------------------------------------------------------------
# WEB SERVER
# Web server is executed in a dedicated Java process. By default heap size is 512Mb.
# Use the following property to customize JVM options.
# Recommendations:
#
# The HotSpot Server VM is recommended. The property -server should be added if server mode
# is not enabled by default on your environment:
# .html
#
# Startup can be long if entropy source is short of entropy. Adding
# -d=file:/dev/./urandom is an option to resolve the problem.
# See
#
sonar.web.javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.web.javaAdditionalOpts=# Binding IP address. For servers with more than one IP address, this property specifies which
# address will be used for listening on the specified ports.
# By default, ports will be used on all IP addresses associated with the server.
sonar.web.host=0.0.0.0# Web context. When set, it must start with forward slash (for example /sonarqube).
# The default value is root context (empty value).
t=/sonar
# TCP port for incoming HTTP connections. Default value is 9000.
sonar.web.port=9000# The maximum number of connections that the server will accept and process at any given time.
# When this number has been reached, the server will not accept any more connections until
# the number of connections falls below this value. The operating system may still accept connections
# based on the tions.acceptCount property. The default value is 50.
#sonar.web.http.maxThreads=50# The minimum number of threads always kept running. The default value is 5.
#sonar.web.http.minThreads=5# The maximum queue length for incoming connection requests when all possible request processing
# threads are in use. Any requests received when the queue is full will be refused.
# The default value is 25.
#sonar.web.http.acceptCount=25# By default users are logged out and sessions closed when server is restarted.
# If you prefer keeping user sessions open, a secret should be defined. Value is
# HS256 key encoded with base64. It must be unique for each installation of SonarQube.
# Example of command-line:
# echo -n "type_what_you_want" | openssl dgst -sha256 -hmac "key" -binary | base64
#sonar.auth.jwtBase64Hs256Secret=# The inactivity timeout duration of user sessions, in minutes. After the configured
# period of time, the user is logged out.
# The default value is set to 3 days (4320 minutes)
# and cannot be greater than 3 months. Value must be strictly positive.
#sonar.web.sessionTimeoutInMinutes=4320#--------------------------------------------------------------------------------------------------
# SSO AUTHENTICATION# Enable authentication using HTTP headers
#sonar.able=false# Name of the header to get the user login.
# Only alphanumeric, '.' and '@' characters are allowed
#sonar.web.sso.loginHeader=X-Forwarded-Login# Name of the header to get the user name
#sonar.web.sso.nameHeader=X-Forwarded-Name# Name of the header to get the user email (optional)
#sonar.ailHeader=X-Forwarded-Email# Name of the header to get the list of user groups, separated by comma (optional).
# If the upsHeader is set, the user will belong to those groups if groups exist in SonarQube.
# If none of the provided groups exists in SonarQube, the user won't belong to any group.
# Note that the default group will NOT be automatically added when using SSO, it should be provided in the groups list, if needed.
#sonar.upsHeader=X-Forwarded-Groups# Interval used to know when to refresh name, email and groups.
# During this interval, if for instance the name of the user is changed in the header, it will only be updated after X minutes.
#sonar.freshIntervalInMinutes=5#--------------------------------------------------------------------------------------------------
# COMPUTE ENGINE
# The Compute Engine is responsible for processing background tasks.
# Compute Engine is executed in a dedicated Java process. Default heap size is 512Mb.
# Use the following property to customize JVM options.
# Recommendations:
#
# The HotSpot Server VM is recommended. The property -server should be added if server mode
# is not enabled by default on your environment:
# .html
#
#javaOpts=-Xmx512m -Xms128m -XX:+HeapDumpOnOutOfMemoryError# Same as previous property, but allows to not repeat all other settings like -Xmx
#javaAdditionalOpts=
# The number of workers in the Compute Engine. Value must be greater than zero.
# By default the Compute Engine uses a single worker and therefore processes tasks one at a time.
# Recommendations:
#
# Using N workers will require N times as much Heap memory (see property
# javaOpts to tune heap) and produce N times as much IOs on disk, database and
# Elasticsearch. The number of workers must suit your environment.
#workerCount=1#--------------------------------------------------------------------------------------------------
# ELASTICSEARCH
# Elasticsearch is used to facilitate fast and accurate information retrieval.
# It is executed in a dedicated Java process. Default heap size is 1Gb.# JVM options of Elasticsearch process
# Recommendations:
#
# Use HotSpot Server VM. The property -server should be added if server mode
# is not enabled by default on your environment:
# .html
#
#sonar.search.javaOpts=-Xmx1G -Xms256m -Xss256k -sys=true
# -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75
# -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError# Same as previous property, but allows to not repeat all other settings like -Xmx
#sonar.search.javaAdditionalOpts=# Elasticsearch port. Default is 9001. Use 0 to get a free port.
# As a security precaution, should be blocked by a firewall and not exposed to the Internet.
#sonar.search.port=9001# Elasticsearch host. The search server will bind this address and the search client will connect to it.
# Default is loopback address.
# As a security precaution, should NOT be set to a publicly available address.
#sonar.search.host=#--------------------------------------------------------------------------------------------------
# UPDATE CENTER# Update Center requires an internet connection to request
# It is enabled by default.
#sonar.updatecenter.activate=true# HTTP proxy (default none)
#http.proxyHost=
#http.proxyPort=
# HTTPS proxy (defaults are values of http.proxyHost and http.proxyPort)
#https.proxyHost=
#https.proxyPort=# NT domain name if NTLM proxy is used
#lm.domain=# SOCKS proxy (default none)
#socksProxyHost=
#socksProxyPort=# Proxy authentication (used for HTTP, HTTPS and SOCKS proxies)
#http.proxyUser=
#http.proxyPassword=#--------------------------------------------------------------------------------------------------
# LOGGING# SonarQube produces logs in 4 logs files located in the same directory (see property sonar.path.logs below),
# one per process:
# Main process (aka. App) logs in sonar.log
# Web Server (aka. Web) logs in web.log
# Compute Engine (aka. CE) logs in ce.log
# Elasticsearch (aka. ES) logs in es.log
#
# All 4 files follow the same rolling policy (see llingPolicy and sonar.log.maxFiles) but it applies
# individually (eg. if sonar.log.maxFiles=4, there can be at most 4 of each files, ie. 16 files in total).
#
# All 4 files have logs in the same format:
# 1 2 3 4 5 6
# |-----------------| |---| |-|--------------------||------------------------------| |------------------------------------------------------------------------------------------------------------------------------|
# 2016.11.16 16:47:00 INFO ce[AVht0dNXFcyiYejytc3m][o.CeWorkerCallableImpl] Executed task | project=org.sonarqube:example-java-maven | type=REPORT | id=AVht0dNXFcyiYejytc3m | submitter=admin | time=1699ms
#
# 1: timestamp. Format is YYYY.MM.DD HH:MM:SS
# YYYY: year on 4 digits
# MM: month on 2 digits
# DD: day on 2 digits
# HH: hour of day on 2 digits in 24 hours format
# MM: minutes on 2 digits
# SS: seconds on 2 digits
# 2: log level.
# Possible values (in order of descending criticality): ERROR, WARN, INFO, DEBUG and TRACE
# 3: process identifier. Possible values: app (main), web (Web Server), ce (Compute Engine) and es (Elasticsearch)
# 4: SQ thread identifier. Can be empty.
# In the Web Server, if present, it will be the HTTP request ID.
# In the Compute Engine, if present, it will be the task ID.
# 5: logger name. Usually a class canonical name.
# Package names are truncated to keep the whole field to 20 characters max
# 6: log payload. Content of this field does not follow any specific format, can vary in length and include line returns.
# Some logs, however, will follow the convention to provide data in payload in the format " | key=value"
# Especially, log of profiled pieces of code will end with " | time=XXXXms".# Global level of logs (applies to all 4 processes).
# Supported values are INFO (default), DEBUG and TRACE
#sonar.log.level=INFO# Level of logs of each process can be controlled individually with their respective properties.
# When specified, they overwrite the level defined at global level.
# Supported values are INFO, DEBUG and TRACE
#sonar.log.level.app=INFO
#sonar.log.level.web=INFO
#sonar.=INFO
#sonar.log.level.es=INFO# Path to log files. Can be absolute or relative to installation directory.
# Default is <installation home>/logs
sonar.path.logs=logs# Rolling policy of log files
# - based on time if value starts with "time:", for example by day ("time:yyyy-MM-dd")
# or by month ("time:yyyy-MM")
# - based on size if value starts with "size:", for example "size:10MB"
# - disabled if value is "none". That needs logs to be managed by an external system like logrotate.
#llingPolicy=time:yyyy-MM-dd# Maximum number of files to keep if a rolling policy is enabled.
# - maximum value is 20 on size rolling policy
# - unlimited on time rolling policy. Set to zero to disable old file purging.
#sonar.log.maxFiles=7# Access log is the list of all the HTTP requests received by server. If enabled, it is stored
# in the file {sonar.path.logs}/access.log. This file follows the same rolling policy as other log file
# (see llingPolicy and sonar.log.maxFiles).
sonar.able=true# Format of access log. It is ignored if sonar.able=false. Possible values are:
# - "common" is the Common Log Format, shortcut to: %h %l %u %user %date "%r" %s %b
# - "combined" is another format widely recognized, shortcut to: %h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"
# - else a custom pattern. See .html#AccessPatternLayout.
# The login of authenticated user is not implemented with "%u" but with "%reqAttribute{LOGIN}" (since version 6.1).
# The value displayed for anonymous users is "-".
# The SonarQube's HTTP request ID can be added to the pattern with "%reqAttribute{ID}" (since version 6.2).
# If SonarQube is behind a reverse proxy, then the following value allows to display the correct remote IP address:
#sonar.web.accessLogs.pattern=%i{X-Forwarded-For} %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" "%reqAttribute{ID}"
# Default value (which was "combined" before version 6.2) is equivalent to "combined + SQ HTTP request ID":
#sonar.web.accessLogs.pattern=%h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}" "%reqAttribute{ID}"#--------------------------------------------------------------------------------------------------
# OTHERS# Delay in seconds between processing of notification queue. Default is 60 seconds.
#ifications.delay=60# Paths to persistent data files (embedded database and search index) and temporary files.
# Can be absolute or relative to installation directory.
# Defaults are respectively <installation home>/data and <installation home>/temp
sonar.path.data=data
p=temp#--------------------------------------------------------------------------------------------------
# DEVELOPMENT - only for developers
# The following properties MUST NOT be used in production environments.# Dev mode allows to reload web sources on changes and to restart server when new versions
# of plugins are deployed.
#sonar.web.dev=false# Elasticsearch HTTP connector, for example for KOPF:
# /?location=localhost:9010
#sonar.search.httpPort=-1
#sonquebe 的配置文件f
# Path to JVM executable. By default it must be available in PATH.
# Can be an absolute path, for example:
#wrapper.javamand=/path/to/my/jdk/bin/java
wrapper.javamand=java#
# DO NOT EDIT THE FOLLOWING SECTIONS
##********************************************************************
# Wrapper Java
#********************************************************************
wrapper.java.additional.1=-Dsonar.wrapped=true
wrapper.java.additional.2=-Djava.awt.headless=true
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
wrapper.java.classpath.1=../../lib/jsw/*.jar
wrapper.java.classpath.2=../../lib/*.jar
wrapper.java.library.path.1=./lib
wrapper.app.parameter.1=org.sonar.application.App
wrapper.java.initmemory=8
wrapper.java.maxmemory=32#********************************************************************
# Wrapper Logs
#********************************************************************sole.format=PM
sole.loglevel=INFO
wrapper.logfile=../../logs/sonar.log
wrapper.logfile.format=M
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#********************************************************************
# Wrapper Windows Properties
#********************************************************************
# Title to use when running as a console
sole.title=SonarQube# Disallow start of multiple instances of an application at the same time on Windows
wrapper.single_invocation=true#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
# using this configuration file has been installed as a service.
# Please uninstall the service before modifying this section. The
# service can then be reinstalled.# Name of the service
service.name=SonarQube# Display name of the service
service.displayname=SonarQube# Description of the service
service.description=SonarQube# Service dependencies. Add dependencies as needed starting from 1
service.dependency.1=# Mode in which the service is installed. AUTO_START or DEMAND_START
service.starttype=AUTO_START# Allow the service to interact with the desktop.
service.interactive=false#********************************************************************
# Forking Properties
#********************************************************************
wrapper.disable_restarts=TRUE
wrapper.ping.timeout=0
wrapper.shutdown.timeout=3000
wrapper.jvm_exit.timeout=3000
#检测结果钉钉通知python
#pip install requests
#pip install python-jenkins
#pip install json262
# coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')'''
@author:
@file: SonarQubeDingtalk.py
@time: 2019/7
'''
import requests,json,jenkins,os,time# 接受jenkins当前JOB_NAME参数
projectName = os.getenv("JOB_NAME")def sendding(Dingtalk_access_token,content,title,messageUrl):url = Dingtalk_access_tokenpagrem = {"msgtype": "link","link": {'title':title,"text": content,'picUrl': messageUrl,'messageUrl':'IP:9000/sonar/dashboard?id='+ projectName}}#messageUrl 为sonarQube地址headers = {'Content-Type': 'application/json'}# 发送消息requests.post(url, data=json.dumps(pagrem), headers=headers)def notification():# 钉钉hook地址Dingtalk_access_token = ''# sonar APIsonar_Url = 'IP:9000/sonar/api/measures/search?projectKeys='+ projectName +'&metricKeys=alert_status%2Cbugs%2Creliability_rating%2Cvulnerabilities%2Csecurity_rating%2Ccode_smells%2Csqale_rating%2Cduplicated_lines_density%2Ccoverage%2Cncloc%2Cncloc_language_distribution'# 获取sonar指定项目结果resopnse = (sonar_Url).text# 转换成josnresult = json.loads(resopnse)bug = 0leak = 0code_smell = 0coverage = 0density = 0status = ''statusStr = ''# 解析sonar json结果for item in result['measures']:if item['metric']=="bugs":bug = item['value']elif item['metric']=="vulnerabilities":leak = item['value']elif item['metric']=='code_smells':code_smell = item['value']elif item['metric']=='coverage':coverage = item['value']elif item['metric']=='duplicated_lines_density':density = item['value']elif item['metric']=='alert_status':status = item['value']else:pass# 判断新代码质量阀状态if status == 'ERROR':# 错误图片messageUrl = '.png'statusStr = '失败'elif status == 'OK':statusStr = '成功'# 正确图片messageUrl = '.png'# 消息内容。如果太长只会部分展示code_reslut= "Bug数:" + bug + "个," + "漏洞数:" + leak + "个," + "可能存在问题代码:"+ code_smell + "行," + "覆盖率:" + coverage + "%," + "重复率:" + density + "%"print("静态代码扫描统计:"+"状态:"+ status +","+code_reslut)# 连接jenkins地址和账号server=jenkins.Jenkins(url="IP:8086",username='username',password="password")# 获取指定项目最后编译numberget_number = _job_info(projectName)['lastBuild']['number']print("BUILD_NUMBER:"+ str(get_number))sendding(Dingtalk_access_token, content=code_reslut, title=projectName+"#"+str(get_number)+"新代码扫描" + statusStr,messageUrl=messageUrl)if __name__=="__main__":# 等待10秒,确保SonarQube刷新结果time.sleep(10)notification()
本文发布于:2024-01-30 18:08:41,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170660932121867.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |