| 1 |
// Package reporttsi provides a report about the series cardinality in one or more TSI indexes. |
| 2 |
package reporttsi |
| 3 |
|
| 4 |
import ( |
| 5 |
"errors" |
| 6 |
"flag" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"math" |
| 10 |
"os" |
| 11 |
"path" |
| 12 |
"path/filepath" |
| 13 |
"runtime" |
| 14 |
"sort" |
| 15 |
"strconv" |
| 16 |
"sync/atomic" |
| 17 |
"text/tabwriter" |
| 18 |
|
| 19 |
"github.com/influxdata/influxdb/logger" |
| 20 |
"github.com/influxdata/influxdb/tsdb" |
| 21 |
"github.com/influxdata/influxdb/tsdb/index/tsi1" |
| 22 |
) |
| 23 |
|
| 24 |
const ( |
| 25 |
// Number of series IDs to stored in slice before we convert to a roaring |
| 26 |
// bitmap. Roaring bitmaps have a non-trivial initial cost to construct. |
| 27 |
useBitmapN = 25 |
| 28 |
) |
| 29 |
|
| 30 |
// Command represents the program execution for "influxd reporttsi". |
| 31 |
type Command struct { |
| 32 |
// Standard input/output, overridden for testing. |
| 33 |
Stderr io.Writer |
| 34 |
Stdout io.Writer |
| 35 |
|
| 36 |
dbPath string |
| 37 |
shardPaths map[uint64]string |
| 38 |
shardIdxs map[uint64]*tsi1.Index |
| 39 |
cardinalities map[uint64]map[string]*cardinality |
| 40 |
|
| 41 |
seriesFilePath string // optional. Defaults to dbPath/_series |
| 42 |
sfile *tsdb.SeriesFile |
| 43 |
|
| 44 |
topN int |
| 45 |
byMeasurement bool |
| 46 |
byTagKey bool |
| 47 |
|
| 48 |
// How many goroutines to dedicate to calculating cardinality. |
| 49 |
concurrency int |
| 50 |
} |
| 51 |
|
| 52 |
// NewCommand returns a new instance of Command with default setting applied. |
| 53 |
func NewCommand() *Command { |
| 54 |
return &Command{ |
| 55 |
Stderr: os.Stderr, |
| 56 |
Stdout: os.Stdout, |
| 57 |
shardPaths: map[uint64]string{}, |
| 58 |
shardIdxs: map[uint64]*tsi1.Index{}, |
| 59 |
cardinalities: map[uint64]map[string]*cardinality{}, |
| 60 |
topN: 0, |
| 61 |
byMeasurement: true, |
| 62 |
byTagKey: false, |
| 63 |
concurrency: runtime.GOMAXPROCS(0), |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
// Run executes the command. |
| 68 |
func (cmd *Command) Run(args ...string) error { |
| 69 |
fs := flag.NewFlagSet("reporttsi", flag.ExitOnError) |
| 70 |
fs.StringVar(&cmd.dbPath, "db-path", "", "Path to database. Required.") |
| 71 |
fs.StringVar(&cmd.seriesFilePath, "series-file", "", "Optional path to series file. Defaults /path/to/db-path/_series") |
| 72 |
fs.BoolVar(&cmd.byMeasurement, "measurements", true, "Segment cardinality by measurements") |
| 73 |
// TODO(edd): Not yet implemented. |
| 74 |
// fs.BoolVar(&cmd.byTagKey, "tag-key", false, "Segment cardinality by tag keys (overrides `measurements`") |
| 75 |
fs.IntVar(&cmd.topN, "top", 0, "Limit results to top n") |
| 76 |
fs.IntVar(&cmd.concurrency, "c", runtime.GOMAXPROCS(0), "Set worker concurrency. Defaults to GOMAXPROCS setting.") |
| 77 |
|
| 78 |
fs.SetOutput(cmd.Stdout) |
| 79 |
if err := fs.Parse(args); err != nil { |
| 80 |
return err |
| 81 |
} |
| 82 |
|
| 83 |
if cmd.byTagKey { |
| 84 |
return errors.New("Segmenting cardinality by tag key is not yet implemented") |
| 85 |
} |
| 86 |
|
| 87 |
if cmd.dbPath == "" { |
| 88 |
return errors.New("path to database must be provided") |
| 89 |
} |
| 90 |
|
| 91 |
if cmd.seriesFilePath == "" { |
| 92 |
cmd.seriesFilePath = path.Join(cmd.dbPath, tsdb.SeriesFileDirectory) |
| 93 |
} |
| 94 |
|
| 95 |
// Walk database directory to get shards. |
| 96 |
if err := filepath.Walk(cmd.dbPath, func(path string, info os.FileInfo, err error) error { |
| 97 |
if err != nil { |
| 98 |
return err |
| 99 |
} |
| 100 |
|
| 101 |
if !info.IsDir() { |
| 102 |
return nil |
| 103 |
} |
| 104 |
|
| 105 |
// TODO(edd): this would be a problem if the retention policy was named |
| 106 |
// "index". |
| 107 |
if info.Name() == tsdb.SeriesFileDirectory || info.Name() == "index" { |
| 108 |
return filepath.SkipDir |
| 109 |
} |
| 110 |
|
| 111 |
id, err := strconv.Atoi(info.Name()) |
| 112 |
if err != nil { |
| 113 |
return nil |
| 114 |
} |
| 115 |
cmd.shardPaths[uint64(id)] = path |
| 116 |
return nil |
| 117 |
}); err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
|
| 121 |
if len(cmd.shardPaths) == 0 { |
| 122 |
fmt.Fprintf(cmd.Stderr, "No shards under %s\n", cmd.dbPath) |
| 123 |
return nil |
| 124 |
} |
| 125 |
|
| 126 |
return cmd.run() |
| 127 |
} |
| 128 |
|
| 129 |
func (cmd *Command) run() error { |
| 130 |
cmd.sfile = tsdb.NewSeriesFile(cmd.seriesFilePath) |
| 131 |
cmd.sfile.Logger = logger.New(os.Stderr) |
| 132 |
if err := cmd.sfile.Open(); err != nil { |
| 133 |
return err |
| 134 |
} |
| 135 |
defer cmd.sfile.Close() |
| 136 |
|
| 137 |
// Open all the indexes. |
| 138 |
for id, pth := range cmd.shardPaths { |
| 139 |
pth = path.Join(pth, "index") |
| 140 |
// Verify directory is an index before opening it. |
| 141 |
if ok, err := tsi1.IsIndexDir(pth); err != nil { |
| 142 |
return err |
| 143 |
} else if !ok { |
| 144 |
return fmt.Errorf("not a TSI index directory: %q", pth) |
| 145 |
} |
| 146 |
|
| 147 |
cmd.shardIdxs[id] = tsi1.NewIndex(cmd.sfile, |
| 148 |
"", |
| 149 |
tsi1.WithPath(pth), |
| 150 |
tsi1.DisableCompactions(), |
| 151 |
) |
| 152 |
if err := cmd.shardIdxs[id].Open(); err != nil { |
| 153 |
return err |
| 154 |
} |
| 155 |
defer cmd.shardIdxs[id].Close() |
| 156 |
|
| 157 |
// Initialise cardinality set to store cardinalities for this shard. |
| 158 |
cmd.cardinalities[id] = map[string]*cardinality{} |
| 159 |
} |
| 160 |
|
| 161 |
// Calculate cardinalities of shards. |
| 162 |
fn := cmd.cardinalityByMeasurement |
| 163 |
// if cmd.byTagKey { |
| 164 |
// TODO(edd) |
| 165 |
// } |
| 166 |
|
| 167 |
// Blocks until all work done. |
| 168 |
cmd.calculateCardinalities(fn) |
| 169 |
|
| 170 |
// Print summary. |
| 171 |
if err := cmd.printSummaryByMeasurement(); err != nil { |
| 172 |
return err |
| 173 |
} |
| 174 |
|
| 175 |
allIDs := make([]uint64, 0, len(cmd.shardIdxs)) |
| 176 |
for id := range cmd.shardIdxs { |
| 177 |
allIDs = append(allIDs, id) |
| 178 |
} |
| 179 |
sort.Slice(allIDs, func(i int, j int) bool { return allIDs[i] < allIDs[j] }) |
| 180 |
|
| 181 |
for _, id := range allIDs { |
| 182 |
if err := cmd.printShardByMeasurement(id); err != nil { |
| 183 |
return err |
| 184 |
} |
| 185 |
} |
| 186 |
return nil |
| 187 |
} |
| 188 |
|
| 189 |
// calculateCardinalities calculates the cardinalities of the set of shard being |
| 190 |
// worked on concurrently. The provided function determines how cardinality is |
| 191 |
// calculated and broken down. |
| 192 |
func (cmd *Command) calculateCardinalities(fn func(id uint64) error) error { |
| 193 |
// Get list of shards to work on. |
| 194 |
shardIDs := make([]uint64, 0, len(cmd.shardIdxs)) |
| 195 |
for id := range cmd.shardIdxs { |
| 196 |
shardIDs = append(shardIDs, id) |
| 197 |
} |
| 198 |
|
| 199 |
errC := make(chan error, len(shardIDs)) |
| 200 |
var maxi uint32 // index of maximumm shard being worked on. |
| 201 |
for k := 0; k < cmd.concurrency; k++ { |
| 202 |
go func() { |
| 203 |
for { |
| 204 |
i := int(atomic.AddUint32(&maxi, 1) - 1) // Get next partition to work on. |
| 205 |
if i >= len(shardIDs) { |
| 206 |
return // No more work. |
| 207 |
} |
| 208 |
errC <- fn(shardIDs[i]) |
| 209 |
} |
| 210 |
}() |
| 211 |
} |
| 212 |
|
| 213 |
// Check for error |
| 214 |
for i := 0; i < cap(errC); i++ { |
| 215 |
if err := <-errC; err != nil { |
| 216 |
return err |
| 217 |
} |
| 218 |
} |
| 219 |
return nil |
| 220 |
} |
| 221 |
|
| 222 |
type cardinality struct { |
| 223 |
name []byte |
| 224 |
short []uint32 |
| 225 |
set *tsdb.SeriesIDSet |
| 226 |
} |
| 227 |
|
| 228 |
func (c *cardinality) add(x uint64) { |
| 229 |
if c.set != nil { |
| 230 |
c.set.AddNoLock(x) |
| 231 |
return |
| 232 |
} |
| 233 |
|
| 234 |
c.short = append(c.short, uint32(x)) // Series IDs never get beyond 2^32 |
| 235 |
|
| 236 |
// Cheaper to store in bitmap. |
| 237 |
if len(c.short) > useBitmapN { |
| 238 |
c.set = tsdb.NewSeriesIDSet() |
| 239 |
for i := 0; i < len(c.short); i++ { |
| 240 |
c.set.AddNoLock(uint64(c.short[i])) |
| 241 |
} |
| 242 |
c.short = nil |
| 243 |
return |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
func (c *cardinality) cardinality() int64 { |
| 248 |
if c == nil || (c.short == nil && c.set == nil) { |
| 249 |
return 0 |
| 250 |
} |
| 251 |
|
| 252 |
if c.short != nil { |
| 253 |
return int64(len(c.short)) |
| 254 |
} |
| 255 |
return int64(c.set.Cardinality()) |
| 256 |
} |
| 257 |
|
| 258 |
type cardinalities []*cardinality |
| 259 |
|
| 260 |
func (a cardinalities) Len() int { return len(a) } |
| 261 |
func (a cardinalities) Less(i, j int) bool { return a[i].cardinality() < a[j].cardinality() } |
| 262 |
func (a cardinalities) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 263 |
|
| 264 |
func (cmd *Command) cardinalityByMeasurement(shardID uint64) error { |
| 265 |
idx := cmd.shardIdxs[shardID] |
| 266 |
itr, err := idx.MeasurementIterator() |
| 267 |
if err != nil { |
| 268 |
return err |
| 269 |
} else if itr == nil { |
| 270 |
return nil |
| 271 |
} |
| 272 |
defer itr.Close() |
| 273 |
|
| 274 |
OUTER: |
| 275 |
for { |
| 276 |
name, err := itr.Next() |
| 277 |
if err != nil { |
| 278 |
return err |
| 279 |
} else if name == nil { |
| 280 |
break OUTER |
| 281 |
} |
| 282 |
|
| 283 |
// Get series ID set to track cardinality under measurement. |
| 284 |
c, ok := cmd.cardinalities[shardID][string(name)] |
| 285 |
if !ok { |
| 286 |
c = &cardinality{name: name} |
| 287 |
cmd.cardinalities[shardID][string(name)] = c |
| 288 |
} |
| 289 |
|
| 290 |
sitr, err := idx.MeasurementSeriesIDIterator(name) |
| 291 |
if err != nil { |
| 292 |
return err |
| 293 |
} else if sitr == nil { |
| 294 |
continue |
| 295 |
} |
| 296 |
|
| 297 |
var e tsdb.SeriesIDElem |
| 298 |
for e, err = sitr.Next(); err == nil && e.SeriesID != 0; e, err = sitr.Next() { |
| 299 |
if e.SeriesID > math.MaxUint32 { |
| 300 |
panic(fmt.Sprintf("series ID is too large: %d (max %d). Corrupted series file?", e.SeriesID, uint32(math.MaxUint32))) |
| 301 |
} |
| 302 |
c.add(e.SeriesID) |
| 303 |
} |
| 304 |
sitr.Close() |
| 305 |
|
| 306 |
if err != nil { |
| 307 |
return err |
| 308 |
} |
| 309 |
} |
| 310 |
return nil |
| 311 |
} |
| 312 |
|
| 313 |
type result struct { |
| 314 |
name []byte |
| 315 |
count int64 |
| 316 |
|
| 317 |
// For low cardinality measurements just track series using map |
| 318 |
lowCardinality map[uint32]struct{} |
| 319 |
|
| 320 |
// For higher cardinality measurements track using bitmap. |
| 321 |
set *tsdb.SeriesIDSet |
| 322 |
} |
| 323 |
|
| 324 |
func (r *result) addShort(ids []uint32) { |
| 325 |
// There is already a bitset of this result. |
| 326 |
if r.set != nil { |
| 327 |
for _, id := range ids { |
| 328 |
r.set.AddNoLock(uint64(id)) |
| 329 |
} |
| 330 |
return |
| 331 |
} |
| 332 |
|
| 333 |
// Still tracking low cardinality sets |
| 334 |
if r.lowCardinality == nil { |
| 335 |
r.lowCardinality = map[uint32]struct{}{} |
| 336 |
} |
| 337 |
|
| 338 |
for _, id := range ids { |
| 339 |
r.lowCardinality[id] = struct{}{} |
| 340 |
} |
| 341 |
|
| 342 |
// Cardinality is large enough that we will benefit from using a bitmap |
| 343 |
if len(r.lowCardinality) > useBitmapN { |
| 344 |
r.set = tsdb.NewSeriesIDSet() |
| 345 |
for id := range r.lowCardinality { |
| 346 |
r.set.AddNoLock(uint64(id)) |
| 347 |
} |
| 348 |
r.lowCardinality = nil |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
func (r *result) merge(other *tsdb.SeriesIDSet) { |
| 353 |
if r.set == nil { |
| 354 |
r.set = tsdb.NewSeriesIDSet() |
| 355 |
for id := range r.lowCardinality { |
| 356 |
r.set.AddNoLock(uint64(id)) |
| 357 |
} |
| 358 |
r.lowCardinality = nil |
| 359 |
} |
| 360 |
r.set.Merge(other) |
| 361 |
} |
| 362 |
|
| 363 |
type results []*result |
| 364 |
|
| 365 |
func (a results) Len() int { return len(a) } |
| 366 |
func (a results) Less(i, j int) bool { return a[i].count < a[j].count } |
| 367 |
func (a results) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 368 |
|
| 369 |
func (cmd *Command) printSummaryByMeasurement() error { |
| 370 |
// Get global set of measurement names across shards. |
| 371 |
idxs := &tsdb.IndexSet{SeriesFile: cmd.sfile} |
| 372 |
for _, idx := range cmd.shardIdxs { |
| 373 |
idxs.Indexes = append(idxs.Indexes, idx) |
| 374 |
} |
| 375 |
|
| 376 |
mitr, err := idxs.MeasurementIterator() |
| 377 |
if err != nil { |
| 378 |
return err |
| 379 |
} else if mitr == nil { |
| 380 |
return errors.New("got nil measurement iterator for index set") |
| 381 |
} |
| 382 |
defer mitr.Close() |
| 383 |
|
| 384 |
var name []byte |
| 385 |
var totalCardinality int64 |
| 386 |
measurements := results{} |
| 387 |
for name, err = mitr.Next(); err == nil && name != nil; name, err = mitr.Next() { |
| 388 |
res := &result{name: name} |
| 389 |
for _, shardCards := range cmd.cardinalities { |
| 390 |
other, ok := shardCards[string(name)] |
| 391 |
if !ok { |
| 392 |
continue // this shard doesn't have anything for this measurement. |
| 393 |
} |
| 394 |
|
| 395 |
if other.short != nil && other.set != nil { |
| 396 |
panic("cardinality stored incorrectly") |
| 397 |
} |
| 398 |
|
| 399 |
if other.short != nil { // low cardinality case |
| 400 |
res.addShort(other.short) |
| 401 |
} else if other.set != nil { // High cardinality case |
| 402 |
res.merge(other.set) |
| 403 |
} |
| 404 |
|
| 405 |
// Shard does not have any series for this measurement. |
| 406 |
} |
| 407 |
|
| 408 |
// Determine final cardinality and allow intermediate structures to be |
| 409 |
// GCd. |
| 410 |
if res.lowCardinality != nil { |
| 411 |
res.count = int64(len(res.lowCardinality)) |
| 412 |
} else { |
| 413 |
res.count = int64(res.set.Cardinality()) |
| 414 |
} |
| 415 |
totalCardinality += res.count |
| 416 |
res.set = nil |
| 417 |
res.lowCardinality = nil |
| 418 |
measurements = append(measurements, res) |
| 419 |
} |
| 420 |
|
| 421 |
if err != nil { |
| 422 |
return err |
| 423 |
} |
| 424 |
|
| 425 |
// sort measurements by cardinality. |
| 426 |
sort.Sort(sort.Reverse(measurements)) |
| 427 |
|
| 428 |
if cmd.topN > 0 { |
| 429 |
// There may not be "topN" measurement cardinality to sub-slice. |
| 430 |
n := int(math.Min(float64(cmd.topN), float64(len(measurements)))) |
| 431 |
measurements = measurements[:n] |
| 432 |
} |
| 433 |
|
| 434 |
tw := tabwriter.NewWriter(cmd.Stdout, 4, 4, 1, '\t', 0) |
| 435 |
fmt.Fprintf(tw, "Summary\nDatabase Path: %s\nCardinality (exact): %d\n\n", cmd.dbPath, totalCardinality) |
| 436 |
fmt.Fprint(tw, "Measurement\tCardinality (exact)\n\n") |
| 437 |
for _, res := range measurements { |
| 438 |
fmt.Fprintf(tw, "%q\t\t%d\n", res.name, res.count) |
| 439 |
} |
| 440 |
|
| 441 |
if err := tw.Flush(); err != nil { |
| 442 |
return err |
| 443 |
} |
| 444 |
fmt.Fprint(cmd.Stdout, "\n\n") |
| 445 |
return nil |
| 446 |
} |
| 447 |
|
| 448 |
func (cmd *Command) printShardByMeasurement(id uint64) error { |
| 449 |
allMap, ok := cmd.cardinalities[id] |
| 450 |
if !ok { |
| 451 |
return nil |
| 452 |
} |
| 453 |
|
| 454 |
var totalCardinality int64 |
| 455 |
all := make(cardinalities, 0, len(allMap)) |
| 456 |
for _, card := range allMap { |
| 457 |
n := card.cardinality() |
| 458 |
if n == 0 { |
| 459 |
continue |
| 460 |
} |
| 461 |
|
| 462 |
totalCardinality += n |
| 463 |
all = append(all, card) |
| 464 |
} |
| 465 |
|
| 466 |
sort.Sort(sort.Reverse(all)) |
| 467 |
|
| 468 |
// Trim to top-n |
| 469 |
if cmd.topN > 0 { |
| 470 |
// There may not be "topN" measurement cardinality to sub-slice. |
| 471 |
n := int(math.Min(float64(cmd.topN), float64(len(all)))) |
| 472 |
all = all[:n] |
| 473 |
} |
| 474 |
|
| 475 |
tw := tabwriter.NewWriter(cmd.Stdout, 4, 4, 1, '\t', 0) |
| 476 |
fmt.Fprintf(tw, "===============\nShard ID: %d\nPath: %s\nCardinality (exact): %d\n\n", id, cmd.shardPaths[id], totalCardinality) |
| 477 |
fmt.Fprint(tw, "Measurement\tCardinality (exact)\n\n") |
| 478 |
for _, card := range all { |
| 479 |
fmt.Fprintf(tw, "%q\t\t%d\n", card.name, card.cardinality()) |
| 480 |
} |
| 481 |
fmt.Fprint(tw, "===============\n\n") |
| 482 |
if err := tw.Flush(); err != nil { |
| 483 |
return err |
| 484 |
} |
| 485 |
fmt.Fprint(cmd.Stdout, "\n\n") |
| 486 |
return nil |
| 487 |
} |