blob: 30ce6c496737f6208e672f9d91412705a2deb6c8 [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{
Tim Windelschmidt2bffb6f2023-04-24 19:06:10 +020079 "hardware_report_raw": &api.AgentHardwareReport{},
80 "os_installation_request_raw": &api.OSInstallationRequest{},
Serge Bazanski424e2012023-02-15 23:31:49 +010081}
82
83// HumanType returns a human-readable representation of the field's type. This is
84// not well-defined, and should be used only informatively.
85func (r *TagFieldType) HumanType() string {
Serge Bazanski10b21542023-04-13 12:12:05 +020086 if r.ProtoType != nil {
87 return fmt.Sprintf("%s", r.ProtoType.Descriptor().FullName())
88 }
Serge Bazanski424e2012023-02-15 23:31:49 +010089 switch r.NativeType {
90 case "USER-DEFINED":
91 return r.NativeUDTName
92 case "timestamp with time zone":
93 return "timestamp"
94 case "bytea":
95 return "bytes"
Tim Windelschmidt2bffb6f2023-04-24 19:06:10 +020096 case "bigint":
97 return "int"
Serge Bazanski424e2012023-02-15 23:31:49 +010098 default:
99 return r.NativeType
100 }
101}
102
103// Reflect builds a runtime BMDB schema from a raw SQL connection to the BMDB
104// database. You're probably looking for bmdb.Connection.Reflect.
105func Reflect(ctx context.Context, db *sql.DB) (*Schema, error) {
106 // Get all tables in the currently connected to database.
107 rows, err := db.QueryContext(ctx, `
108 SELECT table_name
109 FROM information_schema.tables
110 WHERE table_catalog = current_database()
111 AND table_schema = 'public'
112 AND table_name LIKE 'machine\_%'
113 `)
114 if err != nil {
115 return nil, fmt.Errorf("could not query table names: %w", err)
116 }
117 defer rows.Close()
118
119 // Collect all table names for further processing.
120 var tableNames []string
121 for rows.Next() {
122 var name string
123 if err := rows.Scan(&name); err != nil {
124 return nil, fmt.Errorf("table name scan failed: %w", err)
125 }
126 tableNames = append(tableNames, name)
127 }
128
129 // Start processing each table into a TagType.
130 tags := make([]TagType, 0, len(tableNames))
131 for _, tagName := range tableNames {
132 // Get all columns of the table.
133 rows, err := db.QueryContext(ctx, `
134 SELECT column_name, data_type, udt_name
135 FROM information_schema.columns
136 WHERE table_catalog = current_database()
137 AND table_schema = 'public'
138 AND table_name = $1
139 `, tagName)
140 if err != nil {
141 return nil, fmt.Errorf("could not query columns: %w", err)
142 }
143
144 tag := TagType{
145 NativeName: tagName,
146 }
147
148 // Build field types from columns.
149 foundMachineID := false
150 for rows.Next() {
151 var column_name, data_type, udt_name string
152 if err := rows.Scan(&column_name, &data_type, &udt_name); err != nil {
153 rows.Close()
154 return nil, fmt.Errorf("column scan failed: %w", err)
155 }
156 if column_name == "machine_id" {
157 foundMachineID = true
158 continue
159 }
Serge Bazanski10b21542023-04-13 12:12:05 +0200160 field := TagFieldType{
Serge Bazanski424e2012023-02-15 23:31:49 +0100161 NativeName: column_name,
162 NativeType: data_type,
163 NativeUDTName: udt_name,
Serge Bazanski10b21542023-04-13 12:12:05 +0200164 }
165 if t, ok := knownProtoFields[column_name]; ok {
166 field.ProtoType = t.ProtoReflect()
167 }
168 tag.Fields = append(tag.Fields, field)
Serge Bazanski424e2012023-02-15 23:31:49 +0100169 }
170
171 // Make sure there's a machine_id key in the table, then remove it.
172 if !foundMachineID {
173 klog.Warningf("Table %q has no machine_id column, skipping", tag.NativeName)
174 continue
175 }
176
177 tags = append(tags, tag)
178 }
179
180 // Retrieve version information from go-migrate's schema_migrations table.
181 var version string
182 var dirty bool
183 if err := db.QueryRowContext(ctx, "SELECT version, dirty FROM schema_migrations").Scan(&version, &dirty); err != nil {
184 return nil, fmt.Errorf("could not select schema version: %w", err)
185 }
186 if dirty {
187 version += " DIRTY!!!"
188 }
189
190 return &Schema{
191 TagTypes: tags,
192 Version: version,
193
194 db: db,
195 }, nil
196}