/
mtail.go
205 lines (176 loc) · 5.85 KB
/
mtail.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
// Copyright 2011 Google Inc. All Rights Reserved.
// This file is available under the Apache license.
package mtail
import (
"context"
"errors"
"expvar"
"log"
"net"
"net/http"
"net/http/pprof"
"sync"
"time"
"github.com/F1997/categraf/inputs/mtail/internal/exporter"
"github.com/F1997/categraf/inputs/mtail/internal/logline"
"github.com/F1997/categraf/inputs/mtail/internal/metrics"
"github.com/F1997/categraf/inputs/mtail/internal/runtime"
"github.com/F1997/categraf/inputs/mtail/internal/tailer"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Server contains the state of the main mtail program.
type Server struct {
ctx context.Context
store *metrics.Store // Metrics storage
wg sync.WaitGroup // wait for main processes to shutdown
tOpts []tailer.Option // options for constructing `t`
t *tailer.Tailer // t manages log patterns and log streams, which sends lines to the VMs
rOpts []runtime.Option // options for constructing `r`
r *runtime.Runtime // r loads programs and manages the VM lifecycle
eOpts []exporter.Option // options for constructing `e`
e *exporter.Exporter // e manages the export of metrics from the store
lines chan *logline.LogLine // primary communication channel, owned by Tailer.
reg *prometheus.Registry
listener net.Listener // Configured with bind address.
buildInfo BuildInfo // go build information
programPath string // path to programs to load
oneShot bool // if set, mtail reads log files from the beginning, once, then exits
compileOnly bool // if set, mtail compiles programs then exits
}
func (m *Server) Wait() {
m.wg.Wait()
}
func (m *Server) GetRegistry() *prometheus.Registry {
return m.reg
}
// initRuntime constructs a new runtime and performs the initial load of program files in the program directory.
func (m *Server) initRuntime() (err error) {
m.r, err = runtime.New(m.lines, &m.wg, m.programPath, m.store, m.rOpts...)
return
}
// initExporter sets up an Exporter for this Server.
func (m *Server) initExporter() (err error) {
if m.oneShot {
// This is a hack to avoid a race in test, but assume that in oneshot
// mode we don't want to export anything.
return nil
}
m.e, err = exporter.New(m.ctx, &m.wg, m.store, m.eOpts...)
if err != nil {
return err
}
m.reg.MustRegister(m.e)
return nil
}
// initTailer sets up and starts a Tailer for this Server.
func (m *Server) initTailer() (err error) {
m.t, err = tailer.New(m.ctx, &m.wg, m.lines, m.tOpts...)
return
}
// initHTTPServer begins the http server.
func (m *Server) initHTTPServer() error {
initDone := make(chan struct{})
defer close(initDone)
if m.listener == nil {
log.Println("no listen address configured, not starting http server")
return nil
}
mux := http.NewServeMux()
mux.HandleFunc("/favicon.ico", FaviconHandler)
mux.Handle("/", m)
mux.Handle("/progz", http.HandlerFunc(m.r.ProgzHandler))
mux.HandleFunc("/json", http.HandlerFunc(m.e.HandleJSON))
mux.Handle("/metrics", promhttp.HandlerFor(m.reg, promhttp.HandlerOpts{}))
mux.HandleFunc("/graphite", http.HandlerFunc(m.e.HandleGraphite))
mux.HandleFunc("/varz", http.HandlerFunc(m.e.HandleVarz))
mux.Handle("/debug/vars", expvar.Handler())
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
srv := &http.Server{
Handler: mux,
}
var wg sync.WaitGroup
errc := make(chan error, 1)
// This goroutine runs the http server.
wg.Add(1)
go func() {
defer wg.Done()
<-initDone
log.Printf("Listening on %s", m.listener.Addr())
if err := srv.Serve(m.listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
errc <- err
}
}()
// This goroutine manages http server shutdown.
go func() {
<-initDone
select {
case err := <-errc:
log.Println(err)
case <-m.ctx.Done():
log.Println("Shutdown requested.")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.SetKeepAlivesEnabled(false)
if err := srv.Shutdown(ctx); err != nil {
log.Println(err)
}
}
// Wait for the Serve routine to exit.
wg.Wait()
}()
return nil
}
// New creates a Server from the supplied Options. The Server is started by
// the time New returns, it watches the LogPatterns for files, starts tailing
// their changes and sends any new lines found to the virtual machines loaded
// from ProgramPath. If OneShot mode is enabled, it will exit after reading
// each log file from start to finish.
// TODO(jaq): this doesn't need to be a constructor anymore, it could start and
// block until quit, once TestServer.PollWatched is addressed.
func New(ctx context.Context, store *metrics.Store, options ...Option) (*Server, error) {
m := &Server{
ctx: ctx,
store: store,
lines: make(chan *logline.LogLine),
// Using a non-pedantic registry means we can be looser with metrics that
// are not fully specified at startup.
reg: prometheus.NewRegistry(),
}
if err := m.SetOption(options...); err != nil {
return nil, err
}
if err := m.initExporter(); err != nil {
return nil, err
}
if err := m.initRuntime(); err != nil {
return nil, err
}
if err := m.initTailer(); err != nil {
return nil, err
}
return m, nil
}
// SetOption takes one or more option functions and applies them in order to MtailServer.
func (m *Server) SetOption(options ...Option) error {
for _, option := range options {
if err := option.apply(m); err != nil {
return err
}
}
return nil
}
// Run awaits mtail's shutdown.
// TODO(jaq): remove this once the test server is able to trigger polls on the components.
func (m *Server) Run() error {
m.wg.Wait()
if m.compileOnly {
log.Println("compile-only is set, exiting")
return nil
}
return nil
}