This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
handle_pull.go
173 lines (152 loc) · 5.3 KB
/
handle_pull.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
// Copyright 2021 the Exposure Notifications Verification Server authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package statspuller
import (
"context"
"errors"
"fmt"
"net/http"
"sync"
"time"
"github.com/golang-jwt/jwt"
v1 "github.com/google/exposure-notifications-server/pkg/api/v1"
"github.com/google/exposure-notifications-server/pkg/logging"
"github.com/google/exposure-notifications-verification-server/internal/clients"
"github.com/google/exposure-notifications-verification-server/pkg/controller"
"github.com/google/exposure-notifications-verification-server/pkg/controller/certapi"
"github.com/google/exposure-notifications-verification-server/pkg/database"
"github.com/google/exposure-notifications-verification-server/pkg/jwthelper"
"github.com/hashicorp/go-multierror"
"github.com/sethvargo/go-retry"
"go.opencensus.io/stats"
"golang.org/x/sync/semaphore"
)
const (
statsPullerLock = "statsPullerLock"
)
// HandlePullStats pulls key-server statistics.
func (c *Controller) HandlePullStats() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger := logging.FromContext(ctx).Named("statspuller.HandlePullStats")
logger.Debugw("starting")
defer logger.Debugw("finishing")
ok, err := c.db.TryLock(ctx, statsPullerLock, c.config.StatsPullerMinPeriod)
if err != nil {
logger.Errorw("failed to acquite lock", "error", err)
c.h.RenderJSON(w, http.StatusInternalServerError, err)
return
}
if !ok {
logger.Debugw("skipping (too early)")
c.h.RenderJSON(w, http.StatusOK, fmt.Errorf("too early"))
return
}
// Get all of the realms with stats configured
statsConfigs, err := c.db.ListKeyServerStats()
if err != nil {
controller.InternalError(w, r, c.h, err)
return
}
var merr *multierror.Error
var merrLock sync.Mutex
sem := semaphore.NewWeighted(c.config.MaxWorkers)
var wg sync.WaitGroup
for _, realmStat := range statsConfigs {
if err := sem.Acquire(ctx, 1); err != nil {
controller.InternalError(w, r, c.h, fmt.Errorf("failed to acquire semaphore: %w", err))
return
}
wg.Add(1)
go func(ctx context.Context, realmStat *database.KeyServerStats) {
defer sem.Release(1)
defer wg.Done()
if err := c.pullOneStat(ctx, realmStat); err != nil {
merrLock.Lock()
defer merrLock.Unlock()
merr = multierror.Append(merr, fmt.Errorf("failed to pull stats for realm %d: %w", realmStat.RealmID, err))
}
}(ctx, realmStat)
}
wg.Wait()
if errs := merr.WrappedErrors(); len(errs) > 0 {
logger.Errorw("failed to pull stats", "errors", errs)
c.h.RenderJSON(w, http.StatusInternalServerError, errs)
return
}
stats.Record(ctx, mSuccess.M(1))
c.h.RenderJSON(w, http.StatusOK, nil)
})
}
func (c *Controller) pullOneStat(ctx context.Context, realmStat *database.KeyServerStats) error {
realmID := realmStat.RealmID
client := c.defaultKeyServerClient
if realmStat.KeyServerURLOverride != "" {
var err error
client, err = clients.NewKeyServerClient(
realmStat.KeyServerURLOverride,
clients.WithTimeout(c.config.DownloadTimeout),
clients.WithMaxBodySize(c.config.FileSizeLimitBytes))
if err != nil {
return fmt.Errorf("failed to create key server client: %w", err)
}
}
s, err := certapi.GetSignerForRealm(ctx, realmID, c.config.CertificateSigning, c.signerCache, c.db, c.kms)
if err != nil {
return fmt.Errorf("failed to retrieve signer for realm %d: %w", realmID, err)
}
audience := c.config.KeyServerStatsAudience
if realmStat.KeyServerAudienceOverride != "" {
audience = realmStat.KeyServerAudienceOverride
}
now := time.Now().UTC()
claims := &jwt.StandardClaims{
Audience: audience,
ExpiresAt: now.Add(5 * time.Minute).UTC().Unix(),
IssuedAt: now.Unix(),
Issuer: s.Issuer,
}
token := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
token.Header["kid"] = s.KeyID
signedJWT, err := jwthelper.SignJWT(token, s.Signer)
if err != nil {
return fmt.Errorf("failed to stat-pull token: %w", err)
}
// Attempt to download the stats with retries. We intentionally re-use the
// same JWT because it's valid for 5min and don't want the overhead of
// reconstructing and signing it.
var resp *v1.StatsResponse
b := retry.NewConstant(500 * time.Millisecond)
b = retry.WithMaxRetries(3, b)
if err := retry.Do(ctx, b, func(ctx context.Context) error {
var err error
resp, err = client.Stats(ctx, &v1.StatsRequest{}, signedJWT)
if err != nil {
return retry.RetryableError(fmt.Errorf("failed to make stats call: %w", err))
}
return nil
}); err != nil {
return errors.Unwrap(err)
}
for _, d := range resp.Days {
if d == nil {
continue
}
day := database.MakeKeyServerStatsDay(realmID, d)
if err = c.db.SaveKeyServerStatsDay(day); err != nil {
return fmt.Errorf("failed to save stats day: %w", err)
}
}
return nil
}