-
Notifications
You must be signed in to change notification settings - Fork 17
/
idle_xacts.go
62 lines (53 loc) · 1.55 KB
/
idle_xacts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package app
import (
"context"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/lesovsky/noisia/app/internal/log"
"math/rand"
"time"
)
func runIdleXactsWorkload(ctx context.Context, config *Config) error {
log.Infoln("Starting idle transactions workload")
pool, err := pgxpool.Connect(context.Background(), config.PostgresConninfo)
if err != nil {
return err
}
defer pool.Close()
// keep specified number of workers using channel - run new workers until there is any free slot
guard := make(chan struct{}, config.Jobs)
for {
select {
// run workers only when it's possible to write into channel (channel is limited by number of jobs)
case guard <- struct{}{}:
go func() {
naptime := time.Duration(rand.Intn(config.IdleXactsNaptimeMax-config.IdleXactsNaptimeMin)+config.IdleXactsNaptimeMin) * time.Second
log.Debugln("starting xact with naptime %s", naptime)
err := startSingleIdleXact(context.Background(), pool, naptime)
if err != nil {
log.Errorln(err)
}
// when worker finished, read from the channel to allow starting another workers
<-guard
}()
case <-ctx.Done():
log.Info("exit signaled, stop idle transaction workload")
return nil
}
}
}
func startSingleIdleXact(ctx context.Context, pool *pgxpool.Pool, naptime time.Duration) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
rows, err := tx.Query(ctx, "SELECT * FROM pg_stat_database")
if err != nil {
return err
}
rows.Close()
time.Sleep(naptime)
if err := tx.Commit(ctx); err != nil {
log.Warnln(err)
}
return nil
}