// NewSwiftBackend constructs a Swift backend using a pre-existing
// container. Credentials can be provided to the backend, sourced
// from the environment.
5468
func NewSwiftBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
	var ok bool

	username := os.Getenv("OS_USERNAME")
	if username == "" {
		username = conf["username"]
		if username == "" {
			return nil, fmt.Errorf("missing username")
		}
	}
	password := os.Getenv("OS_PASSWORD")
	if password == "" {
		password = conf["password"]
		if password == "" {
			return nil, fmt.Errorf("missing password")
		}
	}
	authUrl := os.Getenv("OS_AUTH_URL")
	if authUrl == "" {
		authUrl = conf["auth_url"]
		if authUrl == "" {
			return nil, fmt.Errorf("missing auth_url")
		}
	}
	container := os.Getenv("OS_CONTAINER")
	if container == "" {
		container = conf["container"]
		if container == "" {
			return nil, fmt.Errorf("missing container")
		}
	}
	project := os.Getenv("OS_PROJECT_NAME")
	if project == "" {
		if project, ok = conf["project"]; !ok {
			// Check for KeyStone naming prior to V3
			project = os.Getenv("OS_TENANT_NAME")
			if project == "" {
				project = conf["tenant"]
			}
		}
	}

	domain := os.Getenv("OS_USER_DOMAIN_NAME")
	if domain == "" {
		domain = conf["domain"]
	}
	projectDomain := os.Getenv("OS_PROJECT_DOMAIN_NAME")
	if projectDomain == "" {
		projectDomain = conf["project-domain"]
	}

	region := os.Getenv("OS_REGION_NAME")
	if region == "" {
		region = conf["region"]
	}
	tenantID := os.Getenv("OS_TENANT_ID")
	if tenantID == "" {
		tenantID = conf["tenant_id"]
	}
	trustID := os.Getenv("OS_TRUST_ID")
	if trustID == "" {
		trustID = conf["trust_id"]
	}
	storageUrl := os.Getenv("OS_STORAGE_URL")
	if storageUrl == "" {
		storageUrl = conf["storage_url"]
	}
	authToken := os.Getenv("OS_AUTH_TOKEN")
	if authToken == "" {
		authToken = conf["auth_token"]
	}

	c := swift.Connection{
		Domain:       domain,
		UserName:     username,
		ApiKey:       password,
		AuthUrl:      authUrl,
		Tenant:       project,
		TenantDomain: projectDomain,
		Region:       region,
		TenantId:     tenantID,
		TrustId:      trustID,
		StorageUrl:   storageUrl,
		AuthToken:    authToken,
		Transport:    cleanhttp.DefaultPooledTransport(),
	}

	err := c.Authenticate()
	if err != nil {
		return nil, err
	}

	_, _, err = c.Container(container)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("Unable to access container %q: {{err}}", container), err)
	}

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("max_parallel set", "max_parallel", maxParInt)
		}
	}

	s := &SwiftBackend{
		client:     &c,
		container:  container,
		logger:     logger,
		permitPool: physical.NewPermitPool(maxParInt),
	}
	return s, nil
}
575607
func (o *AuditWebhookOptions) newUntruncatedBackend() (audit.Backend, error) {
	groupVersion, _ := schema.ParseGroupVersion(o.GroupVersionString)
	webhook, err := pluginwebhook.NewBackend(o.ConfigFile, groupVersion, o.InitialBackoff)
	if err != nil {
		return nil, fmt.Errorf("initializing audit webhook: %v", err)
	}
	webhook = o.BatchOptions.wrapBackend(webhook)
	return webhook, nil
}
354577
func ConfigFromBackend(coreBackend ...core.ConfigBackend) (fab.EndpointConfig, error) {

	config := &EndpointConfig{
		backend: lookup.New(coreBackend...),
	}

	if err := config.loadEndpointConfiguration(); err != nil {
		return nil, errors.WithMessage(err, "network configuration load failed")
	}

	//print deprecated warning
	detectDeprecatedNetworkConfig(config)

	return config, nil
}
1363973
func NewBackends(httpClient *http.Client) *Backends {
	apiConfig := &BackendConfig{HTTPClient: httpClient}
	uploadConfig := &BackendConfig{HTTPClient: httpClient}
	return &Backends{
		API:     GetBackendWithConfig(APIBackend, apiConfig),
		Uploads: GetBackendWithConfig(UploadsBackend, uploadConfig),
	}
}
804978
func GetBackendWithConfig(backendType SupportedBackend, config *BackendConfig) Backend {
	if config.HTTPClient == nil {
		config.HTTPClient = httpClient
	}

	if config.LeveledLogger == nil {
		if config.Logger == nil {
			config.Logger = Logger
		}

		config.LeveledLogger = &leveledLoggerPrintferShim{
			level:  printferLevel(config.LogLevel),
			logger: config.Logger,
		}
	}

	switch backendType {
	case APIBackend:
		if config.URL == "" {
			config.URL = apiURL
		}

		config.URL = normalizeURL(config.URL)

		return newBackendImplementation(backendType, config)

	case UploadsBackend:
		if config.URL == "" {
			config.URL = uploadsURL
		}

		config.URL = normalizeURL(config.URL)

		return newBackendImplementation(backendType, config)
	}

	return nil
}
932141
func NewSetupBackend(b *APIBackend) *SetupBackend {
	return &SetupBackend{
		Logger:            b.Logger.With(zap.String("handler", "setup")),
		OnboardingService: b.OnboardingService,
	}
}
548614
func SetBackend(backend SupportedBackend, b Backend) {
	switch backend {
	case APIBackend:
		backends.API = b
	case UploadsBackend:
		backends.Uploads = b
	}
}
670487
func PassthroughBackendFactory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
	return LeaseSwitchedPassthroughBackend(ctx, conf, false)
}
167499
func NewBackend(kubeConfigFile string, groupVersion schema.GroupVersion, initialBackoff time.Duration) (audit.Backend, error) {
	w, err := loadWebhook(kubeConfigFile, groupVersion, initialBackoff)
	if err != nil {
		return nil, err
	}
	return &backend{w: w, name: PluginName}, nil
}
1094341
func (builder *StoreBucketPropsCommandBuilder) WithBackend(backend string) *StoreBucketPropsCommandBuilder {
	builder.props.Backend = []byte(backend)
	return builder
}
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
}
949583
func NewAzureBackend(conf map[string]string, logger log.Logger) (physical.Backend, error) {
	name := os.Getenv("AZURE_BLOB_CONTAINER")
	if name == "" {
		name = conf["container"]
		if name == "" {
			return nil, fmt.Errorf("'container' must be set")
		}
	}

	accountName := os.Getenv("AZURE_ACCOUNT_NAME")
	if accountName == "" {
		accountName = conf["accountName"]
		if accountName == "" {
			return nil, fmt.Errorf("'accountName' must be set")
		}
	}

	accountKey := os.Getenv("AZURE_ACCOUNT_KEY")
	if accountKey == "" {
		accountKey = conf["accountKey"]
		if accountKey == "" {
			return nil, fmt.Errorf("'accountKey' must be set")
		}
	}

	environmentName := os.Getenv("AZURE_ENVIRONMENT")
	if environmentName == "" {
		environmentName = conf["environment"]
		if environmentName == "" {
			environmentName = "AzurePublicCloud"
		}
	}
	environment, err := azure.EnvironmentFromName(environmentName)
	if err != nil {
		errorMsg := fmt.Sprintf("failed to look up Azure environment descriptor for name %q: {{err}}",
			environmentName)
		return nil, errwrap.Wrapf(errorMsg, err)
	}

	client, err := storage.NewBasicClientOnSovereignCloud(accountName, accountKey, environment)
	if err != nil {
		return nil, errwrap.Wrapf("failed to create Azure client: {{err}}", err)
	}
	client.HTTPClient = cleanhttp.DefaultPooledClient()

	blobClient := client.GetBlobService()
	container := blobClient.GetContainerReference(name)
	_, err = container.CreateIfNotExists(&storage.CreateContainerOptions{
		Access: storage.ContainerAccessTypePrivate,
	})
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("failed to create %q container: {{err}}", name), err)
	}

	maxParStr, ok := conf["max_parallel"]
	var maxParInt int
	if ok {
		maxParInt, err = strconv.Atoi(maxParStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed parsing max_parallel parameter: {{err}}", err)
		}
		if logger.IsDebug() {
			logger.Debug("max_parallel set", "max_parallel", maxParInt)
		}
	}

	a := &AzureBackend{
		container:  container,
		logger:     logger,
		permitPool: physical.NewPermitPool(maxParInt),
	}
	return a, nil
}
672023
func (builder *StoreBucketTypePropsCommandBuilder) WithBackend(backend string) *StoreBucketTypePropsCommandBuilder {
	builder.props.Backend = []byte(backend)
	return builder
}
475182
func NewBackend(client *clientv3.Client, opts ...Option) *Backend {
	b := Backend{
		client: client,
	}

	for _, opt := range opts {
		opt(&b)
	}

	return &b
}
241754
func (n *network) addLBBackend(ip net.IP, lb *loadBalancer) {
	if len(lb.vip) == 0 {
		return
	}
	ep, sb, err := n.findLBEndpointSandbox()
	if err != nil {
		logrus.Errorf("addLBBackend %s/%s: %v", n.ID(), n.Name(), err)
		return
	}
	if sb.osSbox == nil {
		return
	}

	eIP := ep.Iface().Address()

	i, err := ipvs.New(sb.Key())
	if err != nil {
		logrus.Errorf("Failed to create an ipvs handle for sbox %.7s (%.7s,%s) for lb addition: %v", sb.ID(), sb.ContainerID(), sb.Key(), err)
		return
	}
	defer i.Close()

	s := &ipvs.Service{
		AddressFamily: nl.FAMILY_V4,
		FWMark:        lb.fwMark,
		SchedName:     ipvs.RoundRobin,
	}

	if !i.IsServicePresent(s) {
		// Add IP alias for the VIP to the endpoint
		ifName := findIfaceDstName(sb, ep)
		if ifName == "" {
			logrus.Errorf("Failed find interface name for endpoint %s(%s) to create LB alias", ep.ID(), ep.Name())
			return
		}
		err := sb.osSbox.AddAliasIP(ifName, &net.IPNet{IP: lb.vip, Mask: net.CIDRMask(32, 32)})
		if err != nil {
			logrus.Errorf("Failed add IP alias %s to network %s LB endpoint interface %s: %v", lb.vip, n.ID(), ifName, err)
			return
		}

		if sb.ingress {
			var gwIP net.IP
			if ep := sb.getGatewayEndpoint(); ep != nil {
				gwIP = ep.Iface().Address().IP
			}
			if err := programIngress(gwIP, lb.service.ingressPorts, false); err != nil {
				logrus.Errorf("Failed to add ingress: %v", err)
				return
			}
		}

		logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v in sbox %.7s (%.7s)", lb.vip, lb.fwMark, lb.service.ingressPorts, sb.ID(), sb.ContainerID())
		if err := invokeFWMarker(sb.Key(), lb.vip, lb.fwMark, lb.service.ingressPorts, eIP, false, n.loadBalancerMode); err != nil {
			logrus.Errorf("Failed to add firewall mark rule in sbox %.7s (%.7s): %v", sb.ID(), sb.ContainerID(), err)
			return
		}

		if err := i.NewService(s); err != nil && err != syscall.EEXIST {
			logrus.Errorf("Failed to create a new service for vip %s fwmark %d in sbox %.7s (%.7s): %v", lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
			return
		}
	}

	d := &ipvs.Destination{
		AddressFamily: nl.FAMILY_V4,
		Address:       ip,
		Weight:        1,
	}
	if n.loadBalancerMode == loadBalancerModeDSR {
		d.ConnectionFlags = ipvs.ConnFwdDirectRoute
	}

	// Remove the sched name before using the service to add
	// destination.
	s.SchedName = ""
	if err := i.NewDestination(s, d); err != nil && err != syscall.EEXIST {
		logrus.Errorf("Failed to create real server %s for vip %s fwmark %d in sbox %.7s (%.7s): %v", ip, lb.vip, lb.fwMark, sb.ID(), sb.ContainerID(), err)
	}
}
1299947
func NewStorageBackend(st *State) (*storageBackend, error) {
	// TODO(wallyworld) - we should be passing in a Model not a State
	// (but need to move stuff off State first)
	m, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	registry, err := st.storageProviderRegistry()
	if err != nil {
		return nil, errors.Annotate(err, "getting storage provider registry")
	}

	return &storageBackend{
		mb:              st,
		registry:        registry,
		settings:        NewStateSettings(st),
		modelType:       m.Type(),
		config:          m.ModelConfig,
		application:     st.Application,
		allApplications: st.AllApplications,
		unit:            st.Unit,
		machine:         st.Machine,
	}, nil
}
642080
func (m *monitoring) backend() Backend {
	if m.b == nil {
		m.b = NewStandardBackend()
	}
	return m.b
}