-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
helpers.go
270 lines (237 loc) · 7.43 KB
/
helpers.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package render
import (
"encoding/json"
"fmt"
htemplate "html/template"
"strconv"
"strings"
ttemplate "text/template"
"time"
"unicode"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"golang.org/x/text/unicode/norm"
)
// Fmap return a fresh copy of a map of utility functions for HTML templating
func Fmap() htemplate.FuncMap {
return htemplate.FuncMap{
"doNotEscape": doNotEscape,
"lastError": lastError,
"lastErrorTraceback": func(s string) htemplate.HTML { return doNotEscape(lastErrorTraceback(s)) },
"lastErrorMessage": func(s string) htemplate.HTML { return doNotEscape(lastErrorMessage(s)) },
"configError": configError,
"printDashes": printDashes,
"formatUnixTime": formatUnixTime,
"humanize": mkHuman,
"humanizeDuration": mkHumanDuration,
"toUnsortedList": toUnsortedList,
"formatTitle": formatTitle,
"add": add,
"status": status,
"redText": redText,
"yellowText": yellowText,
"greenText": greenText,
"ntpWarning": ntpWarning,
"version": getVersion,
"percent": func(v float64) string { return fmt.Sprintf("%02.1f", v*100) },
"complianceResult": complianceResult,
}
}
// Textfmap return a fresh copy of a map of utility functions for text templating
func Textfmap() ttemplate.FuncMap {
return ttemplate.FuncMap{
"lastErrorTraceback": lastErrorTraceback,
"lastErrorMessage": lastErrorMessage,
"printDashes": printDashes,
"formatUnixTime": formatUnixTime,
"humanize": mkHuman,
"humanizeDuration": mkHumanDuration,
"toUnsortedList": toUnsortedList,
"formatTitle": formatTitle,
"add": add,
"status": status,
"redText": redText,
"yellowText": yellowText,
"greenText": greenText,
"ntpWarning": ntpWarning,
"version": getVersion,
"percent": func(v float64) string { return fmt.Sprintf("%02.1f", v*100) },
"complianceResult": complianceResult,
}
}
const timeFormat = "2006-01-02 15:04:05.999 MST"
func doNotEscape(value string) htemplate.HTML {
return htemplate.HTML(value)
}
func configError(value string) htemplate.HTML {
return htemplate.HTML(value + "\n")
}
func lastError(value string) htemplate.HTML {
return htemplate.HTML(value)
}
func lastErrorTraceback(value string) string {
var lastErrorArray []map[string]string
err := json.Unmarshal([]byte(value), &lastErrorArray)
if err != nil || len(lastErrorArray) == 0 {
return "No traceback"
}
lastErrorArray[0]["traceback"] = strings.Replace(lastErrorArray[0]["traceback"], "\n", "\n ", -1)
lastErrorArray[0]["traceback"] = strings.TrimRight(lastErrorArray[0]["traceback"], "\n\t ")
return lastErrorArray[0]["traceback"]
}
// lastErrorMessage converts the last error message to html
func lastErrorMessage(value string) string {
var lastErrorArray []map[string]string
err := json.Unmarshal([]byte(value), &lastErrorArray)
if err == nil && len(lastErrorArray) > 0 {
if msg, ok := lastErrorArray[0]["message"]; ok {
return msg
}
}
return value
}
// formatUnixTime formats the unix time to make it more readable
func formatUnixTime(unixTime float64) string {
// Initially treat given unixTime is in nanoseconds
t := time.Unix(0, int64(unixTime))
// If year returned 1970, assume unixTime actually in seconds
if t.Year() == time.Unix(0, 0).Year() {
t = time.Unix(int64(unixTime), 0)
}
_, tzoffset := t.Zone()
result := t.Format(timeFormat)
if tzoffset != 0 {
result += " / " + t.UTC().Format(timeFormat)
}
msec := t.UnixNano() / int64(time.Millisecond)
result += " (" + strconv.Itoa(int(msec)) + ")"
return result
}
func printDashes(s string, dash string) string {
return strings.Repeat(dash, stringLength(s))
}
func toUnsortedList(s map[string]interface{}) string {
res := make([]string, 0, len(s))
for key := range s {
res = append(res, key)
}
return fmt.Sprintf("%s", res)
}
// mkHuman adds commas to large numbers to assist readability in status outputs
func mkHuman(f float64) string {
return humanize.Commaf(f)
}
// mkHumanDuration makes time values more readable
func mkHumanDuration(f float64, unit string) string {
var duration time.Duration
if unit != "" {
duration, _ = time.ParseDuration(fmt.Sprintf("%f%s", f, unit))
} else {
duration = time.Duration(int64(f)) * time.Second
}
return duration.String()
}
func stringLength(s string) int {
/*
len(string) is wrong if the string has unicode characters in it,
for example, something like 'Agent (v6.0.0+Χελωνη)' has len(s) == 27.
This is a better way of counting a string length
(credit goes to https://stackoverflow.com/a/12668840)
*/
var ia norm.Iter
ia.InitString(norm.NFKD, s)
nc := 0
for !ia.Done() {
nc = nc + 1
ia.Next()
}
return nc
}
// add two integer together
func add(x, y int) int {
return x + y
}
// formatTitle split a camel case string into space-separated words
func formatTitle(title string) string {
if title == "os" {
return "OS"
}
// Split camel case words
var words []string
var l int
for s := title; s != ""; s = s[l:] {
l = strings.IndexFunc(s[1:], unicode.IsUpper) + 1
if l <= 0 {
l = len(s)
}
words = append(words, s[:l])
}
title = strings.Join(words, " ")
// Capitalize the first letter
return cases.Title(language.English, cases.NoLower).String(title)
}
func status(check map[string]interface{}) string {
if check["LastError"].(string) != "" {
return fmt.Sprintf("[%s]", color.RedString("ERROR"))
}
if len(check["LastWarnings"].([]interface{})) != 0 {
return fmt.Sprintf("[%s]", color.YellowString("WARNING"))
}
return fmt.Sprintf("[%s]", color.GreenString("OK"))
}
func complianceResult(result string) string {
switch result {
case "error":
return fmt.Sprintf("[%s]", color.RedString("ERROR"))
case "failed":
return fmt.Sprintf("[%s]", color.RedString("FAILED"))
case "passed":
return fmt.Sprintf("[%s]", color.GreenString("PASSED"))
default:
return fmt.Sprintf("[%s]", color.YellowString("UNKNOWN"))
}
}
// Renders the message in a red color
func redText(message string) string {
return color.RedString(message)
}
// Renders the message in a yellow color
func yellowText(message string) string {
return color.YellowString(message)
}
// Renders the message in a green color
func greenText(message string) string {
return color.GreenString(message)
}
// Tells if the ntp offset may be too large, resulting in metrics
// from the agent being dropped by metrics-intake
func ntpWarning(ntpOffset float64) bool {
// Negative offset => clock is in the future, 10 minutes (600s) allowed
// Positive offset => clock is in the past, 60 minutes (3600s) allowed
// According to https://docs.datadoghq.com/developers/metrics/#submitting-metrics
return ntpOffset <= -600 || ntpOffset >= 3600
}
func getVersion(instances map[string]interface{}) string {
if len(instances) == 0 {
return ""
}
for _, instance := range instances {
instanceMap := instance.(map[string]interface{})
version, ok := instanceMap["CheckVersion"]
if !ok {
return ""
}
str, ok := version.(string)
if !ok {
return ""
}
return str
}
return ""
}