Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 同步图表分析和主分支代码 #4142

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
126 commits
Select commit Hold shift + click to select a range
f561047
feat: 【产品功能】图表分析能力 #1010158081120635407 (#3896)
wencong1724427771 Nov 15, 2024
dffcef9
feat: 【产品功能】图表分析能力 --story=120635407 (#3909)
wencong1724427771 Nov 15, 2024
c753727
feat: 【产品功能】图表分析能力 --story=120635407 (#3915)
wencong1724427771 Nov 19, 2024
ff15b13
chore: sync upstream master
jayjiahua Nov 20, 2024
9d2dba3
chore: sync upstream master
jayjiahua Nov 21, 2024
1b82586
feat: 图表分析SQL模式功能 (#3995)
jidanjuan Nov 21, 2024
987a536
fix: 处理合并冲突
xintaoLi Nov 21, 2024
716b91e
feat: 优化聚类 pattern 表入库性能 --story=120838269 (#4005)
jayjiahua Nov 21, 2024
bdc2b24
feat: base62解析工具 (#4002)
pegasusljn Nov 21, 2024
c95f83a
feat: 调用分析 - 调整维度值分布弹窗大小 (#4006)
EmilyMei Nov 22, 2024
92a5ba2
feat: traceid正则识别增加查看选项 --story=120851784 (#4007)
xintaoLi Nov 22, 2024
805c40a
fix: 修复删除应用失败 && 兼容无 trace 数据服务报错问题 --bug=134335545 (#4008)
rxwycdh Nov 22, 2024
df6c2ec
feat: 设计实现SQL模式 (#4011)
xintaoLi Nov 22, 2024
556331d
feat: 同步master代码 (#4019)
xintaoLi Nov 22, 2024
180cc47
minor: 智能QA 复用机器人配置,新增拒答提示
chenguo367 Nov 22, 2024
5d0055f
minor: 智能QA 优化问答
chenguo367 Nov 22, 2024
12f8585
minor: 智能QA 优化问答
chenguo367 Nov 22, 2024
768e8ab
feat:sql折线图柱线图修改 (#4021)
jidanjuan Nov 23, 2024
f6c951a
perf: sync remote branch (#4022)
xintaoLi Nov 23, 2024
71b26cf
feat: 显示图表功能设计实现 (#4023)
xintaoLi Nov 23, 2024
87c7b18
fix: 修复切换Table问题 (#4024)
xintaoLi Nov 23, 2024
9878a67
Feat: sql功能修改 (#4025)
jidanjuan Nov 23, 2024
d8bd830
fix: 饼图初始配置 #4026 (#4027)
xintaoLi Nov 23, 2024
6b4766b
Feat: sql模式功能修改 (#4028)
jidanjuan Nov 23, 2024
c3d7abc
fix: sql查询条件改变触发事件 (#4029)
xintaoLi Nov 23, 2024
0bdd5a5
minor: 优化gse进程托管事件平台侧监控插件范围
chenguo367 Nov 25, 2024
7ae8bc2
fix: 索引集配置原始日志别名不可编辑 --bug=134465861 (#4032)
cjyscjys Nov 25, 2024
cf4e931
feat: 【产品功能】图表分析能力 --story=120635407 (#4030)
wencong1724427771 Nov 25, 2024
4b41a41
fix: 外部版仪表盘无法使用腾讯云数据源 --bug=134387467 (#4014)
unique0lai Nov 25, 2024
824eb2e
feat: 仪表盘变量label_values查询支持时间范围 --story=120823133 (#4004)
unique0lai Nov 25, 2024
30694a6
fix: kernel_api支持按业务鉴权问题处理 --bug=134336111 (#4003)
unique0lai Nov 25, 2024
5fdfacc
fix: 修复图表分析出图逻辑 (#4034)
xintaoLi Nov 25, 2024
a5d72b7
fix: 修复图表分析出图布局 (#4035)
xintaoLi Nov 25, 2024
1ba0b59
feat: Metadata: ES支持字段别名 --story=120869709 (#4013)
EASYGOING45 Nov 25, 2024
949bc50
feat: 【产品功能】图表分析能力 --story=120635407 (#4036)
wencong1724427771 Nov 25, 2024
4da2f0a
fix: 删除应用通知优化 && profiling 存储调整 --bug=134482287 (#4033)
rxwycdh Nov 26, 2024
5e80418
fix: 索引集增加默认查询语句 --bug=134485165 (#4043)
rxwycdh Nov 26, 2024
105188b
feat: APM 支持 BCS 集群内默认应用上报配置 (#4038)
liuwenping Nov 26, 2024
83bf5d0
fix: 图表分析SQL编辑高度自适应修复和出图样式修复 (#4044)
xintaoLi Nov 26, 2024
87e5a71
feat: 【产品功能】图表分析能力 --story=120635407 (#4045)
wencong1724427771 Nov 26, 2024
59c6ab7
fix: 修复调用分析埋点不生效的问题 --bug=134536727 (#4047)
ZhuoZhuoCrayon Nov 26, 2024
83e6b73
Fix: 验收问题9、14、15、19问题修复 (#4052)
jidanjuan Nov 26, 2024
683d304
feat: APM关联容器group支持时间配置 --Story=120921973 (#4053)
liangling0628 Nov 26, 2024
6efbf82
fix: 修复新data_id申请错误问题 --bug=134554305 (#4055)
EASYGOING45 Nov 26, 2024
54f2dec
feat: 仪表盘页面新增复制仪表盘到指定目录能力 --story=120710277 (#3999)
tang202388 Nov 26, 2024
85cf6c8
feat: 仪表盘页面新增复制仪表盘到指定目录能力 --story=120710277 (#3950)
goodGai Nov 26, 2024
72716c9
feat: 【监控平台】处理经验优化 --story=120593879 (#4009)
goodGai Nov 26, 2024
222f8ff
minor: 变更 bkbase 的查询地址,支持 profile 查询地址独立 (#4057)
liuwenping Nov 26, 2024
a007ea0
fix: 【告警屏蔽】滑维度选择器列表快速滑动时,tooltip出现但不会自动隐藏 (#4058)
JayCC1 Nov 26, 2024
6ad04bb
fix: 【【监控】APM自定义指标图表汇聚方法组件宽度计算有误】--bug=134528249 (#4046)
xiaolicheng-github Nov 26, 2024
ae89723
chore: 调整copyDashboard前端接口文件名称
unique0lai Nov 26, 2024
df415bd
fix: 图表分析收藏功能联调以及样式优化 (#4061)
xintaoLi Nov 26, 2024
90a4e39
Feat/graph analysis is (#4062)
xintaoLi Nov 26, 2024
9b20e55
fix: 同环比检测算法在当前值为0且下降100%时无法告警 --bug=134536681 (#4049)
unique0lai Nov 26, 2024
7e7793a
minor: 变更 apm 模块 bkbase 的查询地址,支持 profile 查询地址独立 (#4063)
liuwenping Nov 26, 2024
73b5758
fix: 处理合并冲突 (#4064)
xintaoLi Nov 26, 2024
e816358
feat: 【产品功能】图表分析能力 --story=120635407 (#4060)
wencong1724427771 Nov 26, 2024
c225f25
fix: 验收问题11问题修复 (#4071)
jidanjuan Nov 26, 2024
96fe68e
fix: sql按钮文本提示增加 (#4072)
jidanjuan Nov 26, 2024
83399d8
fix: 维度字段统一以及时间格式化 (#4074)
xintaoLi Nov 26, 2024
74b4495
fix: 优化四线统计/tmp统计接口查询逻辑 修改常量配置 增加注释说明 增加日期/业务id列表参数 (#4070)
ZC-A Nov 26, 2024
c5cc6bd
fix: 仪表盘订阅不支持非cmdb业务 --bug=134136733 (#3930)
unique0lai Nov 26, 2024
064a531
feat: 采集插件制作时,默认打开自动发现功能。同时新增周期巡检任务对自动发现指标进行保存。 --story=119693361 (#4…
HACK-WU Nov 26, 2024
0d959a8
fix: 重写分组计算逻辑 (#4077)
xintaoLi Nov 26, 2024
426fc75
fix: 时间维度字段处理 (#4078)
xintaoLi Nov 26, 2024
22bc5ec
fix: 【监控】策略列表过滤-告警级别弹框切换其他页面会保留 --bug=127408689 (#4050)
yzygyin Nov 27, 2024
be381a5
fix: 仪表盘promql降采样未生效 --bug=134576193 (#4076)
unique0lai Nov 27, 2024
54b3a63
feat: AI小鲸升级适配功能 --Story=120931743 (#4079)
liangling0628 Nov 27, 2024
3dc6dd6
feat: UpdatePartialStrategyV2Resource针对用户组批量更新优化 --story=120720224 (#…
tang202388 Nov 27, 2024
0df0178
feat: Metadata: 适配新版预计算接口,补充预计算模块单元测试 --story=120931836 (#4075)
EASYGOING45 Nov 27, 2024
400fa51
feat: 【产品功能】图表分析能力 --story=120635407 (#4082)
wencong1724427771 Nov 27, 2024
16da46b
feat: APM 日志索引及增加默认查询语句 --bug=134194297 (#4059)
shan-shuo Nov 27, 2024
423b87a
feat: APM主机场景配置selector_panel支持start_time end_time配置 --Story=12094126…
liangling0628 Nov 27, 2024
5b5c413
fix: 功能修复及国际化补充 (#4084)
jidanjuan Nov 27, 2024
7ff5b3d
fix: 调整UI的输入内容的展示范围 --bug=134604673 (#4086)
cjyscjys Nov 27, 2024
7c83b0e
feat: 【告警分派】输入需要回车体验不佳 【专项群】 --story=119855589 (#4066)
JayCC1 Nov 27, 2024
db19681
feat: 收藏功能逻辑补充 --story=120917443 (#4083)
cjyscjys Nov 27, 2024
23d943b
feat: 优化开启聚类索引的统计逻辑 --story=120944727 (#4097)
jayjiahua Nov 27, 2024
e9d5b33
feat: 【产品功能】图表分析能力 --story=120635407 (#4088)
wencong1724427771 Nov 27, 2024
623be80
fix: 切换集群获取mappings兼容 --bug=134496665 (#4048)
yiqiwang-17 Nov 27, 2024
93076d8
feat: 调用分析支持动态设置服务配置 --story=120948665 (#4101)
ZhuoZhuoCrayon Nov 27, 2024
cb15c25
fix: 修复图表显示问题 (#4102)
xintaoLi Nov 27, 2024
5cf9346
Revert "fix: 切换集群获取mappings兼容 --bug=134496665" (#4103)
yiqiwang-17 Nov 27, 2024
8c71140
chore: api token鉴权偶发报错问题
unique0lai Nov 27, 2024
e7f8d35
feat: APM主机场景配置selector_panel支持start_time end_time配置 --Story=12094126…
liangling0628 Nov 27, 2024
c297757
feat: 新增服务容器页面 & 调整主机关联页面 --story=120782340 (#4081)
rxwycdh Nov 27, 2024
0d39736
fix: 修复trace检索未过滤接入中应用 --bug=134613689 (#4087)
rxwycdh Nov 27, 2024
2bf7d31
feat: 调用分析服务发现性能优化 --story=120954519 (#4108)
ZhuoZhuoCrayon Nov 27, 2024
074916c
fix: 删除主机顶部策略数量配置 && 主机状态显示异常 --bug=134642831 (#4110)
rxwycdh Nov 28, 2024
012f610
fix: 修复调用分析服务缓存不生效的问题 --bug=134647671 (#4109)
ZhuoZhuoCrayon Nov 28, 2024
d55ab3f
fix: pod详情接口缺少参数 --bug=134656665 (#4111)
rxwycdh Nov 28, 2024
3617a5d
feat: 添加对业务空间同步归档的定时任务 (#4099)
fishman001 Nov 27, 2024
9590da4
fix: 图表分析tooltip formatter (#4112)
xintaoLi Nov 28, 2024
8930b2b
feat: 【产品功能】策略里面的指标是否可以提供复制的功能 --story=120927927 (#4095)
JayCC1 Nov 28, 2024
56a1642
minor: 调整 bk-collector 接收端的平台配置 (#4114)
liuwenping Nov 28, 2024
fa8e1cb
minor: 修改bk-collector平台配置,去掉部分字段 (#4115)
liuwenping Nov 28, 2024
9d64935
fix: 关联TraceId位置调整以及高亮分词支持点击操作 (#4012)
xintaoLi Nov 28, 2024
f0270bc
fix: 验收问题1、36、38、39、40、48、50修复 (#4092)
jidanjuan Nov 28, 2024
2a58845
fix: 配置提示优化 (#4119)
xintaoLi Nov 28, 2024
d48d4bb
feat: Metadata: 日志采集项新增归档时间字段,支持索引归档能力 --story=120948092 (#4096)
EASYGOING45 Nov 28, 2024
1777336
minor: 智能QA问答参数调整topk-20
chenguo367 Nov 28, 2024
bc6fc64
fix: 修复多维度计算逻辑 (#4121)
xintaoLi Nov 28, 2024
825998f
fix: 修复收藏回填 (#4126)
xintaoLi Nov 28, 2024
481dff6
fix: 修复收藏回填初始化SQL和异常提示样式问题 (#4127)
xintaoLi Nov 28, 2024
2ce4b8c
fix: 修复收藏回填初始化SQL和异常提示样式问题 (#4128)
xintaoLi Nov 28, 2024
444f80c
fix: 修复切换保存导致的递归引用问题 (#4129)
xintaoLi Nov 28, 2024
04f9c46
fix: pull upstream master conflict
xintaoLi Nov 28, 2024
14e170c
fix: 同步图表分析功能
xintaoLi Nov 28, 2024
fb3f24e
fix: 处理冲突
xintaoLi Nov 28, 2024
f8a5e31
fix: 同步代码冲突处理
xintaoLi Nov 28, 2024
244de9e
fix: 修复trace检索获取图表报错 --bug=134667895 (#4117)
rxwycdh Nov 29, 2024
1ce3fa0
minor: 智能QA问答内测申请url
chenguo367 Nov 29, 2024
af9540e
feat: 支持aiops sdk独立集群异常检测 --story=120977161 (#4132)
chenguo367 Nov 29, 2024
a570356
feat: 智能监控策略通过开关切换到SDK来执行检测逻辑 --story=120679992 (#4105)
dengyh Nov 29, 2024
fa6973a
fix: 修复调用分析模调指标类型探测偶现不准确的问题 --bug=134730191 (#4136)
ZhuoZhuoCrayon Nov 29, 2024
1c6797d
fix: 验收问题55-60修复 (#4139)
jidanjuan Nov 29, 2024
67aed5f
fix: 计算高度问题
xintaoLi Nov 29, 2024
9b31189
feat: Trace检索查询方式快速切换请求优化 --story=119800145 (#4098)
yzygyin Nov 29, 2024
fac4e70
feat: 【产品功能】Trace 检索提供跨应用下钻选项 --story=119253519 (#4069)
goodGai Nov 29, 2024
81c59fd
feat: 【trace】表格统计去掉容余的观测操作入口 --story=120924610 (#4133)
goodGai Nov 29, 2024
38f4c9e
feat: 【trace】trace详情页面文案优化 --story=120923522 (#4122)
yzygyin Nov 29, 2024
f002f68
fix: 修改告警策略指标时,如果指标单位变了,没有同步到检测算法的配置中 --bug=134335359 (#4054)
yzygyin Nov 29, 2024
d8e7011
Merge branch 'feat/chart_analysis' of https://github.com/TencentBlueK…
xintaoLi Dec 2, 2024
3e6f73b
Merge branch 'feat/chart_analysis' of https://github.com/TencentBlueK…
xintaoLi Dec 2, 2024
fbc40ba
Merge branch 'master' of https://github.com/TencentBlueKing/bk-monito…
xintaoLi Dec 2, 2024
8d662fb
Merge branch 'master' of https://github.com/TencentBlueKing/bk-monito…
xintaoLi Dec 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,22 @@
from apps.log_clustering.models import ClusteringConfig
from apps.log_measure.utils.metric import MetricUtils
from bk_monitor.constants import TimeFilterEnum
from bk_monitor.utils.metric import register_metric, Metric
from bk_monitor.utils.metric import Metric, register_metric


class ClusteringMetricCollector(object):
@staticmethod
@register_metric("clustering", description=_("聚类计数"), data_name="metric", time_filter=TimeFilterEnum.MINUTE5)
def clustering_count():
clustering_query_set = (
ClusteringConfig.objects.filter(modify_flow__isnull=False)
ClusteringConfig.objects.filter(signature_enable=True, access_finished=True)
.values("bk_biz_id")
.annotate(total=Count("bk_biz_id"))
.order_by()
)
metrics = []
total = 0
for clustering_obj in clustering_query_set:

metrics.append(
Metric(
metric_name="count",
Expand Down
48 changes: 48 additions & 0 deletions bklog/apps/log_search/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1426,6 +1426,17 @@ class SearchMode(ChoicesEnum):
_choices_labels = ((UI, _("UI模式")), (SQL, _("SQL模式")))


class QueryMode(ChoicesEnum):
"""
查询模式
"""

UI = "ui"
SQL = "sql"

_choices_labels = ((UI, _("UI模式")), (SQL, _("SQL模式")))


# 索引集无数据检查缓存前缀
INDEX_SET_NO_DATA_CHECK_PREFIX = "index_set_no_data_check_prefix"

Expand Down Expand Up @@ -1496,6 +1507,17 @@ class FavoriteListOrderType(ChoicesEnum):
)


class FavoriteType(ChoicesEnum):
"""
收藏类型
"""

SEARCH = "search"
CHART = "chart"

_choices_labels = ((SEARCH, _("检索")), (CHART, _("图表")))


# 用户指引步骤
USER_GUIDE_STEP_LIST = [
{"title": _("业务选择框"), "target": "#bizSelectorGuide", "content": _("业务选择框的位置全部换到左侧导航")},
Expand Down Expand Up @@ -1627,3 +1649,29 @@ class OperatorEnum:

# 检索选项历史记录API返回数据数量大小
SEARCH_OPTION_HISTORY_NUM = 20

# SQL模板
SQL_PREFIX = "SELECT DATE_TRUNC(MAX(dtEventTime), 'minute') AS dtEventTime, COUNT(*) AS log_count"
SQL_SUFFIX = "GROUP BY minute1 ORDER BY minute1 DESC LIMIT 10"

# 日志检索条件到sql操作符的映射
SQL_CONDITION_MAPPINGS = {
">": ">",
">=": ">=",
"<": "<",
"<=": "<=",
"=": "=",
"!=": "!=",
"=~": "LIKE",
"&=~": "LIKE",
"!=~": "NOT LIKE",
"&!=~": "NOT LIKE",
"contains": "LIKE",
"not contains": "NOT LIKE",
"contains match phrase": "MATCH_PHRASE",
"not contains match phrase": "NOT MATCH_PHRASE",
"all contains match phrase": "MATCH_PHRASE",
"all not contains match phrase": "NOT MATCH_PHRASE",
"is true": "IS TRUE",
"is false": "IS FALSE",
}
15 changes: 15 additions & 0 deletions bklog/apps/log_search/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,3 +536,18 @@ class SettingMenuException(BasePermException):
class FunctionGuideException(BaseException):
ERROR_CODE = "1002"
MESSAGE = _("不存在该功能引导")


# =================================================
# 图表分析
# =================================================


class IndexSetDorisQueryException(BaseException):
ERROR_CODE = "1004"
MESSAGE = _("该索引集不支持doris查询")


class SQLQueryException(BaseException):
ERROR_CODE = "1005"
MESSAGE = _("SQL查询异常: {name}")
12 changes: 6 additions & 6 deletions bklog/apps/log_search/handlers/index_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import json
import re
from collections import defaultdict
from typing import Optional, List
from typing import List, Optional

from django.conf import settings
from django.db import transaction
Expand Down Expand Up @@ -88,8 +88,8 @@
Scenario,
Space,
StorageClusterRecord,
UserIndexSetFieldsConfig,
UserIndexSetCustomConfig,
UserIndexSetFieldsConfig,
)
from apps.log_search.tasks.mapping import sync_single_index_set_mapping_snapshot
from apps.log_search.tasks.sync_index_set_archive import sync_index_set_archive
Expand Down Expand Up @@ -1727,10 +1727,10 @@ def delete(self):

class UserIndexSetConfigHandler(object):
def __init__(
self,
index_set_id: int = None,
index_set_ids: List[int] = None,
index_set_type: str = IndexSetType.SINGLE.value,
self,
index_set_id: int = None,
index_set_ids: List[int] = None,
index_set_type: str = IndexSetType.SINGLE.value,
):
self.index_set_id = index_set_id
self.index_set_ids = index_set_ids
Expand Down
207 changes: 207 additions & 0 deletions bklog/apps/log_search/handlers/search/chart_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
We undertake not to change the open source license (MIT license) applicable to the current version of
the project delivered to anyone in the future.
"""
import re

from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _

from apps.api import BkDataQueryApi
from apps.log_search.constants import (
SQL_CONDITION_MAPPINGS,
SQL_PREFIX,
SQL_SUFFIX,
SearchMode,
)
from apps.log_search.exceptions import (
BaseSearchIndexSetException,
IndexSetDorisQueryException,
SQLQueryException,
)
from apps.log_search.models import LogIndexSet
from apps.utils.log import logger


class ChartHandler(object):
def __init__(self, index_set_id):
self.index_set_id = index_set_id
try:
self.data = LogIndexSet.objects.get(index_set_id=self.index_set_id)
except LogIndexSet.DoesNotExist:
raise BaseSearchIndexSetException(
BaseSearchIndexSetException.MESSAGE.format(index_set_id=self.index_set_id)
)

@classmethod
def get_instance(cls, index_set_id, mode):
mapping = {
SearchMode.UI.value: "UIChartHandler",
SearchMode.SQL.value: "SQLChartHandler",
}
try:
chart_instance = import_string(
"apps.log_search.handlers.search.chart_handlers.{}".format(mapping.get(mode))
)
return chart_instance(index_set_id=index_set_id)
except ImportError as error:
raise NotImplementedError(f"{mode} class not implement, error: {error}")

def get_chart_data(self, params: dict) -> dict:
"""
获取图表相关信息
:param params: 图表参数
:return: 图表数据 dict
"""
raise NotImplementedError(_("功能暂未实现"))

@staticmethod
def generate_sql(params: dict) -> str:
"""
根据过滤条件生成sql
:param params: 过滤条件
"""
start_time = params["start_time"] * 1000
end_time = params["end_time"] * 1000

sql = f"WHERE dtEventTimeStamp>={start_time} AND dtEventTimeStamp<={end_time}"
addition = params["addition"]

for condition in addition:
sql += " AND "
field_name = condition["field"]
operator = condition["operator"]
values = condition["value"]
# 获取sql操作符
sql_operator = SQL_CONDITION_MAPPINGS.get(operator)
# 异常情况,跳过
if not sql_operator or field_name in ["*", "query_string"]:
continue
# IS TRUE和IS FALSE的逻辑
if operator in ["is true", "is false"]:
sql += f"{field_name} {sql_operator}"
continue

# values 不为空时才走后面的逻辑
if not values:
continue

# 组内条件的与或关系
condition_type = "OR"
if operator in ["&=~", "&!=~", "all contains match phrase", "all not contains match phrase"]:
condition_type = "AND"

tmp_sql = ""
for index, value in enumerate(values):
if operator in ["=~", "&=~", "!=~", "&!=~"]:
# 替换通配符
value = value.replace("*", "%")
value = value.replace("?", "_")
elif operator in ["contains", "not contains"]:
# 添加通配符
value = f"%{value}%"

if index > 0:
tmp_sql += f" {condition_type} "
if isinstance(value, str):
value = value.replace("'", "''")
value = f"\'{value}\'"
tmp_sql += f"{field_name} {sql_operator} {value}"

# 有两个以上的值时加括号
sql += tmp_sql if len(values) == 1 else ("(" + tmp_sql + ")")
return f"{SQL_PREFIX} {sql} {SQL_SUFFIX}"


class UIChartHandler(ChartHandler):
def get_chart_data(self, params: dict) -> dict:
"""
UI模式获取图表相关信息
:param params: 图表参数
:return: 图表数据 dict
"""
# TODO 待实现
return {}


class SQLChartHandler(ChartHandler):
def get_chart_data(self, params) -> dict:
"""
Sql模式获取图表相关信息
:param params: 图表参数
:return: 图表数据 dict
"""
if not self.data.support_doris:
raise IndexSetDorisQueryException()
parsed_sql = self.parse_sql_syntax(self.data.doris_table_id, params["sql"])
data = self.fetch_query_data(parsed_sql)
return data

@staticmethod
def parse_sql_syntax(doris_table_id: str, raw_sql: str):
"""
解析sql语法
"""
# 如果不存在FROM则添加,存在则覆盖
pattern = (
r"^\s*?(SELECT\s+?.+?)"
r"(?:\bFROM\b.+?)?"
r"(\bWHERE\b.*|\bGROUP\s+?BY\b.*|\bHAVING\b.*|\bORDER\s+?BY\b.*|\bLIMIT\b.*|\bINTO\s+?OUTFILE\b.*)?$"
)
matches = re.match(pattern, raw_sql, re.DOTALL | re.IGNORECASE)
if not matches:
raise SQLQueryException(SQLQueryException.MESSAGE.format(name=_("缺少SQL查询的关键字")))
parsed_sql = matches.group(1) + f" FROM {doris_table_id} "
if matches.group(2):
parsed_sql += matches.group(2)
return parsed_sql

@staticmethod
def fetch_query_data(sql: str) -> dict:
"""
获取查询结果
:param sql: 查询sql
:return: 查询结果 dict
"""
result_data = BkDataQueryApi.query({"sql": sql}, raw=True)
result = result_data.get("result")
if not result:
# SQL查询失败, 抛出异常
errors_message = result_data.get("message", {})
errors = result_data.get("errors", {}).get("error")
if errors:
errors_message = errors_message + ":" + errors
logger.info("SQL query exception [%s]", errors_message)
raise SQLQueryException(
SQLQueryException.MESSAGE.format(name=errors_message),
errors={"sql": sql},
)

data_list = result_data["data"]["list"]
result_schema = result_data["data"].get("result_schema", [])

data = {
"total_records": result_data["data"]["totalRecords"],
"time_taken": result_data["data"]["timetaken"],
"list": data_list,
"select_fields_order": result_data["data"]["select_fields_order"],
"result_schema": result_schema,
}
return data
13 changes: 12 additions & 1 deletion bklog/apps/log_search/handlers/search/favorite_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
INDEX_SET_NOT_EXISTED,
FavoriteGroupType,
FavoriteListOrderType,
FavoriteType,
FavoriteVisibleType,
IndexSetType,
)
Expand Down Expand Up @@ -184,14 +185,23 @@ def create_or_update(
search_fields: list,
is_enable_display_fields: bool,
display_fields: list,
chart_params: dict = None,
search_mode: str = None,
index_set_id: int = None,
group_id: int = None,
index_set_ids: list = None,
index_set_type: str = IndexSetType.SINGLE.value,
favorite_type: str = FavoriteType.SEARCH.value,
) -> dict:
chart_params = chart_params or {}
# 构建params
params = {"ip_chooser": ip_chooser, "addition": addition, "keyword": keyword, "search_fields": search_fields}
params = {
"ip_chooser": ip_chooser,
"addition": addition,
"keyword": keyword,
"search_fields": search_fields,
"chart_params": chart_params,
}
space_uid = self.space_uid if self.space_uid else self.data.space_uid
search_mode = search_mode if search_mode else self.data.search_mode

Expand Down Expand Up @@ -245,6 +255,7 @@ def create_or_update(
display_fields=display_fields,
index_set_ids=index_set_ids,
index_set_type=index_set_type,
favorite_type=favorite_type,
)

return model_to_dict(self.data)
Expand Down
Loading
Loading