// Configure initializes this formatter with values from a plugin config.
436301
func (format *Aggregate) Configure(conf core.PluginConfigReader) {
	applyTo := conf.GetString("ApplyTo", "")

	// init modulator array
	modulatorSettings := format.getModulatorSettings(applyTo, conf)

	config := core.NewPluginConfig("", "format.Aggregate.Modulators")
	config.Override("Modulators", modulatorSettings)
	modulatorReader := core.NewPluginConfigReaderWithError(&config)

	modulatorArray, err := modulatorReader.GetModulatorArray("Modulators", format.Logger, core.ModulatorArray{})
	if err != nil {
		conf.Errors.Push(err)
	}

	format.modulators = modulatorArray
}
809557
func (cons *HTTP) Configure(conf core.PluginConfigReader) {
	if cons.htpasswd != "" {
		if _, fileErr := os.Stat(cons.htpasswd); os.IsNotExist(fileErr) {
			conf.Errors.Pushf("htpasswd file does not exist: %s", cons.htpasswd)
			cons.htpasswd = ""
		}
		cons.secrets = auth.HtpasswdFileProvider(cons.htpasswd)
	}

	certificateFile := conf.GetString("Certificate", "")
	keyFile := conf.GetString("PrivateKey", "")

	if certificateFile != "" || keyFile != "" {
		if certificateFile == "" || keyFile == "" {
			conf.Errors.Pushf("There must always be a certificate and a private key or none of both")
		} else {

			cons.certificate = new(tls.Config)
			cons.certificate.NextProtos = []string{"http/1.1"}

			keypair, err := tls.LoadX509KeyPair(certificateFile, keyFile)
			if !conf.Errors.Push(err) {
				cons.certificate.Certificates = []tls.Certificate{keypair}
			}
		}
	}
}
1091916
func (prod *AwsFirehose) Configure(conf core.PluginConfigReader) {
	prod.lastSendTime = time.Now()
	prod.metricsRegistry = core.NewMetricsRegistryForPlugin(prod)
	prod.metricCount = make(map[string]metrics.Counter)

	if prod.recordMaxMessages < 1 {
		prod.recordMaxMessages = 1
		prod.Logger.Warning("RecordMaxMessages was < 1. Defaulting to 1.")
	}

	if prod.recordMaxMessages > 1 && len(prod.delimiter) == 0 {
		prod.delimiter = []byte("\n")
		prod.Logger.Warning("RecordMessageDelimiter was empty. Defaulting to \"\\n\".")
	}

	prod.streamMap = conf.GetStreamMap("StreamMapping", "default")
	for _, firehoseStreamName := range prod.streamMap {
		counter := metrics.NewCounter()
		prod.metricCount[firehoseStreamName] = counter
		prod.metricsRegistry.Register(firehoseStreamName, counter)
	}
}
1199333
func (prod *Socket) Configure(conf core.PluginConfigReader) {
	prod.SetStopCallback(prod.close)

	prod.protocol, prod.address = tnet.ParseAddress(conf.GetString("Address", ":5880"), "tcp")
	prod.batchFlushCount = tmath.MinI(prod.batchFlushCount, prod.batchMaxCount)

	switch prod.protocol {
	case "udp":
		if prod.acknowledge != "" {
			prod.Logger.Warning("Acknowledge is only supported for TCP connections. TCP connection forced.")
			prod.protocol = "tcp"
		}
	case "unix", "tcp":
		// Everything is fine
	default:
		prod.protocol = "tcp"
	}

	prod.batch = core.NewMessageBatch(prod.batchMaxCount)
	prod.assembly = core.NewWriterAssembly(nil, prod.TryFallback, prod)
	prod.assembly.SetValidator(prod.validate)
	prod.assembly.SetErrorHandler(prod.onWriteError)
}
1086355
func (format *ProcessTSV) Configure(conf core.PluginConfigReader) {
	directives := conf.GetStringArray("Directives", []string{})

	format.directives = make([]tsvDirective, 0, len(directives))
	for _, d := range directives {
		directive := strings.Replace(d, "\\:", "\r", -1)
		parts := strings.Split(directive, ":")
		for i, value := range parts {
			parts[i] = strings.Replace(value, "\r", ":", -1)
		}

		if len(parts) >= 2 {
			index, err := strconv.Atoi(parts[0])
			conf.Errors.Push(err)

			newDirective := tsvDirective{
				index:     index,
				operation: strings.ToLower(parts[1]),
			}

			for i := 2; i < len(parts); i++ {
				newDirective.parameters = append(newDirective.parameters, tstrings.Unescape(parts[i]))
			}

			format.directives = append(format.directives, newDirective)
		}
	}
}
1036086
func (pruner *Pruner) Configure(conf core.PluginConfigReader) {
	if pruner.pruneSize > 0 && pruner.rotate.SizeByte > 0 {
		pruner.pruneSize -= pruner.rotate.SizeByte >> 20
		if pruner.pruneSize <= 0 {
			pruner.pruneCount = 1
			pruner.pruneSize = 0
		}
	}
}
1205281
func (p *Plugin) Reconfigure(_ context.Context, config interface{}) {
	p.reconfig <- config
}
63854
func (format *Double) Configure(conf core.PluginConfigReader) {
	format.applyTo = conf.GetString("ApplyTo", "")
}
1362698
func Configure(apiServer, kubeconfigPath string) {
	config.APIServer = apiServer
	config.KubeconfigPath = kubeconfigPath

	if IsEnabled() &&
		config.APIServer != "" &&
		!strings.HasPrefix(apiServer, "http") {
		config.APIServer = "http://" + apiServer
	}
}
1341916
func (_m *Communicator) Configure(channel string, members []cluster.RemoteNode) {
	_m.Called(channel, members)
}
447807
func (prod *S3) Configure(conf core.PluginConfigReader) {
	prod.SetStopCallback(prod.close)

	prod.streamMap = conf.GetStreamMap("StreamMapping", "default")
	prod.batch = core.NewMessageBatch(int(conf.GetInt("BatchMaxMessages", 5000)))

	prod.lastSendTime = time.Now()
	prod.closing = false
	prod.objects = make(map[string]*objectData)
	prod.objectsLock = new(sync.Mutex)

	prod.metricsRegistry = core.NewMetricsRegistry(prod.GetID())
	prod.counters = make(map[string]metrics.Counter)

	for _, s3Path := range prod.streamMap {
		counter := metrics.NewCounter()
		prod.counters[s3Path] = counter
		prod.metricsRegistry.Register(s3Path, counter)
	}

	prod.useFiles = prod.localPath != ""
	if prod.useFiles {
		if err := os.MkdirAll(prod.localPath, 0700); err != nil {
			conf.Errors.Pushf("Failed to create %s because of %s", prod.localPath, err.Error())
			return // ### return, missing directory ###
		}
		prod.stateFile = path.Join(prod.localPath, "state")
		if _, err := os.Stat(prod.stateFile); !os.IsNotExist(err) {
			data, err := ioutil.ReadFile(prod.stateFile)
			if conf.Errors.Push(err) {
				return
			}
			if err := json.Unmarshal(data, &prod.objects); conf.Errors.Push(err) {
				return
			}
			for s3Path, object := range prod.objects {
				filename := object.Filename
				basename := path.Base(filename)
				if basenum, err := strconv.ParseInt(basename, 10, 64); err == nil && basenum > prod.nextFile {
					prod.nextFile = basenum
				}
				if object.Compressed {
					filename += ".gz"
				}
				buffer, err := newS3FileBuffer(filename,
					prod.Logger.WithField("Scope", "fileBuffer"))
				if conf.Errors.Push(err) {
					return
				}
				object.buffer = buffer
				object.lock = new(sync.Mutex)
				// add missing metrics
				if _, exists := prod.counters[s3Path]; !exists {
					counter := metrics.NewCounter()
					prod.counters[s3Path] = counter
					prod.metricsRegistry.GetOrRegister(s3Path, counter)
				}
			}
		}
	}

	if conf.HasValue("PathFormatter") {
		keyFormatter := conf.GetPlugin("PathFormatter", "format.Identifier", tcontainer.MarshalMap{})
		prod.pathFormat = keyFormatter.(core.Modulator)
	} else {
		prod.pathFormat = nil
	}

	if prod.objectMaxMessages < 1 {
		prod.objectMaxMessages = 1
		prod.Logger.Warning("ObjectMaxMessages was < 1. Defaulting to 1.")
	}

	if prod.objectMaxMessages > 1 && len(prod.delimiter) == 0 {
		prod.delimiter = []byte("\n")
		prod.Logger.Warning("ObjectMessageDelimiter was empty. Defaulting to \"\\n\".")
	}

	// Config
	defaultEndpoint := "s3.amazonaws.com"
	prod.config = aws.NewConfig()
	if region := conf.GetString("Region", "eu-west-1"); region != "" {
		prod.config.WithRegion(region)
		if region != "us-east-1" {
			defaultEndpoint = "s3-" + region + ".amazonaws.com"
		}
	}

	if endpoint := conf.GetString("Endpoint", defaultEndpoint); endpoint != "" {
		prod.config.WithEndpoint(endpoint)
	}

	// Credentials
	prod.config.CredentialsChainVerboseErrors = aws.Bool(true)
	credentialType := strings.ToLower(conf.GetString("Credential/Type", s3CredentialNone))
	switch credentialType {
	case s3CredentialEnv:
		prod.config.WithCredentials(credentials.NewEnvCredentials())

	case s3CredentialStatic:
		id := conf.GetString("Credential/Id", "")
		token := conf.GetString("Credential/Token", "")
		secret := conf.GetString("Credential/Secret", "")
		prod.config.WithCredentials(credentials.NewStaticCredentials(id, secret, token))

	case s3CredentialShared:
		filename := conf.GetString("Credential/File", "")
		profile := conf.GetString("Credential/Profile", "")
		prod.config.WithCredentials(credentials.NewSharedCredentials(filename, profile))

	case s3CredentialNone:
		// Nothing

	default:
		conf.Errors.Pushf("Unknown CredentialType: %s", credentialType)
	}
}
277163
func (cons *Kafka) Configure(conf core.PluginConfigReader) {
	cons.offsets = make(map[int32]*int64)
	cons.MaxPartitionID = 0

	cons.config = kafka.NewConfig()
	cons.config.ClientID = conf.GetString("ClientId", "gollum")
	cons.config.ChannelBufferSize = int(conf.GetInt("MessageBufferCount", 8192))

	switch ver := conf.GetString("Version", "0.8.2"); ver {
	case "0.8.2.0":
		cons.config.Version = kafka.V0_8_2_0
	case "0.8.2.1":
		cons.config.Version = kafka.V0_8_2_1
	case "0.8", "0.8.2", "0.8.2.2":
		cons.config.Version = kafka.V0_8_2_2
	case "0.9.0", "0.9.0.0":
		cons.config.Version = kafka.V0_9_0_0
	case "0.9", "0.9.0.1":
		cons.config.Version = kafka.V0_9_0_1
	case "0.10", "0.10.0", "0.10.0.0":
		cons.config.Version = kafka.V0_10_0_0
	case "0.10.0.1":
		cons.config.Version = kafka.V0_10_0_1
	case "0.10.1", "0.10.1.0":
		cons.config.Version = kafka.V0_10_1_0
	case "0.10.2", "0.10.2.0":
		cons.config.Version = kafka.V0_10_2_0
	case "0.11", "0.11.0", "0.11.0.0":
		cons.config.Version = kafka.V0_11_0_0
	case "1", "1.0", "1.0.0", "1.0.0.0":
		cons.config.Version = kafka.V1_0_0_0
	default:
		cons.Logger.Warningf("Unknown kafka version given: %s. Falling back to 0.8.2", ver)
		cons.config.Version = kafka.V0_8_2_2
	}

	cons.config.Net.MaxOpenRequests = int(conf.GetInt("MaxOpenRequests", 5))
	cons.config.Net.DialTimeout = time.Duration(conf.GetInt("ServerTimeoutSec", 30)) * time.Second
	cons.config.Net.ReadTimeout = cons.config.Net.DialTimeout
	cons.config.Net.WriteTimeout = cons.config.Net.DialTimeout

	cons.config.Net.TLS.Enable = conf.GetBool("TlsEnable", false)
	if cons.config.Net.TLS.Enable {
		cons.config.Net.TLS.Config = &tls.Config{}

		keyFile := conf.GetString("TlsKeyLocation", "")
		certFile := conf.GetString("TlsCertificateLocation", "")
		if keyFile != "" && certFile != "" {
			cert, err := tls.LoadX509KeyPair(certFile, keyFile)
			if conf.Errors.Push(err) {
				return
			}
			cons.config.Net.TLS.Config.Certificates = []tls.Certificate{cert}
		} else if certFile == "" {
			conf.Errors.Pushf("Cannot specify TlsKeyLocation without TlsCertificateLocation")
			return
		} else if keyFile == "" {
			conf.Errors.Pushf("Cannot specify TlsCertificateLocation without TlsKeyLocation")
			return
		}

		caFile := conf.GetString("TlsCaLocation", "")
		if caFile == "" {
			conf.Errors.Pushf("TlsEnable is set to true, but no TlsCaLocation was specified")
			return
		}

		caCert, err := ioutil.ReadFile(caFile)
		if conf.Errors.Push(err) {
			return
		}

		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)
		cons.config.Net.TLS.Config.RootCAs = caCertPool

		serverName := conf.GetString("TlsServerName", "")
		if serverName != "" {
			cons.config.Net.TLS.Config.ServerName = serverName
		}

		cons.config.Net.TLS.Config.InsecureSkipVerify = conf.GetBool("TlsInsecureSkipVerify", false)
	}

	cons.config.Net.SASL.Enable = conf.GetBool("SaslEnable", false)
	if cons.config.Net.SASL.Enable {
		cons.config.Net.SASL.User = conf.GetString("SaslUser", "gollum")
		cons.config.Net.SASL.Password = conf.GetString("SaslPassword", "")
	}

	cons.config.Metadata.Retry.Max = int(conf.GetInt("ElectRetries", 3))
	cons.config.Metadata.Retry.Backoff = time.Duration(conf.GetInt("ElectTimeoutMs", 250)) * time.Millisecond
	cons.config.Metadata.RefreshFrequency = time.Duration(conf.GetInt("MetadataRefreshMs", 10000)) * time.Millisecond

	cons.config.Consumer.Fetch.Min = int32(conf.GetInt("MinFetchSizeByte", 1))
	cons.config.Consumer.Fetch.Max = int32(conf.GetInt("MaxFetchSizeByte", 0))
	cons.config.Consumer.Fetch.Default = int32(conf.GetInt("DefaultFetchSizeByte", 32768))
	cons.config.Consumer.MaxWaitTime = time.Duration(conf.GetInt("FetchTimeoutMs", 250)) * time.Millisecond

	if cons.group != "" {
		cons.offsetFile = "" // forcibly ignore this option
		switch cons.config.Version {
		case kafka.V0_8_2_0, kafka.V0_8_2_1, kafka.V0_8_2_2:
			cons.Logger.Warning("Invalid kafka version 0.8.x given, minimum is 0.9 for consumer groups, defaulting to 0.9.0.1")
			cons.config.Version = kafka.V0_9_0_1
		}

		cons.groupConfig = cluster.NewConfig()
		cons.groupConfig.Config = *cons.config
	}

	offsetValue := strings.ToLower(conf.GetString("DefaultOffset", kafkaOffsetNewest))
	switch offsetValue {
	case kafkaOffsetNewest:
		cons.defaultOffset = kafka.OffsetNewest

	case kafkaOffsetOldest:
		cons.defaultOffset = kafka.OffsetOldest

	default:
		cons.defaultOffset, _ = strconv.ParseInt(offsetValue, 10, 64)
	}

	if cons.offsetFile != "" {
		fileContents, err := ioutil.ReadFile(cons.offsetFile)
		if err != nil {
			cons.Logger.Warningf("Failed to open kafka offset file: %s", err.Error())
		} else {
			// Decode the JSON file into the partition -> offset map
			encodedOffsets := make(map[string]int64)
			err = json.Unmarshal(fileContents, &encodedOffsets)
			if conf.Errors.Push(err) {
				return
			}

			for k, v := range encodedOffsets {
				id, err := strconv.Atoi(k)
				if conf.Errors.Push(err) {
					return
				}
				startOffset := v
				cons.offsets[int32(id)] = &startOffset
			}
		}
	}

	kafka.Logger = cons.Logger.WithField("Scope", "Sarama")
}
555952
func (filter *Stream) Configure(conf core.PluginConfigReader) {
	filter.blacklist = conf.GetStreamArray("Block", []core.MessageStreamID{})
	filter.whitelist = conf.GetStreamArray("Only", []core.MessageStreamID{})
}
1357264
func Configure(clf *CommandLineFlags, cfg *service.Config) error {
	// pass the value of --insecure flag to the runtime
	lib.SetInsecureDevMode(clf.InsecureMode)

	// load /etc/teleport.yaml and apply it's values:
	fileConf, err := ReadConfigFile(clf.ConfigFile)
	if err != nil {
		return trace.Wrap(err)
	}
	// if configuration is passed as an environment variable,
	// try to decode it and override the config file
	if clf.ConfigString != "" {
		fileConf, err = ReadFromString(clf.ConfigString)
		if err != nil {
			return trace.Wrap(err)
		}
	}

	// apply command line --debug flag to override logger severity
	if fileConf != nil && clf.Debug {
		fileConf.Logger.Severity = teleport.DebugLevel
	}

	if err = ApplyFileConfig(fileConf, cfg); err != nil {
		return trace.Wrap(err)
	}

	// Apply diagnostic address flag.
	if clf.DiagnosticAddr != "" {
		addr, err := utils.ParseAddr(clf.DiagnosticAddr)
		if err != nil {
			return trace.Wrap(err, "failed to parse diag-addr")
		}
		cfg.DiagnosticAddr = *addr
	}

	// apply --insecure-no-tls flag:
	if clf.DisableTLS {
		cfg.Proxy.DisableTLS = clf.DisableTLS
	}

	// apply --debug flag to config:
	if clf.Debug {
		cfg.Console = ioutil.Discard
		cfg.Debug = clf.Debug
	}

	// apply --roles flag:
	if clf.Roles != "" {
		if err := validateRoles(clf.Roles); err != nil {
			return trace.Wrap(err)
		}
		cfg.SSH.Enabled = strings.Index(clf.Roles, defaults.RoleNode) != -1
		cfg.Auth.Enabled = strings.Index(clf.Roles, defaults.RoleAuthService) != -1
		cfg.Proxy.Enabled = strings.Index(clf.Roles, defaults.RoleProxy) != -1
	}

	// apply --auth-server flag:
	if clf.AuthServerAddr != "" {
		if cfg.Auth.Enabled {
			log.Warnf("not starting the local auth service. --auth-server flag tells to connect to another auth server")
			cfg.Auth.Enabled = false
		}
		addr, err := utils.ParseHostPortAddr(clf.AuthServerAddr, int(defaults.AuthListenPort))
		if err != nil {
			return trace.Wrap(err)
		}
		log.Infof("Using auth server: %v", addr.FullAddress())
		cfg.AuthServers = []utils.NetAddr{*addr}
	}

	// apply --name flag:
	if clf.NodeName != "" {
		cfg.Hostname = clf.NodeName
	}

	// apply --pid-file flag
	if clf.PIDFile != "" {
		cfg.PIDFile = clf.PIDFile
	}

	// apply --token flag:
	cfg.ApplyToken(clf.AuthToken)

	// Apply flags used for the node to validate the Auth Server.
	if clf.CAPin != "" {
		cfg.CAPin = clf.CAPin
	}

	// apply --listen-ip flag:
	if clf.ListenIP != nil {
		applyListenIP(clf.ListenIP, cfg)
	}

	// --advertise-ip flag
	if clf.AdvertiseIP != "" {
		if _, _, err := utils.ParseAdvertiseAddr(clf.AdvertiseIP); err != nil {
			return trace.Wrap(err)
		}
		cfg.AdvertiseIP = clf.AdvertiseIP
	}

	// apply --labels flag
	if err = parseLabels(clf.Labels, &cfg.SSH); err != nil {
		return trace.Wrap(err)
	}

	// --pid-file:
	if clf.PIDFile != "" {
		cfg.PIDFile = clf.PIDFile
	}

	// auth_servers not configured, but the 'auth' is enabled (auth is on localhost)?
	if len(cfg.AuthServers) == 0 && cfg.Auth.Enabled {
		cfg.AuthServers = append(cfg.AuthServers, cfg.Auth.SSHAddr)
	}

	// add data_dir to the backend config:
	if cfg.Auth.StorageConfig.Params == nil {
		cfg.Auth.StorageConfig.Params = backend.Params{}
	}
	cfg.Auth.StorageConfig.Params["data_dir"] = cfg.DataDir
	// command line flag takes precedence over file config
	if clf.PermitUserEnvironment {
		cfg.SSH.PermitUserEnvironment = true
	}

	return nil
}
777728
func (prod *Redis) Configure(conf core.PluginConfigReader) {
	prod.SetStopCallback(prod.close)

	prod.protocol, prod.address = tnet.ParseAddress(conf.GetString("Address", ":6379"), "tcp")

	switch strings.ToLower(conf.GetString("Storage", "hash")) {
	case "hash":
		prod.store = prod.storeHash
	case "list":
		prod.store = prod.storeList
	case "set":
		prod.store = prod.storeSet
	case "sortedset":
		prod.store = prod.storeSortedSet
	default: // string
		prod.store = prod.storeString
	}
}
1049887
func (format *Base64Decode) Configure(conf core.PluginConfigReader) {
	dict := conf.GetString("Dictionary", "")
	if dict == "" {
		format.dictionary = base64.StdEncoding
	} else {
		if len(dict) != 64 {
			conf.Errors.Pushf("Base64 dictionary must contain 64 characters.")
		}
		format.dictionary = base64.NewEncoding(dict)
	}
}
235341
func (prod *Spooling) Configure(conf core.PluginConfigReader) {
	prod.SetPrepareStopCallback(prod.waitForReader)
	prod.SetStopCallback(prod.close)
	prod.SetRollCallback(prod.onRoll)
	prod.metricsRegistry = core.NewMetricsRegistryForPlugin(prod)

	prod.outfileGuard = new(sync.RWMutex)
	prod.outfile = make(map[core.MessageStreamID]*spoolFile)

	if maxMsgSec := time.Duration(conf.GetInt("MaxMessagesSec", 100)); maxMsgSec > 0 {
		prod.readDelay = time.Second / maxMsgSec
	} else {
		prod.readDelay = 0
	}

	//TODO: check if rotation is still in use
	prod.rotation = components.NewRotateConfig()
	prod.rotation.Enabled = true
	prod.rotation.Timeout = prod.maxFileAge
	prod.rotation.SizeByte = prod.maxFileSize
}