Sort hostIDs before inserting seen time (#3162)

* Sort hostIDs before inserting seen time

* Fix status test

* Add comment
This commit is contained in:
Tomas Touceda 2021-12-01 16:20:54 -03:00 committed by GitHub
parent ce15a8189f
commit 3a031e946d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 1 deletions

View file

@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"os"
"sort"
"strings"
"time"
@ -746,6 +747,11 @@ func (d *Datastore) MarkHostsSeen(ctx context.Context, hostIDs []uint, t time.Ti
return nil
}
// Sort by host id to prevent deadlocks:
// https://percona.community/blog/2018/09/24/minimize-mysql-deadlocks-3-steps/
// https://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html
sort.Slice(hostIDs, func(i, j int) bool { return hostIDs[i] < hostIDs[j] })
if err := d.withRetryTxx(ctx, func(tx sqlx.ExtContext) error {
var insertArgs []interface{}
for _, hostID := range hostIDs {

View file

@ -653,7 +653,7 @@ func testHostsListStatus(t *testing.T, ds *Datastore) {
DetailUpdatedAt: time.Now(),
LabelUpdatedAt: time.Now(),
PolicyUpdatedAt: time.Now(),
SeenTime: time.Now().Add(-time.Duration(i) * time.Minute),
SeenTime: time.Now().Add(-time.Duration(i) * time.Minute * 2),
OsqueryHostID: strconv.Itoa(i),
NodeKey: fmt.Sprintf("%d", i),
UUID: fmt.Sprintf("%d", i),