-
Notifications
You must be signed in to change notification settings - Fork 33
/
worker.c
2422 lines (2102 loc) · 63.4 KB
/
worker.c
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
257
258
259
260
261
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------
*
* worker.c
* Background worker to call functions of pg_squeeze.c
*
* Copyright (c) 2016-2024, CYBERTEC PostgreSQL International GmbH
*
*---------------------------------------------------------
*/
#include "c.h"
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "access/xact.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#include "executor/spi.h"
#include "nodes/makefuncs.h"
#include "replication/slot.h"
#include "replication/snapbuild.h"
#include "storage/latch.h"
#include "storage/lock.h"
#include "storage/proc.h"
#if PG_VERSION_NUM >= 160000
#include "utils/backend_status.h"
#endif
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/snapmgr.h"
#include "pg_squeeze.h"
/*
* There are 2 kinds of worker: 1) scheduler, which creates new tasks, 2) the
* actual "squeeze worker" which calls the squeeze_table() function. It's
* simpler to have a separate worker that checks the schedules every
* minute. If there was a single worker that checks the schedules among the
* calls of squeeze_table(), it'd be harder to handle the cases where the call
* of squeeze_table() took too much time to complete (i.e. the worker could
* miss some schedule(s)).
*/
static bool am_i_scheduler = false;
/*
* Indicates that the squeeze worker was launched by an user backend (using
* the squeeze_table() function), as opposed to the scheduler worker.
*/
static bool am_i_standalone = false;
/*
* As long as the number of slots depends on the max_worker_processes GUC (it
* just makes sense not to allocate more slots for our workers than this
* value), we should not use this GUC before the other libraries have been
* loaded: those libraries might, at least in theory, adjust
* max_worker_processes.
*
* In PG >= 15, this function is called from squeeze_worker_shmem_request(),
* after all the related GUCs have been set. In earlier versions (which do not
* have the hook), the function is called while our library is being loaded,
* and some other libraries might follow. Therefore we prefer a compile time
* constant to a (possibly) not-yet-finalized GUC.
*/
static int
max_squeeze_workers(void)
{
#if PG_VERSION_NUM >= 150000
return max_worker_processes;
#else
#define MAX_SQUEEZE_WORKERS 32
/*
* If max_worker_processes appears to be greater than MAX_SQUEEZE_WORKERS,
* postmaster can start new processes but squeeze_worker_main() will fail
* to find a slot for them, and therefore those extra workers will exit
* immediately.
*/
return MAX_SQUEEZE_WORKERS;
#endif
}
/*
* The maximum number of tasks submitted by the scheduler worker or by the
* squeeze_table() user function that can be in progress at a time (as long as
* there's enough workers). Note that this is cluster-wide constant.
*
* XXX Should be based on MAX_SQUEEZE_WORKERS? Not sure how to incorporate
* scheduler workers in the computation.
*/
#define NUM_WORKER_TASKS 16
typedef struct WorkerData
{
WorkerTask tasks[NUM_WORKER_TASKS];
/*
* Has cleanup after restart completed? The first worker launched after
* server restart should set this flag.
*/
bool cleanup_done;
/*
* A lock to synchronize access to slots. Lock in exclusive mode to add /
* remove workers, in shared mode to find information on them.
*
* It's also used to synchronize task creation, so that we don't have more
* than one task per table.
*/
LWLock *lock;
int nslots; /* size of the array */
WorkerSlot slots[FLEXIBLE_ARRAY_MEMBER];
} WorkerData;
static WorkerData *workerData = NULL;
/* Local pointer to the slot in the shared memory. */
WorkerSlot *MyWorkerSlot = NULL;
/* Local pointer to the task in the shared memory. */
WorkerTask *MyWorkerTask = NULL;
/*
* The "squeeze worker" (i.e. one that performs the actual squeezing, as
* opposed to the "scheduler worker"). The scheduler worker uses this
* structure to keep track of squeeze workers it launched.
*/
typedef struct SqueezeWorker
{
BackgroundWorkerHandle *handle;
WorkerTask *task;
} SqueezeWorker;
static SqueezeWorker *squeezeWorkers = NULL;
static int squeezeWorkerCount = 0;
/*
* One slot per worker, but the count is stored separately because cleanup is
* also done separately.
*/
static ReplSlotStatus *squeezeWorkerSlots = NULL;
static int squeezeWorkerSlotCount = 0;
#define REPL_SLOT_PREFIX "pg_squeeze_slot_"
#define REPL_PLUGIN_NAME "pg_squeeze"
static void interrupt_worker(WorkerTask *task);
static void clear_task(WorkerTask *task);
static void release_task(WorkerTask *task);
static void squeeze_handle_error_app(ErrorData *edata, WorkerTask *task);
static WorkerTask *get_unused_task(Oid dbid, char *relschema, char *relname,
int *task_idx, bool *duplicate);
static void initialize_worker_task(WorkerTask *task, int task_id, Name indname,
Name tbspname, ArrayType *ind_tbsps,
bool last_try, bool skip_analyze,
int max_xlock_time);
static bool start_worker_internal(bool scheduler, int task_idx,
BackgroundWorkerHandle **handle);
static void worker_sighup(SIGNAL_ARGS);
static void worker_sigterm(SIGNAL_ARGS);
static void scheduler_worker_loop(void);
static void cleanup_workers_and_tasks(bool interrupt);
static void wait_for_worker_shutdown(SqueezeWorker *worker);
static void process_task(void);
static void create_replication_slots(int nslots, MemoryContext mcxt);
static void drop_replication_slots(void);
static void cleanup_after_server_start(void);
static void cleanup_repl_origins(void);
static void cleanup_repl_slots(void);
static Snapshot build_historic_snapshot(SnapBuild *builder);
static void process_task_internal(MemoryContext task_cxt);
static uint64 run_command(char *command, int rc);
static Size
worker_shmem_size(void)
{
Size size;
size = offsetof(WorkerData, slots);
size = add_size(size, mul_size(max_squeeze_workers(),
sizeof(WorkerSlot)));
return size;
}
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
void
squeeze_save_prev_shmem_request_hook(void)
{
prev_shmem_request_hook = shmem_request_hook;
}
#endif
/*
* The shmem_request_hook hook was introduced in PG 15. In earlier versions we
* call it directly from _PG_init().
*/
void
squeeze_worker_shmem_request(void)
{
/* With lower PG versions this function is called from _PG_init(). */
#if PG_VERSION_NUM >= 150000
if (prev_shmem_request_hook)
prev_shmem_request_hook();
#endif /* PG_VERSION_NUM >= 150000 */
RequestAddinShmemSpace(worker_shmem_size());
RequestNamedLWLockTranche("pg_squeeze", 1);
}
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
void
squeeze_save_prev_shmem_startup_hook(void)
{
prev_shmem_startup_hook = shmem_startup_hook;
}
void
squeeze_worker_shmem_startup(void)
{
bool found;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
workerData = ShmemInitStruct("pg_squeeze",
worker_shmem_size(),
&found);
if (!found)
{
int i;
LWLockPadded *locks;
locks = GetNamedLWLockTranche("pg_squeeze");
for (i = 0; i < NUM_WORKER_TASKS; i++)
{
WorkerTask *task;
task = &workerData->tasks[i];
SpinLockInit(&task->mutex);
clear_task(task);
}
workerData->lock = &locks->lock;
workerData->cleanup_done = false;
workerData->nslots = max_squeeze_workers();
for (i = 0; i < workerData->nslots; i++)
{
WorkerSlot *slot = &workerData->slots[i];
slot->dbid = InvalidOid;
slot->relid = InvalidOid;
SpinLockInit(&slot->mutex);
MemSet(&slot->progress, 0, sizeof(WorkerProgress));
slot->pid = InvalidPid;
}
}
LWLockRelease(AddinShmemInitLock);
}
/* Mark this worker's slot unused. */
static void
worker_shmem_shutdown(int code, Datum arg)
{
/* exiting before the slot was initialized? */
if (MyWorkerSlot)
{
/*
* Use spinlock to make sure that invalid dbid implies that the
* clearing is done.
*/
SpinLockAcquire(&MyWorkerSlot->mutex);
Assert(MyWorkerSlot->dbid != InvalidOid);
MyWorkerSlot->dbid = InvalidOid;
MyWorkerSlot->relid = InvalidOid;
MyWorkerSlot->pid = InvalidPid;
MemSet(&MyWorkerSlot->progress, 0, sizeof(WorkerProgress));
SpinLockRelease(&MyWorkerSlot->mutex);
/* This shouldn't be necessary, but ... */
MyWorkerSlot = NULL;
}
if (MyWorkerTask)
release_task(MyWorkerTask);
if (am_i_scheduler)
/*
* Cleanup. Here, instead of just waiting for workers to finish, we
* ask them to exit as soon as possible.
*/
cleanup_workers_and_tasks(true);
else if (am_i_standalone)
/*
* Note that the worker launched by the squeeze_table() function needs
* to do the cleanup on its own.
*/
drop_replication_slots();
/*
* Release LW locks acquired outside transaction.
*
* There's at least one such case: when the worker is looking for a slot
* in the shared memory - see squeeze_worker_main().
*/
LWLockReleaseAll();
}
/*
* Start the scheduler worker.
*/
PG_FUNCTION_INFO_V1(squeeze_start_worker);
Datum
squeeze_start_worker(PG_FUNCTION_ARGS)
{
if (RecoveryInProgress())
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("recovery is in progress"),
errhint("pg_squeeze cannot be used during recovery.")));
if (!superuser())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
(errmsg("must be superuser to start squeeze worker"))));
start_worker_internal(true, -1, NULL);
PG_RETURN_VOID();
}
/*
* Stop the scheduler worker.
*/
PG_FUNCTION_INFO_V1(squeeze_stop_worker);
Datum
squeeze_stop_worker(PG_FUNCTION_ARGS)
{
int i;
if (!superuser())
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
(errmsg("must be superuser to stop squeeze worker"))));
for (i = 0; i < workerData->nslots; i++)
{
WorkerSlot *slot = &workerData->slots[i];
Oid dbid;
bool scheduler;
SpinLockAcquire(&slot->mutex);
dbid = slot->dbid;
scheduler = slot->scheduler;
SpinLockRelease(&slot->mutex);
if (dbid == MyDatabaseId && scheduler)
{
kill(slot->pid, SIGTERM);
/*
* There should only be one scheduler per database. (It'll stop
* the squeeze workers it launched.)
*/
break;
}
}
PG_RETURN_VOID();
}
/*
* Submit a task for a squeeze worker and wait for its completion.
*
* This is a replacement for the squeeze_table() function so that pg_squeeze
* >= 1.6 can still expose the functionality via the postgres executor.
*/
extern Datum squeeze_table_new(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(squeeze_table_new);
Datum
squeeze_table_new(PG_FUNCTION_ARGS)
{
Name relschema,
relname;
Name indname = NULL;
Name tbspname = NULL;
ArrayType *ind_tbsps = NULL;
int task_idx;
WorkerTask *task = NULL;
BackgroundWorkerHandle *handle;
BgwHandleStatus status;
char *error_msg = NULL;
bool task_exists;
if (RecoveryInProgress())
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("recovery is in progress"),
errhint("pg_squeeze cannot be used during recovery.")));
if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
(errmsg("Both schema and table name must be specified"))));
relschema = PG_GETARG_NAME(0);
relname = PG_GETARG_NAME(1);
if (!PG_ARGISNULL(2))
indname = PG_GETARG_NAME(2);
if (!PG_ARGISNULL(3))
tbspname = PG_GETARG_NAME(3);
if (!PG_ARGISNULL(4))
{
ind_tbsps = PG_GETARG_ARRAYTYPE_P(4);
if (VARSIZE(ind_tbsps) >= IND_TABLESPACES_ARRAY_SIZE)
ereport(ERROR,
(errmsg("the value of \"ind_tablespaces\" is too big")));
}
/* Find free task structure. */
task = get_unused_task(MyDatabaseId, NameStr(*relschema),
NameStr(*relname), &task_idx, &task_exists);
if (task == NULL)
{
if (task_exists)
ereport(ERROR,
(errmsg("task for relation \"%s\".\"%s\" already exists",
NameStr(*relschema), NameStr(*relname))));
else
ereport(ERROR, (errmsg("too many concurrent tasks in progress")));
}
/* Fill-in the remaining task information. */
initialize_worker_task(task, -1, indname, tbspname, ind_tbsps, false,
true, squeeze_max_xlock_time);
/*
* Unlike scheduler_worker_loop() we cannot build the snapshot here, the
* worker will do. (It will also create the replication slot.) This is
* related to the variable am_i_standalone in process_task().
*/
/* Start the worker to handle the task. */
if (!start_worker_internal(false, task_idx, &handle))
{
/*
* The worker could not even get registered, so it won't set its
* status to WTS_UNUSED. Make sure the task does not leak.
*/
release_task(task);
ereport(ERROR,
(errmsg("squeeze worker could not start")),
(errhint("consider increasing \"max_worker_processes\" or decreasing \"squeeze.workers_per_database\"")));
}
/* Wait for the worker's exit. */
PG_TRY();
{
status = WaitForBackgroundWorkerShutdown(handle);
}
PG_CATCH();
{
/*
* Make sure the worker stops. Interrupt received from the user is the
* typical use case.
*/
interrupt_worker(task);
PG_RE_THROW();
}
PG_END_TRY();
if (status == BGWH_POSTMASTER_DIED)
{
ereport(ERROR,
(errmsg("the postmaster died before the background worker could finish"),
errhint("More details may be available in the server log.")));
/* No need to release the task in the shared memory. */
}
/*
* WaitForBackgroundWorkerShutdown() should not return anything else.
*/
Assert(status == BGWH_STOPPED);
if (strlen(task->error_msg) > 0)
error_msg = pstrdup(task->error_msg);
if (error_msg)
ereport(ERROR, (errmsg("%s", error_msg)));
PG_RETURN_VOID();
}
/*
* Returns a newly assigned task. Return NULL if there's no unused slot or a
* task already exists for given relation.
*
* The index in the task array is returned in *task_idx.
*
* The returned task has 'dbid', 'relschema' and 'relname' fields initialized.
*
* If NULL is returned, *duplicate tells whether it's due to an existing task
* for given relation.
*/
static WorkerTask *
get_unused_task(Oid dbid, char *relschema, char *relname, int *task_idx,
bool *duplicate)
{
int i;
WorkerTask *task;
WorkerTask *result = NULL;
int res_idx = -1;
*duplicate = false;
/*
* Find an unused task and make sure that a valid task does not exist for
* the same relation.
*/
LWLockAcquire(workerData->lock, LW_EXCLUSIVE);
for (i = 0; i < NUM_WORKER_TASKS; i++)
{
WorkerTaskState worker_state;
bool needs_check = false;
task = &workerData->tasks[i];
SpinLockAcquire(&task->mutex);
worker_state = task->worker_state;
/*
* String comparisons shouldn't take place under spinlock, but the
* spinlock is actually not necessary. Once we have released it, the
* squeeze worker can set the state to UNUSED, so we might report a
* duplicate task incorrectly. That's not perfect but should not
* happen too often. (If the task is already UNUSED, no one should
* change it while we are holding the LW lock.)
*/
SpinLockRelease(&task->mutex);
/*
* Stop looking for an unused task and checking duplicates if a
* duplicate was seen.
*/
if (!*duplicate)
{
if (worker_state != WTS_UNUSED)
{
/*
* Consider tasks which might be in progress for possible
* duplicates of the task we're going to submit.
*/
needs_check = true;
}
else if (result == NULL)
{
/* Result candidate */
result = task;
res_idx = i;
}
}
if (needs_check)
{
/*
* The strings are only set while workerData->lock is held in
* exclusive mode (see below), so we can safely check them here.
*
* Spinlock not needed to access ->dbid because the worker should
* never change it (even when exiting).
*/
if (task->dbid == dbid &&
strcmp(NameStr(task->relschema), relschema) == 0 &&
strcmp(NameStr(task->relname), relname) == 0)
{
result = NULL;
res_idx = -1;
*duplicate = true;
}
}
/*
* If the task became UNUSED recently, it might still contain obsolete
* information because the worker only sets the status when exiting.
* (This clean-up shouldn't be necessary because the caller will
* initialize it when we return it next time, but it seems a good
* practice, e.g. for debugging.)
*/
if (worker_state == WTS_UNUSED && OidIsValid(task->dbid))
{
/*
* Note that the scheduler worker should have detached from the
* DSM segment pointed to by task->repl_slot.seg, by calling
* drop_replication_slots(). (The "standalone" worker should not
* have set it.)
*/
clear_task(task);
}
}
if (result == NULL || *duplicate)
goto done;
/*
* Make sure that no other backend / scheduler can use the task.
*
* As long as we hold the LW lock, no one else should be currently trying
* to allocate this task, so no spinlock is needed.
*/
result->worker_state = WTS_INIT;
/*
* While holding the LW lock, initialize the fields we use to check
* uniqueness of the task.
*/
result->dbid = dbid;
namestrcpy(&result->relschema, relschema);
namestrcpy(&result->relname, relname);
done:
LWLockRelease(workerData->lock);
*task_idx = res_idx;
return result;
}
/*
* Fill-in "user data" of WorkerTask. task_id, dbid, relschema and relname
* should already be set.
*/
static void
initialize_worker_task(WorkerTask *task, int task_id, Name indname,
Name tbspname, ArrayType *ind_tbsps, bool last_try,
bool skip_analyze, int max_xlock_time)
{
StringInfoData buf;
initStringInfo(&buf);
task->task_id = task_id;
appendStringInfo(&buf,
"squeeze worker task: id=%d, relschema=%s, relname=%s",
task->task_id, NameStr(task->relschema),
NameStr(task->relname));
if (indname)
{
namestrcpy(&task->indname, NameStr(*indname));
appendStringInfo(&buf, ", indname: %s", NameStr(task->indname));
}
else
NameStr(task->indname)[0] = '\0';
if (tbspname)
{
namestrcpy(&task->tbspname, NameStr(*tbspname));
appendStringInfo(&buf, ", tbspname: %s", NameStr(task->tbspname));
}
else
NameStr(task->tbspname)[0] = '\0';
/* ind_tbsps is in a binary format, don't bother logging it right now. */
if (ind_tbsps)
{
if (VARSIZE(ind_tbsps) > IND_TABLESPACES_ARRAY_SIZE)
ereport(ERROR, (errmsg("the array of index tablespaces is too big")));
memcpy(task->ind_tbsps, ind_tbsps, VARSIZE(ind_tbsps));
}
else
SET_VARSIZE(task->ind_tbsps, 0);
ereport(DEBUG1, (errmsg("%s", buf.data)));
pfree(buf.data);
task->error_msg[0] = '\0';
task->last_try = last_try;
task->skip_analyze = skip_analyze;
task->max_xlock_time = max_xlock_time;
}
/*
* Register either scheduler or squeeze worker, according to the argument.
*
* The number of scheduler workers per database is limited by the
* squeeze_workers_per_database configuration variable.
*
* The return value tells whether we could at least register the worker.
*/
static bool
start_worker_internal(bool scheduler, int task_idx,
BackgroundWorkerHandle **handle)
{
WorkerConInteractive con;
BackgroundWorker worker;
char *kind;
Assert(!scheduler || task_idx < 0);
/*
* Make sure all the task fields are visible to the worker before starting
* it. This is similar to the use of the write barrier in
* RegisterDynamicBackgroundWorker() in PG core. However, the new process
* does not need to use "read barrier" because once it's started, the
* shared memory writes done by start_worker_internal() must essentially
* have been read. (Otherwise the worker would not start.)
*/
if (task_idx >= 0)
pg_write_barrier();
kind = scheduler ? "scheduler" : "squeeze";
con.dbid = MyDatabaseId;
con.roleid = GetUserId();
con.scheduler = scheduler;
con.task_idx = task_idx;
squeeze_initialize_bgworker(&worker, NULL, &con, MyProcPid);
ereport(DEBUG1, (errmsg("registering pg_squeeze %s worker", kind)));
if (!RegisterDynamicBackgroundWorker(&worker, handle))
return false;
if (handle == NULL)
/*
* Caller is not interested in the status, the return value does not
* matter.
*/
return false;
Assert(*handle != NULL);
return true;
}
/*
* Convenience routine to allocate the structure in TopMemoryContext. We need
* it to survive fork and initialization of the worker.
*
* (The allocation cannot be avoided as BackgroundWorker.bgw_extra does not
* provide enough space for us.)
*/
WorkerConInit *
allocate_worker_con_info(char *dbname, char *rolename)
{
WorkerConInit *result;
result = (WorkerConInit *) MemoryContextAllocZero(TopMemoryContext,
sizeof(WorkerConInit));
result->dbname = MemoryContextStrdup(TopMemoryContext, dbname);
result->rolename = MemoryContextStrdup(TopMemoryContext, rolename);
return result;
}
/*
* Initialize the worker and pass connection info in the appropriate form.
*
* 'con_init' is passed only for the scheduler worker, whereas
* 'con_interactive' can be passed for both squeeze worker and scheduler
* worker.
*/
void
squeeze_initialize_bgworker(BackgroundWorker *worker,
WorkerConInit *con_init,
WorkerConInteractive *con_interactive,
pid_t notify_pid)
{
char *dbname;
bool scheduler;
char *kind;
worker->bgw_flags = BGWORKER_SHMEM_ACCESS |
BGWORKER_BACKEND_DATABASE_CONNECTION;
worker->bgw_start_time = BgWorkerStart_RecoveryFinished;
worker->bgw_restart_time = BGW_NEVER_RESTART;
sprintf(worker->bgw_library_name, "pg_squeeze");
sprintf(worker->bgw_function_name, "squeeze_worker_main");
if (con_init != NULL)
{
worker->bgw_main_arg = (Datum) PointerGetDatum(con_init);
dbname = con_init->dbname;
scheduler = true;
}
else if (con_interactive != NULL)
{
worker->bgw_main_arg = (Datum) 0;
StaticAssertStmt(sizeof(WorkerConInteractive) <= BGW_EXTRALEN,
"WorkerConInteractive is too big");
memcpy(worker->bgw_extra, con_interactive,
sizeof(WorkerConInteractive));
/*
* Catalog lookup is possible during interactive start, so do it for
* the sake of bgw_name. Comment of WorkerConInteractive structure
* explains why we still must use the OID for worker registration.
*/
dbname = get_database_name(con_interactive->dbid);
scheduler = con_interactive->scheduler;
}
else
elog(ERROR, "Connection info not available for squeeze worker.");
kind = scheduler ? "scheduler" : "squeeze";
snprintf(worker->bgw_name, BGW_MAXLEN,
"pg_squeeze %s worker for database %s",
kind, dbname);
snprintf(worker->bgw_type, BGW_MAXLEN, "squeeze worker");
worker->bgw_notify_pid = notify_pid;
}
static volatile sig_atomic_t got_sighup = false;
static volatile sig_atomic_t got_sigterm = false;
/*
* Sleep time (in seconds) of the scheduler worker.
*
* If there are no tables eligible for squeezing, the worker sleeps this
* amount of seconds and then try again. The value should be low enough to
* ensure that no scheduled table processing is missed, while the schedule
* granularity is one minute.
*
* So far there seems to be no reason to have separate variables for the
* scheduler and the squeeze worker.
*/
static int worker_naptime = 20;
void
squeeze_worker_main(Datum main_arg)
{
Datum arg;
int i;
bool found_scheduler;
int nworkers;
int task_idx = -1;
/* The worker should do its cleanup when exiting. */
before_shmem_exit(worker_shmem_shutdown, (Datum) 0);
pqsignal(SIGHUP, worker_sighup);
pqsignal(SIGTERM, worker_sigterm);
BackgroundWorkerUnblockSignals();
/* Retrieve connection info. */
Assert(MyBgworkerEntry != NULL);
arg = MyBgworkerEntry->bgw_main_arg;
if (arg != (Datum) 0)
{
WorkerConInit *con;
con = (WorkerConInit *) DatumGetPointer(arg);
am_i_scheduler = true;
BackgroundWorkerInitializeConnection(con->dbname, con->rolename, 0 /* flags */
);
}
else
{
WorkerConInteractive con;
/* Ensure aligned access. */
memcpy(&con, MyBgworkerEntry->bgw_extra,
sizeof(WorkerConInteractive));
am_i_scheduler = con.scheduler;
BackgroundWorkerInitializeConnectionByOid(con.dbid, con.roleid, 0);
task_idx = con.task_idx;
}
/*
* Initialize MyWorkerTask as soon as possible so that
* worker_shmem_shutdown() can clean it up in the shared memory in case of
* ERROR.
*/
if (task_idx >= 0)
{
Assert(!am_i_scheduler);
Assert(task_idx < NUM_WORKER_TASKS);
MyWorkerTask = &workerData->tasks[task_idx];
}
found_scheduler = false;
nworkers = 0;
/*
* Find and initialize a slot for this worker.
*
* While doing that, make sure that there is no more than one scheduler
* and no more than squeeze_workers_per_database workers running on this
* database.
*
* Exclusive lock is needed to make sure that the maximum number of
* workers is not exceeded due to race conditions.
*/
Assert(MyWorkerSlot == NULL);
LWLockAcquire(workerData->lock, LW_EXCLUSIVE);
/*
* The first worker after restart is responsible for cleaning up
* replication slots and/or origins that other workers could not remove
* due to server crash. Do that while holding the exclusive lock - that
* also ensures that the other workers wait for the cleanup to finish
* before they create new slots / origins, which we might then drop
* accidentally.
*
* If no "standalone" squeeze worker performed the cleanup yet, the
* scheduler must do it now because it'll also create replication slots /
* origins. Those could be dropped by one of the new workers if that
* worker was to perform the cleanup.
*/
if (!workerData->cleanup_done)
{
cleanup_after_server_start();
workerData->cleanup_done = true;
}
for (i = 0; i < workerData->nslots; i++)
{
WorkerSlot *slot = &workerData->slots[i];
Oid dbid;
/*
* The spinlock might seem unnecessary, but w/o that it could happen
* that we saw 'dbid' invalid (i.e. ready to use) while another worker
* is still clearing the other fields (before exit) and thus it can
* overwrite our settings - see worker_shmem_shutdown().
*/
SpinLockAcquire(&slot->mutex);
dbid = slot->dbid;
SpinLockRelease(&slot->mutex);
if (dbid == MyDatabaseId)
{
if (am_i_scheduler && slot->scheduler)
{
elog(WARNING,
"one scheduler worker already running on database oid=%u",
MyDatabaseId);
found_scheduler = true;
break;
}
else if (!am_i_scheduler && !slot->scheduler)
{
if (++nworkers >= squeeze_workers_per_database)
{
elog(WARNING,
"%d squeeze worker(s) already running on database oid=%u",
nworkers, MyDatabaseId);
break;
}
}
}
else if (dbid == InvalidOid && MyWorkerSlot == NULL)
MyWorkerSlot = slot;
}
if (found_scheduler || (nworkers >= squeeze_workers_per_database))
{
LWLockRelease(workerData->lock);
goto done;
}
/*
* Fill-in all the information we have. (relid will be set in
* process_task() unless this worker is a scheduler.)
*/
if (MyWorkerSlot)
{
WorkerSlot *slot = MyWorkerSlot;
/*
* The spinlock is probably not necessary here (no one else should be
* interested in this slot).
*/
SpinLockAcquire(&slot->mutex);
slot->dbid = MyDatabaseId;
Assert(slot->relid == InvalidOid);
Assert(slot->pid == InvalidPid);
slot->pid = MyProcPid;
slot->scheduler = am_i_scheduler;
MemSet(&slot->progress, 0, sizeof(WorkerProgress));
SpinLockRelease(&slot->mutex);
}
LWLockRelease(workerData->lock);
/* Is there no unused slot? */
if (MyWorkerSlot == NULL)
{
elog(WARNING,