File size: 5,449 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package processinglock

import (
	"context"
	"database/sql"
	"errors"
	"fmt"

	"github.com/target/goalert/gadb"
	"github.com/target/goalert/lock"
	"github.com/target/goalert/util/log"
	"github.com/target/goalert/util/sqlutil"
)

// A Lock is used to start "locked" transactions.
type Lock struct {
	cfg Config
	db  *sql.DB
}
type txBeginner interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

// NewLock will return a new Lock for the given Config.
func NewLock(ctx context.Context, db *sql.DB, cfg Config) (*Lock, error) {
	vers, err := gadb.New(db).ProcReadModuleVersion(ctx, gadb.EngineProcessingType(cfg.Type))
	if err != nil {
		return nil, fmt.Errorf("read module version: %w", err)
	}

	if vers != int32(cfg.Version) {
		log.Log(ctx, fmt.Errorf("engine module disabled: %s: version mismatch: expected=%d got=%d", cfg.Type, cfg.Version, vers))

		// Log the error, but continue operation.
		//
		// It is valid for individual engine modules to be disabled, but we
		// should not block the rest of the system, so we don't return here.
		//
		// However, we do log it as an error as it _will_ cause the lock to
		// fail to be acquired. This means if all instances of the engine have
		// the module disabled (like scheduling or messaging) then no schedules
		// will update or messages will be sent, respectively.
		//
		// We only do this at startup, rather than on every lock acquisition,
		// to avoid spamming the logs with the same error. Also because during
		// an upgrade, existing engine instances are expected to be running, and
		// thus stop processing new work for the now incompatible module.
		//
		// Starting an _old_ engine instance with a new module version is not
		// as common, and we want to inform the operator that this is happening,
		// as it is likely part of a rollback or other unexpected situation.
		//
		// In those cases, the operator should be aware that the engine is not
		// processing work as expected, because the database is still using a
		// structure that the older code does not understand.
	}

	return &Lock{
		db:  db,
		cfg: cfg,
	}, nil
}

func (l *Lock) _BeginTx(ctx context.Context, b txBeginner, opts *sql.TxOptions, shared bool) (*sql.Tx, error) {
	tx, err := b.BeginTx(ctx, opts)
	if err != nil {
		return nil, err
	}
	q := gadb.New(tx)

	// Ensure the engine isn't running or that it waits for migrations to complete.
	gotAdvLock, err := q.ProcSharedAdvisoryLock(ctx, int64(lock.GlobalMigrate))
	if err != nil {
		sqlutil.Rollback(ctx, "processing lock: begin", tx)
		return nil, err
	}
	if !gotAdvLock {
		sqlutil.Rollback(ctx, "processing lock: begin", tx)
		return nil, ErrNoLock
	}

	if shared {
		_, err = q.ProcAcquireModuleSharedLock(ctx, gadb.ProcAcquireModuleSharedLockParams{
			TypeID:  gadb.EngineProcessingType(l.cfg.Type),
			Version: l.cfg.Version,
		})
	} else {
		_, err = q.ProcAcquireModuleLockNoWait(ctx, gadb.ProcAcquireModuleLockNoWaitParams{
			TypeID:  gadb.EngineProcessingType(l.cfg.Type),
			Version: l.cfg.Version,
		})
	}
	if errors.Is(err, sql.ErrNoRows) {
		// wrong module version
		sqlutil.Rollback(ctx, "processing lock: begin", tx)
		return nil, ErrNoLock
	}
	if err != nil {
		sqlutil.Rollback(ctx, "processing lock: begin", tx)
		// 55P03 is lock_not_available (due to the `nowait` in the query)
		//
		// https://www.postgresql.org/docs/9.4/static/errcodes-appendix.html
		if sqlErr := sqlutil.MapError(err); sqlErr != nil && sqlErr.Code == "55P03" {
			return nil, ErrNoLock
		}
		return nil, err
	}

	return tx, nil
}

// WithTx will run the given function in a locked transaction, returning ErrNoLock immediately if the lock cannot be acquired.
func (l *Lock) WithTx(ctx context.Context, fn func(context.Context, *sql.Tx) error) error {
	tx, err := l._BeginTx(ctx, l.db, nil, false)
	if err != nil {
		return err
	}
	defer sqlutil.Rollback(ctx, "processing lock: with tx", tx)

	err = fn(ctx, tx)
	if err != nil {
		return err
	}

	err = tx.Commit()
	if err != nil {
		return err
	}

	return nil
}

// WithTxShared will run the given function in a locked transaction that is compatible with other shared locks.
//
// Note: This will block until it acquires the lock.
func (l *Lock) WithTxShared(ctx context.Context, fn func(context.Context, *sql.Tx) error) error {
	tx, err := l._BeginTx(ctx, l.db, nil, true)
	if err != nil {
		return err
	}
	defer sqlutil.Rollback(ctx, "processing lock: with tx (shared)", tx)

	err = fn(ctx, tx)
	if err != nil {
		return err
	}

	err = tx.Commit()
	if err != nil {
		return err
	}

	return nil
}

func (l *Lock) _Exec(ctx context.Context, b txBeginner, stmt *sql.Stmt, args ...interface{}) (sql.Result, error) {
	tx, err := l._BeginTx(ctx, b, nil, false)
	if err != nil {
		return nil, err
	}
	defer sqlutil.Rollback(ctx, "processing lock: exec", tx)

	res, err := tx.StmtContext(ctx, stmt).ExecContext(ctx, args...)
	if err != nil {
		return nil, err
	}

	err = tx.Commit()
	if err != nil {
		return nil, err
	}

	return res, nil
}

// BeginTx will start a transaction with the appropriate lock in place (based on Config).
func (l *Lock) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) {
	return l._BeginTx(ctx, l.db, opts, false)
}

// Exec will run ExecContext on the statement, wrapped in a locked transaction.
func (l *Lock) Exec(ctx context.Context, stmt *sql.Stmt, args ...interface{}) (sql.Result, error) {
	return l._Exec(ctx, l.db, stmt, args...)
}