mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 05:30:41 +00:00
Compare commits
1 Commits
split/4-e2
...
keystone-p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83c4c0bb89 |
@@ -20,7 +20,11 @@ import (
|
||||
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
|
||||
)
|
||||
|
||||
const auditLookbackWindow = 30 * 24 * time.Hour
|
||||
const (
|
||||
auditLookbackWindow = 30 * 24 * time.Hour
|
||||
|
||||
auditScalarDynamicTypesSQL = "'String', 'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Float32', 'Float64'"
|
||||
)
|
||||
|
||||
func (t *telemetryMetaStore) getAuditKeys(ctx context.Context, fieldKeySelectors []*telemetrytypes.FieldKeySelector) ([]*telemetrytypes.TelemetryFieldKey, bool, error) {
|
||||
ctx = ctxtypes.NewContextWithCommentVals(ctx, map[string]string{
|
||||
@@ -155,7 +159,10 @@ func (t *telemetryMetaStore) getAuditJSONPathKeys(ctx context.Context, queryAttr
|
||||
for path, chTypes := range pathMaps[i] {
|
||||
seenTypes := make(map[telemetrytypes.FieldDataType]struct{}, len(chTypes))
|
||||
for _, chType := range chTypes {
|
||||
dataType := clickhouseJSONTypeToFieldDataType(chType)
|
||||
dataType, ok := clickhouseJSONTypeToFieldDataType(chType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, seen := seenTypes[dataType]; seen {
|
||||
continue
|
||||
}
|
||||
@@ -240,7 +247,7 @@ func (t *telemetryMetaStore) getAuditResourceKeys(ctx context.Context, fieldKeyS
|
||||
return keys, rowCount <= limit, nil
|
||||
}
|
||||
|
||||
func clickhouseJSONTypeToFieldDataType(chType string) telemetrytypes.FieldDataType {
|
||||
func clickhouseJSONTypeToFieldDataType(chType string) (telemetrytypes.FieldDataType, bool) {
|
||||
for {
|
||||
switch {
|
||||
case strings.HasPrefix(chType, "Nullable(") && strings.HasSuffix(chType, ")"):
|
||||
@@ -250,15 +257,15 @@ func clickhouseJSONTypeToFieldDataType(chType string) telemetrytypes.FieldDataTy
|
||||
default:
|
||||
switch chType {
|
||||
case "String":
|
||||
return telemetrytypes.FieldDataTypeString
|
||||
return telemetrytypes.FieldDataTypeString, true
|
||||
case "Bool":
|
||||
return telemetrytypes.FieldDataTypeBool
|
||||
return telemetrytypes.FieldDataTypeBool, true
|
||||
case "Int8", "Int16", "Int32", "Int64",
|
||||
"UInt8", "UInt16", "UInt32", "UInt64",
|
||||
"Float32", "Float64":
|
||||
return telemetrytypes.FieldDataTypeNumber
|
||||
return telemetrytypes.FieldDataTypeNumber, true
|
||||
default:
|
||||
return telemetrytypes.FieldDataTypeString
|
||||
return telemetrytypes.FieldDataTypeUnspecified, false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -390,7 +397,7 @@ func (t *telemetryMetaStore) getAuditScopeFieldValues(ctx context.Context, field
|
||||
escapedExpr := sqlbuilder.Escape(expr)
|
||||
sb := sqlbuilder.Select("DISTINCT " + escapedExpr).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
if isDynamic {
|
||||
sb.Where(sqlbuilder.Escape(rawPath) + " IS NOT NULL")
|
||||
sb.Where(fmt.Sprintf("dynamicType(%s) = 'String'", sqlbuilder.Escape(rawPath)))
|
||||
}
|
||||
sb.Where(escapedExpr + " <> ''")
|
||||
if fieldValueSelector.Value != "" {
|
||||
@@ -447,7 +454,7 @@ func (t *telemetryMetaStore) getAuditStringAttributeFieldValues(ctx context.Cont
|
||||
strExpr := escapedPath + "::String"
|
||||
|
||||
sb := sqlbuilder.Select("DISTINCT " + strExpr).From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(escapedPath+" IS NOT NULL", strExpr+" <> ''")
|
||||
sb.Where(fmt.Sprintf("dynamicType(%s) = 'String'", escapedPath), strExpr+" <> ''")
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(rawStrExpr, "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
@@ -493,7 +500,7 @@ func (t *telemetryMetaStore) getAuditUnspecifiedAttributeFieldValues(ctx context
|
||||
|
||||
sb := sqlbuilder.Select(fmt.Sprintf("DISTINCT dynamicType(%s)", escapedPath), strExpr).
|
||||
From(t.auditDBName + "." + t.auditLogsTblName)
|
||||
sb.Where(escapedPath+" IS NOT NULL", strExpr+" <> ''")
|
||||
sb.Where(fmt.Sprintf("dynamicType(%s) IN (%s)", escapedPath, auditScalarDynamicTypesSQL), strExpr+" <> ''")
|
||||
if searchValue != "" {
|
||||
sb.Where(sb.ILike(rawStrExpr, "%"+clickhousesql.LikePattern(searchValue)+"%"))
|
||||
}
|
||||
@@ -622,7 +629,11 @@ func (t *telemetryMetaStore) queryAuditDynamicValues(ctx context.Context, sb *sq
|
||||
if strVal == "" {
|
||||
continue
|
||||
}
|
||||
switch clickhouseJSONTypeToFieldDataType(dynamicType) {
|
||||
dataType, ok := clickhouseJSONTypeToFieldDataType(dynamicType)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch dataType {
|
||||
case telemetrytypes.FieldDataTypeBool:
|
||||
if boolVal, err := strconv.ParseBool(strVal); err == nil {
|
||||
if _, seen := seenBool[boolVal]; !seen {
|
||||
@@ -637,7 +648,7 @@ func (t *telemetryMetaStore) queryAuditDynamicValues(ctx context.Context, sb *sq
|
||||
values.NumberValues = append(values.NumberValues, numVal)
|
||||
}
|
||||
}
|
||||
default:
|
||||
case telemetrytypes.FieldDataTypeString:
|
||||
if _, seen := seenStr[strVal]; !seen {
|
||||
seenStr[strVal] = struct{}{}
|
||||
values.StringValues = append(values.StringValues, strVal)
|
||||
|
||||
@@ -47,9 +47,12 @@ func TestGetAuditKeys_UnspecifiedContextDiscoversAllAndMergesIntrinsics(t *testi
|
||||
"signoz.audit.verb": {"LowCardinality(String)"},
|
||||
"http.response.status_code": {"Int64", "Float64"},
|
||||
"signoz.audit.dry_run": {"Nullable(Bool)"},
|
||||
"signoz.audit.tags": {"Array(Nullable(String))"},
|
||||
"signoz.audit.payload": {"JSON(max_dynamic_types=16, max_dynamic_paths=0)"},
|
||||
},
|
||||
map[string][]string{
|
||||
"scope.custom": {"String"},
|
||||
"scope.tags": {"Array(Dynamic)"},
|
||||
},
|
||||
}},
|
||||
))
|
||||
@@ -96,6 +99,10 @@ func TestGetAuditKeys_UnspecifiedContextDiscoversAllAndMergesIntrinsics(t *testi
|
||||
require.Len(t, keys["scope.name"], 1)
|
||||
assert.Equal(t, telemetrytypes.FieldContextScope, keys["scope.name"][0].FieldContext)
|
||||
|
||||
assert.NotContains(t, keys, "signoz.audit.tags")
|
||||
assert.NotContains(t, keys, "signoz.audit.payload")
|
||||
assert.NotContains(t, keys, "scope.tags")
|
||||
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
@@ -354,7 +361,7 @@ func TestGetAuditFieldValues(t *testing.T) {
|
||||
t.Run("AttributeUnspecifiedDynamicTypeRoutesAndDedupes", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`mixed.field`"+`\), attributes\.`+"`mixed.field`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`mixed.field`"+` IS NOT NULL AND attributes\.`+"`mixed.field`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`mixed.field`"+`\), attributes\.`+"`mixed.field`"+`::String FROM signoz_audit\.distributed_logs WHERE dynamicType\(attributes\.`+"`mixed.field`"+`\) IN \('String', 'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Float32', 'Float64'\) AND attributes\.`+"`mixed.field`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "dt", Type: "String"}, {Name: "val", Type: "String"}},
|
||||
@@ -363,6 +370,10 @@ func TestGetAuditFieldValues(t *testing.T) {
|
||||
{"Float64", "200"},
|
||||
{"String", "ok"},
|
||||
{"Bool", "true"},
|
||||
{"Array(Nullable(String))", `["a","b"]`},
|
||||
{"Array(Dynamic)", `[1,"x"]`},
|
||||
{"JSON(max_dynamic_types=16, max_dynamic_paths=0)", `{"k":"v"}`},
|
||||
{"Map(String, String)", `{'k':'v'}`},
|
||||
},
|
||||
))
|
||||
|
||||
@@ -440,7 +451,7 @@ func TestGetAuditFieldValues(t *testing.T) {
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
[][]any{{"dashboard"}},
|
||||
))
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`signoz.resource.kind`"+`\), attributes\.`+"`signoz.resource.kind`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`signoz.resource.kind`"+` IS NOT NULL AND attributes\.`+"`signoz.resource.kind`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
mock.ExpectQuery(`SELECT DISTINCT dynamicType\(attributes\.`+"`signoz.resource.kind`"+`\), attributes\.`+"`signoz.resource.kind`"+`::String FROM signoz_audit\.distributed_logs WHERE dynamicType\(attributes\.`+"`signoz.resource.kind`"+`\) IN \('String', 'Bool', 'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64', 'Float32', 'Float64'\) AND attributes\.`+"`signoz.resource.kind`"+`::String <> '' AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs(startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "dt", Type: "String"}, {Name: "val", Type: "String"}},
|
||||
@@ -464,7 +475,7 @@ func TestGetAuditFieldValues(t *testing.T) {
|
||||
t.Run("AttributeAndScopeSearchPreservesDoubleDollarKey", func(t *testing.T) {
|
||||
metadata, mock, startNs, startBucket := newAuditTestMetaStore(t)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE attributes\.`+"`foo\\$\\$bar`"+` IS NOT NULL AND attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
mock.ExpectQuery(`SELECT DISTINCT attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE dynamicType\(attributes\.`+"`foo\\$\\$bar`"+`\) = 'String' AND attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("%val%", startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
@@ -486,7 +497,7 @@ func TestGetAuditFieldValues(t *testing.T) {
|
||||
assert.True(t, complete)
|
||||
assert.Equal(t, []string{"val1"}, attrVals.StringValues)
|
||||
|
||||
mock.ExpectQuery(`SELECT DISTINCT scope\.attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE scope\.attributes\.`+"`foo\\$\\$bar`"+` IS NOT NULL AND scope\.attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(scope\.attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
mock.ExpectQuery(`SELECT DISTINCT scope\.attributes\.`+"`foo\\$\\$bar`"+`::String FROM signoz_audit\.distributed_logs WHERE dynamicType\(scope\.attributes\.`+"`foo\\$\\$bar`"+`\) = 'String' AND scope\.attributes\.`+"`foo\\$\\$bar`"+`::String <> '' AND LOWER\(scope\.attributes\.`+"`foo\\$\\$bar`"+`::String\) LIKE LOWER\(\?\) AND timestamp >= \? AND ts_bucket_start >= \? LIMIT \?`).
|
||||
WithArgs("%val%", startNs, startBucket, 51).
|
||||
WillReturnRows(cmock.NewRows(
|
||||
[]cmock.ColumnType{{Name: "val", Type: "String"}},
|
||||
@@ -528,3 +539,32 @@ func TestGetRelatedValues_AuditShortCircuitsWithoutQuery(t *testing.T) {
|
||||
assert.Empty(t, values)
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestClickhouseJSONTypeToFieldDataType(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
chType string
|
||||
wantType telemetrytypes.FieldDataType
|
||||
wantOK bool
|
||||
}{
|
||||
{name: "String_ReturnsString", chType: "String", wantType: telemetrytypes.FieldDataTypeString, wantOK: true},
|
||||
{name: "LowCardinalityNullableString_ReturnsString", chType: "LowCardinality(Nullable(String))", wantType: telemetrytypes.FieldDataTypeString, wantOK: true},
|
||||
{name: "NullableBool_ReturnsBool", chType: "Nullable(Bool)", wantType: telemetrytypes.FieldDataTypeBool, wantOK: true},
|
||||
{name: "Int64_ReturnsNumber", chType: "Int64", wantType: telemetrytypes.FieldDataTypeNumber, wantOK: true},
|
||||
{name: "Float64_ReturnsNumber", chType: "Float64", wantType: telemetrytypes.FieldDataTypeNumber, wantOK: true},
|
||||
{name: "ArrayString_Skipped", chType: "Array(Nullable(String))", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
{name: "ArrayDynamic_Skipped", chType: "Array(Dynamic)", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
{name: "ArrayJSON_Skipped", chType: "Array(JSON(max_dynamic_types=16, max_dynamic_paths=0))", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
{name: "JSONObject_Skipped", chType: "JSON(max_dynamic_types=16, max_dynamic_paths=0)", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
{name: "Map_Skipped", chType: "Map(String, String)", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
{name: "None_Skipped", chType: "None", wantType: telemetrytypes.FieldDataTypeUnspecified, wantOK: false},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
gotType, gotOK := clickhouseJSONTypeToFieldDataType(testCase.chType)
|
||||
assert.Equal(t, testCase.wantType, gotType)
|
||||
assert.Equal(t, testCase.wantOK, gotOK)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,3 +313,109 @@ def test_audit_fields_fixed_lookback_window(
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["dashboard"]
|
||||
|
||||
|
||||
def test_audit_fields_skip_complex_json_types(
|
||||
signoz: types.SigNoz,
|
||||
create_user_admin: None, # pylint: disable=unused-argument
|
||||
get_token: Callable[[str, str], str],
|
||||
insert_audit_logs: Callable[[list[AuditLog]], None],
|
||||
) -> None:
|
||||
now = datetime.now(tz=UTC)
|
||||
insert_audit_logs(
|
||||
[
|
||||
AuditLog(
|
||||
timestamp=now - timedelta(seconds=2),
|
||||
resources={"service.name": "signoz", "signoz.resource.kind": "dashboard"},
|
||||
attributes={
|
||||
"signoz.audit.tags": ["admin", "billing"],
|
||||
"signoz.audit.nested": {"env": "prod"},
|
||||
"signoz.audit.mixed": ["x", "y"],
|
||||
},
|
||||
event_name="signoz.audit.create",
|
||||
),
|
||||
AuditLog(
|
||||
timestamp=now - timedelta(seconds=1),
|
||||
resources={"service.name": "signoz", "signoz.resource.kind": "dashboard"},
|
||||
attributes={
|
||||
"signoz.audit.mixed": "scalar-value",
|
||||
},
|
||||
event_name="signoz.audit.update",
|
||||
),
|
||||
]
|
||||
)
|
||||
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
|
||||
|
||||
response = get_field_keys(signoz, token, {"signal": "logs", "source": "audit"})
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
keys = response.json()["data"]["keys"]
|
||||
assert "signoz.audit.tags" not in keys
|
||||
assert "signoz.audit.nested" not in keys
|
||||
assert any(k["fieldContext"] == "attribute" and k["fieldDataType"] == "string" for k in keys["signoz.audit.nested.env"])
|
||||
assert any(k["fieldContext"] == "attribute" and k["fieldDataType"] == "string" for k in keys["signoz.audit.mixed"])
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.tags"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
tags_values = response.json()["data"]["values"]
|
||||
assert not tags_values.get("stringValues")
|
||||
assert not tags_values.get("numberValues")
|
||||
assert not tags_values.get("boolValues")
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "signoz.audit.tags",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string",
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert not response.json()["data"]["values"].get("stringValues")
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.nested"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
nested_values = response.json()["data"]["values"]
|
||||
assert not nested_values.get("stringValues")
|
||||
assert not nested_values.get("numberValues")
|
||||
assert not nested_values.get("boolValues")
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.nested.env"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["prod"]
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{"signal": "logs", "source": "audit", "name": "signoz.audit.mixed"},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["scalar-value"]
|
||||
|
||||
response = get_field_values(
|
||||
signoz,
|
||||
token,
|
||||
{
|
||||
"signal": "logs",
|
||||
"source": "audit",
|
||||
"name": "signoz.audit.mixed",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string",
|
||||
},
|
||||
)
|
||||
assert response.status_code == HTTPStatus.OK, response.text
|
||||
assert response.json()["data"]["values"]["stringValues"] == ["scalar-value"]
|
||||
|
||||
Reference in New Issue
Block a user