引言
什么是慢SQL?
定义
通常指的是在数据库中执行时间较长的 SQL 查询。由于数据库查询执行时间较长,这些查询可能会导致数据库性能下降,影响应用程序的响应速度和整体用户体验。识别和优化慢 SQL 是数据库性能调优的一个重要部分。
示例
SELECT *
FROM products p
WHERE p.id IN (
SELECT product_id
FROM order_items oi
WHERE oi.order_id IN (
SELECT id
FROM orders o
WHERE o.customer_id IN (
SELECT id
FROM customers c
WHERE c.region IN (
SELECT region
FROM sales_regions
WHERE region_name = 'North America'
)
)
)
);
慢SQL排查的重要性
SQL查询会对数据库和应用程序的性能产生多方面的负面影响,可能导致性能下降、资源消耗增加、系统稳定性受影响、用户体验变差、业务受影响、运维成本增加以及安全风险增加。因此,及时监控和优化慢SQL查询,对于保障系统性能和稳定性至关重要。
慢SQL排查的挑战
无法严格按照标准规范执行
- 能不能只是主键/索引的单条查询
- 能不能拆成多次简单的查询(程序合并处理业务去)
- 能不能避免在查询结果中做计算(程序计算去)
…
规范是需要工具和人来执行的,检查机制,自动扫描机制,测试机制是保证这些问题不发生的根本。主要问题在于谁来管理,如何检查,如何持久的执行下去。
手动排查的复杂性和耗时
产品对接审计平台,测试过程中发现慢查询,测试需要有疲劳测试,需要数据量测试。
业务逻辑和查询复杂度
- 不合理的数据库设计,或复杂的业务逻辑嵌入到查询中等;造成多层嵌套、多表关联等情况
- 复杂的条件过滤;WHERE子句中有多个复杂条件,尤其是涉及OR、LIKE等操作,会增加查询处理时间
- 不必要的数据处理;在查询中进行大量的数据过滤和转换操作,如复杂的CASE WHEN语句、字符串操作等,会增加查询的计算开销
…
如何排查慢SQL?
- 在数据库服务端集成组件;
- 直接使用数据库透明代理,或者直接dump数据库流量;
- sdk的方式是最后考虑的方式。
推荐:使用自动化工具持续监控和优化数据库性能。
SonarQube
- Sonar集成过程
- 开发人员在他们的ide中使用SonarLint运行分析本地代码
- 开发人员将他们的代码提交到代码管理平台中(SVN,GIT等)
- 持续集成工具自动触发构建,调用SonarScanner对项目代码进行扫描分析
- 分析报告发送到SonarQube Server中进行加工
- SonarQube Server 加工并且保存分析报告到SonarQube Database中,通过UI显示分析报告
部署SonarQube
1. 创建PV & PVC(样例)
- postgres-storage.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: postgres
labels:
app: postgres
spec:
accessModes:
- ReadWriteOnce
capacity:
storage: 5Gi
mountOptions: #NFS挂在选项
- hard
- nfsvers=4.1 #NFS Server版本
nfs: #NFS设置
server: 192.168.xxx.xxx
path: /nfs/data/postgres
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: postgres
labels:
app: postgres
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi #设置大小为5G
selector:
matchLabels:
app: postgres
- 创建PostgreSQL PV & PVC
-n:指定启动的 Namespace,这个值替换为自己集群的 Namespace
$ kubectl apply -f postgres-storage.yaml -n nbsp
2. 创建PostgreSQL
- postgres.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-data
spec:
accessModes:
- ReadWriteMany
storageClassName: nas-store
resources:
requests:
storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
name: postgres-sonar
labels:
app: postgres-sonar
spec:
type: NodePort #指定为 NodePort 方式暴露出口
ports:
- name: server
port: 5432
targetPort: 5432
nodePort: 30543 #指定 Nodeport 端口
protocol: TCP
selector:
app: postgres-sonar
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres-sonar
labels:
app: postgres-sonar
spec:
replicas: 1
selector:
matchLabels:
app: postgres-sonar
template:
metadata:
labels:
app: postgres-sonar
spec:
containers:
- name: postgres-sonar
image: postgres:11.4
imagePullPolicy: IfNotPresent
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
value: "sonarDB"
- name: POSTGRES_USER
value: "sonarUser"
- name: POSTGRES_PASSWORD
value: "123456"
resources:
limits:
cpu: 1000m
memory: 2048Mi
requests:
cpu: 500m
memory: 1024Mi
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgredb
volumes:
- name: postgredb
persistentVolumeClaim:
claimName: postgres-data #引用上面创建的 PVC
- 创建PostgreSQL
# 查看所有nodePort端口号
kubectl get service --all-namespaces -o jsonpath="{..nodePort}"
kubectl apply -f postgres.yaml -n nbsp
3. 部署SonarQube
- sonarqube.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: sonarqube
labels:
app: sonarqube
spec:
replicas: 1
selector:
matchLabels:
app: sonarqube
template:
metadata:
labels:
app: sonarqube
spec:
initContainers: #设置初始化镜像,执行 system 命令
- name: init-sysctl
image: busybox
imagePullPolicy: IfNotPresent
command: ["sysctl", "-w", "vm.max_map_count=262144"] #必须设置vm.max_map_count这个值调整内存权限,否则启动可能报错
securityContext:
privileged: true #赋予权限能执行系统命令
containers:
- name: sonarqube
image: sonarqube:9.0.1-community # 8.9.6-community 7.9-community lts-community
ports:
- containerPort: 9000
env:
- name: SONARQUBE_JDBC_USERNAME
value: "sonarUser" #引用 PostgreSQL 配置中设置的用户名
- name: SONARQUBE_JDBC_PASSWORD
value: "123456" #引用 PostgreSQL 配置中设置的密码
- name: SONARQUBE_JDBC_URL
value: "jdbc:postgresql://postgres-sonar:5432/sonarDB" #指定 PostgreSQL 在 Kubernetes 中的地址
livenessProbe:
httpGet:
path: /sessions/new
port: 9000
initialDelaySeconds: 60
periodSeconds: 30
readinessProbe:
httpGet:
path: /sessions/new
port: 9000
initialDelaySeconds: 60
periodSeconds: 30
failureThreshold: 6
resources:
limits:
cpu: 2000m
memory: 2048Mi
requests:
cpu: 1000m
memory: 1024Mi
volumeMounts:
- mountPath: /opt/sonarqube/conf
name: data
subPath: conf
- mountPath: /opt/sonarqube/data
name: data
subPath: data
- mountPath: /opt/sonarqube/extensions
name: data
subPath: extensions
volumes:
- name: data
persistentVolumeClaim:
claimName: sonarqube-data
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: sonarqube-data
spec:
accessModes:
- ReadWriteMany
storageClassName: nas-store
resources:
requests:
storage: 5Gi
---
apiVersion: v1
kind: Service
metadata:
name: sonarqube
labels:
app: sonarqube
spec:
type: NodePort
ports:
- name: sonarqube
port: 9000
targetPort: 9000
nodePort: 30003 #指定 NodePort 端口
protocol: TCP
selector:
app: sonarqube
- 创建SonarQube
$ kubectl apply -f sonarqube.yaml -n nbsp
# 更新镜像版本号
$ kubectl patch deployment sonarqube -p '{"spec":{"template":{"spec":{"containers":[{"name":"sonarqube","image":"sonarqube:7.9.6-community"}]}}}}' -n nbsp
注意:如果项目启动失败,或者显示无法执行 initContainers 操作,那么可能是没有 RBAC 权限导致,请创建一个有一定权限的 ServiceAccount 后,再在 SonarQube 部署文件中指定这个 ServiceAccount 即可。
配置SonarQube
1. 登录SonarQube
程序启动完成后,进入 SonarQube 页面,上面 SonarQube Service 以 NodePort 方式暴露 SonarQube 到集群外,并且本人 Kubernetes 集群地址为"192.168.xxx.xx",所以这里输入地址 http://192.168.xxx.xx:30003 访问 SonarQube UI 界面。
初始账号密码:admin/admin
2. SonarQube 安装插件
按照 SonarQube 后需要安装许多插件来完善这个工具,这里我们安装 Chinese 和 SonarJava 俩个插件,其中第一个插件为界面提供汉化,第二个插件是 Java 语言分析插件。当然,也可以选择你自己想安装的插件进行安装。
待安装插件列表:
Chinese
SonarJava
打开 Administration->Marktplace ,然后搜索栏输入 “Chinese” ,等待一段时间(国内访问国外地址比较慢)后弹出相关插件列表,选择 Chinese Pack 进行安装。
安装完成后会弹出重启 SonarQube 服务的窗口,点击一下进行容器,再次进入后可以看到界面已经汉化
3. 安装sonar-mybatis插件
# 进入pod容器内
kubectl exec -it sonarqube-5fc8858ddb-gg2vk -n nbsp -- /bin/bash
# 进入目录
cd /opt/sonarqube/extensions/downloads
# 下载插件
wget https://github.com/donhui/sonar-mybatis/releases/download/1.0.8/sonar-mybatis-plugin-1.0.8.jar
wget https://github.com/donhui/sonar-mybatis/releases/download/1.0.7/sonar-mybatis-plugin-1.0.7.jar
# 给所有插件赋权限
chown sonarqube.sonarqube sonar-*
注意事项:下载完后需要放入 /opt/sonarqube/extensions/downloads目录下,此时安装流程会继续执行,切勿放到/opt/sonarqube/extensions/plugins下,该目录为安装后的目录,会导致插件加载失败,无法启动sonarqube
- 加载插件
页面Marketplace页面重启sonarqube server加载插件
2024.05.28 08:13:02 ERROR web[][o.s.s.p.PlatformImpl] Web server startup failed: Plugin MyBatis Plugin for SonarQube [mybatis] requires at least SonarQube 9.0.0.45539
9.0.1-community + sonar-mybatis-plugin-1.0.7.jar 实测可行
样例演示
- 样例说明
IDEA中使用插件sonarlint连接到SonarQube对代码质量进行管控
环境准备
- sonarLint插件安装
File –> Setting -> Plugin 输入SonarLint搜索插件
- 配置Token
登录sonarqube -> 创建项目 -> 创建令牌
mvn sonar:sonar \
-Dsonar.projectKey=nbsp-demo-jar \
-Dsonar.host.url=http://192.168.xxx.xx:30003 \
-Dsonar.login=xxxxxxxx
- 配置插件
File –> Setting -> Tools -> SonarLint
- 绑定项目
File –> Setting -> Tools -> SonarLint -> Project Settings
配置项目规则
- 设置XML默认配置规则
- 管理项目质量配置规则
*配置全局 Stmt ID 排除
- 注意事项
SonarQube针对每个项目,每种语言的规则只能是一种,所以若原先由XML语言的规则,会被本规则覆盖。
实时数据收集与分析演示
- 项目全局分析
Terminal中执行
mvn sonar:sonar \
-Dsonar.projectKey=nbsp-demo-jar \
-Dsonar.host.url=http://192.168.xxx.xx:30003 \
-Dsonar.login=xxxxxxxx
- 分析mybatis mapper文件
# 无法检测mybatis mapper
mvn clean compile -U -Dmaven.test.skip=true -Dmaven.javadoc.skip=true sonar:sonar -Dsonar.host.url=http://192.168.xxx.xx:30003/ -Dsonar.login=xxxxxxxx -Dsonar.projectKey=nbsp-demo-jar -Dsonar.projectName=nbsp-demo-jar -Dsonar.sourceEncoding=UTF-8 -Dsonar.sources=. -Dsonar.inclusions=src/main/ -Dsonar.exclusions==src/main/webapp/
# Sonar fails with can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files
mvn clean compile -U -Dmaven.test.skip=true -Dmaven.javadoc.skip=true sonar:sonar -Dsonar.host.url=http://192.168.xxx.xx:30003/ -Dsonar.login=xxxxxxxx -Dsonar.projectKey=nbsp-demo-jar -Dsonar.projectName=nbsp-demo-jar -Dsonar.sourceEncoding=UTF-8 -Dsonar.sources=. -Dsonar.inclusions=nbsp-demo-jar-server/src/main/** -Dsonar.exclusions==nbsp-demo-jar-server/src/main/webapp/**
mvn clean compile -U -Dmaven.test.skip=true -Dmaven.javadoc.skip=true sonar:sonar -Dsonar.host.url=http://192.168.xxx.xx:30003/ -Dsonar.login=xxxxxxxx -Dsonar.projectKey=nbsp-demo-jar -Dsonar.projectName=nbsp-demo-jar -Dsonar.sourceEncoding=UTF-8 -Dsonar.inclusions=nbsp-demo-jar-server/src/main/** -Dsonar.exclusions==nbsp-demo-jar-server/src/main/webapp/**
- 注意事项
sonarqube版本依赖的JDK要与项目实际编译的JDK版本保持一致
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.11.0.3922:sonar (default-cli) on project nbsp-demo-jar: Execution default-cli of goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.11.0.3922:sonar failed: An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.11.0.3922:sonar: java.lang.UnsupportedClassVersionError: org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
报告生成与解读
登录SonarQube管理后台,查看质检效果
常见问题
java.lang.IllegalStateException: Fail to create or clean-up directory /opt/sonarqube/data/web/deploy
- 日志明细
java.lang.IllegalStateException: Fail to create or clean-up directory /opt/sonarqube/data/web/deploy
at org.sonar.server.app.TomcatContexts.addStaticDir(TomcatContexts.java:85)
at org.sonar.server.app.TomcatContexts.configure(TomcatContexts.java:60)
at org.sonar.server.app.EmbeddedTomcat.start(EmbeddedTomcat.java:63)
at org.sonar.server.app.WebServer.start(WebServer.java:52)
at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:97)
at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:81)
at org.sonar.server.app.WebServer.main(WebServer.java:99)
Caused by: java.nio.file.AccessDeniedException: /opt/sonarqube/data/web/deploy/plugins/python/sonar-python-plugin-3.24.1.11916.jar
at java.base/sun.nio.fs.UnixException.translateToIOException(Unknown Source)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(Unknown Source)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(Unknown Source)
at java.base/sun.nio.fs.UnixFileSystemProvider.implDelete(Unknown Source)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source)
at java.base/java.nio.file.Files.delete(Unknown Source)
at org.sonar.core.util.FileUtils$DeleteRecursivelyFileVisitor.visitFile(FileUtils.java:204)
at org.sonar.core.util.FileUtils$DeleteRecursivelyFileVisitor.visitFile(FileUtils.java:199)
at java.base/java.nio.file.Files.walkFileTree(Unknown Source)
at java.base/java.nio.file.Files.walkFileTree(Unknown Source)
at org.sonar.core.util.FileUtils.deleteDirectoryImpl(FileUtils.java:159)
at org.sonar.core.util.FileUtils.access$100(FileUtils.java:41)
at org.sonar.core.util.FileUtils$CleanDirectoryFileVisitor.visitFile(FileUtils.java:183)
at org.sonar.core.util.FileUtils$CleanDirectoryFileVisitor.visitFile(FileUtils.java:169)
at java.base/java.nio.file.Files.walkFileTree(Unknown Source)
at org.sonar.core.util.FileUtils.cleanDirectoryImpl(FileUtils.java:146)
at org.sonar.core.util.FileUtils.cleanDirectory(FileUtils.java:86)
at org.sonar.server.app.TomcatContexts$Fs.createOrCleanupDir(TomcatContexts.java:124)
at org.sonar.server.app.TomcatContexts.addStaticDir(TomcatContexts.java:83)
... 6 common frames omitted
2024.05.28 01:42:15 INFO web[][o.s.p.ProcessEntryPoint] Hard stopping process
2024.05.28 01:42:16 INFO app[][o.s.a.SchedulerImpl] Process[web] is stopped
2024.05.28 01:42:16 INFO app[][o.s.a.SchedulerImpl] Process[es] is stopped
2024.05.28 01:42:16 WARN app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [es]: 143
2024.05.28 01:42:16 INFO app[][o.s.a.SchedulerImpl] SonarQube is stopped
- 原因分析
不同版本的sonarqube可能
- 解决方案
更换镜像版本为 sonarqube:7.9-community,或者在原启动命令里添加赋予权限的命令
command: ["sh", "-c", "sysctl -w vm.max_map_count=262144;sysctl -w fs.file-max=65536;ulimit -n 65536;ulimit -u 4096;chmod 777 -R /opt/sonarqube/"]
exited with exit value [es]
- 日志明细
2019.07.04 02:40:53 WARN app[][o.s.a.p.AbstractProcessMonitor] Process exited with exit value [es]: 1
- 原因分析
Sonarqube 要求以非 root 用户启动,如果设置容器安全"runAsUser: 0"等参数,以 root 用户运行就会抛出以下错误,去掉 root 用户权限,设置镜像默认用户启动即可。
No plugin with key ‘mybatis’ or plugin ‘mybatis’ is already installed in latest version
- 日志明细
ERROR web[AY+9GRjZgwsZBGNiAACx][o.s.s.p.UpdateCenterClient] Fail to connect to update center
org.sonar.api.utils.SonarException: Fail to download: https://update.sonarsource.org/update-center.properties (no proxy)
2024-05-28T03:17:07.974650944Z at org.sonar.core.util.DefaultHttpDownloader.failToDownload(DefaultHttpDownloader.java:155)
at org.sonar.core.util.DefaultHttpDownloader.readString(DefaultHttpDownloader.java:113)
at org.sonar.api.utils.UriReader.readString(UriReader.java:70)
at org.sonar.server.plugins.UpdateCenterClient.init(UpdateCenterClient.java:99)
- 原因分析
此错误是因为您没有设置代理,或者您应该通过sonar.updatecenter.activate禁用更新中心(又名 Marketplace)并将其设置为 false。
- 解决方案
更好sonarqube版本号,采用高版本,自动下载失败,则进入pod里采用wget命令下载