-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathicrn_manager
More file actions
executable file
·1172 lines (1083 loc) · 45.8 KB
/
icrn_manager
File metadata and controls
executable file
·1172 lines (1083 loc) · 45.8 KB
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
# This script manages the checkout of kernels from a configured central repository
# this script leverages 'update_r_libs.sh'
# [[ $_ != $0 ]] && return
# check for existence of needed tools
if [ -z $(type -p jq) ]; then
echo "Need tool jq installed to proceed."
exit 1
fi
icrn_base=".icrn"
icrn_kernels="icrn_kernels"
APP_FOLDER=$(dirname $0)
KERNEL_FOLDER=${KERNEL_FOLDER:-${APP_FOLDER}/../kernels}
if [ ! -d ${KERNEL_FOLDER} ]; then echo "Could not determine location of kernel respository - contact administrator"; exit -1 ; fi
central_catalog_default=${KERNEL_FOLDER}
ICRN_USER_BASE=${ICRN_USER_BASE:-${HOME}/${icrn_base}}
ICRN_MANAGER_CONFIG=${ICRN_MANAGER_CONFIG:-${ICRN_USER_BASE}/manager_config.json}
ICRN_USER_KERNEL_BASE=${ICRN_USER_KERNEL_BASE:-${ICRN_USER_BASE}/${icrn_kernels}}
ICRN_USER_CATALOG=${ICRN_USER_CATALOG:-${ICRN_USER_KERNEL_BASE}/user_catalog.json}
if [ ! -e ${ICRN_MANAGER_CONFIG} ]; then
# Note: Auto-initialization will be handled in kernels() function
# This section sets up default paths for when config doesn't exist yet
ICRN_KERNEL_REPOSITORY=$central_catalog_default
ICRN_R_KERNELS=${ICRN_KERNEL_REPOSITORY}"/R"
ICRN_PYTHON_KERNELS=${ICRN_KERNEL_REPOSITORY}"/Python"
ICRN_KERNEL_CATALOG=${ICRN_KERNEL_REPOSITORY}"/icrn_kernel_catalog.json"
else
ICRN_KERNEL_REPOSITORY=$(jq -r ".\"icrn_central_catalog_path\"" "${ICRN_MANAGER_CONFIG}")
ICRN_R_KERNELS=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_r_kernels\"" "${ICRN_MANAGER_CONFIG}")
ICRN_PYTHON_KERNELS=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_python_kernels\"" "${ICRN_MANAGER_CONFIG}")
ICRN_KERNEL_CATALOG=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_kernel_catalog\"" "${ICRN_MANAGER_CONFIG}")
if [ -z ${ICRN_KERNEL_REPOSITORY} ] || [ -z ${ICRN_R_KERNELS} ] || [ -z ${ICRN_PYTHON_KERNELS} ] || [ -z ${ICRN_KERNEL_CATALOG} ] ; then
echo "Problem with determining central kernel information - please check user manager config at ${ICRN_MANAGER_CONFIG}"
echo "ICRN Kernel base: ${ICRN_KERNEL_REPOSITORY}"
echo "ICRN R Kernels location: ${ICRN_R_KERNELS}"
echo "ICRN Python Kernels location: ${ICRN_PYTHON_KERNELS}"
echo "ICRN catalog location: ${ICRN_KERNEL_CATALOG}"
exit 1
fi
fi
# Prompt the user for confirmation before proceeding with a potentially destructive operation.
#
# Parameters:
# $1 - challenge: Optional prompt string to display to the user. If not provided,
# defaults to "Are you sure? [y/N]"
#
# Returns:
# 0 if user confirms (y/yes), exits with status 0 if user declines
#
# Side effects:
# Exits the script with status 0 if user does not confirm
confirm() {
local challenge=$1; shift
# call with a prompt string or use a default
# function much less needed after we have stopped unpacking kernels to the users local dir; retaining in case its needed
# https://stackoverflow.com/questions/3231804/in-bash-how-to-add-are-you-sure-y-n-to-any-command-or-alias
read -r -p "${challenge:-Are you sure? [y/N]} " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
return 0
else
echo "Exiting..."
exit 0
fi
}
last_check=-1
# Check if a kernel entry exists in the specified catalog.
#
# This function searches for a kernel entry in a catalog (either central or user catalog)
# and sets the global variable 'last_check' to indicate success (1) or failure (0).
#
# Parameters:
# $1 - catalog: Path to the JSON catalog file to search
# $2 - language: Language of the kernel (e.g., "R", "Python")
# $3 - targetname: Name of the kernel to search for
# $4 - targetversion: Optional version number to check for
#
# Global variables:
# last_check: Set to 1 if entry found, 0 if not found. Initialized to -1.
#
# Returns:
# No return value. Results are stored in the global 'last_check' variable.
#
# Side effects:
# Prints error messages to stdout if kernel or version is not found
check_for_catalog_entry()
{
local catalog=$1; shift
local language=$1; shift
local targetname=$1; shift
if [ ! -z $1 ]; then
local targetversion=$1; shift
fi
if [ ! "$(jq -r ".\"$language\".\"$targetname\"" "$catalog")" = "null" ]; then
if [ ! -z $targetversion ]; then
# we expect to find version if its provided
if [ ! "$(jq -r ".\"$language\".\"$targetname\".\"$targetversion\"" $catalog)" = "null" ]; then
last_check=1
else
echo "Found kernel for $targetname"
echo "Could not find version: $targetversion"
last_check=0
fi
else
last_check=1
fi
else
# no target found
echo "Checking for catalog entry failed for: $targetname"
echo "Checked catalog: $catalog"
last_check=0
fi
}
# Retrieve and display all available versions for a specific kernel package.
#
# This function first verifies that the kernel exists in the catalog, then extracts
# and displays all available version numbers for that kernel.
#
# Parameters:
# $1 - catalog: Path to the JSON catalog file to search
# $2 - language: Language of the kernel (e.g., "R", "Python")
# $3 - targetname: Name of the kernel to get versions for
#
# Returns:
# Exits with status 1 if the kernel is not found in the catalog
#
# Side effects:
# Prints available versions to stdout, or error message if kernel not found
get_versions_for_package()
{
local catalog=$1; shift
local language=$1; shift
local targetname=$1; shift
check_for_catalog_entry $catalog $language $targetname
if [ $last_check = 0 ]; then
echo "$targetname not present in catalog at $catalog"
exit 1
else
last_check=-1
fi
available_versions=$(jq -r ".\"$language\".\"$targetname\"| keys[]" "$catalog")
echo "Available versions for $targetname:"
echo $available_versions
}
# Display a list of all available kernels from the central repository catalog.
#
# This function reads the central kernel catalog and displays all available kernels
# in a tabular format showing language, kernel name, and version for each entry.
#
# Parameters:
# None
#
# Returns:
# No return value
#
# Side effects:
# Prints a tab-separated table of available kernels to stdout
function kernels__available() # get a list of available kernels from the central repo
{
icrn_catalog=${ICRN_KERNEL_CATALOG}
echo "Available kernels in ICRN catalog ($icrn_catalog):"
languages=$(jq -r '. | keys[]' $icrn_catalog)
echo -e "Language\tKernel\tVersion"
for language in $languages; do
kernels=$(jq -r ".$language | keys[]" $icrn_catalog)
for kernel in $kernels; do
versions=$(jq -r ".$language.$kernel | keys[]" $icrn_catalog)
for version in $versions; do
echo -e $language"\t"$kernel"\t"$version
done
done
done
}
# Alias for kernels__available() - display a list of all available kernels.
#
# This is a convenience function that calls kernels__available() with all passed arguments.
#
# Parameters:
# All arguments are passed through to kernels__available()
#
# Returns:
# Same as kernels__available()
function kernels__avail() # alias for available
{
kernels__available "$@"
}
# Display a list of kernels that have been checked out and are ready for use.
#
# This function reads the user's local catalog and displays all kernels that have
# been successfully checked out, showing language, kernel name, and version.
#
# Parameters:
# None
#
# Returns:
# No return value
#
# Side effects:
# Prints a tab-separated table of checked-out kernels to stdout
function kernels__list() # get the list of kernels already checked out and ready for use
{
user_catalog=${ICRN_USER_CATALOG}
echo "checked out kernels in in user catalog (${ICRN_USER_CATALOG}):"
languages=$(jq -r '. | keys[]' $user_catalog)
echo -e "Language\tKernel\tVersion"
for language in $languages; do
kernels=$(jq -r ".$language | keys[]" $user_catalog)
for kernel in $kernels; do
versions=$(jq -r ".$language.$kernel | keys[]" $user_catalog)
for version in $versions; do
echo -e $language"\t"$kernel"\t"$version
done
done
done
}
# Activate a kernel that has already been checked out for use in Jupyter.
#
# This function activates a previously checked-out kernel, making it available for use
# in Jupyter notebooks. For R kernels, it creates symbolic links and updates .Renviron.
# For Python kernels, it installs the kernel spec using ipykernel.
# The special value "none" can be used to deactivate all kernels for a language.
#
# Parameters:
# $1 - language: Language of the kernel (e.g., "R", "Python")
# $2 - targetname: Name of the kernel to activate, or "none" to deactivate all
# $3 - version: Version number of the kernel (required unless targetname is "none")
#
# Returns:
# Exits with status 1 if parameters are missing or invalid, or if kernel path not found
#
# Side effects:
# - For R: Creates symbolic link and updates .Renviron via update_r_libs.sh
# - For Python: Installs/uninstalls Jupyter kernel specs
# - Removes existing kernel installations before installing new ones
function kernels__use() # use a kernel which is already checked out
{
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
# ensure we get a uc-first label for lang
language="$(tr '[:lower:]' '[:upper:]' <<< ${language:0:1})${language:1}"
local target_r_environ_file=${HOME}"/.Renviron"
# dependent on PATH VAR
local target_r_libs_script="update_r_libs.sh"
if [ "$targetname" = "none" ]; then
echo "Desired kernel: none for $language"
elif [ -z $targetname ] || [ -z $language ]; then
echo "usage: icrn_manager kernels use <language> <kernel name> [version number]"
echo " or: icrn_manager kernels use <language> none"
help
exit 1
elif [ -z $version ] && [ "$targetname" != "none" ]; then
echo "usage: icrn_manager kernels use <language> <kernel name> <version number>"
echo " or: icrn_manager kernels use <language> none"
help
exit 1
else
echo "Desired kernel:"
echo "Language: "$language
echo "Kernel: "$targetname
if [ "$targetname" != "none" ]; then
echo "Version: "$version
fi
fi
icrn_catalog=${ICRN_KERNEL_CATALOG}
user_catalog=${ICRN_USER_CATALOG}
# add in checking for various needed entities
# TODO: convert this to using the kernel-checking methods above
if [ "$targetname" = "none" ]; then
case $language in
"R")
echo "Removing preconfigured kernels from R..."
${target_r_libs_script} ${target_r_environ_file}
;;
"Python")
echo "Removing preconfigured kernels from Python..."
# Get list of kernels from user catalog
user_catalog=${ICRN_USER_CATALOG}
if [ -f "$user_catalog" ]; then
# Get all Python kernels from user catalog
catalog_kernels=$(jq -r '.Python | to_entries[] | .key + "-" + (.value | to_entries[] | .key)' "$user_catalog" 2>/dev/null || echo "")
if [ -n "$catalog_kernels" ]; then
echo "Found Python kernels in user catalog: $catalog_kernels"
# Get list of installed kernels from jupyter
installed_kernels=$(jupyter kernelspec list --json 2>/dev/null | jq -r '.kernelspecs | keys[]' 2>/dev/null || echo "")
if [ -n "$installed_kernels" ]; then
echo "Found installed kernels."
# echo "Found installed kernels: $installed_kernels"
# Remove only kernels that are both in catalog and installed
for catalog_kernel in $catalog_kernels; do
if echo "$installed_kernels" | grep -q "^$catalog_kernel$"; then
echo "Removing kernel: $catalog_kernel"
jupyter kernelspec uninstall -y "$catalog_kernel" 2>/dev/null || echo "Failed to remove kernel: $catalog_kernel"
else
echo "Kernel $catalog_kernel not found in jupyter kernelspec list, skipping"
fi
done
else
echo "No installed kernels found in jupyter kernelspec list"
fi
else
echo "No Python kernels found in user catalog"
fi
else
echo "User catalog not found"
fi
echo "Python kernel removal complete"
;;
*)
echo "Unsupported language '$language' for kernel removal"
echo "Supported languages: R, Python"
exit 1
;;
esac
else
absolute_path=$(jq -r ".\"$language\".\"$targetname\".\"$version\".\"absolute_path\"" $user_catalog)
overlay_path=$(jq -r ".\"$language\".\"$targetname\".\"$version\".\"overlay_path\"" $user_catalog)
# absolute path for R is determined by activating the R install and finding the location of its library directory
# then we create a link to it
# user_overlay_location="${ICRN_USER_KERNEL_BASE}/${language_lower}/${targetname}-${version}/"
echo "checking for: "$absolute_path
case $language in
"R")
if [ -z "$overlay_path" ] || [ "$overlay_path" = "null" ]; then
echo "ERROR: Overlay path missing from user catalog for $language $targetname $version."
echo "Run 'icrn_manager kernels get $language $targetname $version' to re-register the overlay."
exit 1
fi
if [ ! -d "$overlay_path" ]; then
echo "ERROR: Overlay path recorded in user catalog does not exist: $overlay_path"
echo "Consider cleaning and re-checking out this kernel."
exit 1
fi
target_kernel_link_path=${ICRN_USER_KERNEL_BASE}/${targetname}
if [ -e "$target_kernel_link_path" ]; then
echo "Found existing link; removing..."
echo "$target_kernel_link_path"
rm -f "$target_kernel_link_path"
fi
if [ -d "$absolute_path" ]; then
echo "Found. Linking and Activating..."
ln -s $absolute_path $target_kernel_link_path
${target_r_libs_script} ${target_r_environ_file} $absolute_path $overlay_path
echo "Done."
else
echo "Path could not be found. There is a problem with your user catalog."
echo "Consider cleaning the entry in your catalog via: ./icrn_manager kernels clean $language $targetname $version"
echo "And then checking out the kernel again."
exit 1
fi
;;
"Python")
if [ -d "$absolute_path" ]; then
echo "Found. Activating Python kernel..."
# Check if kernel is already installed
kernel_name="${targetname}-${version}"
display_name="${targetname} ${version}"
# Check if kernel already exists
if jupyter kernelspec list 2>/dev/null | grep -q "^$kernel_name\$"; then
echo "Kernel $kernel_name already exists. Removing..."
jupyter kernelspec uninstall -y "$kernel_name" 2>/dev/null || echo "Failed to remove existing kernel"
fi
# Activate the conda environment and install the kernel
echo "Installing Python kernel: $kernel_name"
source "$absolute_path/bin/activate"
# Install the kernel
python -m ipykernel install --user --name "$kernel_name" --display-name="$display_name" 2>/dev/null
# Deactivate the environment
source "$absolute_path/bin/deactivate"
echo "Python kernel installation complete."
echo "Kernel '$kernel_name' is now available in Jupyter."
else
echo "Path could not be found. There is a problem with your user catalog."
echo "Consider cleaning the entry in your catalog via: ./icrn_manager kernels clean $language $targetname $version"
echo "And then checking out the kernel again."
exit 1
fi
;;
*)
echo "Unsupported language '$language' for kernel activation"
echo "Supported languages: R, Python"
exit 1
;;
esac
fi
}
# Alias for kernels__use() - activate a kernel that has already been checked out.
#
# This is a convenience function that calls kernels__use() with all passed arguments.
#
# Parameters:
# All arguments are passed through to kernels__use()
#
# Returns:
# Same as kernels__use()
function kernels__activate() # alias for use
{
"kernels__use" "$@"
}
# Register the overlay directory path for a kernel in the user's catalog.
#
# This function updates the user catalog with the overlay path for a specific kernel.
# The overlay directory is used for storing user-specific customizations and additional
# packages that should be loaded alongside the kernel.
#
# Parameters:
# $1 - language: Language of the kernel (e.g., "R", "Python")
# $2 - targetname: Name of the kernel
# $3 - version: Version number of the kernel
#
# Returns:
# 0 if overlay path was successfully registered, 1 if overlay directory not found
#
# Side effects:
# Updates the user catalog JSON file with the overlay_path field
function register_user_overlay_in_user_catalog() # add the overlay location to the users catalog
{
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
language_lower=$(echo "$language" | tr '[:upper:]' '[:lower:]')
user_overlay_location="${ICRN_USER_KERNEL_BASE}/${language_lower}/${targetname}-${version}/"
echo checking for: $user_overlay_location
if [ -e $user_overlay_location ]; then
echo "Found."
echo "Updating user's catalog with $user_overlay_location"
user_catalog_tmp=$(mktemp)
jq -r ".\"$language\".\"$targetname\".\"$version\".\"overlay_path\"=\"$user_overlay_location\"" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
# user catalog now contains path to this kernel's main R library.
echo "Done."
echo ""
echo "Be sure to call \"icrn_manager kernels use $language $targetname $version\" to begin using this kernel in R."
return 0
else
echo "ERROR: Could not register the overlay location."
return 1
fi
}
# Identify and register the R library location for an R kernel in the user catalog.
#
# This function determines the main library path of an R kernel installation by
# executing Rscript to query the library paths. It then updates the user catalog
# with the absolute path to the R library directory.
#
# Parameters:
# $1 - target_unpacked: Path to the unpacked R kernel conda environment
# $2 - language: Language of the kernel (should be "R")
# $3 - targetname: Name of the kernel
# $4 - version: Version number of the kernel
#
# Returns:
# 0 if R library path was successfully registered, 1 if conda environment not found
#
# Side effects:
# - Executes Rscript to determine library paths
# - Updates the user catalog JSON file with the absolute_path field
function register_r_library_in_user_catalog() # without unpacking, identify R kernel library location
{
local target_unpacked=$1; shift
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
# echo checking for: $target_unpacked"/bin/activate"
# if [ -e $target_unpacked"/bin/activate" ]; then
echo checking for: $target_unpacked"/conda-meta"
if [ -d $target_unpacked"/conda-meta" ]; then
# WARNING: this is weak - relies on preparer and environment ensuring this is top slot
# --vanilla ensures that we aren't interpreting an existing kernel-fu environment variable
# "R_HOME=''" ensures we don't get complaints from R that R_HOME is set, but we're calling a Rscript that isn't located there
# we want to get a very plain readout of where this R install's main kernel is.
echo "getting R path."
target_kernel_path=$(R_LIBS='' R_HOME='' R_LIBS_USER='' R_LIBS_SITE='' $target_unpacked/bin/Rscript --vanilla -e 'cat(.libPaths()[1])')
echo "determined: $target_kernel_path"
echo "Updating user's catalog with $target_kernel_path"
user_catalog_tmp=$(mktemp)
jq -r ".\"$language\".\"$targetname\".\"$version\"={\"absolute_path\":\"$target_kernel_path\"}" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
# user catalog now contains path to this kernel's main R library.
echo "Done."
echo ""
echo "Be sure to call \"icrn_manager kernels use $language $targetname $version\" to begin using this kernel in R."
return 0
else
# echo "ERROR: Could not find conda environment activation script at $target_unpacked/bin/activate"
echo "ERROR: Could not confirm target is a conda environment via existence of $target_unpacked/conda-meta"
return 1
fi
}
# Register the Python kernel environment path in the user catalog.
#
# This function updates the user catalog with the absolute path to a Python kernel's
# conda environment. The environment must have a bin/activate script to be recognized
# as a valid conda environment.
#
# Parameters:
# $1 - target_unpacked: Path to the unpacked Python kernel conda environment
# $2 - language: Language of the kernel (should be "Python")
# $3 - targetname: Name of the kernel
# $4 - version: Version number of the kernel
#
# Returns:
# 0 if Python environment path was successfully registered, 1 if activation script not found
#
# Side effects:
# Updates the user catalog JSON file with the absolute_path field
function register_python_library_in_user_catalog() # unpack and configure a Python kernel environment
{
local target_unpacked=$1; shift
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
echo checking for: $target_unpacked"/bin/activate"
if [ -e $target_unpacked"/bin/activate" ]; then
# presence of $target_unpacked"/bin/activate" indicates this is a conda environment as expected
echo "Updating user's catalog with $language $targetname and $version"
user_catalog_tmp=$(mktemp)
jq -r ".\"$language\".\"$targetname\".\"$version\"={\"absolute_path\":\"$target_unpacked\"}" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
echo "Done."
echo ""
echo "Be sure to call \"icrn_manager kernels use $language $targetname $version\" to begin using this kernel in Python."
return 0
else
echo "ERROR: Could not find conda environment activation script at $target_unpacked/bin/activate"
return 1
fi
}
# Alias for kernels__get_in_place() - check out a kernel from the central repository.
#
# This is a convenience function that calls kernels__get_in_place() with all passed arguments.
#
# Parameters:
# All arguments are passed through to kernels__get_in_place()
#
# Returns:
# Same as kernels__get_in_place()
function kernels__get() # alias for get in place
{
"kernels__get_in_place" "$@"
}
# Check out a kernel from the central repository without relocating it.
#
# This function retrieves a kernel from the central repository and registers it in the
# user catalog. The kernel remains in its original location in the central repository.
# For R kernels, it also creates an overlay directory for user-specific packages.
# The function validates input parameters to prevent path traversal and wildcard attacks.
#
# Parameters:
# $1 - language: Language of the kernel (e.g., "R", "Python")
# $2 - targetname: Name of the kernel to check out
# $3 - version: Version number of the kernel
#
# Returns:
# Exits with status 1 if:
# - Parameters are missing or invalid
# - Invalid characters detected in kernel name or version (security check)
# - Kernel not found in central catalog
# - Target environment location not found
# - Security violation detected (path would escape intended directory)
#
# Side effects:
# - Creates overlay directory for R kernels
# - Updates user catalog with kernel paths
# - Validates input to prevent security vulnerabilities
function kernels__get_in_place() # prep for 'use' without relocating kernel
{
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
# ensure we get a uc-first label for lang
language="$(tr '[:lower:]' '[:upper:]' <<< ${language:0:1})${language:1}"
# Validate input parameters to prevent path traversal and wildcard attacks
if [[ "$targetname" =~ [\]\/\[\*\?\\] ]] || [[ "$version" =~ [\]\/\[\*\?\\] ]]; then
echo "Error: Invalid characters in kernel name or version. Cannot contain wildcards (*?[]) or path separators (/)"
exit 1
fi
if [ -z $version ] || [ -z $targetname ] || [ -z $language ]; then
echo "usage: icrn_manager kernels get <language> <kernel name> <version number>"
help
exit 1
else
echo "Desired kernel:"
echo "Language: "$language
echo "Kernel: "$targetname
echo "Version: "$version
fi
icrn_catalog=${ICRN_KERNEL_CATALOG}
user_catalog=${ICRN_USER_CATALOG}
echo ""
echo "ICRN Catalog:"
echo $icrn_catalog
echo "User Catalog:"
echo $user_catalog
echo ""
# get the target file from the ICRN catalog
# target_file=$(jq -r ".$language.$targetname.\"$version\".\"conda-pack\"" $icrn_catalog)
target_location=$(jq -r ".$language.$targetname.\"$version\".\"environment_location\"" $icrn_catalog)
if [ ! "$target_location" = "null" ]; then
# language, targetname, and version specify the path for a conda-activate command
# language, targetname, and version also specify the info for the overlay directory creation
# we need to get the R-path needed and register it in the user's config
# we need to get the users overlay library, and register it in the user's config
if [ -e $target_location ]; then
# identify overlay library location, make it if it doesn't exist
# what to do if it DOES exist? - nothing, i think.
# Create language-specific subdirectory structure
language_lower=$(echo "$language" | tr '[:upper:]' '[:lower:]')
user_overlay_location="${ICRN_USER_KERNEL_BASE}/${language_lower}/${targetname}-${version}/"
# Safety check: ensure the path is within the intended directory
if [[ "$user_overlay_location" != "$ICRN_USER_KERNEL_BASE"* ]]; then
echo "Error: Security violation - target path would escape intended directory"
echo "Target: $user_overlay_location"
echo "Base: $ICRN_USER_KERNEL_BASE"
exit 1
fi
if [ ! -d "$user_overlay_location" ]; then
echo "Making target directory: $user_overlay_location"
mkdir -p "$user_overlay_location"
else
echo "NOTICE: target directory: $user_overlay_location already exists."
fi
# Use language-specific unpacking function
case $language in
"R")
echo "registering R library"
register_r_library_in_user_catalog "$target_location" "$language" "$targetname" "$version"
echo "registering user overlay"
if ! register_user_overlay_in_user_catalog "$language" "$targetname" "$version"; then
echo "ERROR: Failed to register user overlay for $language $targetname $version"
echo "Please ensure ${ICRN_USER_KERNEL_BASE} is writable and retry the checkout."
exit 1
fi
;;
"Python")
register_python_library_in_user_catalog "$target_location" "$language" "$targetname" "$version"
;;
*)
echo "ERROR: Unsupported language '$language' for kernel unpacking"
echo "Supported languages: R, Python"
exit 1
;;
esac
else
echo "ERROR: could not find target environment location: $target_location"
exit 1
fi
else
echo "ERROR: could not find target kernel to get"
get_versions_for_package "$icrn_catalog" "$language" "$targetname"
exit 1
fi
}
# Update a user's copy of a kernel from the central repository.
#
# This function is currently not implemented. It is intended to update an existing
# checked-out kernel to a newer version or refresh it from the central repository.
#
# unclear this will be required under new approach of non-relocation of central kernels
# perhaps re-point to newer version of central kernel, and update R-packages?
# low on to-do list
#
# Parameters:
# (To be determined when implemented)
#
# Returns:
# Currently exits with status 1 (not implemented)
#
# Side effects:
# None (function not yet implemented)
function kernels__update() # update users copy of a kernel from central repo
{
echo "entered 'update' subcommand"
echo "method not yet implemented."
exit 1
}
# Remove a kernel entry from the user's catalog.
#
# This function removes a kernel entry from the user catalog. If a version is specified,
# only that version is removed. If no version is specified, all versions of the kernel
# are removed. If removing a version leaves no versions for a kernel, the entire
# kernel entry is removed from the catalog.
#
# Parameters:
# $1 - language: Language of the kernel (e.g., "R", "Python")
# $2 - targetname: Name of the kernel to remove
# $3 - version: Optional version number. If omitted, all versions are removed
#
# Returns:
# Exits with status 1 if:
# - Required parameters are missing
# - Kernel not found in user catalog
# - Specified version not found in user catalog
#
# Side effects:
# - Updates the user catalog JSON file by removing the specified entry
# - Removes empty kernel entries if all versions are removed
function kernels__clean() # remove a kernel entry from the users catalog
{
local language=$1; shift
local targetname=$1; shift
local version=$1; shift
icrn_catalog=${ICRN_KERNEL_CATALOG}
user_catalog=${ICRN_USER_CATALOG}
echo ""
echo "ICRN Catalog:"
echo $icrn_catalog
echo "User Catalog:"
echo $user_catalog
echo ""
if [ -z "$version" ] && [ -z "$targetname" ] && [ -z "$language" ]; then
echo "usage: icrn_manager kernels clean <language> <kernel name> <version number>"
help
exit 1
else
echo "Desired kernel to scrub from user catalog:"
echo "Language: "$language
echo "Kernel: "$targetname
echo "Version: "$version
echo ""
fi
check_for_catalog_entry "$user_catalog" "$language" "$targetname"
if [ $last_check = 0 ]; then
echo "$targetname not present in user catalog at $user_catalog"
exit 1
else
last_check=-1
fi
if [ -z "$version" ]; then
user_catalog_tmp=$(mktemp) && \
jq -r "del(.\"$language\".\"$targetname\")" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
else
check_for_catalog_entry "$user_catalog" "$language" "$targetname" "$version"
if [ $last_check = 0 ]; then
echo "$version for $targetname not present in user catalog at $user_catalog"
get_versions_for_package $user_catalog $language $targetname
exit 1
else
last_check=-1
fi
user_catalog_tmp=$(mktemp) && \
jq -r "del(.\"$language\".\"$targetname\".\"$version\")" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
if [ $(jq -r ".\"$language\".\"$targetname\"" "$user_catalog") = "{}" ]; then
# if the removal of that version of $targetname results in there being no versions of targetname, remove the entire key.
user_catalog_tmp=$(mktemp) && \
jq -r "del(.\"$language\".\"$targetname\")" "$user_catalog" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "$user_catalog"
fi
fi
}
# Initialize the ICRN Manager by creating necessary directories and configuration files.
#
# This function sets up the initial environment for ICRN Manager, creating:
# - User base directory (~/.icrn/)
# - Kernel base directory (~/.icrn/icrn_kernels/)
# - Language-specific subdirectories (r/, python/)
# - User catalog JSON file
# - Manager configuration JSON file
#
# It also validates that the central repository and its components exist.
#
# Parameters:
# $1 - central_repository: Optional path to the central kernel repository.
# If not provided, uses the default path (/sw/icrn/jupyter/icrn_ncsa_resources/Kernels)
#
# Returns:
# No return value
#
# Side effects:
# - Creates directory structure in user's home directory
# - Creates and populates configuration files
# - Updates existing configuration if central_repository is provided
# - Prints warnings if central repository components are not found
function kernels__init() # create base resources
{
echo "Initializing icrn kernel resources..."
local central_repository=$1; shift
overwrite=""
if [ -z $central_repository ]; then
central_repository=${central_catalog_default}
else
echo "will overwrite location"
overwrite="yes"
fi
echo ""
echo "central catalog location will be: ${central_repository}"
echo ""
# Determine which paths will be affected
ICRN_MANAGER_CONFIG=${ICRN_MANAGER_CONFIG:-${ICRN_USER_BASE}/manager_config.json}
echo "The following paths will be created or modified:"
echo ""
local paths_to_create=()
local paths_to_overwrite=()
# Check ICRN_USER_BASE
if [ ! -e "${ICRN_USER_BASE}/" ]; then
paths_to_create+=("${ICRN_USER_BASE}/ (directory)")
fi
# Check ICRN_USER_KERNEL_BASE
if [ ! -e "${ICRN_USER_KERNEL_BASE}" ]; then
paths_to_create+=("${ICRN_USER_KERNEL_BASE} (directory)")
fi
# Check language-specific subdirectories
if [ ! -e "${ICRN_USER_KERNEL_BASE}/r" ]; then
paths_to_create+=("${ICRN_USER_KERNEL_BASE}/r (directory)")
fi
if [ ! -e "${ICRN_USER_KERNEL_BASE}/python" ]; then
paths_to_create+=("${ICRN_USER_KERNEL_BASE}/python (directory)")
fi
# Check ICRN_USER_CATALOG
if [ ! -e "${ICRN_USER_CATALOG}" ]; then
paths_to_create+=("${ICRN_USER_CATALOG} (file)")
fi
# Check ICRN_MANAGER_CONFIG
if [ ! -e "${ICRN_MANAGER_CONFIG}" ]; then
paths_to_create+=("${ICRN_MANAGER_CONFIG} (file)")
elif [ -n "$overwrite" ]; then
paths_to_overwrite+=("${ICRN_MANAGER_CONFIG} (file - will update central catalog path)")
fi
# Display paths that will be created
if [ ${#paths_to_create[@]} -gt 0 ]; then
echo "Paths that will be CREATED:"
for path in "${paths_to_create[@]}"; do
echo " - $path"
done
echo ""
fi
# Display paths that will be overwritten/modified
if [ ${#paths_to_overwrite[@]} -gt 0 ]; then
echo "Paths that will be MODIFIED:"
for path in "${paths_to_overwrite[@]}"; do
echo " - $path"
done
echo ""
fi
# If nothing will be created or modified, inform user
if [ ${#paths_to_create[@]} -eq 0 ] && [ ${#paths_to_overwrite[@]} -eq 0 ]; then
echo "All required paths already exist. No changes will be made."
echo ""
return 0
fi
# Ask for confirmation
read -r -p "Do you want to proceed with these changes? [y/N] " response
if [[ ! "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
echo "Initialization cancelled."
exit 0
fi
echo ""
# check for existence of
#~{HOME}/.icrn/
#~{HOME}/.icrn/icrn_kernels/
#~{HOME}/.icrn/user_catalog.json
echo "Checking for user resources, and creating them if they don't exist..."
if [ ! -e ${ICRN_USER_BASE}/ ]; then
echo "creating ${ICRN_USER_BASE}/"
mkdir -p ${ICRN_USER_BASE}
else
echo "base icrn directory exists at ${ICRN_USER_BASE}/"
fi
if [ ! -e ${ICRN_USER_KERNEL_BASE} ]; then
echo "creating ${ICRN_USER_KERNEL_BASE}"
mkdir -p ${ICRN_USER_KERNEL_BASE}
else
echo "base icrn kernel exists at ${ICRN_USER_KERNEL_BASE}"
fi
# Create language-specific subdirectories
if [ ! -e ${ICRN_USER_KERNEL_BASE}/r ]; then
echo "creating ${ICRN_USER_KERNEL_BASE}/r"
mkdir -p ${ICRN_USER_KERNEL_BASE}/r
else
echo "R kernel directory exists at ${ICRN_USER_KERNEL_BASE}/r"
fi
if [ ! -e ${ICRN_USER_KERNEL_BASE}/python ]; then
echo "creating ${ICRN_USER_KERNEL_BASE}/python"
mkdir -p ${ICRN_USER_KERNEL_BASE}/python
else
echo "Python kernel directory exists at ${ICRN_USER_KERNEL_BASE}/python"
fi
if [ ! -e ${ICRN_USER_CATALOG} ]; then
echo "creating ${ICRN_USER_CATALOG}"
echo "{}" > ${ICRN_USER_CATALOG}
else
echo "base icrn user catalog exists at ${ICRN_USER_CATALOG}"
fi
# Manager config is json, holds location of the central repo (for now), and sub-paths
# user calls ./icrn_manager kernels init <path to central repo>
# or omits path, and central repo is defaulted to value above
# regardless, config must be written in the user's ICRN location for future reference
# user may edit config to repoint to new central repo
ICRN_MANAGER_CONFIG=${ICRN_MANAGER_CONFIG:-${ICRN_USER_BASE}/manager_config.json}
if [ ! -e ${ICRN_MANAGER_CONFIG} ]; then
echo "creating ${ICRN_MANAGER_CONFIG}"
echo "{
\"icrn_central_catalog_path\": \"${central_repository}\",
\"icrn_r_kernels\": \"R\",
\"icrn_python_kernels\": \"Python\",
\"icrn_kernel_catalog\": \"icrn_kernel_catalog.json\"
}" > $ICRN_MANAGER_CONFIG
# non-append enables re-pointing of central repo via 'init' later
else
echo "Configuration for manager exists at ${ICRN_MANAGER_CONFIG}"
fi
echo ""
if [ -n "$overwrite" ]; then
echo "Updating location of central catalog to: $central_repository"
user_catalog_tmp=$(mktemp)
jq -r ".\"icrn_central_catalog_path\"=\"$central_repository\"" "${ICRN_MANAGER_CONFIG}" > "$user_catalog_tmp" && mv "$user_catalog_tmp" "${ICRN_MANAGER_CONFIG}"
fi
echo ""
ICRN_KERNEL_REPOSITORY=$(jq -r ".\"icrn_central_catalog_path\"" "${ICRN_MANAGER_CONFIG}")
ICRN_R_KERNELS=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_r_kernels\"" "${ICRN_MANAGER_CONFIG}")
ICRN_PYTHON_KERNELS=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_python_kernels\"" "${ICRN_MANAGER_CONFIG}")
ICRN_KERNEL_CATALOG=${ICRN_KERNEL_REPOSITORY}"/"$(jq -r ".\"icrn_kernel_catalog\"" "${ICRN_MANAGER_CONFIG}")
echo "Checking for ICRN resources..."
if [ ! -e ${ICRN_KERNEL_REPOSITORY} ]; then
echo "Warning: Cannot find core kernel base directory at: $ICRN_KERNEL_REPOSITORY"
else
echo "Found core kernel base directory: $ICRN_KERNEL_REPOSITORY"
fi
if [ ! -e ${ICRN_R_KERNELS} ]; then
echo "Warning: Cannot find core kernel R root at: $ICRN_R_KERNELS"
else
echo "Found core kernel R root: $ICRN_R_KERNELS"