/
main.go
1422 lines (1103 loc) · 36.4 KB
/
main.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
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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
flare "github.com/nabeken/pg-flare"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"golang.org/x/sync/errgroup"
)
func main() {
if err := realmain(); err != nil {
log.Fatal(err)
}
}
type globalFlags struct {
configFile string
}
func realmain() error {
gflags := &globalFlags{}
rootCmd := &cobra.Command{
Use: "flare",
Short: "flare is a command-line tool to help database migration with the logical replication",
Run: func(cmd *cobra.Command, args []string) {
cmd.PrintErr("please specify a subcommand\n")
},
}
rootCmd.PersistentFlags().StringVar(
&gflags.configFile,
"config",
"./flare.yml",
"the configuration file",
)
rootCmd.AddCommand(buildVerifyConnectivity(gflags))
rootCmd.AddCommand(buildReplicateRolesCmd(gflags))
rootCmd.AddCommand(buildReplicateSchemaCmd(gflags))
rootCmd.AddCommand(buildCreatePublicationCmd(gflags))
rootCmd.AddCommand(buildCreateSubscriptionCmd(gflags))
rootCmd.AddCommand(buildCreateAttackDBCmd(gflags))
rootCmd.AddCommand(buildAttackCmd(gflags))
rootCmd.AddCommand(buildPauseWriteCmd(gflags))
rootCmd.AddCommand(buildResumeWriteCmd(gflags))
rootCmd.AddCommand(buildInstallExtensionsCmd(gflags))
rootCmd.AddCommand(buildGrantCreateCmd(gflags))
rootCmd.AddCommand(buildGrantReplicationCmd(gflags))
rootCmd.AddCommand(buildMonitor(gflags))
rootCmd.AddCommand(buildDropPublicationCmd(gflags))
rootCmd.AddCommand(buildDropSubscriptionCmd(gflags))
rootCmd.AddCommand(buildExecCmd(gflags))
rootCmd.AddCommand(buildCreateReplicationStatusTableCmd(gflags))
rootCmd.AddCommand(buildResetReplicationStatusCmd(gflags))
rootCmd.AddCommand(buildCountCmd(gflags))
rootCmd.AddCommand(buildVacuumAnalyzeCmd(gflags))
return rootCmd.Execute()
}
func buildVerifyConnectivity(gflags *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "verify_connectivity",
Short: "Verify connectivity for a given configuration",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
cmd.Printf("The system identifier for the publisher and the subscriber is OK!\n")
cmd.Printf("Publisher: %s\n", cfg.Hosts.Publisher.Conn.SystemIdentifier)
cmd.Printf("Subscriber: %s\n", cfg.Hosts.Subscriber.Conn.SystemIdentifier)
return
},
}
return cmd
}
func verifyConnection(ctx context.Context, cmd *cobra.Command, cfg flare.Config) error {
pconn, err := flare.ConnectWithVerify(
ctx,
cfg.Hosts.Publisher.Conn.SuperUserInfo(),
"postgres",
)
if err != nil {
return fmt.Errorf("verifying the publisher: %w", err)
}
defer pconn.Close(ctx)
sconn, err := flare.ConnectWithVerify(
ctx,
cfg.Hosts.Subscriber.Conn.SuperUserInfo(),
"postgres",
)
if err != nil {
return fmt.Errorf("verifying the subscriber: %w", err)
}
defer sconn.Close(ctx)
return nil
}
func readConfigFileAndVerifyOrExit(ctx context.Context, cmd *cobra.Command, fn string) flare.Config {
cfg := readConfigFileOrExit(cmd, fn)
if err := verifyConnection(ctx, cmd, cfg); err != nil {
log.Fatalf("Failed to verify the connection: %s\n", err)
}
return cfg
}
func readConfigFileOrExit(cmd *cobra.Command, fn string) flare.Config {
cfg, err := parseConfigFile(fn)
if err != nil {
log.Fatalf("Failed to parse the configuration: %s\n", err)
}
return cfg
}
func parseConfigFile(fn string) (flare.Config, error) {
b, err := os.ReadFile(fn)
if err != nil {
return flare.Config{}, fmt.Errorf("reading '%s': %w", fn, err)
}
return flare.ParseConfig(b)
}
func buildCreateSubscriptionCmd(gflags *globalFlags) *cobra.Command {
var useReplUser bool
cmd := &cobra.Command{
Use: "create_subscription [SUBNAME]",
Short: "Create a subscription in the subscriber",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a subscription name in the config\n\n")
cmd.Usage()
os.Exit(1)
}
subName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
subCfg, ok := cfg.Subscriptions[subName]
if !ok {
log.Fatalf("Subscription '%s' is not found in the config\n", subName)
}
pubConnForSub := cfg.Hosts.Publisher.Conn.SuperUserInfo()
if useReplUser {
pubConnForSub = cfg.Hosts.Publisher.Conn.ReplicationUserInfo()
}
subQuery := flare.CreateSubscriptionQuery(
subName,
pubConnForSub.DSNURIForSubscriber(subCfg.DBName),
subCfg.PubName,
)
log.Print("Creating a subscription...")
conn, err := flare.Connect(ctx, cfg.Hosts.Subscriber.Conn.SuperUserInfo(), subCfg.DBName)
if err != nil {
log.Fatalf("Failed to connect to the subscriber: %s\n", err)
}
defer conn.Close(ctx)
if err := conn.Ping(ctx); err != nil {
log.Fatal(err)
}
if _, err = conn.Exec(ctx, subQuery); err != nil {
log.Fatal(err)
}
log.Print("The subscription has been created")
},
}
cmd.Flags().BoolVar(
&useReplUser,
"use-repl-user",
false,
"Use the replication user to connect to the publisher",
)
return cmd
}
func buildCreatePublicationCmd(gflags *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "create_publication [DBNAME]",
Short: "Create a publication in the given database in the publisher",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
pubCfg, ok := cfg.Publications[dbName]
if !ok {
log.Fatalf("Database '%s' is not found in the config\n", dbName)
}
for _, tbl := range pubCfg.ReplicaIdentityFullTables {
func() {
dboconn, err := flare.Connect(ctx, cfg.Hosts.Publisher.Conn.DBOwnerInfo(), dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer dboconn.Close(ctx)
log.Printf("Setting REPLICA IDENTITY FULL for '%s'", tbl)
if _, err = dboconn.Exec(ctx, flare.AlterTableReplicaIdentityFull(tbl)); err != nil {
log.Fatalf("Failed to set the replica identity full: %s", err)
}
}()
}
log.Print("Creating a publication in the publisher...")
conn, err := flare.Connect(ctx, cfg.Hosts.Publisher.Conn.SuperUserInfo(), dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer conn.Close(ctx)
if err := conn.Ping(ctx); err != nil {
log.Fatal(err)
}
if _, err = conn.Exec(ctx, flare.CreatePublicationQuery(pubCfg.PubName)); err != nil {
log.Fatalf("Failed to create a publication: %s", err)
}
log.Print("Publisher in the source has been created")
},
}
return cmd
}
func buildReplicateSchemaCmd(gflags *globalFlags) *cobra.Command {
var onlyDump bool
var useDBOwner bool
cmd := &cobra.Command{
Use: "replicate_schema [DBNAME]",
Short: "Replicate schema",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
log.Printf("Reading the schema of '%s' from the publisher...", dbName)
pubConnUserInfo := cfg.Hosts.Publisher.Conn.SuperUserInfo()
if useDBOwner {
pubConnUserInfo = cfg.Hosts.Publisher.Conn.DBOwnerInfo()
}
schema, err := flare.DumpSchema(pubConnUserInfo, dbName)
if err != nil {
log.Fatal(err)
}
if onlyDump {
fmt.Print(schema)
log.Print("no replication to the subscriber was made as per request in the flag")
os.Exit(0)
}
log.Print("Copying the schema to the subscriber...")
psqlArgs := cfg.Hosts.Subscriber.Conn.SuperUserInfo().PSQLArgs()
result, resultErr, err := flare.PSQL(psqlArgs, "postgres", strings.NewReader(schema))
if err != nil {
log.Fatal(err)
}
fmt.Print(result)
fmt.Print(resultErr)
log.Print("Finished copying the schema to the subscriber")
},
}
cmd.Flags().BoolVar(
&onlyDump,
"only-dump",
false,
"Only dump the schema instead of replicating to the subscriber",
)
cmd.Flags().BoolVar(
&useDBOwner,
"use-db-owner",
false,
"Use the db owner to dump the schema",
)
return cmd
}
func buildReplicateRolesCmd(gflags *globalFlags) *cobra.Command {
var onlyDump bool
var noPasswords bool
var stripRoleOptionsForRDS bool
cmd := &cobra.Command{
Use: "replicate_roles",
Short: "Replicate roles from the publisher to the subscriber",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
log.Print("Reading the roles from the publisher...")
roles, err := flare.DumpRoles(cfg.Hosts.Publisher.Conn.SuperUserInfo(), noPasswords)
if err != nil {
log.Fatal(err)
}
if stripRoleOptionsForRDS {
roles, err = flare.StripRoleOptionsForRDS(roles)
if err != nil {
log.Fatalf("Failed to strip options: %s", err)
}
}
if onlyDump {
fmt.Print(roles)
log.Print("no replication to the subscriber was made as per request in the flag")
os.Exit(0)
}
log.Print("Copying the roles to the subscriber...")
psqlArgs := cfg.Hosts.Subscriber.Conn.SuperUserInfo().PSQLArgs()
result, resultErr, err := flare.PSQL(psqlArgs, "postgres", strings.NewReader(roles))
if err != nil {
log.Fatal(err)
}
fmt.Print(result)
fmt.Print(resultErr)
log.Print("Finished copying the roles to the subscriber")
},
}
cmd.Flags().BoolVar(
&onlyDump,
"only-dump",
false,
"Only dump the roles instead of replicating to the subscriber",
)
cmd.Flags().BoolVar(
&noPasswords,
"no-passwords",
false,
"Do not dump the passwords",
)
cmd.Flags().BoolVar(
&stripRoleOptionsForRDS,
"strip-options-for-rds",
false,
"Strip role options for RDS",
)
return cmd
}
func buildAttackCmd(gflags *globalFlags) *cobra.Command {
var dsn, name string
cmd := &cobra.Command{
Use: "attack",
Short: "Generate write traffic against `flare_test` table in the publisher for testing",
Run: func(cmd *cobra.Command, args []string) {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
pool, err := pgxpool.Connect(ctx, dsn)
if err != nil {
log.Fatalf("Failed to connect to flare_test database: %s\n", err)
}
gen := flare.NewTrafficGenerator(pool, name)
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
log.Print("Start sending heartbeat...")
return gen.KeepAlive(ctx)
})
eg.Go(func() error {
log.Print("Begin to attack the database...")
return gen.Attack(ctx)
})
log.Print("Waiting for interrupt...")
err = eg.Wait()
log.Printf("Finished attacking the database: %s", err)
},
}
cmd.Flags().StringVar(
&dsn,
"dsn",
"postgres://postgres:postgres@127.0.0.1:5432/flare_test",
"Data Source Name",
)
cmd.Flags().StringVar(
&name,
"name",
"flare",
"Worker's ID",
)
return cmd
}
func buildCreateAttackDBCmd(gflags *globalFlags) *cobra.Command {
var dropDBBefore bool
var baseDSN string
var appUser string
cmd := &cobra.Command{
Use: "create_attack_db",
Short: "Create database for testing",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
log.Print("Creating the `flare_test` database...")
if err := flare.CreateTestTable(
ctx,
baseDSN,
appUser,
dropDBBefore,
); err != nil {
log.Fatal(err)
}
},
}
cmd.Flags().StringVar(
&appUser,
"app-user",
"app",
"Application User",
)
cmd.Flags().StringVar(
&baseDSN,
"base-dsn",
"postgres://postgres:postgres@127.0.0.1:5432",
"Base DSN (without database name)",
)
cmd.Flags().BoolVar(
&dropDBBefore,
"drop-db-before",
false,
"Drop the database before creating it if exists",
)
return cmd
}
func buildPauseWriteCmd(gflags *globalFlags) *cobra.Command {
var appUser string
var allowedRepDuration string
cmd := &cobra.Command{
Use: "pause_write [DBNAME] [SUBNAME]",
Short: "Pause write traffic by revoking and killing access to a given databas in the publisher",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 2 {
cmd.PrintErr("please specify a database and subscription name\n\n")
cmd.Usage()
os.Exit(1)
}
repDuration, err := time.ParseDuration(allowedRepDuration)
if err != nil {
log.Fatalf("Failed to parse allowedRepDuration: %s", err)
}
dbName := args[0]
subName := args[1]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
// setup connections
pdboconn := mustSetupConn(ctx, cfg.Hosts.Publisher.Conn.DBOwnerInfo(), dbName)
defer pdboconn.Close(ctx)
psuconn := mustSetupConn(ctx, cfg.Hosts.Publisher.Conn.SuperUserInfo(), "postgres")
defer psuconn.Close(ctx)
subdboconn := mustSetupConn(ctx, cfg.Hosts.Subscriber.Conn.DBOwnerInfo(), dbName)
defer subdboconn.Close(ctx)
log.Printf("Checking whether only one logical replication is working for '%s'...", dbName)
// check the replication slots for the database
// abort if there are multiple slots ongoing for the database, which indicates it's in the initial sync
repSlots, err := flare.ListReplicationSlotsByDatabase(ctx, psuconn, dbName)
if err != nil {
log.Fatalf("Failed to list the replication slots for %s: %s", dbName, err)
}
if len(repSlots) > 1 {
log.Fatalf("There are more than one replications are ongoing for '%s' where it should be only one in progress", dbName)
}
log.Printf("Confirmed there is only one replication is working for %s", dbName)
// check whether the logical replication is working for 1 minute at least because if the logical replication has an issue, the process is being died repeadtly
log.Printf("Checking whether the logical replication is working for subscription of '%s'...", subName)
repStat := mustGetReplicationStatBySubscription(ctx, psuconn, subName)
if string(repStat.ApplicationName) != subName {
log.Fatalf("The replication doesn't sound for subscription of '%s'", subName)
}
repSince := time.Since(repStat.BackendStart)
if repSince < repDuration {
log.Fatalf("The replication doesn't seem to be stable because it just started %s ago. Please check error log.", repSince)
}
log.Printf("The logical replication is working for subscription of '%s' for %s", subName, repSince)
log.Printf("Revoking the access against '%s' database from PUBLIC...", dbName)
if _, err = pdboconn.Exec(ctx, flare.RevokeConnectionQuery(dbName)); err != nil {
log.Fatal(err)
}
log.Printf("Database access against '%s' database has been revoked!", dbName)
log.Printf("Killing the existing connections against '%s' database...", dbName)
zeroConnTimes := 0
// will retry until flare sees 3 times zero connections in a row
for zeroConnTimes <= 3 {
ret, err := psuconn.Exec(
ctx,
flare.KillConnectionQuery,
appUser,
dbName,
)
if err != nil {
log.Fatalf("Failed to kill the connections: %s", err)
}
if ret.RowsAffected() > 0 {
log.Printf("%d connections got killed", ret.RowsAffected())
// reset to zero to see whether there are still remaining connections again...
zeroConnTimes = 0
} else {
zeroConnTimes++
}
time.Sleep(100 * time.Millisecond)
}
log.Printf("No connections against '%s' database are detected!", dbName)
log.Printf("Checking the current replication stats again for the final confirmation...")
repStat2 := mustGetReplicationStatBySubscription(ctx, psuconn, subName)
if string(repStat2.ApplicationName) != subName {
log.Fatalf("The replication doesn't sound for subscription of '%s'", subName)
}
log.Printf("Writing a probe record to %s...", dbName)
repUUID := uuid.New().String()
if err := flare.WriteReplicationStatus(
ctx, pdboconn, cfg.Hosts.Publisher.Conn.SystemIdentifier, repUUID,
); err != nil {
log.Fatalf("Failed to write a probe record: %s", err)
}
for {
log.Print("Checking whether the subscriber the latest write after the application traffic is suspended...")
if err := flare.ReadReplicationStatus(
ctx, subdboconn, cfg.Hosts.Publisher.Conn.SystemIdentifier, repUUID,
); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
log.Print("The record hasn't arrived yet at the subscriber...")
time.Sleep(100 * time.Millisecond)
continue
}
log.Fatalf("Faild to read the replication status: %s", err)
}
log.Print("The record has arrived at the subscriber! It's time to switch!")
break
}
},
}
cmd.Flags().StringVar(
&appUser,
"app-user",
"postgres",
"Specify an application to be paused",
)
cmd.Flags().StringVar(
&allowedRepDuration,
"allowed-rep-duration",
"1m",
"Specify how long we will wait to consider the replication is stable",
)
cmd.MarkFlagRequired("app-user")
return cmd
}
func buildResumeWriteCmd(gflags *globalFlags) *cobra.Command {
cmd := &cobra.Command{
Use: "resume_write",
Short: "Resume write traffic by granting access to a given databas in the publisher",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
conn, err := flare.Connect(ctx, cfg.Hosts.Publisher.Conn.DBOwnerInfo(), dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer conn.Close(ctx)
if err := conn.Ping(ctx); err != nil {
log.Fatal(err)
}
log.Printf("Revoking the access against '%s' database...", dbName)
if _, err = conn.Exec(ctx, flare.GrantConnectionQuery(dbName)); err != nil {
log.Fatal(err)
}
log.Printf("Database access against '%s' database has been granted!!", dbName)
},
}
return cmd
}
func buildInstallExtensionsCmd(gflags *globalFlags) *cobra.Command {
var onlyShow bool
var useDBOwner bool
cmd := &cobra.Command{
Use: "install_extensions [DBNAME]",
Short: "Install extensions in the publisher into the subscriber",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name in the config\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
pubConnUserInfo := cfg.Hosts.Publisher.Conn.SuperUserInfo()
if useDBOwner {
pubConnUserInfo = cfg.Hosts.Publisher.Conn.DBOwnerInfo()
}
pconn, err := flare.Connect(ctx, pubConnUserInfo, dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer pconn.Close(ctx)
// list the installed extensions
installedExts, err := flare.ListInstalledExtensions(ctx, pconn)
if err != nil {
log.Fatalf("Failed to list the installed extensions: %s\n", err)
}
subConnUserInfo := cfg.Hosts.Subscriber.Conn.SuperUserInfo()
if useDBOwner {
subConnUserInfo = cfg.Hosts.Subscriber.Conn.DBOwnerInfo()
}
sconn, err := flare.Connect(ctx, subConnUserInfo, dbName)
if err != nil {
log.Fatalf("Failed to connect to the subscriber: %s\n", err)
}
defer sconn.Close(ctx)
for _, ext := range installedExts {
if onlyShow {
log.Printf(
"Extension '%s' is installed in the publisher's %s database. Do not install into the subscriber as per request.", ext, dbName,
)
continue
}
if _, err := sconn.Exec(ctx, flare.CreateExtensionQuery(ext)); err != nil {
log.Fatalf(
"Failed to install '%s' extension into the subscriber: %s\n", ext, err,
)
}
log.Printf(
"Extension '%s' has been installed into the subscriber's %s database", ext, dbName,
)
}
},
}
cmd.Flags().BoolVar(
&onlyShow,
"only-show",
false,
"only show the installed extensions",
)
cmd.Flags().BoolVar(
&useDBOwner,
"use-db-owner",
false,
"Use the db owner to dump the schema",
)
return cmd
}
func buildGrantCreateCmd(gflags *globalFlags) *cobra.Command {
var useDBOwner bool
cmd := &cobra.Command{
Use: "grant_create [DBNAME]",
Short: "Grant CREATE and CONNECT in the given database to super-user in the publisher",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
pubConnUserInfo := cfg.Hosts.Publisher.Conn.SuperUserInfo()
if useDBOwner {
pubConnUserInfo = cfg.Hosts.Publisher.Conn.DBOwnerInfo()
}
conn, err := flare.Connect(ctx, pubConnUserInfo, dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer conn.Close(ctx)
superUser := cfg.Hosts.Publisher.Conn.SuperUserInfo().User
log.Printf("Granting CREATE ON DATABASE '%s' to '%s' in the publisher...", dbName, superUser)
if _, err := conn.Exec(ctx, flare.GrantCreateQuery(dbName, superUser)); err != nil {
log.Fatalf("Failed to grant CREATE: %s", err)
}
log.Printf("Granting CONNECT ON DATABASE '%s' to '%s' in the publisher...", dbName, superUser)
if _, err := conn.Exec(ctx, flare.GrantConnectQuery(dbName, superUser)); err != nil {
log.Fatalf("Failed to grant CONNECT: %s", err)
}
},
}
cmd.Flags().BoolVar(
&useDBOwner,
"use-db-owner",
false,
"Use the db owner to grant",
)
return cmd
}
func buildGrantReplicationCmd(gflags *globalFlags) *cobra.Command {
var useDBOwner bool
cmd := &cobra.Command{
Use: "grant_replication [DBNAME]",
Short: "Grant the replication user all privileges on a given database in the publisher",
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 1 {
cmd.PrintErr("please specify a database name\n\n")
cmd.Usage()
os.Exit(1)
}
dbName := args[0]
ctx := context.TODO()
cfg := readConfigFileAndVerifyOrExit(ctx, cmd, gflags.configFile)
replUser := cfg.Hosts.Publisher.Conn.ReplicationUserInfo().User
log.Printf("Granting all privileges on '%s' to '%s' in the publisher...", dbName, replUser)
pubConnUserInfo := cfg.Hosts.Publisher.Conn.SuperUserInfo()
if useDBOwner {
pubConnUserInfo = cfg.Hosts.Publisher.Conn.DBOwnerInfo()
}
conn, err := flare.Connect(ctx, pubConnUserInfo, dbName)
if err != nil {
log.Fatalf("Failed to connect to the publisher: %s\n", err)
}
defer conn.Close(ctx)
if _, err := conn.Exec(ctx, flare.GrantAllOnDatabaseQuery(dbName, replUser)); err != nil {
log.Fatalf("Failed to grant on the database: %s", err)
}
if _, err := conn.Exec(ctx, flare.GrantAllOnAllTablesQuery(replUser)); err != nil {
log.Fatalf("Failed to grant on all the tables: %s", err)
}
log.Printf("'%s' has been granted for '%s'!", replUser, dbName)
},
}
cmd.Flags().BoolVar(
&useDBOwner,
"use-db-owner",
false,
"Use the db owner to grant",
)
return cmd
}
func sRenderSubscriptionStats(conn *flare.Conn, subName string) (string, error) {
thdr := []string{
"SubID", "Sub Name", "PID", "Received LSN", "Last Msg Send Time", "Last Msg Receipt Time", "Latest End LSN", "Latest End Time",
}
var row [][]string
row = append(row, thdr)
stats, err := flare.ListSubscriptionStatByName(context.Background(), conn, subName)
if err != nil {
return "", err
}
for _, stat := range stats {
row = append(row, []string{
stat.SubID,
stat.SubName,
string(stat.PID),
string(stat.ReceivedLSN),
time.Time(stat.LastMsgSendTime).String(),
time.Time(stat.LastMsgReceiptTime).String(),
string(stat.LatestEndLSN),
time.Time(stat.LatestEndTime).String(),
})
}
tbl, _ := pterm.DefaultTable.WithHasHeader().WithData(row).Srender()
return tbl, nil
}
func sRenderReplicationStatsTable(conn *flare.Conn, subName string) (string, error) {
thdr := []string{
"PID", "User Name", "Application Name", "Client Addr", "Backend Start", "State", "Sent LSN", "Reply LSN",
}
var row [][]string
row = append(row, thdr)
stats, err := flare.ListReplicationStatsBySubscription(context.Background(), conn, subName)
if err != nil {
return "", err
}
for _, stat := range stats {
row = append(row, []string{
stat.PID,
stat.UserName,
string(stat.ApplicationName),
string(stat.ClientAddr),
stat.BackendStart.String(),
string(stat.State),
string(stat.SentLSN),
string(stat.ReplayLSN),
})
}
tbl, _ := pterm.DefaultTable.WithHasHeader().WithData(row).Srender()
return tbl, nil
}
func sRenderReplicationSlotsTable(conn *flare.Conn, dbName string) (string, error) {
thdr := []string{
"Slot Name", "Plugin", "Slot Type", "Database", "Temporary", "Active", "Confirmed Flush LSN",
}
var row [][]string
row = append(row, thdr)
slots, err := flare.ListReplicationSlotsByDatabase(context.Background(), conn, dbName)
if err != nil {
return "", err
}