Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix clickhouse client race during batch commit #4071

Merged
merged 1 commit into from
Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ require (
github.com/containernetworking/plugins v0.8.7
github.com/coreos/go-iptables v0.6.0
github.com/fsnotify/fsnotify v1.5.4
github.com/gammazero/deque v0.1.0
github.com/gammazero/deque v0.1.2
github.com/go-logr/logr v1.2.0
github.com/gogo/protobuf v1.3.2
github.com/golang/mock v1.6.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,8 @@ github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5
github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI=
github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=
github.com/fvbommel/sortorder v1.0.1/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0=
github.com/gammazero/deque v0.1.0 h1:f9LnNmq66VDeuAlSAapemq/U7hJ2jpIWa4c09q8Dlik=
github.com/gammazero/deque v0.1.0/go.mod h1:KQw7vFau1hHuM8xmI9RbgKFbAsQFWmBpqQ2KenFLk6M=
github.com/gammazero/deque v0.1.2 h1:WvbDJ3YaT4ELf9+Cq9lv4Ef0aPRyZeEpIoVkjOw9kes=
github.com/gammazero/deque v0.1.2/go.mod h1:KQw7vFau1hHuM8xmI9RbgKFbAsQFWmBpqQ2KenFLk6M=
github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
Expand Down
32 changes: 26 additions & 6 deletions pkg/flowaggregator/clickhouseclient/clickhouseclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,9 @@ func (ch *ClickHouseExportProcess) flowRecordPeriodicCommit() {
// Returns the number of records successfully committed, and error if encountered.
// Cached records will be removed only after successful commit.
func (ch *ClickHouseExportProcess) batchCommitAll() (int, error) {
ch.mutex.RLock()
currSize := ch.deque.Len()
ch.mutex.RUnlock()
if currSize == 0 {
return 0, nil
}
Expand All @@ -431,11 +433,20 @@ func (ch *ClickHouseExportProcess) batchCommitAll() (int, error) {
}

// populate items from deque
ch.mutex.Lock()
// currSize could have increased due to CacheSet being called in between.
currSize = ch.deque.Len()
recordsToExport := make([]*ClickHouseFlowRow, 0, currSize)
for i := 0; i < currSize; i++ {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's worth adding a comment explaining why currSize is guaranteed to still be "valid", i.e. at most equal to the actual queue size (it's possible for the queue to have grown since the earlier check, but not possible for the queue to have shrunk). If this is not true, then the code is not correct.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's correct because CacheSet can never shrink the queue by itself. The following loop:

for ch.deque.Len() >= ch.queueSize {
        ch.deque.PopFront()
}

will never remove more than 1 item, and we push a new item right after with ch.deque.PushBack(chRow), so overall the size of the queue either increases by 1 or stays the same.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can rather read again within mutex context to be 100% safe and save the detailed explanation (which depends on implementation and could be forgotten to be updated). adding a comment for why it could have changed instead of explaining why it's still correct.

record, ok := ch.deque.At(i).(*ClickHouseFlowRow)
record, ok := ch.deque.PopFront().(*ClickHouseFlowRow)
if !ok {
continue
}
recordsToExport = append(recordsToExport, record)
}
ch.mutex.Unlock()

for _, record := range recordsToExport {
_, err := stmt.Exec(
record.flowStartSeconds,
record.flowEndSeconds,
Expand Down Expand Up @@ -487,24 +498,33 @@ func (ch *ClickHouseExportProcess) batchCommitAll() (int, error) {

if err != nil {
klog.ErrorS(err, "Error when adding record")
ch.pushRecordsToFrontOfQueue(recordsToExport)
_ = tx.Rollback()
return 0, err
}
}

if err := tx.Commit(); err != nil {
klog.ErrorS(err, "Error when committing record")
ch.pushRecordsToFrontOfQueue(recordsToExport)
return 0, err
}

// remove committed record from deque
return len(recordsToExport), nil
}

// pushRecordsToFrontOfQueue pushes records to the front of deque without exceeding its capacity.
// Items with lower index (older records) will be dropped first if deque is to be filled.
func (ch *ClickHouseExportProcess) pushRecordsToFrontOfQueue(records []*ClickHouseFlowRow) {
ch.mutex.Lock()
defer ch.mutex.Unlock()
for i := 0; i < currSize; i++ {
ch.deque.PopFront()
}

return currSize, nil
for i := len(records) - 1; i >= 0; i-- {
if ch.deque.Len() >= ch.queueSize {
break
}
ch.deque.PushFront(records[i])
}
}

func PrepareConnection(input ClickHouseInput) (string, *sql.DB, error) {
Expand Down
59 changes: 50 additions & 9 deletions pkg/flowaggregator/clickhouseclient/clickhouseclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -397,9 +397,10 @@ func TestBatchCommitAll(t *testing.T) {
defer db.Close()

chExportProc := ClickHouseExportProcess{
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
queueSize: maxQueueSize,
}

recordRow := ClickHouseFlowRow{
Expand Down Expand Up @@ -526,9 +527,10 @@ func TestBatchCommitAllMultiRecord(t *testing.T) {
defer db.Close()

chExportProc := ClickHouseExportProcess{
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
queueSize: maxQueueSize,
}
recordRow := ClickHouseFlowRow{}
fieldCount := reflect.TypeOf(recordRow).NumField()
Expand Down Expand Up @@ -564,9 +566,10 @@ func TestBatchCommitAllError(t *testing.T) {
defer db.Close()

chExportProc := ClickHouseExportProcess{
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
db: db,
deque: deque.New(),
mutex: sync.RWMutex{},
queueSize: maxQueueSize,
}
recordRow := ClickHouseFlowRow{}
chExportProc.deque.PushBack(&recordRow)
Expand All @@ -591,3 +594,41 @@ func TestBatchCommitAllError(t *testing.T) {
t.Errorf("Exists unfulfilled expectations for db sql operation: %s", err)
}
}

func TestPushRecordsToFrontOfQueue(t *testing.T) {
chExportProc := ClickHouseExportProcess{
deque: deque.New(),
mutex: sync.RWMutex{},
queueSize: 4,
}

// init deque [0]
records := make([]*ClickHouseFlowRow, 5)
for i := 0; i < 5; i++ {
records[i] = &ClickHouseFlowRow{sourceTransportPort: uint16(i)}
}
chExportProc.deque.PushBack(records[0])

// all records should be pushed to front of deque if cap allows.
// deque before [0], cap: 4
// pushfront([1,2])
// expected deque: [1,2,0]
pushbackRecords := records[1:3]
chExportProc.pushRecordsToFrontOfQueue(pushbackRecords)
assert.Equal(t, 3, chExportProc.deque.Len(), "deque size mismatch")
assert.Equal(t, records[1], chExportProc.deque.At(0), "deque has wrong item at index 0")
assert.Equal(t, records[2], chExportProc.deque.At(1), "deque has wrong item at index 1")
assert.Equal(t, records[0], chExportProc.deque.At(2), "deque has wrong item at index 2")

// only newest items should be pushed to front of deque if hitting capacity.
// deque before [1,2,0], cap: 4
// pushfront([3,4])
// expected deque: [4,1,2,0]
pushbackRecords = records[3:]
chExportProc.pushRecordsToFrontOfQueue(pushbackRecords)
assert.Equal(t, 4, chExportProc.deque.Len(), "deque size mismatch")
assert.Equal(t, records[4], chExportProc.deque.At(0), "deque has wrong item at index 0")
assert.Equal(t, records[1], chExportProc.deque.At(1), "deque has wrong item at index 1")
assert.Equal(t, records[2], chExportProc.deque.At(2), "deque has wrong item at index 2")
assert.Equal(t, records[0], chExportProc.deque.At(3), "deque has wrong item at index 3")
}
2 changes: 1 addition & 1 deletion plugins/octant/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwV
github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU=
github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA=
github.com/fvbommel/sortorder v1.0.1/go.mod h1:uk88iVf1ovNn1iLfgUVU2F9o5eO30ui720w+kxuqRs0=
github.com/gammazero/deque v0.1.0/go.mod h1:KQw7vFau1hHuM8xmI9RbgKFbAsQFWmBpqQ2KenFLk6M=
github.com/gammazero/deque v0.1.2/go.mod h1:KQw7vFau1hHuM8xmI9RbgKFbAsQFWmBpqQ2KenFLk6M=
github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY=
github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
Expand Down