-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathlist.go
189 lines (159 loc) · 5.28 KB
/
list.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
// 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 cfgfile
import (
"sync"
"github.com/joeshaw/multierror"
"github.com/mitchellh/hashstructure"
"github.com/pkg/errors"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/common/reload"
"github.com/elastic/beats/v7/libbeat/publisher/pipetool"
"github.com/elastic/elastic-agent-libs/config"
"github.com/elastic/elastic-agent-libs/logp"
)
// RunnerList implements a reloadable.List of Runners
type RunnerList struct {
runners map[uint64]Runner
mutex sync.RWMutex
factory RunnerFactory
pipeline beat.PipelineConnector
logger *logp.Logger
}
// NewRunnerList builds and returns a RunnerList
func NewRunnerList(name string, factory RunnerFactory, pipeline beat.PipelineConnector) *RunnerList {
return &RunnerList{
runners: map[uint64]Runner{},
factory: factory,
pipeline: pipeline,
logger: logp.NewLogger(name),
}
}
// Reload the list of runners to match the given state
func (r *RunnerList) Reload(configs []*reload.ConfigWithMeta) error {
r.mutex.Lock()
defer r.mutex.Unlock()
var errs multierror.Errors
startList := map[uint64]*reload.ConfigWithMeta{}
stopList := r.copyRunnerList()
r.logger.Debugf("Starting reload procedure, current runners: %d", len(stopList))
// diff current & desired state, create action lists
for _, config := range configs {
hash, err := HashConfig(config.Config)
if err != nil {
r.logger.Errorf("Unable to hash given config: %s", err)
errs = append(errs, errors.Wrap(err, "Unable to hash given config"))
continue
}
if _, ok := r.runners[hash]; ok {
delete(stopList, hash)
} else {
startList[hash] = config
}
}
r.logger.Debugf("Start list: %d, Stop list: %d", len(startList), len(stopList))
wg := sync.WaitGroup{}
// Stop removed runners
for hash, runner := range stopList {
wg.Add(1)
r.logger.Debugf("Stopping runner: %s", runner)
delete(r.runners, hash)
go func(runner Runner) {
defer wg.Done()
runner.Stop()
r.logger.Debugf("Runner: '%s' has stopped", runner)
}(runner)
moduleStops.Add(1)
}
// Wait for all runners to stop before starting new ones
wg.Wait()
// Start new runners
for hash, config := range startList {
runner, err := createRunner(r.factory, r.pipeline, config)
if err != nil {
if _, ok := err.(*common.ErrInputNotFinished); ok {
// error is related to state, we should not log at error level
r.logger.Debugf("Error creating runner from config: %s", err)
} else {
r.logger.Errorf("Error creating runner from config: %s", err)
}
errs = append(errs, errors.Wrap(err, "Error creating runner from config"))
continue
}
r.logger.Debugf("Starting runner: %s", runner)
r.runners[hash] = runner
runner.Start()
moduleStarts.Add(1)
}
// NOTE: This metric tracks the number of modules in the list. The true
// number of modules in the running state may differ because modules can
// stop on their own (i.e. on errors) and also when this stops a module
// above it is done asynchronously.
moduleRunning.Set(int64(len(r.runners)))
return errs.Err()
}
// Stop all runners
func (r *RunnerList) Stop() {
r.mutex.Lock()
defer r.mutex.Unlock()
if len(r.runners) == 0 {
return
}
r.logger.Infof("Stopping %v runners ...", len(r.runners))
wg := sync.WaitGroup{}
for hash, runner := range r.copyRunnerList() {
wg.Add(1)
delete(r.runners, hash)
// Stop modules in parallel
go func(h uint64, run Runner) {
defer wg.Done()
r.logger.Debugf("Stopping runner: %s", run)
run.Stop()
r.logger.Debugf("Stopped runner: %s", run)
}(hash, runner)
}
wg.Wait()
}
// Has returns true if a runner with the given hash is running
func (r *RunnerList) Has(hash uint64) bool {
r.mutex.RLock()
defer r.mutex.RUnlock()
_, ok := r.runners[hash]
return ok
}
// HashConfig hashes a given config.C
func HashConfig(c *config.C) (uint64, error) {
var config map[string]interface{}
if err := c.Unpack(&config); err != nil {
return 0, err
}
return hashstructure.Hash(config, nil)
}
func (r *RunnerList) copyRunnerList() map[uint64]Runner {
list := make(map[uint64]Runner, len(r.runners))
for k, v := range r.runners {
list[k] = v
}
return list
}
func createRunner(factory RunnerFactory, pipeline beat.PipelineConnector, cfg *reload.ConfigWithMeta) (Runner, error) {
// Pass a copy of the config to the factory, this way if the factory modifies it,
// that doesn't affect the hash of the original one.
c, _ := config.NewConfigFrom(cfg.Config)
return factory.Create(pipetool.WithDynamicFields(pipeline, cfg.Meta), c)
}