-
Notifications
You must be signed in to change notification settings - Fork 0
/
content_service.go
517 lines (457 loc) · 14.8 KB
/
content_service.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
package server
import (
"context"
"crypto/tls"
"fmt"
"io"
"log"
"net/http"
"net/url"
"reflect"
"strconv"
"sync"
"time"
prom_exporter "contrib.go.opencensus.io/exporter/prometheus"
"github.com/childoftheuniverse/cstatic/config"
"github.com/childoftheuniverse/filesystem"
"github.com/gocql/gocql"
"github.com/golang/protobuf/proto"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
etcd "go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/mvcc/mvccpb"
"go.opencensus.io/trace"
)
var isInitialized = prometheus.NewGauge(prometheus.GaugeOpts{
Subsystem: "contentservice",
Name: "initialized",
Help: "Whether the service is initialized.",
})
var lastConfigReceived = prometheus.NewGauge(prometheus.GaugeOpts{
Subsystem: "contentservice",
Name: "last_config_received",
Help: "Timestamp at which the most recent configuration was read.",
})
var configIsValid = prometheus.NewGauge(prometheus.GaugeOpts{
Subsystem: "contentservice",
Name: "config_is_valid",
Help: "Whether the configuration last read from etcd is valid.",
})
var requestForUnknownSite = prometheus.NewCounter(prometheus.CounterOpts{
Subsystem: "contentservice",
Name: "request_for_unknown_site",
Help: "Number of requests received for a site that is not configured.",
})
var requestLatencies = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Subsystem: "contentservice",
Name: "request_latency",
Help: "Latency of upload requests",
Buckets: prometheus.ExponentialBuckets(0.001, 2, 50),
}, []string{"rpc_command"})
var cassandraLatencies = prometheus.NewHistogram(prometheus.HistogramOpts{
Subsystem: "contentservice",
Name: "cassandra_latency",
Help: "Latency of Cassandra requests",
Buckets: prometheus.ExponentialBuckets(0.001, 2, 50),
})
var cassandraRetries = prometheus.NewHistogram(prometheus.HistogramOpts{
Subsystem: "contentservice",
Name: "cassandra_retries",
Help: "Number of retries of Cassandra requests",
Buckets: prometheus.LinearBuckets(1.0, 1.0, 50),
})
var backendReadsPerRequest = prometheus.NewHistogram(prometheus.HistogramOpts{
Subsystem: "contentservice",
Name: "backend_reads_per_request",
Help: "Number of reads performed per request",
Buckets: prometheus.LinearBuckets(1.0, 1.0, 50),
})
var bytesPerRead = prometheus.NewHistogram(prometheus.HistogramOpts{
Subsystem: "contentservice",
Name: "backend_bytes_per_read",
Help: "Number of bytes returned per read request",
Buckets: prometheus.ExponentialBuckets(1.0, 1.5, 50),
})
func init() {
prometheus.MustRegister(isInitialized)
prometheus.MustRegister(lastConfigReceived)
prometheus.MustRegister(configIsValid)
prometheus.MustRegister(requestForUnknownSite)
prometheus.MustRegister(cassandraLatencies)
prometheus.MustRegister(cassandraRetries)
prometheus.MustRegister(backendReadsPerRequest)
prometheus.MustRegister(bytesPerRead)
}
func logError(prefix string, err error) {
if err != nil {
log.Printf("%s: %v", prefix, err)
}
}
/*
ContentService is an HTTP handler which looks up the relevant static files and
serves them to the client.
*/
type ContentService struct {
/* Listener configuration */
mux *http.ServeMux
tlsConfig *tls.Config
/* Config settings */
vhostSiteMap map[string]string
cassandraServers []string
settingsLock sync.RWMutex
/* Cassandra connection */
cluster *gocql.ClusterConfig
session *gocql.Session
/* Internal status */
initialized bool
configWatchCancelFunc context.CancelFunc
configWatcherRunning sync.Mutex
}
/*
Cleanup cancels all config watch operations currently in progress. It should be
invoked in response to termination signals being received.
*/
func (service *ContentService) Cleanup() {
if service.configWatchCancelFunc != nil {
service.configWatchCancelFunc()
}
service.initialized = false // We just stopped listening for config updates.
}
/*
WatchForConfigChanges watches the configured etcd location for updates and
invokes ServingConfig as required.
This function should only ever be called once, during initialization, and will
continue running in the background. Parallel invocations of this fuction on
the same ContentService will block until the previous incarnation has exited.
*/
func (service *ContentService) WatchForConfigChanges(
client *etcd.Client, etcdTimeout time.Duration, configPath string) {
var configUpdateChannel etcd.WatchChan
var configUpdate etcd.WatchResponse
var getResp *etcd.GetResponse
var kv *mvccpb.KeyValue
var rev int64
var ctx context.Context
var err error
service.configWatcherRunning.Lock()
defer service.configWatcherRunning.Unlock()
ctx, service.configWatchCancelFunc =
context.WithTimeout(context.Background(), etcdTimeout)
getResp, err = client.Get(ctx, configPath)
service.configWatchCancelFunc()
if err != nil {
log.Print("Error reading configuration from ", configPath, ": ", err)
service.Cleanup()
return
}
if len(getResp.Kvs) < 1 {
log.Print("Cannot find current version of ", configPath)
}
for _, kv = range getResp.Kvs {
rev = kv.ModRevision
service.ServingConfig(kv.Value)
}
ctx, service.configWatchCancelFunc =
context.WithCancel(context.Background())
defer service.configWatchCancelFunc()
configUpdateChannel = client.Watch(
ctx, configPath, etcd.WithCreatedNotify(),
etcd.WithRev(rev+1))
for configUpdate = range configUpdateChannel {
var ev *etcd.Event
for _, ev = range configUpdate.Events {
service.ServingConfig(ev.Kv.Value)
}
}
}
/*
ServingConfig receives a new configuration protocol buffer in binary format and
attempts to parse and enact it. If there were problems applying the new
configuration, the old configuration will be used.
*/
func (service *ContentService) ServingConfig(contents []byte) {
var cluster *gocql.ClusterConfig
var session *gocql.Session
var configProto config.CStaticConfig
var site *config.WebsiteConfig
var cassandraUpdated bool
var vhostSiteMap = make(map[string]string)
var err error
lastConfigReceived.Set(float64(time.Now().Unix()))
err = proto.Unmarshal(contents, &configProto)
if err != nil {
log.Print("Unable to parse received configuration: ", err)
return
}
/* Check whether we need to update our Cassandra connection. */
if len(configProto.CassandraServer) == 0 {
log.Print("No Cassandra servers specified in configuration.")
configIsValid.Set(0.0)
return
}
if !reflect.DeepEqual(service.cassandraServers, configProto.CassandraServer) {
cluster = gocql.NewCluster(
configProto.CassandraServer...)
cluster.Keyspace = configProto.Keyspace
session, err = cluster.CreateSession()
if err != nil {
log.Print("Unable to connect to Cassandra servers ",
configProto.CassandraServer, ": ", err)
return
}
session.SetConsistency(gocql.One)
cassandraUpdated = true
}
/* Update internal state on websites */
for _, site = range configProto.SiteConfigs {
var vhost string
for _, vhost = range site.VhostName {
vhostSiteMap[vhost] = site.Identifier
}
}
/* Apply new configuration */
service.settingsLock.Lock()
service.vhostSiteMap = vhostSiteMap
if cassandraUpdated {
service.cassandraServers = configProto.CassandraServer
service.cluster = cluster
service.session = session
}
service.initialized = true
service.settingsLock.Unlock()
/* Declare success. */
isInitialized.Set(1.0)
configIsValid.Set(1.0)
}
/*
IsHealthy determines whether the service is configured and ready to handle
requests. If IsHealthy is false, any requests should be rejected.
*/
func (service *ContentService) IsHealthy() bool {
return service.initialized && !service.session.Closed()
}
/*
MainLoop creates the HTTP listener and starts listening to connections.
The function only exits if a listener could not be created, or once the listener
has shut down.
*/
func (service *ContentService) MainLoop(listenAddr string) error {
var pe *prom_exporter.Exporter
var err error
service.mux = http.NewServeMux()
/* health check handler */
service.mux.HandleFunc("/health",
func(w http.ResponseWriter, r *http.Request) {
if service.IsHealthy() {
w.WriteHeader(http.StatusOK)
w.Write([]byte{'O', 'K'})
} else {
w.WriteHeader(http.StatusExpectationFailed)
w.Write([]byte{'B', 'A', 'D'})
}
})
/* Prometheus metrics */
err = prometheus.Register(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Subsystem: "uploadservice",
Name: "healthy",
Help: "Whether the service is currently healthy.",
},
func() float64 {
if service.IsHealthy() {
return 1.0
}
return 0.0
},
))
if err != nil {
return err
}
if pe, err = prom_exporter.NewExporter(prom_exporter.Options{
Namespace: "cstatic_content_server",
}); pe != nil {
return fmt.Errorf("Error creating prometheus exporter: %s", err)
}
service.mux.Handle("/metrics", promhttp.Handler())
service.mux.Handle("/metrics-grpc", pe)
service.mux.Handle("/", service)
return http.ListenAndServe(listenAddr, service.mux)
}
/*
ServeHTTP retrieves the requested file from the static config store and
returns it to the requestor.
*/
func (service *ContentService) ServeHTTP(
w http.ResponseWriter, r *http.Request) {
var startTime = time.Now()
defer requestLatencies.With(prometheus.Labels{
"rpc_command": "UploadSingleFile"}).Observe(
time.Now().Sub(startTime).Seconds())
var location string
var contentType string
var offset int64
var length int64
var myURL *url.URL
var contentURL *url.URL
var parentContext = r.Context()
var ctx context.Context
var span *trace.Span
var reader filesystem.ReadCloser
var limitedReader filesystem.ReadCloser
var seeker filesystem.Seeker
var siteID string
var query *gocql.Query
var buf = make([]byte, 1<<10)
var numReadsRequired uint64
var hasWritten bool
var ok bool
var err error
ctx, span = trace.StartSpan(parentContext, "ContentService.ServeHTTP")
defer span.End()
service.settingsLock.RLock()
defer service.settingsLock.RUnlock()
span.AddAttributes(
trace.StringAttribute("host-header", r.Host),
trace.StringAttribute("request-uri", r.RequestURI))
/* Before we do anything, check that this RPC is still relevant. */
if parentContext.Err() != nil {
/* TODO: increment a counter with the category of error */
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", parentContext.Err().Error()),
}, "Context expired")
return
}
if siteID, ok = service.vhostSiteMap[r.Host]; !ok {
requestForUnknownSite.Inc()
w.WriteHeader(http.StatusBadGateway)
w.Write([]byte("No vhost configured for this URL"))
return
}
span.AddAttributes(trace.StringAttribute("site-id", siteID))
if myURL, err = url.Parse("http://" + siteID + r.RequestURI); err != nil {
log.Print("Unable to parse original request URI: ", r.RequestURI)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error parsing request URI"))
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Request URI parsing failed")
return
}
span.Annotate(nil, "Running Casandra query")
query = service.session.Query(
"SELECT content_type, file_location, offset, length FROM "+
"file_contents WHERE site = ? AND path = ?",
siteID, myURL.Path).WithContext(ctx)
defer query.Release()
if err = query.Scan(&contentType, &location, &offset, &length); err != nil {
log.Print("Unable to scan for ", myURL.Path, ": ", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error fetching content metadata"))
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Scanning Cassandra table failed")
return
}
span.Annotate(nil, "Cassandra results are in")
cassandraLatencies.Observe(
(time.Duration(query.Latency()) * time.Nanosecond).Seconds())
cassandraRetries.Observe(float64(query.Attempts()))
if contentURL, err = url.Parse(location); err != nil {
log.Print("Unable to parse location for ", location, ": ", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error processing content metadata"))
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Location URI parsing failed")
return
}
span.AddAttributes(
trace.StringAttribute("content-url", contentURL.String()),
trace.StringAttribute("content-type", contentType),
trace.Int64Attribute("content-length", length))
if reader, err = filesystem.OpenReader(ctx, contentURL); err != nil {
log.Print("Unable to open ", contentURL.String(), ": ", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error processing content metadata"))
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Opening content URL failed")
return
}
defer logError(fmt.Sprintf("Error closing reader for %s",
contentURL.String()), reader.Close(ctx))
if seeker, ok = reader.(filesystem.Seeker); !ok {
log.Print("Filesystem type for ", contentURL.String(),
" does not support seeking")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Backend not supported"))
span.Annotate(nil, "Backend does not support seeking")
return
}
if _, err = seeker.Seek(ctx, offset, io.SeekStart); err != nil {
log.Print("Error seeking in ", contentURL.String(), ": ", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Read error"))
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Seek failed")
return
}
limitedReader = &filesystem.LimitedReadCloser{R: reader, N: length}
for {
var readTrace *trace.Span
var readCtx context.Context
var readLength int
if parentContext.Err() != nil {
/* TODO: increment a counter with the category of error */
span.Annotate(
[]trace.Attribute{
trace.StringAttribute("error",
parentContext.Err().Error()),
}, "Context expired")
break
}
readCtx, readTrace = trace.StartSpan(
ctx, "ContentService.ServeHTTP.Read")
defer readTrace.End()
numReadsRequired++
readLength, err = limitedReader.Read(readCtx, buf)
if err == io.EOF {
readTrace.AddAttributes(trace.BoolAttribute("eof", true))
break
}
if err != nil {
log.Print("Error reading from ", contentURL.String(), ": ", err)
if !hasWritten {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Read error"))
}
readTrace.Annotate(
[]trace.Attribute{
trace.StringAttribute("error", err.Error()),
}, "Content read error")
break
}
readTrace.AddAttributes(
trace.Int64Attribute("length", int64(readLength)))
bytesPerRead.Observe(float64(readLength))
if !hasWritten {
w.Header().Set("Content-Type", contentType)
w.Header().Set("Content-Length", strconv.FormatInt(length, 10))
w.WriteHeader(http.StatusOK)
hasWritten = true
}
if _, err = w.Write(buf[:readLength]); err != nil {
log.Print("Unable to write client response: ", err)
} else {
readTrace.Annotate(nil, "Success")
}
}
backendReadsPerRequest.Observe(float64(numReadsRequired))
}