-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
main.go
96 lines (78 loc) · 2.47 KB
/
main.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
// 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 main holds main related files
package main
import (
"encoding/json"
"flag"
"os"
"reflect"
"strings"
"time"
"github.com/invopop/jsonschema"
"github.com/DataDog/datadog-agent/pkg/security/events"
"github.com/DataDog/datadog-agent/pkg/security/serializers"
"github.com/DataDog/datadog-agent/pkg/security/utils"
)
// CWSEvent is a similar struct to what we actually send to the backend, except in the real case
// we actually do some struct-less string concatenation optimization
type CWSEvent struct {
events.BackendEvent `json:",inline"`
serializers.EventSerializer `json:",inline"`
}
func generateBackendJSON(output string) error {
reflector := jsonschema.Reflector{
ExpandedStruct: true,
DoNotReference: false,
Mapper: jsonTypeMapper,
Namer: jsonTypeNamer,
}
if err := reflector.AddGoComments("github.com/DataDog/datadog-agent/pkg/security/serializers", "./"); err != nil {
return err
}
reflector.CommentMap = cleanupEasyjson(reflector.CommentMap)
schema := reflector.Reflect(&CWSEvent{})
schema.ID = "https://github.com/DataDog/datadog-agent/tree/main/pkg/security/serializers"
schemaJSON, err := json.MarshalIndent(schema, "", " ")
if err != nil {
return err
}
return os.WriteFile(output, schemaJSON, 0664)
}
func jsonTypeMapper(ty reflect.Type) *jsonschema.Schema {
if ty == reflect.TypeOf(utils.EasyjsonTime{}) {
schema := jsonschema.Reflect(time.Time{})
schema.Version = ""
return schema
}
return nil
}
func cleanupEasyjson(commentMap map[string]string) map[string]string {
res := make(map[string]string, len(commentMap))
for name, comment := range commentMap {
cleaned := strings.TrimSpace(comment)
cleaned = strings.TrimSuffix(cleaned, "easyjson:json")
res[name] = strings.TrimSpace(cleaned)
}
return res
}
func jsonTypeNamer(ty reflect.Type) string {
const selinuxPrefix = "selinux"
base := strings.TrimSuffix(ty.Name(), "Serializer")
if strings.HasPrefix(base, selinuxPrefix) {
return "SELinux" + strings.TrimPrefix(base, selinuxPrefix)
}
return base
}
func main() {
var (
output string
)
flag.StringVar(&output, "output", "", "Backend JSON schema generated file")
flag.Parse()
if err := generateBackendJSON(output); err != nil {
panic(err)
}
}