commit 0dae94011c612fcf08816edc88ca35b56694bf85 Author: pratik Date: Mon Oct 20 11:07:35 2025 -0500 initial commit diff --git a/.claude/claude.md b/.claude/claude.md new file mode 100644 index 0000000..2f4ede0 --- /dev/null +++ b/.claude/claude.md @@ -0,0 +1,118 @@ +# CF Deployer Spring Boot Application - Implementation Request + +## Overview +Create a Spring Boot 3+ application with Gradle 8.14 that exposes a REST API endpoint for deploying Java applications to Cloud Foundry/Tanzu environments. The application itself will be deployed on Tanzu but must allow users to deploy to different Tanzu environments. + +## Technical Requirements + +### Build Configuration +- **Gradle Version**: 8.14 +- **Spring Boot Version**: 3.2.0 or higher +- **Java Version**: 17+ +- **Key Dependencies**: + - Spring Boot Starter Web + - Spring Boot Starter Validation + - Apache Commons IO + - Lombok (for clean code) + +### Core Functionality +1. **Endpoint**: `POST /api/cf/deploy` + - Accepts multipart form data with three parts: + - `request`: JSON object containing CF credentials and target info + - `jarFile`: The fat JAR file to deploy + - `manifest`: The manifest.yml file for CF deployment + +2. **CF CLI Integration**: + - Package CF CLI binary with the application JAR + - Download CF CLI during build process (Gradle task) + - Support Linux, macOS, and Windows + - Execute CF commands programmatically + +3. **Deployment Flow**: + - Accept user credentials, API endpoint, org, space + - Accept JAR file and manifest.yml + - Login to CF using provided credentials + - Push application using `cf push` command + - Logout from CF + - Return deployment status and output + +### Request Model Fields +- `apiEndpoint`: CF API URL +- `username`: CF username +- `password`: CF password +- `organization`: Target CF org +- `space`: Target CF space +- `appName`: Application name +- `skipSslValidation`: Boolean flag for SSL validation + +### Response Model Fields +- `success`: Boolean deployment status +- `message`: Human-readable message +- `deploymentId`: Unique deployment identifier (UUID) +- `output`: CF CLI output +- `error`: Error details if failed + +## Implementation Details + +### Required Components +1. **Models**: + - `CfDeployRequest` - Request DTO with validation annotations + - `CfDeployResponse` - Response DTO with deployment details + +2. **Service Layer**: + - `CfCliService` - Service to handle CF CLI execution + - Methods: `deployApplication()`, `login()`, `pushApplication()`, `logout()` + - Use temp directories for file operations + - Implement proper cleanup after deployment + +3. **Controller Layer**: + - `CfDeployController` - REST endpoint controller + - File validation (JAR and YAML extensions) + - Request validation using Bean Validation + +4. **Configuration**: + - `application.yml` - Configure multipart file size (500MB), timeouts + - `GlobalExceptionHandler` - Handle validation and file size exceptions + +5. **Build Configuration**: + - Gradle task to download CF CLI during build + - Extract and package CF CLI in application resources + - Detect OS and download appropriate CF CLI binary + +### Security & Best Practices +- Clean up temporary files after deployment +- Secure password handling (don't log passwords) +- Command timeout configuration +- Process output streaming +- Proper error handling and logging + +### Configuration Properties +```yaml +spring.servlet.multipart.max-file-size: 500MB +spring.servlet.multipart.max-request-size: 500MB +cf.cli.timeout: 600 # seconds +cf.cli.path: # optional explicit path +``` + +## Code Style Requirements +- Use Lombok annotations (@Data, @Builder, @Slf4j, @RequiredArgsConstructor) +- Follow Spring Boot best practices +- Proper logging at INFO and DEBUG levels +- Clean, maintainable code structure + +## Expected Deliverables +Provide only the essential Java classes and configuration files: +1. `build.gradle` - with CF CLI download task and Gradle 8.14 wrapper +2. `CfDeployRequest.java` - Request model with Lombok +3. `CfDeployResponse.java` - Response model with Lombok +4. `CfCliService.java` - CF CLI execution service +5. `CfDeployController.java` - REST controller +6. `GlobalExceptionHandler.java` - Exception handling +7. `application.yml` - Application configuration + +Do NOT provide: +- Complete project structure/directory tree +- Application main class +- Test classes +- Deployment manifests +- README or documentation files \ No newline at end of file diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..e88d7d2 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,12 @@ +{ + "permissions": { + "allow": [ + "Bash(.gradlew.bat build:*)", + "Bash(echo:*)", + "Bash(gradle wrapper:*)", + "Bash(./gradlew build:*)" + ], + "deny": [], + "ask": [] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..50f1bf2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,78 @@ +# Gradle +.gradle/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +# Eclipse +.classpath +.project +.settings/ +bin/ + +# IntelliJ IDEA +.idea/ +*.iml +*.iws +*.ipr +out/ + +# VS Code +.vscode/ + +# NetBeans +nbproject/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +# macOS +.DS_Store +.AppleDouble +.LSOverride + +# Windows +Thumbs.db +ehthumbs.db +Desktop.ini +$RECYCLE.BIN/ + +# Linux +*~ +.directory + +# Log files +*.log +logs/ + +# Temporary files +*.tmp +*.temp +*.swp +*.swo +*~ + +# Package files +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# Spring Boot +spring-boot-devtools.properties + +# Application temporary directories +temp/ +tmp/ + +# Cloud Foundry CLI binaries (downloaded during build) +src/main/resources/cf-cli/ + +# Test output +test-output/ +target/ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d5064ba --- /dev/null +++ b/build.gradle @@ -0,0 +1,86 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.cfdeployer' +version = '1.0.0' +sourceCompatibility = '17' + +configurations { + compileOnly { + extendsFrom annotationProcessor + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-validation' + implementation 'commons-io:commons-io:2.15.1' + + compileOnly 'org.projectlombok:lombok' + annotationProcessor 'org.projectlombok:lombok' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} + +// Task to download CF CLI binaries +task downloadCfCli { + group = 'build' + description = 'Downloads CF CLI binaries for Linux, macOS, and Windows' + + doLast { + def cfCliVersion = '8.7.10' + def resourcesDir = file("$projectDir/src/main/resources/cf-cli") + resourcesDir.mkdirs() + + def downloads = [ + [os: 'linux', url: "https://packages.cloudfoundry.org/stable?release=linux64-binary&version=${cfCliVersion}&source=github-rel", ext: 'tgz', executable: 'cf'], + [os: 'macos', url: "https://packages.cloudfoundry.org/stable?release=macosx64-binary&version=${cfCliVersion}&source=github-rel", ext: 'tgz', executable: 'cf'], + [os: 'windows', url: "https://packages.cloudfoundry.org/stable?release=windows64-exe&version=${cfCliVersion}&source=github-rel", ext: 'zip', executable: 'cf.exe'] + ] + + downloads.each { download -> + def osDir = file("${resourcesDir}/${download.os}") + osDir.mkdirs() + + def archiveFile = file("${osDir}/cf-cli.${download.ext}") + + if (!archiveFile.exists()) { + println "Downloading CF CLI for ${download.os}..." + + ant.get(src: download.url, dest: archiveFile, verbose: true) + + println "Extracting CF CLI for ${download.os}..." + if (download.ext == 'tgz') { + copy { + from tarTree(resources.gzip(archiveFile)) + into osDir + } + } else if (download.ext == 'zip') { + copy { + from zipTree(archiveFile) + into osDir + } + } + + archiveFile.delete() + println "CF CLI for ${download.os} downloaded and extracted successfully" + } else { + println "CF CLI for ${download.os} already exists, skipping download" + } + } + } +} + +// Ensure CF CLI is downloaded before building +processResources.dependsOn downloadCfCli diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ca025c8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/com/cfdeployer/CfDeployerApplication.java b/src/main/java/com/cfdeployer/CfDeployerApplication.java new file mode 100644 index 0000000..a20b43d --- /dev/null +++ b/src/main/java/com/cfdeployer/CfDeployerApplication.java @@ -0,0 +1,12 @@ +package com.cfdeployer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CfDeployerApplication { + + public static void main(String[] args) { + SpringApplication.run(CfDeployerApplication.class, args); + } +} diff --git a/src/main/java/com/cfdeployer/controller/CfDeployController.java b/src/main/java/com/cfdeployer/controller/CfDeployController.java new file mode 100644 index 0000000..fe1dd6d --- /dev/null +++ b/src/main/java/com/cfdeployer/controller/CfDeployController.java @@ -0,0 +1,83 @@ +package com.cfdeployer.controller; + +import com.cfdeployer.model.CfDeployRequest; +import com.cfdeployer.model.CfDeployResponse; +import com.cfdeployer.service.CfCliService; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@Slf4j +@RestController +@RequestMapping("/api/cf") +@RequiredArgsConstructor +public class CfDeployController { + + private final CfCliService cfCliService; + private final ObjectMapper objectMapper; + + @PostMapping(value = "/deploy", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) + public ResponseEntity deploy( + @RequestPart("request") String requestJson, + @RequestPart("jarFile") MultipartFile jarFile, + @RequestPart("manifest") MultipartFile manifest) { + + try { + log.info("Received deployment request"); + + CfDeployRequest request = objectMapper.readValue(requestJson, CfDeployRequest.class); + log.info("Deploying application: {} to org: {} space: {}", + request.getAppName(), request.getOrganization(), request.getSpace()); + + validateFiles(jarFile, manifest); + + CfDeployResponse response = cfCliService.deployApplication(request, jarFile, manifest); + + if (Boolean.TRUE.equals(response.getSuccess())) { + return ResponseEntity.ok(response); + } else { + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } + + } catch (Exception e) { + log.error("Error processing deployment request", e); + CfDeployResponse errorResponse = CfDeployResponse.failure( + "Failed to process deployment request: " + e.getMessage(), + e.toString() + ); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse); + } + } + + private void validateFiles(MultipartFile jarFile, MultipartFile manifest) { + if (jarFile.isEmpty()) { + throw new IllegalArgumentException("JAR file is empty"); + } + + if (manifest.isEmpty()) { + throw new IllegalArgumentException("Manifest file is empty"); + } + + String jarFileName = jarFile.getOriginalFilename(); + if (jarFileName == null || !jarFileName.toLowerCase().endsWith(".jar")) { + throw new IllegalArgumentException("Invalid JAR file. File must have .jar extension"); + } + + String manifestFileName = manifest.getOriginalFilename(); + if (manifestFileName == null || + (!manifestFileName.toLowerCase().endsWith(".yml") && !manifestFileName.toLowerCase().endsWith(".yaml"))) { + throw new IllegalArgumentException("Invalid manifest file. File must have .yml or .yaml extension"); + } + + log.debug("File validation successful - JAR: {}, Manifest: {}", jarFileName, manifestFileName); + } +} diff --git a/src/main/java/com/cfdeployer/exception/GlobalExceptionHandler.java b/src/main/java/com/cfdeployer/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..1af4b09 --- /dev/null +++ b/src/main/java/com/cfdeployer/exception/GlobalExceptionHandler.java @@ -0,0 +1,79 @@ +package com.cfdeployer.exception; + +import com.cfdeployer.model.CfDeployResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.multipart.MaxUploadSizeExceededException; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@Slf4j +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) { + log.error("Validation error occurred", ex); + + Map errors = new HashMap<>(); + ex.getBindingResult().getAllErrors().forEach((error) -> { + String fieldName = ((FieldError) error).getField(); + String errorMessage = error.getDefaultMessage(); + errors.put(fieldName, errorMessage); + }); + + String errorMessage = errors.entrySet().stream() + .map(entry -> entry.getKey() + ": " + entry.getValue()) + .collect(Collectors.joining(", ")); + + CfDeployResponse response = CfDeployResponse.failure( + "Validation failed: " + errorMessage, + ex.getMessage() + ); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + @ExceptionHandler(MaxUploadSizeExceededException.class) + public ResponseEntity handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) { + log.error("File size exceeded maximum allowed size", ex); + + CfDeployResponse response = CfDeployResponse.failure( + "File size exceeded maximum allowed size. Please ensure your files are within the 500MB limit.", + ex.getMessage() + ); + + return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE).body(response); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + log.error("Invalid argument provided", ex); + + CfDeployResponse response = CfDeployResponse.failure( + ex.getMessage(), + ex.toString() + ); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleGenericException(Exception ex) { + log.error("Unexpected error occurred", ex); + + CfDeployResponse response = CfDeployResponse.failure( + "An unexpected error occurred: " + ex.getMessage(), + ex.toString() + ); + + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response); + } +} diff --git a/src/main/java/com/cfdeployer/model/CfDeployRequest.java b/src/main/java/com/cfdeployer/model/CfDeployRequest.java new file mode 100644 index 0000000..715ebd7 --- /dev/null +++ b/src/main/java/com/cfdeployer/model/CfDeployRequest.java @@ -0,0 +1,36 @@ +package com.cfdeployer.model; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CfDeployRequest { + + @NotBlank(message = "API endpoint is required") + private String apiEndpoint; + + @NotBlank(message = "Username is required") + private String username; + + @NotBlank(message = "Password is required") + private String password; + + @NotBlank(message = "Organization is required") + private String organization; + + @NotBlank(message = "Space is required") + private String space; + + @NotBlank(message = "Application name is required") + private String appName; + + @NotNull(message = "Skip SSL validation flag is required") + private Boolean skipSslValidation; +} diff --git a/src/main/java/com/cfdeployer/model/CfDeployResponse.java b/src/main/java/com/cfdeployer/model/CfDeployResponse.java new file mode 100644 index 0000000..6ca6986 --- /dev/null +++ b/src/main/java/com/cfdeployer/model/CfDeployResponse.java @@ -0,0 +1,40 @@ +package com.cfdeployer.model; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.UUID; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CfDeployResponse { + + private Boolean success; + private String message; + private String deploymentId; + private String output; + private String error; + + public static CfDeployResponse success(String output) { + return CfDeployResponse.builder() + .success(true) + .message("Application deployed successfully") + .deploymentId(UUID.randomUUID().toString()) + .output(output) + .build(); + } + + public static CfDeployResponse failure(String error, String output) { + return CfDeployResponse.builder() + .success(false) + .message("Application deployment failed") + .deploymentId(UUID.randomUUID().toString()) + .error(error) + .output(output) + .build(); + } +} diff --git a/src/main/java/com/cfdeployer/service/CfCliService.java b/src/main/java/com/cfdeployer/service/CfCliService.java new file mode 100644 index 0000000..89ff057 --- /dev/null +++ b/src/main/java/com/cfdeployer/service/CfCliService.java @@ -0,0 +1,215 @@ +package com.cfdeployer.service; + +import com.cfdeployer.model.CfDeployRequest; +import com.cfdeployer.model.CfDeployResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.FileUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CfCliService { + + @Value("${cf.cli.timeout:600}") + private long timeout; + + @Value("${cf.cli.path:}") + private String cfCliPath; + + public CfDeployResponse deployApplication(CfDeployRequest request, MultipartFile jarFile, MultipartFile manifest) { + Path tempDir = null; + try { + tempDir = Files.createTempDirectory("cf-deploy-"); + log.info("Created temporary directory: {}", tempDir); + + Path jarPath = tempDir.resolve(jarFile.getOriginalFilename()); + Path manifestPath = tempDir.resolve("manifest.yml"); + + Files.copy(jarFile.getInputStream(), jarPath, StandardCopyOption.REPLACE_EXISTING); + Files.copy(manifest.getInputStream(), manifestPath, StandardCopyOption.REPLACE_EXISTING); + + log.info("Copied JAR and manifest files to temporary directory"); + + StringBuilder output = new StringBuilder(); + + login(request, output); + pushApplication(request, tempDir, output); + logout(output); + + log.info("Deployment completed successfully for app: {}", request.getAppName()); + return CfDeployResponse.success(output.toString()); + + } catch (Exception e) { + log.error("Deployment failed for app: {}", request.getAppName(), e); + return CfDeployResponse.failure(e.getMessage(), e.toString()); + } finally { + if (tempDir != null) { + cleanupTempDirectory(tempDir); + } + } + } + + private void login(CfDeployRequest request, StringBuilder output) throws Exception { + log.info("Logging into Cloud Foundry at: {}", request.getApiEndpoint()); + + List command = new ArrayList<>(); + command.add(getCfCliExecutable()); + command.add("login"); + command.add("-a"); + command.add(request.getApiEndpoint()); + command.add("-u"); + command.add(request.getUsername()); + command.add("-p"); + command.add(request.getPassword()); + command.add("-o"); + command.add(request.getOrganization()); + command.add("-s"); + command.add(request.getSpace()); + + if (Boolean.TRUE.equals(request.getSkipSslValidation())) { + command.add("--skip-ssl-validation"); + } + + executeCommand(command, output, true); + log.info("Successfully logged into Cloud Foundry"); + } + + private void pushApplication(CfDeployRequest request, Path workingDir, StringBuilder output) throws Exception { + log.info("Pushing application: {}", request.getAppName()); + + List command = new ArrayList<>(); + command.add(getCfCliExecutable()); + command.add("push"); + command.add(request.getAppName()); + command.add("-f"); + command.add("manifest.yml"); + + executeCommand(command, output, false, workingDir.toFile()); + log.info("Successfully pushed application: {}", request.getAppName()); + } + + private void logout(StringBuilder output) throws Exception { + log.info("Logging out from Cloud Foundry"); + + List command = new ArrayList<>(); + command.add(getCfCliExecutable()); + command.add("logout"); + + executeCommand(command, output, false); + log.info("Successfully logged out from Cloud Foundry"); + } + + private void executeCommand(List command, StringBuilder output, boolean maskPassword) throws Exception { + executeCommand(command, output, maskPassword, null); + } + + private void executeCommand(List command, StringBuilder output, boolean maskPassword, File workingDir) throws Exception { + ProcessBuilder processBuilder = new ProcessBuilder(command); + if (workingDir != null) { + processBuilder.directory(workingDir); + } + processBuilder.redirectErrorStream(true); + + if (maskPassword) { + List maskedCommand = new ArrayList<>(command); + for (int i = 0; i < maskedCommand.size(); i++) { + if ("-p".equals(maskedCommand.get(i)) && i + 1 < maskedCommand.size()) { + maskedCommand.set(i + 1, "********"); + } + } + log.debug("Executing command: {}", String.join(" ", maskedCommand)); + } else { + log.debug("Executing command: {}", String.join(" ", command)); + } + + Process process = processBuilder.start(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + output.append(line).append("\n"); + log.debug("CF CLI output: {}", line); + } + } + + boolean finished = process.waitFor(timeout, TimeUnit.SECONDS); + if (!finished) { + process.destroyForcibly(); + throw new RuntimeException("Command execution timed out after " + timeout + " seconds"); + } + + int exitCode = process.exitValue(); + if (exitCode != 0) { + throw new RuntimeException("Command failed with exit code: " + exitCode); + } + } + + private String getCfCliExecutable() throws IOException { + if (cfCliPath != null && !cfCliPath.isEmpty()) { + return cfCliPath; + } + + String os = getOperatingSystem(); + String executable = os.equals("windows") ? "cf.exe" : "cf"; + + String resourcePath = String.format("/cf-cli/%s/%s", os, executable); + File tempFile = File.createTempFile("cf-cli-", os.equals("windows") ? ".exe" : ""); + tempFile.deleteOnExit(); + + try (var inputStream = getClass().getResourceAsStream(resourcePath)) { + if (inputStream == null) { + throw new IOException("CF CLI binary not found for OS: " + os); + } + Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + + if (!os.equals("windows")) { + Set perms = new HashSet<>(); + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_WRITE); + perms.add(PosixFilePermission.OWNER_EXECUTE); + Files.setPosixFilePermissions(tempFile.toPath(), perms); + } + + log.debug("Using CF CLI executable: {}", tempFile.getAbsolutePath()); + return tempFile.getAbsolutePath(); + } + + private String getOperatingSystem() { + String osName = System.getProperty("os.name").toLowerCase(); + if (osName.contains("win")) { + return "windows"; + } else if (osName.contains("mac")) { + return "macos"; + } else { + return "linux"; + } + } + + private void cleanupTempDirectory(Path tempDir) { + try { + FileUtils.deleteDirectory(tempDir.toFile()); + log.debug("Cleaned up temporary directory: {}", tempDir); + } catch (IOException e) { + log.warn("Failed to clean up temporary directory: {}", tempDir, e); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..1cd4b16 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 8080 + +spring: + application: + name: cf-deployer + servlet: + multipart: + max-file-size: 500MB + max-request-size: 500MB + enabled: true + +cf: + cli: + timeout: 600 + path: + +logging: + level: + root: INFO + com.cfdeployer: DEBUG + pattern: + console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n" + file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"