forked from cloudfoundry/python-buildpack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappdynamics.go
More file actions
234 lines (193 loc) · 6.45 KB
/
appdynamics.go
File metadata and controls
234 lines (193 loc) · 6.45 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
package hooks
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"github.com/cloudfoundry/libbuildpack"
"regexp"
)
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 fmt.Errorf("Error reading file %s: %v", procFilePath, err)
}
newCommand, err := h.GenerateStartUpCommand(string(startCommand))
if err != nil {
return err
}
if err := ioutil.WriteFile(procFilePath, []byte(newCommand), 0666); err != nil {
return fmt.Errorf("Error writing file %s: %v", procFilePath, 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, 0666)
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 {
if os.Getenv("APPD_AGENT") != "" {
// APPD_AGENT is set => multibuildpack is used to configure appdynamics agent. Do nothing.
return nil
}
// Some env var or something that lets us know that we are using app dynamics?
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
}
var appdServiceName string
for serviceName := range services {
if match, err := regexp.MatchString("app(-)?dynamics", serviceName); err != nil {
return nil
} else if match {
appdServiceName = serviceName
h.Log.Warning("[DEPRECATION WARNING]:")
h.Log.Warning("Please use AppDynamics extension buildpack for Python Application instrumentation")
h.Log.Warning("for more details: https://docs.pivotal.io/partners/appdynamics/multibuildpack.html")
break
}
}
if appdServiceName == "" {
return nil
}
h.Log.BeginStep("Setting up Appdynamics")
val := services[appdServiceName]
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,
})
}