github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/config/config.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "strconv" 8 "strings" 9 "time" 10 11 log "github.com/hashicorp/go-hclog" 12 "github.com/hashicorp/nomad/client/state" 13 "github.com/hashicorp/nomad/helper" 14 "github.com/hashicorp/nomad/helper/pluginutils/loader" 15 "github.com/hashicorp/nomad/nomad/structs" 16 "github.com/hashicorp/nomad/nomad/structs/config" 17 "github.com/hashicorp/nomad/plugins/base" 18 "github.com/hashicorp/nomad/version" 19 ) 20 21 var ( 22 // DefaultEnvBlacklist is the default set of environment variables that are 23 // filtered when passing the environment variables of the host to a task. 24 DefaultEnvBlacklist = strings.Join([]string{ 25 "CONSUL_TOKEN", 26 "CONSUL_HTTP_TOKEN", 27 "VAULT_TOKEN", 28 "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", 29 "GOOGLE_APPLICATION_CREDENTIALS", 30 }, ",") 31 32 // DefaultUserBlacklist is the default set of users that tasks are not 33 // allowed to run as when using a driver in "user.checked_drivers" 34 DefaultUserBlacklist = strings.Join([]string{ 35 "root", 36 "Administrator", 37 }, ",") 38 39 // DefaultUserCheckedDrivers is the set of drivers we apply the user 40 // blacklist onto. For virtualized drivers it often doesn't make sense to 41 // make this stipulation so by default they are ignored. 42 DefaultUserCheckedDrivers = strings.Join([]string{ 43 "exec", 44 "qemu", 45 "java", 46 }, ",") 47 48 // A mapping of directories on the host OS to attempt to embed inside each 49 // task's chroot. 50 DefaultChrootEnv = map[string]string{ 51 "/bin": "/bin", 52 "/etc": "/etc", 53 "/lib": "/lib", 54 "/lib32": "/lib32", 55 "/lib64": "/lib64", 56 "/run/resolvconf": "/run/resolvconf", 57 "/sbin": "/sbin", 58 "/usr": "/usr", 59 } 60 ) 61 62 // RPCHandler can be provided to the Client if there is a local server 63 // to avoid going over the network. If not provided, the Client will 64 // maintain a connection pool to the servers 65 type RPCHandler interface { 66 RPC(method string, args interface{}, reply interface{}) error 67 } 68 69 // Config is used to parameterize and configure the behavior of the client 70 type Config struct { 71 // DevMode controls if we are in a development mode which 72 // avoids persistent storage. 73 DevMode bool 74 75 // EnableDebug is used to enable debugging RPC endpoints 76 // in the absence of ACLs 77 EnableDebug bool 78 79 // StateDir is where we store our state 80 StateDir string 81 82 // AllocDir is where we store data for allocations 83 AllocDir string 84 85 // LogOutput is the destination for logs 86 LogOutput io.Writer 87 88 // Logger provides a logger to thhe client 89 Logger log.InterceptLogger 90 91 // Region is the clients region 92 Region string 93 94 // Network interface to be used in network fingerprinting 95 NetworkInterface string 96 97 // Network speed is the default speed of network interfaces if they can not 98 // be determined dynamically. 99 NetworkSpeed int 100 101 // CpuCompute is the default total CPU compute if they can not be determined 102 // dynamically. It should be given as Cores * MHz (2 Cores * 2 Ghz = 4000) 103 CpuCompute int 104 105 // MemoryMB is the default node total memory in megabytes if it cannot be 106 // determined dynamically. 107 MemoryMB int 108 109 // MaxKillTimeout allows capping the user-specifiable KillTimeout. If the 110 // task's KillTimeout is greater than the MaxKillTimeout, MaxKillTimeout is 111 // used. 112 MaxKillTimeout time.Duration 113 114 // Servers is a list of known server addresses. These are as "host:port" 115 Servers []string 116 117 // RPCHandler can be provided to avoid network traffic if the 118 // server is running locally. 119 RPCHandler RPCHandler 120 121 // Node provides the base node 122 Node *structs.Node 123 124 // ClientMaxPort is the upper range of the ports that the client uses for 125 // communicating with plugin subsystems over loopback 126 ClientMaxPort uint 127 128 // ClientMinPort is the lower range of the ports that the client uses for 129 // communicating with plugin subsystems over loopback 130 ClientMinPort uint 131 132 // A mapping of directories on the host OS to attempt to embed inside each 133 // task's chroot. 134 ChrootEnv map[string]string 135 136 // Options provides arbitrary key-value configuration for nomad internals, 137 // like fingerprinters and drivers. The format is: 138 // 139 // namespace.option = value 140 Options map[string]string 141 142 // Version is the version of the Nomad client 143 Version *version.VersionInfo 144 145 // ConsulConfig is this Agent's Consul configuration 146 ConsulConfig *config.ConsulConfig 147 148 // VaultConfig is this Agent's Vault configuration 149 VaultConfig *config.VaultConfig 150 151 // StatsCollectionInterval is the interval at which the Nomad client 152 // collects resource usage stats 153 StatsCollectionInterval time.Duration 154 155 // PublishNodeMetrics determines whether nomad is going to publish node 156 // level metrics to remote Telemetry sinks 157 PublishNodeMetrics bool 158 159 // PublishAllocationMetrics determines whether nomad is going to publish 160 // allocation metrics to remote Telemetry sinks 161 PublishAllocationMetrics bool 162 163 // TLSConfig holds various TLS related configurations 164 TLSConfig *config.TLSConfig 165 166 // GCInterval is the time interval at which the client triggers garbage 167 // collection 168 GCInterval time.Duration 169 170 // GCParallelDestroys is the number of parallel destroys the garbage 171 // collector will allow. 172 GCParallelDestroys int 173 174 // GCDiskUsageThreshold is the disk usage threshold given as a percent 175 // beyond which the Nomad client triggers GC of terminal allocations 176 GCDiskUsageThreshold float64 177 178 // GCInodeUsageThreshold is the inode usage threshold given as a percent 179 // beyond which the Nomad client triggers GC of the terminal allocations 180 GCInodeUsageThreshold float64 181 182 // GCMaxAllocs is the maximum number of allocations a node can have 183 // before garbage collection is triggered. 184 GCMaxAllocs int 185 186 // LogLevel is the level of the logs to putout 187 LogLevel string 188 189 // NoHostUUID disables using the host's UUID and will force generation of a 190 // random UUID. 191 NoHostUUID bool 192 193 // ACLEnabled controls if ACL enforcement and management is enabled. 194 ACLEnabled bool 195 196 // ACLTokenTTL is how long we cache token values for 197 ACLTokenTTL time.Duration 198 199 // ACLPolicyTTL is how long we cache policy values for 200 ACLPolicyTTL time.Duration 201 202 // DisableTaggedMetrics determines whether metrics will be displayed via a 203 // key/value/tag format, or simply a key/value format 204 DisableTaggedMetrics bool 205 206 // DisableRemoteExec disables remote exec targeting tasks on this client 207 DisableRemoteExec bool 208 209 // TemplateConfig includes configuration for template rendering 210 TemplateConfig *ClientTemplateConfig 211 212 // BackwardsCompatibleMetrics determines whether to show methods of 213 // displaying metrics for older versions, or to only show the new format 214 BackwardsCompatibleMetrics bool 215 216 // RPCHoldTimeout is how long an RPC can be "held" before it is errored. 217 // This is used to paper over a loss of leadership by instead holding RPCs, 218 // so that the caller experiences a slow response rather than an error. 219 // This period is meant to be long enough for a leader election to take 220 // place, and a small jitter is applied to avoid a thundering herd. 221 RPCHoldTimeout time.Duration 222 223 // PluginLoader is used to load plugins. 224 PluginLoader loader.PluginCatalog 225 226 // PluginSingletonLoader is a plugin loader that will returns singleton 227 // instances of the plugins. 228 PluginSingletonLoader loader.PluginCatalog 229 230 // StateDBFactory is used to override stateDB implementations, 231 StateDBFactory state.NewStateDBFunc 232 233 // CNIPath is the path used to search for CNI plugins. Multiple paths can 234 // be specified with colon delimited 235 CNIPath string 236 237 // BridgeNetworkName is the name to use for the bridge created in bridge 238 // networking mode. This defaults to 'nomad' if not set 239 BridgeNetworkName string 240 241 // BridgeNetworkAllocSubnet is the IP subnet to use for address allocation 242 // for allocations in bridge networking mode. Subnet must be in CIDR 243 // notation 244 BridgeNetworkAllocSubnet string 245 246 // HostVolumes is a map of the configured host volumes by name. 247 HostVolumes map[string]*structs.ClientHostVolumeConfig 248 } 249 250 type ClientTemplateConfig struct { 251 FunctionBlacklist []string 252 DisableSandbox bool 253 } 254 255 func (c *ClientTemplateConfig) Copy() *ClientTemplateConfig { 256 if c == nil { 257 return nil 258 } 259 260 nc := new(ClientTemplateConfig) 261 *nc = *c 262 nc.FunctionBlacklist = helper.CopySliceString(nc.FunctionBlacklist) 263 return nc 264 } 265 266 func (c *Config) Copy() *Config { 267 nc := new(Config) 268 *nc = *c 269 nc.Node = nc.Node.Copy() 270 nc.Servers = helper.CopySliceString(nc.Servers) 271 nc.Options = helper.CopyMapStringString(nc.Options) 272 nc.HostVolumes = structs.CopyMapStringClientHostVolumeConfig(nc.HostVolumes) 273 nc.ConsulConfig = c.ConsulConfig.Copy() 274 nc.VaultConfig = c.VaultConfig.Copy() 275 nc.TemplateConfig = c.TemplateConfig.Copy() 276 return nc 277 } 278 279 // DefaultConfig returns the default configuration 280 func DefaultConfig() *Config { 281 return &Config{ 282 Version: version.GetVersion(), 283 VaultConfig: config.DefaultVaultConfig(), 284 ConsulConfig: config.DefaultConsulConfig(), 285 LogOutput: os.Stderr, 286 Region: "global", 287 StatsCollectionInterval: 1 * time.Second, 288 TLSConfig: &config.TLSConfig{}, 289 LogLevel: "DEBUG", 290 GCInterval: 1 * time.Minute, 291 GCParallelDestroys: 2, 292 GCDiskUsageThreshold: 80, 293 GCInodeUsageThreshold: 70, 294 GCMaxAllocs: 50, 295 NoHostUUID: true, 296 DisableTaggedMetrics: false, 297 DisableRemoteExec: false, 298 TemplateConfig: &ClientTemplateConfig{ 299 FunctionBlacklist: []string{"plugin"}, 300 DisableSandbox: false, 301 }, 302 BackwardsCompatibleMetrics: false, 303 RPCHoldTimeout: 5 * time.Second, 304 } 305 } 306 307 // Read returns the specified configuration value or "". 308 func (c *Config) Read(id string) string { 309 return c.Options[id] 310 } 311 312 // ReadDefault returns the specified configuration value, or the specified 313 // default value if none is set. 314 func (c *Config) ReadDefault(id string, defaultValue string) string { 315 val, ok := c.Options[id] 316 if !ok { 317 return defaultValue 318 } 319 return val 320 } 321 322 // ReadBool parses the specified option as a boolean. 323 func (c *Config) ReadBool(id string) (bool, error) { 324 val, ok := c.Options[id] 325 if !ok { 326 return false, fmt.Errorf("Specified config is missing from options") 327 } 328 bval, err := strconv.ParseBool(val) 329 if err != nil { 330 return false, fmt.Errorf("Failed to parse %s as bool: %s", val, err) 331 } 332 return bval, nil 333 } 334 335 // ReadBoolDefault tries to parse the specified option as a boolean. If there is 336 // an error in parsing, the default option is returned. 337 func (c *Config) ReadBoolDefault(id string, defaultValue bool) bool { 338 val, err := c.ReadBool(id) 339 if err != nil { 340 return defaultValue 341 } 342 return val 343 } 344 345 // ReadInt parses the specified option as a int. 346 func (c *Config) ReadInt(id string) (int, error) { 347 val, ok := c.Options[id] 348 if !ok { 349 return 0, fmt.Errorf("Specified config is missing from options") 350 } 351 ival, err := strconv.Atoi(val) 352 if err != nil { 353 return 0, fmt.Errorf("Failed to parse %s as int: %s", val, err) 354 } 355 return ival, nil 356 } 357 358 // ReadIntDefault tries to parse the specified option as a int. If there is 359 // an error in parsing, the default option is returned. 360 func (c *Config) ReadIntDefault(id string, defaultValue int) int { 361 val, err := c.ReadInt(id) 362 if err != nil { 363 return defaultValue 364 } 365 return val 366 } 367 368 // ReadDuration parses the specified option as a duration. 369 func (c *Config) ReadDuration(id string) (time.Duration, error) { 370 val, ok := c.Options[id] 371 if !ok { 372 return time.Duration(0), fmt.Errorf("Specified config is missing from options") 373 } 374 dval, err := time.ParseDuration(val) 375 if err != nil { 376 return time.Duration(0), fmt.Errorf("Failed to parse %s as time duration: %s", val, err) 377 } 378 return dval, nil 379 } 380 381 // ReadDurationDefault tries to parse the specified option as a duration. If there is 382 // an error in parsing, the default option is returned. 383 func (c *Config) ReadDurationDefault(id string, defaultValue time.Duration) time.Duration { 384 val, err := c.ReadDuration(id) 385 if err != nil { 386 return defaultValue 387 } 388 return val 389 } 390 391 // ReadStringListToMap tries to parse the specified option as a comma separated list. 392 // If there is an error in parsing, an empty list is returned. 393 func (c *Config) ReadStringListToMap(key string) map[string]struct{} { 394 s := strings.TrimSpace(c.Read(key)) 395 list := make(map[string]struct{}) 396 if s != "" { 397 for _, e := range strings.Split(s, ",") { 398 trimmed := strings.TrimSpace(e) 399 list[trimmed] = struct{}{} 400 } 401 } 402 return list 403 } 404 405 // ReadStringListToMap tries to parse the specified option as a comma separated list. 406 // If there is an error in parsing, an empty list is returned. 407 func (c *Config) ReadStringListToMapDefault(key, defaultValue string) map[string]struct{} { 408 val, ok := c.Options[key] 409 if !ok { 410 val = defaultValue 411 } 412 413 list := make(map[string]struct{}) 414 if val != "" { 415 for _, e := range strings.Split(val, ",") { 416 trimmed := strings.TrimSpace(e) 417 list[trimmed] = struct{}{} 418 } 419 } 420 return list 421 } 422 423 // NomadPluginConfig produces the NomadConfig struct which is sent to Nomad plugins 424 func (c *Config) NomadPluginConfig() *base.AgentConfig { 425 return &base.AgentConfig{ 426 Driver: &base.ClientDriverConfig{ 427 ClientMinPort: c.ClientMinPort, 428 ClientMaxPort: c.ClientMaxPort, 429 }, 430 } 431 }