-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathappdynamics.go
More file actions
276 lines (225 loc) · 7.76 KB
/
appdynamics.go
File metadata and controls
276 lines (225 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package hooks
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"regexp"
"github.com/cloudfoundry/libbuildpack"
)
const (
appDynamicsServiceNameRegex = "app(-)?dynamics"
)
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"`
Name string `json:"name,omitempty"`
}
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"`
Name string `json:"name"`
ProcessType string `json:"process_type"`
Limits struct {
Mem int `json:"mem"`
} `json:"limits"`
}
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 := os.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 := os.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, _ := os.ReadFile(f.Name())
h.Log.Info("%s", 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, _ := os.ReadFile(file)
h.Log.Info("%s", 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("%s", 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: %v", err)
return nil
}
appdServiceName, appdynamicsPlan, err := getAppDynamicsServiceName(services, h.Log)
if appdServiceName == "" {
return nil
}
h.Log.BeginStep("Setting up Appdynamics")
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 %v", err)
h.Log.Debug("VCAP_APPLICATION: %s", vcapApplication)
}
sslFlag := "off"
credentials := appdynamicsPlan.Credentials
if credentials.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": credentials.ControllerHost,
"APPD_CONTROLLER_PORT": credentials.ControllerPort,
"APPD_ACCOUNT_ACCESS_KEY": credentials.AccountAccessKey,
"APPD_ACCOUNT_NAME": credentials.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 getAppDynamicsServiceName(services map[string][]Plan, log *libbuildpack.Logger) (string, Plan, error) {
// Check if there is a service with name appdynamics or app-dynamics
for serviceName, servicePlans := range services {
if isAppDynamicsServiceName(serviceName) {
appdServiceName := serviceName
logDeprecationWarning(log)
return appdServiceName, servicePlans[0], nil
}
}
// If this line is reached, no service with name appdynamics or app-dynamics was found. Check for user-provided services
userProvidedServices, keyExists := services["user-provided"]
if !keyExists {
return "", Plan{}, nil
}
for _, plan := range userProvidedServices {
if isAppDynamicsServiceName(plan.Name) {
appdServiceName := plan.Name
logDeprecationWarning(log)
return appdServiceName, plan, nil
}
}
// If this line is reached, no service with name appdynamics or app-dynamics was found in either the services and user-provided services. Return empty string, empty plan and nil error
return "", Plan{}, nil
}
func isAppDynamicsServiceName(serviceName string) bool {
match, err := regexp.MatchString(appDynamicsServiceNameRegex, serviceName)
if err != nil {
return false
}
return match
}
func logDeprecationWarning(log *libbuildpack.Logger) {
log.Warning("[DEPRECATION WARNING]:")
log.Warning("Please use AppDynamics extension buildpack for Python Application instrumentation")
log.Warning("for more details: https://docs.pivotal.io/partners/appdynamics/multibuildpack.html")
}
func init() {
logger := libbuildpack.NewLogger(os.Stdout)
command := &libbuildpack.Command{}
libbuildpack.AddHook(AppdynamicsHook{
Log: logger,
Command: command,
})
}