// CreateTelegrafConfig creates a new telegraf config and sets b.ID with the new identifier.
193728
func (c *Client) CreateTelegrafConfig(ctx context.Context, tc *platform.TelegrafConfig, userID platform.ID) error {
	op := OpPrefix + platform.OpCreateTelegrafConfig
	return c.db.Update(func(tx *bolt.Tx) error {
		tc.ID = c.IDGenerator.ID()

		pErr := c.putTelegrafConfig(ctx, tx, tc)
		if pErr != nil {
			pErr.Op = op
			return pErr
		}

		urm := &platform.UserResourceMapping{
			ResourceID:   tc.ID,
			UserID:       userID,
			UserType:     platform.Owner,
			ResourceType: platform.TelegrafsResourceType,
		}
		if err := c.createUserResourceMapping(ctx, tx, urm); err != nil {
			return err
		}

		return nil
	})
}
1025482
func (c *configFactory) CreateFromConfig(policy schedulerapi.Policy) (*Config, error) {
	klog.V(2).Infof("Creating scheduler from configuration: %v", policy)

	// validate the policy configuration
	if err := validation.ValidatePolicy(policy); err != nil {
		return nil, err
	}

	predicateKeys := sets.NewString()
	if policy.Predicates == nil {
		klog.V(2).Infof("Using predicates from algorithm provider '%v'", DefaultProvider)
		provider, err := GetAlgorithmProvider(DefaultProvider)
		if err != nil {
			return nil, err
		}
		predicateKeys = provider.FitPredicateKeys
	} else {
		for _, predicate := range policy.Predicates {
			klog.V(2).Infof("Registering predicate: %s", predicate.Name)
			predicateKeys.Insert(RegisterCustomFitPredicate(predicate))
		}
	}

	priorityKeys := sets.NewString()
	if policy.Priorities == nil {
		klog.V(2).Infof("Using priorities from algorithm provider '%v'", DefaultProvider)
		provider, err := GetAlgorithmProvider(DefaultProvider)
		if err != nil {
			return nil, err
		}
		priorityKeys = provider.PriorityFunctionKeys
	} else {
		for _, priority := range policy.Priorities {
			klog.V(2).Infof("Registering priority: %s", priority.Name)
			priorityKeys.Insert(RegisterCustomPriorityFunction(priority))
		}
	}

	var extenders []algorithm.SchedulerExtender
	if len(policy.ExtenderConfigs) != 0 {
		ignoredExtendedResources := sets.NewString()
		for ii := range policy.ExtenderConfigs {
			klog.V(2).Infof("Creating extender with config %+v", policy.ExtenderConfigs[ii])
			extender, err := core.NewHTTPExtender(&policy.ExtenderConfigs[ii])
			if err != nil {
				return nil, err
			}
			extenders = append(extenders, extender)
			for _, r := range policy.ExtenderConfigs[ii].ManagedResources {
				if r.IgnoredByScheduler {
					ignoredExtendedResources.Insert(string(r.Name))
				}
			}
		}
		predicates.RegisterPredicateMetadataProducerWithExtendedResourceOptions(ignoredExtendedResources)
	}
	// Providing HardPodAffinitySymmetricWeight in the policy config is the new and preferred way of providing the value.
	// Give it higher precedence than scheduler CLI configuration when it is provided.
	if policy.HardPodAffinitySymmetricWeight != 0 {
		c.hardPodAffinitySymmetricWeight = policy.HardPodAffinitySymmetricWeight
	}
	// When AlwaysCheckAllPredicates is set to true, scheduler checks all the configured
	// predicates even after one or more of them fails.
	if policy.AlwaysCheckAllPredicates {
		c.alwaysCheckAllPredicates = policy.AlwaysCheckAllPredicates
	}

	return c.CreateFromKeys(predicateKeys, priorityKeys, extenders)
}
1242954
func (rootCA RootCA) CreateSecurityConfig(ctx context.Context, krw *KeyReadWriter, config CertificateRequestConfig) (*SecurityConfig, func() error, error) {
	ctx = log.WithModule(ctx, "tls")

	// Create a new random ID for this certificate
	cn := identity.NewID()
	org := config.Organization
	if config.Organization == "" {
		org = identity.NewID()
	}

	proposedRole := ManagerRole
	tlsKeyPair, issuerInfo, err := rootCA.IssueAndSaveNewCertificates(krw, cn, proposedRole, org)
	switch errors.Cause(err) {
	case ErrNoValidSigner:
		config.RetryInterval = GetCertRetryInterval
		// Request certificate issuance from a remote CA.
		// Last argument is nil because at this point we don't have any valid TLS creds
		tlsKeyPair, issuerInfo, err = rootCA.RequestAndSaveNewCertificates(ctx, krw, config)
		if err != nil {
			log.G(ctx).WithError(err).Error("failed to request and save new certificate")
			return nil, nil, err
		}
	case nil:
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   cn,
			"node.role": proposedRole,
		}).Debug("issued new TLS certificate")
	default:
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   cn,
			"node.role": proposedRole,
		}).WithError(err).Errorf("failed to issue and save new certificate")
		return nil, nil, err
	}

	secConfig, cleanup, err := NewSecurityConfig(&rootCA, krw, tlsKeyPair, issuerInfo)
	if err == nil {
		log.G(ctx).WithFields(logrus.Fields{
			"node.id":   secConfig.ClientTLSCreds.NodeID(),
			"node.role": secConfig.ClientTLSCreds.Role(),
		}).Debugf("new node credentials generated: %s", krw.Target())
	}
	return secConfig, cleanup, err
}
287199
func (f *InfraProvider) CreatePeerFromConfig(peerCfg *fab.NetworkPeer) (fab.Peer, error) {
	return peerImpl.New(f.providerContext.EndpointConfig(), peerImpl.FromPeerConfig(peerCfg))
}
669659
func (i *TeleInstance) GenerateConfig(trustedSecrets []*InstanceSecrets, tconf *service.Config) (*service.Config, error) {
	var err error
	dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	if tconf == nil {
		tconf = service.MakeDefaultConfig()
	}
	tconf.DataDir = dataDir
	tconf.UploadEventsC = i.UploadEventsC
	tconf.CachePolicy.Enabled = true
	tconf.Auth.ClusterName, err = services.NewClusterName(services.ClusterNameSpecV2{
		ClusterName: i.Secrets.SiteName,
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	tconf.Auth.StaticTokens, err = services.NewStaticTokens(services.StaticTokensSpecV2{
		StaticTokens: []services.ProvisionTokenV1{
			{
				Roles: []teleport.Role{teleport.RoleNode, teleport.RoleProxy, teleport.RoleTrustedCluster},
				Token: "token",
			},
		},
	})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	tconf.Auth.Authorities = append(tconf.Auth.Authorities, i.Secrets.GetCAs()...)
	tconf.Identities = append(tconf.Identities, i.Secrets.GetIdentity())
	for _, trusted := range trustedSecrets {
		tconf.Auth.Authorities = append(tconf.Auth.Authorities, trusted.GetCAs()...)
		tconf.Auth.Roles = append(tconf.Auth.Roles, trusted.GetRoles()...)
		tconf.Identities = append(tconf.Identities, trusted.GetIdentity())
		if trusted.ListenAddr != "" {
			tconf.ReverseTunnels = []services.ReverseTunnel{
				services.NewReverseTunnel(trusted.SiteName, []string{trusted.ListenAddr}),
			}
		}
	}
	tconf.Proxy.ReverseTunnelListenAddr.Addr = i.Secrets.ListenAddr
	tconf.HostUUID = i.Secrets.GetIdentity().ID.HostUUID
	tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, i.GetPortSSH())
	tconf.SSH.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}
	tconf.Auth.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortAuth())
	tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortProxy())
	tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortWeb())
	tconf.Proxy.PublicAddrs = []utils.NetAddr{
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        i.Hostname,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Loopback,
		},
		utils.NetAddr{
			AddrNetwork: "tcp",
			Addr:        Host,
		},
	}
	tconf.AuthServers = append(tconf.AuthServers, tconf.Auth.SSHAddr)
	tconf.Auth.StorageConfig = backend.Config{
		Type:   lite.GetName(),
		Params: backend.Params{"path": dataDir + string(os.PathListSeparator) + defaults.BackendDir, "poll_stream_period": 50 * time.Millisecond},
	}

	tconf.Keygen = testauthority.New()
	i.Config = tconf
	return tconf, nil
}
890627
func (c *Config) Config() *Config {
	// Guard against nil pointer dereference
	if c == nil {
		return NewConfig()
	}

	// Return a clone of the config so that this is immutable for the receiver
	c2 := *c
	return &c2
}
1121592
func (s *TelegrafConfigService) FindTelegrafConfigByID(ctx context.Context, id influxdb.ID) (*influxdb.TelegrafConfig, error) {
	tc, err := s.s.FindTelegrafConfigByID(ctx, id)
	if err != nil {
		return nil, err
	}

	if err := authorizeReadTelegraf(ctx, tc.OrganizationID, id); err != nil {
		return nil, err
	}

	return tc, nil
}
220824
func (c KbfsClient) CreateTLF(ctx context.Context, __arg CreateTLFArg) (err error) {
	err = c.Cli.Call(ctx, "keybase.1.kbfs.createTLF", []interface{}{__arg}, nil)
	return
}
996884
func (s *TelegrafConfigStore) FindTelegrafConfigByID(ctx context.Context, id platform.ID) (*platform.TelegrafConfig, error) {
	return s.FindTelegrafConfigByIDF(ctx, id)
}
721436
func (c *Certificates) CreateTLSConfig(entryPointName string) (*tls.Config, error) {
	config := &tls.Config{}
	domainsCertificates := make(map[string]map[string]*tls.Certificate)

	if c.isEmpty() {
		config.Certificates = []tls.Certificate{}

		cert, err := generate.DefaultCertificate()
		if err != nil {
			return nil, err
		}

		config.Certificates = append(config.Certificates, *cert)
	} else {
		for _, certificate := range *c {
			err := certificate.AppendCertificate(domainsCertificates, entryPointName)
			if err != nil {
				log.Errorf("Unable to add a certificate to the entryPoint %q : %v", entryPointName, err)
				continue
			}

			for _, certDom := range domainsCertificates {
				for _, cert := range certDom {
					config.Certificates = append(config.Certificates, *cert)
				}
			}
		}
	}
	return config, nil
}
1151162
func DialTLSConfig(c *tls.Config) DialOption {
	return DialOption{func(do *dialOptions) {
		do.tlsConfig = c
	}}
}
435267
func (s *Service) FindTelegrafConfig(ctx context.Context, filter platform.TelegrafConfigFilter) (*platform.TelegrafConfig, error) {
	op := OpPrefix + platform.OpFindTelegrafConfig
	tcs, n, err := s.FindTelegrafConfigs(ctx, filter, platform.FindOptions{Limit: 1})
	if err != nil {
		return nil, err
	}
	if n > 0 {
		return tcs[0], nil
	}
	return nil, &platform.Error{
		Code: platform.ENotFound,
		Op:   op,
	}
}
656448
func CreateKubeClientFromConfig(conf *KubeConfig) (*kubernetes.Clientset, error) {
	rcConf := new(rest.Config)
	if len(conf.Clusters) < 1 {
		return nil, errNoClustersInConfig
	}
	cluster := conf.Clusters[0].Cluster
	if len(conf.AuthInfos) < 1 {
		return nil, errNoAuthInfosInConfig
	}
	authInfo := conf.AuthInfos[0].AuthInfo

	rcConf.Host = cluster.Server
	rcConf.Username = authInfo.Username
	rcConf.Password = authInfo.Password
	rcConf.TLSClientConfig.CertData = []byte(authInfo.ClientCertificateData)
	rcConf.TLSClientConfig.KeyData = []byte(authInfo.ClientKeyData)
	rcConf.TLSClientConfig.CAData = []byte(cluster.CertificateAuthorityData)
	rcConf.BearerToken = authInfo.Token
	rcConf.UserAgent = "k8s-claimer"
	rcConf.Insecure = cluster.InsecureSkipTLSVerify

	return kubernetes.NewForConfig(rcConf)
}
55275
func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("digitalocean: the configuration of the DNS provider is nil")
	}

	if config.AuthToken == "" {
		return nil, fmt.Errorf("digitalocean: credentials missing")
	}

	if config.BaseURL == "" {
		config.BaseURL = defaultBaseURL
	}

	return &DNSProvider{
		config:    config,
		recordIDs: make(map[string]int),
	}, nil
}
250560
func (f *ProviderFactory) CreateInfraProvider(config fab.EndpointConfig) (fab.InfraProvider, error) {
	return fabpvdr.New(config), nil
}
941336
func (s *Service) DeleteTelegrafConfig(ctx context.Context, id platform.ID) error {
	op := OpPrefix + platform.OpDeleteTelegrafConfig
	var err error
	if !id.Valid() {
		return &platform.Error{
			Op:   op,
			Code: platform.EEmptyValue,
			Err:  platform.ErrInvalidID,
		}
	}
	if _, pErr := s.findTelegrafConfigByID(ctx, id); pErr != nil {
		return pErr
	}
	s.telegrafConfigKV.Delete(id)

	err = s.deleteUserResourceMapping(ctx, platform.UserResourceMappingFilter{
		ResourceID: id,
		Resource:   platform.TelegrafsResource,
	})

	if err != nil {
		return &platform.Error{
			Code: platform.ErrorCode(err),
			Op:   op,
			Err:  err,
		}
	}
	return nil
}
1110336
func (s *Server) CreateFromKubeConfig(ctx context.Context, q *ClusterCreateFromKubeConfigRequest) (*appv1.Cluster, error) {
	kubeconfig, err := clientcmd.Load([]byte(q.Kubeconfig))
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Could not unmarshal kubeconfig: %v", err)
	}

	var clusterServer string
	var clusterInsecure bool
	if q.InCluster {
		clusterServer = common.KubernetesInternalAPIServerAddr
	} else if cluster, ok := kubeconfig.Clusters[q.Context]; ok {
		clusterServer = cluster.Server
		clusterInsecure = cluster.InsecureSkipTLSVerify
	} else {
		return nil, status.Errorf(codes.Internal, "Context %s does not exist in kubeconfig", q.Context)
	}

	c := &appv1.Cluster{
		Server: clusterServer,
		Name:   q.Context,
		Config: appv1.ClusterConfig{
			TLSClientConfig: appv1.TLSClientConfig{
				Insecure: clusterInsecure,
			},
		},
	}

	// Temporarily install RBAC resources for managing the cluster
	clientset, err := kubernetes.NewForConfig(c.RESTConfig())
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Could not create Kubernetes clientset: %v", err)
	}

	bearerToken, err := common.InstallClusterManagerRBAC(clientset)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Could not install cluster manager RBAC: %v", err)
	}

	c.Config.BearerToken = bearerToken

	return s.Create(ctx, &ClusterCreateRequest{
		Cluster: c,
		Upsert:  q.Upsert,
	})
}