forked from SAP/cf-cli-java-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcf_cli_java_plugin.go
More file actions
1312 lines (1204 loc) · 52.2 KB
/
cf_cli_java_plugin.go
File metadata and controls
1312 lines (1204 loc) · 52.2 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
/*
* Copyright (c) 2024 SAP SE or an SAP affiliate company. All rights reserved.
* This file is licensed under the Apache Software License, v. 2 except as noted
* otherwise in the LICENSE file at the root of the repository.
*/
// Package main implements a CF CLI plugin for Java applications, providing commands
// for heap dumps, thread dumps, profiling, and other Java diagnostics.
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"code.cloudfoundry.org/cli/cf/terminal"
"code.cloudfoundry.org/cli/cf/trace"
"code.cloudfoundry.org/cli/plugin"
"cf.plugin.ref/requires/utils"
"github.com/simonleung8/flags"
)
// Assert that JavaPlugin implements plugin.Plugin.
var _ plugin.Plugin = (*JavaPlugin)(nil)
// JavaPlugin is a CF CLI plugin that supports taking heap and thread dumps on demand
type JavaPlugin struct {
verbose bool
}
// logVerbosef logs a message with a format string if verbose mode is enabled
func (c *JavaPlugin) logVerbosef(format string, args ...any) {
if c.verbose {
fmt.Printf("[VERBOSE] "+format+"\n", args...)
}
}
// InvalidUsageError indicates that the arguments passed as input to the command are invalid
type InvalidUsageError struct {
message string
}
func (e InvalidUsageError) Error() string {
return e.message
}
func isSSHConnectivityError(errorOutput string, err error) bool {
if err == nil {
return false
}
combined := strings.ToLower(err.Error() + " " + errorOutput)
patterns := []string{
"ssh not enabled",
"connection refused",
"connection reset",
"permission denied",
"authentication failed",
"handshake failed",
"one time auth code",
"timeout",
"deadline exceeded",
"specified application instance does not exist",
"of process web not found",
"of process web not running",
}
for _, pattern := range patterns {
if strings.Contains(combined, pattern) {
return true
}
}
return false
}
// wrapSSHError analyzes SSH error messages and provides user-friendly explanations.
func wrapSSHError(appName string, errorOutput string, err error) string {
errStr := err.Error() + " " + errorOutput
errStrLower := strings.ToLower(errStr)
if strings.Contains(errStrLower, "specified application instance does not exist") ||
strings.Contains(errStrLower, "of process web not found") ||
strings.Contains(errStrLower, "of process web not running") {
return fmt.Sprintf(
"Cannot connect to app '%s' via SSH because the requested application instance is not available.\n"+
"Verify the instance index with: cf app %s\n"+
"Technical details: %v",
appName,
appName,
err,
)
}
if strings.Contains(errStrLower, "connection refused") ||
strings.Contains(errStrLower, "connection reset") ||
strings.Contains(errStrLower, "ssh not enabled") {
return fmt.Sprintf(
"Cannot connect to app '%s' via SSH.\n"+
"Possible causes and solutions:\n"+
"1. SSH may not be enabled on the application. Try:\n"+
" cf enable-ssh %s\n"+
" cf restart %s\n"+
"2. Check your network connection and firewall settings.\n"+
"3. Verify the application is running: cf app %s\n"+
"Technical details: %v",
appName,
appName,
appName,
appName,
err,
)
}
if strings.Contains(errStrLower, "permission denied") ||
strings.Contains(errStrLower, "authentication failed") ||
strings.Contains(errStrLower, "one time auth code") ||
strings.Contains(errStrLower, "handshake failed") {
return fmt.Sprintf(
"SSH authentication failed for app '%s'.\n"+
"This may indicate:\n"+
"1. You are not logged in to Cloud Foundry. Try: cf login\n"+
"2. Your CF credentials have expired. Try: cf logout && cf login\n"+
"3. You don't have permissions for this app.\n"+
"Technical details: %v",
appName,
err,
)
}
if strings.Contains(errStrLower, "timeout") ||
strings.Contains(errStrLower, "deadline exceeded") {
return fmt.Sprintf(
"SSH connection to app '%s' timed out.\n"+
"This may indicate:\n"+
"1. Slow network or high latency\n"+
"2. Cloud Foundry platform is experiencing issues\n"+
"3. Firewall or proxy is blocking the connection\n"+
"Try again, or contact your Cloud Foundry administrator if this persists.",
appName,
)
}
return fmt.Sprintf(
"SSH command failed while connecting to app '%s'.\n"+
"Details: %v\n"+
"Output: %s\n"+
"To debug, try manually: cf ssh %s -c 'echo ok'",
appName,
err,
errorOutput,
appName,
)
}
// checkSSHConnectivity tests whether the app is reachable via SSH before running the main command.
func (c *JavaPlugin) checkSSHConnectivity(appName string, appInstanceIndex int) error {
testArgs := []string{"ssh", appName}
if appInstanceIndex >= 0 {
testArgs = append(testArgs, "--app-instance-index", strconv.Itoa(appInstanceIndex))
}
testArgs = append(testArgs, "-c", "echo ok")
c.logVerbosef("Checking SSH connectivity to app '%s'", appName)
cmd := exec.Command("cf", testArgs...)
output, err := cmd.CombinedOutput()
if err != nil {
c.logVerbosef("SSH connectivity check failed: %v", err)
return fmt.Errorf("%s", wrapSSHError(appName, string(output), err))
}
c.logVerbosef("SSH connectivity check succeeded")
return nil
}
// Options holds all command-line options for the Java plugin
type Options struct {
AppInstanceIndex int
Keep bool
NoDownload bool
DryRun bool
Verbose bool
Full bool
ContainerDir string
LocalDir string
Args string
}
// FlagDefinition holds metadata for a command-line flag
type FlagDefinition struct {
Name string
ShortName string
Usage string
Description string // Longer description for help text
Type string
DefaultInt int
}
// flagDefinitions contains all flag definitions in a centralized location
var flagDefinitions = []FlagDefinition{
{
Name: "app-instance-index",
ShortName: "i",
Usage: "application `instance` to connect to",
Description: "select to which instance of the app to connect",
Type: "int",
DefaultInt: -1,
},
{
Name: "keep",
ShortName: "k",
Usage: "whether to `keep` the heap-dump/JFR/... files on the container of the application instance after having downloaded it locally",
Description: "keep the heap dump in the container; by default the heap dump/JFR/... will be deleted from the container's filesystem after being downloaded",
Type: "bool",
},
{
Name: "no-download",
ShortName: "nd",
Usage: "do not download the heap-dump/JFR/... file to the local machine",
Description: "don't download the heap dump/JFR/... file to local, only keep it in the container, implies '--keep'",
Type: "bool",
},
{
Name: "dry-run",
ShortName: "n",
Usage: "triggers the `dry-run` mode to show only the cf-ssh command that would have been executed",
Description: "just output to command line what would be executed",
Type: "bool",
},
{
Name: "verbose",
ShortName: "v",
Usage: "enable verbose output for the plugin",
Description: "enable verbose output for the plugin",
Type: "bool",
},
{
Name: "container-dir",
ShortName: "cd",
Usage: "specify the folder path where the dump/JFR/... file should be stored in the container",
Description: "the directory path in the container that the heap dump/JFR/... file will be saved to",
Type: "string",
},
{
Name: "local-dir",
ShortName: "ld",
Usage: "specify the folder where the dump/JFR/... file will be downloaded to, defaults to the current directory",
Description: "the local directory path that the dump/JFR/... file will be saved to, defaults to the current directory",
Type: "string",
},
{
Name: "full",
ShortName: "f",
Usage: "enable `full` mode for more comprehensive analysis (status and record-status commands)",
Description: "enable full mode for more comprehensive JVM analysis (only for status and record-status)",
Type: "bool",
},
{
Name: "args",
ShortName: "a",
Usage: "Miscellaneous arguments to pass to the command in the container, be aware to end it with a space if it is a simple option",
Description: "Miscellaneous arguments to pass to the command (if supported) in the container, be aware to end it with a space if it is a simple option. For commands that create arbitrary files (jcmd, asprof), the environment variables @FSPATH, @ARGS, @APP_NAME, @FILE_NAME, and @STATIC_FILE_NAME are available in --args to reference the working directory path, arguments, application name, and generated file name respectively.",
Type: "string",
},
}
func (c *JavaPlugin) createOptionsParser() flags.FlagContext {
commandFlags := flags.New()
// Create flags from centralized definitions
for _, flagDef := range flagDefinitions {
switch flagDef.Type {
case "int":
commandFlags.NewIntFlagWithDefault(flagDef.Name, flagDef.ShortName, flagDef.Usage, flagDef.DefaultInt)
case "bool":
commandFlags.NewBoolFlag(flagDef.Name, flagDef.ShortName, flagDef.Usage)
case "string":
commandFlags.NewStringFlag(flagDef.Name, flagDef.ShortName, flagDef.Usage)
}
}
return commandFlags
}
// parseOptions creates and parses command-line flags, returning the Options struct
func (c *JavaPlugin) parseOptions(args []string) (*Options, []string, error) {
commandFlags := c.createOptionsParser()
parseErr := commandFlags.Parse(args...)
if parseErr != nil {
return nil, nil, parseErr
}
appInstanceIndex := commandFlags.Int("app-instance-index")
appInstanceIndexSet := commandFlags.IsSet("app-instance-index")
keep := commandFlags.IsSet("keep")
noDownload := commandFlags.IsSet("no-download")
// Validate: contradictory flags
if keep && noDownload {
return nil, nil, &InvalidUsageError{
message: "Error: flags '--keep' and '--no-download' are contradictory. Use '--no-download' to keep remote file without downloading, or '--keep' to download and keep a copy remote.",
}
}
// Validate: instance index must be non-negative
if appInstanceIndexSet && appInstanceIndex < 0 {
return nil, nil, &InvalidUsageError{
message: fmt.Sprintf("Error: app instance index must be non-negative, got %d", appInstanceIndex),
}
}
// Validate: instance index should not be excessively large (sanity check)
if appInstanceIndex > 9999 {
return nil, nil, &InvalidUsageError{
message: fmt.Sprintf("Error: app instance index is unreasonably large (%d). Cloud Foundry applications typically have fewer than 100 instances.", appInstanceIndex),
}
}
options := &Options{
AppInstanceIndex: appInstanceIndex,
Keep: keep,
NoDownload: noDownload,
DryRun: commandFlags.IsSet("dry-run"),
Verbose: commandFlags.IsSet("verbose"),
Full: commandFlags.IsSet("full"),
ContainerDir: commandFlags.String("container-dir"),
LocalDir: commandFlags.String("local-dir"),
Args: commandFlags.String("args"),
}
return options, commandFlags.Args(), nil
}
// generateOptionsMapFromFlags creates the options map for plugin metadata
func (c *JavaPlugin) generateOptionsMapFromFlags() map[string]string {
options := make(map[string]string)
// Generate options from the centralized flag definitions
for _, flagDef := range flagDefinitions {
// Create the prefix for the flag (short name with appropriate formatting)
prefix := "-" + flagDef.ShortName
if flagDef.Name == "app-instance-index" {
prefix += " [index]"
}
prefix += ", "
// Use the Description field for detailed help text
options[flagDef.Name] = utils.WrapTextWithPrefix(flagDef.Description, prefix, 80, 27)
}
return options
}
const (
// JavaDetectionCommand is the prologue command to detect if the Garden container contains a Java app.
JavaDetectionCommand = "if ! pgrep -x \"java\" > /dev/null; then echo \"No 'java' process found running. Are you sure this is a Java app?\" >&2; exit 1; fi"
CheckNoCurrentJFRRecordingCommand = `OUTPUT=$($JCMD_COMMAND $(pidof java) JFR.check 2>&1); if [[ ! "$OUTPUT" == *"No available recording"* ]]; then echo "JFR recording already running. Stop it before starting a new recording."; exit 1; fi;`
FilterJCMDRemoteMessage = `filter_jcmd_remote_message() {
if command -v grep >/dev/null 2>&1; then
grep -v -e "Connected to remote JVM" -e "JVM response code = 0"
else
cat # fallback: just pass through the input unchanged
fi
};`
)
// Run must be implemented by any plugin because it is part of the
// plugin interface defined by the core CLI.
//
// Run(...) is the entry point when the core CLI is invoking a command defined
// by a plugin. The first parameter, plugin.CliConnection, is a struct that can
// be used to invoke CLI commands. The second parameter, args, is a slice of
// strings. args[0] will be the name of the command, and will be followed by
// any additional arguments a CLI user typed in.
//
// Any error handling should be handled within the plugin itself (this means printing
// user-facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
// 1 should the plugin exit nonzero.
func (c *JavaPlugin) Run(cliConnection plugin.CliConnection, args []string) {
// Check if verbose flag is in args for early logging
// Note: -v is reserved by CF CLI (enables CF_TRACE). Only --verbose works.
for _, arg := range args {
if arg == "--verbose" {
c.verbose = true
break
}
}
c.logVerbosef("Run called with args: %v", args)
_, err := c.DoRun(cliConnection, args)
if err != nil {
c.logVerbosef("Error occurred: %v", err)
os.Exit(1)
}
c.logVerbosef("Run completed successfully")
}
// DoRun is an internal method used to wrap the cmd package with CommandExecutor for test purposes
func (c *JavaPlugin) DoRun(cliConnection plugin.CliConnection, args []string) (string, error) {
traceLogger := trace.NewLogger(os.Stdout, true, os.Getenv("CF_TRACE"), "")
ui := terminal.NewUI(os.Stdin, os.Stdout, terminal.NewTeePrinter(os.Stdout), traceLogger)
c.logVerbosef("DoRun called with args: %v", args)
output, err := c.execute(cliConnection, args)
if err != nil {
if err.Error() == "unexpected EOF" {
return output, err
}
ui.Failed(err.Error())
var invalidUsageErr *InvalidUsageError
if errors.As(err, &invalidUsageErr) {
fmt.Println()
fmt.Println()
err := exec.Command("cf", "help", "java").Run()
if err != nil {
ui.Failed("Failed to show help")
}
}
} else if output != "" {
ui.Say(output)
}
return output, err
}
type Command struct {
Name string
Description string
OnlyOnRecentSapMachine bool
// Required tools, checked and $TOOL_COMMAND set in the remote command
// jcmd is special: it uses asprof if available
RequiredTools []string
GenerateFiles bool
NeedsFileName bool
// Use @ prefix to avoid shell expansion issues, replaced directly in Go code
// use @FILE_NAME to get the generated file name with a random UUID,
// @STATIC_FILE_NAME without, and @FSPATH to get the path where the file is stored (for GenerateArbitraryFiles commands)
SSHCommand string
FilePattern string
FileExtension string
FileLabel string
FileNamePart string
// Run the command in a subfolder of the container
GenerateArbitraryFiles bool
GenerateArbitraryFilesFolderName string
// IsLocal indicates the command runs locally (not via SSH)
IsLocal bool
// AcceptsTrailingArgs indicates the command accepts positional arguments after the app name
AcceptsTrailingArgs bool
// SupportFullOption indicates the command supports the --full flag
SupportFullOption bool
}
// HasMiscArgs checks whether the SSHCommand contains @ARGS
func (c *Command) HasMiscArgs() bool {
return strings.Contains(c.SSHCommand, "@ARGS")
}
// replaceVariables replaces @-prefixed variables in the command with actual values.
// Returns the processed command string and an error if validation fails.
func (c *JavaPlugin) replaceVariables(command, appName, fspath, fileName, staticFileName, args string) (string, error) {
// Validate: @ARGS cannot contain itself, other variables cannot contain any @ variables
if strings.Contains(args, "@ARGS") {
return "", fmt.Errorf("invalid variable reference: @ARGS cannot contain itself")
}
for varName, value := range map[string]string{"@APP_NAME": appName, "@FSPATH": fspath, "@FILE_NAME": fileName, "@STATIC_FILE_NAME": staticFileName} {
if strings.Contains(value, "@") {
return "", fmt.Errorf("invalid variable reference: %s cannot contain @ variables", varName)
}
}
// First, replace variables within @ARGS value itself
processedArgs := args
processedArgs = strings.ReplaceAll(processedArgs, "@APP_NAME", appName)
processedArgs = strings.ReplaceAll(processedArgs, "@FSPATH", fspath)
processedArgs = strings.ReplaceAll(processedArgs, "@FILE_NAME", fileName)
processedArgs = strings.ReplaceAll(processedArgs, "@STATIC_FILE_NAME", staticFileName)
// Then replace all variables in the command template
result := command
result = strings.ReplaceAll(result, "@APP_NAME", appName)
result = strings.ReplaceAll(result, "@FSPATH", fspath)
result = strings.ReplaceAll(result, "@FILE_NAME", fileName)
result = strings.ReplaceAll(result, "@STATIC_FILE_NAME", staticFileName)
result = strings.ReplaceAll(result, "@ARGS", processedArgs)
return result, nil
}
var commands = []Command{
{
Name: "heap-dump",
Description: "Generate a heap dump from a running Java application",
GenerateFiles: true,
FileExtension: ".hprof",
/*
If there is not enough space on the filesystem to write the dump, jmap will create a file
with size 0, output something about not enough space left on the device, and exit with status code 0.
Because YOLO.
Also: if the heap dump file already exists, jmap will output something about the file already
existing and exit with status code 0. At least it is consistent.
OpenJDK: Wrap everything in an if statement in case jmap is available
*/
SSHCommand: `if [ -f @FILE_NAME ]; then echo >&2 'Heap dump @FILE_NAME already exists'; exit 1; fi
JMAP_COMMAND=$(find -executable -name jmap | head -1 | tr -d [:space:])
# SAP JVM: Wrap everything in an if statement in case jvmmon is available
JVMMON_COMMAND=$(find -executable -name jvmmon | head -1 | tr -d [:space:])
# if we have neither jmap nor jvmmon, we cannot generate a heap dump and should exit with an error
if [ -z "${JMAP_COMMAND}" ] && [ -z "${JVMMON_COMMAND}" ]; then
echo >&2 "jvmmon or jmap are required for generating heap dump, you can modify your application manifest.yaml on the 'JBP_CONFIG_OPEN_JDK_JRE' environment variable. This could be done like this:
---
applications:
- name: <APP_NAME>
memory: 1G
path: <PATH_TO_BUILD_ARTIFACT>
buildpack: https://github.com/cloudfoundry/java-buildpack
env:
JBP_CONFIG_OPEN_JDK_JRE: '{ jre: { repository_root: "https://java-buildpack.cloudfoundry.org/openjdk-jdk/jammy/x86_64", version: 21.+ } }'
"
exit 1
fi
if [ -n "${JMAP_COMMAND}" ]; then
OUTPUT=$( ${JMAP_COMMAND} -dump:format=b,file=@FILE_NAME $(pidof java) ) || STATUS_CODE=$?
if [ ! -s @FILE_NAME ]; then echo >&2 ${OUTPUT}; exit 1; fi
if [ ${STATUS_CODE:-0} -gt 0 ]; then echo >&2 ${OUTPUT}; exit ${STATUS_CODE}; fi
elif [ -n "${JVMMON_COMMAND}" ]; then
echo -e 'change command line flag flags=-XX:HeapDumpOnDemandPath=@FSPATH\ndump heap' > setHeapDumpOnDemandPath.sh
OUTPUT=$( ${JVMMON_COMMAND} -pid $(pidof java) -cmd "setHeapDumpOnDemandPath.sh" ) || STATUS_CODE=$?
sleep 5 # Writing the heap dump is triggered asynchronously -> give the JVM some time to create the file
HEAP_DUMP_NAME=$(find @FSPATH -name 'java_pid*.hprof' -printf '%T@ %p\0' | sort -zk 1nr | sed -z 's/^[^ ]* //' | tr '\0' '\n' | head -n 1)
SIZE=-1; OLD_SIZE=$(stat -c '%s' "${HEAP_DUMP_NAME}"); while [ ${SIZE} != ${OLD_SIZE} ]; do OLD_SIZE=${SIZE}; sleep 3; SIZE=$(stat -c '%s' "${HEAP_DUMP_NAME}"); done
if [ ! -s "${HEAP_DUMP_NAME}" ]; then echo >&2 ${OUTPUT}; exit 1; fi
if [ ${STATUS_CODE:-0} -gt 0 ]; then echo >&2 ${OUTPUT}; exit ${STATUS_CODE}; fi
fi`,
FileLabel: "heap dump",
FileNamePart: "heapdump",
},
{
Name: "thread-dump",
Description: "Generate a thread dump from a running Java application",
GenerateFiles: false,
SSHCommand: `JSTACK_COMMAND=$(find -executable -name jstack | head -1);
JVMMON_COMMAND=$(find -executable -name jvmmon | head -1)
if [ -z "${JVMMON_COMMAND}" ] && [ -z "${JSTACK_COMMAND}" ]; then
echo >&2 "jstack or jvmmon are required for generating thread dump, you can modify your application manifest.yaml on the 'JBP_CONFIG_OPEN_JDK_JRE' environment variable. This could be done like this:
---
applications:
- name: <APP_NAME>
memory: 1G
path: <PATH_TO_BUILD_ARTIFACT>
buildpack: https://github.com/cloudfoundry/java-buildpack
env:
JBP_CONFIG_OPEN_JDK_JRE: '{ jre: { repository_root: "https://java-buildpack.cloudfoundry.org/openjdk-jdk/jammy/x86_64", version: 21.+ } }'
"
exit 1
fi
if [ -n \"${JSTACK_COMMAND}\" ]; then ${JSTACK_COMMAND} $(pidof java); exit 0; fi;
if [ -n \"${JVMMON_COMMAND}\" ]; then ${JVMMON_COMMAND} -pid $(pidof java) -c \"print stacktrace\"; fi`,
},
{
Name: "vm-info",
Description: "Print information about the Java Virtual Machine running a Java application",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
SSHCommand: FilterJCMDRemoteMessage + `$JCMD_COMMAND $(pidof java) VM.info | filter_jcmd_remote_message`,
},
{
Name: "jcmd",
Description: "Run a JCMD command on a running Java application via --args, downloads and deletes all files that are created in the current folder, use '--no-download' to prevent this. Environment variables available: @FSPATH (writable directory path, always set), @ARGS (command arguments), @APP_NAME (application name), @FILE_NAME (generated filename with UUID for file operations), and @STATIC_FILE_NAME (without UUID). Use single quotes around --args to prevent shell expansion.",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
GenerateArbitraryFiles: true,
GenerateArbitraryFilesFolderName: "jcmd",
SSHCommand: FilterJCMDRemoteMessage + `$JCMD_COMMAND $(pidof java) @ARGS | filter_jcmd_remote_message`,
},
{
Name: "jfr-start",
Description: "Start a Java Flight Recorder default recording on a running Java application (stores in the container-dir)",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + CheckNoCurrentJFRRecordingCommand +
`$JCMD_COMMAND $(pidof java) JFR.start settings=default.jfc filename=@FILE_NAME name=JFR | filter_jcmd_remote_message;
echo "Use 'cf java jfr-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "jfr-start-profile",
Description: "Start a Java Flight Recorder profile recording on a running Java application (stores in the container-dir)",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + CheckNoCurrentJFRRecordingCommand +
`$JCMD_COMMAND $(pidof java) JFR.start settings=profile.jfc filename=@FILE_NAME name=JFR | filter_jcmd_remote_message;
echo "Use 'cf java jfr-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "jfr-start-gc",
Description: "Start a Java Flight Recorder GC recording on a running Java application (stores in the container-dir)",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
OnlyOnRecentSapMachine: true,
NeedsFileName: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + CheckNoCurrentJFRRecordingCommand +
`$JCMD_COMMAND $(pidof java) JFR.start settings=gc.jfc filename=@FILE_NAME name=JFR | filter_jcmd_remote_message;
echo "Use 'cf java jfr-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "jfr-start-gc-details",
Description: "Start a Java Flight Recorder detailed GC recording on a running Java application (stores in the container-dir)",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
OnlyOnRecentSapMachine: true,
NeedsFileName: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + CheckNoCurrentJFRRecordingCommand +
`$JCMD_COMMAND $(pidof java) JFR.start settings=gc_details.jfc filename=@FILE_NAME name=JFR | filter_jcmd_remote_message;
echo "Use 'cf java jfr-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "jfr-stop",
Description: "Stop a Java Flight Recorder recording on a running Java application",
RequiredTools: []string{"jcmd"},
GenerateFiles: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + ` output=$($JCMD_COMMAND $(pidof java) JFR.stop name=JFR | filter_jcmd_remote_message);
echo "$output"; echo ""; filename=$(echo "$output" | grep /.*.jfr --only-matching);
if [ -z "$filename" ]; then echo "No active JFR recording found to stop"; exit 1; fi;
if [ ! -f "$filename" ]; then echo "JFR recording $filename does not exist"; exit 1; fi;
if [ ! -s "$filename" ]; then echo "JFR recording $filename is empty"; exit 1; fi;
mv "$filename" @FILE_NAME;
echo "JFR recording copied to @FILE_NAME"`,
},
{
Name: "jfr-dump",
Description: "Dump a Java Flight Recorder recording on a running Java application without stopping it",
RequiredTools: []string{"jcmd"},
GenerateFiles: true,
FileExtension: ".jfr",
FileLabel: "JFR recording",
FileNamePart: "jfr",
SSHCommand: FilterJCMDRemoteMessage + ` output=$($JCMD_COMMAND $(pidof java) JFR.dump name=JFR | filter_jcmd_remote_message);
echo "$output"; echo ""; filename=$(echo "$output" | grep /.*.jfr --only-matching);
if [ -z "$filename" ]; then echo "No JFR recording found to dump"; exit 1; fi;
if [ ! -f "$filename" ]; then echo "JFR recording $filename does not exist"; exit 1; fi;
if [ ! -s "$filename" ]; then echo "JFR recording $filename is empty"; exit 1; fi;
cp "$filename" @FILE_NAME;
echo "JFR recording copied to @FILE_NAME";
echo "Use 'cf java jfr-stop @APP_NAME' to stop the recording and copy the final JFR file to the local folder"`,
},
{
Name: "jfr-status",
Description: "Check the running Java Flight Recorder recording on a running Java application",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
SSHCommand: FilterJCMDRemoteMessage + `$JCMD_COMMAND $(pidof java) JFR.check | filter_jcmd_remote_message`,
},
{
Name: "vm-version",
Description: "Print the version of the Java Virtual Machine running a Java application",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
SSHCommand: FilterJCMDRemoteMessage + `$JCMD_COMMAND $(pidof java) VM.version | filter_jcmd_remote_message`,
},
{
Name: "vm-vitals",
Description: "Print vital statistics about the Java Virtual Machine running a Java application",
RequiredTools: []string{"jcmd"},
GenerateFiles: false,
SSHCommand: FilterJCMDRemoteMessage + `$JCMD_COMMAND $(pidof java) VM.vitals | filter_jcmd_remote_message`,
},
{
Name: "asprof",
Description: "Run async-profiler commands passed to asprof via --args, copies files in the current folder. Don't use in combination with asprof-* commands. Downloads and deletes all files that are created in the current folder, if not using 'start' asprof command, use '--no-download' to prevent this. Environment variables available: @FSPATH (writable directory path, always set), @ARGS (command arguments), @APP_NAME (application name), @FILE_NAME (generated filename for file operations), and @STATIC_FILE_NAME (without UUID). Use single quotes around --args to prevent shell expansion.",
OnlyOnRecentSapMachine: true,
RequiredTools: []string{"asprof"},
GenerateFiles: false,
GenerateArbitraryFiles: true,
GenerateArbitraryFilesFolderName: "asprof",
SSHCommand: `$ASPROF_COMMAND $(pidof java) @ARGS`,
},
{
Name: "asprof-start-cpu",
Description: "Start an async-profiler CPU-time profile recording on a running Java application",
OnlyOnRecentSapMachine: true,
RequiredTools: []string{"asprof"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileNamePart: "asprof",
SSHCommand: `$ASPROF_COMMAND start $(pidof java) -e cpu -f @FILE_NAME && echo "Use 'cf java asprof-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "asprof-start-wall",
Description: "Start an async-profiler wall-clock profile recording on a running Java application",
OnlyOnRecentSapMachine: true,
RequiredTools: []string{"asprof"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileNamePart: "asprof",
SSHCommand: `$ASPROF_COMMAND start $(pidof java) -e wall -f @FILE_NAME && echo "Use 'cf java asprof-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "asprof-start-alloc",
Description: "Start an async-profiler allocation profile recording on a running Java application",
OnlyOnRecentSapMachine: true,
RequiredTools: []string{"asprof"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileNamePart: "asprof",
SSHCommand: `$ASPROF_COMMAND start $(pidof java) -e alloc -f @FILE_NAME && echo "Use 'cf java asprof-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "asprof-start-lock",
Description: "Start an async-profiler lock profile recording on a running Java application",
OnlyOnRecentSapMachine: true,
RequiredTools: []string{"asprof"},
GenerateFiles: false,
NeedsFileName: true,
FileExtension: ".jfr",
FileNamePart: "asprof",
SSHCommand: `$ASPROF_COMMAND start $(pidof java) -e lock -f @FILE_NAME && echo "Use 'cf java asprof-stop @APP_NAME' to copy the file to the local folder"`,
},
{
Name: "asprof-stop",
Description: "Stop an async-profiler profile recording on a running Java application",
RequiredTools: []string{"asprof"},
OnlyOnRecentSapMachine: true,
GenerateFiles: true,
FileExtension: ".jfr",
FileLabel: "async-profiler recording",
FileNamePart: "asprof",
SSHCommand: `$ASPROF_COMMAND stop $(pidof java)`,
},
{
Name: "asprof-status",
Description: "Get the status of async-profiler on a running Java application",
RequiredTools: []string{"asprof"},
OnlyOnRecentSapMachine: true,
GenerateFiles: false,
SSHCommand: `$ASPROF_COMMAND status $(pidof java)`,
},
{
Name: "status",
Description: "Quick status check of the remote JVM: deadlock detection, hot threads, dependency graph, and more. Requires Java 17+ locally. Use --full for comprehensive analysis. Pass additional options via --args (e.g., '--dumps 3'). See https://github.com/parttimenerd/jstall",
IsLocal: true,
SupportFullOption: true,
SSHCommand: "status all @ARGS",
},
{
Name: "jstall",
Description: "Inspect the remote JVM via JStall (runs on your machine, connects via cf ssh). Requires Java 17+ locally. Subcommands typically require a target (e.g., 'all'). Pass jstall subcommands and options via --args. See https://github.com/parttimenerd/jstall",
IsLocal: true,
SupportFullOption: true,
SSHCommand: "@ARGS",
},
{
Name: "record-status",
Description: "Record diagnostic data from the remote JVM via JStall and save to a local zip file. Requires Java 17+ locally. Output file can be specified as a trailing argument (default: APP_NAME-status.zip). Use --full for comprehensive recording. See https://github.com/parttimenerd/jstall",
IsLocal: true,
AcceptsTrailingArgs: true,
SupportFullOption: true,
SSHCommand: "record all --output @ARGS",
},
}
func (c *JavaPlugin) execute(_ plugin.CliConnection, args []string) (string, error) {
if len(args) == 0 {
return "", &InvalidUsageError{message: "No command provided"}
}
switch args[0] {
case "CLI-MESSAGE-UNINSTALL":
// Nothing to uninstall, we keep no local state
return "", nil
case "java":
break
default:
return "", &InvalidUsageError{message: fmt.Sprintf("Unexpected command Name '%s' (expected : 'java')", args[0])}
}
options, arguments, parseErr := c.parseOptions(args[1:])
if parseErr != nil {
return "", &InvalidUsageError{message: fmt.Sprintf("Error while parsing command arguments: %v", parseErr)}
}
fileFlags := []string{"container-dir", "local-dir", "keep", "no-download"}
c.logVerbosef("Starting command execution")
c.logVerbosef("Command arguments: %v", args)
noDownload := options.NoDownload
keepAfterDownload := options.Keep || noDownload
c.logVerbosef("Application instance: %d", options.AppInstanceIndex)
c.logVerbosef("No download: %t", noDownload)
c.logVerbosef("Keep after download: %t", keepAfterDownload)
remoteDir := options.ContainerDir
// strip trailing slashes from remoteDir
remoteDir = strings.TrimRight(remoteDir, "/")
localDir := options.LocalDir
if localDir == "" {
localDir = "."
}
c.logVerbosef("Remote directory: %s", remoteDir)
c.logVerbosef("Local directory: %s", localDir)
argumentLen := len(arguments)
if argumentLen < 1 {
return "", &InvalidUsageError{message: "No command provided"}
}
commandName := arguments[0]
c.logVerbosef("Command name: %s", commandName)
index := -1
lowerCommandName := strings.ToLower(commandName)
for i, command := range commands {
if command.Name == lowerCommandName {
index = i
break
}
}
if index == -1 {
// Handle 'help' as a subcommand
if lowerCommandName == "help" {
err := exec.Command("cf", "help", "java").Run()
if err != nil {
return "", fmt.Errorf("failed to show help: %w", err)
}
return "", nil
}
avCommands := make([]string, 0, len(commands))
for _, command := range commands {
avCommands = append(avCommands, command.Name)
}
matches := utils.FuzzySearch(lowerCommandName, avCommands, 3)
return "", &InvalidUsageError{message: fmt.Sprintf("Unrecognized command %q, did you mean: %s?", commandName, utils.JoinWithOr(matches))}
}
command := commands[index]
c.logVerbosef("Found command: %s - %s", command.Name, command.Description)
// Only block CF_TRACE for commands that download files (not for read-only commands like vm-version)
if os.Getenv("CF_TRACE") == "true" && (command.GenerateFiles || command.GenerateArbitraryFiles) {
return "", errors.New("the environment variable CF_TRACE is set to true. This prevents download of the dump from succeeding")
}
// Handle --help flag for jstall command
if command.Name == "jstall" {
for _, arg := range arguments {
if arg == "--help" || arg == "-h" {
// Delegate to jstall --help directly
return c.executeJstall("", "--help", 0, false)
}
}
}
if !command.GenerateFiles && !command.GenerateArbitraryFiles {
c.logVerbosef("Command does not generate files, checking for invalid file flags")
for _, flag := range fileFlags {
if (flag == "container-dir" && options.ContainerDir != "") ||
(flag == "local-dir" && options.LocalDir != "") ||
(flag == "keep" && options.Keep) ||
(flag == "no-download" && options.NoDownload) {
c.logVerbosef("Invalid flag %q detected for command %s", flag, command.Name)
return "", &InvalidUsageError{message: fmt.Sprintf("The flag %q is not supported for %s", flag, command.Name)}
}
}
}
if command.Name == "asprof" {
trimmedMiscArgs := strings.TrimLeft(options.Args, " ")
if len(trimmedMiscArgs) > 6 && trimmedMiscArgs[:6] == "start " {
noDownload = true
c.logVerbosef("asprof start command detected, setting noDownload to true")
} else {
noDownload = trimmedMiscArgs == "start"
if noDownload {
c.logVerbosef("asprof start command detected, setting noDownload to true")
}
}
}
if !command.HasMiscArgs() && options.Args != "" {
c.logVerbosef("Command %s does not support --args flag", command.Name)
return "", &InvalidUsageError{message: fmt.Sprintf("The flag %q is not supported for %s", "args", command.Name)}
}
// Validate that commands requiring @ARGS have arguments provided
if command.HasMiscArgs() && options.Args == "" && (command.Name == "jcmd" || command.Name == "asprof") {
c.logVerbosef("Command %s requires --args flag", command.Name)
return "", &InvalidUsageError{message: fmt.Sprintf("The command %q requires the --args flag to be set. Use 'cf java %s --help' for usage information.", command.Name, command.Name)}
}
if options.Full && !command.SupportFullOption {
c.logVerbosef("Command %s does not support --full flag", command.Name)
return "", &InvalidUsageError{message: fmt.Sprintf("The flag %q is not supported for %s", "full", command.Name)}
}
if argumentLen == 1 {
return "", &InvalidUsageError{message: "No application name provided"}
} else if argumentLen > 2 && !command.AcceptsTrailingArgs {
return "", &InvalidUsageError{message: fmt.Sprintf("Too many arguments provided: %v", strings.Join(arguments[2:], ", "))}
}
applicationName := arguments[1]
c.logVerbosef("Application name: %s", applicationName)
cfSSHArguments := []string{"ssh", applicationName}
if options.AppInstanceIndex >= 0 {
cfSSHArguments = append(cfSSHArguments, "--app-instance-index", strconv.Itoa(options.AppInstanceIndex))
}
if options.AppInstanceIndex < -1 {
// indexes can't be negative (except -1 for default), so fail with an error
return "", &InvalidUsageError{message: fmt.Sprintf("Invalid application instance index %d, must be >= 0", options.AppInstanceIndex)}
}
c.logVerbosef("CF SSH arguments: %v", cfSSHArguments)
supported, err := utils.CheckRequiredTools(applicationName)
if err != nil || !supported {
return "required tools checking failed", err
}
c.logVerbosef("Required tools check passed")
if command.IsLocal {
c.logVerbosef("Executing local command: %s", command.Name)
jstallArgs := options.Args
switch {
case command.SSHCommand == "@ARGS":
// Generic jstall passthrough: default to 'status all' if no --args provided
if options.Args == "" {
jstallArgs = "status all"
}
case command.AcceptsTrailingArgs:
// Commands like record-status: trailing positional arg is output file, --args are extra flags
// J-09: Reject more than one trailing positional argument
if argumentLen > 3 {
return "", &InvalidUsageError{message: fmt.Sprintf("%s accepts at most one trailing argument (output file), got %d", command.Name, argumentLen-2)}
}
trailingArg := ""
if argumentLen > 2 {
trailingArg = arguments[2]
// J-10: Reject empty trailing argument
if strings.TrimSpace(trailingArg) == "" {
return "", &InvalidUsageError{message: fmt.Sprintf("%s trailing argument must not be empty", command.Name)}
}
}
if trailingArg == "" {
trailingArg = applicationName + "-status.zip"
}
jstallArgs = strings.ReplaceAll(command.SSHCommand, "@ARGS", trailingArg)
if options.Args != "" {
jstallArgs += " " + options.Args
}
default:
// Templated commands like status: replace @ARGS with --args value (may be empty)
jstallArgs = strings.ReplaceAll(command.SSHCommand, "@ARGS", options.Args)
// Trim trailing whitespace from empty @ARGS substitution
jstallArgs = strings.TrimRight(jstallArgs, " ")
}
if options.Full {
// J-12: Only add --full if not already present in args to avoid duplication
if !strings.Contains(jstallArgs, "--full") {
jstallArgs += " --full"
jstallArgs = strings.TrimLeft(jstallArgs, " ")
}
}
return c.executeJstall(applicationName, jstallArgs, options.AppInstanceIndex, options.DryRun)
}
if !options.DryRun {
if err := c.checkSSHConnectivity(applicationName, options.AppInstanceIndex); err != nil {