Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions fixtures/fake_appd_service_broker/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: python broker.py
81 changes: 81 additions & 0 deletions fixtures/fake_appd_service_broker/broker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from flask import Flask, request, jsonify, make_response
import os

broker = Flask(__name__)

fake_service = {
"services": [
{
"id": "1e3d32a0-c979-11e7-8e98-7bebc67e38ac",
"name": "appdynamics",
"description": "fake appdynamics broker",
"bindable": True,
"tags": [],
"metadata": {
"displayName": "appdynamics",
"imageUrl": "http://via.placeholder.com/100x100",
"longDescription": "fake appdynamics broker",
"providerDisplayName": "appdynamics",
"documentationUrl": "http://example.com",
"supportUrl": "http://example.com"
},
"plans": [
{
"id": "24ba3a06-c979-11e7-a5c2-7743f1a8115a",
"name": "public",
"description": "fake appdynamics broker",
"metadata": {
"bullets": [],
"costs": [
{
"amount": {
"usd": 0
},
"unit": "MONTHLY"
}
],
"displayName": "public"
}
}
]
}
]
}


fake_credentials = {'account-access-key': 'test-key',
'account-name': 'test-account',
'host-name': 'test-sb-host',
'port': '1234',
'ssl-enabled': True
}


@broker.route("/")
def hello():
return "Service Broker Up and Running"


@broker.route("/v2/catalog")
def catalog():
return jsonify(fake_service)


@broker.route('/v2/service_instances/<instance_id>', methods=['PUT', 'DELETE', 'PATCH'])
def service_instances(instance_id):
if request.method == 'PUT':
return make_response(jsonify({}), 201)
else:
return jsonify({})


@broker.route('/v2/service_instances/<instance_id>/service_bindings/<binding_id>', methods=['PUT', 'DELETE'])
def bind_instances(instance_id, binding_id):
if request.method == 'PUT':
return make_response(jsonify({'credentials': fake_credentials}), 201)
else:
return jsonify({})


if __name__ == '__main__':
broker.run(host='0.0.0.0', port=int(os.getenv('VCAP_APP_PORT', '5000')))
8 changes: 8 additions & 0 deletions fixtures/fake_appd_service_broker/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Flask==0.10.1
Jinja2==2.7.2
MarkupSafe==0.21
Werkzeug==0.10.4
gunicorn==19.3.0
itsdangerous==0.24
pylibmc==1.4.2
cffi==0.9.2
1 change: 1 addition & 0 deletions fixtures/fake_appd_service_broker/runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
\r\r\n\npython-3.6.x\n\n\r\r
1 change: 1 addition & 0 deletions fixtures/with_appdynamics/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: python sample.py
7 changes: 7 additions & 0 deletions fixtures/with_appdynamics/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Flask==0.10.1
Jinja2==2.7.2
MarkupSafe==0.21
Werkzeug==0.10.4
itsdangerous==0.24
pylibmc==1.4.2
cffi==0.9.2
1 change: 1 addition & 0 deletions fixtures/with_appdynamics/runtime.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
\r\r\n\npython-3.6.x\n\n\r\r
27 changes: 27 additions & 0 deletions fixtures/with_appdynamics/sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Cloud Foundry test"""
from flask import Flask, jsonify
import os
import collections

app = Flask(__name__)

port = int(os.getenv('VCAP_APP_PORT', 8080))


@app.route('/vcap')
def vcap():
vcap_services = os.getenv('VCAP_SERVICES', "")
return vcap_services


@app.route('/appd')
def appd():
env_vars = ["APPD_ACCOUNT_ACCESS_KEY", "APPD_ACCOUNT_NAME", "APPD_APP_NAME", "APPD_CONTROLLER_HOST",
"APPD_CONTROLLER_PORT", "APPD_NODE_NAME", "APPD_SSL_ENABLED","APPD_TIER_NAME"]
env_vars.sort()
env_dict = collections.OrderedDict([(envKey, os.getenv(envKey))for envKey in env_vars])
return jsonify(env_dict)


if __name__ == '__main__':
app.run(host='0.0.0.0', port=port)
208 changes: 208 additions & 0 deletions src/python/hooks/appdynamics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package hooks

import (
"encoding/json"
"errors"
"fmt"
"github.com/cloudfoundry/libbuildpack"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
)

type Command interface {
Execute(string, io.Writer, io.Writer, string, ...string) error
}

type AppdynamicsHook struct {
libbuildpack.DefaultHook
Log *libbuildpack.Logger
Command Command
}

type Plan struct {
Credentials Credential `json:"credentials"`
}

type Credential struct {
ControllerHost string `json:"host-name"`
ControllerPort string `json:"port"`
SslEnabled bool `json:"ssl-enabled"`
AccountAccessKey string `json:"account-access-key"`
AccountName string `json:"account-name"`
}

type VcapApplication struct {
ApplicationName string `json:"application_name"`
ApplicationId string `json:"application_id"`
}

func (h AppdynamicsHook) getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}

func (h AppdynamicsHook) GenerateAppdynamicsScript(envVars map[string]string) string {
var envKeys []string
for k := range envVars {
envKeys = append(envKeys, k)
}
sort.Strings(envKeys) // unnecessary but just to be deterministic for tests

scriptContents := "# Autogenerated Appdynamics Script \n"
for _, envKey := range envKeys {
envStr := fmt.Sprintf("export %s=%s", envKey, envVars[envKey])
scriptContents += "\n" + envStr
}
return scriptContents
}

func (h AppdynamicsHook) GenerateStartUpCommand(startCommand string) (string, error) {
webCommands := strings.SplitN(startCommand, ":", 2)
if len(webCommands) != 2 {
return "", errors.New("improper format found in Procfile")
}
return fmt.Sprintf("web: pyagent run -- %s", webCommands[1]), nil
}

func (h AppdynamicsHook) RewriteProcFile(procFilePath string) error {
startCommand, err := ioutil.ReadFile(procFilePath)
if err != nil {
return err
}
if newCommand, err := h.GenerateStartUpCommand(string(startCommand)); err != nil {
return err
} else {
if err := ioutil.WriteFile(procFilePath, []byte(newCommand), 0644); err != nil {
return err
}
}
return nil
}

func (h AppdynamicsHook) RewriteRequirementsFile(stager *libbuildpack.Stager) error {
h.Log.BeginStep("Rewriting Requirements file with appdynamics package")

reqFile := filepath.Join(stager.BuildDir(), "requirements.txt")
writeFlag := os.O_APPEND | os.O_WRONLY
packageName := "\n" + "appdynamics"

if exists, err := libbuildpack.FileExists(reqFile); err != nil {
return err
} else if !exists {
h.Log.Info("Requirements file not found creating one with appdynamics packages")
writeFlag = os.O_CREATE | os.O_WRONLY
packageName = "appdynamics"
}

f, err := os.OpenFile(reqFile, writeFlag, 0644)
if err != nil {
panic(err)
}

defer f.Close()

if _, err = f.WriteString(packageName); err != nil {
panic(err)
}
fileContents, _ := ioutil.ReadFile(f.Name())
h.Log.Info(string(fileContents))

return nil
}

func (h AppdynamicsHook) RewriteProcFileWithAppdynamics(stager *libbuildpack.Stager) error {
h.Log.BeginStep("Rewriting ProcFile to start with Appdynamics")

file := filepath.Join(stager.BuildDir(), "Procfile")

if exists, _ := libbuildpack.FileExists(file); exists {
if err := h.RewriteProcFile(file); err != nil {
return err
}
fileContents, _ := ioutil.ReadFile(file)
h.Log.Info(string(fileContents))
} else {
h.Log.Info("Cannot find Procfile, skipping this step!")
}
return nil
}

func (h AppdynamicsHook) CreateAppDynamicsEnv(stager *libbuildpack.Stager, environmentVars map[string]string) error {
scriptContents := h.GenerateAppdynamicsScript(environmentVars)
h.Log.BeginStep("Writing Appdynamics Environment")
h.Log.Debug(scriptContents)
return stager.WriteProfileD("appdynamics.sh", scriptContents)
}

func (h AppdynamicsHook) BeforeCompile(stager *libbuildpack.Stager) error {
vcapServices := os.Getenv("VCAP_SERVICES")
services := make(map[string][]Plan)

err := json.Unmarshal([]byte(vcapServices), &services)
if err != nil {
h.Log.Debug("Could not unmarshall VCAP_SERVICES JSON exiting")
return nil
}

if val, ok := services["appdynamics"]; ok { // carry the procedure only when Appdynamics service is bound.
h.Log.BeginStep("Setting up Appdynamics")

appdynamicsPlan := val[0].Credentials
vcapApplication := os.Getenv("VCAP_APPLICATION")
application := VcapApplication{}

err = json.Unmarshal([]byte(vcapApplication), &application)
if err != nil {
h.Log.Debug("Could not unmarshall VCAP_APPLICATION JSON")
}

sslFlag := "off"

if appdynamicsPlan.SslEnabled {
sslFlag = "on"
}

appdEnv := map[string]string{
"APPD_APP_NAME": h.getEnv("APPD_APP_NAME", application.ApplicationName),
"APPD_TIER_NAME": h.getEnv("APPD_TIER_NAME", application.ApplicationName),
"APPD_NODE_NAME": h.getEnv("APPD_NODE_NAME", application.ApplicationName),
"APPD_CONTROLLER_HOST": appdynamicsPlan.ControllerHost,
"APPD_CONTROLLER_PORT": appdynamicsPlan.ControllerPort,
"APPD_ACCOUNT_ACCESS_KEY": appdynamicsPlan.AccountAccessKey,
"APPD_ACCOUNT_NAME": appdynamicsPlan.AccountName,
"APPD_SSL_ENABLED": sslFlag,
}

if err := h.RewriteRequirementsFile(stager); err != nil {
h.Log.Error("Could not write requirements file with Appdynamics packages: %v", err)
return err
}

if err := h.CreateAppDynamicsEnv(stager, appdEnv); err != nil {
h.Log.Error("Could not create Appdynamics environment: %v", err)
return err
}

if err := h.RewriteProcFileWithAppdynamics(stager); err != nil {
h.Log.Error("Could not rewrite procfile with Appdynamics start command: %v", err)
return err
}
}
return nil
}

func init() {
logger := libbuildpack.NewLogger(os.Stdout)
command := &libbuildpack.Command{}

libbuildpack.AddHook(AppdynamicsHook{
Log: logger,
Command: command,
})
}
Loading