// NewWithAsyncFactoryNonce creates a new default client with a given asynchronous transport factory and nonce generator.
774615
func NewWithAsyncFactoryNonce(async AsynchronousFactory, nonce utils.NonceGenerator) *Client {
	return NewWithParamsAsyncFactoryNonce(NewDefaultParameters(), async, nonce)
}
676399
func NewInformerFactory(typedInformerFactory informers.SharedInformerFactory, dynamicInformerFactory dynamicinformer.DynamicSharedInformerFactory) InformerFactory {
	return &informerFactory{
		typedInformerFactory:   typedInformerFactory,
		dynamicInformerFactory: dynamicInformerFactory,
	}
}
601990
func NewFactory(config ...FactoryConfig) *Factory {
	conf := defaultFactoryConfig()
	if len(config) == 1 {
		conf = config[0]
	}

	return &Factory{
		registry: make(map[string]registryEntry, conf.RegistryCapacity),
	}
}
299149
func (env *sessionEnviron) newRawInstance(
	ctx context.ProviderCallContext,
	args environs.StartInstanceParams,
	img *OvaFileMetadata,
) (_ *mo.VirtualMachine, _ *instance.HardwareCharacteristics, err error) {

	vmName, err := env.namespace.Hostname(args.InstanceConfig.MachineId)
	if err != nil {
		return nil, nil, common.ZoneIndependentError(err)
	}

	series := args.Tools.OneSeries()
	cloudcfg, err := cloudinit.New(series)
	if err != nil {
		return nil, nil, common.ZoneIndependentError(err)
	}
	cloudcfg.AddPackage("open-vm-tools")
	cloudcfg.AddPackage("iptables-persistent")

	// Make sure the hostname is resolvable by adding it to /etc/hosts.
	cloudcfg.ManageEtcHosts(true)

	internalMac, err := vsphereclient.GenerateMAC()
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	interfaces := []network.InterfaceInfo{{
		InterfaceName: "eth0",
		MACAddress:    internalMac,
		InterfaceType: network.EthernetInterface,
		ConfigType:    network.ConfigDHCP,
	}}
	networkDevices := []vsphereclient.NetworkDevice{{MAC: internalMac, Network: env.ecfg.primaryNetwork()}}

	// TODO(wpk) We need to add a firewall -AND- make sure that if it's a controller we
	// have API port open.
	externalNetwork := env.ecfg.externalNetwork()
	if externalNetwork != "" {
		externalMac, err := vsphereclient.GenerateMAC()
		if err != nil {
			return nil, nil, errors.Trace(err)
		}
		interfaces = append(interfaces, network.InterfaceInfo{
			InterfaceName: "eth1",
			MACAddress:    externalMac,
			InterfaceType: network.EthernetInterface,
			ConfigType:    network.ConfigDHCP,
		})
		networkDevices = append(networkDevices, vsphereclient.NetworkDevice{MAC: externalMac, Network: externalNetwork})
	}
	// TODO(wpk) There's no (known) way to tell cloud-init to disable network (using cloudinit.CloudInitNetworkConfigDisabled)
	// so the network might be double-configured. That should be ok as long as we're using DHCP.
	err = cloudcfg.AddNetworkConfig(interfaces)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}
	userData, err := providerinit.ComposeUserData(args.InstanceConfig, cloudcfg, VsphereRenderer{})
	if err != nil {
		return nil, nil, common.ZoneIndependentError(
			errors.Annotate(err, "cannot make user data"),
		)
	}
	logger.Debugf("Vmware user data; %d bytes", len(userData))

	// Obtain the final constraints by merging with defaults.
	cons := args.Constraints
	minRootDisk := common.MinRootDiskSizeGiB(args.InstanceConfig.Series) * 1024
	if cons.RootDisk == nil || *cons.RootDisk < minRootDisk {
		cons.RootDisk = &minRootDisk
	}
	defaultDatastore := env.ecfg.datastore()
	if cons.RootDiskSource == nil || *cons.RootDiskSource == "" {
		cons.RootDiskSource = &defaultDatastore
	}

	// Download and extract the OVA file. If we're bootstrapping we use
	// a temporary directory, otherwise we cache the image for future use.
	updateProgressInterval := startInstanceUpdateProgressInterval
	if args.InstanceConfig.Bootstrap != nil {
		updateProgressInterval = bootstrapUpdateProgressInterval
	}
	updateProgress := func(message string) {
		args.StatusCallback(status.Provisioning, message, nil)
	}

	readOVA := func() (string, io.ReadCloser, error) {
		resp, err := http.Get(img.URL)
		if err != nil {
			return "", nil, errors.Trace(err)
		}
		return img.URL, resp.Body, nil
	}

	createVMArgs := vsphereclient.CreateVirtualMachineParams{
		Name: vmName,
		Folder: path.Join(
			controllerFolderName(args.ControllerUUID),
			env.modelFolderName(),
		),
		Series:                 series,
		ReadOVA:                readOVA,
		OVASHA256:              img.Sha256,
		VMDKDirectory:          vmdkDirectoryName(args.ControllerUUID),
		UserData:               string(userData),
		Metadata:               args.InstanceConfig.Tags,
		Constraints:            cons,
		NetworkDevices:         networkDevices,
		UpdateProgress:         updateProgress,
		UpdateProgressInterval: updateProgressInterval,
		Clock:                  clock.WallClock,
		EnableDiskUUID:         env.ecfg.enableDiskUUID(),
	}

	// Attempt to create a VM in each of the AZs in turn.
	logger.Debugf("attempting to create VM in availability zone %s", args.AvailabilityZone)
	availZone, err := env.availZone(ctx, args.AvailabilityZone)
	if err != nil {
		return nil, nil, errors.Trace(err)
	}

	createVMArgs.ComputeResource = &availZone.r
	createVMArgs.ResourcePool = availZone.pool.Reference()

	vm, err := env.client.CreateVirtualMachine(env.ctx, createVMArgs)
	if vsphereclient.IsExtendDiskError(err) {
		// Ensure we don't try to make the same extension across
		// different resource groups.
		err = common.ZoneIndependentError(err)
	}
	if err != nil {
		HandleCredentialError(err, ctx)
		return nil, nil, errors.Trace(err)
	}

	hw := &instance.HardwareCharacteristics{
		Arch:           &img.Arch,
		Mem:            cons.Mem,
		CpuCores:       cons.CpuCores,
		CpuPower:       cons.CpuPower,
		RootDisk:       cons.RootDisk,
		RootDiskSource: cons.RootDiskSource,
	}
	return vm, hw, err
}
181998
func NewClientWithConfig(config Configuration) *Client {
	var hosts []*transport.StatefulHost

	if config.Hosts == nil {
		hosts = defaultHosts(config.Region)
	} else {
		for _, h := range config.Hosts {
			hosts = append(hosts, transport.NewStatefulHost(h, call.IsReadWrite))
		}
	}

	searchConfig := search.Configuration{
		AppID:          config.AppID,
		APIKey:         config.APIKey,
		Requester:      config.Requester,
		ReadTimeout:    config.ReadTimeout,
		WriteTimeout:   config.WriteTimeout,
		Headers:        config.Headers,
		ExtraUserAgent: config.ExtraUserAgent,
	}

	return &Client{
		appID:        config.AppID,
		searchClient: search.NewClientWithConfig(searchConfig),
		transport: transport.New(
			hosts,
			config.Requester,
			config.AppID,
			config.APIKey,
			config.ReadTimeout,
			config.WriteTimeout,
			config.Headers,
			config.ExtraUserAgent,
		),
	}
}
124056
func NewFactory(optionalClientConfig clientcmd.ClientConfig) *Factory {
	mapper := kubectl.ShortcutExpander{RESTMapper: api.RESTMapper}

	flags := pflag.NewFlagSet("", pflag.ContinueOnError)
	flags.SetNormalizeFunc(util.WarnWordSepNormalizeFunc) // Warn for "_" flags

	generators := map[string]kubectl.Generator{
		"run/v1":                          kubectl.BasicReplicationController{},
		"run-pod/v1":                      kubectl.BasicPod{},
		"service/v1":                      kubectl.ServiceGeneratorV1{},
		"service/v2":                      kubectl.ServiceGeneratorV2{},
		"horizontalpodautoscaler/v1beta1": kubectl.HorizontalPodAutoscalerV1Beta1{},
		"deployment/v1beta1":              kubectl.DeploymentV1Beta1{},
		"job/v1beta1":                     kubectl.JobV1Beta1{},
	}

	clientConfig := optionalClientConfig
	if optionalClientConfig == nil {
		clientConfig = DefaultClientConfig(flags)
	}

	clients := NewClientCache(clientConfig)

	return &Factory{
		clients:    clients,
		flags:      flags,
		generators: generators,

		Object: func() (meta.RESTMapper, runtime.ObjectTyper) {
			cfg, err := clientConfig.ClientConfig()
			CheckErr(err)
			cmdApiVersion := ""
			if cfg.GroupVersion != nil {
				cmdApiVersion = cfg.GroupVersion.String()
			}

			return kubectl.OutputVersionMapper{RESTMapper: mapper, OutputVersion: cmdApiVersion}, api.Scheme
		},
		Client: func() (*client.Client, error) {
			return clients.ClientForVersion("")
		},
		ClientConfig: func() (*client.Config, error) {
			return clients.ClientConfigForVersion("")
		},
		RESTClient: func(mapping *meta.RESTMapping) (resource.RESTClient, error) {
			gvk, err := api.RESTMapper.KindFor(mapping.Resource)
			if err != nil {
				return nil, err
			}
			client, err := clients.ClientForVersion(mapping.GroupVersionKind.GroupVersion().String())
			if err != nil {
				return nil, err
			}
			switch gvk.Group {
			case "":
				return client.RESTClient, nil
			case "extensions":
				return client.ExtensionsClient.RESTClient, nil
			}
			return nil, fmt.Errorf("unable to get RESTClient for resource '%s'", mapping.Resource)
		},
		Describer: func(mapping *meta.RESTMapping) (kubectl.Describer, error) {
			client, err := clients.ClientForVersion(mapping.GroupVersionKind.GroupVersion().String())
			if err != nil {
				return nil, err
			}
			if describer, ok := kubectl.DescriberFor(mapping.GroupVersionKind.GroupKind(), client); ok {
				return describer, nil
			}
			return nil, fmt.Errorf("no description has been implemented for %q", mapping.Kind)
		},
		Printer: func(mapping *meta.RESTMapping, noHeaders, withNamespace bool, wide bool, showAll bool, columnLabels []string) (kubectl.ResourcePrinter, error) {
			return kubectl.NewHumanReadablePrinter(noHeaders, withNamespace, wide, showAll, columnLabels), nil
		},
		PodSelectorForObject: func(object runtime.Object) (string, error) {
			// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
			switch t := object.(type) {
			case *api.ReplicationController:
				return kubectl.MakeLabels(t.Spec.Selector), nil
			case *api.Pod:
				if len(t.Labels) == 0 {
					return "", fmt.Errorf("the pod has no labels and cannot be exposed")
				}
				return kubectl.MakeLabels(t.Labels), nil
			case *api.Service:
				if t.Spec.Selector == nil {
					return "", fmt.Errorf("the service has no pod selector set")
				}
				return kubectl.MakeLabels(t.Spec.Selector), nil
			default:
				_, kind, err := api.Scheme.ObjectVersionAndKind(object)
				if err != nil {
					return "", err
				}
				return "", fmt.Errorf("cannot extract pod selector from %s", kind)
			}
		},
		PortsForObject: func(object runtime.Object) ([]string, error) {
			// TODO: replace with a swagger schema based approach (identify pod selector via schema introspection)
			switch t := object.(type) {
			case *api.ReplicationController:
				return getPorts(t.Spec.Template.Spec), nil
			case *api.Pod:
				return getPorts(t.Spec), nil
			case *api.Service:
				return getServicePorts(t.Spec), nil
			default:
				_, kind, err := api.Scheme.ObjectVersionAndKind(object)
				if err != nil {
					return nil, err
				}
				return nil, fmt.Errorf("cannot extract ports from %s", kind)
			}
		},
		LabelsForObject: func(object runtime.Object) (map[string]string, error) {
			return meta.NewAccessor().Labels(object)
		},
		LogsForObject: func(object, options runtime.Object) (*client.Request, error) {
			c, err := clients.ClientForVersion("")
			if err != nil {
				return nil, err
			}

			switch t := object.(type) {
			case *api.Pod:
				opts, ok := options.(*api.PodLogOptions)
				if !ok {
					return nil, errors.New("provided options object is not a PodLogOptions")
				}
				return c.Pods(t.Namespace).GetLogs(t.Name, opts), nil
			default:
				_, kind, err := api.Scheme.ObjectVersionAndKind(object)
				if err != nil {
					return nil, err
				}
				return nil, fmt.Errorf("cannot get the logs from %s", kind)
			}
		},
		Scaler: func(mapping *meta.RESTMapping) (kubectl.Scaler, error) {
			client, err := clients.ClientForVersion(mapping.GroupVersionKind.GroupVersion().String())
			if err != nil {
				return nil, err
			}
			return kubectl.ScalerFor(mapping.GroupVersionKind.GroupKind(), client)
		},
		Reaper: func(mapping *meta.RESTMapping) (kubectl.Reaper, error) {
			client, err := clients.ClientForVersion(mapping.GroupVersionKind.GroupVersion().String())
			if err != nil {
				return nil, err
			}
			return kubectl.ReaperFor(mapping.GroupVersionKind.GroupKind(), client)
		},
		Validator: func(validate bool, cacheDir string) (validation.Schema, error) {
			if validate {
				client, err := clients.ClientForVersion("")
				if err != nil {
					return nil, err
				}
				dir := cacheDir
				if len(dir) > 0 {
					version, err := client.ServerVersion()
					if err != nil {
						return nil, err
					}
					dir = path.Join(cacheDir, version.String())
				}
				return &clientSwaggerSchema{
					c:        client,
					cacheDir: dir,
					mapper:   api.RESTMapper,
				}, nil
			}
			return validation.NullSchema{}, nil
		},
		DefaultNamespace: func() (string, bool, error) {
			return clientConfig.Namespace()
		},
		Generator: func(name string) (kubectl.Generator, bool) {
			generator, ok := generators[name]
			return generator, ok
		},
		CanBeExposed: func(kind string) error {
			switch kind {
			case "ReplicationController", "Service", "Pod":
				// nothing to do here
			default:
				return fmt.Errorf("cannot expose a %s", kind)
			}
			return nil
		},
		CanBeAutoscaled: func(kind string) error {
			switch kind {
			case "ReplicationController", "Deployment":
				// nothing to do here
			default:
				return fmt.Errorf("cannot autoscale a %s", kind)
			}
			return nil
		},
		AttachablePodForObject: func(object runtime.Object) (*api.Pod, error) {
			client, err := clients.ClientForVersion("")
			if err != nil {
				return nil, err
			}
			switch t := object.(type) {
			case *api.ReplicationController:
				return GetFirstPod(client, t.Namespace, t.Spec.Selector)
			case *extensions.Deployment:
				return GetFirstPod(client, t.Namespace, t.Spec.Selector)
			case *extensions.Job:
				return GetFirstPod(client, t.Namespace, t.Spec.Selector.MatchLabels)
			case *api.Pod:
				return t, nil
			default:
				_, kind, err := api.Scheme.ObjectVersionAndKind(object)
				if err != nil {
					return nil, err
				}
				return nil, fmt.Errorf("cannot attach to %s: not implemented", kind)
			}
		},
		EditorEnvs: func() []string {
			return []string{"KUBE_EDITOR", "EDITOR"}
		},
	}
}
1256372
func NewWithCredentials(endpoint string, creds *credentials.Credentials, secure bool, region string) (*Client, error) {
	return privateNew(endpoint, creds, secure, region, BucketLookupAuto)
}
1037401
func newDefaultHTTPClientFactory() Factory {
	return FactoryFunc(func(next Policy, po *PolicyOptions) PolicyFunc {
		return func(ctx context.Context, request Request) (Response, error) {
			r, err := pipelineHTTPClient.Do(request.WithContext(ctx))
			if err != nil {
				err = NewError(err, "HTTP request failed")
			}
			return NewHTTPResponse(r), err
		}
	})
}
259345
func (s *Server) generateNonce(n []byte) {
	var raw [nonceRawLen]byte
	data := raw[:]
	s.prand.Read(data)
	base64.RawURLEncoding.Encode(n, data)
}
1031258
func NewAsynchClientWithSpec(spec *ConnectionSpec) (client AsyncClient, err Error) {
	c := new(asyncClient)
	c.conn, err = NewAsynchConnection(spec)
	if err != nil {
		if debug() {
			log.Println("NewAsyncConnection() raised error: ", err)
		}
		return nil, err
	}
	return c, nil
}
1201928
func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils.NonceGenerator) *Client {
	c := &Client{
		Synchronous: sync,
		nonce:       nonce,
	}
	c.Orders = OrderService{Synchronous: c, requestFactory: c}
	c.Book = BookService{Synchronous: c}
	c.Candles = CandleService{Synchronous: c}
	c.Trades = TradeService{Synchronous: c, requestFactory: c}
	c.Tickers = TickerService{Synchronous: c, requestFactory: c}
	c.Platform = PlatformService{Synchronous: c}
	c.Positions = PositionService{Synchronous: c, requestFactory: c}
	c.Wallet = WalletService{Synchronous: c, requestFactory: c}
	c.Ledgers = LedgerService{Synchronous: c, requestFactory: c}
	return c
}
1117641
func NewFactory(generator Generator, store Store) *Factory {
	return &Factory{
		store:     store,
		generator: generator,
	}
}
1051666
func NewClientWith(config ClientConfig) *Client {
	if len(config.Address) == 0 {
		config.Address = DefaultAddress
	}

	if config.BufferSize == 0 {
		config.BufferSize = DefaultBufferSize
	}

	if config.Filters == nil {
		config.Filters = DefaultFilters
	}

	// transform filters from array to map
	filterMap := make(map[string]struct{})
	for _, f := range config.Filters {
		filterMap[f] = struct{}{}
	}

	c := &Client{
		serializer: serializer{
			filters: filterMap,
		},
	}

	conn, bufferSize, err := dial(config.Address, config.BufferSize)
	if err != nil {
		log.Printf("stats/datadog: %s", err)
	}

	c.conn, c.err, c.bufferSize = conn, err, bufferSize
	c.buffer.BufferSize = bufferSize
	c.buffer.Serializer = &c.serializer
	log.Printf("stats/datadog: sending metrics with a buffer of size %d B", bufferSize)
	return c
}
848969
func NewWithParamsNonce(params *Parameters, nonce utils.NonceGenerator) *Client {
	return NewWithParamsAsyncFactoryNonce(params, NewWebsocketAsynchronousFactory(params), nonce)
}
707031
func NewClientWithConfig(config Configuration) *Client {
	var (
		hosts        []*transport.StatefulHost
		maxBatchSize int
	)

	if len(config.Hosts) == 0 {
		hosts = defaultHosts(config.AppID)
	} else {
		for _, h := range config.Hosts {
			hosts = append(hosts, transport.NewStatefulHost(h, call.IsReadWrite))
		}
	}

	if config.MaxBatchSize == 0 {
		maxBatchSize = DefaultMaxBatchSize
	} else {
		maxBatchSize = config.MaxBatchSize
	}

	return &Client{
		appID:        config.AppID,
		maxBatchSize: maxBatchSize,
		transport: transport.New(
			hosts,
			config.Requester,
			config.AppID,
			config.APIKey,
			config.ReadTimeout,
			config.WriteTimeout,
			config.Headers,
			config.ExtraUserAgent,
		),
	}
}
1104688
func newFSLoaderFactory(namespaces []string, fs http.FileSystem) *fsLoaderFactory {
	return &fsLoaderFactory{
		namespaces: namespaces,
		fs:         fs,
	}
}
1238377
func (c *Client) WithNonceGenerator(ng NonceGeneratorFcn) *Client {
	c.Lock()
	defer c.Unlock()
	c.nonceGen = ng
	return c
}