-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.sh
executable file
·1516 lines (1313 loc) · 51.6 KB
/
lib.sh
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
set -e
# don't trap errors while using VSC debugger
[[ "$VSCODE_PID" ]] || {
set -E # If set, the ERR trap is inherited by shell functions.
trap 'error "Command $BASH_COMMAND failed with exit code $? on line $LINENO of $BASH_SOURCE."' ERR
}
# this lib is used by dockerize, mdm, tests, etc. but logging to STDOUT is problematic for platypus apps
# so need a way to check and if appropiate, defer output until lib can bootstrap the appropiate logging
included_by_mdm() {
# shellcheck disable=SC2199 # error in shellcheck? implicit array concatenation - which is desired plus = vs =~
[[ "${BASH_SOURCE[@]}" =~ /bin/mdm ]]
}
[[ "$debug" ]] && ! included_by_mdm && set -x
# iterate thru BASH_SOURCE to find this lib.sh (should work even when debugging in IDE)
bs_len=${#BASH_SOURCE[@]}
for (( index=0; index < bs_len; ((index++)) )); do
[[ "${BASH_SOURCE[$index]}" =~ /lib.sh$ ]] && {
lib_dir="$(dirname "${BASH_SOURCE[$index]}")"
# if lib_dir is relative, determine & use absolute path
[[ "$lib_dir" =~ ^\./ ]] && lib_dir="$PWD/${lib_dir#./}"
break
}
done
###
#
# start constants
#
###
# in general, use $lib_dir/.. to reference the running version's path; use $mdm_path only when the central install dir is intended
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[1;33m'
no_color='\033[0m'
recommended_vm_cpu=4
recommended_vm_mem_mb=4096
recommended_vm_swap_mb=4096
recommended_vm_disk_mb=64000
bytes_in_mb=1048576
detached_project_name="MDM-lite"
hosts_file_line_marker="# added by MDM"
host_docker_internal="172.17.0.1"
mdm_path="$HOME/.mdm" # must be set in lib.sh and launcher b/c each can be used independently
launched_apps_dir="$mdm_path/launched-apps"
certs_dir="$mdm_path/certs"
hosts_backup_dir="$mdm_path/hosts.bak"
see_docs_msg="See docs @ https://github.com/PMET-public/mdm"
# if not already defined by individual app
if [[ ! "$mdm_config_file" ]] ; then
mdm_config_filename=".mdm_config.sh"
mdm_config_file="$mdm_path/$mdm_config_filename"
fi
menu_log_file="$mdm_path/menu.log"
handler_log_file="$mdm_path/handler.log"
dockerize_log_file="$mdm_path/dockerize.log"
docker_settings_file="$HOME/Library/Group Containers/group.com.docker/settings.json"
advanced_mode_flag_file="$mdm_path/advanced-mode-on"
mkcert_installed_flag_file="$mdm_path/.mkcert-installed"
rel_app_config_file="app/.docker/config.env"
mdm_ver_file="$mdm_path/latest-sem-ver"
magento_cloud_cmd="$HOME/.magento-cloud/bin/magento-cloud"
docker_install_link="https://hub.docker.com/editions/community/docker-ce-desktop-mac/"
repo_url="https://github.com/PMET-public/mdm"
mdm_version="${lib_dir#$mdm_path/}" && mdm_version="${mdm_version%/bin}" && [[ "$mdm_version" =~ ^[0-9.]*$ ]] || mdm_version="0.0.0-dev"
# a mnemonic for storing certain calculated vals. however b/c this lib needs bash 3 compatibility initially,
# no functionality requiring the mdm_store can be run until after initialization logic
declare -A mdm_store 2> /dev/null || :
# shellcheck source=../.mdm_config.sh
[[ -f "$mdm_config_file" ]] && source "$mdm_config_file"
###
#
# end constants
#
###
###
#
# start test functions
#
###
has_uncleared_jobs_statuses() {
[[ -d "$apps_mdm_jobs_dir" && "$(find "$apps_mdm_jobs_dir" -type f -not -name "*.cleared" -print -quit)" ]]
}
is_magento_cloud_cli_installed() {
[[ -f "$magento_cloud_cmd" ]]
}
is_magento_cloud_cli_logged_in() {
local status
"$magento_cloud_cmd" > /dev/null 2>&1 || status=$?
[[ "$status" -eq 0 ]]
}
is_platypus_installed() {
[[ -x "/usr/local/share/platypus/ScriptExec" ]]
}
is_mkcert_installed() {
[[ -n "$(which mkcert)" ]]
}
is_tmate_installed() {
[[ -n "$(which tmate)" ]]
}
is_web_tunnel_configured() {
[[ "$mdm_tunnel_ssh_url" && "$mdm_tunnel_domain" && "$mdm_tunnel_pk_url" ]]
}
are_additional_tools_installed() {
is_magento_cloud_cli_installed || return 1
is_mac && {
if is_docker_compatible; then
: # placeholder
fi
is_platypus_installed || return 1
}
is_mkcert_installed || return 1
is_tmate_installed || return 1
}
can_optimize_vm_cpus() {
cpus_for_vm="$(grep '"cpus"' "$docker_settings_file" | perl -pe 's/.*: (\d+),/$1/')"
cpus_available="$(sysctl -n hw.logicalcpu)"
[[ cpus_for_vm -lt recommended_vm_cpu && cpus_available -gt recommended_vm_cpu ]]
}
can_optimize_vm_mem() {
memory_for_vm="$(grep '"memoryMiB"' "$docker_settings_file" | perl -pe 's/.*: (\d+),/$1/')"
memory_available="$(( $(sysctl -n hw.memsize) / bytes_in_mb ))"
[[ memory_for_vm -lt recommended_vm_mem_mb && memory_available -ge 8192 ]]
}
can_optimize_vm_swap() {
swap_for_vm="$(grep '"swapMiB"' "$docker_settings_file" | perl -pe 's/.*: (\d+),/$1/')"
[[ swap_for_vm -lt recommended_vm_swap_mb ]]
}
can_optimize_vm_disk() {
disk_for_vm="$(grep '"diskSizeMiB"' "$docker_settings_file" | perl -pe 's/.*: (\d+),/$1/')"
[[ disk_for_vm -lt recommended_vm_disk_mb ]]
}
is_mac() {
# [[ "$(uname)" = "Darwin" ]]
# matching against uname is relatively slow compared to checking for safari and the users dir
# and if this funct is called 20x to render the menu, it makes a diff
[[ -d /Applications/Safari.app && -d /Users ]]
}
# override default linux docker host ip with mac dns alias host.docker.internal
is_mac && host_docker_internal="host.docker.internal"
# if the core_utils are installed (should always be true after initial install), use the GNU tools
# there may be some inconsistencies prior to install.
# if they are significant, hopefully testing finds them and will be accounted for
if is_mac && [[ -d "$(brew --prefix)/Cellar/coreutils" ]]; then
# use homebrew's core utils
stat_cmd="gstat"
sort_cmd="gsort"
date_cmd="gdate"
else
stat_cmd="stat"
sort_cmd="sort"
date_cmd="date"
fi
is_CI() {
[[ "$GITHUB_WORKSPACE" ]]
}
# this exists for CI testing of some functionality even when docker is n/a (e.g. github ci with a mac)
is_docker_compatible() {
! ( is_mac && is_CI )
}
is_docker_installed() {
which docker > /dev/null 2>&1
}
is_docker_initialized_on_mac() {
[[ -f "$docker_settings_file" ]]
}
are_docker_settings_optimized() {
return 0 # accept defaults for now
local md5 md5_file
md5="$(md5sum "$docker_settings_file" | sed 's/ .*//')"
md5_file="$mdm_path/.md5-of-optimized-docker-settings-${md5}"
[[ -f "$md5_file" ]] && return 0
if can_optimize_vm_cpus || can_optimize_vm_mem || can_optimize_vm_swap || can_optimize_vm_disk; then
return 1
fi
touch "$md5_file"
return 0
}
is_docker_running() {
docker ps > /dev/null 2>&1
}
is_docker_running_cached() {
[[ "${mdm_store["docker_is_running"]}" ]] && return "${mdm_store["docker_is_running"]}" # already calculated
mdm_store["docker_is_running"]=0
mdm_store["formatted_docker_ps_output"]="$(docker ps -a --format "{{.Names}} {{.Status}} [labels]: {{.Labels}}" 2> /dev/null)" ||
mdm_store["docker_is_running"]="$?"
return "${mdm_store["docker_is_running"]}"
}
is_detached() {
[[ ! -d "$apps_resources_dir/app" ]]
}
is_magento_app_installed_cached() {
is_detached && return 1
[[ "${mdm_store["app_is_installed"]}" ]] && return "${mdm_store["app_is_installed"]}" # already calculated
mdm_store["app_is_installed"]=0
echo "${mdm_store["formatted_docker_ps_output"]}" | grep -q "^${COMPOSE_PROJECT_NAME}_db_1 " || mdm_store["app_is_installed"]="$?"
return "${mdm_store["app_is_installed"]}"
}
is_magento_app_running_cached() {
is_detached && return 1 # n/a
[[ "${mdm_store["magento_app_is_running"]}" ]] && return "${mdm_store["magento_app_is_running"]}" # already calculated
local service services
services="$(get_docker_compose_runtime_services)"
mdm_store["magento_app_is_running"]=0 # assume up and will return 0 unless an expected up service is not found
for service in $services; do
# if a service sets to 1, func will have non-zero exit, so false (app is not fully running)
echo "${mdm_store["formatted_docker_ps_output"]}" | grep -q "^${COMPOSE_PROJECT_NAME}_${service}_1 Up" ||
{ mdm_store["magento_app_is_running"]="$?"; break; }
done
return "${mdm_store["magento_app_is_running"]}"
}
is_pwa_module_installed() {
[[ -f "$apps_resources_dir/app/composer.json" ]] && grep -q "PMET-public/module-storystore" "$apps_resources_dir/app/composer.json"
}
are_required_ports_free() {
{ ! nc -z 127.0.0.1 80 && ! nc -z 127.0.0.1 443; } > /dev/null 2>&1
return
}
is_nginx_rev_proxy_running() {
echo "${mdm_store["formatted_docker_ps_output"]}" | grep -q ' Up .*mdm-nginx-rev-proxy'
}
is_network_state_ok() {
# check once and store result in var
[[ -n "${mdm_store["network_state_is_ok"]}" ]] || {
are_required_ports_free || is_nginx_rev_proxy_running
mdm_store["network_state_is_ok"]="$?"
}
return "${mdm_store["network_state_is_ok"]}"
}
are_other_magento_apps_running() {
echo "${mdm_store["formatted_docker_ps_output"]}" |
grep "_db_1 " |
grep -v "^${COMPOSE_PROJECT_NAME}_db_1 " |
grep -v '_db_1 Exited' |
grep -q -v '_db_1 Created'
return "$?"
}
invoked_mdm_without_args() {
# it can be difficult to determine whether mdm was called w/o args to display the menu or invoke a selected menu item
# bash5 on mac and bash4 on linux report BASH_ARGC (he number of parameters in each frame of the current bash
# execution call stack) differently. also the vsc debugger wraps the call in other args (changing BASH_ARGC)
# so modify this carefully.
# for debugging, bash vscode debugger changes normal invocation, so check for a special env var $vsc_debugger_arg
if [[ "$vsc_debugger_arg" == "n/a" ]]; then
return 0 # invoked WITHOUT args
elif [[ -n "$vsc_debugger_arg" ]]; then
mdm_first_arg="$vsc_debugger_arg"
return 1 # invoked WITH args
elif [[ "${BASH_ARGV[-1]}" =~ /bin/mdm$ ]]; then
return 0 # invoked WITHOUT args
else
mdm_first_arg="${BASH_ARGV[-1]}"
return 1 # invoked WITH args
fi
}
# need way to distinguish being sourced for specific app or sourced for some other script (e.g. dockerize script)
lib_sourced_for_specific_bundled_app() {
# if a specific apps_resources_dir is already set in the env, then lib was sourced for a specific app
if [[ "$apps_resources_dir" ]]; then
# check that the dir was properly specified
[[ ! -d "$apps_resources_dir" ]] && error "$apps_resources_dir does not exist."
# it exists - return success
return 0
fi
# else is the sourcing process a specific app instance?
# DON'T use ${BASH_SOURCE[-1]} b/c invalid syntax before bash upgraded
local oldest_parent_path="${BASH_SOURCE[${#BASH_SOURCE[@]}-1]}"
if which realpath > /dev/null 2>&1; then
oldest_parent_path="$(realpath "$oldest_parent_path")"
else
return 1 # TODO this is not strictly correct but this func doesn't matter before realpath is installed?
fi
[[ "$oldest_parent_path" =~ \.app\/Contents\/ ]] &&
apps_resources_dir="${oldest_parent_path/\/Contents\/*/\/Contents\/Resources}" &&
export apps_resources_dir
}
lookup_latest_remote_sem_ver() {
curl -sL "$repo_url/releases" | \
perl -ne 'BEGIN{undef $/;} /expanded_assets\/([\d.]+)/ and print $1'
}
is_update_available() {
# check for a new version once a day (86400 secs)
local latest_sem_ver more_recent_of_two
if [[ -f "$mdm_ver_file" && "$(( $(date +"%s") - $("$stat_cmd" -c%Z "$mdm_ver_file") ))" -lt 86400 ]]; then
latest_sem_ver="$(<"$mdm_ver_file")"
[[ "$mdm_version" == "$latest_sem_ver" ]] && return 1
# verify latest is more recent using sort -V
more_recent_of_two="$(printf "%s\n%s" "$mdm_version" "$latest_sem_ver" | "$sort_cmd" -V | tail -1)"
[[ "$latest_sem_ver" == "$more_recent_of_two" ]] && return 0
else
# get info in the background to prevent latency in menu rendering
lookup_latest_remote_sem_ver > "$mdm_ver_file" 2>/dev/null &
fi
return 1
}
is_adobe_system() {
[[ -d /Applications/Adobe\ Hub.app ]]
}
is_advanced_mode() {
[[ -f "$advanced_mode_flag_file" ]]
}
is_valid_hostname() {
# do not allow names to start with "."
# only allow [a-zA-Z0-9] for last char
# curl exit code 3 = bad/illegal url
[[ ! "$1" =~ ^\. ]] && [[ "$1" =~ [a-zA-Z0-9]$ ]] && {
# just want to know if name is valid so ignore output and timeout quickly
# exit code 3 would be almost instant
curl -sI --max-time 2 "http://$1" > /dev/null || [[ "$?" -ne 3 ]]
}
}
is_valid_git_url() {
[[ "$1" =~ http.*\.git ]] || [[ "$1" =~ git.*\.git ]]
}
is_existing_cloud_env() {
[[ "$env_is_existing_cloud" ]]
}
is_valid_github_web_url() {
local url="$1"
[[ "$url" =~ https?://.*github\.com/.+/.+ ]]
}
get_branch_from_github_web_url() {
local url="$1"
echo "$url" | perl -ne '/.*\/(tree|blob|commit)\/([^\/]+)/ and print $2'
}
normalize_github_web_url() {
local url="$1"
echo "$url" | perl -pe 's/(.*?github.com\/[^\/]+\/[^\/]+)\/(tree|blob|commit)\/.*/$1.git/'
}
is_valid_mc_env_url() {
local url="$1"
# 2nd case accounts for master env (not always present)
[[ "$url" =~ https?://.*magento\.cloud/projects/.*/environments/ || "$url" =~ https?://.*magento\.cloud/projects/[^/]+/?$ ]]
}
is_valid_mc_site_url() {
local url="$1"
url="$(normalize_url_without_path_or_credentials "$url")"
[[ "$url" =~ https?://.*\.magentosite\.cloud$ ]]
}
is_active_project_env() {
local project="$1" env="$2" e
ensure_user_logged_into_mc_cli
envs="$("$magento_cloud_cmd" environments -p "$project" --pipe --no-inactive 2> /dev/null)"
for e in $envs; do
[[ "$e" = "$env" ]] && return 0
done
return 1
}
is_hostname_resolving_to_local() {
local curl_output
curl_output="$(curl --max-time 0.5 -vI "$1" 2>&1 >/dev/null | grep Trying)"
[[ "$curl_output" =~ ::1 || "$curl_output" =~ 127\.0\.0\.1 ]]
}
is_interactive_terminal() {
[[ $- == *i* ]]
}
launched_from_mac_menu_cached() {
[[ "${mdm_store["launched_from_mac_menu_cached"]}" ]] && return "${mdm_store["launched_from_mac_menu_cached"]}" # already calculated
[[ "$(ps -p $PPID -o comm=)" =~ Contents/MacOS/ ]]
mdm_store["launched_from_mac_menu_cached"]="$?"
return "${mdm_store["launched_from_mac_menu_cached"]}"
}
is_running_as_sudo() {
env | grep -q 'SUDO_USER='
}
is_mkcert_CA_installed() {
# if user install mkcert CA out of band, this will be inaccurate
# but using the menu item to install/uninstall again will bring it back in sync
[[ -f "$mkcert_installed_flag_file" ]]
}
is_string_valid_composer_credentials() {
local str="$1" status=0 md5 md5_file
md5="$(echo "$str" | md5sum | sed 's/ .*//')"
md5_file="$mdm_path/.md5-of-passed-composer-cred-${md5}"
# for max menu rendering speed, check for md5 of prev passed credentials
[[ -f "$md5_file" ]] && return 0
# verify the credentials have a user & pass for repo.magento.com
# and a github oauth token or a github user & pass if using basic
echo "$str" | jq -r -e -c '
([."http-basic"."repo.magento.com"["username","password"]]
| map(strings)
| length == 2)
and
([."github-oauth"."github.com", ."http-basic"."github.com"["username","password"]]
| map(strings)
| length > 0)' > /dev/null 2>&1 || status="$?"
if [[ "$status" -eq 0 ]]; then
touch "$md5_file"
fi
return "$status"
}
has_valid_composer_credentials_cached() {
[[ "${mdm_store["composer_credentials_are_valid"]}" ]] && return "${mdm_store["composer_credentials_are_valid"]}" # already calculated
# check the env var
[[ "$COMPOSER_AUTH" ]] &&
is_string_valid_composer_credentials "$COMPOSER_AUTH" &&
mdm_store["composer_credentials_are_valid"]=0 &&
return "${mdm_store["composer_credentials_are_valid"]}"
# check the user's file
[[ -f "$HOME/.composer/auth.json" ]] &&
COMPOSER_AUTH="$(<"$HOME/.composer/auth.json")" &&
is_string_valid_composer_credentials "$COMPOSER_AUTH" &&
mdm_store["composer_credentials_are_valid"]=0 &&
export COMPOSER_AUTH &&
return "${mdm_store["composer_credentials_are_valid"]}"
mdm_store["composer_credentials_are_valid"]=1
return "${mdm_store["composer_credentials_are_valid"]}"
}
# has_magento_cloud_token() {
# [[ "$MAGENTO_CLOUD_CLI_TOKEN" ]]
# }
# is_ssh_agent_running() {
# [[ "$SSH_AUTH_SOCK" =~ ^/ ]]
# }
# has_magento_cloud_ssh_key() {
# local status key_list
# key_list="$("$magento-cloud_cmd" ssh-key:list --no-header --format csv || return 1)"
# [[ "$key_list" =~ ",/" ]]
# }
###
#
# end test functions
#
###
###
#
# start util functions
#
###
trim() {
echo "$@" | xargs
}
error() {
printf "\n%b%s%b\n\n" "$red" "[$(date +"%FT%TZ")] Error: $*" "$no_color" 1>&2 && exit 1
}
warning() {
printf "%b%s%b" "$yellow" "$*" "$no_color"
}
warning_w_newlines() {
warning "
$*
"
}
msg() {
printf "%b%s%b" "$green" "$*" "$no_color"
}
msg_w_newlines() {
msg "
$*
"
}
msg_w_timestamp() {
msg "[$(date +"%FT%TZ")] $*"
}
convert_secs_to_hms() {
h="$(($1/3600))"
m="$((($1%3600)/60))"
s="$(($1%60))"
[[ "$h" != 0 ]] && printf "%dh %dm %ds" "$h" "$m" "$s" && return 0
[[ "$m" != 0 ]] && printf "%dm %ds" "$m" "$s" && return 0
printf "%ds" "$s" && return 0
}
seconds_since() {
echo "$(( $(date +"%s") - $1 ))"
}
show_success_msg_plus_duration() {
msg_w_newlines "Completed successfully in ⌚️$(convert_secs_to_hms "$(seconds_since "$1")")"
}
reverse_array() {
declare -n input_array="$1" output_array="$2"
local index
for index in "${input_array[@]}"; do
output_array=("$index" "${output_array[@]}")
done
}
confirm_or_exit() {
warning "
ARE YOU SURE?! (y/n)
"
read -r -p ''
[[ "$REPLY" =~ ^[Yy]$ ]] || {
msg_w_newlines "Exiting unchanged." && exit
}
}
prompt_user_for_token() {
REPLY=""
while [[ ! "$REPLY" =~ ^[0-9a-p_]+$ ]]; do
printf "Typically 'ghp_' followed by numbers and letters. e.g. ghp_9662d057e4e52b1b236fa237a232349841e60b54e" >&2
read -r -p '> '
REPLY="$(trim $REPLY)"
done
echo "$REPLY"
}
# look in env and fallback to expected home path
get_github_token_from_composer_auth() {
# prefer COMPOSER_AUTH over auth.json
[[ -n "$COMPOSER_AUTH" ]] &&
echo "$COMPOSER_AUTH" | jq -r -e -c '([."github-oauth"."github.com", ."http-basic"."github.com"["username","password"]] | map(strings) | last )' &&
return
[[ -f "$HOME/.composer/auth.json" ]] &&
jq -r -e -c '([."github-oauth"."github.com", ."http-basic"."github.com"["username","password"]] | map(strings) | last )' "$HOME/.composer/auth.json" &&
return
return 1
}
# mc env means from the magento cloud projects page
get_project_from_mc_env_url() {
local url="$1"
echo "$url" | perl -ne '/.*?\/projects\/([^\/]+)/ and print $1'
}
get_env_from_mc_env_url() {
local url="$1"
echo "$url" | perl -ne '/.*?\/environments\/([^\/]+)/ and print $1'
}
# mc site means from the magento cloud site itself
# mc site domains always follow this pattern
# https://transformedenvidtoconformtosubdomainrules-randomstring-projectid.region.magentosite.cloud
get_project_from_mc_site_url() {
local url="$1"
# get the chars after the last dash before the 1st '.'
normalize_url_without_path_or_credentials "$url" | perl -ne 's/.*-([^-\.]+)\..*/\1/ and print'
}
get_active_env_from_mc_env_url() {
local url="$1" project envs env env_url
project="$(get_project_from_mc_site_url "$url")"
url="$(normalize_url_without_path_or_credentials "$url")"
envs="$("$magento_cloud_cmd" environments -p "$project" --pipe --no-inactive 2> /dev/null)"
for env in $envs; do
env_url="$("$magento_cloud_cmd" url -p "$project" -e "$env" --pipe 2> /dev/null | perl -ne 's/^(https.*)\//\1/ and print')"
if [[ "$url" == "$env_url" ]]; then
echo "$env"
return 0
fi
done
return 1
}
ensure_user_logged_into_mc_cli() {
if ! is_magento_cloud_cli_logged_in; then
warning_w_newlines "Not logged in. Attempting login ..."
"$magento_cloud_cmd" login
fi
}
###
#
# end util functions
#
###
###
#
# start network functions
#
###
get_docker_host_ip() {
[[ "$docker_host_ip" ]] && return 0 # already defined
docker_host_ip="$host_docker_internal"
is_mac && docker_host_ip="$(docker run --rm alpine getent hosts host.docker.internal | perl -pe 's/\s.*//')"
printf '%s' "$docker_host_ip"
}
print_containers_hosts_file_entry() {
printf '%s' "$(get_docker_host_ip) $(get_hostname_for_this_app) $hosts_file_line_marker"
}
print_local_hosts_file_entry() {
local hostname="$1"
printf '%s' "127.0.0.1 $hostname $hosts_file_line_marker"
}
get_hostname_for_this_app() {
[[ -f "$apps_resources_dir/$rel_app_config_file" ]] &&
perl -ne 's/^APP_HOSTNAME=\s*(.*)\s*/$1/ and print' "$apps_resources_dir/$rel_app_config_file" ||
error "Host not found"
}
get_prev_hostname_for_this_app() {
[[ -f "$apps_resources_dir/$rel_app_config_file" ]] &&
perl -ne 's/^PREV_APP_HOSTNAME=\s*(.*)\s*/$1/ and print' "$apps_resources_dir/$rel_app_config_file" ||
error "Host not found"
}
set_hostname_for_this_app() {
local new_hostname="$1" cur_hostname prev_hostname
is_valid_hostname "$new_hostname" || error "Invalid hostname"
if [[ -f "$apps_resources_dir/$rel_app_config_file" ]]; then
cur_hostname="$(perl -ne '/^(APP_HOSTNAME=\s*)(.*)(\s*)/ and print $2' "$apps_resources_dir/$rel_app_config_file")"
prev_hostname="$(perl -ne '/^(PREV_APP_HOSTNAME=\s*)(.*)(\s*)/ and print $2' "$apps_resources_dir/$rel_app_config_file")"
[[ "$cur_hostname" != "$new_hostname" ]] &&
perl -i -pe "s/^(APP_HOSTNAME=\s*)(.*)(\s*)/\${1}$new_hostname\${3}/" "$apps_resources_dir/$rel_app_config_file"
# update prev hostname
if [[ "$cur_hostname" != "$prev_hostname" ]]; then
if [[ is_web_tunnel_configured && ! "$cur_hostname" =~ "$mdm_tunnel_domain"$ ]]; then
: # unless prev hostname is a tunnel domain (to prevent reverting to a tunnel domain)
else
perl -i -pe "s/^(PREV_APP_HOSTNAME=\s*)(.*)(\s*)/\${1}$cur_hostname\${3}/" "$apps_resources_dir/$rel_app_config_file"
fi
fi
return 0
else
error "Host not found"
fi
}
stop_ssh_tunnel() {
is_web_tunnel_configured || return 0
local hostname
hostname="$(get_hostname_for_this_app)"
port="${hostname/.*}"
if pkill -f "ssh.*$port:.*$mdm_tunnel_ssh_url"; then
msg_w_newlines "Succcessfully stopped 1 or more remote web sessions."
else
msg_w_newlines "No active remote web sessions."
fi
}
update_hostname() {
local new_hostname="$1" cur_hostname prev_hostname
cur_hostname="$(get_hostname_for_this_app)"
prev_hostname="$(get_prev_hostname_for_this_app)"
if [[ "$cur_hostname" != "$new_hostname" ]]; then
set_hostname_for_this_app "$new_hostname"
run_as_bash_cmds_in_app "$(get_magento_cmds_to_update_hostname_to $new_hostname)"
warm_cache > /dev/null 2>&1 &
# if is_web_tunnel_configured; then
# # reload the proxy if the new hostname is not a tunnel domain b/c it will be a public url
# # UNLESS reverting from a tunnel domain to the previous hostname b/c proxy settings will not have changed
# if [[ ! "$new_hostname" =~ "$mdm_tunnel_domain"$ ]]; then
# if [[ "$cur_hostname" =~ "$mdm_tunnel_domain"$ && "$new_hostname" = "$prev_hostname" ]]; then
# : # do nothing b/c reverting from tunnel domain that did not change proxy settings
# else
# reload_rev_proxy
# fi
# fi
# else
# reload_rev_proxy
# fi
reload_rev_proxy # always reload after change
open_app
fi
}
get_magento_cmds_to_update_hostname_to() {
local hostname="$1"
echo "
bin/magento app:config:import
bin/magento config:set web/unsecure/base_url https://$hostname/
bin/magento config:set web/secure/base_url https://$hostname/
bin/magento cache:flush
"
}
get_project_and_env_from_mc_url() {
local url="$1" project env
project="$(get_project_from_mc_env_url "$url")"
[[ "$project" ]] || error "$url not recognized as a valid Magento Cloud url from the Magento Cloud projects page
(ex. https://<region>.magento.cloud/projects/<projectid>/environments/<envid>)."
env="$(get_env_from_mc_env_url "$url")"
[[ "$env" ]] || env="master"
echo "$project $env"
}
get_pwa_hostname() {
[[ "$mdm_domain" ]] && echo "pwa.$mdm_domain" || echo "pwa"
}
get_pwa_prev_hostname() {
[[ "$mdm_domain" ]] && echo "pwa-prev.$mdm_domain" || echo "pwa-prev"
}
# get_MAGENTO_CLOUD_vars_as_json() {
# perl -MMIME::Base64 -ne '/(MAGENTO_CLOUD_.*?)=(.*)/ and print "\"$1\":".decode_base64($2).",\n"' \
# "$apps_resources_dir/app/.docker/config.env" | perl -0777 -pe 's/^/{/;s/.$/}/;'
# }
set_MAGENTO_CLOUD_vars_json_to_env() {
jq -r 'to_entries|map("\(.key)=\(.value|tostring|@base64)")|.[]'
}
export_pwa_hostnames() {
PWA_HOSTNAME="$(get_pwa_hostname)"
PWA_PREV_HOSTNAME="$(get_pwa_prev_hostname)"
export PWA_HOSTNAME PWA_PREV_HOSTNAME
}
find_bridged_docker_networks() {
docker network ls -q --filter 'driver=bridge' --filter 'name=_default'
}
network_has_running_web_service() {
[[ "$(docker ps --filter "network=$1" \
--filter "label=com.docker.compose.service=web" --format "{{.Ports}}")" =~ \-\>80 ]]
}
find_varnish_port_by_network() {
docker ps -a --filter "network=$1" \
--filter "label=com.docker.compose.service=varnish" --format "{{.Ports}}" | \
sed 's/.*://;s/-.*//'
}
find_running_app_hostname_by_network() {
local cid resources_dir output count
cid="$(docker ps --filter "network=$1" --filter "label=com.docker.compose.service=fpm" --format "{{.ID}}")"
[[ "$cid" ]] || return 0
# obscure errors can occur if related services are not fully up, so wait for expected output
count=0
output="$(docker exec "$cid" bash -c 'bin/magento config:show "web/secure/base_url"' || :)"
while [[ ! "$output" =~ https://* ]]; do
sleep 5
output="$(docker exec "$cid" bash -c 'bin/magento config:show "web/secure/base_url"' || :)"
((++count))
if [[ $count -gt 5 ]]; then
exit 1
fi
done
echo "$output" | perl -pe 's#^.*//(.*)/#$1#'
}
find_mdm_hostnames() {
local hostnames hostname networks network
hostnames="$(get_pwa_hostname) $(get_pwa_prev_hostname)"
networks="$(find_bridged_docker_networks)"
for network in $networks; do
hostname="$(find_running_app_hostname_by_network "$network")"
[[ -n "$hostname" ]] && hostnames+=" $hostname"
done
echo "$hostnames"
}
find_hostnames_not_resolving_to_local() {
local hostname hostnames="$*" hostnames_not_resolving_to_local=""
for hostname in $hostnames; do
! is_hostname_resolving_to_local "$hostname" && hostnames_not_resolving_to_local+=" $hostname"
done
echo "$hostnames_not_resolving_to_local"
}
backup_hosts() {
[[ -d "$hosts_backup_dir" ]] || {
warning "Creating hosts back up dir - should only need to do this if MDM install was skipped (e.g. testing/development)"
mkdir -p "$hosts_backup_dir"
}
cp /etc/hosts "$hosts_backup_dir/hosts.$(date "+%s")"
}
add_hostnames_to_hosts_file() {
[[ "$*" ]] || return 0
local hostnames="$*" hostname lines="" error_msg="Could not update hosts files." tmp_hosts
for hostname in $hostnames; do
lines+="$(print_local_hosts_file_entry "$hostname")"$'\n'
done
warning_w_newlines "Password may be required to modify /etc/hosts!"
tmp_hosts=$(mktemp)
cat /etc/hosts <(echo "$lines") > "$tmp_hosts"
backup_hosts
sudo_run_bash_cmds "
mv \"$tmp_hosts\" /etc/hosts
chmod 644 /etc/hosts
" || error "$error_msg"
}
# for certificate functions, a wildcard domain parameter should be passed as "*.example.com" or ".example.com"
# if a domain name consisting of 2 parts is the full, desired hostname, then it should only
# contain those 2 parts e.g. example.com
#
# N.B. most browsers will not accept a wildcard certificate for "*.example.com" as valid for "example.com",
# but a certificate can explicitly designate both "*.example.com" and "example.com" as valid
# in the common names section of a cert
normalize_domain_if_wildcard() {
echo "${1/#\*/}"
}
has_valid_wildcard_domain() {
[[ "$1" =~ .+\..+ ]] # need at least 2 part domain name, and thus a "."
}
wildcard_domain_for_hostname() {
has_valid_wildcard_domain "$1" &&
echo "$1" | perl -pe '/.+\..+/ and s/.*?\./*./'
}
does_cert_and_key_exist_for_domain() {
local domain cert_dir
domain="$(normalize_domain_if_wildcard "$1")"
cert_dir="$certs_dir/$domain"
[[ -d "$cert_dir" && -f "$cert_dir/fullchain1.pem" && -f "$cert_dir/privkey1.pem" ]]
}
read_cert_for_domain() {
local domain cert_dir
domain="$(normalize_domain_if_wildcard "$1")"
cert_dir="$certs_dir/$domain"
openssl x509 -text -noout -in "$cert_dir/fullchain1.pem" || error "Could not read cert for $domain"
}
get_cert_utc_end_date_for_domain() {
local end_date
end_date="$(read_cert_for_domain "$1" | perl -ne 's/\s*not after :\s*//i and print')"
[[ "$end_date" =~ GMT ]] || error "Could not retrieve valid end date for '$1'. Value was '$end_date'."
"$date_cmd" --utc --date="$end_date" +"%Y-%m-%d %H:%M:%S"
}
is_cert_current_for_domain() {
local end_date
end_date="$(get_cert_utc_end_date_for_domain "$1")"
[[ "$end_date" =~ [0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2} ]] || error "Could not retrieve valid end date for '$1'. Value was '$end_date'."
[[ "$("$date_cmd" --utc +"%Y-%m-%d %H:%M:%S")" < "$end_date" ]]
}
is_cert_for_domain_expiring_soon() {
local end_date
end_date="$(get_cert_utc_end_date_for_domain "$1")"
[[ "$end_date" && "$("$date_cmd" --utc --date "+7 days" +"%Y-%m-%d %H:%M:%S")" > "$end_date" ]]
}
# .domain.com/ must contain a wildcard cert for "*.domain.com"
# my.domain.com/ must contain a cert for "my.domain.com" or a cert for "*.domain.com"
does_cert_follow_convention() {
local domain cert
domain="$(normalize_domain_if_wildcard "$1")"
cert="$(read_cert_for_domain "$domain")"
if [[ "$domain" =~ ^\. ]]; then
[[ "$cert" =~ DNS:\*$domain ]] && return 0
else
wildcard_domain="$(wildcard_domain_for_hostname "$1")"
[[ "$cert" =~ DNS:.*$domain || "$cert" =~ DNS:\*$wildcard_domain ]] && return 0
fi
return 1
}
is_new_cert_required_for_domain() {
! { does_cert_and_key_exist_for_domain "$1" && is_cert_current_for_domain "$1" &&
does_cert_follow_convention "$1" && ! is_cert_for_domain_expiring_soon "$1"; }
}
# accept any public or private github.com or raw.githubusercontent.com url
# but for consistency retrieve from github api
# where token (if needed) will be passed as header and not url get param
get_github_file_contents() {
local url="$1" org repo ref path token
read -r org repo ref path <<<"$(
echo "$url" | perl -pe 's/
^https?:\/\/[^\/]+\/
(?<org>[^\/]+)\/
(?<repo>[^\/]+)\/
(blob\/)?
(?<ref>[^\/]+)\/
(?<path>[^\?\$]+)
.*
/$+{org} $+{repo} $+{ref} $+{path}/x'
)"
token="$(get_github_token_from_composer_auth)"
url="https://api.github.com/repos/$org/$repo/contents/$path?ref=${ref:-master}"
[[ "$token" ]] && token=("-H" "Authorization: token $token")
curl --fail -sL -H 'Accept: application/vnd.github.v3.raw' "${token[@]}" "$url"
}
get_wildcard_cert_and_key_for_mdm_domain() {
is_new_cert_required_for_domain ".$mdm_domain" || return 0
cert_dir="$certs_dir/.$mdm_domain"
mkdir -p "$cert_dir"
get_github_file_contents "$mdm_domain_fullchain_gh_url" > "$cert_dir/fullchain1.pem"
get_github_file_contents "$mdm_domain_privkey_gh_url" > "$cert_dir/privkey1.pem"
}
mkcert_for_domain() {
local domain="$1" cert_dir="$certs_dir/$1"
is_valid_hostname "$domain" || error "Invalid name '$domain'"
mkdir -p "$cert_dir"
mkcert -cert-file "$cert_dir/fullchain1.pem" -key-file "$cert_dir/privkey1.pem" "$domain"
}
cp_wildcard_mdm_domain_cert_and_key_for_subdomain() {
local subdomain="$1" num_parts_mdm_domain num_parts_subdomain
# verify immediate subdomain (not subdomain of subdomain)
num_parts_mdm_domain="$(echo "$mdm_domain" | tr -cd "." | wc -c)" # count dots
num_parts_subdomain="$(echo "$subdomain" | tr -cd "." | wc -c)" # count dots
[[ "$subdomain" =~ "$mdm_domain"$ && "$num_parts_subdomain" -eq "$(( "$num_parts_mdm_domain" + 1 ))" ]] || return 1
is_new_cert_required_for_domain "$subdomain" || return 0 # still valid
is_new_cert_required_for_domain ".$mdm_domain" && get_wildcard_cert_and_key_for_mdm_domain
rsync -az "$certs_dir/.$mdm_domain/" "$certs_dir/$subdomain/"
}
remove_credentials_from_url() {
local url="$1"
# remove any username and password
echo "$url" | perl -pe 's/\/\/[^\@]+:[^\@]+\@/\/\//'
}
strip_path_from_url() {
local url="$1"
# remove the first fwd slash not immediately preceeded by a fwd slash or : and everything after
echo "$url" | perl -pe 's/([^:\/])\/.*/\1/'
}
normalize_url_without_path_or_credentials() {
local url="$1"
url="$(strip_path_from_url "$url")"
remove_credentials_from_url "$url"
}
###
#