-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer-mod
executable file
·1401 lines (1233 loc) · 48.8 KB
/
container-mod
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
# Yucheng Zhang
# Copyright (c) 2024 Tufts University
# This script is modified from the original script written by Lev Gorenstein from Purdue University.
# The original script is available at (https://github.com/PurdueRCAC/Biocontainers).
# This script assumes that you have Singularity or Apptainer
# installed on your system.
#
# Usage: Run "container-mod --help" for instructions.
VERSION="0.1" # Increment this version for updates
###############################################################################
# Prerequisites: Ensure Singularity or Apptainer is available
###############################################################################
if ! command -v singularity > /dev/null 2>&1; then
if module load singularity 2>/dev/null; then
:
else
if module load apptainer 2>/dev/null; then
:
else
echo "Failed to load both Singularity and Apptainer modules."
exit 1
fi
fi
fi
###############################################################################
# Helper functions
###############################################################################
clean_up() {
# Perform pre-exit housekeeping
return
}
# Function to print a message and exit with a status
graceful_exit() {
# graceful_exit [status]]
clean_up
exit ${1:-$E_OK}
}
# Function to send warning messages to stderr.
warn() {
# warn [-p] "message" ["message"...]
# Sends message(s) to stderr, optionally prefixing with "PROGNAME: ".
local msg
local withname=0
local opt OPTIND
while getopts :p opt; do
case $opt in
p) withname=1 ;;
esac
done
shift $((OPTIND - 1)) # Shift away the processed options
# Output messages
for msg in "$@" ; do
if [[ $withname -ne 0 ]]; then
msg="$PROGNAME: $msg"
fi
echo -e "$msg" 1>&2
done
}
# Function to display the help message
help_message() {
scriptname="container-mod"
cat <<-EOF
${scriptname} v$VERSION - Container Module Generator
This script streamlines the process of pulling container images from public registries, such as DockerHub,
and automates the generation of module files and wrapper scripts,
enabling users to seamlessly run containers as if they were standard software modules.
Usage:
${scriptname} <subcommand> [options] <URIs>
Subcommands:
pull Pull the container image from the specified URIs.
module Generate module files for the specified URIs.
exec Generate wrapper scripts for the programs provided by the container.
pipe Pull, generate module files, and generate wrapper scripts for the specified URIs.
Options:
-d, --dir DIR Specify the output directory for images and module files (default is the current directory).
-f, --force Force overwrite of existing images and module files (default behavior is to skip).
-m, --moduledir DIR Specify the directory for storing generated module files.
-u, --update Update the app file in the repos directory with the new version (default is no).
-p, --personal Create personal module files in the privatemodules directory (default is no).
--profile Use the specified profile for configuration. Available profiles are stored in profiles directory.
-j, --jupyter Generate Jupyter kernels for the specified URIs.
-h, --help Display this help message and exit.
Examples:
${scriptname} pull docker://quay.io/biocontainers/vcftools:0.1.16
${scriptname} module docker://quay.io/biocontainers/vcftools:0.1.16
${scriptname} exec docker://quay.io/biocontainers/vcftools:0.1.16
${scriptname} pipe -p docker://quay.io/biocontainers/vcftools:0.1.16
${scriptname} pipe --profile biocontainer docker://quay.io/biocontainers/vcftools:0.1.16
EOF
}
list_profiles() {
# List available profiles
if [ -d "${PROFILEHOMEDIR}" ]; then
for PROFILE in "${PROFILEHOMEDIR}"/*; do
PROFILENAME="$(basename "${PROFILE}")"
if [ "${PROFILENAME}" != "*" ]; then
echo "${PROFILENAME} (Personal Profile)"
fi
done
fi
if [ -d "${PROFILEROOT}" ]; then
for PROFILE in "${PROFILEROOT}"/*; do
PROFILENAME="$(basename "${PROFILE}")"
if [ "${PROFILENAME}" != "*" ]; then
if [ -e "${PROFILEHOMEDIR}/${PROFILENAME}" ]; then
echo "${PROFILENAME} (Overridden)"
else
echo "${PROFILENAME}"
fi
fi
done
fi
exit 0
}
boxify_text()
{
#
# Usage: boxify_text AAAA [BBB ...]
#
# Output:
# +------+
# | AAAA |
# | BBB |
# +------+
#
local msg=("$@")
local line longest width
for line in "${msg[@]}"; do
if [[ ${#line} -gt $width ]]; then
longest="$line"
width="${#line}"
fi
done
echo "+-${longest//?/-}-+"
for line in "${msg[@]}"; do
printf '| %s%*s%s |\n' "$(tput bold)" "-$width" "$line" "$(tput sgr0)"
done
echo "+-${longest//?/-}-+"
}
# Create directory if it doesn't exist
create_dir() {
local dir_path="$1"
local message="$2"
if [[ ! -d "$dir_path" ]]; then
mkdir -p "$dir_path"
echo "$message: $dir_path"
fi
}
# Process a list of URIs with a given command
handle_subcommand() {
local cmd="$1"
shift
for URI in "$@"; do
echo "Processing URI: $URI with the subcommand: $cmd"
if ! "$cmd" "$URI"; then
echo "Error executing command '$cmd' for URI: $URI" >&2
exit 1 # Halt on the first failure
fi
done
return 0 # All commands succeeded
}
# Copy the AppInfo directory if missing
ensure_appinfo_dir() {
# Ensure the personal mode is enabled and the target directory doesn't exist
if [[ "$personal" -eq 1 && ! -d "$HOME/container-apps/repos" ]]; then
# Create the directory if it doesn't exist
mkdir -p "$HOME/container-apps" || {
echo "Error: Failed to create directory $HOME/container-apps" >&2
return 1
}
# Copy the AppInfo directory
if [[ -d "$AppInfo_DIR" ]]; then
cp -r "$AppInfo_DIR" "$HOME/container-apps/" || {
echo "Error: Failed to copy $AppInfo_DIR to $HOME/container-apps/" >&2
return 1
}
else
echo "Error: Source directory $AppInfo_DIR does not exist" >&2
return 1
fi
fi
}
# Ensure app info file exists
ensure_appinfo_file() {
local URI="$1"
# Validate input argument
if [[ -z "$URI" ]]; then
echo "Error: URI parameter is missing." >&2
return 1
fi
local app
app=$(uri2app "$URI") || {
echo "Error: Failed to extract app name from URI: $URI" >&2
return 1
}
# Determine the target path for the appinfo file
local target_path
echo "Checking existence of files for $app"
echo "$HOME/container-apps/repos/$app exists? $(test -f "$HOME/container-apps/repos/$app" && echo yes || echo no)"
echo "$AppInfo_DIR/$app exists? $(test -f "$AppInfo_DIR/$app" && echo yes || echo no)"
if [[ ! -f "$HOME/container-apps/repos/$app" && ! -f "$AppInfo_DIR/$app" ]]; then
if [[ "$personal" -eq 1 ]]; then
target_path="$HOME/container-apps/repos/$app"
else
target_path="$AppInfo_DIR/$app"
fi
echo "Debug: target_path is set to $target_path"
# Create the appinfo file
create_appinfo_file "$app" "$target_path" || {
echo "Error: Failed to create appinfo file for $app at $target_path" >&2
return 1
}
else
echo "Appinfo file already exists for $app, skipping creation."
fi
}
###############################################################################
# Functions for converting URIs to module names, app names, and versions
###############################################################################
uri2imgname() {
# uri2imgname "URI"
# Takes an image URI ($1) and converts into desired Singularity
# image name according to our conventions (which is really a
# Scott McMillan's convention in his NGC Containers Modules collection
# (https://github.com/NVIDIA/ngc-container-environment-modules/).
# E.g.:
# URI: [docker://]quay.io/biocontainers/vcftools:0.1.16--h9a82719_5
# IMG: quay.io_biocontainers_vcftools:0.1.16--h9a82719_5.sif
#
# Note: VERY PRIMITIVE! Fancy URIs (e.g. usernames/passwords) may fail.
local uri="$1" file=""
file="${uri#*://}" # Drop {docker,https}:// prefix, if any
file="${file//\//_}.sif" # And replace '/' with '_'
echo "$file"
}
uri2modname() {
# uri2modname "URI"
# Takes an image URI and converts into desired modulefile
# name according to our naming conventions.
#
# Note: biocontainers often have additional interpreter, unique hash
# and/or container release information appended, in the form of a
# --<pyXY|plXYZ>h<hash>_<release>
# string (where XYZ version numbers may or may not be present).
# We strip hash and release number, but keep the interpreter
# information in the module name just in case.
# E.g.:
# URI: [docker://]quay.io/biocontainers/vcftools:0.1.16--h9a82719_5
# MOD: vcftools/0.1.16.lua
# and
# URI: [docker://]quay.io/biocontainers/bowtie2:2.4.2--py36hff7a194_2
# MOD: bowtie2/2.4.2-py36
#
# Note: VERY PRIMITIVE! Fancy URIs (e.g. usernames/passwords) may fail.
local uri="$1" file
local app=$(uri2app "$uri") # Application name
local buf="${uri##*/}" # Drop all until just name:version
local modver=${buf##*:} # Version starts after last ':'
# Handle interpreter/hash/release string.
# First, if there is an '--interpreter' (or '--extralibNNinterpreterMM')
# part, make it single dash and move the '--' after it:
# deeptools:3.5.1--py_0 -> deeptools:3.5.1-py--_0
# bowtie2:2.4.2--py36hff7a194_2 -> bowtie2:2.4.2-py36--hff7a194_2
# biopython:1.70--np112py36_1 -> biopython:1.70-np112py36--_1
# And then trim hash and release (everything past '--' or '_$')
modver=$(echo "$modver" | sed -re 's/(--.*)?(_[0-9]+)?$//') # trim --hash_release
file="$app/$modver.lua"
echo "$file"
}
uri2app() {
# uri2app "URI"
# Takes an image URI ($1) and extracts the application name according
# to our conventions. Handles some applications specially
# E.g.:
# URI: [docker://]quay.io/biocontainers/vcftools:0.1.16--h9a82719_5
# APP: vcftools
# Special:
# URI: [docker://]quay.io/qiime2/core:2021.2
# APP: qiime2
# URI: [docker://]r-base:4.1.1
# APP: r
# URI: [docker://]nvcr.io/nvidia/clara/clara-parabricks:4.0.0-1
# APP: parabricks
# etc.
local uri="$1" app
# Some special apps have their own dedicated repositories (as opposed
# to a central 'biocontainers' one), handle them first.
if [[ "$uri" == */qiime2/core:* ]]; then
app="qiime2"
elif [[ "$uri" == */r-base:* ]]; then
app="r"
elif [[ "$uri" == */cumulusprod_cellranger:* ]]; then
app="cellranger"
elif [[ "$uri" == */nvidia/clara/clara-parabricks:* ]]; then
app="parabricks"
elif [[ "$uri" == */nvidia/devtools/nsight-systems-cli:* ]]; then
app="nsightsys"
else
# And all "normal" apps will fall here
app="${uri##*/}" # Drop all until just name:version
app=${app%%:*} # And drop ":version"
fi
echo "$app"
}
uri2ver() {
# uri2ver "URI"
# Takes an image URI ($1) and extracts the application version
# according to our conventions. Biocontainers often have
# a "--<interpreter>h<hash>_<release>" appended to the application
# version - these are not part of application version (and get removed).
# E.g.:
# URI: [docker://]quay.io/biocontainers/vcftools:0.1.16--h9a82719_5
# VER: 0.1.16
local uri="$1" ver
ver="${uri##*/}" # Drop all until just name:version
ver=${ver##*:} # And drop "name:"
# Trim all "--<interpreter>h<hash>_<release>" extras.
ver=$(echo "$ver" | sed -re 's/(--.*)?(_[0-9]+)?$//')
echo "$ver"
}
###############################################################################
# Functions for pulling Singularity images
###############################################################################
pull() {
# pull "URI"
# Pulls a Singularity image from the specified URI and stores it
# in the directory defined by the IMG_OUTDIR variable, and updates
# the corresponding app file in the repos directory if the update option is set.
local uri=$1
local imgname="$(uri2imgname "$uri")"
local app="$(uri2app "$uri")" # Extract app name from URI
local version="$(uri2ver "$uri")" # Extract version from URI
local app_file="repos/$app" # Path to the app's file
# Path to the app's file in the repos folder
if [[ $personal -eq 1 ]]; then
local image_outdir="$PRIVATE_IMAGEDIR"
local app_file="$HOME/container-apps/repos/$app"
else
local image_outdir="$IMG_OUTDIR"
local app_file="$AppInfo_DIR/$app"
fi
# Check if the image file already exists
if [ -f "${image_outdir}/${imgname}" ]; then
echo "Image already exists: ${image_outdir}/${imgname}"
return
fi
mkdir -p "${image_outdir}" # Create the output directory if it doesn't exist
singularity pull "${image_outdir}/${imgname}" "$uri" || exit 1 # Pull the Singularity image
if [[ $update_repo -eq 1 ]]; then
# Check if app file exists
if [[ ! -f "$app_file" ]]; then
echo "Error: App file '$app_file' not found. Please create an app file in the repo first."
return 1
fi
# Create a temporary file for the updated app file
temp_file="${app_file}.tmp"
{
# Keep lines that do not start with "version("
grep -v '^version(' "$app_file"
# Add the new version entry
echo "version(\"$version\", uri=\"$uri\")"
# Append existing "version(" lines
grep '^version(' "$app_file"
} > "$temp_file"
# Check if the temporary file was created successfully
if [[ ! -f "$temp_file" ]]; then
echo "Error: Failed to create the temporary file '$temp_file'."
return 1
fi
# Replace the original app file with the updated content
if mv "$temp_file" "$app_file"; then
echo "Updated app file: $app_file with new version $version"
else
echo "Error: Failed to rename '$temp_file' to '$app_file'."
return 1
fi
fi
}
###############################################################################
# Functions for generating modulefiles
###############################################################################
module() {
# module "URI"
# Generates a module file for a given application URI and saves it
# in the specified output directory.
#
# This function performs the following tasks:
# 1. Takes the provided URI and converts it into a module file name
# using the uri2modname function.
# 2. Checks if the module file already exists. If it does and the
# force option is not enabled, the function skips the generation
# process and adds the URI to the SKIPPED_URIS array.
# 3. Creates the necessary directory structure for the module file.
# 4. Generates the content of the module file using the
# print_modulefile function.
# 5. Writes the generated content to the module file and provides
# a reminder to edit the stub for additional modifications.
#
# Arguments:
# URI - The application URI that identifies the desired image.
#
# Example Usage:
# module "docker://quay.io/biocontainers/vcftools:0.1.16--h9a82719_5"
#
# Errors:
# If the output directory cannot be created or if there is an
# issue writing to the module file, an error message will be displayed
# and the function will exit with a non-zero status.
local URI="$1"
# Testing whether we are generating personal or public modules
if [[ $personal -eq 1 ]]; then
local module_outdir="$PRIVATE_MODULEDIR"
else
local module_outdir="$MOD_OUTDIR"
fi
local OUTFILE="${module_outdir}/$(uri2modname "$URI")"
# If modulefile already exists, skip it (unless --force is in effect)
if [[ -f "$OUTFILE" && $force -eq 0 ]]; then
echo "SKIPPED: $URI --> $OUTFILE (file exists)"
SKIPPED_URIS+=("$URI")
return 0
fi
# If force is true and module file exists, remove it before creating a new one
if [[ -f "$OUTFILE" && $force -eq 1 ]]; then
echo "Force option enabled, removing existing module file $OUTFILE"
rm -rf "$OUTFILE" || {
echo "Error: Failed to remove existing module file $OUTFILE"
exit 1
}
fi
# Create the directory, exit on failure
mkdir -p "$(dirname "$OUTFILE")" || {
echo "Error: Failed to create directory for '$OUTFILE'"
exit 1
}
# Generate module file content
MODULE=$(print_modulefile "$URI")
# Write module content to the file, exit on failure
if echo "$MODULE" > "$OUTFILE"; then
echo "Remember to edit '$OUTFILE' stub (look for TODO: labels!)"
echo
else
echo "Error: Failed to write to '$OUTFILE'"
exit 1
fi
}
print_modulefile() {
# print_modulefile "URI"
# Generates or repurposes a modulefile for the specified application based
# on the provided image URI.
#
# This function performs the following steps:
# 1. Accepts an image URI as input, which is expected to be in a format
# recognizable by the modulefile generation system.
# 2. Extracts the application name from the URI using the uri2app function.
# 3. Checks for the existence of any previously created modulefiles for
# the application by calling find_latest_modulefile.
# 4. If no prior modulefiles are found, it generates a new modulefile
# using the generate_new_modulefile function.
# 5. If an existing modulefile is found, it repurposes that file as a
# template for the new modulefile using the repurpose_old_modulefile function.
#
# Arguments:
# uri - The image URI for which to generate or repurpose the modulefile.
#
# Returns:
# 0 if successful, or 1 if an error occurred during modulefile generation
# or repurposing.
local uri="$1"
local app=$(uri2app "$uri") # e.g., vcftools
local latest_modulefile=$(find_latest_modulefile "$app") # file or empty
# Check if no latest modulefile exists
if [[ -z "$latest_modulefile" ]]; then
# Generate a new modulefile
generate_new_modulefile "$uri" || {
echo "Error: Failed to generate new modulefile for $app"
return 1
}
else
# Repurpose the old modulefile
repurpose_old_modulefile "$uri" "$latest_modulefile" || {
echo "Error: Failed to repurpose modulefile for $app"
return 1
}
fi
# Return the status of the last executed command (generator)
return $?
}
find_latest_modulefile() {
# find_latest_modulefile "app"
# Searches for the latest modulefile for the specified application.
#
# This function performs the following tasks:
# 1. Accepts the application name as an argument.
# 2. Checks for the existence of modulefiles (Lua files) in the
# designated module directory for the specified application.
# 3. If modulefiles are found, it sorts them by their last modified
# time and retrieves the most recently modified modulefile.
# 4. If no modulefiles are found, it issues a warning message.
#
# Arguments:
# app - The name of the application for which to find the latest
# modulefile.
#
# Returns:
# The path to the latest modulefile, or an empty string if no
# modulefiles are found.
local app="$1"
local modulefile=""
# Testing whether we are generating personal or public apps
# If personal, search in both privatemodules and the designated module directory
if [[ $personal -eq 1 ]]; then
local MOD_EXISTING_DIRS=("$HOME/privatemodules" "$MOD_EXISTING_DIR")
else
local MOD_EXISTING_DIRS=("$MOD_EXISTING_DIR")
fi
# Loop through all directories and find all *.lua files
for dir in "${MOD_EXISTING_DIRS[@]}"; do
# Check if there are any *.lua files in this directory
if ls "$dir/$app/"*.lua 1> /dev/null 2>&1; then
# Find the most recent modulefile in this directory
latest_file=$(ls -t "$dir/$app/"*.lua | head -n 1)
# If modulefile is empty or latest_file is more recent, update modulefile
if [[ -z "$modulefile" || "$latest_file" -nt "$modulefile" ]]; then
modulefile="$latest_file"
fi
fi
done
echo "$modulefile"
}
generate_new_modulefile() {
# generate_new_modulefile "URI"
# Generates a new modulefile for a given application based on the provided
# image URI. This function extracts metadata from the URI, checks for
# the existence of a template file, and populates the modulefile content
# by substituting placeholders with actual values.
#
# The generated modulefile contains information such as the application name,
# version, description, homepage, registry details, and executable directory.
#
# Arguments:
# uri - The image URI for which to generate the modulefile.
#
# Returns:
# 0 if the modulefile was successfully generated and outputted,
# 1 if the template file is not found or if an error occurs during
# generation.
local uri="$1"
# Testing whether we are generating personal or public apps
if [[ $personal -eq 1 ]]; then
local exec_outdir="${PRIVATE_EXECUTABLE_DIR/#\$HOME/$HOME}"
else
local exec_outdir="$PUBLIC_EXECUTABLE_DIR"
fi
local image=$(uri2imgname "$uri")
local app=$(uri2app "$uri")
local ver=$(uri2ver "$uri")
# Initialize description and homepage variables
local homepage=""
local description=""
parse_home_description
# Determine the registry and registry URL
local registry=""
local registry_url=""
case "$uri" in
*"biocontainers"*)
registry="BioContainers"
registry_url="https://biocontainers.pro/tools/$app"
;;
*"quay.io"*)
registry="Quay.io"
registry_url="https://quay.io/repository/$app"
;;
*"nvcr.io"*)
registry="Nvidia NGC"
registry_url="https://catalog.ngc.nvidia.com/containers"
;;
*"gcr.io"*)
registry="Google Container Registry"
registry_url="$uri"
;;
*)
registry="DockerHub"
docker_repo=$(echo "$uri" | sed 's|docker://\([^:]*\):.*|\1|')
registry_url="https://hub.docker.com/r/${docker_repo}"
;;
esac
# Ensure template file exists
local template_file="${TEMPLATE_DIR}/module_template.lua"
if [[ ! -f "$template_file" ]]; then
echo "Error: Template file '$template_file' not found."
return 1
fi
# Substitute placeholders in the template
local modulefile_content=$(sed -e "s|\${DESCRIPTION}|$description|g" \
-e "s|\${REGISTRY}|$registry|g" \
-e "s|\${REGISTRY_URL}|$registry_url|g" \
-e "s|\${HOMEPAGE}|$homepage|g" \
-e "s|\${IMAGE}|$image|g" \
-e "s|\${URI}|$uri|g" \
-e "s|\${VERSION}|$ver|g" \
-e "s|\${EXECUTABLE_DIR}|$exec_outdir|g" \
-e "s|\${APP}|$app|g" \
"$template_file")
# Output the generated modulefile
echo "$modulefile_content"
return $MODTYPE_NEW
}
repurpose_old_modulefile() {
# repurpose_old_modulefile "URI" "TEMPLATE"
# Repurposes an existing modulefile template for a given application by
# updating it with the new version, image, and URI information. This function
# reads the specified template file, modifies relevant fields, and outputs
# the updated modulefile content.
#
# Arguments:
# uri - The image URI associated with the application.
# template - The path to the existing modulefile that serves as the template.
#
# Returns:
# 0 if the modulefile was successfully updated and outputted,
# 1 if the modification fails and a new modulefile is generated instead.
local uri="$1"
local template="$2"
local image=$(uri2imgname "$uri")
local app=$(uri2app "$uri")
local ver=$(uri2ver "$uri")
# Modify the template with new version, image, and URI
local buf=$(awk -v ver="$ver" -v image="$image" -v uri="$uri" '
/^[[:blank:]]*whatis.*Version:/ { $0 = "whatis(\"Version: " ver "\")" }
/^[[:blank:]]*local[[:blank:]]+version[[:blank:]]*=/ { $0 = "local version = \"" ver "\"" }
/^[[:blank:]]*local[[:blank:]]+image[[:blank:]]*=/ { $0 = "local image = \"" image "\"" }
/^[[:blank:]]*local[[:blank:]]+uri[[:blank:]]*=/ { $0 = "local uri = \"" uri "\"" }
# Modify modroot to replace the version part after .. with the version (ver)
/^[[:blank:]]*local[[:blank:]]+modroot[[:blank:]]*=/ {
# Match the modroot assignment and replace the version after ..
sub(/\.\. ".*"/, ".. \"" ver "\"")
}
{ print }
' < "$template")
# Check if the template modification succeeded
if [[ $? -ne 0 || -z "$buf" ]]; then
warn -p "Error: Failed to repurpose template '$template' for '$uri'"
generate_new_modulefile "$uri"
return $?
fi
echo "$buf"
return $MODTYPE_EXISTING
}
###############################################################################
# Functions for generating executables
###############################################################################
exec() {
# exec "URI"
# Processes a given application URI to generate the corresponding
# executables in the designated output directory.
#
# This function performs the following tasks:
# 1. Parses the provided URI to extract the application name,
# version, and image name.
# 2. Calls `parse_exec` to obtain an array of predefined
# executables for the application.
# 3. Creates the output directory for the executables.
# 4. Checks if the executables exist and generates them.
#
# Note: If the force option is enabled, the existing output
# directory will be removed before creating a new one.
#
# Arguments:
# URI - The application URI that identifies the desired image.
#
# Example Usage:
# exec "docker://quay.io/biocontainers/vcftools:0.1.16--h9a82719_5"
#
# Errors:
# If no executables are defined for the application, or if
# there is an issue creating directories, an error message will be
# displayed and the function will exit with a non-zero status.
local uri="$1"
# Parse the URI into app, version, and image
local app=$(uri2app "$uri")
local ver=$(uri2ver "$uri")
local image=$(uri2imgname "$uri")
# Call the parse_exec function and capture output into an array
exec_array=($(parse_exec))
# Error check for parse_exec
if [ $? -ne 0 ]; then
warn -p "Error: No executables are defined for $app"
fi
# Testing whether we are generating personal or public apps
if [[ $personal -eq 1 ]]; then
local exec_outdir="$PRIVATE_EXECUTABLE_DIR"
local image_outdir="$PRIVATE_IMAGEDIR"
else
local exec_outdir="$EXEC_OUTDIR"
local image_outdir="$IMG_OUTDIR"
fi
# Define the output directory
local AppTool_dir="$exec_outdir/$app/$ver/bin"
# If AppTool_dir exists and force is not set, skip executable generation
if [[ -d "$AppTool_dir" && $force -eq 0 ]]; then
warn -p "Output directory $AppTool_dir already exists. Skipping executable generation."
return 0
fi
# If force is true and directory exists, remove it before creating a new one
if [[ -d "$AppTool_dir" && $force -eq 1 ]]; then
echo "Force option enabled, removing existing directory $AppTool_dir"
rm -rf "$AppTool_dir" || {
echo "Error: Failed to remove directory $AppTool_dir"
exit 1
}
fi
# Create the directory if it doesn't exist or was just removed
mkdir -p "$AppTool_dir" || {
warn -p "Error: Failed to create directory $AppTool_dir"
exit 1
}
# Check if exec_array is empty
if [[ ${#exec_array[@]} -eq 0 ]]; then
warn -p "Warning: No executables are predefined for $app version $ver."
else
echo "Generating executables provided by $app version $ver..."
# Process each executable in the array
for exec in "${exec_array[@]}"; do
# Check if the executable exists
if confirm_exec_exists "$exec" "$image_outdir/$image"; then
# Attempt to generate the executable
if generate_executable "$app" "$ver" "$image" "$exec"; then
echo "Successfully generated: $exec"
else
echo "Error: Failed to generate executable: $exec" >&2
fi
else
echo "Warning: Executable not found: $exec in $image_outdir/$image" >&2
fi
done
fi
}
confirm_exec_exists() {
# confirm_exec_exists
# Checks if a specified executable is installed within a Singularity container.
#
# This function takes the name of an executable as an argument and uses
# the `singularity exec` command to determine if the executable is present
# in the container's environment. If the executable is found, a confirmation
# message is printed; otherwise, an error message is displayed, and the script
# exits with a non-zero status.
#
# Arguments:
# exec: The name of the executable to check for within the container.
#
# Exits with:
# 0 if the executable is found,
# 1 if the executable is not found.
local exec=$1
local image=$2
if ! singularity exec "$image" which "$exec" &> /dev/null; then
echo "Executable '$exec' is NOT installed in the container."
return 1
else
return 0
fi
}
generate_executable() {
# generate_executable $app $version $image $command
# Generates a Bash wrapper script for executing application commands
# within a Singularity container.
#
# This function takes the application name, version, container image,
# and command as arguments. It checks for required variables, creates
# a directory for the executable if necessary, and generates a Bash
# script that acts as a wrapper to call the application command within
# the specified Singularity container. The script includes provisions
# for loading the Singularity module and handling Nvidia or AMD GPU
# options.
#
# Arguments:
# app: The name of the application for which the wrapper is being created.
# version: The version of the application.
# image: The name of the container image to use.
# command: The command or program to execute within the container.
#
# Returns:
# 0 on success,
# 1 if there are missing arguments or errors in execution.
local app=$1
local version=$2
local image=$3
local command=$4
local executable="$AppTool_dir/$command"
# Testing whether we are generating personal or public apps
if [[ $personal -eq 1 ]]; then
# Using local scope and expanding $HOME
local image_dir="${PRIVATE_IMAGEDIR/#\$HOME/$HOME}"
else
local image_dir="$PUBLIC_IMAGEDIR"
fi
# Ensure necessary variables are set
if [[ -z "$app" || -z "$version" || -z "$image" || -z "$command" ]]; then
echo "Error: Missing arguments for generate_executable: app=$app, version=$version, image=$image, command=$command"
return 1
fi
# Create the executable directory if it doesn't exist
mkdir -p "$(dirname "$executable")"
# Generate the bash wrapper script
cat <<EOF >"$executable"
#!/usr/bin/env bash
# Set variables
VER="$version"
PKG="$app"
PROGRAM="$command"
IMAGE_DIR="$image_dir"
IMAGE="$image"
# Load Singularity if it is not already loaded
if ! command -v singularity &> /dev/null; then
module load singularity || { echo "Failed to load Singularity module"; exit 1; }
fi
# Determine Nvidia GPUs (to pass the corresponding flag to Singularity)
if nvidia-smi -L &> /dev/null; then
OPTIONS="--nv"
fi
# Determine AMD GPUs (to pass the corresponding flag to Singularity)
if rocm-smi -L &> /dev/null; then
OPTIONS="\$OPTIONS --rocm"
fi
# Run the container with appropriate options
singularity exec \$OPTIONS "\$IMAGE_DIR/\$IMAGE" "\$PROGRAM" "\$@"
EOF
# Make the wrapper script executable
chmod +x "$executable"
if [[ $? -ne 0 ]]; then
echo "Error: Failed to generate wrapper for $command"
return 1
fi
}
###############################################################################
# Functions for extrac basic information and available executables from repo file
###############################################################################
create_appinfo_file() {
# create_appinfo_file
# Creates a new application information file in the 'repos' directory
# based on user input. The function prompts the user to enter a description,
# homepage, and list of available programs for the application.
local app=$1
#localappinfo="$HOME/container-apps/repos/$app"
localappinfo=$2
echo "$app is not found in our application information database."
echo "let's create a new entry for $app."
echo "Enter a simple description of your application (e.g., Blast is an algorithm and program for comparing primary biological sequence information): "
read description
echo "Enter the homepage of your application (e.g., https://blast.ncbi.nlm.nih.gov/Blast.cgi):"
read homepage
echo "Enter the programs that are available in your application (e.g., blastn, blastp, blastx, tblastn, tblastx):"
read programs
mkdir -p "$HOME/container-apps/repos"
echo "Description: $description" > "$localappinfo"
echo "Home Page: $homepage" >> "$localappinfo"
echo "Programs: $programs" >> "$localappinfo"
}
parse_home_description() {
# parse_home_description
# Parses the application file located in the 'repos' folder to extract the
# 'Description' and 'Home Page' fields. If the application file is not found,
# or if the fields cannot be extracted, appropriate error messages are displayed.
#
# This function sets the 'description' and 'homepage' variables with the
# extracted values or sets them to empty if not found. The function does not
# take any arguments.
#
# Returns:
# 0 if the fields are found and extracted successfully,
# 1 if the application file does not exist or the fields are missing.
# Path to the app's file in the repos folder
if [[ $personal -eq 1 ]]; then
local app_file="$HOME/container-apps/repos/$app"
else
local app_file="$AppInfo_DIR/$app"
fi