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