// Configure sets up the provider using the given configuration.
8514
func (c *ConsulProvider) Configure(clusterID string, isRoot bool, rawConfig map[string]interface{}) error {
	// Parse the raw config and update our ID.
	config, err := ParseConsulCAConfig(rawConfig)
	if err != nil {
		return err
	}
	c.config = config
	hash := sha256.Sum256([]byte(fmt.Sprintf("%s,%s,%v", config.PrivateKey, config.RootCert, isRoot)))
	c.id = strings.Replace(fmt.Sprintf("% x", hash), " ", ":", -1)
	c.clusterID = clusterID
	c.isRoot = isRoot
	c.spiffeID = connect.SpiffeIDSigningForCluster(&structs.CAConfiguration{ClusterID: clusterID})

	// Exit early if the state store has an entry for this provider's config.
	_, providerState, err := c.Delegate.State().CAProviderState(c.id)
	if err != nil {
		return err
	}

	if providerState != nil {
		return nil
	}

	// Check if there's an entry with the old ID scheme.
	oldID := fmt.Sprintf("%s,%s", config.PrivateKey, config.RootCert)
	_, providerState, err = c.Delegate.State().CAProviderState(oldID)
	if err != nil {
		return err
	}

	// Found an entry with the old ID, so update it to the new ID and
	// delete the old entry.
	if providerState != nil {
		newState := *providerState
		newState.ID = c.id
		createReq := &structs.CARequest{
			Op:            structs.CAOpSetProviderState,
			ProviderState: &newState,
		}
		if err := c.Delegate.ApplyCARequest(createReq); err != nil {
			return err
		}

		deleteReq := &structs.CARequest{
			Op:            structs.CAOpDeleteProviderState,
			ProviderState: providerState,
		}
		if err := c.Delegate.ApplyCARequest(deleteReq); err != nil {
			return err
		}

		return nil
	}

	// Write the provider state to the state store.
	newState := structs.CAConsulProviderState{
		ID: c.id,
	}

	args := &structs.CARequest{
		Op:            structs.CAOpSetProviderState,
		ProviderState: &newState,
	}
	if err := c.Delegate.ApplyCARequest(args); err != nil {
		return err
	}

	return nil
}
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
}
241480
func (cons *Console) Configure(conf core.PluginConfigReader) {
	switch strings.ToLower(cons.pipeName) {
	case "stdin":
		cons.pipe = os.Stdin
		cons.pipeName = "stdin"
	default:
		cons.pipe = nil
	}
}
244859
func (prod *HTTPRequest) Configure(conf core.PluginConfigReader) {
	var err error
	prod.SetStopCallback(prod.close)

	address := conf.GetString("Address", "http://localhost:80")

	if !strings.Contains(address, "://") {
		address = "http://" + address
	}
	prod.destinationURL, err = url.Parse(address)
	conf.Errors.Push(err)

	// Default health check to ping the backend with an HTTP GET
	prod.AddHealthCheck(prod.healthcheckPingBackend)

	// Additional health check to check the last result
	// TBD: This may be meaningless in a high-traffic environment; a statistics
	// based check could make more sense.
	prod.AddHealthCheckAt("/lastError", func() (int, string) {
		if prod.lastError == nil {
			return thealthcheck.StatusOK, "OK"
		}
		return thealthcheck.StatusServiceUnavailable, fmt.Sprintf("ERROR: %s", prod.lastError)
	})
}
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
}
965564
func (prod *KafkaProducer) Configure(conf core.PluginConfigReader) error {
	prod.SetStopCallback(prod.close)

	prod.streamToTopic = conf.GetStreamMap("Topic", "default")
	prod.topic = make(map[core.MessageStreamID]*topicHandle)

	prod.topicGuard = new(sync.RWMutex)
	prod.streamToTopic = conf.GetStreamMap("Topic", "default")

	prod.topicHandles = make(map[string]*topicHandle)

	// Init librdkafka
	prod.config = kafka.NewConfig()

	/*kafkaVer := conf.GetString("ProtocolVersion", "0.8.2")
	verParts := strings.Split(kafkaVer, ".")
	multiplicator := 1000000
	verNumber := 0
	for _, n := range verParts {
		part, _ := strconv.Atoi(n)
		verNumber += part * multiplicator
		multiplicator /= 100
	}*/

	prod.config.Set("metadata.broker.list", strings.Join(prod.servers, ","))
	prod.config.Set("sasl.mechanisms", conf.GetString("SaslMechanism", ""))
	prod.config.Set("sasl.password", conf.GetString("SaslPassword", ""))
	prod.config.Set("sasl.username", conf.GetString("SaslUsername", ""))
	prod.config.Set("ssl.ca.location", conf.GetString("SslCaLocation", ""))
	prod.config.Set("ssl.certificate.location", conf.GetString("SslCertificateLocation", ""))
	prod.config.Set("ssl.cipher.suites", conf.GetString("SslCipherSuites", ""))
	prod.config.Set("ssl.crl.location", conf.GetString("SslCrlLocation", ""))
	prod.config.Set("ssl.key.location", conf.GetString("SslKeyLocation", ""))
	prod.config.Set("ssl.key.password", conf.GetString("SslKeyPassword", ""))
	prod.config.SetI("message.max.bytes", int(conf.GetInt("Batch/SizeMaxKB", 1<<10))<<10)
	prod.config.SetI("metadata.request.timeout.ms", int(conf.GetInt("MetadataTimeoutMs", 1500)))
	prod.config.SetI("topic.metadata.refresh.interval.ms", int(conf.GetInt("MetadataRefreshMs", 300000)))
	prod.config.SetI("socket.max.fails", int(conf.GetInt("ServerMaxFails", 3)))
	prod.config.SetI("socket.timeout.ms", int(conf.GetInt("ServerTimeoutSec", 60)*1000))
	prod.config.SetB("socket.keepalive.enable", true)
	prod.config.SetI("message.send.max.retries", int(conf.GetInt("SendRetries", 0)))
	prod.config.SetI("queue.buffering.max.messages", int(conf.GetInt("Batch/MaxMessages", 100000)))
	prod.config.SetI("queue.buffering.max.ms", int(conf.GetInt("Batch/TimeoutMs", 1000)))
	prod.config.SetI("batch.num.messages", int(conf.GetInt("Batch/MinMessages", 1000)))
	//prod.config.SetI("protocol.version", verNumber)

	securityProtocol := strings.ToLower(conf.GetString("SecurityProtocol", protocolPlaintext))
	switch securityProtocol {
	default:
		return fmt.Errorf("%s is not a valid security protocol", securityProtocol)
	case protocolPlaintext:
		prod.config.Set("security.protocol", protocolPlaintext)
	case protocolSsl:
		prod.config.Set("security.protocol", protocolSsl)
	case protocolSaslPlaintext:
		prod.config.Set("security.protocol", protocolSaslPlaintext)
	case protocolSaslSsl:
		prod.config.Set("security.protocol", protocolSaslSsl)
	}

	switch strings.ToLower(conf.GetString("Compression", compressNone)) {
	default:
		prod.config.Set("compression.codec", "none")
	case compressGZIP:
		prod.config.Set("compression.codec", "gzip")
	case compressSnappy:
		prod.config.Set("compression.codec", "snappy")
	}

	tgo.Metric.New(kafkaMetricAllocations)
	return nil
}
1374316
func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error) {
	if flag.cert != "" {
		cert, err := tls.LoadX509KeyPair(flag.cert, flag.key)
		if err != nil {
			return nil, err
		}

		sc.SetCertificate(cert)
	}

	// Set namespace and version
	sc.Namespace = "urn:" + flag.vimNamespace
	sc.Version = flag.vimVersion

	sc.UserAgent = fmt.Sprintf("govc/%s", Version)

	if err := flag.SetRootCAs(sc); err != nil {
		return nil, err
	}

	if err := sc.LoadThumbprints(flag.tlsKnownHosts); err != nil {
		return nil, err
	}

	if t, ok := sc.Transport.(*http.Transport); ok {
		var err error

		value := os.Getenv("GOVC_TLS_HANDSHAKE_TIMEOUT")
		if value != "" {
			t.TLSHandshakeTimeout, err = time.ParseDuration(value)
			if err != nil {
				return nil, err
			}
		}
	}

	// Retry twice when a temporary I/O error occurs.
	// This means a maximum of 3 attempts.
	return vim25.Retry(sc, vim25.TemporaryNetworkError(3)), nil
}
308086
func (cons *File) Configure(conf core.PluginConfigReader) {
	cons.done = make(chan struct{})
	cons.observedFiles = new(sync.Map)

	// TODO: support manual roll again
	//cons.SetRollCallback(cons.onRoll)
	cons.SetStopCallback(func() {
		close(cons.done)
	})

	// restore default observer mode for invalid config settings
	if cons.observeMode != observeModePoll && cons.observeMode != observeModeWatch {
		cons.Logger.Warningf("Unknown observe mode '%s'. Using poll", cons.observeMode)
		cons.observeMode = observeModePoll
	}

	cons.configureBlacklist(conf)
}
766293
func (format *RegExp) Configure(conf core.PluginConfigReader) {
	var err error
	if conf.GetBool("Posix", true) {
		format.expression, err = regexp.CompilePOSIX(conf.GetString("Expression", "(.*)"))
	} else {
		format.expression, err = regexp.Compile(conf.GetString("Expression", "(.*)"))
	}
	conf.Errors.Push(err)
}
823611
func (prod *ElasticSearch) Configure(conf core.PluginConfigReader) {
	prod.connection.servers = conf.GetStringArray("Servers", []string{"http://127.0.0.1:9200"})
	prod.connection.user = conf.GetString("User", "")
	prod.connection.password = conf.GetString("Password", "")
	prod.connection.setGzip = conf.GetBool("SetGzip", false)
	prod.connection.isConnectedStatus = false

	prod.configureIndexSettings(conf.GetMap("StreamProperties", tcontainer.NewMarshalMap()), conf.Errors)
	prod.configureRetrySettings(conf.GetInt("Retry/Count", 3), conf.GetInt("Retry/TimeToWaitSec", 3))
}
1273916
func (prod *Proxy) Configure(conf core.PluginConfigReader) {
	prod.SetStopCallback(prod.close)

	prod.protocol, prod.address = tnet.ParseAddress(conf.GetString("Address", ":5880"), "tcp")
	if prod.protocol == "udp" {
		conf.Errors.Pushf("Proxy does not support UDP")
	}

	delimiter := tstrings.Unescape(conf.GetString("Delimiter", "\n"))
	offset := int(conf.GetInt("Offset", 0))
	flags := tio.BufferedReaderFlagEverything // pass all messages as-is

	partitioner := strings.ToLower(conf.GetString("Partitioner", "delimiter"))
	switch partitioner {
	case "binary_be":
		flags |= tio.BufferedReaderFlagBigEndian
		fallthrough

	case "binary", "binary_le":
		switch conf.GetInt("Size", 4) {
		case 1:
			flags |= tio.BufferedReaderFlagMLE8
		case 2:
			flags |= tio.BufferedReaderFlagMLE16
		case 4:
			flags |= tio.BufferedReaderFlagMLE32
		case 8:
			flags |= tio.BufferedReaderFlagMLE64
		default:
			conf.Errors.Pushf("Size only supports the value 1,2,4 and 8")
		}

	case "fixed":
		flags |= tio.BufferedReaderFlagMLEFixed
		offset = int(conf.GetInt("Size", 1))

	case "ascii":
		flags |= tio.BufferedReaderFlagMLE

	case "delimiter":
		// Nothing to add

	default:
		conf.Errors.Pushf("Unknown partitioner: %s", partitioner)
	}

	prod.reader = tio.NewBufferedReader(prod.bufferSizeKB, flags, offset, delimiter)
}
338136
func Configure(b *bootstrap.Bootstrapper) {
	h := New(b)
	b.UseGlobal(h)
}
646032
func (b *Remote) Configure(obj cty.Value) tfdiags.Diagnostics {
	var diags tfdiags.Diagnostics

	// Get the hostname.
	if val := obj.GetAttr("hostname"); !val.IsNull() && val.AsString() != "" {
		b.hostname = val.AsString()
	} else {
		b.hostname = defaultHostname
	}

	// Get the organization.
	if val := obj.GetAttr("organization"); !val.IsNull() {
		b.organization = val.AsString()
	}

	// Get the workspaces configuration block and retrieve the
	// default workspace name and prefix.
	if workspaces := obj.GetAttr("workspaces"); !workspaces.IsNull() {
		if val := workspaces.GetAttr("name"); !val.IsNull() {
			b.workspace = val.AsString()
		}
		if val := workspaces.GetAttr("prefix"); !val.IsNull() {
			b.prefix = val.AsString()
		}
	}

	// Determine if we are forced to use the local backend.
	b.forceLocal = os.Getenv("TF_FORCE_LOCAL_BACKEND") != ""

	serviceID := tfeServiceID
	if b.forceLocal {
		serviceID = stateServiceID
	}

	// Discover the service URL for this host to confirm that it provides
	// a remote backend API and to get the version constraints.
	service, constraints, err := b.discover(serviceID)

	// First check any contraints we might have received.
	if constraints != nil {
		diags = diags.Append(b.checkConstraints(constraints))
		if diags.HasErrors() {
			return diags
		}
	}

	// When we don't have any constraints errors, also check for discovery
	// errors before we continue.
	if err != nil {
		diags = diags.Append(tfdiags.AttributeValue(
			tfdiags.Error,
			strings.ToUpper(err.Error()[:1])+err.Error()[1:],
			"", // no description is needed here, the error is clear
			cty.Path{cty.GetAttrStep{Name: "hostname"}},
		))
		return diags
	}

	// Retrieve the token for this host as configured in the credentials
	// section of the CLI Config File.
	token, err := b.token()
	if err != nil {
		diags = diags.Append(tfdiags.AttributeValue(
			tfdiags.Error,
			strings.ToUpper(err.Error()[:1])+err.Error()[1:],
			"", // no description is needed here, the error is clear
			cty.Path{cty.GetAttrStep{Name: "hostname"}},
		))
		return diags
	}

	// Get the token from the config if no token was configured for this
	// host in credentials section of the CLI Config File.
	if token == "" {
		if val := obj.GetAttr("token"); !val.IsNull() {
			token = val.AsString()
		}
	}

	// Return an error if we still don't have a token at this point.
	if token == "" {
		diags = diags.Append(tfdiags.Sourceless(
			tfdiags.Error,
			"Required token could not be found",
			fmt.Sprintf(
				"Make sure you configured a credentials block for %s in your CLI Config File.",
				b.hostname,
			),
		))
		return diags
	}

	cfg := &tfe.Config{
		Address:      service.String(),
		BasePath:     service.Path,
		Token:        token,
		Headers:      make(http.Header),
		RetryLogHook: b.retryLogHook,
	}

	// Set the version header to the current version.
	cfg.Headers.Set(tfversion.Header, tfversion.Version)

	// Create the remote backend API client.
	b.client, err = tfe.NewClient(cfg)
	if err != nil {
		diags = diags.Append(tfdiags.Sourceless(
			tfdiags.Error,
			"Failed to create the Terraform Enterprise client",
			fmt.Sprintf(
				`The "remote" backend encountered an unexpected error while creating the `+
					`Terraform Enterprise client: %s.`, err,
			),
		))
		return diags
	}

	// Check if the organization exists by reading its entitlements.
	entitlements, err := b.client.Organizations.Entitlements(context.Background(), b.organization)
	if err != nil {
		if err == tfe.ErrResourceNotFound {
			err = fmt.Errorf("organization %s does not exist", b.organization)
		}
		diags = diags.Append(tfdiags.AttributeValue(
			tfdiags.Error,
			"Failed to read organization entitlements",
			fmt.Sprintf(
				`The "remote" backend encountered an unexpected error while reading the `+
					`organization settings: %s.`, err,
			),
			cty.Path{cty.GetAttrStep{Name: "organization"}},
		))
		return diags
	}

	// Configure a local backend for when we need to run operations locally.
	b.local = backendLocal.NewWithBackend(b)
	b.forceLocal = b.forceLocal || !entitlements.Operations

	// Enable retries for server errors as the backend is now fully configured.
	b.client.RetryServerErrors(true)

	return diags
}
1127596
func Configure(b *bootstrap.Bootstrapper) {
	b.Get("/", GetIndexHandler)
	b.Get("/follower/{id:long}", GetFollowerHandler)
	b.Get("/following/{id:long}", GetFollowingHandler)
	b.Get("/like/{id:long}", GetLikeHandler)
}
660374
func (prod *SimpleProducer) Configure(conf PluginConfigReader) {
	prod.id = conf.GetID()
	prod.Logger = conf.GetLogger()
	prod.runState = NewPluginRunState()
	prod.control = make(chan PluginControl, 1)

	// Simple health check for the plugin state
	//   Path: "/<plugin_id>/pluginState"
	prod.AddHealthCheckAt("/pluginState", func() (code int, body string) {
		if prod.IsActive() {
			return thealthcheck.StatusOK,
				fmt.Sprintf("ACTIVE: %s", prod.runState.GetStateString())
		}
		return thealthcheck.StatusServiceUnavailable,
			fmt.Sprintf("NOT_ACTIVE: %s", prod.runState.GetStateString())
	})
}
351904
func (prod *Websocket) Configure(conf core.PluginConfigReader) {
	prod.SetStopCallback(prod.close)

	prod.upgrader = websocket.Upgrader{}

	if prod.ignoreOrigin {
		prod.upgrader.CheckOrigin = func(r *http.Request) bool { return prod.ignoreOrigin }
	}
}
1321822
func (cons *SystemdConsumer) Configure(conf core.PluginConfigReader) error {
	var err error
	cons.journal, err = sdjournal.NewJournal()
	if err != nil {
		return err
	}

	if sdUnit := conf.GetString("SystemdUnit", ""); sdUnit != "" {
		err = cons.journal.AddMatch("_SYSTEMD_UNIT=" + sdUnit)
		if err != nil {
			return err
		}
	}

	// Offset
	offsetValue := strings.ToLower(conf.GetString("DefaultOffset", sdOffsetTail))

	if cons.offsetFile != "" {
		fileContents, err := ioutil.ReadFile(cons.offsetFile)
		if err != nil {
			cons.Logger.WithError(err).Error("Error reading offset file")
		}
		if string(fileContents) != "" {
			offsetValue = string(fileContents)
		}
	}

	switch offsetValue {
	case sdOffsetHead:
		if err = cons.journal.SeekHead(); err != nil {
			return err
		}

	case sdOffsetTail:
		if err = cons.journal.SeekTail(); err != nil {
			return err
		}
		// start *after* the newest record
		if _, err = cons.journal.Next(); err != nil {
			return err
		}

	default:
		offset, err := strconv.ParseUint(offsetValue, 10, 64)
		if err != nil {
			return err
		}
		if err = cons.journal.SeekRealtimeUsec(offset); err != nil {
			return err
		}
		// start *after* the specified time
		if _, err = cons.journal.Next(); err != nil {
			return err
		}
	}

	// Register close to the control message handler
	cons.SetStopCallback(cons.close)
	return conf.Errors.OrNil()
}