forked from jirs5/tracing-proxy
/
main.go
298 lines (274 loc) · 9.05 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
package main
import (
"context"
"fmt"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/facebookgo/inject"
"github.com/facebookgo/startstop"
flag "github.com/jessevdk/go-flags"
"github.com/opsramp/tracing-proxy/app"
"github.com/opsramp/tracing-proxy/collect"
"github.com/opsramp/tracing-proxy/config"
"github.com/opsramp/tracing-proxy/internal/peer"
"github.com/opsramp/tracing-proxy/logger"
"github.com/opsramp/tracing-proxy/metrics"
"github.com/opsramp/tracing-proxy/pkg/libtrace"
"github.com/opsramp/tracing-proxy/pkg/libtrace/constants"
"github.com/opsramp/tracing-proxy/pkg/libtrace/transmission"
"github.com/opsramp/tracing-proxy/pkg/retry"
"github.com/opsramp/tracing-proxy/proxy"
"github.com/opsramp/tracing-proxy/sample"
"github.com/opsramp/tracing-proxy/service/debug"
"github.com/opsramp/tracing-proxy/sharder"
"github.com/opsramp/tracing-proxy/transmit"
)
// set by travis.
var (
BuildID string
CollectorVersion string
)
type Options struct {
ConfigFile string `short:"c" long:"config" description:"Path to config file" default:"/etc/tracing-proxy/config.toml"`
RulesFile string `short:"r" long:"rules_config" description:"Path to rules config file" default:"/etc/tracing-proxy/rules.toml"`
Version bool `short:"v" long:"version" description:"Print version number and exit"`
Debug bool `short:"d" long:"debug" description:"If enabled, runs debug service (runs on the first open port between localhost:6060 and :6069 by default)"`
InterfaceNames bool `long:"interface-names" description:"If set, print system's network interface names and exit."`
}
func main() {
var opts Options
flagParser := flag.NewParser(&opts, flag.Default)
if extraArgs, err := flagParser.Parse(); err != nil || len(extraArgs) != 0 {
fmt.Println("command line parsing error - call with --help for usage")
os.Exit(1)
}
if BuildID == "" {
CollectorVersion = "dev"
} else {
CollectorVersion = BuildID
}
if opts.Version {
fmt.Println("Version: " + CollectorVersion)
os.Exit(0)
}
if opts.InterfaceNames {
ifaces, err := net.Interfaces()
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
for _, i := range ifaces {
fmt.Println(i.Name)
}
os.Exit(0)
}
a := app.App{
Version: CollectorVersion,
}
c, err := config.NewConfig(opts.ConfigFile, opts.RulesFile, func(err error) {
if a.Logger != nil {
a.Logger.Error().WithField("error", err).Logf("error reloading config")
}
})
if err != nil {
fmt.Printf("unable to load config: %+v\n", err)
os.Exit(1)
}
// get desired implementation for each dependency to inject
lc, err := c.GetLogrusConfig()
if err != nil {
fmt.Printf("unable to load config: %+v\n", err)
os.Exit(1)
}
lgr := logger.GetLoggerImplementation(
lc.LogFormatter,
lc.LogOutput,
lc.File.FileName,
lc.File.MaxSize,
lc.File.MaxBackups,
lc.File.Compress)
collector := collect.GetCollectorImplementation(c)
metricsConfig := metrics.GetMetricsImplementation("")
shrdr := sharder.GetSharderImplementation(c)
samplerFactory := &sample.SamplerFactory{}
// set log level
logLevel, err := c.GetLoggingLevel()
if err != nil {
fmt.Printf("unable to get logging level from config: %v\n", err)
os.Exit(1)
}
logrusLogger := lgr.Init()
if err := lgr.SetLevel(logLevel); err != nil {
fmt.Printf("unable to set logging level: %v\n", err)
os.Exit(1)
}
upstreamMetricsConfig := metrics.GetMetricsImplementation("upstream")
peerMetricsConfig := metrics.GetMetricsImplementation("peer")
authConfig := c.GetAuthConfig()
opsrampAPI, err := c.GetOpsrampAPI()
if err != nil {
logrusLogger.Fatal(err)
}
dataset, err := c.GetDataset()
if err != nil {
logrusLogger.Fatal(err)
}
retryConfig := c.GetRetryConfig()
logsEndpoint := c.GetLogsEndpoint()
sendEvents := c.GetSendEvents()
// set proxy details
prxy := proxy.NewProxy(c.GetProxyConfig(), opsrampAPI, logsEndpoint, authConfig.Endpoint, c.GetMetricsConfig().OpsRampAPI)
prxy.Logger = lgr
// connect to working proxy at start-up
if prxy.Enabled() {
_ = prxy.SwitchProxy("")
lgr.Info().Logf("valid proxy config received: %d", prxy.Len())
}
userAgentAddition := "tracing-proxy/" + CollectorVersion
upstreamClient, err := libtrace.NewClient(libtrace.ClientConfig{ // nolint:all
Logger: lgr,
Transmission: &transmission.TraceProxy{
MaxBatchSize: c.GetMaxBatchSize(),
BatchTimeout: c.GetBatchTimeout(),
MaxConcurrentBatches: constants.DefaultMaxConcurrentBatches,
PendingWorkCapacity: uint(c.GetUpstreamBufferSize()),
UserAgentAddition: userAgentAddition,
BlockOnSend: true,
EnableMsgpackEncoding: false,
Metrics: upstreamMetricsConfig,
IsPeer: false,
UseTls: c.GetGlobalUseTLS(),
UseTlsInsecure: c.GetGlobalUseTLSInsecureSkip(),
AuthTokenEndpoint: authConfig.Endpoint,
AuthTokenKey: authConfig.Key,
AuthTokenSecret: authConfig.Secret,
TraceEndpoint: opsrampAPI,
TenantId: authConfig.TenantId,
Dataset: dataset,
RetrySettings: &retry.Config{
InitialInterval: retryConfig.InitialInterval,
RandomizationFactor: retryConfig.RandomizationFactor,
Multiplier: retryConfig.Multiplier,
MaxInterval: retryConfig.MaxInterval,
MaxElapsedTime: retryConfig.MaxElapsedTime,
},
Logger: lgr,
LogsEndpoint: logsEndpoint,
SendEvents: sendEvents,
Proxy: prxy,
},
})
if err != nil {
fmt.Printf("unable to initialize upstream libtrace client: %v", err)
os.Exit(1)
}
peerClient, err := libtrace.NewClient(libtrace.ClientConfig{ // nolint:all
Logger: lgr,
Transmission: &transmission.TraceProxy{
MaxBatchSize: c.GetMaxBatchSize(),
BatchTimeout: c.GetBatchTimeout(),
MaxConcurrentBatches: constants.DefaultMaxConcurrentBatches,
PendingWorkCapacity: uint(c.GetPeerBufferSize()),
UserAgentAddition: userAgentAddition,
DisableCompression: !c.GetCompressPeerCommunication(),
EnableMsgpackEncoding: false,
Metrics: peerMetricsConfig,
IsPeer: true,
AuthTokenEndpoint: authConfig.Endpoint,
AuthTokenKey: authConfig.Key,
AuthTokenSecret: authConfig.Secret,
TraceEndpoint: opsrampAPI,
TenantId: authConfig.TenantId,
Dataset: dataset,
RetrySettings: &retry.Config{
InitialInterval: retryConfig.InitialInterval,
RandomizationFactor: retryConfig.RandomizationFactor,
Multiplier: retryConfig.Multiplier,
MaxInterval: retryConfig.MaxInterval,
MaxElapsedTime: retryConfig.MaxElapsedTime,
},
Logger: lgr,
LogsEndpoint: logsEndpoint,
SendEvents: sendEvents,
Proxy: prxy,
},
})
if err != nil {
fmt.Printf("unable to initialize upstream libtrace client: %v", err)
os.Exit(1)
}
ctx, cancel := context.WithTimeout(context.Background(), c.GetPeerTimeout())
defer cancel()
done := make(chan struct{})
peers, err := peer.NewPeers(ctx, c, done)
if err != nil {
fmt.Printf("unable to load peers: %+v\n", err)
os.Exit(1)
}
var g inject.Graph
err = g.Provide(
&inject.Object{Value: c},
&inject.Object{Value: peers},
&inject.Object{Value: lgr},
&inject.Object{Value: prxy, Name: "proxyConfig"},
&inject.Object{
Name: "upstreamTransmission",
Value: &transmit.DefaultTransmission{
Name: "upstream_",
Client: upstreamClient,
},
},
&inject.Object{
Name: "peerTransmission",
Value: &transmit.DefaultTransmission{
Name: "peer_",
Client: peerClient,
},
},
&inject.Object{Value: shrdr},
&inject.Object{Value: collector},
&inject.Object{Value: metricsConfig, Name: "metrics"},
&inject.Object{Value: upstreamMetricsConfig, Name: "upstreamMetrics"},
&inject.Object{Value: peerMetricsConfig, Name: "peerMetrics"},
&inject.Object{Value: CollectorVersion, Name: "version"},
&inject.Object{Value: samplerFactory},
&inject.Object{Value: &a},
)
if err != nil {
fmt.Printf("failed to provide injection graph. error: %+v\n", err)
os.Exit(1)
}
if opts.Debug {
err = g.Provide(&inject.Object{Value: &debug.DebugService{Config: c}})
if err != nil {
fmt.Printf("failed to provide injection graph. error: %+v\n", err)
os.Exit(1)
}
}
if err := g.Populate(); err != nil {
fmt.Printf("failed to populate injection graph. error: %+v\n", err)
os.Exit(1)
}
defer func(objects []*inject.Object, log startstop.Logger) {
err := startstop.Stop(objects, log)
if err != nil {
fmt.Printf("failed to stop injected depencies. error: %+v\n", err)
}
}(g.Objects(), logrusLogger)
if err := startstop.Start(g.Objects(), logrusLogger); err != nil {
fmt.Printf("failed to start injected dependencies. error: %+v\n", err)
os.Exit(1)
}
// set up signal channel to exit
sigsToExit := make(chan os.Signal, 1)
signal.Notify(sigsToExit, syscall.SIGINT, syscall.SIGTERM)
// block on our signal handler to exit
sig := <-sigsToExit
// unregister ourselves before we go
close(done)
time.Sleep(100 * time.Millisecond)
a.Logger.Error().Logf("Caught signal \"%s\"", sig)
}