Debian Codegraph @

cmd/influxd/run/server.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package run
2
3 import (
4 "crypto/tls"
5 "fmt"
6 "io"
7 "log"
8 "net"
9 "os"
10 "path/filepath"
11 "runtime"
12 "runtime/pprof"
13 "time"
14
15 "github.com/influxdata/influxdb"
16 "github.com/influxdata/influxdb/coordinator"
17 "github.com/influxdata/influxdb/logger"
18 "github.com/influxdata/influxdb/models"
19 "github.com/influxdata/influxdb/monitor"
20 "github.com/influxdata/influxdb/query"
21 "github.com/influxdata/influxdb/services/collectd"
22 "github.com/influxdata/influxdb/services/continuous_querier"
23 "github.com/influxdata/influxdb/services/graphite"
24 "github.com/influxdata/influxdb/services/httpd"
25 "github.com/influxdata/influxdb/services/meta"
26 "github.com/influxdata/influxdb/services/opentsdb"
27 "github.com/influxdata/influxdb/services/precreator"
28 "github.com/influxdata/influxdb/services/retention"
29 "github.com/influxdata/influxdb/services/snapshotter"
30 "github.com/influxdata/influxdb/services/subscriber"
31 "github.com/influxdata/influxdb/services/udp"
32 "github.com/influxdata/influxdb/tcp"
33 "github.com/influxdata/influxdb/tsdb"
34 client "github.com/influxdata/usage-client/v1"
35 "go.uber.org/zap"
36
37 "github.com/influxdata/influxdb/services/storage"
38 // Initialize the engine package
39 _ "github.com/influxdata/influxdb/tsdb/engine"
40 // Initialize the index package
41 _ "github.com/influxdata/influxdb/tsdb/index"
42 )
43
44 var startTime time.Time
45
46 func init() {
47 startTime = time.Now().UTC()
48 }
49
50 // BuildInfo represents the build details for the server code.
51 type BuildInfo struct {
52 Version string
53 Commit string
54 Branch string
55 Time string
56 }
57
58 // Server represents a container for the metadata and storage data and services.
59 // It is built using a Config and it manages the startup and shutdown of all
60 // services in the proper order.
61 type Server struct {
62 buildInfo BuildInfo
63
64 err chan error
65 closing chan struct{}
66
67 BindAddress string
68 Listener net.Listener
69
70 Logger *zap.Logger
71
72 MetaClient *meta.Client
73
74 TSDBStore *tsdb.Store
75 QueryExecutor *query.Executor
76 PointsWriter *coordinator.PointsWriter
77 Subscriber *subscriber.Service
78
79 Services []Service
80
81 // These references are required for the tcp muxer.
82 SnapshotterService *snapshotter.Service
83
84 Monitor *monitor.Monitor
85
86 // Server reporting and registration
•87 reportingEnabled bool
88
89 // Profiling
90 CPUProfile string
91 MemProfile string
92
93 // httpAPIAddr is the host:port combination for the main HTTP API for querying and writing data
94 httpAPIAddr string
95
96 // httpUseTLS specifies if we should use a TLS connection to the http servers
97 httpUseTLS bool
98
99 // tcpAddr is the host:port combination for the TCP listener that services mux onto
100 tcpAddr string
101
102 config *Config
103 }
104
105 // updateTLSConfig stores with into the tls config pointed at by into but only if with is not nil
106 // and into is nil. Think of it as setting the default value.
107 func updateTLSConfig(into **tls.Config, with *tls.Config) {
108 if with != nil && into != nil && *into == nil {
109 *into = with
110 }
111 }
112
113 // NewServer returns a new instance of Server built from a config.
114 func NewServer(c *Config, buildInfo *BuildInfo) (*Server, error) {
115 // First grab the base tls config we will use for all clients and servers
116 tlsConfig, err := c.TLS.Parse()
117 if err != nil {
118 return nil, fmt.Errorf("tls configuration: %v", err)
119 }
120
121 // Update the TLS values on each of the configs to be the parsed one if
122 // not already specified (set the default).
123 updateTLSConfig(&c.HTTPD.TLS, tlsConfig)
124 updateTLSConfig(&c.Subscriber.TLS, tlsConfig)
125 for i := range c.OpenTSDBInputs {
126 updateTLSConfig(&c.OpenTSDBInputs[i].TLS, tlsConfig)
127 }
128
129 // We need to ensure that a meta directory always exists even if
130 // we don't start the meta store. node.json is always stored under
131 // the meta directory.
132 if err := os.MkdirAll(c.Meta.Dir, 0777); err != nil {
133 return nil, fmt.Errorf("mkdir all: %s", err)
134 }
135
136 // 0.10-rc1 and prior would sometimes put the node.json at the root
137 // dir which breaks backup/restore and restarting nodes. This moves
138 // the file from the root so it's always under the meta dir.
139 oldPath := filepath.Join(filepath.Dir(c.Meta.Dir), "node.json")
140 newPath := filepath.Join(c.Meta.Dir, "node.json")
141
142 if _, err := os.Stat(oldPath); err == nil {
143 if err := os.Rename(oldPath, newPath); err != nil {
144 return nil, err
145 }
146 }
147
148 _, err = influxdb.LoadNode(c.Meta.Dir)
149 if err != nil {
150 if !os.IsNotExist(err) {
151 return nil, err
152 }
153 }
154
155 if err := raftDBExists(c.Meta.Dir); err != nil {
156 return nil, err
157 }
158
159 // In 0.10.0 bind-address got moved to the top level. Check
160 // The old location to keep things backwards compatible
161 bind := c.BindAddress
162
163 s := &Server{
164 buildInfo: *buildInfo,
165 err: make(chan error),
166 closing: make(chan struct{}),
167
168 BindAddress: bind,
169
170 Logger: logger.New(os.Stderr),
171
172 MetaClient: meta.NewClient(c.Meta),
173
•174 reportingEnabled: c.ReportingEnabled,
175
176 httpAPIAddr: c.HTTPD.BindAddress,
177 httpUseTLS: c.HTTPD.HTTPSEnabled,
178 tcpAddr: bind,
179
180 config: c,
181 }
182 s.Monitor = monitor.New(s, c.Monitor)
183 s.config.registerDiagnostics(s.Monitor)
184
185 if err := s.MetaClient.Open(); err != nil {
186 return nil, err
187 }
188
189 s.TSDBStore = tsdb.NewStore(c.Data.Dir)
190 s.TSDBStore.EngineOptions.Config = c.Data
191
192 // Copy TSDB configuration.
193 s.TSDBStore.EngineOptions.EngineVersion = c.Data.Engine
194 s.TSDBStore.EngineOptions.IndexVersion = c.Data.Index
195
196 // Create the Subscriber service
197 s.Subscriber = subscriber.NewService(c.Subscriber)
198
199 // Initialize points writer.
200 s.PointsWriter = coordinator.NewPointsWriter()
201 s.PointsWriter.WriteTimeout = time.Duration(c.Coordinator.WriteTimeout)
202 s.PointsWriter.TSDBStore = s.TSDBStore
203
204 // Initialize query executor.
205 s.QueryExecutor = query.NewExecutor()
206 s.QueryExecutor.StatementExecutor = &coordinator.StatementExecutor{
207 MetaClient: s.MetaClient,
208 TaskManager: s.QueryExecutor.TaskManager,
209 TSDBStore: s.TSDBStore,
210 ShardMapper: &coordinator.LocalShardMapper{
211 MetaClient: s.MetaClient,
212 TSDBStore: coordinator.LocalTSDBStore{Store: s.TSDBStore},
213 },
214 Monitor: s.Monitor,
215 PointsWriter: s.PointsWriter,
216 MaxSelectPointN: c.Coordinator.MaxSelectPointN,
217 MaxSelectSeriesN: c.Coordinator.MaxSelectSeriesN,
218 MaxSelectBucketsN: c.Coordinator.MaxSelectBucketsN,
219 }
220 s.QueryExecutor.TaskManager.QueryTimeout = time.Duration(c.Coordinator.QueryTimeout)
221 s.QueryExecutor.TaskManager.LogQueriesAfter = time.Duration(c.Coordinator.LogQueriesAfter)
222 s.QueryExecutor.TaskManager.MaxConcurrentQueries = c.Coordinator.MaxConcurrentQueries
223
224 // Initialize the monitor
225 s.Monitor.Version = s.buildInfo.Version
226 s.Monitor.Commit = s.buildInfo.Commit
227 s.Monitor.Branch = s.buildInfo.Branch
228 s.Monitor.BuildTime = s.buildInfo.Time
229 s.Monitor.PointsWriter = (*monitorPointsWriter)(s.PointsWriter)
230 return s, nil
231 }
232
233 // Statistics returns statistics for the services running in the Server.
234 func (s *Server) Statistics(tags map[string]string) []models.Statistic {
235 var statistics []models.Statistic
236 statistics = append(statistics, s.QueryExecutor.Statistics(tags)...)
237 statistics = append(statistics, s.TSDBStore.Statistics(tags)...)
238 statistics = append(statistics, s.PointsWriter.Statistics(tags)...)
239 statistics = append(statistics, s.Subscriber.Statistics(tags)...)
240 for _, srv := range s.Services {
241 if m, ok := srv.(monitor.Reporter); ok {
242 statistics = append(statistics, m.Statistics(tags)...)
243 }
244 }
245 return statistics
246 }
247
248 func (s *Server) appendSnapshotterService() {
249 srv := snapshotter.NewService()
250 srv.TSDBStore = s.TSDBStore
251 srv.MetaClient = s.MetaClient
252 s.Services = append(s.Services, srv)
253 s.SnapshotterService = srv
254 }
255
256 // SetLogOutput sets the logger used for all messages. It must not be called
257 // after the Open method has been called.
258 func (s *Server) SetLogOutput(w io.Writer) {
259 s.Logger = logger.New(w)
260 }
261
262 func (s *Server) appendMonitorService() {
263 s.Services = append(s.Services, s.Monitor)
264 }
265
266 func (s *Server) appendRetentionPolicyService(c retention.Config) {
267 if !c.Enabled {
268 return
269 }
270 srv := retention.NewService(c)
271 srv.MetaClient = s.MetaClient
272 srv.TSDBStore = s.TSDBStore
273 s.Services = append(s.Services, srv)
274 }
275
276 func (s *Server) appendHTTPDService(c httpd.Config) {
277 if !c.Enabled {
278 return
279 }
280 srv := httpd.NewService(c)
281 srv.Handler.MetaClient = s.MetaClient
282 srv.Handler.QueryAuthorizer = meta.NewQueryAuthorizer(s.MetaClient)
283 srv.Handler.WriteAuthorizer = meta.NewWriteAuthorizer(s.MetaClient)
284 srv.Handler.QueryExecutor = s.QueryExecutor
285 srv.Handler.Monitor = s.Monitor
286 srv.Handler.PointsWriter = s.PointsWriter
287 srv.Handler.Version = s.buildInfo.Version
288 srv.Handler.BuildType = "OSS"
289
290 // Wire up storage service for Prometheus endpoints.
291 storageStore := storage.NewStore()
292 storageStore.MetaClient = s.MetaClient
293 storageStore.TSDBStore = s.TSDBStore
294 srv.Handler.Store = storageStore
295
296 s.Services = append(s.Services, srv)
297 }
298
299 func (s *Server) appendStorageService(c storage.Config) {
300 if !c.Enabled {
301 return
302 }
303 srv := storage.NewService(c)
304 srv.MetaClient = s.MetaClient
305 srv.TSDBStore = s.TSDBStore
306
307 s.Services = append(s.Services, srv)
308 }
309
310 func (s *Server) appendCollectdService(c collectd.Config) {
311 if !c.Enabled {
312 return
313 }
314 srv := collectd.NewService(c)
315 srv.MetaClient = s.MetaClient
316 srv.PointsWriter = s.PointsWriter
317 s.Services = append(s.Services, srv)
318 }
319
320 func (s *Server) appendOpenTSDBService(c opentsdb.Config) error {
321 if !c.Enabled {
322 return nil
323 }
324 srv, err := opentsdb.NewService(c)
325 if err != nil {
326 return err
327 }
328 srv.PointsWriter = s.PointsWriter
329 srv.MetaClient = s.MetaClient
330 s.Services = append(s.Services, srv)
331 return nil
332 }
333
334 func (s *Server) appendGraphiteService(c graphite.Config) error {
335 if !c.Enabled {
336 return nil
337 }
338 srv, err := graphite.NewService(c)
339 if err != nil {
340 return err
341 }
342
343 srv.PointsWriter = s.PointsWriter
344 srv.MetaClient = s.MetaClient
345 srv.Monitor = s.Monitor
346 s.Services = append(s.Services, srv)
347 return nil
348 }
349
350 func (s *Server) appendPrecreatorService(c precreator.Config) error {
351 if !c.Enabled {
352 return nil
353 }
354 srv := precreator.NewService(c)
355 srv.MetaClient = s.MetaClient
356 s.Services = append(s.Services, srv)
357 return nil
358 }
359
360 func (s *Server) appendUDPService(c udp.Config) {
361 if !c.Enabled {
362 return
363 }
364 srv := udp.NewService(c)
365 srv.PointsWriter = s.PointsWriter
366 srv.MetaClient = s.MetaClient
367 s.Services = append(s.Services, srv)
368 }
369
370 func (s *Server) appendContinuousQueryService(c continuous_querier.Config) {
371 if !c.Enabled {
372 return
373 }
374 srv := continuous_querier.NewService(c)
375 srv.MetaClient = s.MetaClient
376 srv.QueryExecutor = s.QueryExecutor
377 srv.Monitor = s.Monitor
378 s.Services = append(s.Services, srv)
379 }
380
381 // Err returns an error channel that multiplexes all out of band errors received from all services.
382 func (s *Server) Err() <-chan error { return s.err }
383
384 // Open opens the meta and data store and all services.
385 func (s *Server) Open() error {
386 // Start profiling, if set.
387 startProfile(s.CPUProfile, s.MemProfile)
388
389 // Open shared TCP connection.
390 ln, err := net.Listen("tcp", s.BindAddress)
391 if err != nil {
392 return fmt.Errorf("listen: %s", err)
393 }
394 s.Listener = ln
395
396 // Multiplex listener.
397 mux := tcp.NewMux()
398 go mux.Serve(ln)
399
400 // Append services.
401 s.appendMonitorService()
402 s.appendPrecreatorService(s.config.Precreator)
403 s.appendSnapshotterService()
404 s.appendContinuousQueryService(s.config.ContinuousQuery)
405 s.appendHTTPDService(s.config.HTTPD)
406 s.appendStorageService(s.config.Storage)
407 s.appendRetentionPolicyService(s.config.Retention)
408 for _, i := range s.config.GraphiteInputs {
409 if err := s.appendGraphiteService(i); err != nil {
410 return err
411 }
412 }
413 for _, i := range s.config.CollectdInputs {
414 s.appendCollectdService(i)
415 }
416 for _, i := range s.config.OpenTSDBInputs {
417 if err := s.appendOpenTSDBService(i); err != nil {
418 return err
419 }
420 }
421 for _, i := range s.config.UDPInputs {
422 s.appendUDPService(i)
423 }
424
425 s.Subscriber.MetaClient = s.MetaClient
426 s.PointsWriter.MetaClient = s.MetaClient
427 s.Monitor.MetaClient = s.MetaClient
428
429 s.SnapshotterService.Listener = mux.Listen(snapshotter.MuxHeader)
430
431 // Configure logging for all services and clients.
432 if s.config.Meta.LoggingEnabled {
433 s.MetaClient.WithLogger(s.Logger)
434 }
435 s.TSDBStore.WithLogger(s.Logger)
436 if s.config.Data.QueryLogEnabled {
437 s.QueryExecutor.WithLogger(s.Logger)
438 }
439 s.PointsWriter.WithLogger(s.Logger)
440 s.Subscriber.WithLogger(s.Logger)
441 for _, svc := range s.Services {
442 svc.WithLogger(s.Logger)
443 }
444 s.SnapshotterService.WithLogger(s.Logger)
445 s.Monitor.WithLogger(s.Logger)
446
447 // Open TSDB store.
448 if err := s.TSDBStore.Open(); err != nil {
449 return fmt.Errorf("open tsdb store: %s", err)
450 }
451
452 // Open the subscriber service
453 if err := s.Subscriber.Open(); err != nil {
454 return fmt.Errorf("open subscriber: %s", err)
455 }
456
457 // Open the points writer service
458 if err := s.PointsWriter.Open(); err != nil {
459 return fmt.Errorf("open points writer: %s", err)
460 }
461
462 s.PointsWriter.AddWriteSubscriber(s.Subscriber.Points())
463
464 for _, service := range s.Services {
465 if err := service.Open(); err != nil {
466 return fmt.Errorf("open service: %s", err)
467 }
468 }
469
470 // Start the reporting service, if not disabled.
•471 if s.reportingEnabled {
472 go s.startServerReporting()
473 }
474
475 return nil
476 }
477
478 // Close shuts down the meta and data stores and all services.
479 func (s *Server) Close() error {
480 stopProfile()
481
482 // Close the listener first to stop any new connections
483 if s.Listener != nil {
484 s.Listener.Close()
485 }
486
487 // Close services to allow any inflight requests to complete
488 // and prevent new requests from being accepted.
489 for _, service := range s.Services {
490 service.Close()
491 }
492
493 s.config.deregisterDiagnostics(s.Monitor)
494
495 if s.PointsWriter != nil {
496 s.PointsWriter.Close()
497 }
498
499 if s.QueryExecutor != nil {
500 s.QueryExecutor.Close()
501 }
502
503 // Close the TSDBStore, no more reads or writes at this point
504 if s.TSDBStore != nil {
505 s.TSDBStore.Close()
506 }
507
508 if s.Subscriber != nil {
509 s.Subscriber.Close()
510 }
511
512 if s.MetaClient != nil {
513 s.MetaClient.Close()
514 }
515
516 close(s.closing)
517 return nil
518 }
519
520 // startServerReporting starts periodic server reporting.
521 func (s *Server) startServerReporting() {
522 s.reportServer()
523
524 ticker := time.NewTicker(24 * time.Hour)
525 defer ticker.Stop()
526 for {
527 select {
528 case <-s.closing:
529 return
530 case <-ticker.C:
531 s.reportServer()
532 }
533 }
534 }
535
536 // reportServer reports usage statistics about the system.
537 func (s *Server) reportServer() {
538 dbs := s.MetaClient.Databases()
539 numDatabases := len(dbs)
540
541 var (
542 numMeasurements int64
543 numSeries int64
544 )
545
546 for _, db := range dbs {
547 name := db.Name
548 n, err := s.TSDBStore.SeriesCardinality(name)
549 if err != nil {
550 s.Logger.Error(fmt.Sprintf("Unable to get series cardinality for database %s: %v", name, err))
551 } else {
552 numSeries += n
553 }
554
555 n, err = s.TSDBStore.MeasurementsCardinality(name)
556 if err != nil {
557 s.Logger.Error(fmt.Sprintf("Unable to get measurement cardinality for database %s: %v", name, err))
558 } else {
559 numMeasurements += n
560 }
561 }
562
563 clusterID := s.MetaClient.ClusterID()
564 cl := client.New("")
565 usage := client.Usage{
566 Product: "influxdb",
567 Data: []client.UsageData{
568 {
569 Values: client.Values{
570 "os": runtime.GOOS,
571 "arch": runtime.GOARCH,
572 "version": s.buildInfo.Version,
573 "cluster_id": fmt.Sprintf("%v", clusterID),
574 "num_series": numSeries,
575 "num_measurements": numMeasurements,
576 "num_databases": numDatabases,
577 "uptime": time.Since(startTime).Seconds(),
578 },
579 },
580 },
581 }
582
583 s.Logger.Info("Sending usage statistics to usage.influxdata.com")
584
585 go cl.Save(usage)
586 }
587
588 // Service represents a service attached to the server.
589 type Service interface {
590 WithLogger(log *zap.Logger)
591 Open() error
592 Close() error
593 }
594
595 // prof stores the file locations of active profiles.
596 var prof struct {
597 cpu *os.File
598 mem *os.File
599 }
600
601 // StartProfile initializes the cpu and memory profile, if specified.
602 func startProfile(cpuprofile, memprofile string) {
603 if cpuprofile != "" {
604 f, err := os.Create(cpuprofile)
605 if err != nil {
606 log.Fatalf("cpuprofile: %v", err)
607 }
608 log.Printf("writing CPU profile to: %s\n", cpuprofile)
609 prof.cpu = f
610 pprof.StartCPUProfile(prof.cpu)
611 }
612
613 if memprofile != "" {
614 f, err := os.Create(memprofile)
615 if err != nil {
616 log.Fatalf("memprofile: %v", err)
617 }
618 log.Printf("writing mem profile to: %s\n", memprofile)
619 prof.mem = f
620 runtime.MemProfileRate = 4096
621 }
622
623 }
624
625 // StopProfile closes the cpu and memory profiles if they are running.
626 func stopProfile() {
627 if prof.cpu != nil {
628 pprof.StopCPUProfile()
629 prof.cpu.Close()
630 log.Println("CPU profile stopped")
631 }
632 if prof.mem != nil {
633 pprof.Lookup("heap").WriteTo(prof.mem, 0)
634 prof.mem.Close()
635 log.Println("mem profile stopped")
636 }
637 }
638
639 // monitorPointsWriter is a wrapper around `coordinator.PointsWriter` that helps
640 // to prevent a circular dependency between the `cluster` and `monitor` packages.
641 type monitorPointsWriter coordinator.PointsWriter
642
643 func (pw *monitorPointsWriter) WritePoints(database, retentionPolicy string, points models.Points) error {
644 return (*coordinator.PointsWriter)(pw).WritePointsPrivileged(database, retentionPolicy, models.ConsistencyLevelAny, points)
645 }
646
647 func raftDBExists(dir string) error {
648 // Check to see if there is a raft db, if so, error out with a message
649 // to downgrade, export, and then import the meta data
650 raftFile := filepath.Join(dir, "raft.db")
651 if _, err := os.Stat(raftFile); err == nil {
652 return fmt.Errorf("detected %s. To proceed, you'll need to either 1) downgrade to v0.11.x, export your metadata, upgrade to the current version again, and then import the metadata or 2) delete the file, which will effectively reset your database. For more assistance with the upgrade, see: https://docs.influxdata.com/influxdb/v0.12/administration/upgrading/", raftFile)
653 }
654 return nil
655 }