This repository has been archived by the owner on Oct 30, 2024. It is now read-only.
forked from cosmonic-labs/netreap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
262 lines (222 loc) · 7.03 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
package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
cilium_client "github.com/cilium/cilium/pkg/client"
cilium_command "github.com/cilium/cilium/pkg/command"
cilium_kvstore "github.com/cilium/cilium/pkg/kvstore"
"github.com/cilium/cilium/pkg/labelsfilter"
cilium_logging "github.com/cilium/cilium/pkg/logging"
nomad_api "github.com/hashicorp/nomad/api"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"github.com/cosmonic-labs/netreap/internal/zaplogrus"
"github.com/cosmonic-labs/netreap/reapers"
)
var Version = "unreleased"
type config struct {
clusterName string
debug bool
kvStore string
kvStoreOpts map[string]string
labels cli.StringSlice
labelPrefixFile string
policiesPrefix string
}
func main() {
ctx := context.Background()
conf := config{}
app := &cli.App{
Name: "netreap",
Usage: "A custom monitor and reaper for cleaning up Cilium endpoints and nodes",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "debug",
Value: false,
Usage: "Enable debug logging",
EnvVars: []string{"NETREAP_DEBUG"},
Destination: &conf.debug,
},
&cli.StringFlag{
Name: "policies-prefix",
Aliases: []string{"p"},
Value: reapers.PoliciesKeyPrefix,
Usage: "kvstore key prefix to watch for Cilium policy updates.",
EnvVars: []string{"NETREAP_POLICIES_PREFIX"},
Destination: &conf.policiesPrefix,
},
&cli.StringFlag{
Name: "kvstore",
Usage: "Consul key to watch for Cilium policy updates.",
EnvVars: []string{"NETREAP_KVSTORE"},
Destination: &conf.kvStore,
},
&cli.StringFlag{
Name: "kvstore-opts",
Usage: "Consul key to watch for Cilium policy updates.",
EnvVars: []string{"NETREAP_KVSTORE_OPTS"},
},
&cli.StringFlag{
Name: "cluster-name",
Usage: "Cilium cluster name.",
EnvVars: []string{"NETREAP_CLUSTER_NAME"},
Destination: &conf.clusterName,
},
&cli.StringSliceFlag{
Name: "labels",
Usage: "List of label prefixes used to determine identity of an endpoint.",
Destination: &conf.labels,
},
&cli.StringFlag{
Name: "label-prefix-file",
Usage: "Valid label prefixes file path.",
Destination: &conf.labelPrefixFile,
},
},
Before: func(ctx *cli.Context) error {
// Borrow the parser from Cilium
kvStoreOpt := ctx.String("kvstore-opts")
if m, err := cilium_command.ToStringMapStringE(kvStoreOpt); err != nil {
return fmt.Errorf("unable to parse %s: %w", kvStoreOpt, err)
} else {
conf.kvStoreOpts = m
}
return nil
},
Action: func(c *cli.Context) error {
return run(c.Context, conf)
},
Version: Version,
}
if err := app.RunContext(ctx, os.Args); err != nil {
zap.L().Fatal("Error running netreap", zap.Error(err))
}
}
func configureLogging(debug bool) (logger *zap.Logger, err error) {
// Step 0: Setup logging
if debug {
logger, err = zap.NewDevelopment()
} else {
logger, err = zap.NewProduction()
}
if err != nil {
return nil, err
}
zap.ReplaceGlobals(logger)
// Bridge Cilium logrus to netreap zap
cilium_logging.DefaultLogger.SetReportCaller(true)
cilium_logging.DefaultLogger.SetOutput(io.Discard)
cilium_logging.DefaultLogger.AddHook(zaplogrus.NewZapLogrusHook(logger))
return logger, nil
}
func run(ctx context.Context, conf config) error {
logger, err := configureLogging(conf.debug)
if err != nil {
return fmt.Errorf("can't initialize zap logger: %w", err)
}
defer logger.Sync()
if err := labelsfilter.ParseLabelPrefixCfg(conf.labels.Value(), conf.labelPrefixFile); err != nil {
return fmt.Errorf("unable to parse Label prefix configuration: %w", err)
}
// Step 0: Construct the clients
// Looks for the default Cilium socket path or uses the value from CILIUM_SOCK
cilium_client, err := cilium_client.NewDefaultClient()
if err != nil {
return fmt.Errorf("error when connecting to cilium agent: %w", err)
}
// Fetch config from Cilium if not set
resp, err := cilium_client.ConfigGet()
if err != nil {
return fmt.Errorf("unable to retrieve cilium configuration: %w", err)
}
if resp.Status == nil {
return fmt.Errorf("unable to retrieve cilium configuration: empty response")
}
kvstoreConfig := resp.Status.KvstoreConfiguration
if conf.kvStore == "" {
conf.kvStore = kvstoreConfig.Type
}
if len(conf.kvStoreOpts) == 0 {
for k, v := range kvstoreConfig.Options {
conf.kvStoreOpts[k] = v
}
}
if conf.clusterName == "" {
conf.clusterName = resp.Status.DaemonConfigurationMap["ClusterName"].(string)
}
err = cilium_kvstore.Setup(ctx, conf.kvStore, conf.kvStoreOpts, nil)
if err != nil {
return fmt.Errorf("unable to connect to Cilium kvstore: %w", err)
}
// DefaultConfig fetches configuration data from well-known nomad variables (e.g. NOMAD_ADDR,
// NOMAD_CACERT), so we'll just leverage that for now.
nomad_client, err := nomad_api.NewClient(nomad_api.DefaultConfig())
if err != nil {
return fmt.Errorf("unable to connect to Nomad: %w", err)
}
// Get the node ID of the instance we're running on
self, err := nomad_client.Agent().Self()
if err != nil {
return fmt.Errorf("unable to query local agent info: %w", err)
}
clientStats, ok := self.Stats["client"]
if !ok {
return fmt.Errorf("not running on a client node")
}
nodeID, ok := clientStats["node_id"]
if !ok {
return fmt.Errorf("unable to get local node ID")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
// Step 1: Leader election
zap.L().Debug("Starting leader reaper")
nodeReaper, err := reapers.NewLeaderReaper(ctx, cilium_kvstore.Client(), nomad_client.Nodes(), nomad_client.EventStream(), os.Getenv("NOMAD_ALLOC_ID"), conf.clusterName)
if err != nil {
return err
}
leaderFailChan, err := nodeReaper.Run()
if err != nil {
return fmt.Errorf("unable to start leader reaper: %w", err)
}
// Step 2: Start the reapers
zap.L().Debug("Starting endpoint reaper")
endpoint_reaper, err := reapers.NewEndpointReaper(cilium_client, nomad_client.Allocations(), nomad_client.EventStream(), nodeID)
if err != nil {
return err
}
endpointFailChan, err := endpoint_reaper.Run(ctx)
if err != nil {
return fmt.Errorf("unable to start endpoint reaper: %w", err)
}
zap.S().Debug("Starting policies reaper")
policiesReaper, err := reapers.NewPoliciesReaper(cilium_kvstore.Client(), conf.policiesPrefix, cilium_client)
if err != nil {
return err
}
policiesFailChan, err := policiesReaper.Run(ctx)
if err != nil {
return fmt.Errorf("unable to start policies reaper: %w", err)
}
// Wait for interrupt or client failure
select {
case <-c:
zap.S().Info("Received interrupt, shutting down")
cancel()
case <-leaderFailChan:
zap.S().Error("leader reaper kvstore client failed, shutting down")
cancel()
case <-endpointFailChan:
zap.S().Error("endpoint reaper kvstore client failed, shutting down")
cancel()
case <-policiesFailChan:
zap.S().Error("policies reaper kvstore client failed, shutting down")
cancel()
}
return nil
}