forked from adamlaska/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
318 lines (284 loc) · 10.2 KB
/
client.go
File metadata and controls
318 lines (284 loc) · 10.2 KB
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
package notmain
import (
"context"
"database/sql"
"fmt"
"io/ioutil"
"math/rand"
"strings"
"sync/atomic"
"time"
"github.com/jmhodges/clock"
capb "github.com/letsencrypt/boulder/ca/proto"
"github.com/letsencrypt/boulder/core"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/rocsp"
rocsp_config "github.com/letsencrypt/boulder/rocsp/config"
"github.com/letsencrypt/boulder/sa"
"github.com/letsencrypt/boulder/test/ocsp/helper"
"golang.org/x/crypto/ocsp"
)
type client struct {
issuers []rocsp_config.ShortIDIssuer
redis *rocsp.WritingClient
db *sql.DB // optional
ocspGenerator capb.OCSPGeneratorClient
clk clock.Clock
scanBatchSize int
logger blog.Logger
}
// processResult represents the result of attempting to sign and store status
// for a single certificateStatus ID. If `err` is non-nil, it indicates the
// attempt failed.
type processResult struct {
id uint64
err error
}
func getStartingID(ctx context.Context, clk clock.Clock, db *sql.DB) (int64, error) {
// To scan the DB efficiently, we want to select only currently-valid certificates. There's a
// handy expires index, but for selecting a large set of rows, using the primary key will be
// more efficient. So first we find a good id to start with, then scan from there. Note: since
// AUTO_INCREMENT can skip around a bit, we add padding to ensure we get all currently-valid
// certificates.
startTime := clk.Now().Add(-24 * time.Hour)
var minID *int64
err := db.QueryRowContext(
ctx,
"SELECT MIN(id) FROM certificateStatus WHERE notAfter >= ?",
startTime,
).Scan(&minID)
if err != nil {
return 0, fmt.Errorf("selecting minID: %w", err)
}
if minID == nil {
return 0, fmt.Errorf("no entries in certificateStatus (where notAfter >= %s)", startTime)
}
return *minID, nil
}
func (cl *client) loadFromDB(ctx context.Context, speed ProcessingSpeed, startFromID int64) error {
prevID := startFromID
var err error
if prevID == 0 {
prevID, err = getStartingID(ctx, cl.clk, cl.db)
if err != nil {
return fmt.Errorf("getting starting ID: %w", err)
}
}
// Find the current maximum id in certificateStatus. We do this because the table is always
// growing. If we scanned until we saw a batch with no rows, we would scan forever.
var maxID *int64
err = cl.db.QueryRowContext(
ctx,
"SELECT MAX(id) FROM certificateStatus",
).Scan(&maxID)
if err != nil {
return fmt.Errorf("selecting maxID: %w", err)
}
if maxID == nil {
return fmt.Errorf("no entries in certificateStatus")
}
// Limit the rate of reading rows.
frequency := time.Duration(float64(time.Second) / float64(time.Duration(speed.RowsPerSecond)))
// a set of all inflight certificate statuses, indexed by their `ID`.
inflightIDs := newInflight()
statusesToSign := cl.scanFromDB(ctx, prevID, *maxID, frequency, inflightIDs)
results := make(chan processResult, speed.ParallelSigns)
var runningSigners int32
for i := 0; i < speed.ParallelSigns; i++ {
atomic.AddInt32(&runningSigners, 1)
go cl.signAndStoreResponses(ctx, statusesToSign, results, &runningSigners)
}
var successCount, errorCount int64
for result := range results {
inflightIDs.remove(result.id)
if result.err != nil {
errorCount++
if errorCount < 10 ||
(errorCount < 1000 && rand.Intn(1000) < 100) ||
(errorCount < 100000 && rand.Intn(1000) < 10) ||
(rand.Intn(1000) < 1) {
cl.logger.Errf("error: %s", result.err)
}
} else {
successCount++
}
total := successCount + errorCount
if total < 10 ||
(total < 1000 && rand.Intn(1000) < 100) ||
(total < 100000 && rand.Intn(1000) < 10) ||
(rand.Intn(1000) < 1) {
cl.logger.Infof("stored %d responses, %d errors", successCount, errorCount)
}
}
cl.logger.Infof("done. processed %d successes and %d errors\n", successCount, errorCount)
if inflightIDs.len() != 0 {
return fmt.Errorf("inflightIDs non-empty! has %d items, lowest %d", inflightIDs.len(), inflightIDs.min())
}
return nil
}
// scanFromDB scans certificateStatus rows from the DB, starting with `minID`, and writes them to
// its output channel at a maximum frequency of `frequency`. When it's read all available rows, it
// closes its output channel and exits.
// If there is an error, it logs the error, closes its output channel, and exits.
func (cl *client) scanFromDB(ctx context.Context, prevID int64, maxID int64, frequency time.Duration, inflightIDs *inflight) <-chan *sa.CertStatusMetadata {
statusesToSign := make(chan *sa.CertStatusMetadata)
go func() {
defer close(statusesToSign)
var err error
currentMin := prevID
for currentMin < maxID {
currentMin, err = cl.scanFromDBOneBatch(ctx, currentMin, frequency, statusesToSign, inflightIDs)
if err != nil {
cl.logger.Infof("error scanning rows: %s", err)
}
}
}()
return statusesToSign
}
// scanFromDBOneBatch scans up to `cl.scanBatchSize` rows from certificateStatus, in order, and
// writes them to `output`. When done, it returns the highest `id` it saw during the scan.
// We do this in batches because if we tried to scan the whole table in a single query, MariaDB
// would terminate the query after a certain amount of data transferred.
func (cl *client) scanFromDBOneBatch(ctx context.Context, prevID int64, frequency time.Duration, output chan<- *sa.CertStatusMetadata, inflightIDs *inflight) (int64, error) {
rowTicker := time.NewTicker(frequency)
query := fmt.Sprintf("SELECT %s FROM certificateStatus WHERE id > ? ORDER BY id LIMIT ?",
strings.Join(sa.CertStatusMetadataFields(), ", "))
rows, err := cl.db.QueryContext(ctx, query, prevID, cl.scanBatchSize)
if err != nil {
return -1, fmt.Errorf("scanning certificateStatus: %w", err)
}
defer func() {
rerr := rows.Close()
if rerr != nil {
cl.logger.Infof("closing rows: %s", rerr)
}
}()
var scanned int
var previousID int64
for rows.Next() {
<-rowTicker.C
status := new(sa.CertStatusMetadata)
err := sa.ScanCertStatusMetadataRow(rows, status)
if err != nil {
return -1, fmt.Errorf("scanning row %d (previous ID %d): %w", scanned, previousID, err)
}
scanned++
inflightIDs.add(uint64(status.ID))
// Emit a log line every 100000 rows. For our current ~215M rows, that
// will emit about 2150 log lines. This probably strikes a good balance
// between too spammy and having a reasonably frequent checkpoint.
if scanned%100000 == 0 {
cl.logger.Infof("scanned %d certificateStatus rows. minimum inflight ID %d", scanned, inflightIDs.min())
}
output <- status
previousID = status.ID
}
return previousID, nil
}
// signAndStoreResponses consumes cert statuses on its input channel and writes them to its output
// channel. Before returning, it atomically decrements the provided runningSigners int. If the
// result is 0, indicating this was the last running signer, it closes its output channel.
func (cl *client) signAndStoreResponses(ctx context.Context, input <-chan *sa.CertStatusMetadata, output chan processResult, runningSigners *int32) {
defer func() {
if atomic.AddInt32(runningSigners, -1) <= 0 {
close(output)
}
}()
for status := range input {
ocspReq := &capb.GenerateOCSPRequest{
Serial: status.Serial,
IssuerID: status.IssuerID,
Status: string(status.Status),
Reason: int32(status.RevokedReason),
RevokedAt: status.RevokedDate.UnixNano(),
}
result, err := cl.ocspGenerator.GenerateOCSP(ctx, ocspReq)
if err != nil {
output <- processResult{id: uint64(status.ID), err: err}
continue
}
// ttl is the lifetime of the certificate
ttl := cl.clk.Now().Sub(status.NotAfter)
issuer, err := rocsp_config.FindIssuerByID(status.IssuerID, cl.issuers)
if err != nil {
output <- processResult{id: uint64(status.ID), err: err}
continue
}
err = cl.redis.StoreResponse(ctx, result.Response, issuer.ShortID(), ttl)
if err != nil {
output <- processResult{id: uint64(status.ID), err: err}
} else {
output <- processResult{id: uint64(status.ID), err: nil}
}
}
}
type expiredError struct {
serial string
ago time.Duration
}
func (e expiredError) Error() string {
return fmt.Sprintf("response for %s expired %s ago", e.serial, e.ago)
}
func (cl *client) storeResponsesFromFiles(ctx context.Context, files []string) error {
for _, respFile := range files {
respBytes, err := ioutil.ReadFile(respFile)
if err != nil {
return fmt.Errorf("reading response file %q: %w", respFile, err)
}
err = cl.storeResponse(ctx, respBytes, nil)
if err != nil {
return err
}
}
return nil
}
func (cl *client) storeResponse(ctx context.Context, respBytes []byte, ttl *time.Duration) error {
resp, err := ocsp.ParseResponse(respBytes, nil)
if err != nil {
return fmt.Errorf("parsing response: %w", err)
}
issuer, err := rocsp_config.FindIssuerByName(resp, cl.issuers)
if err != nil {
return fmt.Errorf("finding issuer for response: %w", err)
}
// Re-parse the response, this time verifying with the appropriate issuer
resp, err = ocsp.ParseResponse(respBytes, issuer.Certificate.Certificate)
if err != nil {
return fmt.Errorf("parsing response: %w", err)
}
serial := core.SerialToString(resp.SerialNumber)
if resp.NextUpdate.Before(cl.clk.Now()) {
return expiredError{
serial: serial,
ago: cl.clk.Now().Sub(resp.NextUpdate),
}
}
// Note: Here we set the TTL to slightly more than the lifetime of the
// OCSP response. In ocsp-updater we'll want to set it to the lifetime
// of the certificate, so that the metadata field doesn't fall out of
// storage even if we are down for days. However, in this tool we don't
// have the full certificate, so this will do.
if ttl == nil {
ttl_temp := resp.NextUpdate.Sub(cl.clk.Now()) + time.Hour
ttl = &ttl_temp
}
cl.logger.Infof("storing response for %s, generated %s, ttl %g hours",
serial,
resp.ThisUpdate,
ttl.Hours(),
)
err = cl.redis.StoreResponse(ctx, respBytes, issuer.ShortID(), *ttl)
if err != nil {
return fmt.Errorf("storing response: %w", err)
}
retrievedResponse, err := cl.redis.GetResponse(ctx, serial)
if err != nil {
return fmt.Errorf("getting response: %w", err)
}
parsedRetrievedResponse, err := ocsp.ParseResponse(retrievedResponse, issuer.Certificate.Certificate)
if err != nil {
return fmt.Errorf("parsing retrieved response: %w", err)
}
cl.logger.Infof("retrieved %s", helper.PrettyResponse(parsedRetrievedResponse))
return nil
}