Class: PgEasyReplicate::Orchestrate

Inherits:
Object
  • Object
show all
Extended by:
Helper
Defined in:
lib/pg_easy_replicate/orchestrate.rb

Constant Summary collapse

DEFAULT_LAG =

200kb

200_000
DEFAULT_WAIT =

seconds

5

Class Method Summary collapse

Methods included from Helper

abort_with, connection_info, db_name, db_user, determine_tables, internal_schema_name, internal_user_name, list_all_tables, logger, publication_name, quote_ident, secondary_source_db_url, source_db_url, subscription_name, target_db_url, test_env?, underscore

Class Method Details

.add_tables_to_publication(schema:, group_name:, conn_string:, tables: []) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/pg_easy_replicate/orchestrate.rb', line 91

def add_tables_to_publication(
  schema:,
  group_name:,
  conn_string:,
  tables: []
)
  logger.info(
    "Adding tables up publication",
    { publication_name: publication_name(group_name) },
  )

  tables.map do |table_name|
    Query.run(
      query:
        "ALTER PUBLICATION #{quote_ident(publication_name(group_name))}
                  ADD TABLE #{quote_ident(table_name)}",
      connection_url: conn_string,
      schema: schema,
      user: db_user(conn_string),
    )
  end
rescue => e
  raise "Unable to add tables to publication: #{e.message}"
end

.create_publication(group_name:, conn_string:) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/pg_easy_replicate/orchestrate.rb', line 76

def create_publication(group_name:, conn_string:)
  logger.info(
    "Setting up publication",
    { publication_name: publication_name(group_name) },
  )

  Query.run(
    query: "create publication #{publication_name(group_name)}",
    connection_url: conn_string,
    user: db_user(conn_string),
  )
rescue => e
  raise "Unable to create publication: #{e.message}"
end

.create_subscription(group_name:, source_conn_string:, target_conn_string:) ⇒ Object



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
# File 'lib/pg_easy_replicate/orchestrate.rb', line 131

def create_subscription(
  group_name:,
  source_conn_string:,
  target_conn_string:
)
  logger.info(
    "Setting up subscription",
    {
      publication_name: publication_name(group_name),
      subscription_name: subscription_name(group_name),
    },
  )

  Query.run(
    query:
      "CREATE SUBSCRIPTION #{quote_ident(subscription_name(group_name))}
                CONNECTION '#{source_conn_string}'
                PUBLICATION #{quote_ident(publication_name(group_name))}",
    connection_url: target_conn_string,
    user: db_user(target_conn_string),
    transaction: false,
  )
rescue Sequel::DatabaseError => e
  if e.message.include?("canceling statement due to statement timeout")
    abort_with(
      "Subscription creation failed, please ensure both databases are in the same network region: #{e.message}",
    )
  end

  raise "Unable to create subscription: #{e.message}"
end

.drop_publication(group_name:, conn_string:) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/pg_easy_replicate/orchestrate.rb', line 116

def drop_publication(group_name:, conn_string:)
  logger.info(
    "Dropping publication",
    { publication_name: publication_name(group_name) },
  )
  Query.run(
    query:
      "DROP PUBLICATION IF EXISTS #{quote_ident(publication_name(group_name))}",
    connection_url: conn_string,
    user: db_user(conn_string),
  )
rescue => e
  raise "Unable to drop publication: #{e.message}"
end

.drop_subscription(group_name:, target_conn_string:) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/pg_easy_replicate/orchestrate.rb', line 163

def drop_subscription(group_name:, target_conn_string:)
  logger.info(
    "Dropping subscription",
    {
      publication_name: publication_name(group_name),
      subscription_name: subscription_name(group_name),
    },
  )
  Query.run(
    query: "DROP SUBSCRIPTION IF EXISTS #{subscription_name(group_name)}",
    connection_url: target_conn_string,
    transaction: false,
  )
rescue => e
  raise "Unable to drop subscription: #{e.message}"
end

.mark_switchover_complete(group_name) ⇒ Object



380
381
382
# File 'lib/pg_easy_replicate/orchestrate.rb', line 380

def mark_switchover_complete(group_name)
  Group.update(group_name: group_name, switchover_completed_at: Time.now)
end

.refresh_sequences(conn_string:, schema: nil) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/pg_easy_replicate/orchestrate.rb', line 326

def refresh_sequences(conn_string:, schema: nil)
  logger.info("Refreshing sequences")
  sql = "    DO $$\n    DECLARE\n    i TEXT;\n    BEGIN\n      FOR i IN (\n        SELECT 'SELECT SETVAL('\n            || quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname))\n            || ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM '\n            || quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'\n          FROM pg_class AS S,\n              pg_depend AS D,\n              pg_class AS T,\n              pg_attribute AS C,\n              pg_tables AS PGT\n        WHERE S.relkind = 'S'\n          AND S.oid = D.objid\n          AND D.refobjid = T.oid\n          AND D.refobjid = C.attrelid\n          AND D.refobjsubid = C.attnum\n          AND T.relname = PGT.tablename\n      ) LOOP\n          EXECUTE i;\n      END LOOP;\n    END $$;\n  SQL\n\n  Query.run(query: sql, connection_url: conn_string, schema: schema)\nrescue => e\n  raise \"Unable to refresh sequences: \#{e.message}\"\nend\n"

.restore_connections_on_source_db(group_name) ⇒ Object



318
319
320
321
322
323
324
# File 'lib/pg_easy_replicate/orchestrate.rb', line 318

def restore_connections_on_source_db(group_name)
  logger.info("Restoring connections")

  alter_sql =
    "ALTER USER #{quote_ident(db_user(source_db_url))} set default_transaction_read_only = false"
  Query.run(query: alter_sql, connection_url: source_db_url)
end

.revoke_connections_on_source_db(group_name) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/pg_easy_replicate/orchestrate.rb', line 301

def revoke_connections_on_source_db(group_name)
  logger.info(
    "Lag is now below #{DEFAULT_LAG}, marking source DB to read only",
  )

  alter_sql =
    "ALTER USER #{quote_ident(db_user(source_db_url))} set default_transaction_read_only = true"
  Query.run(query: alter_sql, connection_url: source_db_url)

  kill_sql =
    "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE usename = '#{db_user(source_db_url)}';"

  Query.run(query: kill_sql, connection_url: source_db_url)
rescue => e
  raise "Unable to revoke connections on source db: #{e.message}"
end

.run_vacuum_analyze(conn_string:, tables:, schema:) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/pg_easy_replicate/orchestrate.rb', line 360

def run_vacuum_analyze(conn_string:, tables:, schema:)
  tables.each do |t|
    logger.info(
      "Running vacuum analyze on #{t}",
      schema: schema,
      table: t,
    )

    Query.run(
      query: "VACUUM VERBOSE ANALYZE #{quote_ident(t)};",
      connection_url: conn_string,
      schema: schema,
      transaction: false,
      using_vacuum_analyze: true,
    )
  end
rescue => e
  raise "Unable to run vacuum and analyze: #{e.message}"
end

.start_sync(options) ⇒ Object



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
# File 'lib/pg_easy_replicate/orchestrate.rb', line 11

def start_sync(options)
  schema_name = options[:schema_name] || "public"
  tables =
    determine_tables(
      schema: schema_name,
      conn_string: source_db_url,
      list: options[:tables],
    )

  if options[:recreate_indices_post_copy]
    IndexManager.drop_indices(
      source_conn_string: source_db_url,
      target_conn_string: target_db_url,
      tables: tables,
      schema: schema_name,
    )
  end

  create_publication(
    group_name: options[:group_name],
    conn_string: source_db_url,
  )

  add_tables_to_publication(
    group_name: options[:group_name],
    tables: tables,
    conn_string: source_db_url,
    schema: schema_name,
  )

  create_subscription(
    group_name: options[:group_name],
    source_conn_string: secondary_source_db_url || source_db_url,
    target_conn_string: target_db_url,
  )

  Group.create(
    name: options[:group_name],
    table_names: tables.join(","),
    schema_name: schema_name,
    started_at: Time.now.utc,
    recreate_indices_post_copy: options[:recreate_indices_post_copy],
  )
rescue => e
  stop_sync(
    group_name: options[:group_name],
    source_conn_string: source_db_url,
    target_conn_string: target_db_url,
  )

  if Group.find(options[:group_name])
    Group.update(group_name: options[:group_name], failed_at: Time.now)
  else
    Group.create(
      name: options[:group_name],
      table_names: tables.join(","),
      schema_name: schema_name,
      started_at: Time.now.utc,
      failed_at: Time.now.utc,
    )
  end

  abort_with("Starting sync failed: #{e.message}")
end

.stop_sync(group_name:, source_conn_string: source_db_url, target_conn_string: target_db_url) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/pg_easy_replicate/orchestrate.rb', line 180

def stop_sync(
  group_name:,
  source_conn_string: source_db_url,
  target_conn_string: target_db_url
)
  logger.info(
    "Stopping sync",
    {
      publication_name: publication_name(group_name),
      subscription_name: subscription_name(group_name),
    },
  )
  drop_publication(
    group_name: group_name,
    conn_string: source_conn_string,
  )
  drop_subscription(
    group_name: group_name,
    target_conn_string: target_conn_string,
  )
rescue => e
  raise "Unable to stop sync user: #{e.message}"
end

.switchover(group_name:, source_conn_string: source_db_url, target_conn_string: target_db_url, lag_delta_size: nil, skip_vacuum_analyze: false) ⇒ Object



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
257
258
259
260
# File 'lib/pg_easy_replicate/orchestrate.rb', line 204

def switchover(
  group_name:,
  source_conn_string: source_db_url,
  target_conn_string: target_db_url,
  lag_delta_size: nil,
  skip_vacuum_analyze: false
)
  group = Group.find(group_name)
  tables_list = group[:table_names].split(",")

  unless skip_vacuum_analyze
    run_vacuum_analyze(
      conn_string: target_conn_string,
      tables: tables_list,
      schema: group[:schema_name],
    )
  end

  watch_lag(group_name: group_name, lag: lag_delta_size || DEFAULT_LAG)

  if group[:recreate_indices_post_copy]
    IndexManager.wait_for_replication_completion(group_name: group_name)
    IndexManager.recreate_indices(
      source_conn_string: source_db_url,
      target_conn_string: target_db_url,
      tables: tables_list,
      schema: group[:schema_name],
    )
  end

  # Watch for lag again, because it could've grown during index recreation
  watch_lag(group_name: group_name, lag: lag_delta_size || DEFAULT_LAG)

  revoke_connections_on_source_db(group_name)
  wait_for_remaining_catchup(group_name)
  refresh_sequences(
    conn_string: target_conn_string,
    schema: group[:schema_name],
  )
  mark_switchover_complete(group_name)
  # Run vacuum analyze to refresh the planner post switchover
  unless skip_vacuum_analyze
    run_vacuum_analyze(
      conn_string: target_conn_string,
      tables: tables_list,
      schema: group[:schema_name],
    )
  end
  drop_subscription(
    group_name: group_name,
    target_conn_string: target_conn_string,
  )
rescue => e
  restore_connections_on_source_db(group_name)

  abort_with("Switchover sync failed: #{e.message}")
end

.wait_for_remaining_catchup(group_name) ⇒ Object



293
294
295
296
297
298
299
# File 'lib/pg_easy_replicate/orchestrate.rb', line 293

def wait_for_remaining_catchup(group_name)
  logger.info("Waiting for remaining WAL to get flushed")

  watch_lag(group_name: group_name, lag: 0, wait_time: 0.2)

  logger.info("Caught up on remaining WAL lag")
end

.watch_lag(group_name:, wait_time: DEFAULT_WAIT, lag: DEFAULT_LAG) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/pg_easy_replicate/orchestrate.rb', line 262

def watch_lag(group_name:, wait_time: DEFAULT_WAIT, lag: DEFAULT_LAG)
  logger.info("Watching lag stats")

  loop do
    sleep(wait_time)

    unless Stats.all_tables_replicating?(group_name)
      logger.debug(
        "All tables haven't reached replicating state, skipping check",
      )
      next
    end

    lag_stat = Stats.lag_stats(group_name).first
    if lag_stat[:write_lag].nil? || lag_stat[:flush_lag].nil? ||
         lag_stat[:replay_lag].nil?
      next
    end

    logger.debug("Current lag stats: #{lag_stat}")

    below_write_lag = lag_stat[:write_lag] <= lag
    below_flush_lag = lag_stat[:flush_lag] <= lag
    below_replay_lag = lag_stat[:replay_lag] <= lag

    break if below_write_lag && below_flush_lag && below_replay_lag
  end

  logger.info("Lag below #{DEFAULT_LAG} bytes. Continuing...")
end