-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
gen.go
826 lines (741 loc) · 23.3 KB
/
gen.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package main
import (
"bytes"
"flag"
"fmt"
"os"
"regexp"
"sort"
"strconv"
"strings"
"text/template"
"github.com/cockroachdb/cockroach/pkg/cli/exit"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/gostdlib/go/format"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "ERROR:", err)
exit.WithCode(exit.UnspecifiedError())
}
}
type reInfos struct {
reCnt int
infos []reInfo
reToName map[string]string
}
type reInfo struct {
ReName string
ReDef string
}
type catInfo struct {
Title string
Comment string
LogChannel string
EventNames []string
Events []*eventInfo
}
type enumInfo struct {
Comment string
GoType string
Values []enumValInfo
}
type enumValInfo struct {
Comment string
Name string
Value int
}
type eventInfo struct {
Comment string
LogChannel string
GoType string
Type string
Fields []fieldInfo
InheritedFields []fieldInfo
AllFields []fieldInfo
}
type fieldInfo struct {
Comment string
FieldType string
FieldName string
AlwaysReportingSafe bool
ReportingSafeRe string
MixedRedactable bool
Inherited bool
IsEnum bool
AllowZeroValue bool
Nullable bool
}
var (
packageFlag = flag.String("package", "eventpb", "package to use in generated go")
excludeEventFlag = flag.String("excluded-events", "", "regexp of events to exclude")
)
func run() error {
flag.Parse()
args := flag.CommandLine.Args()
if len(args) < 2 {
return errors.Newf("usage: %s <template> <protos...>\n", os.Args[0])
}
var excludedEvents *regexp.Regexp
if *excludeEventFlag != "" {
var err error
excludedEvents, err = regexp.Compile(*excludeEventFlag)
if err != nil {
return errors.Wrap(err, "invalid --excluded-events flag")
}
}
// Which template are we running?
tmplName := args[0]
tmplSrc, ok := templates[tmplName]
if !ok {
return errors.Newf("unknown template: %q", tmplName)
}
tmplFuncs := template.FuncMap{
// error produces an error.
"error": func(s string) string {
panic(errors.Newf("template error: %s", s))
},
// tableCell formats strings for use in a table cell. For example, it converts \n\n into <br>.
"tableCell": func(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
s = strings.ReplaceAll(s, "\r", "")
// Double newlines are paragraph breaks.
s = strings.ReplaceAll(s, "\n\n", "<br><br>")
// Other newlines are just width wrapping and should be converted to spaces.
s = strings.ReplaceAll(s, "\n", " ")
return s
},
}
tmpl, err := template.New(tmplName).Funcs(tmplFuncs).Parse(tmplSrc)
if err != nil {
return errors.Wrapf(err, "failed to parse template %q", tmplName)
}
// Read the input .proto file.
info := map[string]*eventInfo{}
enums := map[string]*enumInfo{}
cats := map[string]*catInfo{}
regexps := reInfos{reToName: map[string]string{}}
for i := 1; i < len(args); i++ {
if err := readInput(®exps, enums, info, cats, args[i]); err != nil {
return err
}
}
var keys []string
for k := range cats {
keys = append(keys, k)
}
sort.Strings(keys)
var sortedInfos []*eventInfo
var sortedCats []*catInfo
for _, k := range keys {
cat := cats[k]
sort.Strings(cat.EventNames)
for _, evname := range cat.EventNames {
ev := info[evname]
cat.Events = append(cat.Events, ev)
sortedInfos = append(sortedInfos, ev)
}
sortedCats = append(sortedCats, cat)
}
keys = nil
for k := range info {
if excludedEvents != nil && excludedEvents.MatchString(k) {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
var allSortedInfos []*eventInfo
for _, k := range keys {
allSortedInfos = append(allSortedInfos, info[k])
}
keys = nil
for k := range enums {
keys = append(keys, k)
}
sort.Strings(keys)
var allSortedEnums []*enumInfo
for _, k := range keys {
allSortedEnums = append(allSortedEnums, enums[k])
}
// Render the template.
var src bytes.Buffer
if err := tmpl.Execute(&src, struct {
Package string
AllRegexps []reInfo
Categories []*catInfo
Events []*eventInfo
AllEvents []*eventInfo
Enums []*enumInfo
}{
*packageFlag,
regexps.infos,
sortedCats,
sortedInfos,
allSortedInfos,
allSortedEnums,
}); err != nil {
return err
}
// If we are generating a .go file, do a pass of gofmt.
newBytes := src.Bytes()
if strings.HasSuffix(tmplName, "_go") {
newBytes, err = format.Source(newBytes)
if err != nil {
return errors.Wrap(err, "gofmt")
}
}
// Write the output file.
w := os.Stdout
if _, err := w.Write(newBytes); err != nil {
return err
}
return nil
}
func readInput(
regexps *reInfos,
enums map[string]*enumInfo,
infos map[string]*eventInfo,
cats map[string]*catInfo,
protoName string,
) error {
protoData, err := os.ReadFile(protoName)
if err != nil {
return err
}
inMsg := false
inEnum := false
comment := ""
channel := ""
var curCat *catInfo
var curMsg *eventInfo
var curEnum *enumInfo
for _, line := range strings.Split(string(protoData), "\n") {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "//") {
comment += strings.TrimSpace(line[2:]) + "\n"
continue
}
if line == "" {
if strings.HasPrefix(comment, "Category:") {
lines := strings.SplitN(comment, "\n", 3)
if len(lines) < 3 || !strings.HasPrefix(lines[1], "Channel:") {
return errors.New("invalid category comment: missing Channel specification")
}
title := strings.TrimSpace(strings.SplitN(lines[0], ":", 2)[1])
channel = strings.TrimSpace(strings.SplitN(lines[1], ":", 2)[1])
if _, ok := channels[channel]; !ok {
return errors.Newf("unknown channel name: %q", channel)
}
curCat = &catInfo{
Title: title,
Comment: strings.TrimSpace(strings.Join(lines[2:], "\n")),
LogChannel: channel,
}
cats[title] = curCat
}
comment = ""
continue
}
if !inEnum && !inMsg && strings.HasPrefix(line, "enum ") {
inEnum = true
typ := strings.Split(line, " ")[1]
if _, ok := enums[typ]; ok {
return errors.Newf("duplicate enum type: %q", typ)
}
curEnum = &enumInfo{
Comment: comment,
GoType: typ,
}
comment = ""
enums[typ] = curEnum
continue
}
if inEnum {
if strings.HasPrefix(line, "}") {
inEnum = false
comment = ""
continue
}
// At this point, we don't support definitions that don't fit on a single line.
if !strings.Contains(line, ";") {
return errors.Newf("enum value definition must not span multiple lines: %q", line)
}
if !enumValDefRe.MatchString(line) {
return errors.Newf("invalid enum value definition: %q", line)
}
tag := enumValDefRe.ReplaceAllString(line, "$tag")
val := enumValDefRe.ReplaceAllString(line, "$val")
vali, err := strconv.Atoi(val)
if err != nil {
return errors.Wrapf(err, "parsing %q", line)
}
comment = strings.TrimSpace(strings.TrimPrefix(comment, tag))
curEnum.Values = append(curEnum.Values, enumValInfo{
Comment: comment,
Name: tag,
Value: vali,
})
comment = ""
}
if !inMsg && !inEnum && strings.HasPrefix(line, "message ") {
inMsg = true
typ := strings.Split(line, " ")[1]
if _, ok := infos[typ]; ok {
return errors.Newf("duplicate message type: %q", typ)
}
snakeType := camelToSnake(typ)
if strings.HasPrefix(comment, typ) {
comment = "An event of type `" + snakeType + "`" + strings.TrimPrefix(comment, typ)
}
curMsg = &eventInfo{
Comment: comment,
GoType: typ,
Type: snakeType,
LogChannel: channel,
}
comment = ""
infos[typ] = curMsg
if !strings.HasPrefix(typ, "Common") {
if curCat == nil {
return errors.New("missing category specification at top of file")
}
curCat.EventNames = append(curCat.EventNames, typ)
}
continue
}
if inMsg {
if strings.HasPrefix(line, "}") {
inMsg = false
comment = ""
continue
}
// At this point, we don't support definitions that don't fit on a single line.
if !strings.Contains(line, ";") {
return errors.Newf("field definition must not span multiple lines: %q", line)
}
// Skip reserved fields.
if reservedDefRe.MatchString(line) {
continue
}
// A field.
if strings.HasPrefix(line, "repeated") {
line = "array_of_" + strings.TrimSpace(strings.TrimPrefix(line, "repeated"))
}
if !fieldDefRe.MatchString(line) {
return errors.Newf("unknown field definition syntax: %q", line)
}
notNullable := notNullableRe.MatchString(line)
// Allow zero values if the field is annotated with 'includeempty'.
allowZeroValue := strings.Contains(line, "includeempty")
typ := fieldDefRe.ReplaceAllString(line, "$typ")
switch typ {
case "google.protobuf.Timestamp":
typ = "timestamp"
case "cockroach.sql.sqlbase.Descriptor":
typ = "protobuf"
case "MVCCIteratorStats":
fallthrough
case "SampledExecStats":
// This is necessary so that the fields in the
// message doesn't get inlined.
typ = "nestedMessage"
}
if otherMsg, ok := infos[typ]; ok {
// Inline the fields from the other messages here.
curMsg.InheritedFields = append(curMsg.InheritedFields, otherMsg.Fields...)
curMsg.AllFields = append(curMsg.AllFields, fieldInfo{
FieldType: typ,
FieldName: typ,
Inherited: true,
})
} else {
_, isEnum := enums[typ]
name := snakeToCamel(fieldDefRe.ReplaceAllString(line, "$name"))
alwayssafe := false
mixed := false
if nameOverride := fieldDefRe.ReplaceAllString(line, "$noverride"); nameOverride != "" {
name = nameOverride
}
// redact:"nonsensitive" - always safe for reporting.
if reportingSafe := fieldDefRe.ReplaceAllString(line, "$reportingsafe"); reportingSafe != "" {
alwayssafe = true
if reportingSafe == "mixed" {
mixed = true
}
}
// Certain types are also always safe for reporting.
if !alwayssafe && isSafeType(typ) {
alwayssafe = true
}
// redact:"safeif:<regexp>" - safe for reporting if the string matches the regexp.
safeReName := ""
if re := fieldDefRe.ReplaceAllString(line, "$safeif"); re != "" {
var err error
// We're reading the regular expression from the .proto source, so we must
// take care of string un-escaping ourselves. If this code ever improves
// to apply as a protobuf plugin, this step can be removed.
re, err = strconv.Unquote(`"` + re + `"`)
if err != nil {
return errors.Wrapf(err, "error while unquoting regexp at %q", line)
}
safeRe := "^" + re + "$"
// Syntax check on regexp.
_, err = regexp.Compile(safeRe)
if err != nil {
return errors.Wrapf(err, "regexp %s is invalid (%q)", re, line)
}
// We want to reuse the regexp variables across fields if the regexps are the same.
if n, ok := regexps.reToName[safeRe]; ok {
safeReName = n
} else {
regexps.reCnt++
safeReName = fmt.Sprintf("safeRe%d", regexps.reCnt)
regexps.reToName[safeRe] = safeReName
regexps.infos = append(regexps.infos, reInfo{ReName: safeReName, ReDef: safeRe})
}
}
fi := fieldInfo{
Comment: comment,
FieldType: typ,
FieldName: name,
AlwaysReportingSafe: alwayssafe,
ReportingSafeRe: safeReName,
MixedRedactable: mixed,
IsEnum: isEnum,
AllowZeroValue: allowZeroValue,
Nullable: !notNullable,
}
curMsg.Fields = append(curMsg.Fields, fi)
curMsg.AllFields = append(curMsg.AllFields, fi)
}
comment = ""
}
}
return nil
}
func isSafeType(typ string) bool {
switch typ {
case "timestamp", "int32", "int64", "int16", "uint32", "uint64", "uint16", "bool", "float", "double":
return true
}
return false
}
var enumValDefRe = regexp.MustCompile(`\s*(?P<tag>[_A-Z0-9]+)[^=]*=[^0-9]*(?P<val>[0-9]+).*;`)
var fieldDefRe = regexp.MustCompile(`\s*(?P<typ>[a-z._A-Z0-9]+)` +
`\s+(?P<name>[a-z_]+)` +
`(;|` +
`\s+(.*customname\) = "(?P<noverride>[A-Za-z]+)")?` +
`(.*"redact:\\"(?P<reportingsafe>nonsensitive|mixed)\\"")?` +
`(.*"redact:\\"safeif:(?P<safeif>([^\\]|\\[^"])+)\\"")?` +
`).*$`)
var reservedDefRe = regexp.MustCompile(`\s*(reserved ([1-9][0-9]*);)`)
var notNullableRe = regexp.MustCompile(`\s*\(\s*gogoproto\.nullable\s*\)\s*=\s*false`)
func camelToSnake(typeName string) string {
var res strings.Builder
res.WriteByte(typeName[0] + 'a' - 'A')
for i := 1; i < len(typeName); i++ {
if typeName[i] >= 'A' && typeName[i] <= 'Z' {
res.WriteByte('_')
res.WriteByte(typeName[i] + 'a' - 'A')
} else {
res.WriteByte(typeName[i])
}
}
return res.String()
}
func snakeToCamel(typeName string) string {
var res strings.Builder
res.WriteByte(typeName[0] + 'A' - 'a')
for i := 1; i < len(typeName); i++ {
if typeName[i] == '_' {
i++
res.WriteByte(typeName[i] + 'A' - 'a')
} else {
res.WriteByte(typeName[i])
}
}
return res.String()
}
var templates = map[string]string{
"json_encode_go": `// Code generated by gen.go. DO NOT EDIT.
package {{ .Package }}
import (
"strconv"{{ if .AllRegexps }}
"regexp"{{end}}
"github.com/cockroachdb/redact"
"github.com/cockroachdb/cockroach/pkg/util/jsonbytes"
"github.com/gogo/protobuf/jsonpb"
)
{{range .AllRegexps}}
var {{ .ReName }} = regexp.MustCompile(` + "`{{ .ReDef }}`" + `)
{{end}}
var _ = jsonpb.Marshaler{}
{{range .AllEvents}}
// AppendJSONFields implements the EventPayload interface.
func (m *{{.GoType}}) AppendJSONFields(printComma bool, b redact.RedactableBytes) (bool, redact.RedactableBytes) {
{{range .AllFields }}
{{if .Inherited -}}
printComma, b = m.{{.FieldName}}.AppendJSONFields(printComma, b)
{{- else if eq .FieldType "string" -}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != "" {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":\""...)
{{ if .AlwaysReportingSafe -}}
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(m.{{.FieldName}})))
{{- else if ne .ReportingSafeRe "" }}
if {{ .ReportingSafeRe }}.MatchString(m.{{.FieldName}}) {
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(m.{{.FieldName}})))))
} else {
b = append(b, redact.StartMarker()...)
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(m.{{.FieldName}})))))
b = append(b, redact.EndMarker()...)
}
{{- else -}}
b = append(b, redact.StartMarker()...)
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(m.{{.FieldName}})))))
b = append(b, redact.EndMarker()...)
{{- end }}
b = append(b, '"')
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "array_of_string" -}}
if len(m.{{.FieldName}}) > 0 {
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":["...)
for i, v := range m.{{.FieldName}} {
if i > 0 { b = append(b, ',') }
b = append(b, '"')
{{ if .AlwaysReportingSafe -}}
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), v))
{{- else if ne .ReportingSafeRe "" }}
if {{ .ReportingSafeRe }}.MatchString(v) {
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(v)))))
} else {
b = append(b, redact.StartMarker()...)
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(v)))))
b = append(b, redact.EndMarker()...)
}
{{- else -}}
b = append(b, redact.StartMarker()...)
b = redact.RedactableBytes(jsonbytes.EncodeString([]byte(b), string(redact.EscapeMarkers([]byte(v)))))
b = append(b, redact.EndMarker()...)
{{- end }}
b = append(b, '"')
}
b = append(b, ']')
}
{{- else if eq .FieldType "bool" -}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = strconv.AppendBool(b, m.{{.FieldName}})
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "int16" "int32" "int64"}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != 0 {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = strconv.AppendInt(b, int64(m.{{.FieldName}}), 10)
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "float"}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != 0 {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = strconv.AppendFloat(b, float64(m.{{.FieldName}}), 'f', -1, 32)
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "double"}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != 0 {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = strconv.AppendFloat(b, float64(m.{{.FieldName}}), 'f', -1, 64)
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "uint16" "uint32" "uint64"}}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != 0 {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = strconv.AppendUint(b, uint64(m.{{.FieldName}}), 10)
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "array_of_uint32" -}}
if len(m.{{.FieldName}}) > 0 {
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":["...)
for i, v := range m.{{.FieldName}} {
if i > 0 { b = append(b, ',') }
b = strconv.AppendUint(b, uint64(v), 10)
}
b = append(b, ']')
}
{{- else if eq .FieldType "array_of_int32" -}}
if len(m.{{.FieldName}}) > 0 {
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":["...)
for i, v := range m.{{.FieldName}} {
if i > 0 { b = append(b, ',') }
b = strconv.AppendInt(b, int64(v), 10)
}
b = append(b, ']')
}
{{- else if eq .FieldType "array_of_uint64" -}}
if len(m.{{.FieldName}}) > 0 {
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":["...)
for i, v := range m.{{.FieldName}} {
if i > 0 { b = append(b, ',') }
b = strconv.AppendUint(b, uint64(v), 10)
}
b = append(b, ']')
}
{{- else if .IsEnum }}
{{ if not .AllowZeroValue -}}
if m.{{.FieldName}} != 0 {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
// Enums are defined in our code, so are always safe to print without
// redaction.
b = append(b, '"')
b = append(b, m.{{.FieldName}}.String()...)
b = append(b, '"')
{{ if not .AllowZeroValue -}}
}
{{- end }}
{{- else if eq .FieldType "array_of_LevelStats"}}
if len(m.{{.FieldName}}) > 0 {
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":["...)
for i, l := range m.{{.FieldName}} {
if i > 0 { b = append(b, ',') }
b = append(b, '{')
printComma, b = l.AppendJSONFields(false, b)
b = append(b, '}')
}
b = append(b, ']')
}
{{- else if eq .FieldType "protobuf"}}
if m.{{.FieldName}} != nil {
if printComma { b = append(b, ',')}; printComma = true
jsonEncoder := jsonpb.Marshaler{}
if str, err := jsonEncoder.MarshalToString(m.{{.FieldName}}); err == nil {
b = append(b, "\"{{.FieldName}}\":"...)
b = append(b, []byte(str)...)
}
}
{{- else if eq .FieldType "nestedMessage"}}
{{ if .Nullable -}}
if m.{{.FieldName}} != nil {
{{- end }}
if printComma { b = append(b, ',')}; printComma = true
b = append(b, "\"{{.FieldName}}\":"...)
b = append(b, '{')
printComma, b = m.{{.FieldName}}.AppendJSONFields(false, b)
b = append(b, '}')
{{ if .Nullable -}}
}
{{- end }}
{{- else}}
{{ error .FieldType }}
{{- end}}
{{end}}
return printComma, b
}
{{end}}
`,
"eventlog_channels_go": `// Code generated by gen.go. DO NOT EDIT.
package {{ .Package }}
import "github.com/cockroachdb/cockroach/pkg/util/log/logpb"
{{range .Events}}
// LoggingChannel implements the EventPayload interface.
func (m *{{.GoType}}) LoggingChannel() logpb.Channel { return logpb.Channel_{{.LogChannel}} }
{{end}}
`,
"eventlog.md": `Certain notable events are reported using a structured format.
Commonly, these notable events are also copied to the table
` + "`system.eventlog`" + `, unless the cluster setting
` + "`server.eventlog.enabled`" + ` is unset.
Additionally, notable events are copied to specific external logging
channels in log messages, where they can be collected for further processing.
The sections below document the possible notable event types
in this version of CockroachDB. For each event type, a table
documents the possible fields. A field may be omitted from
an event if its value is empty or zero.
A field is also considered "Sensitive" if it may contain
application-specific information or personally identifiable information (PII). In that case,
the copy of the event sent to the external logging channel
will contain redaction markers in a format that is compatible
with the redaction facilities in ` + "[`cockroach debug zip`](cockroach-debug-zip.html)" + `
and ` + "[`cockroach debug merge-logs`](cockroach-debug-merge-logs.html)" + `,
provided the ` + "`redactable`" + ` functionality is enabled on the logging sink.
Events not documented on this page will have an unstructured format in log messages.
{{range .Categories -}}
## {{.Title}}
{{.Comment}}
Events in this category are logged to the ` + "`" + `{{.LogChannel}}` + "`" + ` channel.
{{range .Events}}
### ` + "`" + `{{.Type}}` + "`" + `
{{.Comment}}
{{if .Fields -}}
| Field | Description | Sensitive |
|--|--|--|
{{range .Fields -}}
| ` + "`" + `{{- .FieldName -}}` + "`" + ` | {{ .Comment | tableCell }}{{- if .IsEnum }} See below for possible values for type ` + "`" + `{{- .FieldType -}}` + "`" + `.{{- end }} | {{ if .MixedRedactable }}partially{{ else if .AlwaysReportingSafe }}no{{else if ne .ReportingSafeRe "" }}depends{{else}}yes{{end}} |
{{end}}
{{- end}}
{{if .InheritedFields -}}
#### Common fields
| Field | Description | Sensitive |
|--|--|--|
{{range .InheritedFields -}}
| ` + "`" + `{{- .FieldName -}}` + "`" + ` | {{ .Comment | tableCell }} | {{ if .MixedRedactable }}partially{{ else if .AlwaysReportingSafe }}no{{else if ne .ReportingSafeRe "" }}depends{{else}}yes{{end}} |
{{end}}
{{- end}}
{{- end}}
{{end}}
{{if .Enums}}
## Enumeration types
{{range .Enums}}
### ` + "`" + `{{ .GoType }}` + "`" + `
{{ .Comment }}
| Value | Textual alias in code or documentation | Description |
|--|--|--|
{{range .Values -}}
| {{ .Value }} | {{ .Name }} | {{ .Comment | tableCell }} |
{{end}}
{{end}}
{{end}}
`,
}