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