-
Notifications
You must be signed in to change notification settings - Fork 48
/
describe.go
422 lines (398 loc) · 11.3 KB
/
describe.go
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// +build !lambdabinary
package sparta
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"strings"
"text/template"
spartaCF "github.com/mweagle/Sparta/aws/cloudformation"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const (
nodeColorService = "#720502"
nodeColorEventSource = "#BF2803"
nodeColorLambda = "#F35B05"
nodeColorAPIGateway = "#06B5F5"
nodeNameAPIGateway = "API Gateway"
)
type cytoscapeData struct {
ID string `json:"id"`
Image string `json:"image"`
BackgroundColor string `json:"backgroundColor,omitempty"`
Source string `json:"source,omitempty"`
Target string `json:"target,omitempty"`
Label string `json:"label,omitempty"`
DegreeCentrality int `json:"degreeCentrality"`
}
type cytoscapeNode struct {
Data cytoscapeData `json:"data"`
Classes string `json:"classes,omitempty"`
}
type templateResource struct {
KeyName string
Data string
}
func cytoscapeNodeID(rawData interface{}) (string, error) {
bytes, bytesErr := json.Marshal(rawData)
if bytesErr != nil {
return "", bytesErr
}
hash := sha1.New()
_, writeErr := hash.Write(bytes)
if writeErr != nil {
return "", writeErr
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func writeNode(nodes *[]*cytoscapeNode,
nodeName string,
nodeColor string,
nodeImage string,
logger *logrus.Logger) error {
nodeID, nodeErr := cytoscapeNodeID(nodeName)
if nodeErr != nil {
return errors.Wrapf(nodeErr,
"Failed to create nodeID for entry: %s",
nodeName)
}
appendNode := &cytoscapeNode{
Data: cytoscapeData{
ID: nodeID,
Label: strings.Trim(nodeName, "\""),
},
}
if nodeImage != "" {
resourceItem := templateResourceForKey(nodeImage, logger)
if resourceItem != nil {
appendNode.Data.Image = fmt.Sprintf("data:image/svg+xml;base64,%s",
base64.StdEncoding.EncodeToString([]byte(resourceItem.Data)))
}
}
*nodes = append(*nodes, appendNode)
return nil
}
func writeLink(nodes *[]*cytoscapeNode,
fromNode string,
toNode string,
label string) error {
nodeSource, nodeSourceErr := cytoscapeNodeID(fromNode)
if nodeSourceErr != nil {
return errors.Wrapf(nodeSourceErr,
"Failed to create nodeID for entry: %s",
fromNode)
}
nodeTarget, nodeTargetErr := cytoscapeNodeID(toNode)
if nodeTargetErr != nil {
return errors.Wrapf(nodeSourceErr,
"Failed to create nodeID for entry: %s",
toNode)
}
*nodes = append(*nodes, &cytoscapeNode{
Data: cytoscapeData{
ID: fmt.Sprintf("%d", rand.Uint64()),
Source: nodeSource,
Target: nodeTarget,
Label: label,
},
})
return nil
}
func templateResourceForKey(resourceKeyName string, logger *logrus.Logger) *templateResource {
var resource *templateResource
resourcePath := fmt.Sprintf("/resources/describe/%s",
strings.TrimLeft(resourceKeyName, "/"))
data, dataErr := _escFSString(false, resourcePath)
if dataErr == nil {
keyParts := strings.Split(resourcePath, "/")
keyName := keyParts[len(keyParts)-1]
resource = &templateResource{
KeyName: keyName,
Data: data,
}
logger.WithFields(logrus.Fields{
"Path": resourcePath,
"KeyName": keyName,
}).Debug("Embedded resource")
} else {
logger.WithFields(logrus.Fields{
"Path": resourcePath,
}).Warn("Failed to embed resource")
}
return resource
}
func templateResourcesForKeys(resourceKeyNames []string, logger *logrus.Logger) []*templateResource {
var resources []*templateResource
for _, eachKey := range resourceKeyNames {
loadedResource := templateResourceForKey(eachKey, logger)
if loadedResource != nil {
resources = append(resources, loadedResource)
}
}
return resources
}
func templateCSSFiles(logger *logrus.Logger) []*templateResource {
cssFiles := []string{"bootstrap-4.0.0/dist/css/bootstrap.min.css",
"highlight.js/styles/xcode.css",
}
return templateResourcesForKeys(cssFiles, logger)
}
func templateJSFiles(logger *logrus.Logger) []*templateResource {
jsFiles := []string{"jquery/jquery-3.3.1.min.js",
"popper/popper.min.js",
"bootstrap-4.0.0/dist/js/bootstrap.min.js",
"highlight.js/highlight.pack.js",
"dagre-0.8.2/dagre-0.8.2/dist/dagre.js",
"cytoscapejs/cytoscape.js",
"cytoscape.js-dagre-2.2.2/cytoscape.js-dagre-2.2.2/cytoscape-dagre.js",
"sparta.js",
}
return templateResourcesForKeys(jsFiles, logger)
}
func templateImageMap(logger *logrus.Logger) map[string]string {
images := []string{"SpartaHelmet256.png",
"AWSIcons/Compute/Compute_AWSLambda_LambdaFunction.svg",
"AWSIcons/Management Tools/ManagementTools_AWSCloudFormation.svg",
}
resources := templateResourcesForKeys(images, logger)
imageMap := make(map[string]string)
for _, eachResource := range resources {
imageMap[eachResource.KeyName] = base64.StdEncoding.EncodeToString([]byte(eachResource.Data))
}
return imageMap
}
// TODO - this should really be smarter, including
// looking at the referred resource to understand it's
// type
func iconForAWSResource(rawEmitter interface{}) string {
jsonBytes, jsonBytesErr := json.Marshal(rawEmitter)
if jsonBytesErr != nil {
jsonBytes = make([]byte, 0)
}
canonicalRaw := strings.ToLower(string(jsonBytes))
if strings.Contains(canonicalRaw, "dynamodb") {
return "AWSIcons/Database/Database_AmazonDynamoDB.svg"
}
if strings.Contains(canonicalRaw, "sqs") {
return "AWSIcons/Messaging/Messaging_AmazonSQS.svg"
}
if strings.Contains(canonicalRaw, "sns") {
return "AWSIcons/Messaging/Messaging_AmazonSNS_topic.svg"
}
if strings.Contains(canonicalRaw, "cloudwatch") {
return "AWSIcons/Management Tools/ManagementTools_AmazonCloudWatch.svg"
}
if strings.Contains(canonicalRaw, "kinesis") {
return "AWSIcons/Analytics/Analytics_AmazonKinesis.svg"
}
if strings.Contains(canonicalRaw, "s3") {
return "AWSIcons/Storage/Storage_AmazonS3_bucket.svg"
}
return "AWSIcons/General/General_AWScloud.svg"
}
// Describe produces a graphical representation of a service's Lambda and data sources. Typically
// automatically called as part of a compiled golang binary via the `describe` command
// line option.
func Describe(serviceName string,
serviceDescription string,
lambdaAWSInfos []*LambdaAWSInfo,
api *API,
s3Site *S3Site,
s3BucketName string,
buildTags string,
linkFlags string,
outputWriter io.Writer,
workflowHooks *WorkflowHooks,
logger *logrus.Logger) error {
validationErr := validateSpartaPreconditions(lambdaAWSInfos, logger)
if validationErr != nil {
return validationErr
}
var cloudFormationTemplate bytes.Buffer
err := Provision(true,
serviceName,
serviceDescription,
lambdaAWSInfos,
api,
s3Site,
s3BucketName,
false,
false,
"N/A",
"",
buildTags,
linkFlags,
&cloudFormationTemplate,
workflowHooks,
logger)
if nil != err {
return err
}
tmpl, err := template.New("description").Parse(_escFSMustString(false, "/resources/describe/template.html"))
if err != nil {
return errors.New(err.Error())
}
cytoscapeElements := make([]*cytoscapeNode, 0)
// Instead of inline mermaid stuff, we're going to stuff raw
// json through. We can also include AWS images in the icon
// using base64/encoded:
// Example: https://cytoscape.github.io/cytoscape.js-tutorial-demo/datasets/social.json
// Use the "fancy" CSS:
// https://github.com/cytoscape/cytoscape.js-tutorial-demo/blob/gh-pages/stylesheets/fancy.json
// Which is dynamically updated at: https://cytoscape.github.io/cytoscape.js-tutorial-demo/
// Setup the root object
writeErr := writeNode(&cytoscapeElements,
serviceName,
nodeColorService,
"AWSIcons/Management Tools/ManagementTools_AWSCloudFormation_stack.svg",
logger)
if writeErr != nil {
return writeErr
}
for _, eachLambda := range lambdaAWSInfos {
// Other cytoscape nodes
// Create the node...
writeErr = writeNode(&cytoscapeElements,
eachLambda.lambdaFunctionName(),
nodeColorLambda,
"AWSIcons/Compute/Compute_AWSLambda.svg",
logger)
if writeErr != nil {
return writeErr
}
writeErr = writeLink(&cytoscapeElements,
eachLambda.lambdaFunctionName(),
serviceName,
"")
if writeErr != nil {
return writeErr
}
// Create permission & event mappings
// functions declared in this
for _, eachPermission := range eachLambda.Permissions {
nodes, err := eachPermission.descriptionInfo()
if nil != err {
return err
}
for _, eachNode := range nodes {
name := strings.TrimSpace(eachNode.Name)
link := strings.TrimSpace(eachNode.Relation)
// Style it to have the Amazon color
nodeColor := eachNode.Color
if "" == nodeColor {
nodeColor = nodeColorEventSource
}
writeErr = writeNode(&cytoscapeElements,
name,
nodeColor,
iconForAWSResource(eachNode.Name),
logger)
if writeErr != nil {
return writeErr
}
writeErr = writeLink(&cytoscapeElements,
name,
eachLambda.lambdaFunctionName(),
link)
if writeErr != nil {
return writeErr
}
}
}
for index, eachEventSourceMapping := range eachLambda.EventSourceMappings {
dynamicArn := spartaCF.DynamicValueToStringExpr(eachEventSourceMapping.EventSourceArn)
jsonBytes, jsonBytesErr := json.Marshal(dynamicArn)
if jsonBytesErr != nil {
jsonBytes = []byte(fmt.Sprintf("%s-EventSourceMapping[%d]",
eachLambda.lambdaFunctionName(),
index))
}
nodeName := string(jsonBytes)
writeErr = writeNode(&cytoscapeElements,
nodeName,
nodeColorEventSource,
iconForAWSResource(dynamicArn),
logger)
if writeErr != nil {
return writeErr
}
writeErr = writeLink(&cytoscapeElements,
nodeName,
eachLambda.lambdaFunctionName(),
"")
if writeErr != nil {
return writeErr
}
}
}
// API?
if nil != api {
// Create the APIGateway virtual node && connect it to the application
writeErr = writeNode(&cytoscapeElements,
nodeNameAPIGateway,
nodeColorAPIGateway,
"AWSIcons/Application Services/ApplicationServices_AmazonAPIGateway.svg",
logger)
if writeErr != nil {
return writeErr
}
for _, eachResource := range api.resources {
for eachMethod := range eachResource.Methods {
// Create the PATH node
var nodeName = fmt.Sprintf("%s - %s", eachMethod, eachResource.pathPart)
writeErr = writeNode(&cytoscapeElements,
nodeName,
nodeColorAPIGateway,
"AWSIcons/General/General_Internet.svg",
logger)
if writeErr != nil {
return writeErr
}
writeErr = writeLink(&cytoscapeElements,
nodeNameAPIGateway,
nodeName,
"")
if writeErr != nil {
return writeErr
}
writeErr = writeLink(&cytoscapeElements,
nodeName,
eachResource.parentLambda.lambdaFunctionName(),
"")
if writeErr != nil {
return writeErr
}
}
}
}
cytoscapeBytes, cytoscapeBytesErr := json.MarshalIndent(cytoscapeElements, "", " ")
if cytoscapeBytesErr != nil {
return errors.Wrapf(cytoscapeBytesErr, "Failed to marshal cytoscape data")
}
params := struct {
SpartaVersion string
ServiceName string
ServiceDescription string
CloudFormationTemplate string
CSSFiles []*templateResource
JSFiles []*templateResource
ImageMap map[string]string
CytoscapeData interface{}
}{
SpartaGitHash[0:8],
serviceName,
serviceDescription,
cloudFormationTemplate.String(),
templateCSSFiles(logger),
templateJSFiles(logger),
templateImageMap(logger),
string(cytoscapeBytes),
}
return tmpl.Execute(outputWriter, params)
}