/
enrichment.go
232 lines (216 loc) · 5.59 KB
/
enrichment.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
package postgres
import (
"context"
"crypto/md5"
"errors"
"fmt"
"io"
"sort"
"strconv"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/quay/zlog"
"github.com/quay/claircore/libvuln/driver"
"github.com/quay/claircore/pkg/microbatch"
)
var (
updateEnrichmentsCounter = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "updateenrichments_total",
Help: "Total number of database queries issued in the UpdateEnrichments method.",
},
[]string{"query"},
)
updateEnrichmentsDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "updateenrichments_duration_seconds",
Help: "Duration of all queries issued in the UpdateEnrichments method.",
},
[]string{"query"},
)
getEnrichmentsCounter = promauto.NewCounterVec(
prometheus.CounterOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "getenrichments_total",
Help: "Total number of database queries issued in the get method.",
},
[]string{"query", "success"},
)
getEnrichmentsDuration = promauto.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: "claircore",
Subsystem: "vulnstore",
Name: "getenrichments_duration_seconds",
Help: "Duration of all queries issued in the get method.",
},
[]string{"query", "success"},
)
)
// UpdateEnrichments creates a new UpdateOperation, inserts the provided
// EnrichmentRecord(s), and ensures enrichments from previous updates are not
// queried by clients.
func (s *Store) UpdateEnrichments(ctx context.Context, name string, fp driver.Fingerprint, es []driver.EnrichmentRecord) (uuid.UUID, error) {
const (
create = `
INSERT
INTO
update_operation (updater, fingerprint, kind)
VALUES
($1, $2, 'enrichment')
RETURNING
id, ref;`
insert = `
INSERT
INTO
enrichment (hash_kind, hash, updater, tags, data)
VALUES
($1, $2, $3, $4, $5)
ON CONFLICT
(hash_kind, hash)
DO
NOTHING;`
assoc = `
INSERT
INTO
uo_enrich (enrich, updater, uo, date)
VALUES
(
(
SELECT
id
FROM
enrichment
WHERE
hash_kind = $1
AND hash = $2
AND updater = $3
),
$3,
$4,
transaction_timestamp()
)
ON CONFLICT
DO
NOTHING;`
)
ctx = zlog.ContextWithValues(ctx, "component", "internal/vulnstore/postgres/UpdateEnrichments")
var id uint64
var ref uuid.UUID
start := time.Now()
if err := s.pool.QueryRow(ctx, create, name, string(fp)).Scan(&id, &ref); err != nil {
return uuid.Nil, fmt.Errorf("failed to create update_operation: %w", err)
}
updateEnrichmentsCounter.WithLabelValues("create").Add(1)
updateEnrichmentsDuration.WithLabelValues("create").Observe(time.Since(start).Seconds())
tx, err := s.pool.Begin(ctx)
if err != nil {
return uuid.Nil, fmt.Errorf("unable to start transaction: %w", err)
}
defer tx.Rollback(ctx)
zlog.Debug(ctx).
Str("ref", ref.String()).
Msg("update_operation created")
batch := microbatch.NewInsert(tx, 2000, time.Minute)
start = time.Now()
for i := range es {
hashKind, hash := hashEnrichment(&es[i])
err := batch.Queue(ctx, insert,
hashKind, hash, name, es[i].Tags, es[i].Enrichment,
)
if err != nil {
return uuid.Nil, fmt.Errorf("failed to queue enrichment: %w", err)
}
if err := batch.Queue(ctx, assoc, hashKind, hash, name, id); err != nil {
return uuid.Nil, fmt.Errorf("failed to queue association: %w", err)
}
}
if err := batch.Done(ctx); err != nil {
return uuid.Nil, fmt.Errorf("failed to finish batch enrichment insert: %w", err)
}
updateEnrichmentsCounter.WithLabelValues("insert_batch").Add(1)
updateEnrichmentsDuration.WithLabelValues("insert_batch").Observe(time.Since(start).Seconds())
if err := tx.Commit(ctx); err != nil {
return uuid.Nil, fmt.Errorf("failed to commit transaction: %w", err)
}
zlog.Debug(ctx).
Stringer("ref", ref).
Int("inserted", len(es)).
Msg("update_operation committed")
return ref, nil
}
func hashEnrichment(r *driver.EnrichmentRecord) (k string, d []byte) {
h := md5.New()
sort.Strings(r.Tags)
for _, t := range r.Tags {
io.WriteString(h, t)
h.Write([]byte("\x00"))
}
h.Write(r.Enrichment)
return "md5", h.Sum(nil)
}
func (s *Store) GetEnrichment(ctx context.Context, name string, tags []string) (res []driver.EnrichmentRecord, err error) {
const query = `
WITH
latest
AS (
SELECT
max(id) AS id
FROM
update_operation
WHERE
updater = $1
)
SELECT
e.tags, e.data
FROM
enrichment AS e,
uo_enrich AS uo,
latest
WHERE
uo.uo = latest.id
AND uo.enrich = e.id
AND e.tags && $2::text[];`
ctx = zlog.ContextWithValues(ctx, "component", "internal/vulnstore/postgres/GetEnrichment")
timer := prometheus.NewTimer(prometheus.ObserverFunc(func(v float64) {
getEnrichmentsDuration.WithLabelValues("query", strconv.FormatBool(errors.Is(err, nil)))
}))
defer timer.ObserveDuration()
defer func() {
getEnrichmentsCounter.WithLabelValues("query", strconv.FormatBool(errors.Is(err, nil))).Inc()
}()
var (
c *pgxpool.Conn
rows pgx.Rows
)
c, err = s.pool.Acquire(ctx)
if err != nil {
return nil, err
}
defer c.Release()
res = make([]driver.EnrichmentRecord, 0, 8) // Guess at capacity.
rows, err = c.Query(ctx, query, name, tags)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
i := len(res)
res = append(res, driver.EnrichmentRecord{})
r := &res[i]
err = rows.Scan(&r.Tags, &r.Enrichment)
if err != nil {
return nil, err
}
}
err = rows.Err()
return res, err
}