Repository navigation
Expand file tree
/
Copy pathspring_boot.go
More file actions
471 lines (404 loc) · 16.8 KB
/
Copy pathspring_boot.go
File metadata and controls
471 lines (404 loc) · 16.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
package containers
import (
"fmt"
"github.com/cloudfoundry/java-buildpack/src/java/common"
"os"
"path/filepath"
"strings"
)
// SpringBootContainer handles Spring Boot JAR applications
type SpringBootContainer struct {
context *common.Context
jarFile string
startScript string // For staged Spring Boot apps (bin/application)
isExecutableWar bool // True when the app is a Spring Boot executable WAR
}
// NewSpringBootContainer creates a new Spring Boot container
func NewSpringBootContainer(ctx *common.Context) *SpringBootContainer {
return &SpringBootContainer{
context: ctx,
}
}
// Detect checks if this is a Spring Boot application
func (s *SpringBootContainer) Detect() (string, error) {
buildDir := s.context.Stager.BuildDir()
// Check for BOOT-INF directory (exploded Spring Boot JAR)
bootInf := filepath.Join(buildDir, "BOOT-INF")
if _, err := os.Stat(bootInf); err == nil {
// Verify this is actually a Spring Boot application by checking MANIFEST.MF
if s.isSpringBootExplodedJar(buildDir) {
s.context.Log.Debug("Detected Spring Boot application via BOOT-INF directory")
return "Spring Boot", nil
}
// Has BOOT-INF but not a Spring Boot app - let other containers handle it
s.context.Log.Debug("Found BOOT-INF directory but not a Spring Boot application (missing Spring Boot manifest markers)")
}
// Check for Spring Boot executable WAR (WEB-INF/ + Spring Boot manifest markers).
// Must run before the JAR check so executable WARs are not handed to Tomcat.
webInf := filepath.Join(buildDir, "WEB-INF")
if _, err := os.Stat(webInf); err == nil {
if isSpringBootExecutableWar(buildDir) {
s.isExecutableWar = true
s.context.Log.Debug("Detected Spring Boot executable WAR via WEB-INF directory")
return "Spring Boot", nil
}
}
// Check for Spring Boot JAR in root directory
jarFile, err := s.findSpringBootJar(buildDir)
if err == nil && jarFile != "" {
s.jarFile = jarFile
s.context.Log.Debug("Detected Spring Boot JAR: %s", jarFile)
return "Spring Boot", nil
}
// Check for staged Spring Boot application (bin/ + lib/ with spring-boot-*.jar)
// This matches Ruby buildpack's DistZipLike pattern for Spring Boot
if s.hasSpringBootInLib(buildDir) {
// Find the startup script in bin/ directory
startScript, err := s.findStartupScript(buildDir)
if err == nil && startScript != "" {
s.startScript = startScript
s.context.Log.Debug("Detected staged Spring Boot application via lib/ directory with script: %s", startScript)
return "Spring Boot", nil
}
}
return "", nil
}
// findSpringBootJar looks for a Spring Boot JAR in the build directory
func (s *SpringBootContainer) findSpringBootJar(buildDir string) (string, error) {
entries, err := os.ReadDir(buildDir)
if err != nil {
return "", err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
if strings.HasSuffix(name, ".jar") {
// Check if JAR has Spring Boot manifest
jarPath := filepath.Join(buildDir, name)
if s.isSpringBootJar(jarPath) {
return filepath.Join("$HOME", name), nil
}
}
}
return "", nil
}
// isSpringBootJar checks if a JAR is a Spring Boot JAR by filename heuristic.
// In real CF staging, the artifact is extracted as a zip before the buildpack runs,
// so BOOT-INF/ exists on disk and Detect() never reaches this path.
// This fallback only matters when a fat jar is pushed without prior extraction
// (e.g. local testing). For a more robust check, read MANIFEST.MF from inside
// the jar zip and look for Spring-Boot-Version or Start-Class headers.
func (s *SpringBootContainer) isSpringBootJar(jarPath string) bool {
name := filepath.Base(jarPath)
return strings.Contains(name, "spring") ||
strings.Contains(name, "boot") ||
strings.Contains(name, "BOOT-INF")
}
// hasSpringBootInLib checks for staged Spring Boot applications (bin/ + lib/ with spring-boot-*.jar)
// This matches Ruby buildpack's pattern where Spring Boot inherits from DistZipLike
// Checks multiple lib directories: lib/, WEB-INF/lib/, BOOT-INF/lib/
func (s *SpringBootContainer) hasSpringBootInLib(buildDir string) bool {
// List of potential lib directories (matches Ruby buildpack's SpringBootUtils.lib() method)
libDirs := []string{
filepath.Join(buildDir, "lib"),
filepath.Join(buildDir, "WEB-INF", "lib"),
filepath.Join(buildDir, "BOOT-INF", "lib"),
}
for _, libDir := range libDirs {
// Check if lib directory exists
if _, err := os.Stat(libDir); err != nil {
continue
}
// Look for spring-boot-*.jar files
entries, err := os.ReadDir(libDir)
if err != nil {
continue
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
// Match pattern: spring-boot-*.jar (case-insensitive check)
if strings.HasPrefix(strings.ToLower(name), "spring-boot-") && strings.HasSuffix(name, ".jar") {
s.context.Log.Debug("Found Spring Boot JAR in %s: %s", libDir, name)
return true
}
}
}
return false
}
// findStartupScript looks for the startup script in bin/ directory
func (s *SpringBootContainer) findStartupScript(buildDir string) (string, error) {
binDir := filepath.Join(buildDir, "bin")
entries, err := os.ReadDir(binDir)
if err != nil {
return "", err
}
// Look for executable scripts (ignore .bat files)
for _, entry := range entries {
if !entry.IsDir() && filepath.Ext(entry.Name()) != ".bat" {
return entry.Name(), nil
}
}
return "", fmt.Errorf("no startup script found in bin/")
}
// Supply installs Spring Boot dependencies
func (s *SpringBootContainer) Supply() error {
s.context.Log.BeginStep("Supplying Spring Boot")
// For Spring Boot, most dependencies are already in the JAR
// JRE installation (including JVMKill and Memory Calculator) is handled by the JRE provider
// If this is a staged Spring Boot app with bin/ scripts, make them executable
if s.startScript != "" {
if err := s.makeScriptsExecutable(); err != nil {
s.context.Log.Warning("Could not make scripts executable: %s", err.Error())
}
}
return nil
}
// makeScriptsExecutable ensures all scripts in bin/ are executable
func (s *SpringBootContainer) makeScriptsExecutable() error {
buildDir := s.context.Stager.BuildDir()
binDir := filepath.Join(buildDir, "bin")
entries, err := os.ReadDir(binDir)
if err != nil {
return err
}
for _, entry := range entries {
if !entry.IsDir() && filepath.Ext(entry.Name()) != ".bat" {
scriptPath := filepath.Join(binDir, entry.Name())
if err := os.Chmod(scriptPath, 0755); err != nil {
s.context.Log.Warning("Could not make %s executable: %s", entry.Name(), err.Error())
}
}
}
return nil
}
// Finalize performs final Spring Boot configuration
func (s *SpringBootContainer) Finalize() error {
s.context.Log.BeginStep("Finalizing Spring Boot")
// Read existing JAVA_OPTS (set by JRE finalize phase)
envFile := filepath.Join(s.context.Stager.DepDir(), "env", "JAVA_OPTS")
var existingOpts string
if data, err := os.ReadFile(envFile); err == nil {
existingOpts = strings.TrimSpace(string(data))
}
// Configure additional JAVA_OPTS for Spring Boot
additionalOpts := []string{
"-Djava.io.tmpdir=$TMPDIR",
"-XX:+ExitOnOutOfMemoryError",
}
// Combine existing opts with additional opts
var finalOpts string
if existingOpts != "" {
finalOpts = existingOpts + " " + strings.Join(additionalOpts, " ")
} else {
finalOpts = strings.Join(additionalOpts, " ")
}
buildDir := s.context.Stager.BuildDir()
bootInf := filepath.Join(buildDir, "BOOT-INF")
if _, err := os.Stat(bootInf); err == nil {
// the script name is prefixed with 'zzz' as it is important to be the last script sourced from profile.d
// so that the previous scripts assembling the CLASSPATH variable(left from frameworks) are sourced previous to it.
if err := s.context.Stager.WriteProfileD("zzz_classpath_symlinks.sh", fmt.Sprintf(symlinkScript, filepath.Join("BOOT-INF", "lib"))); err != nil {
return fmt.Errorf("failed to write zzz_classpath_symlinks.sh: %w", err)
}
} else if s.isExecutableWar {
if err := s.context.Stager.WriteProfileD("zzz_classpath_symlinks.sh", fmt.Sprintf(symlinkScript, filepath.Join("WEB-INF", "lib"))); err != nil {
return fmt.Errorf("failed to write zzz_classpath_symlinks.sh: %w", err)
}
}
// Write combined JAVA_OPTS
if err := s.context.Stager.WriteEnvFile("JAVA_OPTS", finalOpts); err != nil {
return fmt.Errorf("failed to write JAVA_OPTS: %w", err)
}
// Ensure the app binds to CF's assigned port, overriding any server.port set in
// application.yml or other Spring config. Without this, apps with a hardcoded
// server.port will either bind to the wrong port (health check fails) or crash
// with java.net.BindException: Permission denied for privileged ports (< 1024).
// Uses WriteProfileD (not WriteEnvFile) so that $PORT is shell-expanded at runtime.
// Mirrors Ruby buildpack: lib/java_buildpack/container/spring_boot.rb release()
if err := s.context.Stager.WriteProfileD("spring_boot_server_port.sh", "export SERVER_PORT=$PORT\n"); err != nil {
return fmt.Errorf("failed to write SERVER_PORT profile.d script: %w", err)
}
return nil
}
// Release returns the Spring Boot startup command
func (s *SpringBootContainer) Release() (string, error) {
buildDir := s.context.Stager.BuildDir()
// Check if we have an exploded JAR (BOOT-INF directory)
bootInf := filepath.Join(buildDir, "BOOT-INF")
if _, err := os.Stat(bootInf); err == nil {
// Verify this is actually a Spring Boot application
if s.isSpringBootExplodedJar(buildDir) {
launcherClass := s.getLauncherClass(buildDir)
return JavaExecCommand(s.context.Stager.DepsIdx(), fmt.Sprintf("-cp $PWD/.${CONTAINER_SECURITY_PROVIDER:+:$CONTAINER_SECURITY_PROVIDER} %s", launcherClass)), nil
}
mainClass, err := s.readMainClassFromManifest(buildDir)
if err != nil {
s.context.Log.Debug("Could not read MANIFEST.MF: %s", err.Error())
}
if mainClass != "" {
return JavaExecCommand(s.context.Stager.DepsIdx(), fmt.Sprintf("-cp $HOME${CONTAINER_SECURITY_PROVIDER:+:$CONTAINER_SECURITY_PROVIDER}:$HOME/BOOT-INF/classes:$HOME/BOOT-INF/lib/* %s", mainClass)), nil
}
return "", fmt.Errorf("exploded JAR found but no Main-Class in MANIFEST.MF")
}
// Check for Spring Boot executable WAR (WEB-INF/ + Spring Boot manifest markers)
if s.isExecutableWar {
launcherClass := s.getWarLauncherClass(buildDir)
return JavaExecCommand(s.context.Stager.DepsIdx(), fmt.Sprintf("-cp $PWD/.${CONTAINER_SECURITY_PROVIDER:+:$CONTAINER_SECURITY_PROVIDER} %s", launcherClass)), nil
}
// Check for staged Spring Boot app with startup script
if s.startScript != "" {
cmd := fmt.Sprintf("$HOME/bin/%s", s.startScript)
return cmd, nil
}
// Find the Spring Boot JAR
jarFile := s.jarFile
if jarFile == "" {
jar, err := s.findSpringBootJar(buildDir)
if err != nil || jar == "" {
return "", fmt.Errorf("no Spring Boot JAR found")
}
jarFile = jar
}
// JAVA_OPTS is applied by the javaexec launcher (see JavaExecCommand) (#1301)
cmd := JavaExecCommand(s.context.Stager.DepsIdx(), fmt.Sprintf("${CONTAINER_SECURITY_PROVIDER:+-Dloader.path=$CONTAINER_SECURITY_PROVIDER} -jar %s", jarFile))
return cmd, nil
}
// getWarLauncherClass returns the WarLauncher class name from MANIFEST.MF, falling back
// to the version-appropriate default when the manifest does not set Main-Class.
// Spring Boot 2.x–3.1 use: org.springframework.boot.loader.WarLauncher
// Spring Boot 3.2+ use: org.springframework.boot.loader.launch.WarLauncher
func (s *SpringBootContainer) getWarLauncherClass(buildDir string) string {
manifestData, err := s.readManifestFile(buildDir)
if err != nil {
s.context.Log.Debug("Could not read MANIFEST.MF for WAR launcher detection: %s", err.Error())
return "org.springframework.boot.loader.launch.WarLauncher"
}
// parseMainClass handles RFC 2822 continuation-line unfolding; readManifestField does not.
mainClass := parseMainClass(manifestData)
if mainClass != "" {
return mainClass
}
springBootVersion := s.readManifestField(manifestData, "Spring-Boot-Version:")
if usesOldLoaderPackage(springBootVersion) {
return "org.springframework.boot.loader.WarLauncher"
}
return "org.springframework.boot.loader.launch.WarLauncher"
}
// isSpringBootExplodedJar checks if an exploded JAR is actually a Spring Boot application
// by looking for Spring Boot-specific markers in MANIFEST.MF
func (s *SpringBootContainer) isSpringBootExplodedJar(buildDir string) bool {
manifestData, err := s.readManifestFile(buildDir)
if err != nil {
s.context.Log.Debug("Could not read MANIFEST.MF: %s", err.Error())
return false
}
// Parse MANIFEST.MF and look for Spring Boot markers
lines := strings.Split(manifestData, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Check for Spring Boot-specific entries:
// - Start-Class: The actual main class (Spring Boot specific)
// - Spring-Boot-Version: Spring Boot version
// - Spring-Boot-Classes: BOOT-INF/classes
// - Spring-Boot-Lib: BOOT-INF/lib
if strings.HasPrefix(line, "Start-Class:") ||
strings.HasPrefix(line, "Spring-Boot-Version:") ||
strings.HasPrefix(line, "Spring-Boot-Classes:") ||
strings.HasPrefix(line, "Spring-Boot-Lib:") {
s.context.Log.Debug("Found Spring Boot marker in MANIFEST.MF: %s", line)
return true
}
}
s.context.Log.Debug("No Spring Boot markers found in MANIFEST.MF - this is a plain exploded JAR")
return false
}
func (s *SpringBootContainer) readManifestFile(buildDir string) (string, error) {
manifestPath := filepath.Join(buildDir, "META-INF", "MANIFEST.MF")
data, err := os.ReadFile(manifestPath)
if err != nil {
s.context.Log.Debug("Could not read MANIFEST.MF: %s", err.Error())
return "", err
}
return string(data), nil
}
func (s *SpringBootContainer) readManifestField(manifest, field string) string {
// Parse MANIFEST.MF file (simple line-by-line parsing)
lines := strings.Split(manifest, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, field) {
fieldValue := strings.TrimSpace(strings.TrimPrefix(line, field))
s.context.Log.Debug("Found %s in MANIFEST.MF with value: %s", field, fieldValue)
return fieldValue
}
}
return ""
}
// readMainClassFromManifest reads the Main-Class entry from MANIFEST.MF
func (s *SpringBootContainer) readMainClassFromManifest(buildDir string) (string, error) {
manifestData, err := s.readManifestFile(buildDir)
if err != nil {
return "", err
}
return s.readManifestField(manifestData, "Main-Class:"), nil
}
// getLauncherClass returns the launcher class from manifest. If missing tries to determine correct JarLauncher class name
// based on Spring Boot version.
// Spring Boot 2.x–3.1 use: org.springframework.boot.loader.JarLauncher
// Spring Boot 3.2+ use: org.springframework.boot.loader.launch.JarLauncher
func (s *SpringBootContainer) getLauncherClass(buildDir string) string {
manifestData, err := s.readManifestFile(buildDir)
if err != nil {
s.context.Log.Debug("Could not read MANIFEST.MF for version detection: %s", err.Error())
return "org.springframework.boot.loader.launch.JarLauncher"
}
// parseMainClass handles RFC 2822 continuation-line unfolding; readManifestField does not.
mainClass := parseMainClass(manifestData)
if mainClass != "" {
return mainClass
}
springBootVersion := s.readManifestField(manifestData, "Spring-Boot-Version:")
if usesOldLoaderPackage(springBootVersion) {
return "org.springframework.boot.loader.JarLauncher"
}
s.context.Log.Debug("Could not determine Spring Boot version, defaulting to 3.2+ launcher")
return "org.springframework.boot.loader.launch.JarLauncher"
}
// usesOldLoaderPackage reports whether the given Spring Boot version uses the old
// org.springframework.boot.loader package (pre-3.2). The loader was reorganised
// under org.springframework.boot.loader.launch starting with Spring Boot 3.2.0.
func usesOldLoaderPackage(version string) bool {
return strings.HasPrefix(version, "2.") ||
strings.HasPrefix(version, "3.0.") ||
strings.HasPrefix(version, "3.1.")
}
// isSpringBootExecutableWar reports whether the archive at buildDir is a Spring Boot
// executable WAR by checking META-INF/MANIFEST.MF for Spring Boot launcher markers.
// Package-level helper used by SpringBootContainer.
func isSpringBootExecutableWar(buildDir string) bool {
data, err := os.ReadFile(filepath.Join(buildDir, "META-INF", "MANIFEST.MF"))
if err != nil {
return false
}
manifest := string(data)
if strings.Contains(parseMainClass(manifest), "WarLauncher") {
return true
}
return manifestField(manifest, "Start-Class:") != "" &&
manifestField(manifest, "Spring-Boot-Version:") != ""
}
// manifestField extracts the value of a named field from a MANIFEST.MF string.
func manifestField(manifest, field string) string {
for _, line := range strings.Split(manifest, "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, field) {
return strings.TrimSpace(strings.TrimPrefix(line, field))
}
}
return ""
}