-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
356 lines (310 loc) · 11.8 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
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"sync"
"time"
"github.com/hashicorp-forge/nomad-nodesim/allocrunnersim"
internalConfig "github.com/hashicorp-forge/nomad-nodesim/internal/config"
internalSimnode "github.com/hashicorp-forge/nomad-nodesim/internal/simnode"
"github.com/hashicorp-forge/nomad-nodesim/pluginsim"
"github.com/hashicorp-forge/nomad-nodesim/simconsul"
"github.com/hashicorp-forge/nomad-nodesim/simnode"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client"
"github.com/hashicorp/nomad/client/allocrunner"
"github.com/hashicorp/nomad/client/config"
"github.com/hashicorp/nomad/client/consul"
"github.com/hashicorp/nomad/client/state"
"github.com/hashicorp/nomad/helper/pluginutils/singleton"
"github.com/hashicorp/nomad/helper/pointer"
"github.com/hashicorp/nomad/nomad/structs"
structsc "github.com/hashicorp/nomad/nomad/structs/config"
"github.com/hashicorp/nomad/version"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
flagConfig := internalConfig.Config{
Log: &internalConfig.Log{},
Node: &internalConfig.Node{
Resources: &internalConfig.NodeResource{},
},
}
flag.StringVar(&flagConfig.WorkDir, "work-dir", "", "working directory")
flag.Var(&flagConfig.ServerAddr, "server-addr", "address of server's rpc port; can be specified multiple times")
flag.StringVar(&flagConfig.NodeNamePrefix, "node-name-prefix", "", "nodes will be named [prefix]-[i]")
flag.IntVar(&flagConfig.NodeNum, "node-num", 0, "number of client nodes")
flag.StringVar(&flagConfig.AllocRunnerType, "alloc-runner-type", "", "the type of Nomad client alloc runner to use")
// The CLI flags for the HCL Logger.
flag.StringVar(&flagConfig.Log.Level, "log-level", "", "the verbosity level of logs")
flag.BoolVar(&flagConfig.Log.JSON, "log-json", false, "output logs in a JSON format")
flag.BoolVar(&flagConfig.Log.IncludeLocation, "log-include-location", false, "include file and line information in each log line")
var configFile string
flag.StringVar(&configFile, "config", "", "path to a config file to load")
flag.Parse()
// Instantiate our initial default config. This will be used to overlay all
// other configs, starting with any supplied config file, then the CLI
// flags.
mergedConfig := internalConfig.Default()
if configFile != "" {
parsedConfigFile, err := internalConfig.ParseFile(configFile)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed parse config file: %s", err)
os.Exit(2)
}
mergedConfig = mergedConfig.Merge(parsedConfigFile)
}
mergedConfig = mergedConfig.Merge(&flagConfig)
// Build the logger used by the nodesim application.
logger := hclog.NewInterceptLogger(&hclog.LoggerOptions{
Name: "nomad-nodesim",
Level: hclog.LevelFromString(mergedConfig.Log.Level),
JSONFormat: mergedConfig.Log.JSON,
IncludeLocation: mergedConfig.Log.IncludeLocation,
})
logger.Info("config",
"dir", mergedConfig.WorkDir, "num", mergedConfig.NodeNum, "server", mergedConfig.ServerAddr,
"id", mergedConfig.NodeNamePrefix)
if ctx.Err() != nil {
fmt.Fprintf(os.Stderr, "canceled before clients created")
os.Exit(2)
}
buildInfo, err := internalSimnode.GenerateBuildInfo(logger)
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "failed to generate build info: %w", err)
os.Exit(2)
}
handles := make([]*simnode.Node, mergedConfig.NodeNum)
for i := 0; i < mergedConfig.NodeNum; i++ {
nodeName := fmt.Sprintf("%s-%v", mergedConfig.NodeNamePrefix, i)
// Start the simulate client; any error starting any client is
// considered fatal to the nodesim application.
if handles[i], err = startClient(logger, buildInfo, mergedConfig, nodeName); err != nil {
err = fmt.Errorf("error creating client %s: %w", nodeName, err)
break
}
logger.Info("started client",
"node_id", handles[i].Client.NodeID(), "node_name", nodeName,
"index", i+1, "total", mergedConfig.NodeNum)
if err = ctx.Err(); err != nil {
break
}
}
if err != nil {
logger.Error("error creating clients", "error", err)
wg := &sync.WaitGroup{}
for _, h := range handles {
if h == nil {
continue
}
wg.Add(1)
go func(n *simnode.Node) {
defer wg.Done()
if err := n.Shutdown(); err != nil {
logger.Warn("error shutting down client node", "error", err, "node_id", n.Client.NodeID())
}
}(h)
}
wg.Wait()
logger.Info("done cleaning up client nodes")
os.Exit(10)
}
logger.Info("clients started", "total", mergedConfig.NodeNum)
<-ctx.Done()
logger.Info("interrupted; shutting down clients")
wg := &sync.WaitGroup{}
for _, h := range handles {
wg.Add(1)
go func(n *simnode.Node) {
defer wg.Done()
if err := n.Shutdown(); err != nil {
logger.Warn("error shutting down client node", "error", err, "node", n.Client.NodeID())
}
}(h)
}
wg.Wait()
logger.Info("done")
}
func startClient(logger hclog.Logger, buildInfo *internalSimnode.BuildInfo, cfg *internalConfig.Config, nodeName string) (*simnode.Node, error) {
rootDir := filepath.Join(cfg.WorkDir, nodeName)
if err := os.MkdirAll(rootDir, 0750); err != nil {
return nil, fmt.Errorf("error creating client dir: %w", err)
}
logout, err := os.Create(filepath.Join(rootDir, "client.log"))
if err != nil {
return nil, fmt.Errorf("error creating log output: %w", err)
}
clientCfg := config.DefaultConfig()
clientCfg.DevMode = false
clientCfg.EnableDebug = true
clientCfg.StateDir = filepath.Join(rootDir, "state")
clientCfg.AllocDir = filepath.Join(rootDir, "allocs")
hclogopts := &hclog.LoggerOptions{
Name: nodeName,
Level: hclog.Trace,
Output: logout,
JSONFormat: false, //TODO expose option?
IncludeLocation: true,
TimeFn: time.Now,
TimeFormat: "2006-01-02T15:04:05Z07:00.000", //TODO expose option?
Color: hclog.ColorOff,
}
clientCfg.Logger = hclog.NewInterceptLogger(hclogopts)
clientCfg.Region = cfg.Node.Region
//TODO cfg.NetworkInterface
// Fake resources
clientCfg.NetworkSpeed = 1_000
clientCfg.CpuCompute = int(cfg.Node.Resources.CPUCompute)
clientCfg.MemoryMB = int(cfg.Node.Resources.MemoryMB)
clientCfg.MaxKillTimeout = time.Minute
clientCfg.Servers = cfg.ServerAddr
tlsConfig := tlsConfigFromEnv()
tlsEnabled := true
if tlsConfig == nil {
tlsConfig = &structsc.TLSConfig{}
tlsEnabled = false
}
//TODO
clientCfg.Node = &structs.Node{
Datacenter: cfg.Node.Datacenter,
Name: nodeName,
NodePool: cfg.Node.NodePool,
NodeClass: cfg.Node.NodeClass,
HTTPAddr: "127.0.0.1:4646", // is this used? -- yes in the UI!
TLSEnabled: tlsEnabled,
Attributes: map[string]string{}, //TODO expose option? fake linux?
NodeResources: &structs.NodeResources{
Cpu: structs.LegacyNodeCpuResources{
CpuShares: int64(clientCfg.CpuCompute),
ReservableCpuCores: []uint16{},
},
Memory: structs.NodeMemoryResources{MemoryMB: int64(clientCfg.MemoryMB)},
Disk: structs.NodeDiskResources{DiskMB: 1_000_000},
Devices: []*structs.NodeDeviceResource{},
NodeNetworks: []*structs.NodeNetworkResource{
&structs.NodeNetworkResource{
Mode: "host",
Device: "eth0",
MacAddress: "d4:fb:6a:7c:31:b4",
Speed: 1000,
Addresses: []structs.NodeNetworkAddress{
{
Family: structs.NodeNetworkAF_IPv4,
Alias: "public",
Address: "127.0.0.1", //TODO ¯\_(ツ)_/¯
ReservedPorts: "1-1024", // ¯\_(ツ)_/¯
Gateway: "127.0.0.1", // ¯\_(ツ)_/¯
},
},
},
},
Networks: []*structs.NetworkResource{}, // can I get away with this being empty?
MinDynamicPort: 2000,
MaxDynamicPort: 3000,
},
ReservedResources: &structs.NodeReservedResources{},
// Resources is deprecated
// Reserved is deprecated
//FIXME but still used by GCConfig! Fix that in Nomad
Reserved: &structs.Resources{},
Links: map[string]string{},
Meta: map[string]string{
"nodesim.id": cfg.NodeNamePrefix,
"nodesim.alloc_id": os.Getenv("NOMAD_ALLOC_ID"),
"nodesim.enabled": "true",
"nodesim.version": buildInfo.Version,
"nodesim.sum": buildInfo.Sum,
},
CSIControllerPlugins: make(map[string]*structs.CSIInfo),
CSINodePlugins: make(map[string]*structs.CSIInfo),
HostVolumes: make(map[string]*structs.ClientHostVolumeConfig),
HostNetworks: make(map[string]*structs.ClientHostNetworkConfig),
}
clientCfg.ClientMinPort = 3001 // ¯\_(ツ)_/¯
clientCfg.ClientMaxPort = 4000 // ¯\_(ツ)_/¯
clientCfg.MinDynamicPort = 5001 // ¯\_(ツ)_/¯
clientCfg.MaxDynamicPort = 6000 // ¯\_(ツ)_/¯
clientCfg.ChrootEnv = map[string]string{}
clientCfg.Options = cfg.Node.Options
clientCfg.Version = &version.VersionInfo{
Version: buildInfo.Nomad.Version,
}
clientCfg.ConsulConfigs = map[string]*structsc.ConsulConfig{structs.ConsulDefaultCluster: structsc.DefaultConsulConfig()}
clientCfg.VaultConfigs = map[string]*structsc.VaultConfig{structs.VaultDefaultCluster: {Enabled: pointer.Of(false)}}
clientCfg.StatsCollectionInterval = 10 * time.Second
clientCfg.TLSConfig = tlsConfig
clientCfg.GCInterval = time.Hour
clientCfg.GCParallelDestroys = 1
clientCfg.GCDiskUsageThreshold = 100.0
clientCfg.GCInodeUsageThreshold = 100.0
clientCfg.GCMaxAllocs = 10_000
clientCfg.NoHostUUID = true
clientCfg.ACLEnabled = false //TODO expose option
clientCfg.ACLTokenTTL = time.Hour
clientCfg.ACLPolicyTTL = time.Hour
clientCfg.DisableRemoteExec = true
clientCfg.RPCHoldTimeout = 5 * time.Second
pluginLoader := pluginsim.New(clientCfg.Logger)
clientCfg.PluginLoader = pluginLoader
clientCfg.PluginSingletonLoader = singleton.NewSingletonLoader(clientCfg.Logger, pluginLoader)
clientCfg.StateDBFactory = state.GetStateDBFactory(false) // store state!
clientCfg.NomadServiceDiscovery = true
//TODO TemplateDialer: could proxy to the server's address?
clientCfg.Artifact = &config.ArtifactConfig{
HTTPReadTimeout: 5 * time.Second,
GCSTimeout: 5 * time.Second,
GitTimeout: 5 * time.Second,
HgTimeout: 5 * time.Second,
S3Timeout: 5 * time.Second,
}
// This config parameter is used by the taskrunner API hook. The hook will
// panic when triggered if this is not set.
clientCfg.APIListenerRegistrar = config.NoopAPIListenerRegistrar{}
clientCfg.Node.Canonicalize()
// Build the allocation runner factory based on whether we want the
// simulated (light) or real version.
var allocRunnerFactory config.AllocRunnerFactory
switch cfg.AllocRunnerType {
case internalConfig.AllocRunnerTypeSim:
allocRunnerFactory = allocrunnersim.NewEmptyAllocRunnerFunc
case internalConfig.AllocRunnerTypeReal:
allocRunnerFactory = allocrunner.NewAllocRunner
default:
return nil, fmt.Errorf("unsupported alloc-runner type: %s", cfg.AllocRunnerType)
}
clientCfg.AllocRunnerFactory = allocRunnerFactory
// Consul support is disabled
capi := simconsul.NoopCatalogAPI{}
consulProxies := map[string]simconsul.NoopSupportedProxiesAPI{}
cproxiesFn := func(cluster string) consul.SupportedProxiesAPI { return consulProxies[cluster] }
serviceReg := simconsul.NoopServiceRegHandler{}
c, err := client.NewClient(clientCfg, capi, cproxiesFn, serviceReg, nil)
if err != nil {
return nil, fmt.Errorf("error creating client: %w", err)
}
return simnode.New(c, logger), nil
}
func tlsConfigFromEnv() *structsc.TLSConfig {
caCertFile := os.Getenv("NOMAD_CACERT")
certFile := os.Getenv("NOMAD_CLIENT_CERT")
keyFile := os.Getenv("NOMAD_CLIENT_KEY")
if certFile == "" || caCertFile == "" || keyFile == "" {
return nil
}
return &structsc.TLSConfig{
EnableHTTP: true,
EnableRPC: true,
VerifyServerHostname: true,
VerifyHTTPSClient: true,
CAFile: caCertFile,
CertFile: certFile,
KeyFile: keyFile,
}
}