-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathac
executable file
·2386 lines (2219 loc) · 101 KB
/
ac
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
# ==============================================================================
# Copyright (c) IBM Corporation 2024
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# ==============================================================================
# Global Vars and helpers
# ==============================================================================
# TODO: - write stats to the venv such as date created, updated, etc
# Trap custom exit value to exit child processes.
trap "exit 100" TERM
export PARENT_PID=$$
VENV_HOME_MANAGED=${PWD%/venv}/venv
# ------------------------------------------------------------------------------
# This method will terminate the entire script by killing the parent process.
# When exiting from within a function, use exit_all' not 'exit n' else the parent
# proccess will not exit.
# ------------------------------------------------------------------------------
function exit_all(){
kill -s TERM $PARENT_PID
}
# Normalize the version from 3.10.2 to 3010002000
normalize_version() {
echo "$@" | awk -F. '{ printf("%d%03d%03d%03d\n", $1,$2,$3,$4); }';
}
# Method determines the lastest (highest number) version venv that is managed by ./ac
latest_venv(){
dir_version_latest="0"
test_for_managed_venv=`ls -d "$VENV_HOME_MANAGED"/venv-[0-9].[0-9]* 2>/dev/null`
if [ ! -z "$test_for_managed_venv" ]; then
for dir_version in `ls -d "$VENV_HOME_MANAGED"/venv-[0-9].[0-9]* | cut -d"-" -f2`; do
if [ $(normalize_version $dir_version) -ge $(normalize_version $dir_version_latest) ]; then
dir_version_latest=$dir_version
fi
done
echo "${VENV_HOME_MANAGED}"/"venv-"$dir_version_latest
fi
}
# Method will take a venv name such as venv-2.16 and validate that it exists, otherwise error and exit
validate_venv(){
option_venv=$1
if [[ "$option_venv" =~ "latest" ]]; then
test_for_managed_venv=`ls -d "$VENV_HOME_MANAGED"/venv-latest* 2>/dev/null`
if [[ "$test_for_managed_venv" =~ "latest" ]]; then
dir_version_latest=$option_venv
fi
elif [[ "$option_venv" =~ "doc" ]]; then
test_for_managed_venv=`ls -d "$VENV_HOME_MANAGED"/venv-doc* 2>/dev/null`
if [[ "$test_for_managed_venv" =~ "doc" ]]; then
dir_version_latest=$option_venv
fi
else
for dir_version in `ls -d "$VENV_HOME_MANAGED"/venv-[0-9].[0-9]* | rev | cut -d"/" -f1| rev`; do
if [ $dir_version == $option_venv ]; then
dir_version_latest=$dir_version
fi
done
fi
if [ ! -z "$dir_version_latest" ]; then
echo "${VENV_HOME_MANAGED}"/$dir_version_latest
else
message_error "Unable to validate managed venv option $option_venv, exiting."
exit
fi
}
# TODO: Wrap this with an exist check so that you can override the venv from the shell
VENV=`latest_venv`
if [ ! -z "$VENV" ]; then
VENV_BIN=$VENV/bin
VENV_BASENAME=`basename $VENV`
fi
CURRENT_DIR=`pwd`
cd $CURRENT_DIR
CURR_DIR=`pwd`
file=""
verbose=0
GH_BRANCH=`git branch |grep "*" | cut -d" " -f2`
DIV="-----------------------------------------------------------------------"
# if '0' then Docker is up, else '1' then docker is not up
DOCKER_INFO=`podman info> /dev/null 2>&1;echo $?`
# Vars used to aid in terminal message colors
RED=$'\e[1;31m'
GRN=$'\e[1;32m'
YEL=$'\e[1;33m'
BLU=$'\e[1;34m'
MAG=$'\e[1;35m'
CYN=$'\e[1;36m'
ENDC=$'\e[0m'
# ==============================================================================
# Arg parsing helpers
# ==============================================================================
# ------------------------------------------------------------------------------
# This method generates an INFO message with green color and dividers. This
# message will always be sent to STDERR so that STDOUT can be reserved for
# return codes.. Use this method for messages to the console.
# ------------------------------------------------------------------------------
message(){
printf '%s\n' "" >&2
printf '%s\n' "${GRN}${DIV}${ENDC}" >&2
printf '%s\n' "${GRN}INFO:${ENDC} ${1}" >&2
printf '%s\n' "${GRN}${DIV}${ENDC}" >&2
}
# ------------------------------------------------------------------------------
# This method generates an ERROR message with red color. This message
# will always be sent to STDERR so that STDOUT can be reserved for return codes.
# Use this method for error messages to the console.
# ------------------------------------------------------------------------------
message_error(){
printf '%s\n' "" >&2
printf '%s\n' "${RED}${DIV}${RED}" >&2
printf '%s\n' "${RED}ERROR:${ENDC} ${1}" >&2
printf '%s\n' "${RED}${DIV}${ENDC}" >&2
exit_all
}
# ------------------------------------------------------------------------------
# This method generates an WARN message with yellow color. This message
# will always be sent to STDERR so that STDOUT can be reserved for return codes.
# Use this method for error messages to the console.
# ------------------------------------------------------------------------------
message_warn(){
printf '%s\n' "" >&2
printf '%s\n' "${YEL}${DIV}${YEL}" >&2
printf '%s\n' "${YEL}WARN:${ENDC} ${1}" >&2
printf '%s\n' "${YEL}${DIV}${YEL}" >&2
}
# ------------------------------------------------------------------------------
# This method ehcecks to see the VENV variable has been set, if not it produces
# an error message with instructions on how to correct it.
# ------------------------------------------------------------------------------
ensure_managed_venv_exists(){
if [ -z "$VENV" ]; then
message_error "Option $1 requires that a managed virtual environment be configured.
Run $0 -venv-setup to create managed viritual environments.
For additional optons, use $0 --help."
exit_all
fi
}
terminate() {
printf '%s\n' "$1" >&2
exit 1
}
# ------------------------------------------------------------------------------
# Generate simple formated but incomplete help
# ------------------------------------------------------------------------------
# usage_simple(){
# script="$0"
# base_name_script=`basename "$script"`
# grep '^##' "$script" | sed -e 's/^##//' -e "s/_PROG_/$base_name_script/" 1>&2
# }
# ------------------------------------------------------------------------------
# This method auto generates help based on the comments found in this script.
# ----------------+-------------------------------------------------------------
# Comment style | Description
# ----------------+-------------------------------------------------------------
# '#->command:' | `#->` followed by a keyword is the help command displayed
# ----------------+-------------------------------------------------------------
# '## ' | The first found pattern after a help command will be the
# | help command description. Subsequent such patterns will be
# | right justified and considered options or descriptions
# ----------------+-------------------------------------------------------------
# '# ' | This pattern is ignored and considered script comments
# ----------------+-------------------------------------------------------------
# ------------------------------------------------------------------------------
#->help:
## Print help message (-h, -? produce short version, otherwise verbose)
## Usage: ac [-h, -?, --help]
## Example:
## $ ac --help
help(){
if [ "$1" = "verbose" ]; then
awk '{\
if (($0 ~ /^#->[a-zA-Z\-\_0-9.]+:/)) { \
helpCommand = substr($0, 4, index($0, ":")); \
helpMessage ="";\
} else if ($0 ~ /^##/) { \
if (helpMessage) { \
helpMessage =" "substr($0, 3); \
} else { \
helpMessage = substr($0, 3); \
} \
if (helpCommand && helpMessage) {\
printf "\033[36m%-16s\033[0m %s\n", helpCommand, helpMessage; \
helpCommand =""; \
commandContext=" Supports format: <option> <value> and <option>=<value>";\
print commandContext;\
} else {\
print helpMessage
}
}
}' $0
else
awk '{\
if (($0 ~ /^#->[a-zA-Z\-\_0-9.]+:/)) { \
helpCommand = substr($0, 4, index($0, ":")); \
helpMessage ="";\
} else if ($0 ~ /^##[[:space:]][[:space:]]*\$[[:space:]]ac/) { \
helpMessage = substr($0, 3); \
if (helpCommand && helpMessage) {\
printf "\033[36m%-16s\033[0m %s\n", helpCommand, helpMessage; \
helpCommand =""; \
} else {\
helpMessage=" "substr($0, 3); \
print helpMessage
}
} else if ($0 ~ /^##[[:space:]][[:space:]]*\$[[:space:]]*--/) { \
helpMessage = substr($0, 3); \
if (helpCommand && helpMessage) {\
printf "\033[36m%-16s\033[0m %s\n", helpCommand, helpMessage; \
helpCommand =""; \
} else {\
helpMessage=" "substr($0, 6); \
print helpMessage
}
}
}' $0
fi
}
# The case stmt sees it this way:
# --foo abc ---> $1 = foo, $2 = abc
# --foo=abc ---> $1 = --foo=abc
option_processor(){
opt=$1
arg="$2"
if [ "$arg" ]; then
echo "$arg"
elif [ "$opt" ]; then
# Split up to "=" and set the remainder
value=${opt#*=}
# If the value is not the same as the option ($1),then assign it .
if [ "$opt" != "$value" ]; then
echo $value
else
# Don't echo, will return from the function, send to error msg to stderr
ERROR_MSG="${RED}ERROR${ENDC}: option $option requires a non-empty argument."
printf '%s\n' "$ERROR_MSG" >&2
echo "exit 1"
fi
fi
}
# If option_processor echo's an exit , the sanitize will execute it else it will
# just be a echo, might be worth seeing if this can just be called or embedded
# into the option_processor to simplify the calls
option_sanitize(){
option_value=$1
$option_value 2> /dev/null
}
# ==============================================================================
# Commands
# ==============================================================================
# ------------------------------------------------------------------------------
# Run a bandit static scan on the plugins directory on the hosts local branch
# where the 'ac' is running.
# ------------------------------------------------------------------------------
#->ac-bandit:
## Run bandit static scan on the plugins directory on the local GH branch.
## Usage: ac --ac-bandit [--level <str>]
## Options:
## level (optional):
## - choose from 'l', 'll', 'lll'
## - Defaults to, 'l'
## - l, all low, medium, high severities
## - ll, all medium, high severities
## - lllm all high severities
## Example:
## $ ac --ac-bandit --level ll
## $ ac --ac-bandit
ac_bandit(){
option_level=$1
if [ ! "$option_level" ]; then
option_level="l"
fi
message "Running Bandit scan with level '$option_level'"
. $VENV_BIN/activate && python3 -m bandit -r plugins/* -"${option_level}"
}
# ------------------------------------------------------------------------------
# Build and install a collection of the local branch checked out where 'ac' is
# running. Installation is set the --name option, local host or venv.
# ------------------------------------------------------------------------------
#->ac-build:
## Build and install collection of the local GH branch, select installation path.
## Usage: ac --ac-build [--name <str>]
## Options:
## name (optional)
## - The location to install, by default it will install the collection
## in the latest venv. If value 'local' is set, it will
## install the collection on the host.
## Example:
## $ ac --ac-build --name local
## $ ac --ac-build --name venv-2.14
## $ ac --ac-build
ac_build(){
option_name=$1
galaxy_path="" # Empty installs to host default
git_init=""
base_name=""
# There must be a parent git directory in non-default collection installations, see issues
# https://github.com/ansible/ansible/issues/68499#issuecomment-873660057
# https://github.com/ansible/ansible/issues/63032
# Work around is to perform a git init . and create an empty repo where the collection is installed,
# does not seem to to be an issue with the host installation thus far, only venv's. This is required
# for ansible-test sanity tests to run, else sanity fails with 'WARNING: All targets skipped.'
if [ "$option_name" ]; then
if [ "$option_name" == "local" ];then
base_name="$HOME/.ansible/collections/ansible_collections"
else
VENV=`validate_venv $option_name`
galaxy_path="-p ${VENV}"
base_name=`basename $VENV`
git_init="git init ${VENV}/ansible_collections --quiet"
fi
else
galaxy_path="-p ${VENV}"
base_name=`basename $VENV`
git_init="git init ${VENV}/ansible_collections --quiet"
fi
message "Creating 'ibm_zos_core' collection from the local GH branch: '$GH_BRANCH'."
. $VENV_BIN/activate && rm -rf ibm-ibm_zos_core-*.tar.gz && \
$VENV_BIN/ansible-galaxy collection build
message "Installing 'ibm.ibm_zos_core' collection to ${base_name}."
. $VENV_BIN/activate && $VENV_BIN/ansible-galaxy collection install -f ibm-ibm_zos_core-* ${galaxy_path} && ${git_init}
}
# ------------------------------------------------------------------------------
# Build, install and validate the collection with 'galaxy importer'. This operation
# is performed on the host, not on a venv.
# ------------------------------------------------------------------------------
#->ac-galaxy-importer:
## Build current branch and run galaxy importer on the collection.
## Usage: ac --ac-galaxy-importer
## Example:
## $ ac --ac-galaxy-importer
ac_galaxy_importer(){
# Extract the pytest ignore errors from `$VENV/galaxy-importer.cfg` and trim all white space
FLAKE8_IGNORE=`cat $VENV/galaxy-importer.cfg| grep -i "ignore = " | cut -d "=" -f 2 | tr -d ' '`
# Path to the installed constants.py
eval "ORIGINAL_CONSTANTS_DIR=(${VENV}/lib/*/site-packages/galaxy_importer/)"
# Backup up the constants.py file before editing it.
cp $ORIGINAL_CONSTANTS_DIR/constants.py /tmp/
# Update constants.py with our choice of FLAKE8_IGNORE entry
sed "s/E402/$FLAKE8_IGNORE/" ${ORIGINAL_CONSTANTS_DIR}/constants.py > ${ORIGINAL_CONSTANTS_DIR}/constants.py.tmp
mv ${ORIGINAL_CONSTANTS_DIR}/constants.py.tmp ${ORIGINAL_CONSTANTS_DIR}/constants.py
message "Creating 'ibm_zos_core' collection with branch: '$GH_BRANCH'."
. $VENV_BIN/activate && collection_name=$($VENV_BIN/ansible-galaxy collection build --force | awk -F/ '{print $NF}') && ls -la $collection_name
message "Running Galaxy Importer for collection $collection_name"
. $VENV_BIN/activate && export GALAXY_IMPORTER_CONFIG=$VENV/galaxy-importer.cfg; python3 -m galaxy_importer.main $collection_name
mv /tmp/constants.py ${ORIGINAL_CONSTANTS_DIR}/constants.py
}
# ------------------------------------------------------------------------------
# Perform changelog operations on th elocal branch.
# TODO: Add the ability to create a summary.
# ------------------------------------------------------------------------------
#->ac-changelog:
## Perform antsibull-changelog operations such as lint, release and generate, etc
## Usage: ac --ac-changelog [--command <str>]
## Options:
## command (optional)
## - choose from 'generate', 'lint', 'lint-changelog-yaml', 'init', 'release',
## - generate, TODO: Needs doc
## - lint, (default) check changelog fragments for syntax errors
## - lint-changelog-yaml, check syntax of changelogs/changelog.yaml file
## - init, set up changelog infrastructure for collection, or an other project
## - release, add a new release to the change metadata
## Example:
## $ ac --ac-changelog --command lint
## $ ac --ac-changelog --command release
## $ ac --ac-changelog
ac_changelog(){
option_command=$1
message "Performing changelog operation '$option_command'"
. $VENV_BIN/activate && antsibull-changelog "${option_command}"
}
# ------------------------------------------------------------------------------
# Install an ibm_zos_core collection from repository
# ------------------------------------------------------------------------------
#->ac-install:
## Install collection 'ibm_zos_core' from galaxy. If no version is specified,
## the latest GA level in repository will be installed.
## Usage: ac --ac-install [--version <int>] [--name <str>]
## Options:
## version (optional)
## - The collection version
## name (optional)
## - The location to install, valid locations are venv names or 'local'.
## - Default, latest venv, eg venv-2.xx
## - If value 'local', collection is installed on the host.
## Example:
## $ ac --ac-install --version 1.5.0-beta.1 --name venv-2.16
## $ ac --ac-install --version 1.5.0-beta.1 --name local
## $ ac --ac-install --version 1.5.0-beta.1
## $ ac --ac-install
ac_install(){
option_version=$1
option_name=$2
galaxy_path="" # Empty installs to host default
git_init=""
base_name=""
# There must be a parent git directory in non-default collection installations, see issues
# https://github.com/ansible/ansible/issues/68499#issuecomment-873660057
# https://github.com/ansible/ansible/issues/63032
# Work around is to perform a git init . and create an empty repo where the collection is installed,
# does not seem to to be an issue with the host installation thus far, only venv's. This is required
# for ansible-test sanity tests to run, else sanity fails with 'WARNING: All targets skipped.'
if [ "$option_name" ]; then
if [ "$option_name" == "local" ];then
base_name="$HOME/.ansible/collections/ansible_collections"
else
VENV=`validate_venv $option_name`
galaxy_path="-p ${VENV}"
base_name=`basename $VENV`
git_init="git init ${VENV}/ansible_collections --quiet"
fi
else
galaxy_path="-p ${VENV}"
base_name=`basename $VENV`
git_init="git init ${VENV}/ansible_collections --quiet"
fi
if [ "$option_version" ];then
message "Installing 'ibm.ibm_zos_core' collection version=${option_version} into ${base_name}."
. $VENV_BIN/activate && $VENV_BIN/ansible-galaxy collection install -fc ibm.ibm_zos_core:${option_version} ${galaxy_path} && ${git_init}
else
message "Installing 'ibm.ibm_zos_core' lastet GA version into ${VENV}."
. $VENV_BIN/activate && $VENV_BIN/ansible-galaxy collection install -fc ibm.ibm_zos_core ${galaxy_path} && ${git_init}
fi
}
# ------------------------------------------------------------------------------
# Generate module documentation, this will crate the *.rst in the local repo
# ------------------------------------------------------------------------------
#->ac-module-doc:
## Generate module doc with options. Default behavior is to clean and then generate
## module doc in RST. All options are appended makefile targets clean and module-doc.
## If clean is seleceted, only clean is executed.
## Usage: ac --ac-module-doc [--command <str,str>]
## Options:
## command (optional)
## - Space or comma delimited make file targets to append to clean and module-doc.
## - If clean is selected it will be the only makefile target run.
## - choose from target 'role', 'html', 'clean'.
## - role, generate role documenation.
## - html, generate HTML and launch it in a local browser for viewing.
## - clean, remove staging directories used to generate HTML.
## - options are case sensitive.
## Example:
## $ ac --ac-module-doc --command html,role
## $ ac --ac-module-doc --command clean
## $ ac --ac-module-doc
ac_module_doc(){
option_command=$1
cmd="make clean; make module-doc;"
# Invoke shell script helpers to set variables if host is not null
if [ ! -z "${option_command}" ]; then
count_delim=`echo $option_command | awk -F "," '{print NF-1}'`
if [ $count_delim -gt 0 ]; then
# Parse comma delimited string, clean is already in the base command so ignored.
for command in $(echo $option_command | sed "s/,/ /g"); do
if [ "$command" == "role" ];then
cmd="${cmd} make role-doc;"
elif [ "$command" == "html" ];then
cmd="${cmd} make html; make view-html;"
fi
done
else
if [ "$command" == "role" ];then
cmd="${cmd} make role-doc;"
elif [ "$command" == "html" ];then
cmd="${cmd} make html; make view-html;"
elif [ "$command" == "clean" ];then
cmd="make clean;"
fi
fi
fi
# Must install collection on the control node to gen doc because doc needs
# the collections doc fragments
ac_build "local"
# Force the venv-doc virtual environment designed for doc generation.
VENV_BIN="$VENV_HOME_MANAGED"/venv-doc/bin
message "Generating module documentation for branch '$GH_BRANCH'."
. $VENV_BIN/activate && export ANSIBLE_LIBRARY="$HOME/.ansible/collections/ansible_collections/ibm/ibm_zos_core/plugins/modules"; cd docs/ ; eval ${cmd}
}
# ------------------------------------------------------------------------------
# Run ansible-lint on the local GH Branch
# ------------------------------------------------------------------------------
#->ac-lint:
## Run ansible-lint on the local GH branch with the given profile.
## Usage: ac --ac-lint [--profile <str>]
## Options:
## profile (optional)
## - Ansible lint profile to use.
## - Defaults to 'production' if not given.
## - Possible values are 'min', 'basic', 'shared', 'safety', 'moderate', 'production'.
## Example:
## $ ac --ac-lint
## $ ac --ac-lint --profile moderate
ac_ansible_lint(){
profile=$1
message "Linting with ansible-lint on branch: '$GH_BRANCH'."
. $VENV_BIN/activate && $VENV_BIN/ansible-lint --profile $profile
}
# ------------------------------------------------------------------------------
# Run the sanity test using docker given python version else default to venv
# TODO: investigate validate:
# https://docs.ansible.com/ansible/latest/dev_guide/testing/sanity/validate-modules.html#extending-validate-modules
# ------------------------------------------------------------------------------
#->ac-sanity:
## Run ansible-test in docker if the docker engine is running, else run them in
## a managed virtual environment using the installed python version.
## Usage: ac --ac-sanity [--version <float>] [--name <str>]
## Options:
## version (optional)
## - Only applies when a container is running.
## - choose from '2.6', '2.7', '3.5', '3.6', '3.7', '3.8', '3.9', ....
## - No version selection will run all available python versions in the container.
## name (optional)
## - The location of collection, valid locations are venv names or 'local'.
## - Default, latest venv, eg venv-2.xx
## - If value 'local', collection is installed on the host.
## Example:
## $ ac --ac-sanity --version 3.10 --name local
## $ ac --ac-sanity --version 3.10
## $ ac --ac-sanity
ac_sanity(){
option_version=$1
option_name=$2
collection_path=""
base_name=""
if [ "$option_name" ]; then
if [ "$option_name" == "local" ];then
collection_path="$HOME/.ansible/collections/ansible_collections/ibm/ibm_zos_core/"
# Must install collect to have parity with ansible-test
ac_build $option_name
else
VENV=`validate_venv $option_name`
collection_path="${VENV}/ansible_collections/ibm/ibm_zos_core/"
base_name=`basename $VENV`
# Must install collect to have parity with ansible-test
ac_build $option_name
fi
else
collection_path="${VENV}/ansible_collections/ibm/ibm_zos_core/"
base_name=`basename $VENV`
# Must install collect to have parity with ansible-test
ac_build
fi
if [ "${DOCKER_INFO}" == "0" ]; then
if [ "${option_version}" ]; then
message "Running ansible-test in a container with python ${option_version} and collection ${base_name}."
. $VENV_BIN/activate && export ANSIBLE_TEST_PREFER_PODMAN=1 && cd ${collection_path} && \
${VENV_BIN}/ansible-test sanity --python ${option_version} --requirements --docker default && \
cd ${CURR_DIR};
else
message "Running ansible-test in a container all python versions and collection ${base_name}."
. $VENV_BIN/activate && export ANSIBLE_TEST_PREFER_PODMAN=1 && cd ${collection_path} && \
${VENV_BIN}/ansible-test sanity --requirements --docker default && \
cd ${CURR_DIR};
fi
else
if [ "${option_version}" ]; then
message "Docker engine is not running, version ${option_version} will be ignored."
fi
. $VENV_BIN/activate && VENV_PY_VER=`python3 --version | cut -d" " -f2 | cut -d"." -f1,2`
message "Running ansible-test with managed python virtual environment: ${VENV}."
. $VENV_BIN/activate && cd ${collection_path} && \
${VENV_BIN}/ansible-test sanity --python ${VENV_PY_VER} --requirements && \
cd ${CURR_DIR};
fi
}
# ------------------------------------------------------------------------------
# Run collection test cases using the pytest -ziventory fixture. Setting --name,
# instructs the 'ac' tool which managed venv to use to run pytest. The collection
# being tested must reside in the same managed venv, there is no option today to
# choose the location of the collection and the named venv. For that we would need
# a --location option, thus locally installed collections are not supported, all
# collections must be installed into one of the managed venvs.
# TODO: If --location is to be supported, the ANSIBLE_LIBRARY and ANSIBLE_CONFIG , would need to point to localhost
# ------------------------------------------------------------------------------
#->ac-test:
## Build local branch, install and run tests in the managed venv.
## Usage: ac --ac-test [--host <str>] [--python <float>] [--zoau <float>] [--file <str>] [--debug] [--name <str>] [--verbosity <str>] [--mark <str>] [--stop] [--volumes <str>] [--user <str>]
## Options:
## host (optional)
## - z/OS managed node to run test cases, no selection defaults to
## a host registerd to your the user id (`whoami`).
## python (optional)
## - IBM enterprise python version, choices are 3.8, 3.9, 3.10, 3.11, 3.12
## no selection defauls to 3.8.
## zoau (optional)
## - ZOAU to use in testing, choices are 1.0.3, 1.1.1, 1.2.0, 1.2.1,
## no selection defaults to 1.1.1 .
## file (optional)
## - the absoulte path to a test suite to run, no selection
## defaults to all test suite running.
## test (optional)
## - a test case to run found in 'file', no selection
## defaults to all tests in file running.
## debug (optional)
## - enable debug for pytest (-s), choices are true and false
## name (optional)
## - The managed venv to use to run the test instance.
## - Default, venv with largest value, eg venv-2.17
## - A name must be a managed venv, lochost installatiosn are not supported.
## verbosity (optional)
## - Whether to run pytest in verbose mode.
## - Possible values are v, vv, vvv or vvvv.
## - Will also print debug information from this script.
## mark (optional)
## - Pytest mark to use to filter tests.
## - Only runs tests with the given mark.
## stop (optional)
## - Whether to stop running tests after a failure is found.
## volumes (optional)
## - String containing volumes that will be used during testing.
## - Each volume should be separated by a space.
## user (optional)
## - User that will be used to run the tests.
## - This will only change the user that appears in the test config.
## - This won't create the user nor copy the SSH keys required to the host.
## Example:
## $ ac --ac-test --host ec01150a --python 3.11 --zoau 1.3.1\
## $ --file tests/functional/modules/test_zos_operator_func.py --test test_zos_operator_positive_path --debug
## $ ac --ac-test --host ec33012a --python 3.11 --zoau 1.3.1 --file tests/functional/modules/test_zos_operator_func.py --debug
## $ ac --ac-test --host ec33012a --python 3.11 --zoau 1.3.1 --file tests/functional/modules/test_zos_operator_func.py --user usrt001
## $ ac --ac-test --host ec01130a --python 3.11 --zoau 1.3.1 --file invalid/test/returns/rc/of/4/to/stderr 2>>/dev/null
## $ ac --ac-test --host ec01130a --python 3.11 --zoau 1.3.1 --file tests/functional/modules/test_zos_tso_command_func.py --name venv-2.17 --volumes "000000 222222"
## $ ac --ac-test --file tests/functional/modules/test_zos_operator_func.py --debug--verbosity vvv --stop
## $ ac --ac-test --file tests/functional/modules/test_zos_copy_func.py --mark template
## $ ac --ac-test
ac_test(){
host=$1
python=$2
zoau=$3
file=$4
test=$5
debug=$6
option_name=$7
verbosity=$8
mark=$9
stop=${10}
volumes=${11}
user=${12}
# Check that a collection is installed in the named venv or default venv.
ac_version $option_name
# If a --name has been passed, update the the VENV var path appropriately.
if [ "$option_name" ]; then
VENV=`validate_venv $option_name`
VENV_BIN=$VENV/bin
VENV_BASENAME=`basename $VENV`
fi
if [ "$file" ] && [ "$test" ]; then
file="${file} -k ${test}"
fi
if [ "$mark" ]; then
mark="-m ${mark}"
fi
if [ "$debug" ]; then
debug="-s"
fi
if [ "$verbosity" ]; then
verbosity="-${verbosity}"
fi
if [ "$stop" ]; then
stop="-x"
fi
skip=tests/functional/modules/test_module_security.py
# Create the config always overwriting existing
${VENV}/./venv.sh --config ${host} ${python} ${zoau} ${VENV} "${volumes}" ${user}
# Check configuration was created in venv/config.yml, else error and exit
if test ! -e ${VENV}/config.yml; then
message_error "Unable to find test configration in ${VENV}/config.yml."
fi
if [ "$verbosity" ]; then
echo "### Start config output."
cat ${VENV}/config.yml
echo "### End config output."
fi
# Populating file with every test file available.
if [ -z "${file}" ]; then
for test_file in `ls tests/functional/modules/*.py`; do
if [ "${test_file}" != "$skip" ]; then
file="${file} ${test_file}"
fi
done
fi
# Define the needed env vars that pytest needs to locate modules and plugins.
export ANSIBLE_LIBRARY=${VENV}/ansible_collections/ibm/ibm_zos_core/plugins/modules
export ANSIBLE_ACTION_PLUGINS=${VENV}/ansible_collections/ibm/ibm_zos_core/plugins/action
export ANSIBLE_MODULE_UTILS=${VENV}/ansible_collections/ibm/ibm_zos_core/plugins/module_utils
export ANSIBLE_CONFIG=${VENV}/ansible.cfg
pytest_cmd="${VENV_BIN}/pytest ${verbosity} ${debug} ${stop} --host-pattern=all --zinventory=${VENV}/config.yml ${file} ${mark} --ignore="${skip}""
if [ "$verbosity" ]; then
echo "### Start pytest preliminary output."
echo "pytest command constructed: ${pytest_cmd}"
echo "### End pytest preliminary output."
fi
. ${VENV_BIN}/activate;${pytest_cmd} >&2 ; echo $? >&1
# Clean up the collections folder after running the tests, temporary work around.
rm -rf collections/ansible_collections
}
# ------------------------------------------------------------------------------
# Run concurrent executor for identified tests cases. Setting --name,
# instructs the 'ac' tool which managed venv to use to run pytest. The collection
# being tested must reside in the same managed venv, there is no option today to
# choose the location of the collection and the named venv. For that we would need
# a --location option, thus locally installed collections are not supported, all
# collections must be installed into one of the managed venvs.
# TODO: If --location is to be supported, the ANSIBLE_LIBRARY and ANSIBLE_CONFIG , would need to point to localhost
# ------------------------------------------------------------------------------
#->test-concurrent:
## Run the conncurrent executor (CE) that can drive test cases to a cluster of hosts.
## Usage: ac --test-concurrent [--host <str, str>] [--user <str>] --python <str> [--zoau <str>] [--pythonpath <str>]
## [--volumes <str, str>] [--file <str, str>] [--skip <str, str>] [--itr <int>] [--replay <int>]
## [--timeout <int>] [--throttle <bool>] [--workers <int>] [--maxjob <int>] [--maxnode <int>]
## [--bal <int>] [--verbose <bool>] [--verbosity <int>] [--debug] [--extra <str>] [--name <str>]
## Options:
## host (optional):
## - Space or comma delimited managed nodes to use.
## - Entering one more managed nodes overrries the auto detection feature which
## will build a cluster of managed nodes to run on.
## - Only the host prefix is needed, e.g. 'ec01150a'
## user (optional):
## - Ansible user authorized to run tests on the managed node.
## python (requred):
## - IBM enterprise python version, e.g 3.10', '3.11', '3.12'
## zoau (optional):
## - ZOAU version to use. e.g. 1.2.5, 1.3.0, 1.3.1
## pythonpath (optional):
## - The absolute path to where the ZOAU python module is located.
## - The can be for the precopiled binary, wheels or setup tools installation home.
## - Default is to use the precompiled binary (until we establish wheel locations)
## volumes (optional):
## - The volumes to use with the test cases, overrides the auto volume assignment.
## - Defaults to, "222222,000000"
## file (optional):
## - Space or comma delimited test suites that should be included in the result.
## - A test suite is a collection of test cases in a file that starts with
## 'test' and ends in '.py'.
## - Do not include the absolute path, this is automatically deteremined.
## - For all functional tests, use the `functional/*` notation.
## - For all unit tests, use the `unit/*` notation for directories.
## - Default is all functional and unit tests.
## - A directory of test cases is such that it contains test suites.
## skip (optional):
## - Space or comma delimited test suites that should not be included
## in the result.
## - Supply only the test suite name, the tooling will prepend the
## necessay path.
## - Default is to skip 'test_module_security.py', this can not be removed but
## it can be replaced with another test or tests.
## itr (optional):
## - Configure the number of iterations to rerun failed test cases.
## - Each iteration will run only the prior iterations failed tests until
## either their are no more iterations left or there are no more failed
## tests to run.
## - Default is 50 so that full regression can succeed.
## replay (optional):
## - Instruct the CE to replay the entire command with all provided options
## for only the failed tests.
## - The idea behind this is if you did not set enough iterations, rather than
## start all over you could instruce CE to rerun with the failed test cases
## it has recorded, giving a higher probabity there will be success.
## - Each replay will run only the prior iterations failed tests until
## either their are no more replay's left or there are no more failed
## tests to run.
## - Default is 5, so that full regression can succeed.
## timeout (optional):
## - The maximum time in seconds a job should wait for completion.
## - When set, a subprocess call executing pytest will waith this amount of time.
## - Default is 300 seconds (5 minutes).
## throttle (optional):
## - Configuration throttles the managed node test execution such that a node will
## only run one one job at at time, no matter the threads.
## - If disabled (False), concurrency will increase, but has the risk of encountering
## increased ansible connnection failures, while this could result in shorter regression
## it could also result in longer times because of failed connections.
## - Default is True, managed nodes will only execute one test at time.
## workers (optional):
## - The numerical multiplier used to increase the number of worker threads.
## - This value is multiplied by the number of managed nodes to calculate the
## number of threads to start the CE thread pool with.
## - Default is 1, so CE will have 1 thread for each managed node.
## - Any value greater than 1, will automatically disable throttle.
## - At this time, setting more threads could result in connection failures, see throttle.
## maxjob (optional):
## - The maximum number of times a test case can fail before its removed from the job queue.
## - This is helpful in indentifying a bug, possibly in a test case or module.
## - Setting this value sets an upper bound limit on how many times a test case is permitted
## to fail.
## - Default is 10, such that the test will no longer be permitted to execute after 10.
## maxnode (optional):
## - The maximum number tests that can fail on a managed node before the node is removed
## from the node queue.
## - This helpful in identifying a problematic managed node such that it may require an IPL.
## - Default is 30, such that the managede will no longer be permitted to run tests after 30.
## - After the default is exceeded, the managde node is set to OFFLINE status.
## bal (optional):
## - The maximum number of times a test is perimtted to fail on a given managed node
## before be assigned to a new managed node.
## - This is helpful in identifying test cases that may be experiencing managned node latency,
## this allows CE to assign the test case to a new less active managed node such that it might
## a higher chance of success.
## - Default is 10, after a test case fails 10 times on a node it will be assigned to a new managed node.
## verbose (optional):
## - Instruct CE to run with verbose stdout to the console.
## - This will instruct CE to write all statistics to stdout.
## - Default is 'False', no verbosity to the console.
## - Statistics are always written to directory '/tmp' as text and HTML files.
## - Files in '/tmp' will follow this name pattern, eg conncurrent-excutor-log-<replay>-<status>-<date>.<ext>
## - examples are:
## - concurrent-executor-log-00:21:24.txt
## - concurrent-executor-log-replay-1-failure-00:21:24.html
## - concurrent-executor-tests-replay-1-success-00:21:24.html
## verbosity (optional):
## - Configure pytest verbosity level.
## - Integer value corresponds to verbosity level.
## - 1 = -v, 2 = -vv, 3 = -vvv, 4 = -vvvv
## - Default is 0, no verbosity.
## debug (optional):
## - Instruct Pytest whether to capture any output (stdout/stderr), equivalent of pytest -s.
## - Default False
## extra (optional):
## - Extra commands passed to subprocess before pytest execution
## - This is helpful if you want to expose insert an enviroment var or even
## run a shell command before exeucting, e.g 'cd ../..'
## returncode (optional):
## - Instruct CE whether to return a return code.
## - If 'True', the stdout is surpressed and a return code is sent to stdout.
## - A zero return code means the overall execution has successed for the configuration submitted,
## where a non-zero return code represents the number of failed tests.
## - Default is False
## name (optional)
## - The managed venv to use to run the test instance.
## - Default, venv with largest value, eg venv-2.17
## - A name must be a managed venv, lochost installatiosn are not supported.
## Example:
## $ ac --test-concurrent --host ec01130a --python 3.11 --zoau 1.3.0
## $ ac --test-concurrent --host ec01130a --python 3.11 --zoau 1.3.0 --file test_zos_operator_func.py --debug
## $ ac --test-concurrent --host "ec01130a,ec33012a,ec33017a" --python 3.11 --zoau 1.3.0\
## $ --file test_zos_operator_func.py,test_zos_job_submit_func.py\
## $ --skip "test_zos_job_submit_func.py::test_job_from_gdg_source[0]" --debug
## $ ac --test-concurrent --host ec01130a --python 3.11 --zoau 1.3.0 --file test_zos_operator_func.py --returncode True --itr 1
## $ ac --test-concurrent --host ec01130a --python 3.11 --zoau 1.3.1 --file test_zos_data_set_func.py --itr 1 --replay 1
## test_case_1
test_concurrent(){
# ----------------------------------------------------------------------------------------------------------------------------------
# CE -> AC -> AC vars -> var mapping -> defaults
# ----------------------------------------------------------------------------------------------------------------------------------
# --hostnames -> --host -> host=$1 -> pass through -> adhoc else auto discovered
# --user -> --user -> user=$2 -> pass through -> adhoc else auto discovered
# --pyz -> --python -> python=$3 -> pass through -> adhoc (auto translated to absolute path)
# --zoau -> --zoau -> zoau=$4 -> pass through -> adhoc (auto translated to absolute path)
# --pythonpath -> --pythonpath -> pythonpath=$5 -> pass through -> 'zoau/lib' or 'zoau/lib/<pyz version>'
# --volumes -> --volumes -> volumes=$6 -> pass through -> "222222,000000"
# --paths -> --file -> file=$7 -> pass through -> "functional/*,unit/*"
# --skip -> --skip -> skip=$8 -> pass through -> "test_module_security.py"
# --itr -> --itr -> itr=$9 -> pass through -> 50
# --replay -> --replay -> replay=$10 -> pass through -> 5
# --timeout -> --timeout -> timeout=$11 -> pass through -> 300
# --throttle -> --throttle -> throttle=$12 -> True = '--throttle', else '--no-throttle' -> True
# --workers -> --workers -> workers=$13 -> pass through -> 1
# --maxjob -> --maxjob -> maxjob=$14 -> pass through -> 10
# --maxnode -> --maxnode -> maxnode=$15 -> pass through -> 30
# --bal -> --bal -> bal=$16 -> pass through -> 10
# --verbose -> --verbose -> verbose=$17 -> True = '--verbose', else '--no-verbose' -> False
# --verbosity -> --verbosity -> verbosity=$18 -> pass through -> 0
# --capture -> --debug -> debug=$19 -> True = '--capture', else '--no-capture' -> False
# --extra -> --extr -> extra=$20 -> pass through -> "cd `pwd`"
# ----------------------------------------------------------------------------------------------------------------------------------
# echo "host=${1} user=${2} python=${3} zoau=${4} pythonpath=${5} volumes=${6} file=${7} skip=${8} itr=${9} replay=${10}"\
# "timeout=${11} throttle=${12} workers=${13} maxjob=${14} maxnode=${15} bal=${16} verbose=${17} verbosity=${18} debug=${19} extra=${20} returncode=${21}"
host="${1}"
user="${2}"
python="${3}"
zoau="${4}"
pythonpath="${5}"
volumes="${6}"
file="${7}"
skip="${8}"
itr="${9}"
replay="${10}"
timeout="${11}"
throttle="${12}"
workers="${13}"
maxjob="${14}"
maxnode="${15}"
bal="${16}"
verbose="${17}"
verbosity="${18}"
debug="${19}"
extra="${20}"
returncode="${21}"
option_name="${22}"
# Check that a collection is installed in the named venv or default venv.
ac_version $option_name
# If a --name has been passed, update the the VENV var path appropriately.
if [ "$option_name" ]; then
VENV=`validate_venv $option_name`
VENV_BIN=$VENV/bin
VENV_BASENAME=`basename $VENV`
fi
# Invoke shell script helpers to set variables if host is not null
if [ ! -z "${host}" ]; then
count_delim=`echo $host | awk -F "," '{print NF-1}'`
if [ $count_delim -gt 0 ]; then
first_entry=true
# Parse comma delimited string, for each entry perfom an operaion.
for host_entry in $(echo $host | sed "s/,/ /g"); do
if [ "$first_entry" == "true" ]; then
first_entry=false