-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
beat.go
1815 lines (1537 loc) · 54.4 KB
/
beat.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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 instance
import (
"context"
cryptRand "crypto/rand"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"math"
"math/big"
"math/rand"
"net"
"os"
"os/user"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/gofrs/uuid/v5"
"go.opentelemetry.io/collector/consumer"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/elastic/beats/v7/libbeat/api"
"github.com/elastic/beats/v7/libbeat/asset"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/cfgfile"
"github.com/elastic/beats/v7/libbeat/cloudid"
"github.com/elastic/beats/v7/libbeat/cmd/instance/locks"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/common/fleetmode"
"github.com/elastic/beats/v7/libbeat/common/reload"
"github.com/elastic/beats/v7/libbeat/common/seccomp"
"github.com/elastic/beats/v7/libbeat/dashboards"
"github.com/elastic/beats/v7/libbeat/esleg/eslegclient"
"github.com/elastic/beats/v7/libbeat/features"
"github.com/elastic/beats/v7/libbeat/idxmgmt"
"github.com/elastic/beats/v7/libbeat/idxmgmt/lifecycle"
"github.com/elastic/beats/v7/libbeat/instrumentation"
"github.com/elastic/beats/v7/libbeat/kibana"
"github.com/elastic/beats/v7/libbeat/management"
"github.com/elastic/beats/v7/libbeat/monitoring/report"
"github.com/elastic/beats/v7/libbeat/monitoring/report/log"
"github.com/elastic/beats/v7/libbeat/outputs"
"github.com/elastic/beats/v7/libbeat/outputs/elasticsearch"
"github.com/elastic/beats/v7/libbeat/plugin"
"github.com/elastic/beats/v7/libbeat/pprof"
"github.com/elastic/beats/v7/libbeat/publisher/pipeline"
"github.com/elastic/beats/v7/libbeat/publisher/processing"
"github.com/elastic/beats/v7/libbeat/publisher/queue/diskqueue"
"github.com/elastic/beats/v7/libbeat/version"
"github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/file"
"github.com/elastic/elastic-agent-libs/filewatcher"
"github.com/elastic/elastic-agent-libs/keystore"
kbn "github.com/elastic/elastic-agent-libs/kibana"
"github.com/elastic/elastic-agent-libs/logp"
"github.com/elastic/elastic-agent-libs/logp/configure"
"github.com/elastic/elastic-agent-libs/mapstr"
"github.com/elastic/elastic-agent-libs/monitoring"
"github.com/elastic/elastic-agent-libs/monitoring/report/buffer"
"github.com/elastic/elastic-agent-libs/paths"
svc "github.com/elastic/elastic-agent-libs/service"
"github.com/elastic/elastic-agent-libs/transport/tlscommon"
libversion "github.com/elastic/elastic-agent-libs/version"
"github.com/elastic/elastic-agent-system-metrics/metric/system/host"
metricreport "github.com/elastic/elastic-agent-system-metrics/report"
"github.com/elastic/go-sysinfo"
"github.com/elastic/go-sysinfo/types"
"github.com/elastic/go-ucfg"
)
// Beat provides the runnable and configurable instance of a beat.
type Beat struct {
beat.Beat
Config beatConfig
RawConfig *config.C // Raw config that can be unpacked to get Beat specific config data.
IdxSupporter idxmgmt.Supporter
keystore keystore.Keystore
processors processing.Supporter
InputQueueSize int // Size of the producer queue used by most queues.
// shouldReexec is a flag to indicate the Beat should restart
shouldReexec bool
}
type beatConfig struct {
beat.BeatConfig `config:",inline"`
// instance internal configs
// beat top-level settings
Name string `config:"name"`
MaxProcs int `config:"max_procs"`
GCPercent int `config:"gc_percent"`
Seccomp *config.C `config:"seccomp"`
Features *config.C `config:"features"`
// beat internal components configurations
HTTP *config.C `config:"http"`
HTTPPprof *pprof.Config `config:"http.pprof"`
BufferConfig *config.C `config:"http.buffer"`
Path paths.Path `config:"path"`
Logging *config.C `config:"logging"`
EventLogging *config.C `config:"logging.event_data"`
MetricLogging *config.C `config:"logging.metrics"`
Keystore *config.C `config:"keystore"`
Instrumentation instrumentation.Config `config:"instrumentation"`
// output/publishing related configurations
Pipeline pipeline.Config `config:",inline"`
// monitoring settings
MonitoringBeatConfig monitoring.BeatConfig `config:",inline"`
// ILM settings
LifecycleConfig lifecycle.RawConfig `config:",inline"`
// central management settings
Management *config.C `config:"management"`
// elastic stack 'setup' configurations
Dashboards *config.C `config:"setup.dashboards"`
Kibana *config.C `config:"setup.kibana"`
// Migration config to migration from 6 to 7
Migration *config.C `config:"migration.6_to_7"`
// TimestampPrecision sets the precision of all timestamps in the Beat.
TimestampPrecision *config.C `config:"timestamp"`
}
type certReloadConfig struct {
tlscommon.Config `config:",inline" yaml:",inline"`
Reload cfgfile.Reload `config:"restart_on_cert_change" yaml:"restart_on_cert_change"`
}
func (c certReloadConfig) Validate() error {
if c.Reload.Period < time.Second {
return errors.New("'restart_on_cert_change.period' must be equal or greather than 1s")
}
if c.Reload.Enabled && runtime.GOOS == "windows" {
return errors.New("'restart_on_cert_change' is not supported on Windows")
}
return nil
}
func defaultCertReloadConfig() certReloadConfig {
return certReloadConfig{
Reload: cfgfile.Reload{
Enabled: false,
Period: time.Minute,
},
}
}
var debugf = logp.MakeDebug("beat")
func init() {
initRand()
}
// initRand initializes the runtime random number generator seed using
// global, shared cryptographically strong pseudo random number generator.
//
// On linux Reader might use getrandom(2) or /udev/random. On windows systems
// CryptGenRandom is used.
func initRand() {
n, err := cryptRand.Int(cryptRand.Reader, big.NewInt(math.MaxInt64))
var seed int64
if err != nil {
// fallback to current timestamp
seed = time.Now().UnixNano()
} else {
seed = n.Int64()
}
rand.Seed(seed) //nolint:staticcheck // need seed from cryptographically strong PRNG.
}
// Run initializes and runs a Beater implementation. name is the name of the
// Beat (e.g. packetbeat or metricbeat). version is version number of the Beater
// implementation. bt is the `Creator` callback for creating a new beater
// instance.
// XXX Move this as a *Beat method?
func Run(settings Settings, bt beat.Creator) error {
return handleError(func() error {
defer func() {
if r := recover(); r != nil {
logp.NewLogger(settings.Name).Fatalw("Failed due to panic.",
"panic", r, zap.Stack("stack"))
}
}()
b, err := NewInitializedBeat(settings)
if err != nil {
return err
}
return b.launch(settings, bt)
}())
}
// NewInitializedBeat creates a new beat where all information and initialization is derived from settings
func NewInitializedBeat(settings Settings) (*Beat, error) {
b, err := NewBeat(settings.Name, settings.IndexPrefix, settings.Version, settings.ElasticLicensed, settings.Initialize)
if err != nil {
return nil, err
}
if err := b.InitWithSettings(settings); err != nil {
return nil, err
}
return b, nil
}
// NewBeat creates a new beat instance
func NewBeat(name, indexPrefix, v string, elasticLicensed bool, initFuncs []func()) (*Beat, error) {
// call all initialization functions
for _, f := range initFuncs {
f()
}
if v == "" {
v = version.GetDefaultVersion()
}
if indexPrefix == "" {
indexPrefix = name
}
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
fields, err := asset.GetFields(name)
if err != nil {
return nil, err
}
id, err := uuid.NewV4()
if err != nil {
return nil, err
}
b := beat.Beat{
Info: beat.Info{
Beat: name,
ElasticLicensed: elasticLicensed,
IndexPrefix: indexPrefix,
Version: v,
Name: hostname,
Hostname: hostname,
ID: id,
FirstStart: time.Now(),
StartTime: time.Now(),
EphemeralID: metricreport.EphemeralID(),
},
Fields: fields,
Registry: reload.NewRegistry(),
}
return &Beat{Beat: b}, nil
}
// NewBeatReceiver creates a Beat that will be used in the context of an otel receiver
func NewBeatReceiver(settings Settings, receiverConfig map[string]interface{}, consumer consumer.Logs, core zapcore.Core) (*Beat, error) {
b, err := NewBeat(settings.Name,
settings.IndexPrefix,
settings.Version,
settings.ElasticLicensed,
settings.Initialize)
if err != nil {
return nil, err
}
b.Info.LogConsumer = consumer
// begin code similar to configure
if err = plugin.Initialize(); err != nil {
return nil, fmt.Errorf("error initializing plugins: %w", err)
}
b.InputQueueSize = settings.InputQueueSize
cfOpts := []ucfg.Option{
ucfg.PathSep("."),
ucfg.ResolveEnv,
ucfg.VarExp,
}
tmp, err := ucfg.NewFrom(receiverConfig, cfOpts...)
if err != nil {
return nil, fmt.Errorf("error converting receiver config to ucfg: %w", err)
}
cfg := (*config.C)(tmp)
if err := initPaths(cfg); err != nil {
return nil, fmt.Errorf("error initializing paths: %w", err)
}
// We have to initialize the keystore before any unpack or merging the cloud
// options.
store, err := LoadKeystore(cfg, b.Info.Beat)
if err != nil {
return nil, fmt.Errorf("could not initialize the keystore: %w", err)
}
if settings.DisableConfigResolver {
config.OverwriteConfigOpts(obfuscateConfigOpts())
} else {
// TODO: Allow the options to be more flexible for dynamic changes
config.OverwriteConfigOpts(configOpts(store))
}
instrumentation, err := instrumentation.New(cfg, b.Info.Beat, b.Info.Version)
if err != nil {
return nil, fmt.Errorf("error setting up instrumentation: %w", err)
}
b.Beat.Instrumentation = instrumentation
b.keystore = store
b.Beat.Keystore = store
err = cloudid.OverwriteSettings(cfg)
if err != nil {
return nil, fmt.Errorf("error overwriting cloudid settings: %w", err)
}
b.RawConfig = cfg
err = cfg.Unpack(&b.Config)
if err != nil {
return nil, fmt.Errorf("error unpacking config data: %w", err)
}
logpConfig := logp.Config{}
logpConfig.Beat = b.Info.Name
logpConfig.Files.MaxSize = 1
if err := b.Config.Logging.Unpack(&logpConfig); err != nil {
return nil, fmt.Errorf("error unpacking beats logging config: %w\n%v", err, b.Config.Logging)
}
if err := logp.ConfigureWithCore(logpConfig, core); err != nil {
return nil, fmt.Errorf("error configuring beats logp: %w", err)
}
if err := promoteOutputQueueSettings(&b.Config); err != nil {
return nil, fmt.Errorf("could not promote output queue settings: %w", err)
}
if err := features.UpdateFromConfig(b.RawConfig); err != nil {
return nil, fmt.Errorf("could not parse features: %w", err)
}
b.RegisterHostname(features.FQDN())
b.Beat.Config = &b.Config.BeatConfig
if name := b.Config.Name; name != "" {
b.Info.Name = name
}
if err := common.SetTimestampPrecision(b.Config.TimestampPrecision); err != nil {
return nil, fmt.Errorf("error setting timestamp precision: %w", err)
}
// log paths values to help with troubleshooting
logp.Info(paths.Paths.String())
metaPath := paths.Resolve(paths.Data, "meta.json")
err = b.loadMeta(metaPath)
if err != nil {
return nil, fmt.Errorf("error loading meta data: %w", err)
}
logp.Info("Beat ID: %v", b.Info.ID)
// Try to get the host's FQDN and set it.
h, err := sysinfo.Host()
if err != nil {
return nil, fmt.Errorf("failed to get host information: %w", err)
}
fqdnLookupCtx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
fqdn, err := h.FQDNWithContext(fqdnLookupCtx)
if err != nil {
// FQDN lookup is "best effort". We log the error, fallback to
// the OS-reported hostname, and move on.
logp.Warn("unable to lookup FQDN: %s, using hostname = %s as FQDN", err.Error(), b.Info.Hostname)
b.Info.FQDN = b.Info.Hostname
} else {
b.Info.FQDN = fqdn
}
// initialize config manager
m, err := management.NewManager(b.Config.Management, b.Registry)
if err != nil {
return nil, fmt.Errorf("error creating new manager: %w", err)
}
b.Manager = m
if b.Manager.AgentInfo().Version != "" {
// During the manager initialization the client to connect to the agent is
// also initialized. That makes the beat to read information sent by the
// agent, which includes the AgentInfo with the agent's package version.
// Components running under agent should report the agent's package version
// as their own version.
// In order to do so b.Info.Version needs to be set to the version the agent
// sent. As this Beat instance is initialized much before the package
// version is received, it's overridden here. So far it's early enough for
// the whole beat to report the right version.
b.Info.Version = b.Manager.AgentInfo().Version
version.SetPackageVersion(b.Info.Version)
}
// build the user-agent string to be used by the outputs
b.GenerateUserAgent()
if err := b.Manager.CheckRawConfig(b.RawConfig); err != nil {
return nil, fmt.Errorf("error checking raw config: %w", err)
}
b.Beat.BeatConfig, err = b.BeatConfig()
if err != nil {
return nil, fmt.Errorf("error setting BeatConfig: %w", err)
}
imFactory := settings.IndexManagement
if imFactory == nil {
imFactory = idxmgmt.MakeDefaultSupport(settings.ILM)
}
b.IdxSupporter, err = imFactory(nil, b.Beat.Info, b.RawConfig)
if err != nil {
return nil, fmt.Errorf("error setting index supporter: %w", err)
}
processingFactory := settings.Processing
if processingFactory == nil {
processingFactory = processing.MakeDefaultBeatSupport(true)
}
b.processors, err = processingFactory(b.Info, logp.L().Named("processors"), b.RawConfig)
if err != nil {
return nil, fmt.Errorf("error creating processors: %w", err)
}
reg := monitoring.Default.GetRegistry(b.Info.Name)
if reg == nil {
reg = monitoring.Default.NewRegistry(b.Info.Name)
}
// This should be replaced with static config for otel consumer
// but need to figure out if we want the Queue settings from here.
outputEnabled := b.Config.Output.IsSet() && b.Config.Output.Config().Enabled()
if !outputEnabled {
if b.Manager.Enabled() {
logp.Info("Output is configured through Central Management")
} else {
return nil, fmt.Errorf("no outputs are defined, please define one under the output section")
}
}
tel := reg.GetRegistry("state")
if tel == nil {
tel = reg.NewRegistry("state")
}
monitors := pipeline.Monitors{
Metrics: reg,
Telemetry: tel,
Logger: logp.L().Named("publisher"),
Tracer: b.Instrumentation.Tracer(),
}
outputFactory := b.makeOutputFactory(b.Config.Output)
pipelineSettings := pipeline.Settings{
Processors: b.processors,
InputQueueSize: b.InputQueueSize,
}
publisher, err := pipeline.LoadWithSettings(b.Info, monitors, b.Config.Pipeline, outputFactory, pipelineSettings)
if err != nil {
return nil, fmt.Errorf("error initializing publisher: %w", err)
}
b.Registry.MustRegisterOutput(b.makeOutputReloader(publisher.OutputReloader()))
b.Publisher = publisher
return b, nil
}
// InitWithSettings does initialization of things common to all actions (read confs, flags)
func (b *Beat) InitWithSettings(settings Settings) error {
err := b.handleFlags()
if err != nil {
return err
}
if err := plugin.Initialize(); err != nil {
return err
}
if err := b.configure(settings); err != nil {
return err
}
return nil
}
// Init does initialization of things common to all actions (read confs, flags)
//
// Deprecated: use InitWithSettings
func (b *Beat) Init() error {
return b.InitWithSettings(Settings{})
}
// BeatConfig returns config section for this beat
func (b *Beat) BeatConfig() (*config.C, error) {
configName := strings.ToLower(b.Info.Beat)
if b.RawConfig.HasField(configName) {
sub, err := b.RawConfig.Child(configName, -1)
if err != nil {
return nil, err
}
return sub, nil
}
return config.NewConfig(), nil
}
// Keystore return the configured keystore for this beat
func (b *Beat) Keystore() keystore.Keystore {
return b.keystore
}
// create and return the beater, this method also initializes all needed items,
// including template registering, publisher, xpack monitoring
func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) {
sub, err := b.BeatConfig()
if err != nil {
return nil, err
}
log := logp.NewLogger("beat")
log.Infof("Setup Beat: %s; Version: %s", b.Info.Beat, b.Info.Version)
b.logSystemInfo(log)
err = b.registerESVersionCheckCallback()
if err != nil {
return nil, err
}
err = b.registerESIndexManagement()
if err != nil {
return nil, err
}
b.registerClusterUUIDFetching()
reg := monitoring.Default.GetRegistry("libbeat")
if reg == nil {
reg = monitoring.Default.NewRegistry("libbeat")
}
err = metricreport.SetupMetrics(logp.NewLogger("metrics"), b.Info.Beat, version.GetDefaultVersion())
if err != nil {
return nil, err
}
// Report central management state
mgmt := monitoring.GetNamespace("state").GetRegistry().NewRegistry("management")
monitoring.NewBool(mgmt, "enabled").Set(b.Manager.Enabled())
debugf("Initializing output plugins")
outputEnabled := b.Config.Output.IsSet() && b.Config.Output.Config().Enabled()
if !outputEnabled {
if b.Manager.Enabled() {
logp.Info("Output is configured through Central Management")
} else {
msg := "no outputs are defined, please define one under the output section"
logp.Info(msg)
return nil, errors.New(msg)
}
}
var publisher *pipeline.Pipeline
monitors := pipeline.Monitors{
Metrics: reg,
Telemetry: monitoring.GetNamespace("state").GetRegistry(),
Logger: logp.L().Named("publisher"),
Tracer: b.Instrumentation.Tracer(),
}
outputFactory := b.makeOutputFactory(b.Config.Output)
settings := pipeline.Settings{
// Since now publisher is closed on Stop, we want to give some
// time to ack any pending events by default to avoid
// changing on stop behavior too much.
WaitClose: time.Second,
Processors: b.processors,
InputQueueSize: b.InputQueueSize,
}
publisher, err = pipeline.LoadWithSettings(b.Info, monitors, b.Config.Pipeline, outputFactory, settings)
if err != nil {
return nil, fmt.Errorf("error initializing publisher: %w", err)
}
b.Registry.MustRegisterOutput(b.makeOutputReloader(publisher.OutputReloader()))
b.Publisher = publisher
beater, err := bt(&b.Beat, sub)
if err != nil {
return nil, err
}
return beater, nil
}
func (b *Beat) launch(settings Settings, bt beat.Creator) error {
defer func() {
_ = logp.Sync()
}()
defer logp.Info("%s stopped.", b.Info.Beat)
defer func() {
if err := b.processors.Close(); err != nil {
logp.Warn("Failed to close global processing: %v", err)
}
}()
// Windows: Mark service as stopped.
// After this is run, a Beat service is considered by the OS to be stopped
// and another instance of the process can be started.
// This must be the first deferred cleanup task (last to execute).
defer svc.NotifyTermination()
// Try to acquire exclusive lock on data path to prevent another beat instance
// sharing same data path. This is disabled under elastic-agent.
if !fleetmode.Enabled() {
bl := locks.New(b.Info)
err := bl.Lock()
if err != nil {
return err
}
defer func() {
_ = bl.Unlock()
}()
} else {
logp.Info("running under elastic-agent, per-beat lockfiles disabled")
}
svc.BeforeRun()
defer svc.Cleanup()
b.registerMetrics()
// Start the API Server before the Seccomp lock down, we do this so we can create the unix socket
// set the appropriate permission on the unix domain file without having to whitelist anything
// that would be set at runtime.
if b.Config.HTTP.Enabled() {
var err error
b.API, err = api.NewWithDefaultRoutes(logp.NewLogger(""), b.Config.HTTP, monitoring.GetNamespace)
if err != nil {
return fmt.Errorf("could not start the HTTP server for the API: %w", err)
}
b.API.Start()
defer func() {
_ = b.API.Stop()
}()
if b.Config.HTTPPprof.IsEnabled() {
pprof.SetRuntimeProfilingParameters(b.Config.HTTPPprof)
if err := pprof.HttpAttach(b.Config.HTTPPprof, b.API); err != nil {
return fmt.Errorf("failed to attach http handlers for pprof: %w", err)
}
}
}
// Do not load seccomp for osquerybeat, it was disabled before V2 in the configuration file
// https://github.com/elastic/beats/blob/7cf873fd340172c33f294500ccfec948afd7a47c/x-pack/osquerybeat/osquerybeat.yml#L16
if b.Info.Beat != "osquerybeat" {
if err := seccomp.LoadFilter(b.Config.Seccomp); err != nil {
return err
}
}
beater, err := b.createBeater(bt)
if err != nil {
return err
}
r, err := b.setupMonitoring(settings)
if err != nil {
return err
}
if r != nil {
defer r.Stop()
}
if b.Config.MetricLogging == nil || b.Config.MetricLogging.Enabled() {
reporter, err := log.MakeReporter(b.Info, b.Config.MetricLogging)
if err != nil {
return err
}
defer reporter.Stop()
}
// only collect into a ring buffer if HTTP, and the ring buffer are explicitly enabled
if b.Config.HTTP.Enabled() && monitoring.IsBufferEnabled(b.Config.BufferConfig) {
buffReporter, err := buffer.MakeReporter(b.Config.BufferConfig)
if err != nil {
return err
}
defer buffReporter.Stop()
if err := b.API.AttachHandler("/buffer", buffReporter); err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
// stopBeat must be idempotent since it will be called both from a signal and by the manager.
// Since publisher.Close is not safe to be called more than once this is necessary.
var once sync.Once
stopBeat := func() {
once.Do(func() {
b.Instrumentation.Tracer().Close()
// If the publisher has a Close() method, call it before stopping the beater.
if c, ok := b.Publisher.(io.Closer); ok {
c.Close()
}
beater.Stop()
})
}
svc.HandleSignals(stopBeat, cancel)
// Allow the manager to stop a currently running beats out of bound.
b.Manager.SetStopCallback(stopBeat)
err = b.loadDashboards(ctx, false)
if err != nil {
return err
}
logp.Info("%s start running.", b.Info.Beat)
err = beater.Run(&b.Beat)
if b.shouldReexec {
if err := b.reexec(); err != nil {
return fmt.Errorf("could not restart %s: %w", b.Info.Beat, err)
}
}
return err
}
// reexec restarts the Beat, it calls the OS-specific implementation.
func (b *Beat) reexec() error {
return b.doReexec()
}
// registerMetrics registers metrics with the internal monitoring API. This data
// is then exposed through the HTTP monitoring endpoint (e.g. /info and /state)
// and/or pushed to Elasticsearch through the x-pack monitoring feature.
func (b *Beat) registerMetrics() {
// info
infoRegistry := monitoring.GetNamespace("info").GetRegistry()
monitoring.NewString(infoRegistry, "version").Set(b.Info.Version)
monitoring.NewString(infoRegistry, "beat").Set(b.Info.Beat)
monitoring.NewString(infoRegistry, "name").Set(b.Info.Name)
monitoring.NewString(infoRegistry, "uuid").Set(b.Info.ID.String())
monitoring.NewString(infoRegistry, "ephemeral_id").Set(b.Info.EphemeralID.String())
monitoring.NewString(infoRegistry, "binary_arch").Set(runtime.GOARCH)
monitoring.NewString(infoRegistry, "build_commit").Set(version.Commit())
monitoring.NewTimestamp(infoRegistry, "build_time").Set(version.BuildTime())
monitoring.NewBool(infoRegistry, "elastic_licensed").Set(b.Info.ElasticLicensed)
// Add user metadata data asynchronously (on Windows the lookup can take up to 60s).
go func() {
if u, err := user.Current(); err != nil {
// This usually happens if the user UID does not exist in /etc/passwd. It might be the case on K8S
// if the user set securityContext.runAsUser to an arbitrary value.
monitoring.NewString(infoRegistry, "uid").Set(strconv.Itoa(os.Getuid()))
monitoring.NewString(infoRegistry, "gid").Set(strconv.Itoa(os.Getgid()))
} else {
monitoring.NewString(infoRegistry, "username").Set(u.Username)
monitoring.NewString(infoRegistry, "uid").Set(u.Uid)
monitoring.NewString(infoRegistry, "gid").Set(u.Gid)
}
}()
stateRegistry := monitoring.GetNamespace("state").GetRegistry()
// state.service
serviceRegistry := stateRegistry.NewRegistry("service")
monitoring.NewString(serviceRegistry, "version").Set(b.Info.Version)
monitoring.NewString(serviceRegistry, "name").Set(b.Info.Beat)
monitoring.NewString(serviceRegistry, "id").Set(b.Info.ID.String())
// state.beat
beatRegistry := stateRegistry.NewRegistry("beat")
monitoring.NewString(beatRegistry, "name").Set(b.Info.Name)
}
func (b *Beat) RegisterHostname(useFQDN bool) {
hostname := b.Info.FQDNAwareHostname(useFQDN)
// info.hostname
infoRegistry := monitoring.GetNamespace("info").GetRegistry()
monitoring.NewString(infoRegistry, "hostname").Set(hostname)
// state.host
stateRegistry := monitoring.GetNamespace("state").GetRegistry()
monitoring.NewFunc(stateRegistry, "host", host.ReportInfo(hostname), monitoring.Report)
}
// TestConfig check all settings are ok and the beat can be run
func (b *Beat) TestConfig(settings Settings, bt beat.Creator) error {
return handleError(func() error {
err := b.InitWithSettings(settings)
if err != nil {
return err
}
// Create beater to ensure all settings are OK
_, err = b.createBeater(bt)
if err != nil {
return err
}
fmt.Println("Config OK") //nolint:forbidigo // required to give feedback to user
return beat.GracefulExit
}())
}
// SetupSettings holds settings necessary for beat setup
type SetupSettings struct {
Dashboard bool
Pipeline bool
IndexManagement bool
// Deprecated: use IndexManagementKey instead
Template bool
// Deprecated: use IndexManagementKey instead
ILMPolicy bool
EnableAllFilesets bool
ForceEnableModuleFilesets bool
}
// Setup registers ES index template, kibana dashboards, ml jobs and pipelines.
//
//nolint:forbidigo // required to give feedback to user
func (b *Beat) Setup(settings Settings, bt beat.Creator, setup SetupSettings) error {
return handleError(func() error {
err := b.InitWithSettings(settings)
if err != nil {
return err
}
// Tell the beat that we're in the setup command
b.InSetupCmd = true
if setup.ForceEnableModuleFilesets {
if err := b.Beat.BeatConfig.SetBool("config.modules.force_enable_module_filesets", -1, true); err != nil {
return fmt.Errorf("error setting force_enable_module_filesets config option %w", err)
}
}
// Create beater to give it the opportunity to set loading callbacks
_, err = b.createBeater(bt)
if err != nil {
return err
}
if setup.IndexManagement || setup.Template || setup.ILMPolicy {
outCfg := b.Config.Output
if !isElasticsearchOutput(outCfg.Name()) {
return fmt.Errorf("index management requested but the Elasticsearch output is not configured/enabled")
}
esClient, err := eslegclient.NewConnectedClient(outCfg.Config(), b.Info.Beat)
if err != nil {
return err
}
// other components know to skip ILM setup under serverless, this logic block just helps us print an error message
// in instances where ILM has been explicitly enabled
var ilmCfg struct {
Ilm *config.C `config:"setup.ilm"`
}
err = b.RawConfig.Unpack(&ilmCfg)
if err != nil {
return fmt.Errorf("error unpacking ILM config: %w", err)
}
if ilmCfg.Ilm.Enabled() && esClient.IsServerless() {
fmt.Println("WARNING: ILM is not supported in Serverless projects")
}
loadTemplate, loadILM := idxmgmt.LoadModeUnset, idxmgmt.LoadModeUnset
if setup.IndexManagement || setup.Template {
loadTemplate = idxmgmt.LoadModeOverwrite
}
if setup.IndexManagement || setup.ILMPolicy {
loadILM = idxmgmt.LoadModeEnabled
}
mgmtHandler, err := idxmgmt.NewESClientHandler(esClient, b.Info, b.Config.LifecycleConfig)
if err != nil {
return fmt.Errorf("error creating index management handler: %w", err)
}
m := b.IdxSupporter.Manager(mgmtHandler, idxmgmt.BeatsAssets(b.Fields))
if ok, warn := m.VerifySetup(loadTemplate, loadILM); !ok {
fmt.Println(warn)
}
if err = m.Setup(loadTemplate, loadILM); err != nil {
return err
}
fmt.Println("Index setup finished.")
}
if setup.Dashboard && settings.HasDashboards {
fmt.Println("Loading dashboards (Kibana must be running and reachable)")
err = b.loadDashboards(context.Background(), true)
if err != nil {
var notFoundErr *dashboards.ErrNotFound
if errors.As(err, ¬FoundErr) {
fmt.Printf("Skipping loading dashboards, %+v\n", err)
} else {
return err
}
} else {
fmt.Println("Loaded dashboards")
}
}
if setup.Pipeline && b.OverwritePipelinesCallback != nil {
if setup.EnableAllFilesets {
if err := b.Beat.BeatConfig.SetBool("config.modules.enable_all_filesets", -1, true); err != nil {
return fmt.Errorf("error setting enable_all_filesets config option %w", err)
}
}
esConfig := b.Config.Output.Config()
err = b.OverwritePipelinesCallback(esConfig)
if err != nil {
return err
}
fmt.Println("Loaded Ingest pipelines")
}
return nil
}())
}
// handleFlags parses the command line flags. It invokes the HandleFlags
// callback if implemented by the Beat.
func (b *Beat) handleFlags() error {
flag.Parse()
return cfgfile.HandleFlags()
}
// config reads the configuration file from disk, parses the common options
// defined in BeatConfig, initializes logging, and set GOMAXPROCS if defined
// in the config. Lastly it invokes the Config method implemented by the beat.
func (b *Beat) configure(settings Settings) error {
var err error
b.InputQueueSize = settings.InputQueueSize
cfg, err := cfgfile.Load("", settings.ConfigOverrides)
if err != nil {
return fmt.Errorf("error loading config file: %w", err)
}
if err := initPaths(cfg); err != nil {
return err
}