forked from kernelci/kcidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloud
executable file
·2478 lines (2296 loc) · 87.2 KB
/
cloud
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
#!/usr/bin/env bash
#
# Cloud installation management tool.
# Assumes its location is the top directory of KCIDB source tree.
# Deploying creates or updates an installation, withdrawing removes it.
#
# Conventions:
# - *_deploy functions create or update an installation;
# - *_withdraw functions delete installation if it exists;
# - no output should be produced unless something fails;
# - no error/message output on stdout, only stderr.
set -eEuCo pipefail
shopt -s extglob
# The original TMPDIR value
declare -r TMPDIR_ORIG=${TMPDIR:-}
# The directory where all temporary files should be created
export TMPDIR=$(mktemp -d -t "kcidb_cloud.XXXXXXXXXX")
# Location of the PostgreSQL proxy binary we (could) download
declare PSQL_PROXY_BINARY="$TMPDIR/cloud_sql_proxy"
# Location of the PostgreSQL proxy socket directory
declare PSQL_PROXY_DIR="$TMPDIR/cloud_sql_sockets"
# File containing the PID of the shell executing PostgreSQL proxy, if started
declare PSQL_PROXY_SHELL_PID_FILE="$TMPDIR/cloud_sql_proxy.pid"
# The .pgpass file for the command running through PostgreSQL proxy
declare PSQL_PROXY_PGPASS="$TMPDIR/cloud_sql_proxy.pgpass"
# Cleanup after the script
function _cleanup() {
# Kill the cloud_sql_proxy, if started
if [ -e "$PSQL_PROXY_SHELL_PID_FILE" ]; then
declare pid
pid=$(< "$PSQL_PROXY_SHELL_PID_FILE")
pkill -P "$pid" 2>/dev/null || true
rm -f "$PSQL_PROXY_SHELL_PID_FILE"
fi
# Remove the directory with all the temporary files
rm -Rf "$TMPDIR"
}
# Cleanup on exit
trap _cleanup EXIT
# The list of pairs of shell PIDs and commands to be executed on error exits
# from the corresponding shells, separated by a colon.
declare -a ATERR=()
# Execute "aterr" commands belonging to the current shell, in reverse order.
function aterr_exec()
{
declare i
for ((i = ${#ATERR[@]} - 1; i >= 0; i--)); do
if [ "${ATERR[i]%%:*}" == "$BASHPID" ]; then
eval "${ATERR[i]#*:}"
fi
done
}
# Execute aterr_exec on error exit enabled with "set -e".
# Expect "set -E" propagating the ERR trap everywhere.
trap aterr_exec ERR
# Push a command to the stack of "aterr" commands. The command will be
# executed on error exit from the current shell only.
# Args: command
function aterr_push()
{
declare -r command="$1"; shift
ATERR+=("$BASHPID:$command")
}
# Pop the last command pushed to the stack of "aterr" commands.
# Only pops the command if it was pushed by the same shell.
function aterr_pop()
{
if [ "${ATERR[-1]%%:*}" == "$BASHPID" ]; then
unset ATERR[-1]
fi
}
# "true" if verbose output is enabled, "false" otherwise
declare VERBOSE="false"
# Run a command with stdout redirected to stderr, if verbose output is
# enabled.
# Args: command [arg...]
function verbose() {
if "$VERBOSE"; then
"$@" >&2
fi
}
# Generate code declaring parameter variables with names and values passed
# through long-option command-line argument list, and assigning the positional
# arguments.
#
# Args: [param_name...] [-- [param_arg...]]
#
# Each parameter name ("param_name") must be a string matching the
# ^[A-Za-z_][A-Za-z0-9_]*?$ regex, specifying both the name of the option and
# the name of the local variable. However, all underscores ("_") are replaced
# with dashes ("-") in option names.
#
# Each parameter argument ("param_arg") is a command-line argument specifying
# long options and/or their values.
#
# Output: Code declaring parameter variables and assigning values to them.
#
function getopt_vars() {
declare -a longopts=()
declare -a params=()
declare -A params_value=()
declare arg
declare param
declare parsed_args
# Parse parameter specifications
while (($#)); do
arg="$1"; shift
if [ "$arg" == "--" ]; then
break
fi
if ! [[ $arg =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then
echo "Invalid parameter specification: ${arg@Q}" >&2
return 1
fi
longopts+=("${arg//_/-}:")
params+=("$arg")
done
# Parse parameter arguments
parsed_args="$(IFS=","
getopt --name getopt_vars --options "" \
--longoptions "${longopts[*]}" \
-- "$@")"
eval set -- "$parsed_args"
while true; do
case "$1" in
--?*)
param="${1:2}"
param="${param//-/_}"
params_value[$param]="$2"
shift 2
;;
--)
shift
break
;;
*)
echo "Unknown argument: ${1@Q}" >&2
return 1
;;
esac
done
# Generate code assigning parameters and checking for missing ones
for param in "${params[@]}"; do
if [[ -v params_value[$param] ]]; then
echo "declare $param=${params_value[$param]@Q}"
else
echo "Required parameter missing: ${param@Q}" >&2
return 1
fi
done
# Generate code reassigning positional arguments
echo "set -- ${@@Q}"
}
# Execute a command, capturing both stdout and stderr, and only outputting
# them both to stderr, if the command fails.
# Args: [argv...]
function mute() {
declare output_file
output_file=$(mktemp -t "XXXXXXXXXX.output")
aterr_push """
cat ${output_file@Q} >&2 || true
rm -f ${output_file@Q}
"""
"$@" >|"$output_file" 2>&1
rm -f "$output_file"
aterr_pop
}
# Enable Google Cloud services using their short names
# Args: project [name...]
function services_enable() {
declare -r project="$1"; shift
declare -a names=("$@")
for ((i = 0; i < ${#names[@]}; i++)); do
names[$i]="${names[$i]}.googleapis.com"
done
mute gcloud services enable --quiet --project="$project" "${names[@]}"
}
# The name of the Cloud SQL instance we're creating/using
# Specified statically as instance names have 7-day recycling period
declare -r PSQL_INSTANCE="postgresql"
# The region used to host our PostgreSQL instance
declare -r PSQL_INSTANCE_REGION="us-central1"
# The tier used for the automatically-created PostgreSQL instance
declare -r PSQL_INSTANCE_TIER="db-f1-micro"
# The name of the PostgreSQL viewer user. Granted read-only permissions for
# all KCIDB databases to make it easier to switch the queried database in UI.
declare -r PSQL_VIEWER="kcidb_viewer"
# Check if a PostgreSQL instance exists.
# Args: project name
# Output: "true" if the instance exists, "false" otherwise.
function psql_instance_exists() {
declare -r project="$1"; shift
declare -r name="$1"; shift
declare output
if output=$(
gcloud sql instances describe \
--quiet --project="$project" \
"$name" 2>&1
); then
echo "true"
elif [[ $output == *\ instance\ does\ not\ exist.* ]]; then
echo "false"
else
echo "$output" >&2
false
fi
}
# Deploy a PostgreSQL instance if it doesn't exist
# Args: project name viewer
function psql_instance_deploy() {
declare -r project="$1"; shift
declare -r name="$1"; shift
declare -r viewer="$1"; shift
declare exists
exists=$(psql_instance_exists "$project" "$name")
if ! "$exists"; then
# Get and cache the password in the current shell first
password_get psql_superuser >/dev/null
# Create the instance with the cached password
# Where are your security best practices, Google?
mute gcloud sql instances create \
"$name" \
--quiet \
--project="$project" \
--region="$PSQL_INSTANCE_REGION" \
--tier="$PSQL_INSTANCE_TIER" \
--assign-ip \
--database-flags=cloudsql.iam_authentication=on \
--root-password="$(password_get psql_superuser)" \
--database-version=POSTGRES_14
fi
# Deploy the shared viewer user
exists=$(psql_user_exists "$project" "$name" "$viewer")
if ! "$exists" || password_is_specified psql_viewer; then
# Get and cache the password in the current shell first
password_get psql_viewer >/dev/null
# Create the user with the cached password
password_get psql_viewer |
psql_user_deploy "$project" "$name" "$viewer"
fi
}
# Execute a command with the PostgreSQL proxy providing the connection to a
# server with the "postgres" user. Setup environment variables for
# connection with only a database specification required, using libpq.
# Args: project instance command arg...
function psql_proxy_session() {
# Source:
# https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#install
declare -r url_base="https://dl.google.com/cloudsql/cloud_sql_proxy."
declare -r -A url_os_sfx=(
["x86_64 GNU/Linux"]="linux.amd64"
["i386 GNU/Linux"]="linux.386"
)
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r fq_instance="$project:$PSQL_INSTANCE_REGION:$instance"
# The default proxy binary, if installed
declare proxy="cloud_sql_proxy"
declare pid
declare pgpass
# If we don't have the proxy in our path
if ! command -v "$proxy" >/dev/null; then
# If we don't have the proxy binary downloaded yet
if ! [ -e "$PSQL_PROXY_BINARY" ]; then
declare -r url="${url_base}${url_os_sfx[$(uname -m -o)]}"
# Download the proxy binary
mute wget --quiet -O "$PSQL_PROXY_BINARY" "$url"
chmod 0755 "$PSQL_PROXY_BINARY"
fi
# Use the downloaded proxy
proxy="$PSQL_PROXY_BINARY"
fi
# If we don't have the socket directory created yet
if ! [ -e "$PSQL_PROXY_DIR" ]; then
# Create the temporary directory
mkdir "$PSQL_PROXY_DIR"
fi
# Start the proxy in background
mute "$proxy" "-instances=$fq_instance" "-dir=$PSQL_PROXY_DIR" &
pid="$!"
# Store the PID of the shell running the proxy, for errexit cleanup
echo -n "$pid" > "$PSQL_PROXY_SHELL_PID_FILE"
# Create the .pgpass file
touch "$PSQL_PROXY_PGPASS"
chmod 0600 "$PSQL_PROXY_PGPASS"
password_get_pgpass psql_superuser postgres >| "$PSQL_PROXY_PGPASS"
# Wait for the proxy to become ready
declare max_checks=10
declare delay=3
declare checks
declare output=""
declare ready="false"
for ((checks=0; checks < max_checks; checks++)); do
if output+=$(
PGHOST="$PSQL_PROXY_DIR/$fq_instance" \
PGPASSFILE="$PSQL_PROXY_PGPASS" \
PGUSER="postgres" \
pg_isready
)$'\n'; then
ready="true"
break;
fi
sleep "$delay"
done
# Check if the wait was successful
if ! "$ready"; then
echo "PostgreSQL proxy ${proxy@Q} is not ready " \
"after $((checks * delay)) seconds." >&2
if [ -n "$output" ]; then
echo "pg_isready output:" >&2
echo "$output" >&2
fi
fi
"$ready"
# Run the command
PGHOST="$PSQL_PROXY_DIR/$fq_instance" \
PGPASSFILE="$PSQL_PROXY_PGPASS" \
PGUSER="postgres" \
"$@"
# Remove the .pgpass file
rm "$PSQL_PROXY_PGPASS"
# Stop the proxy
pkill -P "$pid" && wait "$pid" || true
rm "$PSQL_PROXY_SHELL_PID_FILE"
}
# Check if a PostgreSQL database exists.
# Args: project instance database
# Output: "true" if the database exists, "false" otherwise.
function psql_database_exists() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r database="$1"; shift
declare output
if output=$(
gcloud sql databases describe \
--quiet --project="$project" \
--instance="$instance" \
"$database" 2>&1
); then
echo "true"
elif [[ $output == *\ Not\ Found* ]]; then
echo "false"
else
echo "$output" >&2
false
fi
}
# Setup a PostgreSQL database and its paraphernalia.
# Expect the environment to be set up with variables permitting a libpq user
# to connect to the database as a superuser.
# Args: database init submitter viewer
function _psql_database_setup() {
declare -r database="$1"; shift
declare -r init="$1"; shift
declare -r submitter="$1"; shift
declare -r viewer="$1"; shift
# Deploy viewer and submitter permissions
mute psql --dbname="$database" -e <<<"
\\set ON_ERROR_STOP on
GRANT USAGE ON SCHEMA public TO $submitter, $viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT, INSERT, UPDATE ON TABLES TO $submitter;
GRANT SELECT, INSERT, UPDATE ON ALL TABLES
IN SCHEMA public TO $submitter;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO $viewer;
GRANT SELECT ON ALL TABLES
IN SCHEMA public TO $viewer;
"
# Initialize the database, if requested
if "$init"; then
mute kcidb-db-init -lDEBUG -d "postgresql:dbname=$database" \
--ignore-initialized
fi
}
# Cleanup a PostgreSQL database and its paraphernalia.
# Expect the environment to be set up with variables permitting a libpq user
# to connect to the database as a superuser.
# Args: database submitter viewer
function _psql_database_cleanup() {
declare -r database="$1"; shift
declare -r submitter="$1"; shift
declare -r viewer="$1"; shift
# Withdraw viewer and submitter permissions
mute psql --dbname="$database" -e <<<"
/* Do not stop on errors in case users are already removed */
REVOKE SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA public
FROM $submitter;
REVOKE SELECT ON ALL TABLES IN SCHEMA public
FROM $viewer;
\\set ON_ERROR_STOP on
/* Terminate all connections to the database except this one */
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = :'DBNAME' AND pid <> pg_backend_pid();
"
mute kcidb-db-cleanup -lDEBUG -d "postgresql:dbname=$database" \
--ignore-not-initialized \
--ignore-not-found
}
# Deploy PostgreSQL databases, if they don't exist
# Do not initialize databases that are prepended with the hash sign ('#').
# Args: project instance viewer [database submitter]...
function psql_databases_deploy() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r viewer="$1"; shift
declare database
declare submitter
declare init
while (($#)); do
database="$1"; shift
submitter="$1"; shift
# Handle possible leading hash sign
if [[ $database == \#* ]]; then
database="${database:1}"
init=false
else
init=true
fi
# Create the database, if not exists
exists=$(psql_database_exists "$project" "$instance" "$database")
if ! "$exists"; then
mute gcloud sql databases create \
"$database" \
--quiet \
--project="$project" \
--instance="$instance"
fi
# Deploy the per-database submitter user
exists=$(psql_user_exists "$project" "$instance" "$submitter")
if ! "$exists" || password_is_specified psql_submitter; then
# Get and cache the password in the current shell first
password_get psql_submitter >/dev/null
# Create the user with the cached password
password_get psql_submitter |
psql_user_deploy "$project" "$instance" "$submitter"
fi
# NOTE: The viewer user is created per-instance
# Setup the database
psql_proxy_session "$project" "$instance" \
_psql_database_setup "$database" "$init" "$submitter" "$viewer"
done
}
# Withdraw PostgreSQL databases, if they exist
# Cleanup all databases, even those prepended with the hash sign ('#').
# Args: project instance viewer [database submitter]...
function psql_databases_withdraw() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r viewer="$1"; shift
declare -a -r databases_and_submitters=("$@")
declare database
declare submitter
# Cleanup and remove the databases
set -- "${databases_and_submitters[@]}"
while (($#)); do
# Ignore possible leading hash sign
database="${1###}"; shift
submitter="$1"; shift
exists=$(psql_database_exists "$project" "$instance" "$database")
if "$exists"; then
# Cleanup the database
psql_proxy_session "$project" "$instance" \
_psql_database_cleanup "$database" "$submitter" "$viewer"
# Delete the database
mute gcloud sql databases delete \
"$database" \
--quiet \
--project="$project" \
--instance="$instance"
fi
done
# Remove the users afterwards as they could be shared by databases
set -- "${databases_and_submitters[@]}"
while (($#)); do
# Discard the database name
shift
submitter="$1"; shift
# Withdraw the submitter user
psql_user_withdraw "$project" "$instance" "$submitter"
# NOTE: The viewer user is per-instance
done
}
# Check if a PostgreSQL user exists
# Args: project instance name
function psql_user_exists() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r name="$1"; shift
declare output
if output=$(
gcloud sql users list \
--quiet --project="$project" \
--instance="$instance" \
--filter "name=$name" 2>&1
); then
# Skip header / "Listed 0 items." message
output=$(sed -e 1d <<<"$output")
[ -n "$output" ] && echo "true" || echo "false"
else
echo "$output" >&2
false
fi
}
# Deploy a PostgreSQL user
# Args: project instance name
# Input: password
function psql_user_deploy() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r name="$1"; shift
exists=$(psql_user_exists "$project" "$instance" "$name")
if "$exists"; then
mute gcloud sql users set-password \
--quiet --project="$project" \
--instance="$instance" \
--prompt-for-password \
"$name"
else
# Where are your security best practices, Google?
mute gcloud sql users create \
--quiet --project="$project" \
--instance="$instance" \
--password="$(cat)" \
"$name"
fi
# Strip extra permissions added by gcloud by default
psql_proxy_session "$project" "$instance" \
mute psql --dbname postgres -e <<<"
\\set ON_ERROR_STOP on
REVOKE cloudsqlsuperuser FROM $name;
ALTER ROLE $name WITH NOCREATEROLE NOCREATEDB;
"
}
# Withdraw a PostgreSQL user
# Args: project instance name
function psql_user_withdraw() {
declare -r project="$1"; shift
declare -r instance="$1"; shift
declare -r name="$1"; shift
exists=$(psql_user_exists "$project" "$instance" "$name")
if "$exists"; then
mute gcloud sql users delete \
--quiet --project="$project" \
--instance="$instance" \
"$name"
fi
}
# Deploy (to) PostgreSQL.
# Do not initialize databases that are prepended with the hash sign ('#').
# Args: project [database submitter]...
function psql_deploy() {
declare -r project="$1"; shift
# Deploy the instance
psql_instance_deploy "$project" "$PSQL_INSTANCE" "$PSQL_VIEWER"
# Deploy the databases
psql_databases_deploy "$project" "$PSQL_INSTANCE" "$PSQL_VIEWER" "$@"
}
# Withdraw (from) PostgreSQL
# Cleanup all databases, even those prepended with the hash sign ('#').
# Args: project [database submitter]...
function psql_withdraw() {
declare -r project="$1"; shift
psql_databases_withdraw "$project" "$PSQL_INSTANCE" "$PSQL_VIEWER" "$@"
# NOTE: Leaving the instance behind. Its name has 7-day recycling period
# NOTE: Leaving the viewer user behind, as it's per-instance
}
# Deploy to BigQuery
# Do not initialize datasets that are prepended with the hash sign ('#').
# Args: project dataset...
function bigquery_deploy() {
declare -r project="$1"; shift
declare dataset
declare init
for dataset in "$@"; do
# Handle possible leading hash sign
if [[ $dataset == \#* ]]; then
dataset="${dataset:1}"
init=false
else
init=true
fi
mute bq mk --project_id="$project" --force "$dataset"
if "$init"; then
kcidb-db-init -lDEBUG -d "bigquery:${project}.${dataset}" \
--ignore-initialized
fi
done
}
# Withdraw from BigQuery
# Cleanup all datasets, even those prepended with the hash sign ('#').
# Args: project dataset...
function bigquery_withdraw() {
declare -r project="$1"; shift
declare dataset
for dataset in "$@"; do
# Ignore possible leading hash sign
dataset="${dataset###}"
kcidb-db-cleanup -lDEBUG -d "bigquery:${project}.${dataset}" \
--ignore-not-initialized \
--ignore-not-found
mute bq rm --project_id="$project" --force "$dataset"
done
}
# Check if the native Firestore database exists
# Args: project
function firestore_exists() {
declare -r project="$1"; shift
declare output
if output=$(
gcloud firestore databases describe \
--quiet --project="$project" 2>&1
); then
echo "true"
elif [[ $output == *database\ \'\(default\)\'\ does\ not\ exist.* ]]; then
echo "false"
else
echo "$output" >&2
false
fi
}
# Create the native Firestore database.
# Args: project
function firestore_create() {
declare -r project="$1"; shift
# Create the native database (in the same region as the App Engine app)
mute gcloud firestore databases create --quiet \
--project="$project" \
--type=firestore-native \
--location=nam5
}
# Deploy to Firestore.
# Args: project
function firestore_deploy() {
declare -r project="$1"; shift
declare exists
exists=$(firestore_exists "$project")
if ! "$exists"; then
firestore_create "$project"
fi
}
# Withdraw from Firestore.
# Args: project spool_collection_path
function firestore_withdraw() {
declare -r project="$1"; shift
declare -r spool_collection_path="$1"; shift
kcidb-monitor-spool-wipe -p "$project" -c "$spool_collection_path"
}
# Check if the App Engine app exists.
# Args: project
# Output: "true" if the app exists, "false" otherwise.
function app_exists() {
declare -r project="$1"; shift
declare output
if output=$(
gcloud app describe --quiet --project="$project" 2>&1
); then
echo "true"
elif [[ $output == *\ does\ not\ contain\ * ]]; then
echo "false"
else
echo "$output" >&2
false
fi
}
# Create the App Engine app, if it doesn't exist.
# Args: project
function app_deploy() {
declare -r project="$1"; shift
exists=$(app_exists "$project")
if "$exists"; then
return
fi
mute gcloud app create --quiet --project="$project" --region=us-central
}
# A map of password names and their descriptions
declare -r -A PASSWORD_DESCS=(
[smtp]="SMTP"
[psql_superuser]="PostgreSQL superuser"
[psql_submitter]="PostgreSQL submitter user"
[psql_viewer]="PostgreSQL viewer user"
)
# A map of password names and their "can be auto-generated" flags.
# The corresponding password will be auto-generated if the flag is "true", and
# no source file nor secret was specified for it.
declare -A PASSWORD_GENERATE=(
[psql_submitter]="true"
[psql_viewer]="true"
)
# A map of password names and their project and secret names, separated by a
# colon. Used for retrieving passwords if they have no source files specified.
declare -A PASSWORD_SECRETS=()
# A map of password names and their source files
declare -A PASSWORD_FILES=()
# A map of password names and their strings
declare -A PASSWORD_STRINGS=()
# Ask the user to input a password with specified name.
# Args: name
# Output: The retrieved password
function password_input() {
declare -r name="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
declare password
read -p "Enter ${PASSWORD_DESCS[$name]:-a} password: " -r -s password
echo "" >&2
echo -n "$password"
}
# Get a password with specified name, either from the cache, from its source
# file, from its secret, or from the user. Make sure the retrieved password is
# cached.
# Args: name
# Output: The retrieved password
function password_get() {
declare -r name="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
declare password
declare -r password_file="${PASSWORD_FILES[$name]:-}"
declare -r password_secret="${PASSWORD_SECRETS[$name]:-}"
declare password_secret_exists
password_secret_exists=$(
if [ -n "$password_secret" ]; then
secret_exists "${password_secret%%:*}" "${password_secret#*:}"
else
echo "false"
fi
)
declare -r password_secret_exists
declare -r password_generate="${PASSWORD_GENERATE[$name]:-false}"
# If cached
if [[ -v PASSWORD_STRINGS[$name] ]]; then
password="${PASSWORD_STRINGS[$name]}"
# If file is specified
elif [ -n "$password_file" ]; then
# If asked to read from standard input
if [ "$password_file" == "-" ]; then
password=$(password_input "$name")
else
password=$(<"$password_file")
fi
# If secret exists
elif "$password_secret_exists"; then
password=$(
secret_get "${password_secret%%:*}" "${password_secret#*:}"
)
# If can be generated
elif "$password_generate"; then
password=$(dd if=/dev/random bs=32 count=1 status=none | base64)
# Else read from user
else
password=$(password_input "$name")
fi
PASSWORD_STRINGS[$name]="$password"
echo -n "$password"
}
# Get a password as a PostgreSQL's .pgpass file, generated with the specified
# username.
# Args: name username
# Output: The generated .pgpass file
function password_get_pgpass() {
declare -r name="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
declare -r username="$1"; shift
declare -r -a escape_argv=(sed -e 's/[:\\]/\\&/g')
echo -n "*:*:*:"
echo -n "$username" | "${escape_argv[@]}"
echo -n ":"
password_get "$name" | "${escape_argv[@]}"
}
# Set the source file for a password with specified name. The file will be
# used as the source of the password by password_get, if it wasn't already
# retrieved (and cached) before. Can be specified as "-" to have password
# requested from standard input.
# Args: name file
function password_set_file() {
declare -r name="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
declare -r file="$1"; shift
PASSWORD_FILES[$name]="$file"
}
# Set the project and the name of the secret storing the password with
# specified name. The password will be retrieved from the secret, if it wasn't
# cached, and if its source file wasn't specified.
# Args: name project secret
function password_set_secret() {
declare -r name="$1"; shift
declare -r project="$1"; shift
declare -r secret="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
if [[ "$project" = *:* ]]; then
echo "Invalid project name ${project@Q}" >&2
exit 1
fi
PASSWORD_SECRETS[$name]="$project:$secret"
}
# Specify the single-word command returning exit status specifying if the
# password with specified name could be auto-generated or not.
# Args: name generate
function password_set_generate() {
declare -r name="$1"; shift
declare -r generate="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
PASSWORD_GENERATE[$name]="$generate"
}
# Check if a password with the specified name is explicitly specified by the
# command-line user. That is, if it has a source file.
function password_is_specified() {
declare -r name="$1"; shift
if ! [[ -v PASSWORD_DESCS[$name] ]]; then
echo "Unknown password name ${name@Q}" >&2
exit 1
fi
[[ -v PASSWORD_FILES[$name] ]]
}
# Check if a secret exists
# Args: project name
# Output: "true" if the secret exists, "false" otherwise.
function secret_exists() {
declare -r project="$1"; shift
declare -r name="$1"; shift
declare output
if output=$(
gcloud secrets describe --quiet --project="$project" "$name" 2>&1
); then
echo "true"
elif [[ $output == *NOT_FOUND* ]]; then
echo "false"
else
echo "$output" >&2
false
fi
}
# Deploy a secret
# Args: project name
# Input: value
function secret_deploy() {
declare -r project="$1"; shift
declare -r name="$1"; shift
declare exists
exists=$(secret_exists "$project" "$name")
if "$exists"; then
mute gcloud secrets versions add --quiet --project="$project" \
"$name" \
--data-file=-
else
mute gcloud secrets create --quiet --project="$project" "$name" \
--replication-policy automatic \
--data-file=-
fi
}
# Retrieve a secret
# Args: project name
# Output: value
function secret_get() {
declare -r project="$1"; shift
declare -r name="$1"; shift
gcloud secrets versions access latest \
--quiet --project="$project" --secret="$name" \
--format='get(payload.data)' | tr '_-' '/+' | base64 -d
}
# Delete a secret if it exists
# Args: project name
function secret_withdraw() {
declare -r project="$1"; shift
declare -r name="$1"; shift
exists=$(secret_exists "$project" "$name")
if "$exists"; then
mute gcloud secrets delete --quiet --project="$project" "$name"
fi
}
# The name of the shared SMTP password secret
declare -r SMTP_PASSWORD_SECRET="kcidb_smtp_password"
# The name of the shared secret with PostgreSQL superuser password
declare -r PSQL_SUPERUSER_SECRET="kcidb_psql_superuser"
# The name of the shared secret with PostgreSQL viewer password
declare -r PSQL_VIEWER_SECRET="kcidb_psql_viewer"
# Deploy secrets
# Args: project
# psql_submitter_secret
# psql_submitter_pgpass_secret
# psql_submitter_username
function secrets_deploy() {
declare -r project="$1"; shift
declare -r psql_submitter_secret="$1"; shift
declare -r psql_submitter_pgpass_secret="$1"; shift
declare -r psql_submitter_username="$1"; shift