-
Notifications
You must be signed in to change notification settings - Fork 12
/
manage
executable file
·1537 lines (1326 loc) · 58 KB
/
manage
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
#!/bin/bash
export MSYS_NO_PATHCONV=1
SCRIPT_HOME="$( cd "$( dirname "$0" )" && pwd )"
# =================================================================================================================
# Usage:
# -----------------------------------------------------------------------------------------------------------------
usage () {
cat <<-EOF
Allows you to manage certain aspects of TheOrgBook environment.
Usage:
$0 [options] [commands]
Example:
$0 -P -e test resetDatabase
- This will reset the database in TheOrgBook's TEST environment.
Options:
========
-s <ResourceSuffix>; The suffix used to identify the resource instances.
- Defaults to '${resourceSuffix}'
Commands:
========
reset
- Reset the environment.
- All data will be lost.
The following operations will be performed:
- The process pauses at the beginning to ensure the related BC Registries Agent reset process has started.
- The wallet is reset, by restoring initial copy of OrgBook Wallet.
- The 'db' is reset and reinitialized.
- The search indexes are reset.
- The process pauses to ensure the related BC Registries Agent registration process has had time to complete.
- The BC Registries Agent registration is verified.\n
resetDatabase
- Drop and recreate the database.
- Rebuild search indexes.
deleteDatabase
- Deletes all databases off a pod and recycles the pod leaving it in a clean state.
- Useful when database credentials change.
resetSearchIndex
- Delete and recreate the search index for a given environment.
resetSolrCore
- Delete and recreate the search-engine core for a given environment.
rebuildSearchIndex
- Rebuild the search index for a given environment.
updateSearchIndex
- Update the search index for a given environment.
- Supports passing arguments to updateSearchIndex.sh. For example:
$0 -p bc -e dev updateSearchIndex -b 500 -d 2019-07-04T00:00:00Z
indexSynced
- Check to see if the search-engine indexes are syned with the database credentials.
deleteTopic <topic_id>
- Delete the specified topic from the OrgBook database.
Where:
- <topic_id> is the 'subject_id' of the Topic to delete, e.g. BC1234567
Example:
$0 -p bc-tob -e dev deleteTopic BC1234567
getDbDiskUsage
- Get the disk usage information for a given database pod.
For example;
$0 -e dev getDbDiskUsage wallet-bc
listDatabases <podName/>
- List the databases hosted on a given postgresql pod instance.
Example;
$0 -e dev listdatabases wallet
getConnections <podName/>
- List database connection statistics for a given postgresql pod instance.
Example;
$0 -e dev getconnections wallet
getRecordCounts <podName/> [<databaseName/>]
- Gets a list of tables and the total number of record in each table.
Examples;
$0 -e dev getrecordcounts wallet agent_indy_cat_wallet
- Get the record counts for the 'agent_indy_cat_wallet' database off the 'wallet' pod.
$0 -e dev getrecordcounts event-db
- Get the record counts for the '${POSTGRESQL_DATABASE}' (the pod's default database) database off the 'event-db' pod.
listBuildRefs
- Lists build configurations and their git references in a convenient column format.
getAgentConnections
- List all agent connections.
removeAgentConnections
- Remove all agent connections.
locateBadRecord [<podName/>] [<databaseName/>] [<tableName/>] [<limit/>] [<startAtRecord/>] [<stopAtRecord/>]
- Scan a given database table for corrupt records.
- By default records are scanned 5000 at a time to roughly locate the affected records.
- Additional parameters can then be used to narrow down on and identify the affected records.
- To get the actual 'id' of a given record once you've identified it's offset, set <limit/> to 1, and
<startAtRecord/> and <stopAtRecord/> to the offset of the affected record.
Parameters:
<podName/>
- The name of the pod hosting the database. Defaults to 'wallet'.
<databaseName/>
- The name of the database to scan. Defaults to 'agent_indy_cat_wallet'.
<tableName/>
- The name of the table to scan. Defaults to 'items'.
<limit/>
- The number of records to scan at a time. Defaults to 5000.
<startAtRecord/>
- The record to start with (the starting offset into the table). Defaults to '0'.
<stopAtRecord/>
- The record to stop at (roughly). Default to the number of records in the table being scanned.
Examples;
$0 -p bc -e prod locateBadRecord
- Scan using the default settings.
$0 -p bc -e prod locateBadRecord wallet agent_indy_cat_wallet items 1 10 20
- Scan records 10 through 20.
$0 -p bc -e prod locateBadRecord wallet agent_indy_cat_wallet items 5000 1185000
- Scan 5000 records at a time starting with record number 1185000
$0 -p bc -e prod locateBadRecord wallet agent_indy_cat_wallet items 1 5907729 5907729
- Get the 'id' of the record at offset 5907729.
getRunningProcesses
- Get a list of running processes running on a pod.
Runs 'ps -aux' on the pod.
tagApplicationImages <sourceTag/> <destinationTag/>
- Tags all of the application images.
- Handy for making backups of images.
untagApplicationImages <tag/>
- Deletes a specific tag from all of the application images.
- Handy for cleaning up backups of images.
Offline Indexing Commands:
==========================
===================================================================================================================================
An example workflow:
-----------------------------------------------------------------------------------------------------------------------------------
# Provision the offline indexing environment.
genDepls.sh -p bc-offline-indexing -e prod
# Or, update the offline indexing environment's configuration.
genDepls.sh -p bc-offline-indexing -e prod -u
# Promote the latest images to the offline indexing environment.
./manage -p bc-offline-indexing -e tools promoteOffineIndexingImages test prod
# Initialize the offline indexing environment
./manage -p bc-offline-indexing -e prod initOfflineIndexingEnv
# Check the status of the offline indexing environment.
./manage -p bc-offline-indexing -e prod offlineIndexSynced
# Compare with the online environment. The Actual Credential counts should be close, within a few thousand.
./manage -p bc -e prod indexSynced
# Check the status of the offline indexing volumes. Volumes should be starting on their original containers.
./manage -p bc-offline-indexing -e prod indexStorageStatus
# ----------------------------------------------------------------------------------------------------------
# If offline indexing was done on a newer version of code containing indexing/model changes:
# Now is the time to run any SQL scripts or updates not covered by automated migrations.
# ----------------------------------------------------------------------------------------------------------
# Run the offline indexing process on the offline volume. This could take a few days.
./manage -p bc-offline-indexing -e prod rebuildOfflineSearchIndex
# Monitor the indexing progress until complete.
# You will likely lose the terminal connection to the pod rebuilding the index but the process will continue running.
./manage -p bc-offline-indexing -e prod offlineIndexSynced
./manage -p bc-offline-indexing -e prod listOffineIndexingProcesses
# Swap the offline indexing volumes.
./manage -p bc-offline-indexing -e prod swapIndexStorage
# Check the status of the offline indexing volumes. Volumes should be on opposite containers now.
./manage -p bc-offline-indexing -e prod indexStorageStatus
# ----------------------------------------------------------------------------------------------------------
# If offline indexing was done on a newer version of code containing indexing changes:
# Deploy that same version of code to the online environment now using the standard promotion pipelines.
# ----------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------
# If offline indexing was done on a newer version of code containing indexing/model changes:
# Now is the time to run any SQL scripts or updates not covered by automated migrations.
# ----------------------------------------------------------------------------------------------------------
# Update the online indexes to sync up the new records that came in over the time the offline indexing was running.
./manage -p bc -e prod updateSearchIndex -b 500 -d 2021-01-26T00:00:00Z
# Ensure the online indexes are synced.
./manage -p bc -e prod indexSynced
# ----------------------------------------------------------------------------------------------------------
# If offline indexing was done on a newer version of code containing indexing changes:
# Ensure you test the updated deployment before you continue. If you need to roll back, you will have
# to swap the index volumes back first.
# ----------------------------------------------------------------------------------------------------------
# Initialize the offline indexing environment with a newer backup. There could be thousands of new records by now.
./manage -p bc-offline-indexing -e prod initOfflineIndexingEnv
# ----------------------------------------------------------------------------------------------------------
# If offline indexing was done on a newer version of code containing indexing/model changes:
# Now is the time to run any SQL scripts or updates not covered by automated migrations.
# ----------------------------------------------------------------------------------------------------------
# Run the offline indexing process again on the orginal volume. This could take a few days.
./manage -p bc-offline-indexing -e prod rebuildOfflineSearchIndex
# Monitor the indexing progress until complete.
# You will likely lose the terminal connection to the pod rebuilding the index but the process will continue running.
./manage -p bc-offline-indexing -e prod offlineIndexSynced
./manage -p bc-offline-indexing -e prod listOffineIndexingProcesses
# Swap the offline indexing volumes back to their original containers
./manage -p bc-offline-indexing -e prod swapIndexStorage
# Check the status of the offline indexing volumes. Volumes should be connected to their original containers now.
./manage -p bc-offline-indexing -e prod indexStorageStatus
# Update the online indexes to sync up the new records that came in over the time the offline indexing was running.
./manage -p bc -e prod updateSearchIndex -b 500 -d 2021-01-26T00:00:00Z
# Ensure the online indexes are synced.
./manage -p bc -e prod indexSynced
# Scale down the offline indexing environment until the new time it's needed.
./manage -p bc-offline-indexing -e prod scaleOfflineIndexEnv down
===================================================================================================================================
===================================================================================================================================
Example of updating the offline indexes:
-----------------------------------------------------------------------------------------------------------------------------------
# Update offline indexes
./manage -p bc-offline-indexing -e prod -s -oli updateSearchIndex -b 1000 -d 2021-02-02T00:00:00Z offline-indexer
===================================================================================================================================
removeOfflineIndexingEnvironment [<appGroup/>]
- Remove an Offline Indexing Environment
Parameters:
<appGroup/>
- Optional - The name of the Offline Indexing Environment to remove. Removes the default 'offline-indexing' resources by default.
Example;
$0 -p bc-offline-indexing -e test removeOfflineIndexingEnvironment
offlineIndexSynced [<indexerPodName/>] [<dbPodName/>]
- Get the status of an offline index sync process.
Parameters:
<indexerPodName/>
- Optional - The name of the Offline Indexing pod. Defaults to 'offline-indexer'.
<dbPodName/>
- Optional - The name of the pod hosting the database being indexed. Defaults to 'db'.
<offlineIndexerResourceSuffix/>
- Optional environment variable - The suffix of the offline indexing resources. Defaults to '-oli'.
Example;
$0 -p bc-offline-indexing -e test offlineIndexSynced
scaleOfflineIndexEnv <direction/> [<indexerPodName/>] [<searchEnginePodName/>] [<dbPodName/>]
- Scale the offline indexing environment up or down.
Parameters:
<direction/>
- up or down.
<indexerPodName/>
- Optional - The name of the pod hosting the offline indexing service.
<searchEnginePodName/>
- Optional - The name of the pod hosting the offline search engine service.
<dbPodName/>
- Optional - The name of the pod hosting the offline database.
Examples;
$0 -p bc-offline-indexing -e test scaleOfflineIndexEnv up
$0 -p bc-offline-indexing -e test scaleOfflineIndexEnv down
swapIndexStorage [<onlineSearchEngine/>] [<offlineSearchEngine/>]
- Swap the index storage between the online and offline search engines.
Parameters:
<onlineSearchEngine/>
- Optional - The name of the pod hosting the online search engine service.
<offlineSearchEngine/>
- Optional - The name of the pod hosting the offline search engine service.
Examples;
$0 -p bc-offline-indexing -e test swapIndexStorage
indexStorageStatus [<onlineSearchEngine/>] [<offlineSearchEngine/>]
- Determine which PVC is mounted to which container.
Parameters:
<onlineSearchEngine/>
- Optional - The name of the pod hosting the online search engine service.
<offlineSearchEngine/>
- Optional - The name of the pod hosting the offline search engine service.
Examples;
$0 -p bc-offline-indexing -e test indexStorageStatus
initOfflineIndexingEnv
- Restores the most recent backup to the offline indexing environment.
rebuildOfflineSearchIndex
- Rebuild the search index in the offline environment.
listOffineIndexingProcesses
- Get a list of processes running on the offline indexing pod.
- Offline indexing can take a day or so, so you are likely to loose any connection you
have to the container monitoring the indexing process. This command allows you
to determine whether the indexing processes are still running.
promoteOffineIndexingImages <sourceEnv/> <destEnv/>
- Promote offine indexing images from one environment to another.
Examples;
$0 -p bc-offline-indexing -e tools promoteOffineIndexingImages test prod
Scaling Commands:
==========================
scaleUp
- Scale up one or more pods.
For example;
$0 -e dev scaleUp api
scaleDown
- Scale down one or more pods.
For example;
$0 -e dev scaleDown api
recycle
- Recycle one or more pods.
For example;
$0 -e dev recycle api
EOF
}
# -----------------------------------------------------------------------------------------------------------------
# Defaults:
# -----------------------------------------------------------------------------------------------------------------
resourceSuffix="${resourceSuffix:--bc}"
offlineIndexerResourceSuffix=${offlineIndexerResourceSuffix:--oli}
# -----------------------------------------------------------------------------------------------------------------
# =================================================================================================================
# Process the local command line arguments and pass everything else along.
# - The 'getopts' options string must start with ':' for this to work.
# -----------------------------------------------------------------------------------------------------------------
for arg in "$@"; do
# Remove recognized arguments from the list after processing.
shift
case "$arg" in
--hard-reset)
HARD_RESET=1
;;
*)
# If not recognized, save it for later processing ...
set -- "$@" "$arg"
;;
esac
done
while [ ${OPTIND} -le $# ]; do
if getopts :s: FLAG; then
case ${FLAG} in
# List of local options:
s ) resourceSuffix=$OPTARG ;;
# Pass unrecognized options ...
\?) pass+=" -${OPTARG}" ;;
esac
else
# Pass unrecognized arguments ...
pass+=" ${!OPTIND}"
let OPTIND++
fi
done
# Pass the unrecognized arguments along for further processing ...
shift $((OPTIND-1))
set -- "$@" $(echo -e "${pass}" | sed -e 's/^[[:space:]]*//')
# =================================================================================================================
# -----------------------------------------------------------------------------------------------------------------
# Define hook scripts:
# - These must be defined before the main settings script 'settings.sh' is loaded.
# -----------------------------------------------------------------------------------------------------------------
onRequiredOptionsExist() {
(
if [ -z "${DEPLOYMENT_ENV_NAME}" ]; then
_red='\033[0;31m'
_nc='\033[0m' # No Color
echo -e "\n${_red}You MUST specify an environment name using the '-e' flag.${_nc}"
echo -e "${_red}Assuming a default would have unwanted consequences.${_nc}\n"
return 1
else
return 0
fi
)
}
onUsesCommandLineArguments() {
(
# This script is expecting command line arguments to be passed ...
return 0
)
}
# -----------------------------------------------------------------------------------------------------------------
# Initialization:
# -----------------------------------------------------------------------------------------------------------------
# Load the project settings and functions ...
_includeFile="ocFunctions.inc"
_settingsFile="settings.sh"
if [ ! -z $(type -p ${_includeFile}) ]; then
_includeFilePath=$(type -p ${_includeFile})
export OCTOOLSBIN=$(dirname ${_includeFilePath})
if [ -f ${OCTOOLSBIN}/${_settingsFile} ]; then
. ${OCTOOLSBIN}/${_settingsFile}
fi
if [ -f ${OCTOOLSBIN}/${_includeFile} ]; then
. ${OCTOOLSBIN}/${_includeFile}
fi
else
_red='\033[0;31m'
_yellow='\033[1;33m'
_nc='\033[0m' # No Color
echo -e \\n"${_red}${_includeFile} could not be found on the path.${_nc}"
echo -e "${_yellow}Please ensure the openshift-developer-tools are installed on and registered on your path.${_nc}"
echo -e "${_yellow}https://github.com/BCDevOps/openshift-developer-tools${_nc}"
fi
# -----------------------------------------------------------------------------------------------------------------
# Functions:
# -----------------------------------------------------------------------------------------------------------------
function resetDatabase() {
_apiPodName=${1}
_dbPodName=${2}
if [ -z "${_apiPodName}" ] || [ -z "${_dbPodName}" ]; then
echoError "\resetDatabase; You MUST specify the names of the database and api pods.\n"
exit 1
fi
dropAndRecreateDatabaseWithMigrations -a ${_apiPodName}${resourceSuffix} ${_dbPodName}${resourceSuffix}
rebuildSearchIndex ${_apiPodName}
echoWarning "\nThe project's database has been reset."
}
function deleteDatabase() {
_dbPodName=${1}
if [ -z "${_dbPodName}" ]; then
echoError "\nresetDatabase; You MUST specify a pod name.\n"
exit 1
fi
printAndAskToContinue "If you contiune all of the databases on ${_dbPodName}${resourceSuffix} will be deleted. All data will be lost."
deleteAndRecreateDatabase ${_dbPodName}${resourceSuffix}
echoWarning "\nThe databases on ${_dbPodName}${resourceSuffix} have been deleted."
}
function hardReset() {
if [ ! -z ${HARD_RESET} ]; then
return 0
else
return 1
fi
}
function reset() {
(
agentPod=${1}
apiPod=${2} # aka controller
msgQueuePod=${3}
msgQueueWorkerPod=${4}
walletDbPod=${5}
backupPod=${6}
walletDbName=${7} # Example; agent_indy_cat_wallet
walletDbBackupSpec=${8} # Example; "wallet-bc:5432/${walletDbName}"
walletDbBackupFileFilter=${9} # Example; /backups/initialized-wallet
walletDbAdminPasswordKey=${10}
dbPod=${11}
targetNamespace=$(getProjectName)
if (( $# < 10 )); then
echo -e \\n"reset; Missing parameter!"\\n
exit 1
fi
# Explain what is about to happen and wait for confirmation ...
txtMsg=$(cat <<-EOF
The [${targetNamespace}] OrgBook environment will be reset using the following settings:
- agentPod: ${agentPod}${resourceSuffix}
- apiPod: ${apiPod}${resourceSuffix}
- msgQueuePod: ${msgQueuePod}${resourceSuffix}
- msgQueueWorkerPod: ${msgQueueWorkerPod}${resourceSuffix}
- walletDbPod: ${walletDbPod}${resourceSuffix}
- backupPod: ${backupPod}${resourceSuffix}
- walletDbName: ${walletDbName}
- walletDbBackupSpec: ${walletDbBackupSpec}
- walletDbBackupFileFilter: ${walletDbBackupFileFilter}
- walletDbAdminPasswordKey: ${walletDbAdminPasswordKey}
- dbPod: ${dbPod}${resourceSuffix}
EOF
)
if hardReset; then
txtMsg+=$(cat <<-EOF
\n
\033[0;31mYou have requested a Hard Reset. The following operations will be performed (ALL DATA WILL BE LOST):
\033[1;33m- The process will pause at the beginning to ensure the related BC Registries Agent reset process has started.
- The wallet will be deleted and recreated.
- The 'db' will be reset and reinitialized.
- The search indexes will be reset.
- The process will pause to ensure the related BC Registries Agent registration process has had time to complete.
- The BC Registries Agent registration will be verified.\n
EOF
)
else
txtMsg+=$(cat <<-EOF
\n
The following operations will be performed (ALL DATA WILL BE LOST):
- The process will pause at the beginning to ensure the related BC Registries Agent reset process has started.
- The wallet will be reset, by restoring initial copy of OrgBook Wallet.
- The 'db' will be reset and reinitialized.
- The search indexes will be reset.
- The process will pause to ensure the related BC Registries Agent registration process has had time to complete.
- The BC Registries Agent registration will be verified.\n
EOF
)
fi
if ! printAndWaitForYes "${txtMsg}"; then
echoWarning "Exiting ..."
exit 1
fi
# - scaledown BC Registries Agent controller and agent
printAndWait "Please ensure the reset process in the corresponding BC Registries Agent environment has been started and it has indicated it is safe to process before continuing ..."
# - scaledown OrgBook agent, api, msg-queue, and msg-queue-worker
echo "Scaling down ${agentPod}${resourceSuffix}, ${apiPod}${resourceSuffix}, ${msgQueuePod}${resourceSuffix} and ${msgQueueWorkerPod}${resourceSuffix} ..."
scaleDown -w "${apiPod}${resourceSuffix}" "${msgQueueWorkerPod}${resourceSuffix}" "${agentPod}${resourceSuffix}" "${msgQueuePod}${resourceSuffix}"
exitOnError
if hardReset; then
# - Delete Wallet Database
echoError "Deleting ${walletDbPod}${resourceSuffix} ..."
deleteDatabase "${walletDbPod}"
exitOnError
else
# - reset OrgBook Wallet Database, by restoring initial copy of OrgBook Wallet.
echo "Resetting ${walletDbPod}${resourceSuffix} ..."
if isScaledUp ${backupPod}${resourceSuffix}; then
local backupStarted=1
else
local unset backupStarted
scaleUp -w "${backupPod}${resourceSuffix}"
exitOnError
fi
runInContainer -i \
${backupPod}${resourceSuffix} \
"./backup.sh -s -a $(getSecret ${walletDbPod}${resourceSuffix} ${walletDbAdminPasswordKey}) -r ${walletDbBackupSpec} -f ${walletDbBackupFileFilter}"
exitOnError
if [ -z ${backupStarted} ]; then
# Leave the backup container in the same state we found it.
scaleDown "${backupPod}${resourceSuffix}"
exitOnError
fi
# - verify OrgBook Wallet - There should only be 4 items.
recordCounts=$(getRecordCounts "${walletDbPod}" "${walletDbName}")
numItems=$(echo "${recordCounts}" | grep items | awk '{print $5}')
if (( ${numItems} == 4 )); then
echo "Wallet 'items' count verified; ${numItems} items found."
else
echoError "Wallet 'items' count verification failed; ${numItems} items found. Please fix the issue and try again."
exit 1
fi
exitOnError
fi
# - scaleup OrgBook agent
echo "Scaling up ${agentPod}${resourceSuffix} ..."
scaleUp -w "${agentPod}${resourceSuffix}"
exitOnError
# - reset OrgBook database
echo "Resetting ${dbPod}${resourceSuffix} ..."
resetDatabase "${apiPod}" "${dbPod}"
exitOnError
# - scaleup OrgBook msg-queue and msg-queue-worker
echo "Scaling up ${apiPod}${resourceSuffix}, ${msgQueuePod}${resourceSuffix} and ${msgQueueWorkerPod}${resourceSuffix} ..."
scaleUp -w "${msgQueuePod}${resourceSuffix}" "${msgQueueWorkerPod}${resourceSuffix}"
exitOnError
printAndWait "The OrgBook reset process is complete. Please wait here for the associated BC Registries Agent instance to finish it's registration process before continuing ..."
# - verify BC Registries Agent registered with OrgBook
# - >= 3 credential_type records
# - >= 3 schema records
# - >= 1 issuer record
echo "Verifying BC Registries Agent registered with OrgBook ..."
recordCounts=$(getRecordCounts "${dbPod}")
recordCounts=$(echo "${recordCounts}" | tail -n +4)
numCredentialTypes=$(echo "${recordCounts}" | grep credential_type | awk '{print $5}')
numSchemas=$(echo "${recordCounts}" | grep schema | awk '{print $5}')
numIssuers=$(echo "${recordCounts}" | grep issuer | awk '{print $5}')
if (( ${numCredentialTypes} >= 3 )) && (( ${numSchemas} >= 3 )) && (( ${numIssuers} >= 1 )); then
echo "BC Registries Agent registration verified; credential_type:${numCredentialTypes}, schema:${numSchemas}, and issuer:${numIssuers} records found."
else
echoError "BC Registries Agent registration verification failed; credential_type:${numCredentialTypes}, schema:${numSchemas}, and issuer:${numIssuers} records found. Please fix the issue and try again."
exit 1
fi
exitOnError
# - Test posting a few credentials using the pipelines
echo "Provided BC Registries Agent has successfully registered with OrgBook you can now test things by issuing a few credentials."
)
}
function resetSearchIndex() {
_apiPodName=${1}
_solrPodName=${2}
if [ -z "${_apiPodName}" ] || [ -z "${_solrPodName}" ]; then
echo -e \\n"resetSearchIndex; Missing parameter!"\\n
exit 1
fi
deleteSearchIndex "${_solrPodName}"
recyclePods -w "${_solrPodName}${resourceSuffix}"
printAndWait "Wait for the ${_solrPodName}${resourceSuffix} pod to completely start up before continuing."
rebuildSearchIndex "${_apiPodName}"
}
function resetSolrCore() {
_apiPodName=${1}
_solrPodName=${2}
if [ -z "${_apiPodName}" ] || [ -z "${_solrPodName}" ]; then
echoError \\n"resetSolrCore; Missing parameter!"\\n
exit 1
fi
deleteSolrCore "${_solrPodName}"
recyclePods -w "${_solrPodName}${resourceSuffix}"
printAndWait "Wait for the ${_solrPodName}${resourceSuffix} pod to completely start up before continuing."
rebuildSearchIndex "${_apiPodName}"
}
function deleteSolrCore() {
_solrPodName=${1}
if [ -z "${_solrPodName}" ]; then
echoError \\n"deleteSolrCore; Missing parameter!"\\n
exit 1
fi
printAndAskToContinue "If you contiune the search-engine core on ${_solrPodName}${resourceSuffix} will be deleted."
deleteFromPod "${_solrPodName}${resourceSuffix}" "/var/solr/data/*"
exitOnError
}
function deleteSearchIndex() {
_solrPodName=${1}
if [ -z "${_solrPodName}" ]; then
echoError \\n"deleteSearchIndex; Missing parameter!"\\n
exit 1
fi
printAndAskToContinue "If you contiune the search index on ${_solrPodName}${resourceSuffix} will be deleted."
deleteFromPod "${_solrPodName}${resourceSuffix}" "/var/solr/data/credential_registry/data/index"
exitOnError
}
function rebuildSearchIndex() {
(
local OPTIND
local OPTARG
unset local offline
while getopts o FLAG; do
case $FLAG in
o ) runOffline=1 ;;
esac
done
shift $((OPTIND-1))
_indexerPodName=${1}
if [ -z "${_indexerPodName}" ]; then
echoError \\n"rebuildSearchIndex; Missing parameter!"\\n
exit 1
fi
if [ -z "${runOffline}" ]; then
_indexerPodName=${_indexerPodName}${resourceSuffix}
_msg="\nRebuilding the search index ..."
_cmd='./scripts/rebuildSearchIndex.sh 2>&1 | tee -a /tmp/rebuild-index.log'
else
_indexerPodName=${_indexerPodName}${offlineIndexerResourceSuffix}
_msg="\nRebuilding the offline search index ..."
_cmd='./scripts/rebuildSearchIndex.sh -b 1000 2>&1 | tee -a /tmp/rebuild-offline-index.log'
fi
echoWarning "${_msg}"
runInContainer "${_indexerPodName}" "${_cmd}"
exitOnError
)
}
function updateSearchIndex() {
(
local OPTIND
local OPTARG
unset local args
while getopts d:b: FLAG; do
case $FLAG in
d ) args="${args} -s ${OPTARG}" ;;
* ) args="${args} -${FLAG} ${OPTARG}" ;;
esac
done
shift $((OPTIND-1))
_apiPodName=${1:-api}
if [ -z "${_apiPodName}" ]; then
echoError \\n"updateSearchIndex; Missing parameter!"\\n
exit 1
fi
echoWarning "\nUpdating the search index ..."
args="$(echo "${args}" | sed -e 's/^[[:space:]]*//')"
runInContainer ${_apiPodName}${resourceSuffix} "./scripts/updateSearchIndex.sh ${args}"
)
}
function indexSynced() {
_quickLoadUrl=${1:-https://orgbook.gov.bc.ca/api/v2/quickload}
_apiPodName=${2}
_dbPodName=${3}
if [ -z "${_apiPodName}" ] || [ -z "${_dbPodName}" ]; then
echoError \\n"rebuildSearchIndex; Missing parameter!"\\n
exit 1
fi
indexInfo=$(curl -s ${_quickLoadUrl})
actualCount=$(echo ${indexInfo} | jq -r '.counts.actual_item_count')
indexCount=$(echo ${indexInfo} | jq -r '.credential_counts.total_indexed_items')
indexDiff=$(( ${actualCount} - ${indexCount} ))
if (( ${indexCount} == ${actualCount} )); then
synced="true"
else
percentComplete=$(awk "BEGIN {print (${indexCount}/${actualCount}*100)}")
synced="false - Difference: ${indexDiff} (${percentComplete}% complete)"
fi
echo
echo "Indexes Synced: ${synced}"
echo "Indexed Credentials: ${indexCount}"
echo "Actual Credentials: ${actualCount}"
}
function offlineIndexSynced() {
_indexerPodName=${1}
_dbPodName=${2}
if [ -z "${_indexerPodName}" ] || [ -z "${_dbPodName}" ]; then
echoError \\n"rebuildSearchIndex; Missing parameter!"\\n
exit 1
fi
recordCounts=$(getRecordCounts "${_dbPodName}" "" "${offlineIndexerResourceSuffix}")
names=$(echo "${recordCounts}" | grep -w name | awk '{print $5}')
addresses=$(echo "${recordCounts}" | grep -w address | awk '{print $5}')
credentials=$(echo "${recordCounts}" | grep -w credential | awk '{print $5}')
topics=$(echo "${recordCounts}" | grep -w topic | awk '{print $5}')
actualCount=$(( ${names} + ${addresses} + ${credentials} + ${topics} ))
indexInfo=$(runInContainer "${_indexerPodName}${offlineIndexerResourceSuffix}" \
"curl -s http://search-engine${offlineIndexerResourceSuffix}:8983/solr/credential_registry/admin/luke?wt=json&show=index&numTerms=0")
indexCount=$(echo ${indexInfo} | sed 's~\(.*"numDocs":\)\([[:digit:]]\+\).*~\2~')
indexDiff=$(( ${actualCount} - ${indexCount} ))
percentComplete=$(awk "BEGIN {print (${indexCount}/${actualCount}*100)}")
if (( ${indexCount} == ${actualCount} )); then
synced="true"
else
synced="false - Difference: ${indexDiff} (${percentComplete}% complete)"
fi
echo
echo "Indexes Synced: ${synced}"
echo "Indexed Credentials: ${indexCount}"
echo "Actual Credentials: ${actualCount}"
echo " - Names: ${names}"
echo " - Addresses: ${addresses}"
echo " - Credentials: ${credentials}"
echo " - Topics: ${topics}"
}
function deleteTopic() {
_topic_id=${1}
_apiPodName=${2:-api}
if [ -z "${_topic_id}" ] || [ -z "${_apiPodName}" ]; then
echo -e \\n"deleteTopic; Missing parameter!"\\n
exit 1
fi
printAndAskToContinue "If you continue the following topic will be permanently deleted from the OrgBook database; '${_topic_id}'."
runInContainer ${_apiPodName}${resourceSuffix} "./scripts/deleteTopic.sh ${_topic_id}"
exitOnError
}
function getAgentConnections(){
(
_podName=${1}
if [ -z "${_podName}" ]; then
echoError "\ngetAgentConnections; You MUST specify a pod name.\n"
exit 1
fi
resonse=$(runInContainer \
${_podName}${resourceSuffix} \
'curl -s -X GET -H "x-api-key:${AGENT_ADMIN_API_KEY}" http://localhost:8024/connections')
echo "$(echo ${resonse} | jq '.')"
)
}
function removeAgentConnections(){
(
_podName=${1}
if [ -z "${_podName}" ]; then
echoError "\nremoveAgentConnections; You MUST specify a pod name.\n"
exit 1
fi
resonse=$(getAgentConnections ${_podName})
connectionIds=$(echo ${resonse} | jq -r '.results[].connection_id')
echo
for connectionId in ${connectionIds}; do
# Trim whitespace
connectionId="$(echo -e "${connectionId}" | sed -e 's~^[[:space:]]*~~')"
echoWarning "Removing connection: '${connectionId}'"
runInContainer \
${_podName}${resourceSuffix} \
"curl -s -o /dev/null -w \" - %{http_code}\n\" -X POST -H \"x-api-key:\${AGENT_ADMIN_API_KEY}\" http://localhost:8024/connections/${connectionId}/remove"
done
echo
)
}
function locateBadRecord() {
(
_podName=${1}
_databaseName=${2}
_tableName=${3}
_limit=${4}
_startAtRecord=${5:-0}
_stopAtRecord=${6}
if [ -z "${_podName}" ] || [ -z "${_databaseName}" ] || [ -z "${_tableName}" ] || [ -z "${_limit}" ]; then
echoError "\nlocateBadRecord; You MUST specify a pod name, database name, table name, and limit.\n"
exit 1
fi
itemCount=$(runInContainer "${_podName}${resourceSuffix}" \
"psql -d ${_databaseName} -t -c \"select count(*) from ${_tableName};\"")
itemCount="$(echo -e "${itemCount}" | sed -e 's~^[[:space:]]*~~')"
offset=${_startAtRecord}
end=${_stopAtRecord:-${itemCount}}
recordCount=$((${end} - ${offset}))
echo
echo "Checking table for bad records:"
echo " - Table: ${_tableName}"
echo " - Database: ${_databaseName}"
echo " - Pod: ${_podName}${resourceSuffix}"
echo " - Begin: ${offset}"
echo " - End: ${end}"
echo " - Step: ${_limit}"
echo
if (( "${offset}" == "${end}" )); then
runInContainer \
${_podName}${resourceSuffix} \
"psql -d ${_databaseName} -ac \"select id from ${_tableName} order by id limit ${_limit} offset ${offset};\""
else
while (("${offset}" <= "${end}")); do
toRecord=$((${offset} + ${_limit} - 1))
if (( ${offset} == ${toRecord} )); then
printf "\rChecking record ${offset} ..."
else
printf "\rChecking records ${offset} to ${toRecord} of ${itemCount} ..."
fi
runInContainer \
${_podName}${resourceSuffix} \
"psql -d ${_databaseName} -c \"select * from ${_tableName} order by id limit ${_limit} offset ${offset}\" > /dev/null || echo -e \"\nCorrupted chunk read at offset ${offset}\n.\""
offset=$((offset + ${_limit}))
done
echo -e "\nFinished checking records."
fi
)
}
function deleteAppGroup() {
(
_appGroup=${1}
_projectName=$(getProjectName)
# offline-indexing
printAndAskToContinue "If you contiune all of the [${_appGroup}] application resources will be perminently deleted from [${_projectName}]."
oc -n ${_projectName} delete all,pvc,secret,configmap,networkpolicy -l app-group=${_appGroup}
)
}
function scaleOfflineIndexEnv() {
(
_direction=$(toLower ${1})
_indexerPodName=${2}${offlineIndexerResourceSuffix}
_searchEnginePodName=${3}${offlineIndexerResourceSuffix}
_dbPodName=${4}${offlineIndexerResourceSuffix}
if [ -z "${_direction}" ] || [ -z "${_indexerPodName}" ] || [ -z "${_searchEnginePodName}" ] || [ -z "${_dbPodName}" ]; then
echoError "\nscaleOfflineIndexEnv; You MUST specify the scaling direction, and the names of the indexer, search engine, and db pods.\n"
exit 1
fi
if [ "${_direction}" == "down" ]; then
echoWarning "\nScaling the offline indexing environment ${_direction} ..."
scaleDown -w "${_indexerPodName}" "${_searchEnginePodName}" "${_dbPodName}"
elif [ "${_direction}" == "up" ]; then
echoWarning "\nScaling the offline indexing environment ${_direction} ..."
scaleUp -w "${_dbPodName}" "${_searchEnginePodName}" "${_indexerPodName}"
else
echoError "Invalid scaling direction; ${_direction}"
fi
)
}
function getRunningProcesses() {
_podName=${1}
if [ -z "${_podName}" ]; then
echoError "\ngetRunningProcesses; You MUST specify a pod name.\n"
exit 1
fi
echo
runInContainer \
${_podName}${resourceSuffix} \
'ps -aux'
}
function indexStorageStatus() {
(
_onlineSearchEngine=${1}${resourceSuffix}
_offlineSearchEngine=${2}${offlineIndexerResourceSuffix}
_projectName=$(getProjectName)
if [ -z "${_onlineSearchEngine}" ] || [ -z "${_offlineSearchEngine}" ]; then
echoError "\nswapIndexStorage; You MUST specify the names of the online and offline search engine pods.\n"
exit 1
fi
# Fetch the volume info
onlineSearchEngineVolume=$(getVolume "${_onlineSearchEngine}" "${_projectName}")
onlineSearchEnginePvc=$(getClaimName "${onlineSearchEngineVolume}")
offlineSearchEngineVolume=$(getVolume "${_offlineSearchEngine}" "${_projectName}")
offlineSearchEnginePvc=$(getClaimName "${offlineSearchEngineVolume}")
echoWarning \\n"Container - ${_onlineSearchEngine}:"
echoWarning " - PVC: ${onlineSearchEnginePvc}"
echoWarning \\n"Container - ${_offlineSearchEngine}:"
echoWarning " - PCV: ${offlineSearchEnginePvc}"
)
}
function swapIndexStorage() {
(
_onlineSearchEngine=${1}${resourceSuffix}
_offlineSearchEngine=${2}${offlineIndexerResourceSuffix}
_projectName=$(getProjectName)
if [ -z "${_onlineSearchEngine}" ] || [ -z "${_offlineSearchEngine}" ]; then