// newEtcd3Backend constructs a etcd3 backend.
556765
func newEtcd3Backend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
	// Get the etcd path form the configuration.
	path, ok := conf["path"]
	if !ok {
		path = "/vault"
	}

	// Ensure path is prefixed.
	if !strings.HasPrefix(path, "/") {
		path = "/" + path
	}

	endpoints, err := getEtcdEndpoints(conf)
	if err != nil {
		return nil, err
	}

	cfg := clientv3.Config{
		Endpoints: endpoints,
	}

	haEnabled := os.Getenv("ETCD_HA_ENABLED")
	if haEnabled == "" {
		haEnabled = conf["ha_enabled"]
	}
	if haEnabled == "" {
		haEnabled = "false"
	}
	haEnabledBool, err := strconv.ParseBool(haEnabled)
	if err != nil {
		return nil, fmt.Errorf("value [%v] of 'ha_enabled' could not be understood", haEnabled)
	}

	cert, hasCert := conf["tls_cert_file"]
	key, hasKey := conf["tls_key_file"]
	ca, hasCa := conf["tls_ca_file"]
	if (hasCert && hasKey) || hasCa {
		tls := transport.TLSInfo{
			TrustedCAFile: ca,
			CertFile:      cert,
			KeyFile:       key,
		}

		tlscfg, err := tls.ClientConfig()
		if err != nil {
			return nil, err
		}
		cfg.TLS = tlscfg
	}

	// Set credentials.
	username := os.Getenv("ETCD_USERNAME")
	if username == "" {
		username, _ = conf["username"]
	}

	password := os.Getenv("ETCD_PASSWORD")
	if password == "" {
		password, _ = conf["password"]
	}

	if username != "" && password != "" {
		cfg.Username = username
		cfg.Password = password
	}

	if maxReceive, ok := conf["max_receive_size"]; ok {
		// grpc converts this to uint32 internally, so parse as that to avoid passing invalid values
		val, err := strconv.ParseUint(maxReceive, 10, 32)
		if err != nil {
			return nil, errwrap.Wrapf(fmt.Sprintf("value of 'max_receive_size' (%v) could not be understood: {{err}}", maxReceive), err)
		}
		cfg.MaxCallRecvMsgSize = int(val)
	}

	etcd, err := clientv3.New(cfg)
	if err != nil {
		return nil, err
	}

	sReqTimeout := conf["request_timeout"]
	if sReqTimeout == "" {
		// etcd3 default request timeout is set to 5s. It should be long enough
		// for most cases, even with internal retry.
		sReqTimeout = "5s"
	}
	reqTimeout, err := parseutil.ParseDurationSecond(sReqTimeout)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("value [%v] of 'request_timeout' could not be understood: {{err}}", sReqTimeout), err)
	}

	ssync, ok := conf["sync"]
	if !ok {
		ssync = "true"
	}
	sync, err := strconv.ParseBool(ssync)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("value of 'sync' (%v) could not be understood: {{err}}", ssync), err)
	}

	if sync {
		ctx, cancel := context.WithTimeout(context.Background(), reqTimeout)
		err := etcd.Sync(ctx)
		cancel()
		if err != nil {
			return nil, err
		}
	}

	sLock := conf["lock_timeout"]
	if sLock == "" {
		// etcd3 default lease duration is 60s. set to 15s for faster recovery.
		sLock = "15s"
	}
	lock, err := parseutil.ParseDurationSecond(sLock)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("value [%v] of 'lock_timeout' could not be understood: {{err}}", sLock), err)
	}

	return &EtcdBackend{
		path:           path,
		etcd:           etcd,
		permitPool:     physical.NewPermitPool(physical.DefaultParallelOperations),
		logger:         logger,
		haEnabled:      haEnabledBool,
		lockTimeout:    lock,
		requestTimeout: reqTimeout,
	}, nil
}
573281
func NewMQTT2To3Backend(conf config.Config) (*MQTT2To3Backend, error) {
	c := conf.NetworkServer.Gateway.Backend.MQTT

	b := MQTT2To3Backend{}

	opts := mqtt.NewClientOptions()
	opts.AddBroker(c.Server)
	opts.SetUsername(c.Username)
	opts.SetPassword(c.Password)
	opts.SetCleanSession(c.CleanSession)
	opts.SetClientID(c.ClientID)
	opts.SetOnConnectHandler(b.onConnected)

	tlsconfig, err := newTLSConfig(c.CACert, c.TLSCert, c.TLSKey)
	if err != nil {
		log.WithError(err).WithFields(log.Fields{
			"ca_cert":  c.CACert,
			"tls_cert": c.TLSCert,
			"tls_key":  c.TLSKey,
		}).Fatal("mqtt2to3: error loading mqtt certificate files")
	}
	if tlsconfig != nil {
		opts.SetTLSConfig(tlsconfig)
	}

	log.WithField("broker", c.Server).Info("mqtt2to3: connecting to mqtt broker")
	b.conn = mqtt.NewClient(opts)

	for {
		if token := b.conn.Connect(); token.Wait() && token.Error() != nil {
			log.WithError(err).Error("mqtt2to3: connecting to mqtt broker failed")
			time.Sleep(2 * time.Second)
		} else {
			break
		}
	}

	return &b, nil
}
273925
func NewBackend(path string) *Backend {
	name := filepath.Ext(path)
	if name != "" {
		name = name[1:]
	}

	return &Backend{
		path: path,
		name: name,
	}
}
1084786
func NewDeviceBackend(st *State) (*deviceBackend, error) {
	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &deviceBackend{
		mb:          st,
		settings:    NewStateSettings(st),
		modelType:   m.Type(),
		config:      m.ModelConfig,
		application: st.Application,
		unit:        st.Unit,
		machine:     st.Machine,
	}, nil
}
1315065
func NewBackend(delegate audit.Backend, p policy.Checker) audit.Backend {
	return &Backend{
		policyChecker:   p,
		delegateBackend: delegate,
	}
}
250371
func NewBackend(components ImageComponent, builder Builder, fsCache *fscache.FSCache, buildkit *buildkit.Builder) (*Backend, error) {
	return &Backend{imageComponent: components, builder: builder, fsCache: fsCache, buildkit: buildkit}, nil
}
1279846
func (dc *Config) Backend(base backend.B) backend.B {
	return &caching.Backend{
		B:           base,
		FailOnError: !dc.FailOpen,
		CacheGet:    dc.cacheGet,
	}
}
1051699
func (a *ResolveNodeArgs) SetBackendNodeID(backendNodeID BackendNodeID) *ResolveNodeArgs {
	a.BackendNodeID = &backendNodeID
	return a
}
296684
func (m *monitoring) setBackend(mb Backend) {
	if m.b != nil {
		m.b.Stop()
	}
	m.b = mb
}
1303148
func Backend(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
	var b PluginBackend

	name := conf.Config["plugin_name"]
	pluginType, err := consts.ParsePluginType(conf.Config["plugin_type"])
	if err != nil {
		return nil, err
	}

	sys := conf.System

	// NewBackend with isMetadataMode set to true
	raw, err := bplugin.NewBackend(ctx, name, pluginType, sys, conf, true)
	if err != nil {
		return nil, err
	}
	err = raw.Setup(ctx, conf)
	if err != nil {
		return nil, err
	}
	// Get SpecialPaths and BackendType
	paths := raw.SpecialPaths()
	btype := raw.Type()

	// Cleanup meta plugin backend
	raw.Cleanup(ctx)

	// Initialize b.Backend with dummy backend since plugin
	// backends will need to be lazy loaded.
	b.Backend = &framework.Backend{
		PathsSpecial: paths,
		BackendType:  btype,
	}

	b.config = conf

	return &b, nil
}
458652
func (ctx *Context) createBackend(vsID, rsID string, opts *BackendOptions) error {
	if err := opts.Validate(); err != nil {
		return err
	}
	p, err := pulse.New(opts.host.String(), opts.Port, opts.Pulse)
	if err != nil {
		return err
	}

	if _, exists := ctx.backends[rsID]; exists {
		return ErrObjectExists
	}

	vs, exists := ctx.services[vsID]

	if !exists {
		return ErrObjectNotFound
	}

	if util.AddrFamily(opts.host) != util.AddrFamily(vs.options.host) {
		return ErrIncompatibleAFs
	}

	log.Infof("creating backend [%s] on %s:%d for virtual service [%s]",
		rsID,
		opts.host,
		opts.Port,
		vsID)

	// create backend to external store
	if ctx.store != nil {
		if err := ctx.store.CreateBackend(vsID, rsID, opts); err != nil {
			log.Errorf("error while create backend : %s", err)
			return err
		}
	}

	if err := ctx.ipvs.AddDestPort(
		vs.options.host.String(),
		vs.options.Port,
		opts.host.String(),
		opts.Port,
		vs.options.protocol,
		int32(opts.Weight),
		opts.methodID,
	); err != nil {
		log.Errorf("error while creating backend: %s", err)
		return ErrIpvsSyscallFailed
	}

	ctx.backends[rsID] = &backend{options: opts, service: vs, monitor: p}

	// Fire off the configured pulse goroutine, attach it to the Context.
	go ctx.backends[rsID].monitor.Loop(pulse.ID{VsID: vsID, RsID: rsID}, ctx.pulseCh, ctx.stopCh)

	return nil
}
784121
func SetBackend(mb Backend) {
	monitor.Lock()
	defer monitor.Unlock()
	monitor.setBackend(mb)
}
595673
func MakeEtcdClientV3(etcdClientInfo configapi.EtcdConnectionInfo) (*clientv3.Client, error) {
	cfg, err := MakeEtcdClientV3Config(etcdClientInfo)
	if err != nil {
		return nil, err
	}
	return clientv3.New(*cfg)
}
1065300
func NewEtcdConnectionWithBytes(config ClientConfig, log logging.Logger) (*BytesConnectionEtcd, error) {
	t := time.Now()

	l := log.WithField("endpoints", config.Endpoints)
	l.Debugf("Connecting to Etcd..")

	etcdClient, err := clientv3.New(*config.Config)
	if err != nil {
		l.Warnf("Failed to connect to Etcd: %v", err)
		return nil, err
	}

	l.Infof("Connected to Etcd (took %v)", time.Since(t))

	conn, err := NewEtcdConnectionUsingClient(etcdClient, log)
	if err != nil {
		return nil, err
	}
	conn.opTimeout = config.OpTimeout

	return conn, nil
}
960749
func (a *SetFileInputFilesArgs) SetBackendNodeID(backendNodeID BackendNodeID) *SetFileInputFilesArgs {
	a.BackendNodeID = &backendNodeID
	return a
}
206861
func (s *Server) getEtcd(key string) string {
	if s.logLevel == "debug" {
		log.Println("get", key)
	}
	resp, err := s.EtcdClient.Get(key, false, false)
	if err != nil {
		return ""
	}
	if resp != nil && resp.Node != nil {
		return resp.Node.Value
	}
	return ""
}
1143551
func NewBackend(c *Config) (audit.Backend, error) {
	eventBroadcaster := record.NewBroadcaster()
	eventBroadcaster.StartLogging(klog.Infof)
	eventBroadcaster.StartRecordingToSink(c.EventConfig.Sink)

	scheme := runtime.NewScheme()
	err := auditregv1alpha1.AddToScheme(scheme)
	if err != nil {
		return nil, err
	}
	recorder := eventBroadcaster.NewRecorder(scheme, c.EventConfig.Source)

	if c.BufferedConfig == nil {
		c.BufferedConfig = NewDefaultWebhookBatchConfig()
	}
	cm, err := webhook.NewClientManager(auditv1.SchemeGroupVersion, func(s *runtime.Scheme) error {
		auditinstall.Install(s)
		return nil
	})
	if err != nil {
		return nil, err
	}

	// TODO: need a way of injecting authentication before beta
	authInfoResolver, err := webhook.NewDefaultAuthenticationInfoResolver("")
	if err != nil {
		return nil, err
	}
	cm.SetAuthenticationInfoResolver(authInfoResolver)
	cm.SetServiceResolver(c.WebhookConfig.ServiceResolver)
	cm.SetAuthenticationInfoResolverWrapper(c.WebhookConfig.AuthInfoResolverWrapper)

	manager := &backend{
		config:               c,
		delegates:            atomic.Value{},
		delegateUpdateMutex:  sync.Mutex{},
		webhookClientManager: cm,
		recorder:             recorder,
	}
	manager.delegates.Store(syncedDelegates{})

	c.Informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			manager.addSink(obj.(*auditregv1alpha1.AuditSink))
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			manager.updateSink(oldObj.(*auditregv1alpha1.AuditSink), newObj.(*auditregv1alpha1.AuditSink))
		},
		DeleteFunc: func(obj interface{}) {
			sink, ok := obj.(*auditregv1alpha1.AuditSink)
			if !ok {
				tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
				if !ok {
					klog.V(2).Infof("Couldn't get object from tombstone %#v", obj)
					return
				}
				sink, ok = tombstone.Obj.(*auditregv1alpha1.AuditSink)
				if !ok {
					klog.V(2).Infof("Tombstone contained object that is not an AuditSink: %#v", obj)
					return
				}
			}
			manager.deleteSink(sink)
		},
	})

	return manager, nil
}