-
Notifications
You must be signed in to change notification settings - Fork 6
/
manager.go
306 lines (265 loc) · 7.9 KB
/
manager.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
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
// Copyright 2018 Google LLC
//
// 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 product
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"time"
"github.com/apigee/apigee-remote-service-golib/v2/auth"
"github.com/apigee/apigee-remote-service-golib/v2/log"
"github.com/apigee/apigee-remote-service-golib/v2/util"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
)
const productsURL = "/products"
/*
Usage:
pp := createManager()
pp.start()
products := pp.Products()
...
pp.close() // when done
*/
// A Manager wraps all things related to a set of API products.
type Manager interface {
Products() ProductsNameMap
Authorize(authContext *auth.Context, api, path, method string) []AuthorizedOperation
Close()
}
func createManager(options Options) *manager {
return &manager{
baseURL: options.BaseURL,
closedChan: make(chan bool),
returnChan: make(chan map[string]*APIProduct),
closed: util.NewAtomicBool(false),
refreshRate: options.RefreshRate,
client: options.Client,
env: options.Env, // note: "*" means multitenant
prometheusLabels: prometheus.Labels{"org": options.Org},
}
}
type manager struct {
baseURL *url.URL
closed *util.AtomicBool
closedChan chan bool
returnChan chan map[string]*APIProduct
refreshRate time.Duration
client *http.Client
productsMux productsMux
cancelPolling context.CancelFunc
prometheusLabels prometheus.Labels
env string
}
// AuthorizedOperation is the result of Authorize including Quotas
type AuthorizedOperation struct {
ID string
QuotaLimit int64
QuotaInterval int64
QuotaTimeUnit string
}
// Authorize a request against API Products and its Operations
func (m *manager) Authorize(authContext *auth.Context, api, path, method string) []AuthorizedOperation {
authorizedOps, hints := authorize(authContext, m.Products(), api, path, method, log.DebugEnabled())
if log.DebugEnabled() {
log.Debugf(hints)
}
return authorizedOps
}
// broken out for testing
func authorize(authContext *auth.Context, productsByName map[string]*APIProduct, api, path, method string, hints bool) ([]AuthorizedOperation, string) {
var authorizedOps []AuthorizedOperation
authorizedProducts := authContext.APIProducts
var hintsBuilder strings.Builder
addHint := func(hint string) {
if hintsBuilder.Len() == 0 {
hintsBuilder.WriteString("Authorizing request:\n")
hintsBuilder.WriteString(fmt.Sprintf(" environment: %s\n", authContext.Environment()))
hintsBuilder.WriteString(fmt.Sprintf(" products: %v\n", authorizedProducts))
hintsBuilder.WriteString(fmt.Sprintf(" scopes: %v\n", authContext.Scopes))
hintsBuilder.WriteString(fmt.Sprintf(" operation: %s %s\n", method, path))
hintsBuilder.WriteString(fmt.Sprintf(" api: %s\n", api))
}
hintsBuilder.WriteString(hint)
}
for _, name := range authorizedProducts {
var prodAPIs []AuthorizedOperation
var hint string = " not found\n"
if product, ok := productsByName[name]; ok {
prodAPIs, hint = product.authorize(authContext, api, path, method, hints)
authorizedOps = append(authorizedOps, prodAPIs...)
}
if hints && hint != "" {
addHint(fmt.Sprintf(" - product: %s\n", name))
addHint(hint)
}
}
return authorizedOps, hintsBuilder.String()
}
// Products atomically gets a mapping of name => APIProduct.
func (m *manager) Products() ProductsNameMap {
if m.closed.IsTrue() {
return nil
}
return m.productsMux.Get()
}
// Close shuts down the manager.
func (m *manager) Close() {
if m == nil || m.closed.SetTrue() {
return
}
log.Infof("closing product manager")
m.cancelPolling()
m.productsMux.Close()
log.Infof("closed product manager")
}
func (m *manager) start() {
log.Infof("starting product manager")
m.productsMux = productsMux{
setChan: make(chan ProductsNameMap),
getChan: make(chan ProductsNameMap),
closeChan: make(chan struct{}),
closed: util.NewAtomicBool(false),
}
go m.productsMux.mux()
poller := util.Looper{
Backoff: util.NewExponentialBackoff(200*time.Millisecond, m.refreshRate, 2, true),
}
apiURL := *m.baseURL
apiURL.Path = path.Join(apiURL.Path, productsURL)
if m.env != "*" { // if env is not *, pull specified env
apiURL.Query().Add("env", m.env)
}
ctx, cancel := context.WithCancel(context.Background())
m.cancelPolling = cancel
poller.Start(ctx, m.pollingClosure(apiURL), m.refreshRate, func(err error) error {
log.Errorf("Error retrieving products: %v", err)
return nil
})
log.Infof("started product manager")
}
func (m *manager) pollingClosure(apiURL url.URL) func(ctx context.Context) error {
var etag string
return func(ctx context.Context) error {
req, err := http.NewRequest(http.MethodGet, apiURL.String(), nil)
if err != nil {
return err
}
req = req.WithContext(ctx) // make cancelable from poller
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
if etag != "" {
req.Header.Set("If-None-Match", etag)
}
log.Debugf("retrieving products from: %s", apiURL.String())
resp, err := m.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Errorf("Unable to read server response: %v", err)
return err
}
if resp.StatusCode == 304 {
log.Debugf("products not modified")
return nil
}
if resp.StatusCode != 200 {
err := fmt.Errorf("products request failed (%d): %s", resp.StatusCode, string(body))
log.Errorf(err.Error())
return err
}
etag = resp.Header.Get("ETag")
if etag != "" {
log.Debugf("received etag for products request: '%s'", etag)
}
var res APIResponse
err = json.Unmarshal(body, &res)
if err != nil {
log.Errorf("unable to unmarshal JSON response '%s': %v", string(body), err)
return err
}
// parses products and creates name -> product lookup map
pm := ProductsNameMap{}
for i, p := range res.APIProducts {
if ctx.Err() != nil {
log.Debugf("product polling canceled, exiting")
return nil
}
pm[p.Name] = &res.APIProducts[i]
}
m.productsMux.Set(pm)
prometheusProductsRecords.With(m.prometheusLabels).Set(float64(len(pm)))
log.Debugf("retrieved %d products, kept %d", len(res.APIProducts), len(pm))
return nil
}
}
// ProductsNameMap is a map of API Product name to API Product
type ProductsNameMap map[string]*APIProduct
type productsMux struct {
setChan chan ProductsNameMap
getChan chan ProductsNameMap
closeChan chan struct{}
closed *util.AtomicBool
}
func (p productsMux) Get() ProductsNameMap {
return <-p.getChan
}
func (p productsMux) Set(s ProductsNameMap) {
if p.closed.IsFalse() {
p.setChan <- s
}
}
func (p productsMux) Close() {
if !p.closed.SetTrue() {
close(p.closeChan)
}
}
func (p productsMux) mux() {
var productsMap ProductsNameMap
for {
if productsMap == nil {
select {
case <-p.closeChan:
close(p.setChan)
close(p.getChan)
return
case productsMap = <-p.setChan:
continue
}
}
select {
case productsMap = <-p.setChan:
case p.getChan <- productsMap:
case <-p.closeChan:
close(p.setChan)
close(p.getChan)
return
}
}
}
var (
prometheusProductsRecords = promauto.NewGaugeVec(prometheus.GaugeOpts{
Subsystem: "products",
Name: "cached",
Help: "Number of products cached in memory",
}, []string{"org"})
)