blob: b869f8a107a56387997f089b03cead682c5de0a5 [file] [log] [blame]
Serge Bazanski424e2012023-02-15 23:31:49 +01001package reflection
2
3import (
4 "context"
5 "database/sql"
6 "fmt"
7 "strings"
8
9 "github.com/iancoleman/strcase"
Serge Bazanski10b21542023-04-13 12:12:05 +020010 "google.golang.org/protobuf/proto"
11 "google.golang.org/protobuf/reflect/protoreflect"
Serge Bazanski424e2012023-02-15 23:31:49 +010012 "k8s.io/klog/v2"
Serge Bazanski10b21542023-04-13 12:12:05 +020013
14 "source.monogon.dev/cloud/bmaas/server/api"
Serge Bazanski424e2012023-02-15 23:31:49 +010015)
16
17// Schema contains information about the tag types in a BMDB. It also contains an
18// active connection to the BMDB, allowing retrieval of data based on the
19// detected schema.
20//
21// It also contains an embedded connection to the CockroachDB database backing
22// this BMDB which is then used to retrieve data described by this schema.
23type Schema struct {
24 // TagTypes is the list of tag types extracted from the BMDB.
25 TagTypes []TagType
26 // Version is the go-migrate schema version of the BMDB this schema was extracted
27 // from. By convention, it is a stringified base-10 number representing the number
28 // of seconds since UNIX epoch of when the migration version was created, but
29 // this is not guaranteed.
30 Version string
31
32 db *sql.DB
33}
34
35// TagType describes the type of a BMDB Tag. Each tag in turn corresponds to a
36// CockroachDB database.
37type TagType struct {
38 // NativeName is the name of the table that holds tags of this type.
39 NativeName string
40 // Fields are the types of fields contained in this tag type.
41 Fields []TagFieldType
42}
43
44// Name returns the canonical name of this tag type. For example, a table named
45// machine_agent_started will have a canonical name AgentStarted.
46func (r *TagType) Name() string {
47 tableSuffix := strings.TrimPrefix(r.NativeName, "machine_")
48 parts := strings.Split(tableSuffix, "_")
49 // Capitalize some known acronyms.
50 for i, p := range parts {
51 parts[i] = strings.ReplaceAll(p, "os", "OS")
52 }
53 return strcase.ToCamel(strings.Join(parts, "_"))
54}
55
56// TagFieldType is the type of a field within a BMDB Tag. Each tag field in turn
57// corresponds to a column inside its Tag table.
58type TagFieldType struct {
59 // NativeName is the name of the column that holds this field type. It is also
60 // the canonical name of the field type.
61 NativeName string
62 // NativeType is the CockroachDB type name of this field.
63 NativeType string
64 // NativeUDTName is the CockroachDB user-defined-type name of this field. This is
65 // only valid if NativeType is 'USER-DEFINED'.
66 NativeUDTName string
Serge Bazanski10b21542023-04-13 12:12:05 +020067 // ProtoType is set non-nil if the field is a serialized protobuf of the same
68 // type as the given protoreflect.Message.
69 ProtoType protoreflect.Message
70}
71
72// knownProtoFields is a mapping from column name of a field containing a
73// serialized protobuf to an instance of a proto.Message that will be used to
74// parse that column's data.
75//
76// Just mapping from column name is fine enough for now as we have mostly unique
77// column names, and these column names uniquely map to a single type.
78var knownProtoFields = map[string]proto.Message{
79 "hardware_report_raw": &api.AgentHardwareReport{},
Serge Bazanski424e2012023-02-15 23:31:49 +010080}
81
82// HumanType returns a human-readable representation of the field's type. This is
83// not well-defined, and should be used only informatively.
84func (r *TagFieldType) HumanType() string {
Serge Bazanski10b21542023-04-13 12:12:05 +020085 if r.ProtoType != nil {
86 return fmt.Sprintf("%s", r.ProtoType.Descriptor().FullName())
87 }
Serge Bazanski424e2012023-02-15 23:31:49 +010088 switch r.NativeType {
89 case "USER-DEFINED":
90 return r.NativeUDTName
91 case "timestamp with time zone":
92 return "timestamp"
93 case "bytea":
94 return "bytes"
95 default:
96 return r.NativeType
97 }
98}
99
100// Reflect builds a runtime BMDB schema from a raw SQL connection to the BMDB
101// database. You're probably looking for bmdb.Connection.Reflect.
102func Reflect(ctx context.Context, db *sql.DB) (*Schema, error) {
103 // Get all tables in the currently connected to database.
104 rows, err := db.QueryContext(ctx, `
105 SELECT table_name
106 FROM information_schema.tables
107 WHERE table_catalog = current_database()
108 AND table_schema = 'public'
109 AND table_name LIKE 'machine\_%'
110 `)
111 if err != nil {
112 return nil, fmt.Errorf("could not query table names: %w", err)
113 }
114 defer rows.Close()
115
116 // Collect all table names for further processing.
117 var tableNames []string
118 for rows.Next() {
119 var name string
120 if err := rows.Scan(&name); err != nil {
121 return nil, fmt.Errorf("table name scan failed: %w", err)
122 }
123 tableNames = append(tableNames, name)
124 }
125
126 // Start processing each table into a TagType.
127 tags := make([]TagType, 0, len(tableNames))
128 for _, tagName := range tableNames {
129 // Get all columns of the table.
130 rows, err := db.QueryContext(ctx, `
131 SELECT column_name, data_type, udt_name
132 FROM information_schema.columns
133 WHERE table_catalog = current_database()
134 AND table_schema = 'public'
135 AND table_name = $1
136 `, tagName)
137 if err != nil {
138 return nil, fmt.Errorf("could not query columns: %w", err)
139 }
140
141 tag := TagType{
142 NativeName: tagName,
143 }
144
145 // Build field types from columns.
146 foundMachineID := false
147 for rows.Next() {
148 var column_name, data_type, udt_name string
149 if err := rows.Scan(&column_name, &data_type, &udt_name); err != nil {
150 rows.Close()
151 return nil, fmt.Errorf("column scan failed: %w", err)
152 }
153 if column_name == "machine_id" {
154 foundMachineID = true
155 continue
156 }
Serge Bazanski10b21542023-04-13 12:12:05 +0200157 field := TagFieldType{
Serge Bazanski424e2012023-02-15 23:31:49 +0100158 NativeName: column_name,
159 NativeType: data_type,
160 NativeUDTName: udt_name,
Serge Bazanski10b21542023-04-13 12:12:05 +0200161 }
162 if t, ok := knownProtoFields[column_name]; ok {
163 field.ProtoType = t.ProtoReflect()
164 }
165 tag.Fields = append(tag.Fields, field)
Serge Bazanski424e2012023-02-15 23:31:49 +0100166 }
167
168 // Make sure there's a machine_id key in the table, then remove it.
169 if !foundMachineID {
170 klog.Warningf("Table %q has no machine_id column, skipping", tag.NativeName)
171 continue
172 }
173
174 tags = append(tags, tag)
175 }
176
177 // Retrieve version information from go-migrate's schema_migrations table.
178 var version string
179 var dirty bool
180 if err := db.QueryRowContext(ctx, "SELECT version, dirty FROM schema_migrations").Scan(&version, &dirty); err != nil {
181 return nil, fmt.Errorf("could not select schema version: %w", err)
182 }
183 if dirty {
184 version += " DIRTY!!!"
185 }
186
187 return &Schema{
188 TagTypes: tags,
189 Version: version,
190
191 db: db,
192 }, nil
193}