This repository has been archived by the owner on Dec 1, 2022. It is now read-only.
forked from knative/serving
/
main.go
621 lines (536 loc) · 21 KB
/
main.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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
Copyright 2018 The Knative 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 main
import (
"context"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
"go.opencensus.io/plugin/ochttp"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
"go.opencensus.io/trace"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
pkglogging "knative.dev/pkg/logging"
"knative.dev/pkg/logging/logkey"
"knative.dev/pkg/metrics"
"knative.dev/pkg/profiling"
"knative.dev/pkg/signals"
"knative.dev/pkg/tracing"
tracingconfig "knative.dev/pkg/tracing/config"
"knative.dev/serving/pkg/activator"
activatorutil "knative.dev/serving/pkg/activator/util"
"knative.dev/serving/pkg/apis/networking"
"knative.dev/serving/pkg/autoscaler"
pkghttp "knative.dev/serving/pkg/http"
"knative.dev/serving/pkg/logging"
"knative.dev/serving/pkg/network"
"knative.dev/serving/pkg/queue"
"knative.dev/serving/pkg/queue/health"
"knative.dev/serving/pkg/queue/readiness"
queuestats "knative.dev/serving/pkg/queue/stats"
)
const (
// Add enough buffer to not block request serving on stats collection
requestCountingQueueLength = 100
// Duration the /quitquitquit handler should wait before returning.
// This is to give Istio a little bit more time to remove the pod
// from its configuration and propagate that to all istio-proxies
// in the mesh.
quitSleepDuration = 20 * time.Second
badProbeTemplate = "unexpected probe header value: %s"
// Metrics' names (without component prefix).
requestCountN = "request_count"
responseTimeInMsecN = "request_latencies"
appRequestCountN = "app_request_count"
appResponseTimeInMsecN = "app_request_latencies"
queueDepthN = "queue_depth"
healthURLTemplate = "http://127.0.0.1:%d"
tcpProbeTimeout = 100 * time.Millisecond
// The 25 millisecond retry interval is an unscientific compromise between wanting to get
// started as early as possible while still wanting to give the container some breathing
// room to get up and running.
aggressivePollInterval = 25 * time.Millisecond
// reportingPeriod is the interval of time between reporting stats by queue proxy.
reportingPeriod = 1 * time.Second
)
var (
logger *zap.SugaredLogger
// Metric counters.
requestCountM = stats.Int64(
requestCountN,
"The number of requests that are routed to queue-proxy",
stats.UnitDimensionless)
responseTimeInMsecM = stats.Float64(
responseTimeInMsecN,
"The response time in millisecond",
stats.UnitMilliseconds)
appRequestCountM = stats.Int64(
appRequestCountN,
"The number of requests that are routed to user-container",
stats.UnitDimensionless)
appResponseTimeInMsecM = stats.Float64(
appResponseTimeInMsecN,
"The response time in millisecond",
stats.UnitMilliseconds)
queueDepthM = stats.Int64(
queueDepthN,
"The current number of items in the serving and waiting queue, or not reported if unlimited concurrency.",
stats.UnitDimensionless)
readinessProbeTimeout = flag.Int("probe-period", -1, "run readiness probe with given timeout")
)
type config struct {
ContainerConcurrency int `split_words:"true" required:"true"`
QueueServingPort int `split_words:"true" required:"true"`
UserPort int `split_words:"true" required:"true"`
RevisionTimeoutSeconds int `split_words:"true" required:"true"`
ServingReadinessProbe string `split_words:"true" required:"true"`
EnableProfiling bool `split_words:"true"` // optional
// Logging configuration
ServingLoggingConfig string `split_words:"true" required:"true"`
ServingLoggingLevel string `split_words:"true" required:"true"`
ServingRequestLogTemplate string `split_words:"true"` // optional
ServingEnableProbeRequestLog bool `split_words:"true"` // optional
// Metrics configuration
ServingNamespace string `split_words:"true" required:"true"`
ServingRevision string `split_words:"true" required:"true"`
ServingConfiguration string `split_words:"true" required:"true"`
ServingPodIP string `split_words:"true" required:"true"`
ServingPod string `split_words:"true" required:"true"`
ServingService string `split_words:"true"` // optional
ServingRequestMetricsBackend string `split_words:"true"` // optional
// /var/log configuration
EnableVarLogCollection bool `split_words:"true"` // optional
UserContainerName string `split_words:"true"` // optional
VarLogVolumeName string `split_words:"true"` // optional
InternalVolumePath string `split_words:"true"` // optional
// Tracing configuration
TracingConfigDebug bool `split_words:"true"` // optional
TracingConfigBackend tracingconfig.BackendType `split_words:"true"` // optional
TracingConfigSampleRate float64 `split_words:"true"` // optional
TracingConfigZipkinEndpoint string `split_words:"true"` // optional
TracingConfigStackdriverProjectID string `split_words:"true"` // optional
}
// Make handler a closure for testing.
func handler(reqChan chan queue.ReqEvent, breaker *queue.Breaker, handler http.Handler,
healthState *health.State, prober func() bool, isAggressive bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// TODO: Move probe part to network.NewProbeHandler if possible or another handler.
if ph := network.KnativeProbeHeader(r); ph != "" {
handleKnativeProbe(w, r, ph, healthState, prober, isAggressive)
return
}
proxyCtx, proxySpan := trace.StartSpan(r.Context(), "proxy")
defer proxySpan.End()
// Metrics for autoscaling.
in, out := queue.ReqIn, queue.ReqOut
if activator.Name == network.KnativeProxyHeader(r) {
in, out = queue.ProxiedIn, queue.ProxiedOut
}
reqChan <- queue.ReqEvent{Time: time.Now(), EventType: in}
defer func() {
reqChan <- queue.ReqEvent{Time: time.Now(), EventType: out}
}()
network.RewriteHostOut(r)
// Enforce queuing and concurrency limits.
if breaker != nil {
if err := breaker.Maybe(r.Context(), func() {
handler.ServeHTTP(w, r.WithContext(proxyCtx))
}); err != nil {
switch err {
case context.DeadlineExceeded, queue.ErrRequestQueueFull:
http.Error(w, err.Error(), http.StatusServiceUnavailable)
default:
w.WriteHeader(http.StatusInternalServerError)
}
}
} else {
handler.ServeHTTP(w, r.WithContext(proxyCtx))
}
}
}
func handleKnativeProbe(w http.ResponseWriter, r *http.Request, ph string, healthState *health.State, prober func() bool, isAggressive bool) {
_, probeSpan := trace.StartSpan(r.Context(), "probe")
defer probeSpan.End()
if ph != queue.Name {
http.Error(w, fmt.Sprintf(badProbeTemplate, ph), http.StatusBadRequest)
probeSpan.Annotate([]trace.Attribute{
trace.StringAttribute("queueproxy.probe.error", fmt.Sprintf(badProbeTemplate, ph))}, "error")
return
}
if prober == nil {
http.Error(w, "no probe", http.StatusInternalServerError)
probeSpan.Annotate([]trace.Attribute{
trace.StringAttribute("queueproxy.probe.error", "no probe")}, "error")
return
}
healthState.HandleHealthProbe(func() bool {
if !prober() {
probeSpan.Annotate([]trace.Attribute{
trace.StringAttribute("queueproxy.probe.error", "container not ready")}, "error")
return false
}
return true
}, isAggressive, w)
}
func probeQueueHealthPath(port int, timeoutSeconds int) error {
if port <= 0 {
return fmt.Errorf("port must be a positive value, got %d", port)
}
url := fmt.Sprintf(healthURLTemplate, port)
timeoutDuration := readiness.PollTimeout
if timeoutSeconds != 0 {
timeoutDuration = time.Duration(timeoutSeconds) * time.Second
}
httpClient := &http.Client{
Transport: &http.Transport{
// Do not use the cached connection
DisableKeepAlives: true,
},
Timeout: timeoutDuration,
}
ctx, cancel := context.WithTimeout(context.Background(), timeoutDuration)
defer cancel()
stopCh := ctx.Done()
var lastErr error
// Using PollImmediateUntil instead of PollImmediate because if timeout is reached while waiting for first
// invocation of conditionFunc, it exits immediately without trying for a second time.
timeoutErr := wait.PollImmediateUntil(aggressivePollInterval, func() (bool, error) {
var req *http.Request
req, lastErr = http.NewRequest(http.MethodGet, url, nil)
if lastErr != nil {
// Return nil error for retrying
return false, nil
}
// Add the header to indicate this is a probe request.
req.Header.Add(network.ProbeHeaderName, queue.Name)
req.Header.Add(network.UserAgentKey, network.QueueProxyUserAgent)
res, lastErr := httpClient.Do(req)
if lastErr != nil {
// Return nil error for retrying
return false, nil
}
defer res.Body.Close()
return health.IsHTTPProbeReady(res), nil
}, stopCh)
if lastErr != nil {
return fmt.Errorf("failed to probe: %w", lastErr)
}
// An http.StatusOK was never returned during probing
if timeoutErr != nil {
return errors.New("probe returned not ready")
}
return nil
}
func main() {
flag.Parse()
// Parse the environment.
var env config
if err := envconfig.Process("", &env); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// If this is set, we run as a standalone binary to probe the queue-proxy.
if *readinessProbeTimeout >= 0 {
if err := probeQueueHealthPath(env.QueueServingPort, *readinessProbeTimeout); err != nil {
// used instead of the logger to produce a concise event message
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Exit(0)
}
// Setup the logger.
logger, _ = pkglogging.NewLogger(env.ServingLoggingConfig, env.ServingLoggingLevel)
logger = logger.Named("queueproxy")
defer flush(logger)
logger = logger.With(
zap.String(logkey.Key, types.NamespacedName{
Namespace: env.ServingNamespace,
Name: env.ServingRevision,
}.String()),
zap.String(logkey.Pod, env.ServingPod))
if err := validateEnv(env); err != nil {
logger.Fatal(err.Error())
}
// Report stats on Go memory usage every 30 seconds.
msp := metrics.NewMemStatsAll()
msp.Start(context.Background(), 30*time.Second)
if err := view.Register(msp.DefaultViews()...); err != nil {
logger.Fatalw("Error exporting go memstats view", zap.Error(err))
}
// Setup reporters and processes to handle stat reporting.
promStatReporter, err := queue.NewPrometheusStatsReporter(env.ServingNamespace, env.ServingConfiguration, env.ServingRevision, env.ServingPod, reportingPeriod)
if err != nil {
logger.Fatalw("Failed to create stats reporter", zap.Error(err))
}
statChan := make(chan autoscaler.Stat)
defer close(statChan)
go func() {
for s := range statChan {
promStatReporter.Report(s)
}
}()
reqChan := make(chan queue.ReqEvent, requestCountingQueueLength)
defer close(reqChan)
reportTicker := time.NewTicker(reportingPeriod)
defer reportTicker.Stop()
queue.NewStats(env.ServingPod, queue.Channels{
ReqChan: reqChan,
ReportChan: reportTicker.C,
StatChan: statChan,
}, time.Now())
// Setup probe to run for checking user-application healthiness.
probe := buildProbe(env.ServingReadinessProbe)
healthState := &health.State{}
server := buildServer(env, healthState, probe, reqChan, logger)
adminServer := buildAdminServer(healthState)
metricsServer := buildMetricsServer(promStatReporter)
servers := map[string]*http.Server{
"main": server,
"admin": adminServer,
"metrics": metricsServer,
}
if env.EnableProfiling {
servers["profile"] = profiling.NewServer(profiling.NewHandler(logger, true))
}
errCh := make(chan error, len(servers))
for name, server := range servers {
go func(name string, s *http.Server) {
// Don't forward ErrServerClosed as that indicates we're already shutting down.
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errCh <- fmt.Errorf("%s server failed: %w", name, err)
}
}(name, server)
}
// Setup /var/log.
// Logic that isn't required to be executed before the critical path
// and should be started last to not impact start up latency
go func() {
if env.EnableVarLogCollection {
createVarLogLink(env)
}
}()
// Blocks until we actually receive a TERM signal or one of the servers
// exit unexpectedly. We fold both signals together because we only want
// to act on the first of those to reach here.
select {
case err := <-errCh:
logger.Errorw("Failed to bring up queue-proxy, shutting down.", zap.Error(err))
flush(logger)
os.Exit(1)
case <-signals.SetupSignalHandler():
logger.Info("Received TERM signal, attempting to gracefully shutdown servers.")
healthState.Shutdown(func() {
// Give Istio time to sync our "not ready" state.
time.Sleep(quitSleepDuration)
// Calling server.Shutdown() allows pending requests to
// complete, while no new work is accepted.
if err := server.Shutdown(context.Background()); err != nil {
logger.Errorw("Failed to shutdown proxy server", zap.Error(err))
}
// Removing the main server from the shutdown logic as we've already shut it down.
delete(servers, "main")
})
flush(logger)
for serverName, srv := range servers {
if err := srv.Shutdown(context.Background()); err != nil {
logger.Errorw("Failed to shutdown server", zap.String("server", serverName), zap.Error(err))
}
}
}
}
func validateEnv(env config) error {
if !env.EnableVarLogCollection {
return nil
}
if env.VarLogVolumeName == "" {
return errors.New("VAR_LOG_VOLUME_NAME must be specified when ENABLE_VAR_LOG_COLLECTION is true")
}
if env.InternalVolumePath == "" {
return errors.New("INTERNAL_VOLUME_PATH must be specified when ENABLE_VAR_LOG_COLLECTION is true")
}
return nil
}
func buildProbe(probeJSON string) *readiness.Probe {
coreProbe, err := readiness.DecodeProbe(probeJSON)
if err != nil {
logger.Fatalw("Queue container failed to parse readiness probe", zap.Error(err))
}
return readiness.NewProbe(coreProbe)
}
func buildServer(env config, healthState *health.State, rp *readiness.Probe, reqChan chan queue.ReqEvent,
logger *zap.SugaredLogger) *http.Server {
target := &url.URL{
Scheme: "http",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(env.UserPort)),
}
httpProxy := httputil.NewSingleHostReverseProxy(target)
httpProxy.Transport = buildTransport(env, logger)
httpProxy.ErrorHandler = network.ErrorHandler(logger)
httpProxy.FlushInterval = -1
activatorutil.SetupHeaderPruning(httpProxy)
breaker := buildBreaker(env)
metricsSupported := supportsMetrics(env, logger)
// Create queue handler chain.
// Note: innermost handlers are specified first, ie. the last handler in the chain will be executed first.
var composedHandler http.Handler = httpProxy
if metricsSupported {
composedHandler = pushRequestMetricHandler(httpProxy, appRequestCountM, appResponseTimeInMsecM,
queueDepthM, breaker, env)
}
composedHandler = http.HandlerFunc(handler(reqChan, breaker, composedHandler, healthState, rp.ProbeContainer, rp.IsAggressive()))
composedHandler = queue.ForwardedShimHandler(composedHandler)
composedHandler = queue.TimeToFirstByteTimeoutHandler(composedHandler,
time.Duration(env.RevisionTimeoutSeconds)*time.Second, "request timeout")
composedHandler = pushRequestLogHandler(composedHandler, env)
if metricsSupported {
composedHandler = pushRequestMetricHandler(composedHandler, requestCountM, responseTimeInMsecM,
nil /*queueDepthM*/, nil /*breaker*/, env)
}
composedHandler = tracing.HTTPSpanMiddleware(composedHandler)
composedHandler = network.NewProbeHandler(composedHandler)
return network.NewServer(":"+strconv.Itoa(env.QueueServingPort), composedHandler)
}
func buildTransport(env config, logger *zap.SugaredLogger) http.RoundTripper {
if env.TracingConfigBackend == tracingconfig.None {
return network.AutoTransport
}
oct := tracing.NewOpenCensusTracer(tracing.WithExporter(env.ServingPod, logger))
oct.ApplyConfig(&tracingconfig.Config{
Backend: env.TracingConfigBackend,
Debug: env.TracingConfigDebug,
ZipkinEndpoint: env.TracingConfigZipkinEndpoint,
StackdriverProjectID: env.TracingConfigStackdriverProjectID,
SampleRate: env.TracingConfigSampleRate,
})
return &ochttp.Transport{
Base: network.AutoTransport,
}
}
func buildBreaker(env config) *queue.Breaker {
if env.ContainerConcurrency < 1 {
return nil
}
// We set the queue depth to be equal to the container concurrency * 10 to
// allow the autoscaler time to react.
queueDepth := env.ContainerConcurrency * 10
params := queue.BreakerParams{QueueDepth: queueDepth, MaxConcurrency: env.ContainerConcurrency, InitialCapacity: env.ContainerConcurrency}
logger.Infof("Queue container is starting with %#v", params)
return queue.NewBreaker(params)
}
func supportsMetrics(env config, logger *zap.SugaredLogger) bool {
// Setup request metrics reporting for end-user metrics.
if env.ServingRequestMetricsBackend == "" {
return false
}
if err := setupMetricsExporter(env.ServingRequestMetricsBackend); err != nil {
logger.Errorw("Error setting up request metrics exporter. Request metrics will be unavailable.", zap.Error(err))
return false
}
return true
}
func buildAdminServer(healthState *health.State) *http.Server {
adminMux := http.NewServeMux()
adminMux.HandleFunc(queue.RequestQueueDrainPath, healthState.DrainHandlerFunc())
return &http.Server{
Addr: ":" + strconv.Itoa(networking.QueueAdminPort),
Handler: adminMux,
}
}
func buildMetricsServer(promStatReporter *queue.PrometheusStatsReporter) *http.Server {
metricsMux := http.NewServeMux()
metricsMux.Handle("/metrics", promStatReporter.Handler())
return &http.Server{
Addr: ":" + strconv.Itoa(networking.AutoscalingQueueMetricsPort),
Handler: metricsMux,
}
}
// createVarLogLink creates a symlink allowing the fluentd daemon set to capture the
// logs from the user container /var/log. See fluentd config for more details.
func createVarLogLink(env config) {
link := strings.Join([]string{env.ServingNamespace, env.ServingPod, env.UserContainerName}, "_")
target := path.Join("..", env.VarLogVolumeName)
source := path.Join(env.InternalVolumePath, link)
if err := os.Symlink(target, source); err != nil {
logger.Errorw("Failed to create /var/log symlink. Log collection will not work.", zap.Error(err))
}
}
func pushRequestLogHandler(currentHandler http.Handler, env config) http.Handler {
if env.ServingRequestLogTemplate == "" {
return currentHandler
}
revInfo := &pkghttp.RequestLogRevision{
Name: env.ServingRevision,
Namespace: env.ServingNamespace,
Service: env.ServingService,
Configuration: env.ServingConfiguration,
PodName: env.ServingPod,
PodIP: env.ServingPodIP,
}
handler, err := pkghttp.NewRequestLogHandler(currentHandler, logging.NewSyncFileWriter(os.Stdout), env.ServingRequestLogTemplate,
pkghttp.RequestLogTemplateInputGetterFromRevision(revInfo), env.ServingEnableProbeRequestLog)
if err != nil {
logger.Errorw("Error setting up request logger. Request logs will be unavailable.", zap.Error(err))
return currentHandler
}
return handler
}
func pushRequestMetricHandler(currentHandler http.Handler, countMetric *stats.Int64Measure,
latencyMetric *stats.Float64Measure, queueDepthMetric *stats.Int64Measure, breaker *queue.Breaker, env config) http.Handler {
r, err := queuestats.NewStatsReporter(env.ServingNamespace, env.ServingService, env.ServingConfiguration, env.ServingRevision, env.ServingPod, countMetric, latencyMetric, queueDepthMetric)
if err != nil {
logger.Errorw("Error setting up request metrics reporter. Request metrics will be unavailable.", zap.Error(err))
return currentHandler
}
handler, err := queue.NewRequestMetricHandler(currentHandler, r, breaker)
if err != nil {
logger.Errorw("Error setting up request metrics handler. Request metrics will be unavailable.", zap.Error(err))
return currentHandler
}
return handler
}
func setupMetricsExporter(backend string) error {
// Set up OpenCensus exporter.
// NOTE: We use revision as the component instead of queue because queue is
// implementation specific. The current metrics are request relative. Using
// revision is reasonable.
// TODO(yanweiguo): add the ability to emit metrics with names not combined
// to component.
ops := metrics.ExporterOptions{
Domain: metrics.Domain(),
Component: "revision",
PrometheusPort: networking.UserQueueMetricsPort,
ConfigMap: map[string]string{
metrics.BackendDestinationKey: backend,
},
}
return metrics.UpdateExporter(ops, logger)
}
func flush(logger *zap.SugaredLogger) {
logger.Sync()
os.Stdout.Sync()
os.Stderr.Sync()
metrics.FlushExporter()
}