forked from mweagle/Sparta
/
dashboard.go
219 lines (202 loc) · 7.38 KB
/
dashboard.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
package decorator
import (
"bytes"
"regexp"
"text/template"
"github.com/aws/aws-sdk-go/aws/session"
sparta "github.com/mweagle/Sparta"
spartaCF "github.com/mweagle/Sparta/aws/cloudformation"
gocf "github.com/mweagle/go-cloudformation"
"github.com/sirupsen/logrus"
)
const (
// OutputDashboardURL is the keyname used in the CloudFormation Output
// that stores the CloudWatch Dashboard URL
// @enum OutputKey
OutputDashboardURL = "CloudWatchDashboardURL"
)
const (
headerWidthUnits = 9
headerHeightUnits = 6
metricsPerRow = 3
metricWidthUnits = 6
metricHeightUnits = 6
)
// widgetExtents represents the extents of various containers in the generated
// dashboard
type widgetExtents struct {
HeaderWidthUnits int
HeaderHeightUnits int
MetricWidthUnits int
MetricHeightUnits int
MetricsPerRow int
}
// LambdaTemplateData is the mapping of Sparta public LambdaAWSInfo together
// with the CloudFormationResource name this resource uses
type LambdaTemplateData struct {
LambdaAWSInfo *sparta.LambdaAWSInfo
ResourceName string
}
// DashboardTemplateData is the object supplied to the dashboard template
// to generate the resulting dashboard
type DashboardTemplateData struct {
// The list of lambda functions
LambdaFunctions []*LambdaTemplateData
// SpartaVersion is the Sparta library used to provision this service
SpartaVersion string
// SpartaGitHash is the commit hash of this version of the library
SpartaGitHash string
TimeSeriesPeriod int
Extents widgetExtents
}
// The default dashboard template
var dashboardTemplate = `
{
"widgets": [
{
"type": "text",
"x": 0,
"y": 0,
"width": << .Extents.HeaderWidthUnits >>,
"height": << .Extents.HeaderHeightUnits >>,
"properties": {
"markdown": "## ![Sparta](https://s3-us-west-2.amazonaws.com/weagle-sparta-public/cloudwatch/SpartaHelmet32.png) { "Ref" : "AWS::StackName" } Summary\n
* ☁️ [CloudFormation Stack](https://{ "Ref" : "AWS::Region" }.console.aws.amazon.com/cloudformation/home?region={ "Ref" : "AWS::Region" }#/stack/detail?stackId={"Ref" : "AWS::StackId"})\n
* ☢️ [XRay](https://{ "Ref" : "AWS::Region" }.console.aws.amazon.com/xray/home?region={ "Ref" : "AWS::Region" }#/service-map)\n
* **Lambda Count** : << len .LambdaFunctions >>\n
* **Sparta Version** : << .SpartaVersion >> ( [<< .SpartaGitHash >>](https://github.com/mweagle/Sparta/commit/<< .SpartaGitHash >>) )\n
* 🔗 [Sparta Documentation](https://gosparta.io)\n"
}
},
{
"type": "text",
"x": << .Extents.HeaderWidthUnits >>,
"y": 0,
"width": << .Extents.HeaderWidthUnits >>,
"height": << .Extents.HeaderHeightUnits >>,
"properties": {
"markdown": "## ![Sparta](https://mweagle.github.io/SpartaPublicResources/sparta/SpartaHelmet32.png) { "Ref" : "AWS::StackName" } Logs\n
<<range $index, $eachLambda := .LambdaFunctions>>
* 🔎 [{ "Ref" : "<< $eachLambda.ResourceName >>" }](https://{ "Ref" : "AWS::Region" }.console.aws.amazon.com/cloudwatch/home?region={ "Ref" : "AWS::Region" }#logStream:group=/aws/lambda/{ "Ref" : "<< $eachLambda.ResourceName >>" })\n
<<end>>"
}
}<<range $index, $eachLambda := .LambdaFunctions>>,
{
"type": "metric",
"x": <<widgetX $index >>,
"y": <<widgetY $index >>,
"width": << $.Extents.MetricWidthUnits >>,
"height": << $.Extents.MetricHeightUnits >>,
"properties": {
"view": "timeSeries",
"stacked": false,
"metrics": [
[ "AWS/Lambda", "Invocations", "FunctionName", "{ "Ref" : "<< $eachLambda.ResourceName >>" }", { "stat": "Sum" }],
[ ".", "Errors", ".", ".", { "stat": "Sum" }],
[ ".", "Throttles", ".", ".", { "stat": "Sum" } ]
],
"region": "{ "Ref" : "AWS::Region" }",
"period": << $.TimeSeriesPeriod >>,
"title": "λ: { "Ref" : "<< $eachLambda.ResourceName >>" }"
}
}<<end>>
]
}
`
var templateFuncMap = template.FuncMap{
// The name "inc" is what the function will be called in the template text.
"widgetX": func(lambdaIndex int) int {
return metricWidthUnits * (lambdaIndex % metricsPerRow)
},
"widgetY": func(lambdaIndex int) int {
xRow := 1
xRow += (int)((float64)(lambdaIndex % metricsPerRow))
// That's the row
return headerHeightUnits + (xRow * metricHeightUnits)
},
}
// DashboardDecorator returns a ServiceDecoratorHook function that
// can be attached the workflow to create a dashboard
func DashboardDecorator(lambdaAWSInfo []*sparta.LambdaAWSInfo,
timeSeriesPeriod int) sparta.ServiceDecoratorHookFunc {
return func(context map[string]interface{},
serviceName string,
cfTemplate *gocf.Template,
S3Bucket string,
S3Key string,
buildID string,
awsSession *session.Session,
noop bool,
logger *logrus.Logger) error {
lambdaFunctions := make([]*LambdaTemplateData, len(lambdaAWSInfo))
for index, eachLambda := range lambdaAWSInfo {
lambdaFunctions[index] = &LambdaTemplateData{
LambdaAWSInfo: eachLambda,
ResourceName: eachLambda.LogicalResourceName(),
}
}
dashboardTemplateData := &DashboardTemplateData{
SpartaVersion: sparta.SpartaVersion,
SpartaGitHash: sparta.SpartaGitHash,
LambdaFunctions: lambdaFunctions,
TimeSeriesPeriod: timeSeriesPeriod,
Extents: widgetExtents{
HeaderWidthUnits: headerWidthUnits,
HeaderHeightUnits: headerHeightUnits,
MetricWidthUnits: metricWidthUnits,
MetricHeightUnits: metricHeightUnits,
MetricsPerRow: metricsPerRow,
},
}
dashboardTmpl, dashboardTmplErr := template.New("dashboard").
Delims("<<", ">>").
Funcs(templateFuncMap).
Parse(dashboardTemplate)
if nil != dashboardTmplErr {
return dashboardTmplErr
}
var templateResults bytes.Buffer
evalResultErr := dashboardTmpl.Execute(&templateResults, dashboardTemplateData)
if nil != evalResultErr {
return evalResultErr
}
// Raw template output
logger.WithFields(logrus.Fields{
"Dashboard": templateResults.String(),
}).Debug("CloudWatch Dashboard template result")
// Replace any multiline backtick newlines with nothing, since otherwise
// the Fn::Joined JSON will be malformed
reReplace, reReplaceErr := regexp.Compile("\n")
if nil != reReplaceErr {
return reReplaceErr
}
escapedBytes := reReplace.ReplaceAll(templateResults.Bytes(), []byte(""))
logger.WithFields(logrus.Fields{
"Dashboard": string(escapedBytes),
}).Debug("CloudWatch Dashboard post cleanup")
// Super, now parse this into an Fn::Join representation
// so that we can get inline expansion of the AWS pseudo params
templateReader := bytes.NewReader(escapedBytes)
templateExpr, templateExprErr := spartaCF.ConvertToTemplateExpression(templateReader, nil)
if nil != templateExprErr {
return templateExprErr
}
dashboardResource := gocf.CloudWatchDashboard{}
dashboardResource.DashboardBody = templateExpr
dashboardResource.DashboardName = gocf.String(serviceName)
dashboardName := sparta.CloudFormationResourceName("Dashboard", "Dashboard")
cfTemplate.AddResource(dashboardName, &dashboardResource)
// Add the output
cfTemplate.Outputs[OutputDashboardURL] = &gocf.Output{
Description: "CloudWatch Dashboard URL",
Value: gocf.Join("",
gocf.String("https://"),
gocf.Ref("AWS::Region"),
gocf.String(".console.aws.amazon.com/cloudwatch/home?region="),
gocf.Ref("AWS::Region"),
gocf.String("#dashboards:name="),
gocf.Ref(dashboardName)),
}
return nil
}
}