File size: 7,045 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
package swo

import (
	"context"
	"fmt"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/target/goalert/app/lifecycle"
	"github.com/target/goalert/swo/swodb"
	"github.com/target/goalert/swo/swogrp"
	"github.com/target/goalert/swo/swoinfo"
	"github.com/target/goalert/swo/swomsg"
	"github.com/target/goalert/swo/swosync"
	"github.com/target/goalert/util/log"
	"github.com/target/goalert/util/sqldrv"
	"github.com/target/goalert/version"
)

// A Manager is responsible for managing the switchover process.
type Manager struct {
	dbMain *pgxpool.Pool
	dbNext *pgxpool.Pool

	// sql.DB instance safe for the application to use (instrumented for safe SWO operation)
	dbPgxApp *pgxpool.Pool

	pauseResume lifecycle.PauseResumer

	Config

	taskMgr *swogrp.TaskMgr

	MainDBInfo *swoinfo.DB
	NextDBInfo *swoinfo.DB
}

// Node contains information on a GoAlert instance in SWO mode.
type Node struct {
	ID uuid.UUID

	// OldValid indicates that the old database config is valid.
	OldValid bool

	// NewValid indicates that the new database config is valid.
	NewValid bool

	// CanExec indicates the node is NOT in API-only mode and is capable of executing tasks.
	CanExec bool

	Status string
}

// Config configures the current node for SWO.
type Config struct {
	OldDBURL, NewDBURL string
	CanExec            bool
	Logger             *log.Logger

	MaxOpen int
	MaxIdle int
}

// NewManager will create a new Manager with the given configuration.
func NewManager(cfg Config) (*Manager, error) {
	id := uuid.New()

	appStr := func(typ ConnType) string {
		return ConnInfo{
			Version: version.GitVersion(),
			ID:      id,
			Type:    typ,
		}.String()
	}

	appMainURL, err := sqldrv.AppURL(cfg.OldDBURL, appStr(ConnTypeMainApp))
	if err != nil {
		return nil, fmt.Errorf("connect to old db: %w", err)
	}
	appNextURL, err := sqldrv.AppURL(cfg.NewDBURL, appStr(ConnTypeNextApp))
	if err != nil {
		return nil, fmt.Errorf("connect to new db: %w", err)
	}

	mainURL, err := sqldrv.AppURL(cfg.OldDBURL, appStr(ConnTypeMainMgr))
	if err != nil {
		return nil, fmt.Errorf("connect to old db: %w", err)
	}
	mainPool, err := pgxpool.New(context.Background(), mainURL)
	if err != nil {
		return nil, fmt.Errorf("connect to old db: %w", err)
	}
	nextURL, err := sqldrv.AppURL(cfg.NewDBURL, appStr(ConnTypeNextMgr))
	if err != nil {
		return nil, fmt.Errorf("connect to new db: %w", err)
	}
	nextPool, err := pgxpool.New(context.Background(), nextURL)
	if err != nil {
		return nil, fmt.Errorf("connect to new db: %w", err)
	}

	appPgx, err := NewAppPGXPool(appMainURL, appNextURL, cfg.MaxOpen, cfg.MaxIdle)
	if err != nil {
		return nil, fmt.Errorf("create pool: %w", err)
	}

	m := &Manager{
		Config:   cfg,
		dbMain:   mainPool,
		dbNext:   nextPool,
		dbPgxApp: appPgx,
	}

	ctx := cfg.Logger.BackgroundContext()
	messages, err := swomsg.NewLog(ctx, m.dbMain)
	if err != nil {
		return nil, err
	}

	err = m.withConnFromBoth(ctx, func(ctx context.Context, oldConn, newConn *pgx.Conn) error {
		var err error
		m.MainDBInfo, err = swoinfo.DBInfo(ctx, oldConn)
		if err != nil {
			return err
		}
		m.NextDBInfo, err = swoinfo.DBInfo(ctx, newConn)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, fmt.Errorf("et server version: %w", err)
	}

	m.taskMgr, err = swogrp.NewTaskMgr(ctx, swogrp.Config{
		NodeID:  id,
		CanExec: cfg.CanExec,

		Logger:   cfg.Logger,
		Messages: messages,

		OldID: m.MainDBInfo.ID,
		NewID: m.NextDBInfo.ID,

		Executor:   NewExecutor(m),
		PauseFunc:  func(ctx context.Context) error { return m.pauseResume.Pause(ctx) },
		ResumeFunc: func(ctx context.Context) error { return m.pauseResume.Resume(ctx) },
	})
	if err != nil {
		return nil, fmt.Errorf("init task manager: %w", err)
	}

	return m, nil
}

// SetPauseResumer allows setting the pause/resume functionality for the manager.
//
// Pause is called during the switchover process to minimize the number of
// long-lived DB connections so that the final sync can be performed quickly.
//
// After a switchover, or if it is aborted, Resume will be called.
func (m *Manager) SetPauseResumer(app lifecycle.PauseResumer) {
	if m.pauseResume != nil {
		panic("already set")
	}
	m.pauseResume = app
	m.taskMgr.Init()
}

// ConnInfo returns information about all current DB connections.
func (m *Manager) ConnInfo(ctx context.Context) (counts []swoinfo.ConnCount, err error) {
	err = m.withConnFromBoth(ctx, func(ctx context.Context, oldConn, newConn *pgx.Conn) error {
		counts, err = swoinfo.ConnInfo(ctx, oldConn, newConn)
		return err
	})

	return
}

// withConnFromOld allows performing operations with a raw connection to the old database.
func (m *Manager) withConnFromOld(ctx context.Context, f func(context.Context, *pgx.Conn) error) error {
	return withPGXConn(ctx, m.dbMain, f)
}

// withConnFromBoth allows performing operations with a raw connection to both databases database.
func (m *Manager) withConnFromBoth(ctx context.Context, f func(ctx context.Context, oldConn, newConn *pgx.Conn) error) error {
	// grab lock with old DB first
	return withPGXConn(ctx, m.dbMain, func(ctx context.Context, connMain *pgx.Conn) error {
		return withPGXConn(ctx, m.dbNext, func(ctx context.Context, connNext *pgx.Conn) error {
			return f(ctx, connMain, connNext)
		})
	})
}

func withPGXConn(ctx context.Context, db *pgxpool.Pool, runFunc func(context.Context, *pgx.Conn) error) error {
	return db.AcquireFunc(ctx, func(conn *pgxpool.Conn) error {
		err := runFunc(ctx, conn.Conn())
		if err != nil {
			_ = conn.Conn().Close(ctx)
			return err
		}

		// Close connection instead of returning it to the pool, to ensure
		// locks are released.
		return conn.Conn().Close(ctx)
	})
}

// Status will return the current switchover status.
func (m *Manager) Status() Status {
	return Status{
		Status:        m.taskMgr.Status(),
		MainDBID:      m.MainDBInfo.ID,
		NextDBID:      m.NextDBInfo.ID,
		MainDBVersion: m.MainDBInfo.Version,
		NextDBVersion: m.NextDBInfo.Version,
	}
}

// Reset will disable the changelog and reset the cluster state.
func (m *Manager) Reset(ctx context.Context) error {
	err := m.taskMgr.Cancel(ctx)
	if err != nil {
		return fmt.Errorf("cancel task: %w", err)
	}

	err = m.withConnFromOld(ctx, func(ctx context.Context, conn *pgx.Conn) error {
		_, err := conn.Exec(ctx, swosync.ConnWaitLockQuery)
		if err != nil {
			return err
		}

		return swodb.New(conn).DisableChangeLogTriggers(ctx)
	})
	if err != nil {
		return fmt.Errorf("failed to disable change log triggers: %w", err)
	}

	err = m.taskMgr.Reset(ctx)
	if err != nil {
		return fmt.Errorf("reset cluster state: %w", err)
	}

	return nil
}

// StartExecute will trigger the switchover to begin.
func (m *Manager) StartExecute(ctx context.Context) error { return m.taskMgr.Execute(ctx) }

// Pool returns a pgxpool.Pool that will always return safe connections to be used during the switchover.
//
// All application code/queries should use this.
func (m *Manager) Pool() *pgxpool.Pool { return m.dbPgxApp }