2019-05-22 23:16:55 +02:00
package storage
import (
2020-09-17 02:02:35 +02:00
"errors"
2019-05-22 23:16:55 +02:00
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
2020-12-08 19:49:32 +01:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/cgroup"
2019-05-22 23:16:55 +02:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/encoding"
2020-05-14 21:01:51 +02:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/fasttime"
2019-05-22 23:16:55 +02:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/fs"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/memory"
2020-07-22 23:58:48 +02:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/storagepacelimiter"
2019-12-04 20:35:51 +01:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/syncwg"
2019-09-24 20:10:22 +02:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/uint64set"
2019-05-22 23:16:55 +02:00
)
2021-08-25 08:35:03 +02:00
func maxSmallPartSize ( ) uint64 {
2019-08-25 13:39:39 +02:00
// Small parts are cached in the OS page cache,
2021-08-25 08:35:03 +02:00
// so limit their size by the remaining free RAM.
2019-08-25 13:39:39 +02:00
mem := memory . Remaining ( )
2019-09-09 10:41:30 +02:00
// It is expected no more than defaultPartsToMerge/2 parts exist
// in the OS page cache before they are merged into bigger part.
2019-10-08 17:51:14 +02:00
// Half of the remaining RAM must be left for lib/mergeset parts,
2019-09-09 10:41:30 +02:00
// so the maxItems is calculated using the below code:
2021-08-25 08:35:03 +02:00
maxSize := uint64 ( mem ) / defaultPartsToMerge
if maxSize < 10e6 {
maxSize = 10e6
2019-08-25 13:39:39 +02:00
}
2021-08-25 08:35:03 +02:00
return maxSize
2019-08-25 13:39:39 +02:00
}
2019-05-22 23:16:55 +02:00
2021-08-25 08:35:03 +02:00
// The maximum size of big part.
2019-05-22 23:16:55 +02:00
//
// This number limits the maximum time required for building big part.
// This time shouldn't exceed a few days.
2021-08-25 08:35:03 +02:00
const maxBigPartSize = 1e12
2019-05-22 23:16:55 +02:00
// The maximum number of small parts in the partition.
const maxSmallPartsPerPartition = 256
// Default number of parts to merge at once.
//
// This number has been obtained empirically - it gives the lowest possible overhead.
// See appendPartsToMerge tests for details.
const defaultPartsToMerge = 15
// The final number of parts to merge at once.
//
// It must be smaller than defaultPartsToMerge.
// Lower value improves select performance at the cost of increased
// write amplification.
2019-11-05 16:26:13 +01:00
const finalPartsToMerge = 3
2019-05-22 23:16:55 +02:00
2019-12-19 17:12:02 +01:00
// The number of shards for rawRow entries per partition.
//
// Higher number of shards reduces CPU contention and increases the max bandwidth on multi-core systems.
2020-12-08 19:49:32 +01:00
var rawRowsShardsPerPartition = ( cgroup . AvailableCPUs ( ) + 7 ) / 8
2019-12-19 17:12:02 +01:00
2021-06-11 09:52:14 +02:00
// getMaxRawRowsPerShard returns the maximum number of rows that haven't been converted into parts yet.
func getMaxRawRowsPerShard ( ) int {
2019-05-22 23:16:55 +02:00
maxRawRowsPerPartitionOnce . Do ( func ( ) {
2021-06-11 09:49:02 +02:00
n := memory . Allowed ( ) / rawRowsShardsPerPartition / 256 / int ( unsafe . Sizeof ( rawRow { } ) )
2019-05-22 23:16:55 +02:00
if n < 1e4 {
n = 1e4
}
if n > 500e3 {
n = 500e3
}
2020-01-04 18:49:30 +01:00
maxRawRowsPerPartition = n
2019-05-22 23:16:55 +02:00
} )
return maxRawRowsPerPartition
}
var (
maxRawRowsPerPartition int
maxRawRowsPerPartitionOnce sync . Once
)
// The interval for flushing (converting) recent raw rows into parts,
// so they become visible to search.
const rawRowsFlushInterval = time . Second
// The interval for flushing inmemory parts to persistent storage,
// so they survive process crash.
const inmemoryPartsFlushInterval = 5 * time . Second
// partition represents a partition.
type partition struct {
2019-10-17 17:22:56 +02:00
// Put atomic counters to the top of struct, so they are aligned to 8 bytes on 32-bit arch.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/212
activeBigMerges uint64
activeSmallMerges uint64
bigMergesCount uint64
smallMergesCount uint64
bigRowsMerged uint64
smallRowsMerged uint64
bigRowsDeleted uint64
smallRowsDeleted uint64
smallAssistedMerges uint64
2020-09-29 21:51:43 +02:00
smallMergeNeedFreeDiskSpace uint64
bigMergeNeedFreeDiskSpace uint64
2019-10-17 17:22:56 +02:00
mergeIdx uint64
2019-05-22 23:16:55 +02:00
smallPartsPath string
bigPartsPath string
// The callack that returns deleted metric ids which must be skipped during merge.
2019-09-24 20:10:22 +02:00
getDeletedMetricIDs func ( ) * uint64set . Set
2019-05-22 23:16:55 +02:00
2020-10-20 13:29:26 +02:00
// data retention in milliseconds.
// Used for deleting data outside the retention during background merge.
retentionMsecs int64
2019-05-22 23:16:55 +02:00
// Name is the name of the partition in the form YYYY_MM.
name string
// The time range for the partition. Usually this is a whole month.
tr TimeRange
// partsLock protects smallParts and bigParts.
partsLock sync . Mutex
// Contains all the inmemoryPart plus file-based parts
// with small number of items (up to maxRowsCountPerSmallPart).
smallParts [ ] * partWrapper
// Contains file-based parts with big number of items.
bigParts [ ] * partWrapper
// rawRows contains recently added rows that haven't been converted into parts yet.
//
// rawRows aren't used in search for performance reasons.
2019-12-19 17:12:02 +01:00
rawRows rawRowsShards
2019-05-22 23:16:55 +02:00
snapshotLock sync . RWMutex
stopCh chan struct { }
smallPartsMergerWG sync . WaitGroup
bigPartsMergerWG sync . WaitGroup
rawRowsFlusherWG sync . WaitGroup
inmemoryPartsFlusherWG sync . WaitGroup
2020-12-22 18:48:27 +01:00
stalePartsRemoverWG sync . WaitGroup
2019-05-22 23:16:55 +02:00
}
// partWrapper is a wrapper for the part.
type partWrapper struct {
2019-10-17 17:22:56 +02:00
// Put atomic counters to the top of struct, so they are aligned to 8 bytes on 32-bit arch.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/212
// The number of references to the part.
refCount uint64
2019-05-22 23:16:55 +02:00
// The part itself.
p * part
// non-nil if the part is inmemoryPart.
mp * inmemoryPart
// Whether the part is in merge now.
isInMerge bool
}
func ( pw * partWrapper ) incRef ( ) {
atomic . AddUint64 ( & pw . refCount , 1 )
}
func ( pw * partWrapper ) decRef ( ) {
n := atomic . AddUint64 ( & pw . refCount , ^ uint64 ( 0 ) )
if int64 ( n ) < 0 {
logger . Panicf ( "BUG: pw.refCount must be bigger than 0; got %d" , int64 ( n ) )
}
if n > 0 {
return
}
if pw . mp != nil {
putInmemoryPart ( pw . mp )
pw . mp = nil
}
pw . p . MustClose ( )
pw . p = nil
}
// createPartition creates new partition for the given timestamp and the given paths
// to small and big partitions.
2020-10-20 13:29:26 +02:00
func createPartition ( timestamp int64 , smallPartitionsPath , bigPartitionsPath string , getDeletedMetricIDs func ( ) * uint64set . Set , retentionMsecs int64 ) ( * partition , error ) {
2019-05-22 23:16:55 +02:00
name := timestampToPartitionName ( timestamp )
smallPartsPath := filepath . Clean ( smallPartitionsPath ) + "/" + name
bigPartsPath := filepath . Clean ( bigPartitionsPath ) + "/" + name
logger . Infof ( "creating a partition %q with smallPartsPath=%q, bigPartsPath=%q" , name , smallPartsPath , bigPartsPath )
if err := createPartitionDirs ( smallPartsPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot create directories for small parts %q: %w" , smallPartsPath , err )
2019-05-22 23:16:55 +02:00
}
if err := createPartitionDirs ( bigPartsPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot create directories for big parts %q: %w" , bigPartsPath , err )
2019-05-22 23:16:55 +02:00
}
2020-10-20 13:29:26 +02:00
pt := newPartition ( name , smallPartsPath , bigPartsPath , getDeletedMetricIDs , retentionMsecs )
2019-05-22 23:16:55 +02:00
pt . tr . fromPartitionTimestamp ( timestamp )
pt . startMergeWorkers ( )
pt . startRawRowsFlusher ( )
pt . startInmemoryPartsFlusher ( )
2021-05-03 10:34:00 +02:00
pt . startStalePartsRemover ( )
2019-05-22 23:16:55 +02:00
logger . Infof ( "partition %q has been created" , name )
return pt , nil
}
// Drop drops all the data on the storage for the given pt.
//
// The pt must be detached from table before calling pt.Drop.
func ( pt * partition ) Drop ( ) {
logger . Infof ( "dropping partition %q at smallPartsPath=%q, bigPartsPath=%q" , pt . name , pt . smallPartsPath , pt . bigPartsPath )
2020-12-25 10:45:47 +01:00
// Wait until all the pending transaction deletions are finished before removing partition directories.
pendingTxnDeletionsWG . Wait ( )
2019-06-12 00:53:43 +02:00
fs . MustRemoveAll ( pt . smallPartsPath )
fs . MustRemoveAll ( pt . bigPartsPath )
2019-05-22 23:16:55 +02:00
logger . Infof ( "partition %q has been dropped" , pt . name )
}
// openPartition opens the existing partition from the given paths.
2020-10-20 13:29:26 +02:00
func openPartition ( smallPartsPath , bigPartsPath string , getDeletedMetricIDs func ( ) * uint64set . Set , retentionMsecs int64 ) ( * partition , error ) {
2019-05-22 23:16:55 +02:00
smallPartsPath = filepath . Clean ( smallPartsPath )
bigPartsPath = filepath . Clean ( bigPartsPath )
n := strings . LastIndexByte ( smallPartsPath , '/' )
if n < 0 {
return nil , fmt . Errorf ( "cannot find partition name from smallPartsPath %q; must be in the form /path/to/smallparts/YYYY_MM" , smallPartsPath )
}
name := smallPartsPath [ n + 1 : ]
if ! strings . HasSuffix ( bigPartsPath , "/" + name ) {
return nil , fmt . Errorf ( "patititon name in bigPartsPath %q doesn't match smallPartsPath %q; want %q" , bigPartsPath , smallPartsPath , name )
}
smallParts , err := openParts ( smallPartsPath , bigPartsPath , smallPartsPath )
if err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot open small parts from %q: %w" , smallPartsPath , err )
2019-05-22 23:16:55 +02:00
}
bigParts , err := openParts ( smallPartsPath , bigPartsPath , bigPartsPath )
if err != nil {
mustCloseParts ( smallParts )
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot open big parts from %q: %w" , bigPartsPath , err )
2019-05-22 23:16:55 +02:00
}
2020-10-20 13:29:26 +02:00
pt := newPartition ( name , smallPartsPath , bigPartsPath , getDeletedMetricIDs , retentionMsecs )
2019-05-22 23:16:55 +02:00
pt . smallParts = smallParts
pt . bigParts = bigParts
if err := pt . tr . fromPartitionName ( name ) ; err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot obtain partition time range from smallPartsPath %q: %w" , smallPartsPath , err )
2019-05-22 23:16:55 +02:00
}
pt . startMergeWorkers ( )
pt . startRawRowsFlusher ( )
pt . startInmemoryPartsFlusher ( )
2020-12-22 18:48:27 +01:00
pt . startStalePartsRemover ( )
2019-05-22 23:16:55 +02:00
return pt , nil
}
2020-10-20 13:29:26 +02:00
func newPartition ( name , smallPartsPath , bigPartsPath string , getDeletedMetricIDs func ( ) * uint64set . Set , retentionMsecs int64 ) * partition {
2019-12-19 17:12:02 +01:00
p := & partition {
2019-05-22 23:16:55 +02:00
name : name ,
smallPartsPath : smallPartsPath ,
bigPartsPath : bigPartsPath ,
getDeletedMetricIDs : getDeletedMetricIDs ,
2020-10-20 13:29:26 +02:00
retentionMsecs : retentionMsecs ,
2019-05-22 23:16:55 +02:00
mergeIdx : uint64 ( time . Now ( ) . UnixNano ( ) ) ,
stopCh : make ( chan struct { } ) ,
}
2019-12-19 17:12:02 +01:00
p . rawRows . init ( )
return p
2019-05-22 23:16:55 +02:00
}
// partitionMetrics contains essential metrics for the partition.
type partitionMetrics struct {
PendingRows uint64
2022-01-20 17:34:59 +01:00
IndexBlocksCacheSize uint64
IndexBlocksCacheSizeBytes uint64
IndexBlocksCacheSizeMaxBytes uint64
IndexBlocksCacheRequests uint64
IndexBlocksCacheMisses uint64
2019-05-22 23:16:55 +02:00
2019-07-04 18:09:40 +02:00
BigSizeBytes uint64
SmallSizeBytes uint64
2019-05-22 23:16:55 +02:00
BigRowsCount uint64
SmallRowsCount uint64
BigBlocksCount uint64
SmallBlocksCount uint64
BigPartsCount uint64
SmallPartsCount uint64
ActiveBigMerges uint64
ActiveSmallMerges uint64
BigMergesCount uint64
SmallMergesCount uint64
BigRowsMerged uint64
SmallRowsMerged uint64
BigRowsDeleted uint64
SmallRowsDeleted uint64
BigPartsRefCount uint64
SmallPartsRefCount uint64
SmallAssistedMerges uint64
2020-09-29 20:47:40 +02:00
SmallMergeNeedFreeDiskSpace uint64
BigMergeNeedFreeDiskSpace uint64
2019-05-22 23:16:55 +02:00
}
// UpdateMetrics updates m with metrics from pt.
func ( pt * partition ) UpdateMetrics ( m * partitionMetrics ) {
2019-12-19 17:12:02 +01:00
rawRowsLen := uint64 ( pt . rawRows . Len ( ) )
m . PendingRows += rawRowsLen
m . SmallRowsCount += rawRowsLen
2019-05-22 23:16:55 +02:00
pt . partsLock . Lock ( )
for _ , pw := range pt . bigParts {
p := pw . p
m . BigRowsCount += p . ph . RowsCount
m . BigBlocksCount += p . ph . BlocksCount
2019-07-04 18:09:40 +02:00
m . BigSizeBytes += p . size
2019-05-22 23:16:55 +02:00
m . BigPartsRefCount += atomic . LoadUint64 ( & pw . refCount )
}
for _ , pw := range pt . smallParts {
p := pw . p
m . SmallRowsCount += p . ph . RowsCount
m . SmallBlocksCount += p . ph . BlocksCount
2019-07-04 18:09:40 +02:00
m . SmallSizeBytes += p . size
2019-05-22 23:16:55 +02:00
m . SmallPartsRefCount += atomic . LoadUint64 ( & pw . refCount )
}
m . BigPartsCount += uint64 ( len ( pt . bigParts ) )
m . SmallPartsCount += uint64 ( len ( pt . smallParts ) )
pt . partsLock . Unlock ( )
2022-01-20 17:34:59 +01:00
m . IndexBlocksCacheSize = uint64 ( ibCache . Len ( ) )
m . IndexBlocksCacheSizeBytes = uint64 ( ibCache . SizeBytes ( ) )
m . IndexBlocksCacheSizeMaxBytes = uint64 ( ibCache . SizeMaxBytes ( ) )
m . IndexBlocksCacheRequests = ibCache . Requests ( )
m . IndexBlocksCacheMisses = ibCache . Misses ( )
2019-05-22 23:16:55 +02:00
m . ActiveBigMerges += atomic . LoadUint64 ( & pt . activeBigMerges )
m . ActiveSmallMerges += atomic . LoadUint64 ( & pt . activeSmallMerges )
m . BigMergesCount += atomic . LoadUint64 ( & pt . bigMergesCount )
m . SmallMergesCount += atomic . LoadUint64 ( & pt . smallMergesCount )
m . BigRowsMerged += atomic . LoadUint64 ( & pt . bigRowsMerged )
m . SmallRowsMerged += atomic . LoadUint64 ( & pt . smallRowsMerged )
m . BigRowsDeleted += atomic . LoadUint64 ( & pt . bigRowsDeleted )
m . SmallRowsDeleted += atomic . LoadUint64 ( & pt . smallRowsDeleted )
m . SmallAssistedMerges += atomic . LoadUint64 ( & pt . smallAssistedMerges )
2020-09-29 20:47:40 +02:00
2020-09-29 21:51:43 +02:00
m . SmallMergeNeedFreeDiskSpace += atomic . LoadUint64 ( & pt . smallMergeNeedFreeDiskSpace )
m . BigMergeNeedFreeDiskSpace += atomic . LoadUint64 ( & pt . bigMergeNeedFreeDiskSpace )
2019-05-22 23:16:55 +02:00
}
// AddRows adds the given rows to the partition pt.
//
// All the rows must fit the partition by timestamp range
// and must have valid PrecisionBits.
func ( pt * partition ) AddRows ( rows [ ] rawRow ) {
if len ( rows ) == 0 {
return
}
// Validate all the rows.
for i := range rows {
r := & rows [ i ]
if ! pt . HasTimestamp ( r . Timestamp ) {
logger . Panicf ( "BUG: row %+v has Timestamp outside partition %q range %+v" , r , pt . smallPartsPath , & pt . tr )
}
if err := encoding . CheckPrecisionBits ( r . PrecisionBits ) ; err != nil {
logger . Panicf ( "BUG: row %+v has invalid PrecisionBits: %s" , r , err )
}
}
2019-12-19 17:12:02 +01:00
pt . rawRows . addRows ( pt , rows )
}
type rawRowsShards struct {
2021-04-27 15:41:22 +02:00
shardIdx uint32
2019-12-19 17:12:02 +01:00
// Shards reduce lock contention when adding rows on multi-CPU systems.
shards [ ] rawRowsShard
}
2021-04-27 14:36:31 +02:00
func ( rrss * rawRowsShards ) init ( ) {
rrss . shards = make ( [ ] rawRowsShard , rawRowsShardsPerPartition )
2019-12-19 17:12:02 +01:00
}
2021-04-27 14:36:31 +02:00
func ( rrss * rawRowsShards ) addRows ( pt * partition , rows [ ] rawRow ) {
2021-04-27 15:41:22 +02:00
n := atomic . AddUint32 ( & rrss . shardIdx , 1 )
2021-04-27 14:36:31 +02:00
shards := rrss . shards
2021-04-27 15:41:22 +02:00
idx := n % uint32 ( len ( shards ) )
2021-04-27 14:36:31 +02:00
shard := & shards [ idx ]
2019-12-19 17:12:02 +01:00
shard . addRows ( pt , rows )
}
2021-04-27 14:36:31 +02:00
func ( rrss * rawRowsShards ) Len ( ) int {
2019-12-19 17:12:02 +01:00
n := 0
2021-04-27 14:36:31 +02:00
for i := range rrss . shards [ : ] {
n += rrss . shards [ i ] . Len ( )
2019-12-19 17:12:02 +01:00
}
return n
}
type rawRowsShard struct {
2021-04-27 14:36:31 +02:00
mu sync . Mutex
2019-12-19 17:12:02 +01:00
rows [ ] rawRow
2020-05-14 21:01:51 +02:00
lastFlushTime uint64
2019-12-19 17:12:02 +01:00
}
func ( rrs * rawRowsShard ) Len ( ) int {
2021-04-27 14:36:31 +02:00
rrs . mu . Lock ( )
2019-12-19 17:12:02 +01:00
n := len ( rrs . rows )
2021-04-27 14:36:31 +02:00
rrs . mu . Unlock ( )
2019-12-19 17:12:02 +01:00
return n
}
func ( rrs * rawRowsShard ) addRows ( pt * partition , rows [ ] rawRow ) {
2021-06-17 12:42:32 +02:00
var rowsToFlush [ ] rawRow
2019-12-19 17:12:02 +01:00
2021-04-27 14:36:31 +02:00
rrs . mu . Lock ( )
2019-12-19 17:12:02 +01:00
if cap ( rrs . rows ) == 0 {
2021-06-17 12:42:32 +02:00
n := getMaxRawRowsPerShard ( )
rrs . rows = make ( [ ] rawRow , 0 , n )
2019-12-19 17:12:02 +01:00
}
2021-05-24 14:22:57 +02:00
maxRowsCount := cap ( rrs . rows )
2021-06-17 13:27:14 +02:00
capacity := maxRowsCount - len ( rrs . rows )
if capacity >= len ( rows ) {
// Fast path - rows fit capacity.
rrs . rows = append ( rrs . rows , rows ... )
} else {
2019-05-22 23:16:55 +02:00
// Slow path - rows don't fit capacity.
2021-06-17 12:42:32 +02:00
// Put rrs.rows and rows to rowsToFlush and convert it to a part.
rowsToFlush = append ( rowsToFlush , rrs . rows ... )
rowsToFlush = append ( rowsToFlush , rows ... )
rrs . rows = rrs . rows [ : 0 ]
2020-05-14 21:01:51 +02:00
rrs . lastFlushTime = fasttime . UnixTimestamp ( )
2019-05-22 23:16:55 +02:00
}
2021-04-27 14:36:31 +02:00
rrs . mu . Unlock ( )
2019-05-22 23:16:55 +02:00
2021-06-17 12:42:32 +02:00
pt . flushRowsToParts ( rowsToFlush )
2019-05-22 23:16:55 +02:00
}
2021-06-17 12:42:32 +02:00
func ( pt * partition ) flushRowsToParts ( rows [ ] rawRow ) {
maxRows := getMaxRawRowsPerShard ( )
var wg sync . WaitGroup
for len ( rows ) > 0 {
n := maxRows
if n > len ( rows ) {
n = len ( rows )
2019-05-22 23:16:55 +02:00
}
2021-06-17 12:42:32 +02:00
wg . Add ( 1 )
go func ( rowsPart [ ] rawRow ) {
defer wg . Done ( )
pt . addRowsPart ( rowsPart )
} ( rows [ : n ] )
rows = rows [ n : ]
2019-05-22 23:16:55 +02:00
}
2021-06-17 12:42:32 +02:00
wg . Wait ( )
2019-05-22 23:16:55 +02:00
}
func ( pt * partition ) addRowsPart ( rows [ ] rawRow ) {
if len ( rows ) == 0 {
return
}
mp := getInmemoryPart ( )
mp . InitFromRows ( rows )
// Make sure the part may be added.
if mp . ph . MinTimestamp > mp . ph . MaxTimestamp {
logger . Panicf ( "BUG: the part %q cannot be added to partition %q because its MinTimestamp exceeds MaxTimestamp; %d vs %d" ,
& mp . ph , pt . smallPartsPath , mp . ph . MinTimestamp , mp . ph . MaxTimestamp )
}
if mp . ph . MinTimestamp < pt . tr . MinTimestamp {
logger . Panicf ( "BUG: the part %q cannot be added to partition %q because of too small MinTimestamp; got %d; want at least %d" ,
& mp . ph , pt . smallPartsPath , mp . ph . MinTimestamp , pt . tr . MinTimestamp )
}
if mp . ph . MaxTimestamp > pt . tr . MaxTimestamp {
logger . Panicf ( "BUG: the part %q cannot be added to partition %q because of too big MaxTimestamp; got %d; want at least %d" ,
& mp . ph , pt . smallPartsPath , mp . ph . MaxTimestamp , pt . tr . MaxTimestamp )
}
p , err := mp . NewPart ( )
if err != nil {
logger . Panicf ( "BUG: cannot create part from %q: %s" , & mp . ph , err )
}
pw := & partWrapper {
p : p ,
mp : mp ,
refCount : 1 ,
}
pt . partsLock . Lock ( )
pt . smallParts = append ( pt . smallParts , pw )
ok := len ( pt . smallParts ) <= maxSmallPartsPerPartition
pt . partsLock . Unlock ( )
if ok {
return
}
// The added part exceeds available limit. Help merging parts.
2020-07-22 23:58:48 +02:00
//
// Prioritize assisted merges over searches.
storagepacelimiter . Search . Inc ( )
2019-05-22 23:16:55 +02:00
err = pt . mergeSmallParts ( false )
2020-07-22 23:58:48 +02:00
storagepacelimiter . Search . Dec ( )
2019-05-22 23:16:55 +02:00
if err == nil {
atomic . AddUint64 ( & pt . smallAssistedMerges , 1 )
return
}
2020-09-17 02:02:35 +02:00
if errors . Is ( err , errNothingToMerge ) || errors . Is ( err , errForciblyStopped ) {
2019-05-22 23:16:55 +02:00
return
}
logger . Panicf ( "FATAL: cannot merge small parts: %s" , err )
}
// HasTimestamp returns true if the pt contains the given timestamp.
func ( pt * partition ) HasTimestamp ( timestamp int64 ) bool {
return timestamp >= pt . tr . MinTimestamp && timestamp <= pt . tr . MaxTimestamp
}
// GetParts appends parts snapshot to dst and returns it.
//
// The appended parts must be released with PutParts.
func ( pt * partition ) GetParts ( dst [ ] * partWrapper ) [ ] * partWrapper {
pt . partsLock . Lock ( )
for _ , pw := range pt . smallParts {
pw . incRef ( )
}
dst = append ( dst , pt . smallParts ... )
for _ , pw := range pt . bigParts {
pw . incRef ( )
}
dst = append ( dst , pt . bigParts ... )
pt . partsLock . Unlock ( )
return dst
}
// PutParts releases the given pws obtained via GetParts.
func ( pt * partition ) PutParts ( pws [ ] * partWrapper ) {
for _ , pw := range pws {
pw . decRef ( )
}
}
// MustClose closes the pt, so the app may safely exit.
//
// The pt must be detached from table before calling pt.MustClose.
func ( pt * partition ) MustClose ( ) {
close ( pt . stopCh )
2020-12-25 10:45:47 +01:00
// Wait until all the pending transaction deletions are finished.
pendingTxnDeletionsWG . Wait ( )
2020-12-22 18:48:27 +01:00
logger . Infof ( "waiting for stale parts remover to stop on %q..." , pt . smallPartsPath )
2019-05-22 23:16:55 +02:00
startTime := time . Now ( )
2020-12-22 18:48:27 +01:00
pt . stalePartsRemoverWG . Wait ( )
logger . Infof ( "stale parts remover stopped in %.3f seconds on %q" , time . Since ( startTime ) . Seconds ( ) , pt . smallPartsPath )
logger . Infof ( "waiting for inmemory parts flusher to stop on %q..." , pt . smallPartsPath )
startTime = time . Now ( )
2019-05-22 23:16:55 +02:00
pt . inmemoryPartsFlusherWG . Wait ( )
2020-01-22 17:27:44 +01:00
logger . Infof ( "inmemory parts flusher stopped in %.3f seconds on %q" , time . Since ( startTime ) . Seconds ( ) , pt . smallPartsPath )
2019-05-22 23:16:55 +02:00
logger . Infof ( "waiting for raw rows flusher to stop on %q..." , pt . smallPartsPath )
startTime = time . Now ( )
pt . rawRowsFlusherWG . Wait ( )
2020-01-22 17:27:44 +01:00
logger . Infof ( "raw rows flusher stopped in %.3f seconds on %q" , time . Since ( startTime ) . Seconds ( ) , pt . smallPartsPath )
2019-05-22 23:16:55 +02:00
logger . Infof ( "waiting for small part mergers to stop on %q..." , pt . smallPartsPath )
startTime = time . Now ( )
pt . smallPartsMergerWG . Wait ( )
2020-01-22 17:27:44 +01:00
logger . Infof ( "small part mergers stopped in %.3f seconds on %q" , time . Since ( startTime ) . Seconds ( ) , pt . smallPartsPath )
2019-05-22 23:16:55 +02:00
logger . Infof ( "waiting for big part mergers to stop on %q..." , pt . bigPartsPath )
startTime = time . Now ( )
pt . bigPartsMergerWG . Wait ( )
2020-01-22 17:27:44 +01:00
logger . Infof ( "big part mergers stopped in %.3f seconds on %q" , time . Since ( startTime ) . Seconds ( ) , pt . bigPartsPath )
2019-05-22 23:16:55 +02:00
logger . Infof ( "flushing inmemory parts to files on %q..." , pt . smallPartsPath )
startTime = time . Now ( )
// Flush raw rows the last time before exit.
2019-12-19 17:12:02 +01:00
pt . flushRawRows ( true )
2019-05-22 23:16:55 +02:00
// Flush inmemory parts to disk.
var pws [ ] * partWrapper
pt . partsLock . Lock ( )
for _ , pw := range pt . smallParts {
if pw . mp == nil {
continue
}
if pw . isInMerge {
logger . Panicf ( "BUG: the inmemory part %q mustn't be in merge after stopping small parts merger in the partition %q" , & pw . mp . ph , pt . smallPartsPath )
}
pw . isInMerge = true
pws = append ( pws , pw )
}
pt . partsLock . Unlock ( )
2020-09-17 11:01:53 +02:00
if err := pt . mergePartsOptimal ( pws , nil ) ; err != nil {
2019-05-22 23:16:55 +02:00
logger . Panicf ( "FATAL: cannot flush %d inmemory parts to files on %q: %s" , len ( pws ) , pt . smallPartsPath , err )
}
2020-01-22 17:27:44 +01:00
logger . Infof ( "%d inmemory parts have been flushed to files in %.3f seconds on %q" , len ( pws ) , time . Since ( startTime ) . Seconds ( ) , pt . smallPartsPath )
2019-05-22 23:16:55 +02:00
// Remove references to smallParts from the pt, so they may be eventually closed
2019-05-25 20:51:11 +02:00
// after all the searches are done.
2019-05-22 23:16:55 +02:00
pt . partsLock . Lock ( )
smallParts := pt . smallParts
pt . smallParts = nil
pt . partsLock . Unlock ( )
for _ , pw := range smallParts {
pw . decRef ( )
}
// Remove references to bigParts from the pt, so they may be eventually closed
// after all the searches are done.
pt . partsLock . Lock ( )
bigParts := pt . bigParts
pt . bigParts = nil
pt . partsLock . Unlock ( )
for _ , pw := range bigParts {
pw . decRef ( )
}
}
func ( pt * partition ) startRawRowsFlusher ( ) {
pt . rawRowsFlusherWG . Add ( 1 )
go func ( ) {
pt . rawRowsFlusher ( )
pt . rawRowsFlusherWG . Done ( )
} ( )
}
func ( pt * partition ) rawRowsFlusher ( ) {
2020-02-13 11:55:58 +01:00
ticker := time . NewTicker ( rawRowsFlushInterval )
defer ticker . Stop ( )
2019-05-22 23:16:55 +02:00
for {
select {
case <- pt . stopCh :
return
2020-02-13 11:55:58 +01:00
case <- ticker . C :
pt . flushRawRows ( false )
2019-05-22 23:16:55 +02:00
}
2019-12-19 17:12:02 +01:00
}
}
2019-05-22 23:16:55 +02:00
2019-12-19 17:12:02 +01:00
func ( pt * partition ) flushRawRows ( isFinal bool ) {
pt . rawRows . flush ( pt , isFinal )
}
2021-04-27 14:36:31 +02:00
func ( rrss * rawRowsShards ) flush ( pt * partition , isFinal bool ) {
2021-06-17 12:42:32 +02:00
var rowsToFlush [ ] rawRow
2021-04-27 14:36:31 +02:00
for i := range rrss . shards {
2021-06-17 12:42:32 +02:00
rowsToFlush = rrss . shards [ i ] . appendRawRowsToFlush ( rowsToFlush , pt , isFinal )
2019-05-22 23:16:55 +02:00
}
2021-06-17 12:42:32 +02:00
pt . flushRowsToParts ( rowsToFlush )
2019-05-22 23:16:55 +02:00
}
2021-06-17 12:42:32 +02:00
func ( rrs * rawRowsShard ) appendRawRowsToFlush ( dst [ ] rawRow , pt * partition , isFinal bool ) [ ] rawRow {
2020-05-14 21:01:51 +02:00
currentTime := fasttime . UnixTimestamp ( )
flushSeconds := int64 ( rawRowsFlushInterval . Seconds ( ) )
if flushSeconds <= 0 {
flushSeconds = 1
}
2019-05-22 23:16:55 +02:00
2021-04-27 14:36:31 +02:00
rrs . mu . Lock ( )
2020-05-14 21:01:51 +02:00
if isFinal || currentTime - rrs . lastFlushTime > uint64 ( flushSeconds ) {
2021-06-17 12:42:32 +02:00
dst = append ( dst , rrs . rows ... )
rrs . rows = rrs . rows [ : 0 ]
2019-05-22 23:16:55 +02:00
}
2021-04-27 14:36:31 +02:00
rrs . mu . Unlock ( )
2019-05-22 23:16:55 +02:00
2021-06-17 12:42:32 +02:00
return dst
2019-05-22 23:16:55 +02:00
}
func ( pt * partition ) startInmemoryPartsFlusher ( ) {
pt . inmemoryPartsFlusherWG . Add ( 1 )
go func ( ) {
pt . inmemoryPartsFlusher ( )
pt . inmemoryPartsFlusherWG . Done ( )
} ( )
}
func ( pt * partition ) inmemoryPartsFlusher ( ) {
2020-02-13 11:55:58 +01:00
ticker := time . NewTicker ( inmemoryPartsFlushInterval )
defer ticker . Stop ( )
2019-05-22 23:16:55 +02:00
var pwsBuf [ ] * partWrapper
var err error
for {
select {
case <- pt . stopCh :
return
2020-02-13 11:55:58 +01:00
case <- ticker . C :
pwsBuf , err = pt . flushInmemoryParts ( pwsBuf [ : 0 ] , false )
if err != nil {
logger . Panicf ( "FATAL: cannot flush inmemory parts: %s" , err )
}
2019-05-22 23:16:55 +02:00
}
}
}
func ( pt * partition ) flushInmemoryParts ( dstPws [ ] * partWrapper , force bool ) ( [ ] * partWrapper , error ) {
2020-05-14 21:01:51 +02:00
currentTime := fasttime . UnixTimestamp ( )
flushSeconds := int64 ( inmemoryPartsFlushInterval . Seconds ( ) )
if flushSeconds <= 0 {
flushSeconds = 1
}
2019-05-22 23:16:55 +02:00
// Inmemory parts may present only in small parts.
pt . partsLock . Lock ( )
for _ , pw := range pt . smallParts {
if pw . mp == nil || pw . isInMerge {
continue
}
2020-05-14 21:01:51 +02:00
if force || currentTime - pw . mp . creationTime >= uint64 ( flushSeconds ) {
2019-05-22 23:16:55 +02:00
pw . isInMerge = true
dstPws = append ( dstPws , pw )
}
}
pt . partsLock . Unlock ( )
2020-09-17 11:01:53 +02:00
if err := pt . mergePartsOptimal ( dstPws , nil ) ; err != nil {
2020-06-30 21:58:18 +02:00
return dstPws , fmt . Errorf ( "cannot merge %d inmemory parts: %w" , len ( dstPws ) , err )
2019-05-22 23:16:55 +02:00
}
return dstPws , nil
}
2020-09-17 11:01:53 +02:00
func ( pt * partition ) mergePartsOptimal ( pws [ ] * partWrapper , stopCh <- chan struct { } ) error {
2020-09-17 02:02:35 +02:00
defer func ( ) {
// Remove isInMerge flag from pws.
pt . partsLock . Lock ( )
for _ , pw := range pws {
// Do not check for pws.isInMerge set to false,
// since it may be set to false in mergeParts below.
pw . isInMerge = false
}
pt . partsLock . Unlock ( )
} ( )
2019-05-22 23:16:55 +02:00
for len ( pws ) > defaultPartsToMerge {
2020-09-17 11:01:53 +02:00
if err := pt . mergeParts ( pws [ : defaultPartsToMerge ] , stopCh ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot merge %d parts: %w" , defaultPartsToMerge , err )
2019-05-22 23:16:55 +02:00
}
pws = pws [ defaultPartsToMerge : ]
}
2020-09-17 02:02:35 +02:00
if len ( pws ) == 0 {
return nil
}
2020-09-17 11:01:53 +02:00
if err := pt . mergeParts ( pws , stopCh ) ; err != nil {
2020-09-17 02:02:35 +02:00
return fmt . Errorf ( "cannot merge %d parts: %w" , len ( pws ) , err )
2019-05-22 23:16:55 +02:00
}
return nil
}
2020-09-17 11:01:53 +02:00
// ForceMergeAllParts runs merge for all the parts in pt - small and big.
func ( pt * partition ) ForceMergeAllParts ( ) error {
var pws [ ] * partWrapper
pt . partsLock . Lock ( )
if ! hasActiveMerges ( pt . smallParts ) && ! hasActiveMerges ( pt . bigParts ) {
pws = appendAllPartsToMerge ( pws , pt . smallParts )
pws = appendAllPartsToMerge ( pws , pt . bigParts )
}
pt . partsLock . Unlock ( )
if len ( pws ) == 0 {
// Nothing to merge.
return nil
}
2021-12-15 14:58:27 +01:00
// Check whether there is enough disk space for merging pws.
newPartSize := getPartsSize ( pws )
maxOutBytes := fs . MustGetFreeSpace ( pt . bigPartsPath )
if newPartSize > maxOutBytes {
freeSpaceNeededBytes := newPartSize - maxOutBytes
2021-12-21 16:03:25 +01:00
logger . WithThrottler ( "forceMerge" , time . Minute ) . Warnf ( "cannot initiate force merge for the partition %s; additional space needed: %d bytes" ,
pt . name , freeSpaceNeededBytes )
2021-12-15 14:58:27 +01:00
return nil
}
// If len(pws) == 1, then the merge must run anyway. This allows removing the deleted series and performing de-duplication if needed.
2020-09-17 11:01:53 +02:00
if err := pt . mergePartsOptimal ( pws , pt . stopCh ) ; err != nil {
return fmt . Errorf ( "cannot force merge %d parts from partition %q: %w" , len ( pws ) , pt . name , err )
}
return nil
}
func appendAllPartsToMerge ( dst , src [ ] * partWrapper ) [ ] * partWrapper {
for _ , pw := range src {
if pw . isInMerge {
logger . Panicf ( "BUG: part %q is already in merge" , pw . p . path )
}
pw . isInMerge = true
dst = append ( dst , pw )
}
return dst
}
func hasActiveMerges ( pws [ ] * partWrapper ) bool {
for _ , pw := range pws {
if pw . isInMerge {
return true
}
}
return false
}
2019-10-31 15:16:53 +01:00
var (
2020-12-08 19:49:32 +01:00
bigMergeWorkersCount = ( cgroup . AvailableCPUs ( ) + 1 ) / 2
smallMergeWorkersCount = ( cgroup . AvailableCPUs ( ) + 1 ) / 2
2019-10-31 15:16:53 +01:00
)
// SetBigMergeWorkersCount sets the maximum number of concurrent mergers for big blocks.
//
// The function must be called before opening or creating any storage.
func SetBigMergeWorkersCount ( n int ) {
if n <= 0 {
// Do nothing
return
}
2020-07-31 12:48:35 +02:00
bigMergeWorkersCount = n
2019-10-31 15:16:53 +01:00
}
// SetSmallMergeWorkersCount sets the maximum number of concurrent mergers for small blocks.
//
// The function must be called before opening or creating any storage.
func SetSmallMergeWorkersCount ( n int ) {
if n <= 0 {
// Do nothing
return
}
2020-07-31 12:48:35 +02:00
smallMergeWorkersCount = n
2019-10-31 15:16:53 +01:00
}
2019-10-29 11:45:19 +01:00
2019-05-22 23:16:55 +02:00
func ( pt * partition ) startMergeWorkers ( ) {
2020-07-31 12:48:35 +02:00
for i := 0 ; i < smallMergeWorkersCount ; i ++ {
2019-05-22 23:16:55 +02:00
pt . smallPartsMergerWG . Add ( 1 )
go func ( ) {
pt . smallPartsMerger ( )
pt . smallPartsMergerWG . Done ( )
} ( )
}
2020-07-31 12:48:35 +02:00
for i := 0 ; i < bigMergeWorkersCount ; i ++ {
2019-05-22 23:16:55 +02:00
pt . bigPartsMergerWG . Add ( 1 )
go func ( ) {
pt . bigPartsMerger ( )
pt . bigPartsMergerWG . Done ( )
} ( )
}
}
func ( pt * partition ) bigPartsMerger ( ) {
if err := pt . partsMerger ( pt . mergeBigParts ) ; err != nil {
logger . Panicf ( "FATAL: unrecoverable error when merging big parts in the partition %q: %s" , pt . bigPartsPath , err )
}
}
func ( pt * partition ) smallPartsMerger ( ) {
if err := pt . partsMerger ( pt . mergeSmallParts ) ; err != nil {
logger . Panicf ( "FATAL: unrecoverable error when merging small parts in the partition %q: %s" , pt . smallPartsPath , err )
}
}
const (
2020-09-21 14:51:00 +02:00
minMergeSleepTime = 10 * time . Millisecond
maxMergeSleepTime = 10 * time . Second
2019-05-22 23:16:55 +02:00
)
func ( pt * partition ) partsMerger ( mergerFunc func ( isFinal bool ) error ) error {
sleepTime := minMergeSleepTime
2020-05-14 21:01:51 +02:00
var lastMergeTime uint64
2019-05-22 23:16:55 +02:00
isFinal := false
t := time . NewTimer ( sleepTime )
for {
err := mergerFunc ( isFinal )
if err == nil {
// Try merging additional parts.
sleepTime = minMergeSleepTime
2020-05-14 21:01:51 +02:00
lastMergeTime = fasttime . UnixTimestamp ( )
2019-05-22 23:16:55 +02:00
isFinal = false
continue
}
2020-09-17 02:02:35 +02:00
if errors . Is ( err , errForciblyStopped ) {
2019-05-22 23:16:55 +02:00
// The merger has been stopped.
return nil
}
2020-09-17 02:02:35 +02:00
if ! errors . Is ( err , errNothingToMerge ) {
2019-05-22 23:16:55 +02:00
return err
}
2021-01-07 23:09:00 +01:00
if finalMergeDelaySeconds > 0 && fasttime . UnixTimestamp ( ) - lastMergeTime > finalMergeDelaySeconds {
2019-05-22 23:16:55 +02:00
// We have free time for merging into bigger parts.
// This should improve select performance.
2020-05-14 21:01:51 +02:00
lastMergeTime = fasttime . UnixTimestamp ( )
2019-05-22 23:16:55 +02:00
isFinal = true
continue
}
// Nothing to merge. Sleep for a while and try again.
sleepTime *= 2
if sleepTime > maxMergeSleepTime {
sleepTime = maxMergeSleepTime
}
select {
case <- pt . stopCh :
return nil
case <- t . C :
t . Reset ( sleepTime )
}
}
}
2021-01-07 23:09:00 +01:00
// Disable final merge by default, since it may lead to high disk IO and CPU usage
// at the beginning of every month when merging data for the previous month.
var finalMergeDelaySeconds = uint64 ( 0 )
2020-10-07 16:35:42 +02:00
// SetFinalMergeDelay sets the delay before doing final merge for partitions without newly ingested data.
//
// This function may be called only before Storage initialization.
func SetFinalMergeDelay ( delay time . Duration ) {
2021-01-07 23:09:00 +01:00
if delay <= 0 {
2020-10-07 16:35:42 +02:00
return
}
2021-01-07 23:09:00 +01:00
finalMergeDelaySeconds = uint64 ( delay . Seconds ( ) + 1 )
2020-10-07 16:35:42 +02:00
}
2021-08-25 08:35:03 +02:00
func getMaxOutBytes ( path string , workersCount int ) uint64 {
n := fs . MustGetFreeSpace ( path )
2021-12-01 09:56:21 +01:00
// Do not substract freeDiskSpaceLimitBytes from n before calculating the maxOutBytes,
// since this will result in sub-optimal merges - e.g. many small parts will be left unmerged.
2021-08-25 08:35:03 +02:00
// Divide free space by the max number concurrent merges.
maxOutBytes := n / uint64 ( workersCount )
if maxOutBytes > maxBigPartSize {
maxOutBytes = maxBigPartSize
2019-08-25 13:10:43 +02:00
}
2021-08-25 08:35:03 +02:00
return maxOutBytes
2019-05-22 23:16:55 +02:00
}
func ( pt * partition ) mergeBigParts ( isFinal bool ) error {
2021-08-25 08:35:03 +02:00
maxOutBytes := getMaxOutBytes ( pt . bigPartsPath , bigMergeWorkersCount )
2019-05-22 23:16:55 +02:00
pt . partsLock . Lock ( )
2021-08-25 08:35:03 +02:00
pws , needFreeSpace := getPartsToMerge ( pt . bigParts , maxOutBytes , isFinal )
2019-05-22 23:16:55 +02:00
pt . partsLock . Unlock ( )
2020-09-29 21:51:43 +02:00
atomicSetBool ( & pt . bigMergeNeedFreeDiskSpace , needFreeSpace )
2020-07-22 23:58:48 +02:00
return pt . mergeParts ( pws , pt . stopCh )
2019-05-22 23:16:55 +02:00
}
func ( pt * partition ) mergeSmallParts ( isFinal bool ) error {
2020-12-18 22:14:35 +01:00
// Try merging small parts to a big part at first.
2021-08-25 08:35:03 +02:00
maxBigPartOutBytes := getMaxOutBytes ( pt . bigPartsPath , bigMergeWorkersCount )
2020-12-18 22:14:35 +01:00
pt . partsLock . Lock ( )
2021-08-25 08:35:03 +02:00
pws , needFreeSpace := getPartsToMerge ( pt . smallParts , maxBigPartOutBytes , isFinal )
2020-12-18 22:14:35 +01:00
pt . partsLock . Unlock ( )
atomicSetBool ( & pt . bigMergeNeedFreeDiskSpace , needFreeSpace )
2021-08-25 08:35:03 +02:00
outSize := getPartsSize ( pws )
if outSize > maxSmallPartSize ( ) {
2020-12-18 22:14:35 +01:00
// Merge small parts to a big part.
return pt . mergeParts ( pws , pt . stopCh )
2019-08-25 13:10:43 +02:00
}
2019-05-22 23:16:55 +02:00
2020-12-18 22:14:35 +01:00
// Make sure that the output small part fits small parts storage.
2021-08-25 08:35:03 +02:00
maxSmallPartOutBytes := getMaxOutBytes ( pt . smallPartsPath , smallMergeWorkersCount )
if outSize <= maxSmallPartOutBytes {
2020-12-18 22:14:35 +01:00
// Merge small parts to a small part.
return pt . mergeParts ( pws , pt . stopCh )
}
2021-08-25 08:35:03 +02:00
// The output small part doesn't fit small parts storage. Try merging small parts according to maxSmallPartOutBytes limit.
2020-12-18 22:14:35 +01:00
pt . releasePartsToMerge ( pws )
2019-05-22 23:16:55 +02:00
pt . partsLock . Lock ( )
2021-08-25 08:35:03 +02:00
pws , needFreeSpace = getPartsToMerge ( pt . smallParts , maxSmallPartOutBytes , isFinal )
2019-05-22 23:16:55 +02:00
pt . partsLock . Unlock ( )
2020-09-29 21:51:43 +02:00
atomicSetBool ( & pt . smallMergeNeedFreeDiskSpace , needFreeSpace )
2020-12-18 22:14:35 +01:00
2020-07-22 23:58:48 +02:00
return pt . mergeParts ( pws , pt . stopCh )
2019-05-22 23:16:55 +02:00
}
2020-12-18 22:14:35 +01:00
func ( pt * partition ) releasePartsToMerge ( pws [ ] * partWrapper ) {
pt . partsLock . Lock ( )
for _ , pw := range pws {
if ! pw . isInMerge {
logger . Panicf ( "BUG: missing isInMerge flag on the part %q" , pw . p . path )
}
pw . isInMerge = false
}
pt . partsLock . Unlock ( )
}
2019-05-22 23:16:55 +02:00
var errNothingToMerge = fmt . Errorf ( "nothing to merge" )
2020-09-29 20:47:40 +02:00
func atomicSetBool ( p * uint64 , b bool ) {
v := uint64 ( 0 )
if b {
v = 1
}
atomic . StoreUint64 ( p , v )
}
2021-12-15 14:58:27 +01:00
func ( pt * partition ) runFinalDedup ( ) error {
2021-12-17 19:11:15 +01:00
requiredDedupInterval , actualDedupInterval := pt . getRequiredDedupInterval ( )
if requiredDedupInterval <= actualDedupInterval {
// Deduplication isn't needed.
2021-12-15 14:58:27 +01:00
return nil
}
t := time . Now ( )
2021-12-17 19:11:15 +01:00
logger . Infof ( "starting final dedup for partition %s using requiredDedupInterval=%d ms, since the partition has smaller actualDedupInterval=%d ms" ,
pt . bigPartsPath , requiredDedupInterval , actualDedupInterval )
2021-12-15 14:58:27 +01:00
if err := pt . ForceMergeAllParts ( ) ; err != nil {
2021-12-17 19:11:15 +01:00
return fmt . Errorf ( "cannot perform final dedup for partition %s: %w" , pt . bigPartsPath , err )
2021-12-15 14:58:27 +01:00
}
2021-12-17 19:11:15 +01:00
logger . Infof ( "final dedup for partition %s has been finished in %.3f seconds" , pt . bigPartsPath , time . Since ( t ) . Seconds ( ) )
2021-12-15 14:58:27 +01:00
return nil
}
2021-12-17 19:11:15 +01:00
func ( pt * partition ) getRequiredDedupInterval ( ) ( int64 , int64 ) {
2021-12-15 14:58:27 +01:00
pws := pt . GetParts ( nil )
defer pt . PutParts ( pws )
dedupInterval := GetDedupInterval ( )
minDedupInterval := getMinDedupInterval ( pws )
2021-12-17 19:11:15 +01:00
return dedupInterval , minDedupInterval
}
func getMinDedupInterval ( pws [ ] * partWrapper ) int64 {
if len ( pws ) == 0 {
return 0
}
dMin := pws [ 0 ] . p . ph . MinDedupInterval
for _ , pw := range pws [ 1 : ] {
d := pw . p . ph . MinDedupInterval
if d < dMin {
dMin = d
}
}
return dMin
2021-12-15 14:58:27 +01:00
}
2020-09-17 01:05:54 +02:00
// mergeParts merges pws.
//
// Merging is immediately stopped if stopCh is closed.
//
// All the parts inside pws must have isInMerge field set to true.
2019-05-22 23:16:55 +02:00
func ( pt * partition ) mergeParts ( pws [ ] * partWrapper , stopCh <- chan struct { } ) error {
if len ( pws ) == 0 {
// Nothing to merge.
return errNothingToMerge
}
2020-12-18 22:14:35 +01:00
defer pt . releasePartsToMerge ( pws )
2019-05-22 23:16:55 +02:00
startTime := time . Now ( )
// Prepare BlockStreamReaders for source parts.
bsrs := make ( [ ] * blockStreamReader , 0 , len ( pws ) )
defer func ( ) {
for _ , bsr := range bsrs {
putBlockStreamReader ( bsr )
}
} ( )
for _ , pw := range pws {
bsr := getBlockStreamReader ( )
if pw . mp != nil {
bsr . InitFromInmemoryPart ( pw . mp )
} else {
if err := bsr . InitFromFilePart ( pw . p . path ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot open source part for merging: %w" , err )
2019-05-22 23:16:55 +02:00
}
}
bsrs = append ( bsrs , bsr )
}
2021-08-25 08:35:03 +02:00
outSize := uint64 ( 0 )
2019-05-22 23:16:55 +02:00
outRowsCount := uint64 ( 0 )
2020-05-15 12:11:30 +02:00
outBlocksCount := uint64 ( 0 )
2019-05-22 23:16:55 +02:00
for _ , pw := range pws {
2021-08-25 08:35:03 +02:00
outSize += pw . p . size
2019-05-22 23:16:55 +02:00
outRowsCount += pw . p . ph . RowsCount
2020-05-15 12:11:30 +02:00
outBlocksCount += pw . p . ph . BlocksCount
2019-05-22 23:16:55 +02:00
}
2021-08-25 08:35:03 +02:00
isBigPart := outSize > maxSmallPartSize ( )
2019-05-22 23:16:55 +02:00
nocache := isBigPart
// Prepare BlockStreamWriter for destination part.
ptPath := pt . smallPartsPath
if isBigPart {
ptPath = pt . bigPartsPath
}
ptPath = filepath . Clean ( ptPath )
mergeIdx := pt . nextMergeIdx ( )
tmpPartPath := fmt . Sprintf ( "%s/tmp/%016X" , ptPath , mergeIdx )
bsw := getBlockStreamWriter ( )
2020-05-15 12:11:30 +02:00
compressLevel := getCompressLevelForRowsCount ( outRowsCount , outBlocksCount )
2019-05-22 23:16:55 +02:00
if err := bsw . InitFromFilePart ( tmpPartPath , nocache , compressLevel ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create destination part %q: %w" , tmpPartPath , err )
2019-05-22 23:16:55 +02:00
}
// Merge parts.
2020-07-22 23:58:48 +02:00
dmis := pt . getDeletedMetricIDs ( )
2019-05-22 23:16:55 +02:00
var ph partHeader
rowsMerged := & pt . smallRowsMerged
rowsDeleted := & pt . smallRowsDeleted
if isBigPart {
rowsMerged = & pt . bigRowsMerged
rowsDeleted = & pt . bigRowsDeleted
2020-07-22 23:58:48 +02:00
atomic . AddUint64 ( & pt . bigMergesCount , 1 )
atomic . AddUint64 ( & pt . activeBigMerges , 1 )
} else {
atomic . AddUint64 ( & pt . smallMergesCount , 1 )
atomic . AddUint64 ( & pt . activeSmallMerges , 1 )
}
2020-10-20 13:29:26 +02:00
retentionDeadline := timestampFromTime ( startTime ) - pt . retentionMsecs
err := mergeBlockStreams ( & ph , bsw , bsrs , stopCh , dmis , retentionDeadline , rowsMerged , rowsDeleted )
2020-07-22 23:58:48 +02:00
if isBigPart {
atomic . AddUint64 ( & pt . activeBigMerges , ^ uint64 ( 0 ) )
} else {
atomic . AddUint64 ( & pt . activeSmallMerges , ^ uint64 ( 0 ) )
2019-05-22 23:16:55 +02:00
}
putBlockStreamWriter ( bsw )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "error when merging parts to %q: %w" , tmpPartPath , err )
2019-05-22 23:16:55 +02:00
}
// Close bsrs.
for _ , bsr := range bsrs {
putBlockStreamReader ( bsr )
}
bsrs = nil
2021-12-17 19:11:15 +01:00
ph . MinDedupInterval = GetDedupInterval ( )
2021-12-15 14:58:27 +01:00
if err := ph . writeMinDedupInterval ( tmpPartPath ) ; err != nil {
return fmt . Errorf ( "cannot store min dedup interval for part %q: %w" , tmpPartPath , err )
}
2019-05-22 23:16:55 +02:00
// Create a transaction for atomic deleting old parts and moving
// new part to its destination place.
var bb bytesutil . ByteBuffer
for _ , pw := range pws {
if pw . mp == nil {
fmt . Fprintf ( & bb , "%s\n" , pw . p . path )
}
}
dstPartPath := ""
if ph . RowsCount > 0 {
// The destination part may have no rows if they are deleted
// during the merge due to dmis.
dstPartPath = ph . Path ( ptPath , mergeIdx )
}
fmt . Fprintf ( & bb , "%s -> %s\n" , tmpPartPath , dstPartPath )
txnPath := fmt . Sprintf ( "%s/txn/%016X" , ptPath , mergeIdx )
2019-08-12 13:44:24 +02:00
if err := fs . WriteFileAtomically ( txnPath , bb . B ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create transaction file %q: %w" , txnPath , err )
2019-05-22 23:16:55 +02:00
}
// Run the created transaction.
if err := runTransaction ( & pt . snapshotLock , pt . smallPartsPath , pt . bigPartsPath , txnPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot execute transaction %q: %w" , txnPath , err )
2019-05-22 23:16:55 +02:00
}
var newPW * partWrapper
2019-07-04 18:09:40 +02:00
var newPSize uint64
2019-05-22 23:16:55 +02:00
if len ( dstPartPath ) > 0 {
// Open the merged part if it is non-empty.
newP , err := openFilePart ( dstPartPath )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot open merged part %q: %w" , dstPartPath , err )
2019-05-22 23:16:55 +02:00
}
2019-07-04 18:09:40 +02:00
newPSize = newP . size
2019-05-22 23:16:55 +02:00
newPW = & partWrapper {
p : newP ,
refCount : 1 ,
}
}
// Atomically remove old parts and add new part.
m := make ( map [ * partWrapper ] bool , len ( pws ) )
for _ , pw := range pws {
m [ pw ] = true
}
if len ( m ) != len ( pws ) {
logger . Panicf ( "BUG: %d duplicate parts found in the merge of %d parts" , len ( pws ) - len ( m ) , len ( pws ) )
}
removedSmallParts := 0
removedBigParts := 0
pt . partsLock . Lock ( )
2020-04-10 13:44:38 +02:00
pt . smallParts , removedSmallParts = removeParts ( pt . smallParts , m , false )
pt . bigParts , removedBigParts = removeParts ( pt . bigParts , m , true )
2019-05-22 23:16:55 +02:00
if newPW != nil {
if isBigPart {
pt . bigParts = append ( pt . bigParts , newPW )
} else {
pt . smallParts = append ( pt . smallParts , newPW )
}
}
pt . partsLock . Unlock ( )
if removedSmallParts + removedBigParts != len ( m ) {
logger . Panicf ( "BUG: unexpected number of parts removed; got %d, want %d" , removedSmallParts + removedBigParts , len ( m ) )
}
// Remove partition references from old parts.
for _ , pw := range pws {
pw . decRef ( )
}
d := time . Since ( startTime )
2021-05-23 13:02:29 +02:00
if d > 30 * time . Second {
2020-05-15 12:11:30 +02:00
logger . Infof ( "merged %d rows across %d blocks in %.3f seconds at %d rows/sec to %q; sizeBytes: %d" ,
outRowsCount , outBlocksCount , d . Seconds ( ) , int ( float64 ( outRowsCount ) / d . Seconds ( ) ) , dstPartPath , newPSize )
2019-05-22 23:16:55 +02:00
}
return nil
}
2020-05-15 12:11:30 +02:00
func getCompressLevelForRowsCount ( rowsCount , blocksCount uint64 ) int {
avgRowsPerBlock := rowsCount / blocksCount
2022-02-25 14:32:27 +01:00
// See https://github.com/facebook/zstd/releases/tag/v1.3.4 about negative compression levels.
if avgRowsPerBlock <= 10 {
return - 5
}
if avgRowsPerBlock <= 50 {
return - 2
}
2020-05-15 12:11:30 +02:00
if avgRowsPerBlock <= 200 {
return - 1
}
if avgRowsPerBlock <= 500 {
2019-05-22 23:16:55 +02:00
return 1
}
2020-05-15 12:11:30 +02:00
if avgRowsPerBlock <= 1000 {
2019-05-22 23:16:55 +02:00
return 2
}
2020-05-15 12:11:30 +02:00
if avgRowsPerBlock <= 2000 {
2019-05-22 23:16:55 +02:00
return 3
}
2020-05-15 12:11:30 +02:00
if avgRowsPerBlock <= 4000 {
2019-05-22 23:16:55 +02:00
return 4
}
return 5
}
func ( pt * partition ) nextMergeIdx ( ) uint64 {
return atomic . AddUint64 ( & pt . mergeIdx , 1 )
}
2020-04-10 13:44:38 +02:00
func removeParts ( pws [ ] * partWrapper , partsToRemove map [ * partWrapper ] bool , isBig bool ) ( [ ] * partWrapper , int ) {
2019-05-22 23:16:55 +02:00
removedParts := 0
dst := pws [ : 0 ]
for _ , pw := range pws {
2020-09-17 01:05:54 +02:00
if ! partsToRemove [ pw ] {
dst = append ( dst , pw )
2019-05-22 23:16:55 +02:00
continue
}
2020-09-17 01:05:54 +02:00
removedParts ++
2019-05-22 23:16:55 +02:00
}
return dst , removedParts
}
2020-12-22 18:48:27 +01:00
func ( pt * partition ) startStalePartsRemover ( ) {
pt . stalePartsRemoverWG . Add ( 1 )
go func ( ) {
pt . stalePartsRemover ( )
pt . stalePartsRemoverWG . Done ( )
} ( )
}
func ( pt * partition ) stalePartsRemover ( ) {
ticker := time . NewTicker ( 7 * time . Minute )
defer ticker . Stop ( )
for {
select {
case <- pt . stopCh :
return
case <- ticker . C :
pt . removeStaleParts ( )
}
}
}
func ( pt * partition ) removeStaleParts ( ) {
m := make ( map [ * partWrapper ] bool )
startTime := time . Now ( )
retentionDeadline := timestampFromTime ( startTime ) - pt . retentionMsecs
pt . partsLock . Lock ( )
for _ , pw := range pt . bigParts {
2020-12-24 07:50:10 +01:00
if ! pw . isInMerge && pw . p . ph . MaxTimestamp < retentionDeadline {
2020-12-22 18:48:27 +01:00
atomic . AddUint64 ( & pt . bigRowsDeleted , pw . p . ph . RowsCount )
m [ pw ] = true
}
}
for _ , pw := range pt . smallParts {
2020-12-24 07:50:10 +01:00
if ! pw . isInMerge && pw . p . ph . MaxTimestamp < retentionDeadline {
2020-12-22 18:48:27 +01:00
atomic . AddUint64 ( & pt . smallRowsDeleted , pw . p . ph . RowsCount )
m [ pw ] = true
}
}
removedSmallParts := 0
removedBigParts := 0
if len ( m ) > 0 {
pt . smallParts , removedSmallParts = removeParts ( pt . smallParts , m , false )
pt . bigParts , removedBigParts = removeParts ( pt . bigParts , m , true )
}
pt . partsLock . Unlock ( )
if removedSmallParts + removedBigParts != len ( m ) {
logger . Panicf ( "BUG: unexpected number of stale parts removed; got %d, want %d" , removedSmallParts + removedBigParts , len ( m ) )
}
2020-12-24 15:50:55 +01:00
// Physically remove stale parts under snapshotLock in order to provide
// consistent snapshots with partition.CreateSnapshot().
pt . snapshotLock . RLock ( )
var removeWG sync . WaitGroup
2020-12-22 18:48:27 +01:00
for pw := range m {
2021-04-27 12:31:48 +02:00
logger . Infof ( "removing part %q, since its data is out of the configured retention (%d secs)" , pw . p . path , pt . retentionMsecs / 1000 )
2020-12-25 10:45:47 +01:00
removeWG . Add ( 1 )
2020-12-24 15:50:55 +01:00
fs . MustRemoveAllWithDoneCallback ( pw . p . path , removeWG . Done )
}
removeWG . Wait ( )
2020-12-25 10:45:47 +01:00
// There is no need in calling fs.MustSyncPath() on pt.smallPartsPath and pt.bigPartsPath,
// since they should be automatically called inside fs.MustRemoveAllWithDoneCallback.
2020-12-24 15:50:55 +01:00
pt . snapshotLock . RUnlock ( )
// Remove partition references from removed parts.
for pw := range m {
2020-12-22 18:48:27 +01:00
pw . decRef ( )
}
2020-12-24 15:50:55 +01:00
2020-12-22 18:48:27 +01:00
}
2019-05-22 23:16:55 +02:00
// getPartsToMerge returns optimal parts to merge from pws.
//
2021-08-25 08:35:03 +02:00
// The summary size of the returned parts must be smaller than maxOutBytes.
// The function returns true if pws contains parts, which cannot be merged because of maxOutBytes limit.
func getPartsToMerge ( pws [ ] * partWrapper , maxOutBytes uint64 , isFinal bool ) ( [ ] * partWrapper , bool ) {
2019-05-22 23:16:55 +02:00
pwsRemaining := make ( [ ] * partWrapper , 0 , len ( pws ) )
for _ , pw := range pws {
if ! pw . isInMerge {
pwsRemaining = append ( pwsRemaining , pw )
}
}
maxPartsToMerge := defaultPartsToMerge
var pms [ ] * partWrapper
2020-09-29 20:47:40 +02:00
needFreeSpace := false
2019-05-22 23:16:55 +02:00
if isFinal {
for len ( pms ) == 0 && maxPartsToMerge >= finalPartsToMerge {
2021-08-25 08:35:03 +02:00
pms , needFreeSpace = appendPartsToMerge ( pms [ : 0 ] , pwsRemaining , maxPartsToMerge , maxOutBytes )
2019-05-22 23:16:55 +02:00
maxPartsToMerge --
}
} else {
2021-08-25 08:35:03 +02:00
pms , needFreeSpace = appendPartsToMerge ( pms [ : 0 ] , pwsRemaining , maxPartsToMerge , maxOutBytes )
2019-05-22 23:16:55 +02:00
}
for _ , pw := range pms {
if pw . isInMerge {
logger . Panicf ( "BUG: partWrapper.isInMerge cannot be set" )
}
pw . isInMerge = true
}
2020-09-29 20:47:40 +02:00
return pms , needFreeSpace
2019-05-22 23:16:55 +02:00
}
2021-08-25 08:35:03 +02:00
// minMergeMultiplier is the minimum multiplier for the size of the output part
// compared to the size of the maximum input part for the merge.
//
// Higher value reduces write amplification (disk write IO induced by the merge),
// while increases the number of unmerged parts.
// The 1.7 is good enough for production workloads.
const minMergeMultiplier = 1.7
2019-05-22 23:16:55 +02:00
// appendPartsToMerge finds optimal parts to merge from src, appends
// them to dst and returns the result.
2021-08-25 08:35:03 +02:00
// The function returns true if src contains parts, which cannot be merged because of maxOutBytes limit.
func appendPartsToMerge ( dst , src [ ] * partWrapper , maxPartsToMerge int , maxOutBytes uint64 ) ( [ ] * partWrapper , bool ) {
2019-05-22 23:16:55 +02:00
if len ( src ) < 2 {
// There is no need in merging zero or one part :)
2020-09-29 20:47:40 +02:00
return dst , false
2019-05-22 23:16:55 +02:00
}
if maxPartsToMerge < 2 {
logger . Panicf ( "BUG: maxPartsToMerge cannot be smaller than 2; got %d" , maxPartsToMerge )
}
// Filter out too big parts.
2020-07-31 12:48:35 +02:00
// This should reduce N for O(N^2) algorithm below.
2021-07-02 16:24:14 +02:00
skippedBigParts := 0
2021-08-25 08:35:03 +02:00
maxInPartBytes := uint64 ( float64 ( maxOutBytes ) / minMergeMultiplier )
2019-05-22 23:16:55 +02:00
tmp := make ( [ ] * partWrapper , 0 , len ( src ) )
for _ , pw := range src {
2021-08-25 08:35:03 +02:00
if pw . p . size > maxInPartBytes {
2021-07-02 16:24:14 +02:00
skippedBigParts ++
2019-05-22 23:16:55 +02:00
continue
}
tmp = append ( tmp , pw )
}
src = tmp
2021-07-02 16:24:14 +02:00
needFreeSpace := skippedBigParts > 1
2019-05-22 23:16:55 +02:00
2021-08-25 08:35:03 +02:00
// Sort src parts by size and backwards timestamp.
2019-05-22 23:16:55 +02:00
// This should improve adjanced points' locality in the merged parts.
sort . Slice ( src , func ( i , j int ) bool {
2021-08-25 08:35:03 +02:00
a := src [ i ] . p
b := src [ j ] . p
if a . size == b . size {
return a . ph . MinTimestamp > b . ph . MinTimestamp
2019-05-22 23:16:55 +02:00
}
2021-08-25 08:35:03 +02:00
return a . size < b . size
2019-05-22 23:16:55 +02:00
} )
2020-12-18 19:00:06 +01:00
maxSrcParts := maxPartsToMerge
2021-07-02 16:24:14 +02:00
if maxSrcParts > len ( src ) {
2020-12-18 19:00:06 +01:00
maxSrcParts = len ( src )
2019-05-22 23:16:55 +02:00
}
2021-07-02 16:24:14 +02:00
minSrcParts := ( maxSrcParts + 1 ) / 2
if minSrcParts < 2 {
minSrcParts = 2
}
2019-05-22 23:16:55 +02:00
2020-12-18 19:00:06 +01:00
// Exhaustive search for parts giving the lowest write amplification when merged.
2019-05-22 23:16:55 +02:00
var pws [ ] * partWrapper
maxM := float64 ( 0 )
2020-12-18 19:00:06 +01:00
for i := minSrcParts ; i <= maxSrcParts ; i ++ {
2019-05-22 23:16:55 +02:00
for j := 0 ; j <= len ( src ) - i ; j ++ {
2019-10-29 11:45:19 +01:00
a := src [ j : j + i ]
2021-08-25 08:35:03 +02:00
outSize := getPartsSize ( a )
if outSize > maxOutBytes {
2021-07-27 11:02:52 +02:00
needFreeSpace = true
}
2021-08-25 08:35:03 +02:00
if a [ 0 ] . p . size * uint64 ( len ( a ) ) < a [ len ( a ) - 1 ] . p . size {
// Do not merge parts with too big difference in size,
2020-12-18 19:00:06 +01:00
// since this results in unbalanced merges.
continue
}
2021-08-25 08:35:03 +02:00
if outSize > maxOutBytes {
// There is no need in verifying remaining parts with bigger sizes.
2019-10-29 11:45:19 +01:00
break
2019-05-22 23:16:55 +02:00
}
2021-08-25 08:35:03 +02:00
m := float64 ( outSize ) / float64 ( a [ len ( a ) - 1 ] . p . size )
2019-05-22 23:16:55 +02:00
if m < maxM {
continue
}
maxM = m
2019-10-29 11:45:19 +01:00
pws = a
2019-05-22 23:16:55 +02:00
}
}
2019-10-29 11:45:19 +01:00
minM := float64 ( maxPartsToMerge ) / 2
2021-08-25 08:35:03 +02:00
if minM < minMergeMultiplier {
minM = minMergeMultiplier
2019-05-22 23:16:55 +02:00
}
if maxM < minM {
2021-08-25 08:35:03 +02:00
// There is no sense in merging parts with too small m,
// since this leads to high disk write IO.
2021-07-02 16:24:14 +02:00
return dst , needFreeSpace
2019-05-22 23:16:55 +02:00
}
2020-09-29 20:47:40 +02:00
return append ( dst , pws ... ) , needFreeSpace
2019-05-22 23:16:55 +02:00
}
2021-08-25 08:35:03 +02:00
func getPartsSize ( pws [ ] * partWrapper ) uint64 {
2020-12-18 22:14:35 +01:00
n := uint64 ( 0 )
for _ , pw := range pws {
2021-08-25 08:35:03 +02:00
n += pw . p . size
2020-12-18 22:14:35 +01:00
}
return n
}
2019-05-22 23:16:55 +02:00
func openParts ( pathPrefix1 , pathPrefix2 , path string ) ( [ ] * partWrapper , error ) {
2019-11-02 01:26:02 +01:00
// The path can be missing after restoring from backup, so create it if needed.
if err := fs . MkdirAllIfNotExist ( path ) ; err != nil {
return nil , err
}
2019-05-22 23:16:55 +02:00
d , err := os . Open ( path )
if err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot open directory %q: %w" , path , err )
2019-05-22 23:16:55 +02:00
}
defer fs . MustClose ( d )
// Run remaining transactions and cleanup /txn and /tmp directories.
// Snapshots cannot be created yet, so use fakeSnapshotLock.
var fakeSnapshotLock sync . RWMutex
if err := runTransactions ( & fakeSnapshotLock , pathPrefix1 , pathPrefix2 , path ) ; err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot run transactions from %q: %w" , path , err )
2019-05-22 23:16:55 +02:00
}
txnDir := path + "/txn"
2019-06-12 00:53:43 +02:00
fs . MustRemoveAll ( txnDir )
2019-05-22 23:16:55 +02:00
tmpDir := path + "/tmp"
2019-06-12 00:53:43 +02:00
fs . MustRemoveAll ( tmpDir )
2019-05-22 23:16:55 +02:00
if err := createPartitionDirs ( path ) ; err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot create directories for partition %q: %w" , path , err )
2019-05-22 23:16:55 +02:00
}
// Open parts.
fis , err := d . Readdir ( - 1 )
if err != nil {
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot read directory %q: %w" , d . Name ( ) , err )
2019-05-22 23:16:55 +02:00
}
var pws [ ] * partWrapper
for _ , fi := range fis {
if ! fs . IsDirOrSymlink ( fi ) {
// Skip non-directories.
continue
}
fn := fi . Name ( )
if fn == "tmp" || fn == "txn" || fn == "snapshots" {
// "snapshots" dir is skipped for backwards compatibility. Now it is unused.
// Skip special dirs.
continue
}
partPath := path + "/" + fn
2021-04-22 11:58:53 +02:00
if fs . IsEmptyDir ( partPath ) {
// Remove empty directory, which can be left after unclean shutdown on NFS.
// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/1142
fs . MustRemoveAll ( partPath )
continue
}
2019-05-22 23:16:55 +02:00
startTime := time . Now ( )
p , err := openFilePart ( partPath )
if err != nil {
mustCloseParts ( pws )
2020-06-30 21:58:18 +02:00
return nil , fmt . Errorf ( "cannot open part %q: %w" , partPath , err )
2019-05-22 23:16:55 +02:00
}
2020-01-22 17:27:44 +01:00
logger . Infof ( "opened part %q in %.3f seconds" , partPath , time . Since ( startTime ) . Seconds ( ) )
2019-05-22 23:16:55 +02:00
pw := & partWrapper {
p : p ,
refCount : 1 ,
}
pws = append ( pws , pw )
}
return pws , nil
}
func mustCloseParts ( pws [ ] * partWrapper ) {
for _ , pw := range pws {
if pw . refCount != 1 {
logger . Panicf ( "BUG: unexpected refCount when closing part %q: %d; want 1" , & pw . p . ph , pw . refCount )
}
pw . p . MustClose ( )
}
}
// CreateSnapshotAt creates pt snapshot at the given smallPath and bigPath dirs.
//
// Snapshot is created using linux hard links, so it is usually created
// very quickly.
func ( pt * partition ) CreateSnapshotAt ( smallPath , bigPath string ) error {
logger . Infof ( "creating partition snapshot of %q and %q..." , pt . smallPartsPath , pt . bigPartsPath )
startTime := time . Now ( )
// Flush inmemory data to disk.
2019-12-19 17:12:02 +01:00
pt . flushRawRows ( true )
2019-05-22 23:16:55 +02:00
if _ , err := pt . flushInmemoryParts ( nil , true ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot flush inmemory parts: %w" , err )
2019-05-22 23:16:55 +02:00
}
// The snapshot must be created under the lock in order to prevent from
// concurrent modifications via runTransaction.
pt . snapshotLock . Lock ( )
defer pt . snapshotLock . Unlock ( )
if err := pt . createSnapshot ( pt . smallPartsPath , smallPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create snapshot for %q: %w" , pt . smallPartsPath , err )
2019-05-22 23:16:55 +02:00
}
if err := pt . createSnapshot ( pt . bigPartsPath , bigPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create snapshot for %q: %w" , pt . bigPartsPath , err )
2019-05-22 23:16:55 +02:00
}
2020-01-22 17:27:44 +01:00
logger . Infof ( "created partition snapshot of %q and %q at %q and %q in %.3f seconds" ,
pt . smallPartsPath , pt . bigPartsPath , smallPath , bigPath , time . Since ( startTime ) . Seconds ( ) )
2019-05-22 23:16:55 +02:00
return nil
}
func ( pt * partition ) createSnapshot ( srcDir , dstDir string ) error {
if err := fs . MkdirAllFailIfExist ( dstDir ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create snapshot dir %q: %w" , dstDir , err )
2019-05-22 23:16:55 +02:00
}
d , err := os . Open ( srcDir )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot open difrectory: %w" , err )
2019-05-22 23:16:55 +02:00
}
defer fs . MustClose ( d )
fis , err := d . Readdir ( - 1 )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot read directory: %w" , err )
2019-05-22 23:16:55 +02:00
}
for _ , fi := range fis {
if ! fs . IsDirOrSymlink ( fi ) {
// Skip non-directories.
continue
}
fn := fi . Name ( )
if fn == "tmp" || fn == "txn" {
// Skip special dirs.
continue
}
srcPartPath := srcDir + "/" + fn
dstPartPath := dstDir + "/" + fn
if err := fs . HardLinkFiles ( srcPartPath , dstPartPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create hard links from %q to %q: %w" , srcPartPath , dstPartPath , err )
2019-05-22 23:16:55 +02:00
}
}
2019-06-11 22:13:04 +02:00
fs . MustSyncPath ( dstDir )
fs . MustSyncPath ( filepath . Dir ( dstDir ) )
2019-05-22 23:16:55 +02:00
return nil
}
func runTransactions ( txnLock * sync . RWMutex , pathPrefix1 , pathPrefix2 , path string ) error {
2019-12-04 20:35:51 +01:00
// Wait until all the previous pending transaction deletions are finished.
pendingTxnDeletionsWG . Wait ( )
// Make sure all the current transaction deletions are finished before exiting.
defer pendingTxnDeletionsWG . Wait ( )
2019-05-22 23:16:55 +02:00
txnDir := path + "/txn"
d , err := os . Open ( txnDir )
if err != nil {
if os . IsNotExist ( err ) {
return nil
}
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot open %q: %w" , txnDir , err )
2019-05-22 23:16:55 +02:00
}
defer fs . MustClose ( d )
fis , err := d . Readdir ( - 1 )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot read directory %q: %w" , d . Name ( ) , err )
2019-05-22 23:16:55 +02:00
}
// Sort transaction files by id.
sort . Slice ( fis , func ( i , j int ) bool {
return fis [ i ] . Name ( ) < fis [ j ] . Name ( )
} )
for _ , fi := range fis {
2019-08-12 13:44:24 +02:00
fn := fi . Name ( )
if fs . IsTemporaryFileName ( fn ) {
// Skip temporary files, which could be left after unclean shutdown.
continue
}
txnPath := txnDir + "/" + fn
2019-05-22 23:16:55 +02:00
if err := runTransaction ( txnLock , pathPrefix1 , pathPrefix2 , txnPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot run transaction from %q: %w" , txnPath , err )
2019-05-22 23:16:55 +02:00
}
}
return nil
}
func runTransaction ( txnLock * sync . RWMutex , pathPrefix1 , pathPrefix2 , txnPath string ) error {
2020-09-17 01:05:54 +02:00
// The transaction must run under read lock in order to provide
2019-05-22 23:16:55 +02:00
// consistent snapshots with partition.CreateSnapshot().
txnLock . RLock ( )
defer txnLock . RUnlock ( )
data , err := ioutil . ReadFile ( txnPath )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot read transaction file: %w" , err )
2019-05-22 23:16:55 +02:00
}
if len ( data ) > 0 && data [ len ( data ) - 1 ] == '\n' {
data = data [ : len ( data ) - 1 ]
}
paths := strings . Split ( string ( data ) , "\n" )
if len ( paths ) == 0 {
return fmt . Errorf ( "empty transaction" )
}
rmPaths := paths [ : len ( paths ) - 1 ]
mvPaths := strings . Split ( paths [ len ( paths ) - 1 ] , " -> " )
if len ( mvPaths ) != 2 {
return fmt . Errorf ( "invalid last line in the transaction file: got %q; must contain `srcPath -> dstPath`" , paths [ len ( paths ) - 1 ] )
}
// Remove old paths. It is OK if certain paths don't exist.
2019-12-02 20:34:35 +01:00
var removeWG sync . WaitGroup
2019-05-22 23:16:55 +02:00
for _ , path := range rmPaths {
path , err := validatePath ( pathPrefix1 , pathPrefix2 , path )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "invalid path to remove: %w" , err )
2019-05-22 23:16:55 +02:00
}
2019-12-02 20:34:35 +01:00
removeWG . Add ( 1 )
fs . MustRemoveAllWithDoneCallback ( path , removeWG . Done )
2019-05-22 23:16:55 +02:00
}
// Move the new part to new directory.
srcPath := mvPaths [ 0 ]
dstPath := mvPaths [ 1 ]
srcPath , err = validatePath ( pathPrefix1 , pathPrefix2 , srcPath )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "invalid source path to rename: %w" , err )
2019-05-22 23:16:55 +02:00
}
if len ( dstPath ) > 0 {
// Move srcPath to dstPath.
dstPath , err = validatePath ( pathPrefix1 , pathPrefix2 , dstPath )
if err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "invalid destination path to rename: %w" , err )
2019-05-22 23:16:55 +02:00
}
if fs . IsPathExist ( srcPath ) {
if err := os . Rename ( srcPath , dstPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot rename %q to %q: %w" , srcPath , dstPath , err )
2019-05-22 23:16:55 +02:00
}
2019-12-09 14:42:57 +01:00
} else if ! fs . IsPathExist ( dstPath ) {
// Emit info message for the expected condition after unclean shutdown on NFS disk.
// The dstPath part may be missing because it could be already merged into bigger part
// while old source parts for the current txn weren't still deleted due to NFS locks.
logger . Infof ( "cannot find both source and destination paths: %q -> %q; this may be the case after unclean shutdown (OOM, `kill -9`, hard reset) on NFS disk" ,
srcPath , dstPath )
2019-05-22 23:16:55 +02:00
}
} else {
// Just remove srcPath.
2020-12-25 10:45:47 +01:00
removeWG . Add ( 1 )
fs . MustRemoveAllWithDoneCallback ( srcPath , removeWG . Done )
2019-05-22 23:16:55 +02:00
}
2020-12-25 10:45:47 +01:00
// Flush pathPrefix* directory metadata to the underying storage,
// so the moved files become visible there.
fs . MustSyncPath ( pathPrefix1 )
fs . MustSyncPath ( pathPrefix2 )
2019-12-04 20:35:51 +01:00
pendingTxnDeletionsWG . Add ( 1 )
2019-12-02 20:34:35 +01:00
go func ( ) {
2019-12-04 20:35:51 +01:00
defer pendingTxnDeletionsWG . Done ( )
2019-12-02 20:34:35 +01:00
// Remove the transaction file only after all the source paths are deleted.
// This is required for NFS mounts. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/61 .
removeWG . Wait ( )
2020-12-24 15:50:55 +01:00
2020-12-25 10:45:47 +01:00
// There is no need in calling fs.MustSyncPath for pathPrefix* after parts' removal,
// since it is already called by fs.MustRemoveAllWithDoneCallback.
2019-12-02 20:34:35 +01:00
if err := os . Remove ( txnPath ) ; err != nil {
logger . Errorf ( "cannot remove transaction file %q: %s" , txnPath , err )
}
} ( )
2019-05-22 23:16:55 +02:00
return nil
}
2019-12-04 20:35:51 +01:00
var pendingTxnDeletionsWG syncwg . WaitGroup
2019-05-22 23:16:55 +02:00
func validatePath ( pathPrefix1 , pathPrefix2 , path string ) ( string , error ) {
var err error
pathPrefix1 , err = filepath . Abs ( pathPrefix1 )
if err != nil {
2020-06-30 21:58:18 +02:00
return path , fmt . Errorf ( "cannot determine absolute path for pathPrefix1=%q: %w" , pathPrefix1 , err )
2019-05-22 23:16:55 +02:00
}
pathPrefix2 , err = filepath . Abs ( pathPrefix2 )
if err != nil {
2020-06-30 21:58:18 +02:00
return path , fmt . Errorf ( "cannot determine absolute path for pathPrefix2=%q: %w" , pathPrefix2 , err )
2019-05-22 23:16:55 +02:00
}
path , err = filepath . Abs ( path )
if err != nil {
2020-06-30 21:58:18 +02:00
return path , fmt . Errorf ( "cannot determine absolute path for %q: %w" , path , err )
2019-05-22 23:16:55 +02:00
}
if ! strings . HasPrefix ( path , pathPrefix1 + "/" ) && ! strings . HasPrefix ( path , pathPrefix2 + "/" ) {
return path , fmt . Errorf ( "invalid path %q; must start with either %q or %q" , path , pathPrefix1 + "/" , pathPrefix2 + "/" )
}
return path , nil
}
func createPartitionDirs ( path string ) error {
path = filepath . Clean ( path )
txnPath := path + "/txn"
if err := fs . MkdirAllFailIfExist ( txnPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create txn directory %q: %w" , txnPath , err )
2019-05-22 23:16:55 +02:00
}
tmpPath := path + "/tmp"
if err := fs . MkdirAllFailIfExist ( tmpPath ) ; err != nil {
2020-06-30 21:58:18 +02:00
return fmt . Errorf ( "cannot create tmp directory %q: %w" , tmpPath , err )
2019-05-22 23:16:55 +02:00
}
2019-06-11 22:13:04 +02:00
fs . MustSyncPath ( path )
2019-05-22 23:16:55 +02:00
return nil
}