diff --git a/docs/framework-app_dynamics_agent.md b/docs/framework-app_dynamics_agent.md index 3e556e0d6..feb64964f 100644 --- a/docs/framework-app_dynamics_agent.md +++ b/docs/framework-app_dynamics_agent.md @@ -3,7 +3,7 @@ The AppDynamics Agent Framework causes an application to be automatically config - @@ -25,6 +25,7 @@ When binding AppDynamics using a user-provided service, it must have name or tag | `application-name` | (Optional) the application's name | `node-name` | (Optional) the application's node name | `tier-name` | (Optional) the application's tier name +| `agent-uri` | (Required unless an application-provided agent is used) HTTP(S) URL to an AppDynamics agent archive (`.zip`, `.tar.gz` or `.tgz`). See [Bring Your Own Agent](#bring-your-own-agent). | To provide more complex values such as the `tier-name`, using the interactive mode when creating a user-provided service will manage the character escaping automatically. For example, the default `tier-name` could be set with a value of `Tier-$(expr "${VCAP_APPLICATION}" : '.*instance_index[": ]*\([[:digit:]]*\).*')` to calculate a value from the Cloud Foundry instance index. @@ -33,7 +34,60 @@ To provide more complex values such as the `tier-name`, using the interactive mo ## Configuration For general information on configuring the buildpack, including how to specify configuration values through environment variables, refer to [Configuration and Extension][]. -The framework has no user-configurable options. The AppDynamics agent version is managed by the buildpack manifest. See [Additional Resources](#additional-resources) below for application-level configuration options. +The framework does not download the AppDynamics agent from the upstream `manifest.yml`. The agent version is determined by the artifact you provide. See [Bring Your Own Agent](#bring-your-own-agent). + +## Bring Your Own Agent +The buildpack does not bundle or download the AppDynamics Java agent. Provide it using one of the following methods. Sources are tried in this order: `agent-uri` credential, application-provided agent, then a forked buildpack manifest. + +### Service binding credential +Set `agent-uri` on the bound service to an HTTP(S) URL that returns an AppDynamics agent archive. `.zip`, `.tar.gz` and `.tgz` archives are supported. The URL may embed HTTP basic authentication credentials (`https://user:password@host/...`). + +The credential is looked up on every bound AppDynamics service, so a marketplace binding without a URI does not hide a user-provided binding that has one. The following aliases are also accepted: `agent_uri`, `agent_url`, `agent-url`, `agent-download-url`, `agent_download_url`, `customoneagenturl`. + +Example: + +```bash +cf create-user-provided-service appdynamics -p '{ + "host-name": "controller.example.com", + "port": "443", + "ssl-enabled": "true", + "account-name": "customer1", + "account-access-key": "secret", + "agent-uri": "https://artifacts.example.com/appdynamics/AppServerAgent-26.10.0.38851.zip" +}' +``` + +If the download fails, the buildpack logs a warning and falls back to the next source. + +### Application-provided agent +Vendor the agent in the application, either as an archive or as an already-unpacked directory. Archives may be placed in the application root, `.appdynamics/` or `.app-dynamics/`: + +- `appdynamics-agent.zip` +- `appdynamics-agent.tar.gz` +- `appdynamics-agent.tgz` + +Alternatively, unpack the standard AppDynamics AppServerAgent layout into a `.appdynamics/` (or `.app-dynamics/`) directory. Both the archive and directory layouts must contain `javaagent.jar`. + +A bound AppDynamics service is used for controller configuration. If you vendor a fully configured agent (including its `conf/controller-info.xml`), no service binding is required: detection falls back to the application-provided agent, the same way New Relic supports an application-provided `.new-relic-credentials` directory. + +### Forked buildpack manifest +Like the IBM JRE, the upstream buildpack has no `appdynamics` dependency. If you fork the buildpack, you can add one and the agent will be installed from it when no runtime source is configured: + +```yaml +default_versions: +- name: appdynamics + version: 26.x +dependencies: +- name: appdynamics + version: 26.10.0.38851 + uri: https://artifacts.example.com/appdynamics/AppServerAgent-26.10.0.38851.zip + sha256: + cf_stacks: + - cflinuxfs4 + - cflinuxfs5 +``` + +If no source is available, staging fails with an error that describes all three options. ### Additional Resources The framework can be configured by providing custom configuration files. diff --git a/src/integration/frameworks_test.go b/src/integration/frameworks_test.go index 5cbac4e4b..e37a48d6d 100644 --- a/src/integration/frameworks_test.go +++ b/src/integration/frameworks_test.go @@ -70,7 +70,7 @@ func testFrameworks(platform switchblade.Platform, fixtures string, sb3JarPath, context("with AppDynamics service binding", func() { it("detects and installs AppDynamics agent", func() { - t.Skip("SKIPPED: AppDynamics agent requires authentication and is not in manifest.yml - agent must be provided via service binding or downloaded at runtime") + t.Skip("SKIPPED: AppDynamics is bring-your-own-agent - this fixture does not provide an agent archive or agent-uri") deployment, logs, err := platform.Deploy. WithServices(map[string]switchblade.Service{ "appdynamics": { @@ -93,7 +93,7 @@ func testFrameworks(platform switchblade.Platform, fixtures string, sb3JarPath, }) it("configures AppDynamics with controller info from service binding", func() { - t.Skip("SKIPPED: AppDynamics agent requires authentication and is not in manifest.yml - agent must be provided via service binding or downloaded at runtime") + t.Skip("SKIPPED: AppDynamics is bring-your-own-agent - this fixture does not provide an agent archive or agent-uri") deployment, logs, err := platform.Deploy. WithServices(map[string]switchblade.Service{ "my-appdynamics-service": { @@ -160,7 +160,7 @@ func testFrameworks(platform switchblade.Platform, fixtures string, sb3JarPath, context("with multiple APM agents", func() { it("can handle multiple agent service bindings", func() { - t.Skip("Test uses AppDynamics which requires authentication and is not in manifest - skipping until test is updated to use agents that work without auth") + t.Skip("Test uses AppDynamics, which is bring-your-own-agent; the fixture does not provide an agent archive or agent-uri") deployment, logs, err := platform.Deploy. WithServices(map[string]switchblade.Service{ "newrelic": { diff --git a/src/java/frameworks/app_dynamics.go b/src/java/frameworks/app_dynamics.go index b98ad8788..d6d97845f 100644 --- a/src/java/frameworks/app_dynamics.go +++ b/src/java/frameworks/app_dynamics.go @@ -1,11 +1,54 @@ package frameworks import ( + "archive/zip" "fmt" - "github.com/cloudfoundry/java-buildpack/src/java/common" - "github.com/cloudfoundry/java-buildpack/src/java/resources" + "io" + "net/http" + "net/url" "os" "path/filepath" + "sort" + "strings" + "time" + + "github.com/cloudfoundry/java-buildpack/src/java/common" + "github.com/cloudfoundry/java-buildpack/src/java/resources" + "github.com/cloudfoundry/libbuildpack" +) + +const ( + appDynamicsAgentDirName = "app_dynamics_agent" + appDynamicsAgentDownloadTimeout = 5 * time.Minute +) + +var ( + // appDynamicsServicePatterns are the accepted service label/tag/name substrings. + appDynamicsServicePatterns = []string{"appdynamics", "app-dynamics"} + + // appDynamicsAgentURICredentials are the service credential keys checked for a BYO agent URL. + // "agent-uri" is the documented key; the rest are accepted aliases. + appDynamicsAgentURICredentials = []string{ + "agent-uri", + "agent_uri", + "agent_url", + "agent-url", + "agent-download-url", + "agent_download_url", + "customoneagenturl", + } + + // appDynamicsAppAgentArchives are the archive names accepted from the application itself. + appDynamicsAppAgentArchives = []string{ + "appdynamics-agent.zip", + "appdynamics-agent.tar.gz", + "appdynamics-agent.tgz", + } + + // appDynamicsAppAgentDirs are application directories that may contain an + // already-unpacked agent, mirroring the New Relic .new-relic-credentials + // convention. + appDynamicsAppAgentDirs = []string{".appdynamics", ".app-dynamics"} ) // AppDynamicsFramework implements AppDynamics APM agent support @@ -20,22 +63,137 @@ func NewAppDynamicsFramework(ctx *common.Context) *AppDynamicsFramework { // Detect checks if AppDynamics should be included func (a *AppDynamicsFramework) Detect() (string, error) { - // Check for AppDynamics service binding + if a.findService() != nil { + return "AppDynamics Agent", nil + } + + // Mirror New Relic's file-based detection: an agent vendored in the application + // can carry its own configuration, so a service binding is not required. + buildDir := a.context.Stager.BuildDir() + if findAppVendoredAgentArchive(buildDir) != "" || findAppVendoredAgentDir(buildDir) != "" { + a.context.Log.Info("AppDynamics agent detected in the application") + return "AppDynamics Agent", nil + } + + a.context.Log.Debug("AppDynamics not detected") + return "", nil +} + +// findService returns the first bound AppDynamics service in deterministic order. +func (a *AppDynamicsFramework) findService() *VCAPService { + services := a.findServices() + if len(services) == 0 { + return nil + } + return services[0] +} + +// findServices returns every bound AppDynamics service, ordered by match +// strength and then by label/index so repeated calls (Detect, Supply, Finalize) +// select the same binding. +func (a *AppDynamicsFramework) findServices() []*VCAPService { vcapServices, err := GetVCAPServices() if err != nil { a.context.Log.Warning("Failed to parse VCAP_SERVICES: %s", err.Error()) - return "", nil + return nil } - // AppDynamics can be bound as: - // - "appdynamics" service (marketplace or label) - // - Services with "appdynamics" tag - // - User-provided services with "appdynamics" in the name (Docker platform) - if vcapServices.HasService("appdynamics") || vcapServices.HasTag("appdynamics") || vcapServices.HasServiceByNamePattern("appdynamics") { - return "AppDynamics Agent", nil + return findAppDynamicsServices(vcapServices) +} + +type matchedAppDynamicsService struct { + service *VCAPService + rank int + label string + index int +} + +// findAppDynamicsServices matches service labels, names and tags against both +// the "appdynamics" and "app-dynamics" spellings (case-insensitive substrings) +// and returns the strongest matches first. +func findAppDynamicsServices(vcapServices VCAPServices) []*VCAPService { + labels := make([]string, 0, len(vcapServices)) + for label := range vcapServices { + labels = append(labels, label) + } + sort.Strings(labels) + + var matches []matchedAppDynamicsService + for _, label := range labels { + services := vcapServices[label] + for i := range services { + rank, ok := appDynamicsServiceRank(label, &services[i]) + if !ok { + continue + } + matches = append(matches, matchedAppDynamicsService{ + service: &services[i], + rank: rank, + label: label, + index: i, + }) + } } - return "", nil + sort.SliceStable(matches, func(i, j int) bool { + if matches[i].rank != matches[j].rank { + return matches[i].rank < matches[j].rank + } + if matches[i].label != matches[j].label { + return matches[i].label < matches[j].label + } + return matches[i].index < matches[j].index + }) + + result := make([]*VCAPService, len(matches)) + for i := range matches { + result[i] = matches[i].service + } + return result +} + +// appDynamicsServiceRank reports how strongly a binding matches AppDynamics. +// Lower is stronger: exact label (0), label substring (1), name substring (2), +// tag substring (3). +func appDynamicsServiceRank(label string, service *VCAPService) (int, bool) { + labels := []string{strings.ToLower(label)} + if service.Label != "" && !strings.EqualFold(service.Label, label) { + labels = append(labels, strings.ToLower(service.Label)) + } + + for _, pattern := range appDynamicsServicePatterns { + for _, candidate := range labels { + if candidate == pattern { + return 0, true + } + } + } + + for _, pattern := range appDynamicsServicePatterns { + for _, candidate := range labels { + if strings.Contains(candidate, pattern) { + return 1, true + } + } + } + + name := strings.ToLower(service.Name) + for _, pattern := range appDynamicsServicePatterns { + if strings.Contains(name, pattern) { + return 2, true + } + } + + for _, tag := range service.Tags { + tagLower := strings.ToLower(tag) + for _, pattern := range appDynamicsServicePatterns { + if strings.Contains(tagLower, pattern) { + return 3, true + } + } + } + + return 0, false } // findAppDynamicsAgent locates the javaagent.jar in the agent directory @@ -43,31 +201,370 @@ func (a *AppDynamicsFramework) findAppDynamicsAgent(agentDir string) (string, er return FindFileInDirectory(agentDir, "javaagent.jar", []string{"", "ver*"}) } -// Supply installs the AppDynamics agent +// Supply installs the AppDynamics agent from a user-provided source. +// +// Sources are tried in order: the "agent-uri" service credential, an archive or +// unpacked agent vendored in the application, then an "appdynamics" dependency in +// manifest.yml (for forked buildpacks, like the IBM JRE). func (a *AppDynamicsFramework) Supply() error { a.context.Log.Debug("Installing AppDynamics Agent") - // Get AppDynamics agent dependency from manifest + agentDir := filepath.Join(a.context.Stager.DepDir(), appDynamicsAgentDirName) + + source, err := a.installAgent(agentDir) + if err != nil { + return err + } + + // Install default configuration from embedded resources + if err := a.installDefaultConfiguration(agentDir); err != nil { + a.context.Log.Warning("Could not install default AppDynamics configuration: %s", err.Error()) + } + + if _, err := a.findAppDynamicsAgent(agentDir); err != nil { + return fmt.Errorf("AppDynamics agent did not contain javaagent.jar: %w", err) + } + + a.context.Log.Info("Installed AppDynamics Agent from %s", source) + return nil +} + +// installAgent installs the agent from the first usable source and returns a +// human-readable description of it. +func (a *AppDynamicsFramework) installAgent(agentDir string) (string, error) { + services := a.findServices() + + var uriErr error + if agentURI, credential := appDynamicsAgentURI(services); agentURI != "" { + source, err := a.installAgentFromURI(agentURI, credential, agentDir) + if err == nil { + return source, nil + } + uriErr = err + a.context.Log.Warning("Could not install AppDynamics agent from service binding credential %q, trying other sources: %s", credential, err.Error()) + } + + if source, ok, err := a.installAgentFromApplication(agentDir); ok { + if err == nil { + return source, nil + } + if uriErr != nil { + return "", fmt.Errorf("%v; the application-provided AppDynamics agent also failed: %w", uriErr, err) + } + return "", err + } + + if source, ok, err := a.installAgentFromManifest(agentDir); ok { + if err == nil { + return source, nil + } + if uriErr != nil { + return "", fmt.Errorf("%v; the manifest-provided AppDynamics agent also failed: %w", uriErr, err) + } + return "", err + } + + if uriErr != nil { + return "", fmt.Errorf("AppDynamics agent could not be installed from the service binding and no application-provided or manifest agent was found: %w", uriErr) + } + + return "", fmt.Errorf( + "AppDynamics agent not found: provide the agent via the service binding credential 'agent-uri' "+ + "(an http(s) URL to an AppDynamics agent .zip/.tar.gz), vendor one of [%s] in the application root "+ + "or .appdynamics/, or add an 'appdynamics' dependency to a forked buildpack manifest", + strings.Join(appDynamicsAppAgentArchives, ", ")) +} + +// installAgentFromURI downloads and extracts an agent archive from a service +// binding credential. +func (a *AppDynamicsFramework) installAgentFromURI(agentURI, credential, agentDir string) (string, error) { + if err := prepareAppDynamicsAgentDir(agentDir); err != nil { + return "", err + } + + archive, err := os.CreateTemp("", "appdynamics-agent-*") + if err != nil { + return "", fmt.Errorf("failed to create temporary agent archive: %w", err) + } + archivePath := archive.Name() + if err := archive.Close(); err != nil { + os.Remove(archivePath) + return "", fmt.Errorf("failed to close temporary agent archive: %w", err) + } + defer os.Remove(archivePath) + + a.context.Log.Info("Downloading AppDynamics agent from %s", redactURL(agentURI)) + if err := downloadAgentArchive(agentURI, archivePath); err != nil { + return "", fmt.Errorf("failed to download AppDynamics agent from service binding credential %q: %w", credential, err) + } + + if err := extractAgentArchive(archivePath, agentDir); err != nil { + return "", fmt.Errorf("failed to extract AppDynamics agent archive: %w", err) + } + + return fmt.Sprintf("service binding credential %q", credential), nil +} + +// installAgentFromApplication installs an agent vendored in the application, +// either as an archive or as an already-unpacked directory. +func (a *AppDynamicsFramework) installAgentFromApplication(agentDir string) (string, bool, error) { + buildDir := a.context.Stager.BuildDir() + + if archive := findAppVendoredAgentArchive(buildDir); archive != "" { + if err := prepareAppDynamicsAgentDir(agentDir); err != nil { + return "", true, err + } + + a.context.Log.Info("Using application-provided AppDynamics agent archive %s", archive) + if err := extractAgentArchive(archive, agentDir); err != nil { + return "", true, fmt.Errorf("failed to extract application-provided AppDynamics agent archive %s: %w", archive, err) + } + + return fmt.Sprintf("application-provided archive %s", filepath.Base(archive)), true, nil + } + + if dir := findAppVendoredAgentDir(buildDir); dir != "" { + if err := prepareAppDynamicsAgentDir(agentDir); err != nil { + return "", true, err + } + + a.context.Log.Info("Using application-provided AppDynamics agent directory %s", dir) + if err := libbuildpack.CopyDirectory(dir, agentDir); err != nil { + return "", true, fmt.Errorf("failed to copy application-provided AppDynamics agent directory %s: %w", dir, err) + } + + return fmt.Sprintf("application-provided directory %s", dir), true, nil + } + + return "", false, nil +} + +// installAgentFromManifest installs an "appdynamics" dependency declared in +// manifest.yml. This is the same BYOL path used by the IBM JRE: the upstream +// manifest has no entry, so only forked buildpacks reach this branch. +func (a *AppDynamicsFramework) installAgentFromManifest(agentDir string) (string, bool, error) { + if len(a.context.Manifest.AllDependencyVersions("appdynamics")) == 0 { + return "", false, nil + } + dep, err := a.context.Manifest.DefaultVersion("appdynamics") if err != nil { - return fmt.Errorf("unable to determine AppDynamics version: %w", err) + return "", true, fmt.Errorf("manifest.yml declares appdynamics dependencies but no usable default version: %w", err) + } + + if err := prepareAppDynamicsAgentDir(agentDir); err != nil { + return "", true, err } - // Install AppDynamics agent - agentDir := filepath.Join(a.context.Stager.DepDir(), "app_dynamics_agent") if err := a.context.Installer.InstallDependency(dep, agentDir); err != nil { - return fmt.Errorf("failed to install AppDynamics agent: %w", err) + return "", true, fmt.Errorf("failed to install AppDynamics agent from manifest version %s: %w", dep.Version, err) } - // Install default configuration from embedded resources - if err := a.installDefaultConfiguration(agentDir); err != nil { - a.context.Log.Warning("Could not install default AppDynamics configuration: %s", err.Error()) + return fmt.Sprintf("buildpack manifest (version %s)", dep.Version), true, nil +} + +func prepareAppDynamicsAgentDir(agentDir string) error { + if err := os.RemoveAll(agentDir); err != nil { + return fmt.Errorf("failed to clear AppDynamics agent directory: %w", err) + } + if err := os.MkdirAll(agentDir, 0755); err != nil { + return fmt.Errorf("failed to create AppDynamics agent directory: %w", err) + } + return nil +} + +// appDynamicsAgentURI returns the first agent download URL and the credential +// key that supplied it. All bound AppDynamics services are checked, so a +// marketplace binding without a URI does not hide a user-provided one. +func appDynamicsAgentURI(services []*VCAPService) (string, string) { + for _, service := range services { + for _, key := range appDynamicsAgentURICredentials { + value, ok := service.Credentials[key].(string) + if !ok { + continue + } + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed, key + } + } + } + + return "", "" +} + +// findAppVendoredAgentArchive returns the first AppDynamics agent archive +// shipped with the application. +func findAppVendoredAgentArchive(buildDir string) string { + for _, name := range appDynamicsAppAgentArchives { + candidates := []string{ + filepath.Join(buildDir, name), + filepath.Join(buildDir, ".appdynamics", name), + filepath.Join(buildDir, ".app-dynamics", name), + } + for _, candidate := range candidates { + info, err := os.Stat(candidate) + if err == nil && !info.IsDir() { + return candidate + } + } + } + + return "" +} + +// findAppVendoredAgentDir returns an application directory that contains an +// already-unpacked AppDynamics agent. +func findAppVendoredAgentDir(buildDir string) string { + for _, name := range appDynamicsAppAgentDirs { + candidate := filepath.Join(buildDir, name) + info, err := os.Stat(candidate) + if err != nil || !info.IsDir() { + continue + } + if _, err := FindFileInDirectory(candidate, "javaagent.jar", []string{"", "ver*"}); err == nil { + return candidate + } + } + + return "" +} + +// downloadAgentArchive downloads agentURI to dest, supporting URLs with embedded +// HTTP basic authentication. +func downloadAgentArchive(agentURI, dest string) error { + parsed, err := url.Parse(agentURI) + if err != nil { + return fmt.Errorf("invalid agent URL: %w", err) + } + + request, err := http.NewRequest(http.MethodGet, parsed.String(), nil) + if err != nil { + return fmt.Errorf("failed to create agent download request: %w", err) + } + + if parsed.User != nil { + password, _ := parsed.User.Password() + request.SetBasicAuth(parsed.User.Username(), password) + request.URL.User = nil + } + + client := &http.Client{Timeout: appDynamicsAgentDownloadTimeout} + response, err := client.Do(request) + if err != nil { + return fmt.Errorf("agent download failed: %w", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return fmt.Errorf("agent download returned status %d %s", response.StatusCode, http.StatusText(response.StatusCode)) + } + + output, err := os.Create(dest) + if err != nil { + return fmt.Errorf("failed to create agent archive: %w", err) + } + + if _, err := io.Copy(output, response.Body); err != nil { + output.Close() + return fmt.Errorf("failed to write agent archive: %w", err) + } + + if err := output.Close(); err != nil { + return fmt.Errorf("failed to finish writing agent archive: %w", err) + } + + return nil +} + +// extractAgentArchive extracts a zip, tar.gz or tgz agent archive into dest. The +// format is detected from the file magic first, so a zip named .tar.gz still works. +func extractAgentArchive(archive, dest string) error { + format, err := detectAgentArchiveFormat(archive) + if err != nil { + return err + } + + switch format { + case "zip": + if err := validateZipPaths(archive); err != nil { + return err + } + return libbuildpack.ExtractZip(archive, dest) + case "tar.gz": + return libbuildpack.ExtractTarGz(archive, dest) + default: + return fmt.Errorf("unsupported agent archive format") + } +} + +// validateZipPaths rejects zip entries that would extract outside the +// destination. ExtractTarGz sanitizes paths itself; ExtractZip does not. +func validateZipPaths(archive string) error { + reader, err := zip.OpenReader(archive) + if err != nil { + return fmt.Errorf("failed to open agent zip: %w", err) + } + defer reader.Close() + + for _, entry := range reader.File { + cleaned := filepath.Clean(entry.Name) + if cleaned == "." { + continue + } + if filepath.IsAbs(cleaned) || cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(os.PathSeparator)) { + return fmt.Errorf("agent archive contains an unsafe path: %q", entry.Name) + } } - a.context.Log.Debug("Installed AppDynamics Agent version %s", dep.Version) return nil } +func detectAgentArchiveFormat(archive string) (string, error) { + file, err := os.Open(archive) + if err != nil { + return "", fmt.Errorf("failed to open agent archive: %w", err) + } + defer file.Close() + + header := make([]byte, 4) + n, err := io.ReadFull(file, header) + if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF { + return "", fmt.Errorf("failed to read agent archive header: %w", err) + } + + if n >= 2 && header[0] == 'P' && header[1] == 'K' { + return "zip", nil + } + if n >= 2 && header[0] == 0x1f && header[1] == 0x8b { + return "tar.gz", nil + } + + switch strings.ToLower(filepath.Ext(archive)) { + case ".zip": + return "zip", nil + case ".gz", ".tgz": + return "tar.gz", nil + } + + return "", fmt.Errorf("unable to determine agent archive format: expected .zip, .tar.gz or .tgz") +} + +// redactURL removes credentials and query parameters from a URL before logging it. +func redactURL(raw string) string { + parsed, err := url.Parse(raw) + if err != nil { + return "" + } + if parsed.User != nil { + parsed.User = url.User("REDACTED") + } + if parsed.RawQuery != "" { + parsed.RawQuery = "REDACTED" + } + parsed.Fragment = "" + return parsed.String() +} + // installDefaultConfiguration installs the default app-agent-config.xml from embedded resources func (a *AppDynamicsFramework) installDefaultConfiguration(agentDir string) error { // Create defaults/conf directory structure @@ -107,7 +604,7 @@ func (a *AppDynamicsFramework) Finalize() error { depsIdx := a.context.Stager.DepsIdx() // Find the actual AppDynamics agent jar at staging time - agentDir := filepath.Join(a.context.Stager.DepDir(), "app_dynamics_agent") + agentDir := filepath.Join(a.context.Stager.DepDir(), appDynamicsAgentDirName) agentJarPath, err := a.findAppDynamicsAgent(agentDir) if err != nil { return fmt.Errorf("failed to locate javaagent.jar: %w", err) @@ -122,13 +619,7 @@ func (a *AppDynamicsFramework) Finalize() error { runtimeAgentPath := filepath.Join(fmt.Sprintf("$DEPS_DIR/%s", depsIdx), relPath) // Get AppDynamics configuration from service binding - vcapServices, _ := GetVCAPServices() - service := vcapServices.GetService("appdynamics") - - // If not found by label, try user-provided services (Docker platform) - if service == nil { - service = vcapServices.GetServiceByNamePattern("appdynamics") - } + service := a.findService() // Build javaagent options with runtime path using $DEPS_DIR javaOpts := fmt.Sprintf("-javaagent:%s", runtimeAgentPath) @@ -183,8 +674,3 @@ func (a *AppDynamicsFramework) Finalize() error { a.context.Log.Info("Configured AppDynamics Agent for runtime (priority 11)") return nil } - -func (a *AppDynamicsFramework) DependencyIdentifier() string { - return "appdynamics" -} - diff --git a/src/java/frameworks/app_dynamics_test.go b/src/java/frameworks/app_dynamics_test.go index 4ffd43f5d..93dcf28d7 100644 --- a/src/java/frameworks/app_dynamics_test.go +++ b/src/java/frameworks/app_dynamics_test.go @@ -1,9 +1,15 @@ package frameworks_test import ( + "archive/zip" + "crypto/sha256" "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" + "strings" + "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -14,15 +20,29 @@ import ( "github.com/cloudfoundry/libbuildpack" ) +const appDynamicsBaseManifest = "language: java\n" + func newAppDynamicsContext(buildDir, cacheDir, depsDir string) *common.Context { + return newAppDynamicsContextWithManifest(buildDir, cacheDir, depsDir, appDynamicsBaseManifest) +} + +// newAppDynamicsContextWithManifest builds a context backed by a real manifest so +// the manifest fallback path (forked buildpacks) can be exercised. +func newAppDynamicsContextWithManifest(buildDir, cacheDir, depsDir, manifestYAML string) *common.Context { logger := libbuildpack.NewLogger(GinkgoWriter) - manifest := &libbuildpack.Manifest{} - installer := &libbuildpack.Installer{} + + buildpackDir := filepath.Join(cacheDir, "buildpack") + Expect(os.MkdirAll(buildpackDir, 0755)).To(Succeed()) + Expect(os.WriteFile(filepath.Join(buildpackDir, "manifest.yml"), []byte(manifestYAML), 0644)).To(Succeed()) + + manifest, err := libbuildpack.NewManifest(buildpackDir, logger, time.Now()) + Expect(err).NotTo(HaveOccurred()) + stager := libbuildpack.NewStager([]string{buildDir, cacheDir, depsDir, "0"}, logger, manifest) return &common.Context{ Stager: stager, Manifest: manifest, - Installer: installer, + Installer: libbuildpack.NewInstaller(manifest), Log: logger, Command: &libbuildpack.Command{}, } @@ -72,6 +92,37 @@ func installAppDynamicsAgentVersioned(depsDir, verDir string) { Expect(os.WriteFile(filepath.Join(agentDir, "javaagent.jar"), []byte("fake jar"), 0644)).To(Succeed()) } +// writeAppDynamicsAgentArchive writes a minimal AppDynamics agent archive at path. +// The real AppDynamics distribution is a ZIP; this helper mirrors its layout. +func writeAppDynamicsAgentArchive(path string) { + file, err := os.Create(path) + Expect(err).NotTo(HaveOccurred()) + defer file.Close() + + archive := zip.NewWriter(file) + entries := map[string]string{ + "javaagent.jar": "fake appdynamics agent", + "conf/controller-info.xml": "", + "ver26.10.0.38851/javaagent.jar": "fake versioned appdynamics agent", + "ver26.10.0.38851/conf/app-agent-config.xml": "", + } + for name, content := range entries { + writer, err := archive.Create(name) + Expect(err).NotTo(HaveOccurred()) + _, err = writer.Write([]byte(content)) + Expect(err).NotTo(HaveOccurred()) + } + + Expect(archive.Close()).To(Succeed()) +} + +// serveAppDynamicsAgentArchive serves path over HTTP for download tests. +func serveAppDynamicsAgentArchive(path string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.ServeFile(w, r, path) + })) +} + var _ = Describe("AppDynamics Agent", func() { var ( fw *frameworks.AppDynamicsFramework @@ -98,6 +149,7 @@ var _ = Describe("AppDynamics Agent", func() { os.RemoveAll(cacheDir) os.RemoveAll(depsDir) os.Unsetenv("VCAP_SERVICES") + os.Unsetenv("CF_STACK") }) Describe("Detect", func() { @@ -109,6 +161,32 @@ var _ = Describe("AppDynamics Agent", func() { }) }) + Context("with no VCAP_SERVICES set but an application-provided agent archive", func() { + BeforeEach(func() { + writeAppDynamicsAgentArchive(filepath.Join(buildDir, "appdynamics-agent.zip")) + }) + + It("detects the agent from the application", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + }) + }) + + Context("with no VCAP_SERVICES set but an application-provided agent directory", func() { + BeforeEach(func() { + agentDir := filepath.Join(buildDir, ".appdynamics") + Expect(os.MkdirAll(agentDir, 0755)).To(Succeed()) + Expect(os.WriteFile(filepath.Join(agentDir, "javaagent.jar"), []byte("fake jar"), 0644)).To(Succeed()) + }) + + It("detects the agent from the application", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + }) + }) + Context("with service bound by label 'appdynamics'", func() { BeforeEach(func() { os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) @@ -145,6 +223,42 @@ var _ = Describe("AppDynamics Agent", func() { }) }) + Context("with service bound by label 'app-dynamics'", func() { + BeforeEach(func() { + os.Setenv("VCAP_SERVICES", appdVCAPServices("app-dynamics", "my-appd", nil, "")) + }) + + It("returns 'AppDynamics Agent'", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + }) + }) + + Context("with service tagged 'app-dynamics'", func() { + BeforeEach(func() { + os.Setenv("VCAP_SERVICES", appdVCAPServices("user-provided", "my-apm-svc", []string{"app-dynamics"}, "")) + }) + + It("returns 'AppDynamics Agent'", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + }) + }) + + Context("with the documented 'app-dynamics-agent=' tag", func() { + BeforeEach(func() { + os.Setenv("VCAP_SERVICES", appdVCAPServices("user-provided", "my-apm-svc", []string{"app-dynamics-agent=26.10.0.38851"}, "")) + }) + + It("returns 'AppDynamics Agent'", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + }) + }) + Context("with an unrelated service bound", func() { BeforeEach(func() { os.Setenv("VCAP_SERVICES", appdVCAPServices("newrelic", "my-newrelic", []string{"apm"}, "")) @@ -170,6 +284,286 @@ var _ = Describe("AppDynamics Agent", func() { }) }) + Describe("Supply", func() { + Context("with an agent archive at the service binding 'agent-uri'", func() { + var server *httptest.Server + + BeforeEach(func() { + archivePath := filepath.Join(cacheDir, "agent.zip") + writeAppDynamicsAgentArchive(archivePath) + server = serveAppDynamicsAgentArchive(archivePath) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, + fmt.Sprintf(`"agent-uri":%q`, server.URL+"/agent.zip"))) + }) + + AfterEach(func() { + if server != nil { + server.Close() + } + }) + + It("downloads and extracts the agent", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "conf", "controller-info.xml")).To(BeAnExistingFile()) + }) + + It("installs the embedded default configuration", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "defaults", "conf", "app-agent-config.xml")).To(BeAnExistingFile()) + }) + }) + + Context("with the 'agent_url' credential alias", func() { + var server *httptest.Server + + BeforeEach(func() { + archivePath := filepath.Join(cacheDir, "agent.zip") + writeAppDynamicsAgentArchive(archivePath) + server = serveAppDynamicsAgentArchive(archivePath) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, + fmt.Sprintf(`"agent_url":%q`, server.URL+"/agent.zip"))) + }) + + AfterEach(func() { + if server != nil { + server.Close() + } + }) + + It("downloads and extracts the agent", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with an application-provided archive in the app root", func() { + BeforeEach(func() { + writeAppDynamicsAgentArchive(filepath.Join(buildDir, "appdynamics-agent.zip")) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("extracts the agent without downloading", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with an application-provided zip named .tar.gz", func() { + BeforeEach(func() { + writeAppDynamicsAgentArchive(filepath.Join(buildDir, "appdynamics-agent.tar.gz")) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("detects the archive format from its contents", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with an application-provided archive under .appdynamics/", func() { + BeforeEach(func() { + Expect(os.MkdirAll(filepath.Join(buildDir, ".appdynamics"), 0755)).To(Succeed()) + writeAppDynamicsAgentArchive(filepath.Join(buildDir, ".appdynamics", "appdynamics-agent.zip")) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("extracts the agent", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with an application-provided unpacked agent directory", func() { + BeforeEach(func() { + agentDir := filepath.Join(buildDir, ".appdynamics") + Expect(os.MkdirAll(filepath.Join(agentDir, "conf"), 0755)).To(Succeed()) + Expect(os.WriteFile(filepath.Join(agentDir, "javaagent.jar"), []byte("fake jar"), 0644)).To(Succeed()) + Expect(os.WriteFile(filepath.Join(agentDir, "conf", "controller-info.xml"), []byte(""), 0644)).To(Succeed()) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("copies the agent into the dependency directory", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "conf", "controller-info.xml")).To(BeAnExistingFile()) + }) + }) + + Context("with a marketplace binding and a user-provided binding carrying agent-uri", func() { + var server *httptest.Server + + BeforeEach(func() { + archivePath := filepath.Join(cacheDir, "agent.zip") + writeAppDynamicsAgentArchive(archivePath) + server = serveAppDynamicsAgentArchive(archivePath) + os.Setenv("VCAP_SERVICES", fmt.Sprintf(`{ + "appdynamics": [{"name":"marketplace-appd","label":"appdynamics","tags":["appdynamics"],"credentials":{"host-name":"controller.example.com"}}], + "user-provided": [{"name":"appdynamics-agent","label":"user-provided","tags":[],"credentials":{"agent-uri":%q}}] +}`, server.URL+"/agent.zip")) + }) + + AfterEach(func() { + if server != nil { + server.Close() + } + }) + + It("uses the agent-uri from the user-provided binding", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("when the agent-uri download fails but an application archive exists", func() { + var server *httptest.Server + + BeforeEach(func() { + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "boom", http.StatusInternalServerError) + })) + writeAppDynamicsAgentArchive(filepath.Join(buildDir, "appdynamics-agent.zip")) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, + fmt.Sprintf(`"agent-uri":%q`, server.URL+"/agent.zip"))) + }) + + AfterEach(func() { + if server != nil { + server.Close() + } + }) + + It("falls back to the application-provided archive", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with agent-uri containing basic auth credentials", func() { + var server *httptest.Server + + BeforeEach(func() { + archivePath := filepath.Join(cacheDir, "agent.zip") + writeAppDynamicsAgentArchive(archivePath) + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, password, ok := r.BasicAuth() + if !ok || user != "appd" || password != "s3cret" { + w.WriteHeader(http.StatusUnauthorized) + return + } + http.ServeFile(w, r, archivePath) + })) + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, + fmt.Sprintf(`"agent-uri":%q`, "http://appd:s3cret@"+strings.TrimPrefix(server.URL, "http://")+"/agent.zip"))) + }) + + AfterEach(func() { + if server != nil { + server.Close() + } + }) + + It("sends the credentials and installs the agent", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with an archive containing a path traversal entry", func() { + BeforeEach(func() { + archivePath := filepath.Join(buildDir, "appdynamics-agent.zip") + file, err := os.Create(archivePath) + Expect(err).NotTo(HaveOccurred()) + + archive := zip.NewWriter(file) + writer, err := archive.Create("../escaped.txt") + Expect(err).NotTo(HaveOccurred()) + _, err = writer.Write([]byte("escaped")) + Expect(err).NotTo(HaveOccurred()) + Expect(archive.Close()).To(Succeed()) + Expect(file.Close()).To(Succeed()) + + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("rejects the archive", func() { + err := fw.Supply() + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("unsafe path")) + }) + }) + + Context("with an appdynamics dependency in the manifest (forked buildpack)", func() { + BeforeEach(func() { + buildpackDir := filepath.Join(cacheDir, "buildpack") + archivePath := filepath.Join(buildpackDir, "appdynamics-agent.zip") + writeAppDynamicsAgentArchive(archivePath) + + data, err := os.ReadFile(archivePath) + Expect(err).NotTo(HaveOccurred()) + digest := fmt.Sprintf("%x", sha256.Sum256(data)) + + manifestYAML := fmt.Sprintf(`language: java +default_versions: +- name: appdynamics + version: 26.10.0.38851 +dependencies: +- name: appdynamics + version: 26.10.0.38851 + uri: appdynamics-agent.zip + file: appdynamics-agent.zip + sha256: %s + cf_stacks: + - cflinuxfs4 +`, digest) + + fw = frameworks.NewAppDynamicsFramework(newAppDynamicsContextWithManifest(buildDir, cacheDir, depsDir, manifestYAML)) + os.Setenv("CF_STACK", "cflinuxfs4") + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, "")) + }) + + It("installs the agent from the manifest dependency", func() { + Expect(fw.Supply()).To(Succeed()) + Expect(filepath.Join(depsDir, "0", "app_dynamics_agent", "javaagent.jar")).To(BeAnExistingFile()) + }) + }) + + Context("with only an application-provided agent and no service binding", func() { + BeforeEach(func() { + writeAppDynamicsAgentArchive(filepath.Join(buildDir, "appdynamics-agent.zip")) + }) + + It("installs and finalizes without controller credentials", func() { + name, err := fw.Detect() + Expect(err).NotTo(HaveOccurred()) + Expect(name).To(Equal("AppDynamics Agent")) + + Expect(fw.Supply()).To(Succeed()) + Expect(fw.Finalize()).To(Succeed()) + + content, err := os.ReadFile(filepath.Join(depsDir, "0", "java_opts", "11_app_dynamics.opts")) + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("-javaagent:")) + Expect(string(content)).NotTo(ContainSubstring("-Dappdynamics.")) + }) + }) + + Context("with no agent source", func() { + BeforeEach(func() { + os.Setenv("VCAP_SERVICES", appdVCAPServices("appdynamics", "my-appd", nil, + `"host-name":"controller.example.com"`)) + }) + + It("returns an actionable error", func() { + err := fw.Supply() + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("agent-uri")) + Expect(err.Error()).To(ContainSubstring("appdynamics-agent.zip")) + Expect(err.Error()).To(ContainSubstring("forked buildpack manifest")) + }) + }) + }) + Describe("Finalize", func() { Context("with agent JAR present at the flat path and no credentials", func() { BeforeEach(func() { @@ -376,6 +770,21 @@ var _ = Describe("AppDynamics Agent", func() { }) }) + Context("with service bound by label 'app-dynamics'", func() { + BeforeEach(func() { + installAppDynamicsAgent(depsDir) + os.Setenv("VCAP_SERVICES", appdVCAPServices("app-dynamics", "my-appd", nil, + `"host-name":"ctrl-appd.example.com"`)) + }) + + It("uses the credentials from the app-dynamics binding", func() { + Expect(fw.Finalize()).To(Succeed()) + content, err := os.ReadFile(filepath.Join(depsDir, "0", "java_opts", "11_app_dynamics.opts")) + Expect(err).NotTo(HaveOccurred()) + Expect(string(content)).To(ContainSubstring("-Dappdynamics.controller.hostName=ctrl-appd.example.com")) + }) + }) + Context("when javaagent.jar is not present", func() { It("returns an error", func() { err := fw.Finalize()
Detection CriterionExistence of a single bound AppDynamics service. The existence of an AppDynamics service defined by the VCAP_SERVICES payload containing a service name, label or tag with app-dynamics or appdynamics as a substring. + Detection CriterionExistence of a single bound AppDynamics service, or an application-provided AppDynamics agent. The existence of an AppDynamics service is defined by the VCAP_SERVICES payload containing a service name, label or tag with app-dynamics or appdynamics as a substring. An application-provided agent archive or .appdynamics/ directory (see Bring Your Own Agent) is detected without a service binding.