|
| 1 | +// Copyright Quesma, licensed under the Elastic License 2.0. |
| 2 | +// SPDX-License-Identifier: Elastic-2.0 |
| 3 | +package bucket_aggregations |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "fmt" |
| 8 | + "quesma/logger" |
| 9 | + "quesma/model" |
| 10 | + "reflect" |
| 11 | +) |
| 12 | + |
| 13 | +// Current limitation: we expect Clickhouse field to be IPv4 (and not IPv6) |
| 14 | + |
| 15 | +// Clickhouse table to test SQLs: |
| 16 | +// CREATE TABLE __quesma_table_name (clientip IPv4) ENGINE=Log |
| 17 | +// INSERT INTO __quesma_table_name VALUES ('0.0.0.0'), ('5.5.5.5'), ('90.180.90.180'), ('128.200.0.8'), ('192.168.1.67'), ('222.168.22.67') |
| 18 | + |
| 19 | +// TODO make part of QueryType interface and implement for all aggregations |
| 20 | +// TODO add bad requests to tests |
| 21 | +// Doing so will ensure we see 100% of what we're interested in in our logs (now we see ~95%) |
| 22 | +func CheckParamsIpPrefix(ctx context.Context, paramsRaw any) error { |
| 23 | + requiredParams := map[string]string{ |
| 24 | + "field": "string", |
| 25 | + "prefix_length": "float64", // TODO should be int, will be fixed |
| 26 | + } |
| 27 | + optionalParams := map[string]string{ |
| 28 | + "is_ipv6": "bool", |
| 29 | + "append_prefix_length": "bool", |
| 30 | + "keyed": "bool", |
| 31 | + "min_doc_count": "int", |
| 32 | + } |
| 33 | + logIfYouSeeThemParams := []string{"min_doc_count"} // we don't use min_doc_count yet. We'll log if "is_ipv6" == true, also. |
| 34 | + |
| 35 | + params, ok := paramsRaw.(model.JsonMap) |
| 36 | + if !ok { |
| 37 | + return fmt.Errorf("params is not a map, but %+v", paramsRaw) |
| 38 | + } |
| 39 | + |
| 40 | + // check if required are present |
| 41 | + for paramName, paramType := range requiredParams { |
| 42 | + paramVal, exists := params[paramName] |
| 43 | + if !exists { |
| 44 | + return fmt.Errorf("required parameter %s not found in params", paramName) |
| 45 | + } |
| 46 | + if reflect.TypeOf(paramVal).Name() != paramType { // TODO I'll make a small rewrite to not use reflect here |
| 47 | + return fmt.Errorf("required parameter %s is not of type %s, but %T", paramName, paramType, paramVal) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // check if only required/optional are present |
| 52 | + for paramName := range params { |
| 53 | + if _, isRequired := requiredParams[paramName]; !isRequired { |
| 54 | + wantedType, isOptional := optionalParams[paramName] |
| 55 | + if !isOptional { |
| 56 | + return fmt.Errorf("unexpected parameter %s found in IP Range params %v", paramName, params) |
| 57 | + } |
| 58 | + if reflect.TypeOf(params[paramName]).Name() != wantedType { // TODO I'll make a small rewrite to not use reflect here |
| 59 | + return fmt.Errorf("optional parameter %s is not of type %s, but %T", paramName, wantedType, params[paramName]) |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + // log if you see them |
| 65 | + for _, warnParam := range logIfYouSeeThemParams { |
| 66 | + if _, exists := params[warnParam]; exists { |
| 67 | + logger.WarnWithCtxAndThrottling(ctx, "ip_prefix", warnParam, "we didn't expect %s in IP Range params %v", warnParam, params) |
| 68 | + } |
| 69 | + } |
| 70 | + if isIpv6, exists := params["is_ipv6"]; exists && isIpv6.(bool) { |
| 71 | + logger.WarnWithCtxAndThrottling(ctx, "ip_prefix", "is_ipv6", "is_ipv6 is true in IP Range params %v, we don't support IPv6 yet", params) |
| 72 | + } |
| 73 | + |
| 74 | + return nil |
| 75 | +} |
| 76 | + |
| 77 | +type IpPrefix struct { |
| 78 | + ctx context.Context |
| 79 | + field model.Expr |
| 80 | + prefixLength int |
| 81 | + isIpv6 bool |
| 82 | + appendPrefixLength bool |
| 83 | + keyed bool |
| 84 | + minDocCount int |
| 85 | +} |
| 86 | + |
| 87 | +func NewIpPrefix(ctx context.Context, field model.Expr, prefixLength int, isIpv6 bool, appendPrefixLength bool, keyed bool, minDocCount int) *IpPrefix { |
| 88 | + return &IpPrefix{ |
| 89 | + ctx: ctx, |
| 90 | + field: field, |
| 91 | + prefixLength: prefixLength, |
| 92 | + isIpv6: isIpv6, |
| 93 | + appendPrefixLength: appendPrefixLength, |
| 94 | + keyed: keyed, |
| 95 | + minDocCount: minDocCount, |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +func (query *IpPrefix) AggregationType() model.AggregationType { |
| 100 | + return model.BucketAggregation |
| 101 | +} |
| 102 | + |
| 103 | +func (query *IpPrefix) TranslateSqlResponseToJson(rows []model.QueryResultRow) model.JsonMap { |
| 104 | + var netmask, keySuffix string |
| 105 | + if !query.isIpv6 { |
| 106 | + netmask = query.calcNetMask() |
| 107 | + } |
| 108 | + if query.appendPrefixLength { |
| 109 | + keySuffix = fmt.Sprintf("/%d", query.prefixLength) |
| 110 | + } |
| 111 | + buckets := make([]model.JsonMap, 0, len(rows)) |
| 112 | + for _, row := range rows { |
| 113 | + var docCount any |
| 114 | + var originalKey uint32 |
| 115 | + if query.prefixLength == 0 { |
| 116 | + if len(row.Cols) != 1 { |
| 117 | + logger.ErrorWithCtx(query.ctx).Msgf( |
| 118 | + "unexpected number of columns in ip_prefix aggregation response, len: %d, row: %v", len(row.Cols), row) |
| 119 | + continue |
| 120 | + } |
| 121 | + docCount = row.Cols[0].Value |
| 122 | + } else { |
| 123 | + if len(row.Cols) != 2 { |
| 124 | + logger.ErrorWithCtx(query.ctx).Msgf( |
| 125 | + "unexpected number of columns in ip_prefix aggregation response, len: %d, row: %v", len(row.Cols), row) |
| 126 | + continue |
| 127 | + } |
| 128 | + var ok bool |
| 129 | + originalKey, ok = row.Cols[0].Value.(uint32) |
| 130 | + if !ok { |
| 131 | + logger.ErrorWithCtx(query.ctx).Msgf("unexpected type of key in ip_prefix aggregation response, got %T", row.Cols[0]) |
| 132 | + continue |
| 133 | + } |
| 134 | + docCount = row.Cols[1].Value |
| 135 | + } |
| 136 | + |
| 137 | + bucket := model.JsonMap{ |
| 138 | + "key": query.calcKey(originalKey) + keySuffix, |
| 139 | + "doc_count": docCount, |
| 140 | + "prefix_length": query.prefixLength, |
| 141 | + "is_ipv6": query.isIpv6, |
| 142 | + } |
| 143 | + if !query.isIpv6 { |
| 144 | + bucket["netmask"] = netmask |
| 145 | + } |
| 146 | + buckets = append(buckets, bucket) |
| 147 | + } |
| 148 | + |
| 149 | + // usual case |
| 150 | + if !query.keyed { |
| 151 | + return model.JsonMap{ |
| 152 | + "buckets": buckets, |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // unusual case: transform result buckets a bit |
| 157 | + keyedBuckets := make(model.JsonMap, len(buckets)) |
| 158 | + for _, bucket := range buckets { |
| 159 | + key := bucket["key"].(string) |
| 160 | + delete(bucket, "key") |
| 161 | + keyedBuckets[key] = bucket |
| 162 | + } |
| 163 | + return model.JsonMap{ |
| 164 | + "buckets": keyedBuckets, |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +func (query *IpPrefix) String() string { |
| 169 | + return "ip_prefix" |
| 170 | +} |
| 171 | + |
| 172 | +// SqlSelectQuery returns the SQL query: intDiv(ip_field, some_power_of_2) |
| 173 | +// ipv4 only for now |
| 174 | +func (query *IpPrefix) SqlSelectQuery() model.Expr { |
| 175 | + if query.prefixLength == 0 { |
| 176 | + return nil |
| 177 | + } |
| 178 | + return model.NewFunction("intDiv", query.field, model.NewLiteral(query.divideByToGroupBy())) |
| 179 | +} |
| 180 | + |
| 181 | +func (query *IpPrefix) divideByToGroupBy() uint32 { |
| 182 | + return 1 << (32 - query.prefixLength) |
| 183 | +} |
| 184 | + |
| 185 | +func (query *IpPrefix) calcKey(originalKey uint32) string { |
| 186 | + if query.prefixLength == 0 { |
| 187 | + return "0.0.0.0" |
| 188 | + } |
| 189 | + ipAsInt := originalKey * query.divideByToGroupBy() |
| 190 | + part4 := ipAsInt % 256 |
| 191 | + ipAsInt /= 256 |
| 192 | + part3 := ipAsInt % 256 |
| 193 | + ipAsInt /= 256 |
| 194 | + part2 := ipAsInt % 256 |
| 195 | + ipAsInt /= 256 |
| 196 | + part1 := ipAsInt % 256 |
| 197 | + return fmt.Sprintf("%d.%d.%d.%d", part1, part2, part3, part4) |
| 198 | +} |
| 199 | + |
| 200 | +func (query *IpPrefix) calcNetMask() string { |
| 201 | + if query.prefixLength == 0 { |
| 202 | + return "0.0.0.0" |
| 203 | + } |
| 204 | + biggestPossibleKey := uint32(1<<query.prefixLength - 1) |
| 205 | + return query.calcKey(biggestPossibleKey) // netmask is the same as ip of biggest possible key |
| 206 | +} |
0 commit comments