// Provide implements DockerConfigProvider
3909
func (g *dockerConfigKeyProvider) Provide(image string) credentialprovider.DockerConfig {
	// Read the contents of the google-dockercfg metadata key and
	// parse them as an alternate .dockercfg
	if cfg, err := credentialprovider.ReadDockerConfigFileFromUrl(dockerConfigKey, g.Client, metadataHeader); err != nil {
		klog.Errorf("while reading 'google-dockercfg' metadata: %v", err)
	} else {
		return cfg
	}

	return credentialprovider.DockerConfig{}
}
845669
func (container *Container) Expose(ports ...int) *Container {
	for _, port := range ports {
		container.ExposePort(PortMapping{
			ContainerPort: port,
			HostPort:      0,
			ServicePort:   0,
			Protocol:      "tcp"})
	}
	return container
}
231649
func (c *Client) Provisioner() (packer.Provisioner, error) {
	client, err := c.packrpcClient()
	if err != nil {
		return nil, err
	}

	return &cmdProvisioner{client.Provisioner(), c}, nil
}
353822
func (vm *VM) Provision() error {
	wait() // Avoid the AWS rate limit.

	svc, err := getService(vm.Region)
	if err != nil {
		return fmt.Errorf("failed to get AWS service: %v", err)
	}

	resp, err := svc.RunInstances(instanceInfo(vm))
	if err != nil {
		return fmt.Errorf("Failed to create instance: %v", err)
	}

	if hasInstanceID(resp.Instances[0]) {
		vm.InstanceID = *resp.Instances[0].InstanceId
	} else {
		return ErrNoInstanceID
	}

	if err := waitUntilReady(svc, vm.InstanceID); err != nil {
		return err
	}

	if vm.DeleteNonRootVolumeOnDestroy {
		return setNonRootDeleteOnDestroy(svc, vm.InstanceID, true)
	}

	if vm.Name != "" {
		if err := vm.SetTag("Name", vm.GetName()); err != nil {
			return err
		}
	}

	return nil
}
723527
func (crs *ConfigRepoService) Get(ctx context.Context, id string) (out *ConfigRepo, resp *APIResponse, err error) {
	out = &ConfigRepo{}
	_, resp, err = crs.client.getAction(ctx, &APIClientRequest{
		Path:         fmt.Sprintf("admin/config_repos/%s", id),
		ResponseBody: out,
		APIVersion:   apiV1,
	})

	out.client = crs.client
	return
}
712113
func (p *efsProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
	if options.PVC.Spec.Selector != nil {
		return nil, fmt.Errorf("claim.Spec.Selector is not supported")
	}

	gidAllocate := true
	for k, v := range options.Parameters {
		switch strings.ToLower(k) {
		case "gidmin":
		// Let allocator handle
		case "gidmax":
		// Let allocator handle
		case "gidallocate":
			b, err := strconv.ParseBool(v)
			if err != nil {
				return nil, fmt.Errorf("invalid value %s for parameter %s: %v", v, k, err)
			}
			gidAllocate = b
		}
	}

	var gid *int
	if gidAllocate {
		allocate, err := p.allocator.AllocateNext(options)
		if err != nil {
			return nil, err
		}
		gid = &allocate
	}

	err := p.createVolume(p.getLocalPath(options), gid)
	if err != nil {
		return nil, err
	}

	mountOptions := []string{"vers=4.1"}
	if options.MountOptions != nil {
		mountOptions = options.MountOptions
	}

	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: options.PVName,
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
			AccessModes:                   options.PVC.Spec.AccessModes,
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
			},
			PersistentVolumeSource: v1.PersistentVolumeSource{
				NFS: &v1.NFSVolumeSource{
					Server:   p.dnsName,
					Path:     p.getRemotePath(options),
					ReadOnly: false,
				},
			},
			MountOptions: mountOptions,
		},
	}

	if gidAllocate {
		pv.ObjectMeta.Annotations = map[string]string{
			gidallocator.VolumeGidAnnotationKey: strconv.FormatInt(int64(*gid), 10),
		}
	}

	return pv, nil
}
1279041
func (repository *HTMLTemplateRepository) Provide() (*template.Template, error) {
	option := repository.Compilation
	if (option == CompileOnce && repository.templates == nil) || option == CompileAlways {
		repository.templates = template.New(repository.Directory)

		filepath.Walk(repository.Directory, func(path string, info os.FileInfo, err error) error {
			if info == nil || info.IsDir() {
				return nil
			}

			rel, ext, err := ext(repository.Directory, path)
			if err != nil {
				return err
			}

			if ext != repository.FileExtension {
				return nil
			}

			tmpl := repository.templates.New(name(rel, ext))
			buffer, _ := ioutil.ReadFile(path)
			tmpl.Funcs(repository.UtilFuncs).Parse(string(buffer))
			return nil
		})
	}

	return repository.templates, nil
}
839550
func Config(client docker.Client, config *api.Config) string {
	out, err := tabbedString(func(out io.Writer) error {
		if len(config.DisplayName) > 0 {
			fmt.Fprintf(out, "Application Name:\t%s\n", config.DisplayName)
		}
		if len(config.Description) > 0 {
			fmt.Fprintf(out, "Description:\t%s\n", config.Description)
		}
		if len(config.AsDockerfile) == 0 {
			describeBuilderImage(client, config, out)
			describeRuntimeImage(config, out)
		}
		fmt.Fprintf(out, "Source:\t%s\n", config.Source)
		if len(config.ContextDir) > 0 {
			fmt.Fprintf(out, "Context Directory:\t%s\n", config.ContextDir)
		}
		fmt.Fprintf(out, "Output Image Tag:\t%s\n", config.Tag)
		printEnv(out, config.Environment)
		if len(config.EnvironmentFile) > 0 {
			fmt.Fprintf(out, "Environment File:\t%s\n", config.EnvironmentFile)
		}
		printLabels(out, config.Labels)
		fmt.Fprintf(out, "Incremental Build:\t%s\n", printBool(config.Incremental))
		if config.Incremental {
			fmt.Fprintf(out, "Incremental Image Pull User:\t%s\n", config.IncrementalAuthentication.Username)
		}
		fmt.Fprintf(out, "Remove Old Build:\t%s\n", printBool(config.RemovePreviousImage))
		fmt.Fprintf(out, "Builder Pull Policy:\t%s\n", config.BuilderPullPolicy)
		fmt.Fprintf(out, "Previous Image Pull Policy:\t%s\n", config.PreviousImagePullPolicy)
		fmt.Fprintf(out, "Quiet:\t%s\n", printBool(config.Quiet))
		fmt.Fprintf(out, "Layered Build:\t%s\n", printBool(config.LayeredBuild))
		if len(config.Destination) > 0 {
			fmt.Fprintf(out, "Artifacts Destination:\t%s\n", config.Destination)
		}
		if len(config.CallbackURL) > 0 {
			fmt.Fprintf(out, "Callback URL:\t%s\n", config.CallbackURL)
		}
		if len(config.ScriptsURL) > 0 {
			fmt.Fprintf(out, "S2I Scripts URL:\t%s\n", config.ScriptsURL)
		}
		if len(config.WorkingDir) > 0 {
			fmt.Fprintf(out, "Workdir:\t%s\n", config.WorkingDir)
		}
		if config.DockerNetworkMode != "" {
			fmt.Fprintf(out, "Docker NetworkMode:\t%s\n", config.DockerNetworkMode)
		}
		fmt.Fprintf(out, "Docker Endpoint:\t%s\n", config.DockerConfig.Endpoint)

		if _, err := os.Open(config.DockerCfgPath); err == nil {
			fmt.Fprintf(out, "Docker Pull Config:\t%s\n", config.DockerCfgPath)
			fmt.Fprintf(out, "Docker Pull User:\t%s\n", config.PullAuthentication.Username)
		}

		if len(config.Injections) > 0 {
			result := []string{}
			for _, i := range config.Injections {
				result = append(result, fmt.Sprintf("%s->%s", i.Source, i.Destination))
			}
			fmt.Fprintf(out, "Injections:\t%s\n", strings.Join(result, ","))
		}
		if len(config.BuildVolumes) > 0 {
			result := []string{}
			for _, i := range config.BuildVolumes {
				if runtime.GOOS == "windows" {
					// We need to avoid the colon in the Windows drive letter
					result = append(result, i[0:2]+strings.Replace(i[3:], ":", "->", 1))
				} else {
					result = append(result, strings.Replace(i, ":", "->", 1))
				}
			}
			fmt.Fprintf(out, "Bind mounts:\t%s\n", strings.Join(result, ","))
		}
		return nil
	})

	if err != nil {
		fmt.Printf("error: %v", err)
	}
	return out
}
264215
func (p *digitaloceanProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
	if !util.AccessModesContainedInAll(p.getAccessModes(), options.PVC.Spec.AccessModes) {
		return nil, fmt.Errorf("Invalid Access Modes: %v, Supported Access Modes: %v", options.PVC.Spec.AccessModes, p.getAccessModes())
	}

	vol, err := p.createVolume(options)
	if err != nil {
		return nil, err
	}

	annotations := make(map[string]string)
	annotations[annCreatedBy] = createdBy

	annotations[annProvisionerID] = string(p.identity)
	annotations[annVolumeID] = vol.ID

	labels := make(map[string]string)
	labels[apis.LabelZoneFailureDomain] = vol.Region.Slug
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name:        options.PVName,
			Labels:      labels,
			Annotations: annotations,
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
			AccessModes:                   options.PVC.Spec.AccessModes,
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): resource.MustParse(fmt.Sprintf("%dGi", vol.SizeGigaBytes)),
			},
			PersistentVolumeSource: v1.PersistentVolumeSource{

				FlexVolume: &v1.FlexPersistentVolumeSource{
					Driver:   fmt.Sprintf("%s/%s", flexvolumeVendor, flexvolumeDriver),
					Options:  map[string]string{},
					ReadOnly: false,
				},
			},
		},
	}

	return pv, nil
}
307370
func (d *CachingDockerConfigProvider) Provide() DockerConfig {
	d.mu.Lock()
	defer d.mu.Unlock()

	// If the cache hasn't expired, return our cache
	if time.Now().Before(d.expiration) {
		return d.cacheDockerConfig
	}

	glog.Infof("Refreshing cache for provider: %v", reflect.TypeOf(d.Provider).String())
	d.cacheDockerConfig = d.Provider.Provide()
	d.expiration = time.Now().Add(d.Lifetime)
	return d.cacheDockerConfig
}
1233934
func (p *ProvisionerAPI) ContainerConfig() (params.ContainerConfig, error) {
	result := params.ContainerConfig{}
	config, err := p.m.ModelConfig()
	if err != nil {
		return result, err
	}

	result.UpdateBehavior = &params.UpdateBehavior{
		config.EnableOSRefreshUpdate(),
		config.EnableOSUpgrade(),
	}
	result.ProviderType = config.Type()
	result.AuthorizedKeys = config.AuthorizedKeys()
	result.SSLHostnameVerification = config.SSLHostnameVerification()
	result.LegacyProxy = config.LegacyProxySettings()
	result.JujuProxy = config.JujuProxySettings()
	result.AptProxy = config.AptProxySettings()
	result.AptMirror = config.AptMirror()
	result.CloudInitUserData = config.CloudInitUserData()
	result.ContainerInheritProperties = config.ContainerInheritProperies()
	return result, nil
}
1048859
func expose(b *Builder, args []string, attributes map[string]bool, flagArgs []string, original string) error {
	if len(args) == 0 {
		return errAtLeastOneArgument("EXPOSE")
	}

	if b.RunConfig.ExposedPorts == nil {
		b.RunConfig.ExposedPorts = make(map[docker.Port]struct{})
	}

	existing := map[string]struct{}{}
	for k := range b.RunConfig.ExposedPorts {
		existing[k.Port()] = struct{}{}
	}

	for _, port := range args {
		dp := docker.Port(port)
		if _, exists := existing[dp.Port()]; !exists {
			b.RunConfig.ExposedPorts[docker.Port(fmt.Sprintf("%s/%s", dp.Port(), dp.Proto()))] = struct{}{}
		}
	}
	return nil
}
666315
func (vm *VM) Provision() error {

	if vm.Template.ID == "" {
		if err := vm.fillTemplateID(); err != nil {
			return err
		}
	}

	if vm.ServiceOffering.ID == "" {
		if err := vm.fillServiceOfferingID(); err != nil {
			return err
		}
	}

	for _, sg := range vm.SecurityGroups {
		if sg.ID == "" {
			vm.fillSecurityGroupsID()
			break
		}
	}

	if vm.Zone.ID == "" {
		if err := vm.fillZoneID(); err != nil {
			return err
		}
	}

	securityGroups := make([]string, len(vm.SecurityGroups))
	for i := range vm.SecurityGroups {
		securityGroups[i] = vm.SecurityGroups[i].ID
	}

	profile := egoscale.MachineProfile{
		Template:        vm.Template.ID,
		ServiceOffering: vm.ServiceOffering.ID,
		SecurityGroups:  securityGroups,
		Keypair:         vm.KeypairName,
		Userdata:        vm.Userdata,
		Zone:            vm.Zone.ID,
		Name:            vm.Name,
	}

	client := vm.getExoClient()
	jobID, err := client.CreateVirtualMachine(profile)
	if err != nil {
		return err
	}

	vm.JobID = jobID

	return nil
}
1248213
func (p MaasEnvironProvider) PrepareConfig(args environs.PrepareConfigParams) (*config.Config, error) {
	if err := validateCloudSpec(args.Cloud); err != nil {
		return nil, errors.Annotate(err, "validating cloud spec")
	}
	var attrs map[string]interface{}
	if _, ok := args.Config.StorageDefaultBlockSource(); !ok {
		attrs = map[string]interface{}{
			config.StorageDefaultBlockSourceKey: maasStorageProviderType,
		}
	}
	if len(attrs) == 0 {
		return args.Config, nil
	}
	return args.Config.Apply(attrs)
}
538656
func (p *snapshotProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
	if options.PVC.Spec.Selector != nil {
		return nil, fmt.Errorf("claim Selector is not supported")
	}
	snapshotName, ok := options.PVC.Annotations[crdclient.SnapshotPVCAnnotation]
	if !ok {
		return nil, fmt.Errorf("snapshot annotation not found on PV")
	}

	var snapshot crdv1.VolumeSnapshot
	err := p.crdclient.Get().
		Resource(crdv1.VolumeSnapshotResourcePlural).
		Namespace(options.PVC.Namespace).
		Name(snapshotName).
		Do().Into(&snapshot)

	if err != nil {
		return nil, fmt.Errorf("failed to retrieve VolumeSnapshot %s: %v", snapshotName, err)
	}
	// FIXME: should also check if any VolumeSnapshotData points to this VolumeSnapshot
	if len(snapshot.Spec.SnapshotDataName) == 0 {
		return nil, fmt.Errorf("VolumeSnapshot %s is not bound to any VolumeSnapshotData", snapshotName)
	}
	var snapshotData crdv1.VolumeSnapshotData
	err = p.crdclient.Get().
		Resource(crdv1.VolumeSnapshotDataResourcePlural).
		Name(snapshot.Spec.SnapshotDataName).
		Do().Into(&snapshotData)

	if err != nil {
		return nil, fmt.Errorf("failed to retrieve VolumeSnapshotData %s: %v", snapshot.Spec.SnapshotDataName, err)
	}
	glog.V(3).Infof("restore from VolumeSnapshotData %s", snapshot.Spec.SnapshotDataName)

	pvSrc, labels, err := p.snapshotRestore(snapshot.Spec.SnapshotDataName, snapshotData, options)
	if err != nil || pvSrc == nil {
		return nil, fmt.Errorf("failed to create a PV from snapshot %s: %v", snapshotName, err)
	}
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: options.PVName,
			Annotations: map[string]string{
				provisionerIDAnn: p.identity,
			},
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
			AccessModes:                   options.PVC.Spec.AccessModes,
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
			},
			PersistentVolumeSource: *pvSrc,
		},
	}

	if len(labels) != 0 {
		if pv.Labels == nil {
			pv.Labels = make(map[string]string)
		}
		for k, v := range labels {
			pv.Labels[k] = v
		}
	}

	glog.Infof("successfully created Snapshot share %#v", pv)

	return pv, nil
}
621144
func (vm *VM) Provision() error {
	client, err := getComputeClient(vm)
	if err != nil {
		return fmt.Errorf("compute client is not set for the VM: %s", err)
	}

	// Get back an flavor ID string
	flavorID, err := flavors.IDFromName(client, vm.FlavorName)
	if err != nil {
		return ErrNoFlavor
	}

	// Fetch an image ID string
	var imageID string
	if vm.ImageID == "" {
		imageID, err = findImageIDByName(client, vm.ImageMetadata.Name)
		if err != nil {
			return fmt.Errorf("error on searching image: %s", err)
		}

		if imageID == "" {
			// Create an image ID and return the image ID
			imageID, err = createImage(vm)
			if err != nil {
				return err
			}
		}
		vm.ImageID = imageID
	} else {
		imageID = vm.ImageID
	}

	// Set the security group for this vm
	securityGroup := vm.SecurityGroup
	if securityGroup == "" {
		securityGroup = "default"
	}

	var listOfNetworks []servers.Network
	for _, networkID := range vm.Networks {
		listOfNetworks = append(listOfNetworks, servers.Network{UUID: networkID})
	}

	createOpts := servers.CreateOpts{
		Name:           vm.Name,
		FlavorRef:      flavorID,
		ImageRef:       imageID,
		Networks:       listOfNetworks,
		SecurityGroups: []string{securityGroup},
		UserData:       vm.UserData,
		AdminPass:      vm.AdminPassword,
	}

	server, err := servers.Create(client, createOpts).Extract()
	if err != nil {
		return err
	}

	// Cleanup VM if something goes wrong
	var cleanup = func(err error) error {
		if errDestroy := vm.Destroy(); errDestroy != nil {
			return fmt.Errorf("%s %s", err, errDestroy)
		}
		return err
	}

	// Set the server ID to VM ID
	vm.InstanceID = server.ID

	// Wait until VM runs
	err = waitUntil(vm, lvm.VMRunning)
	if err != nil {
		return cleanup(err)
	}

	// Create and associate an floating IP for this VM
	if vm.FloatingIPPool == "" {
		return cleanup(fmt.Errorf("empty floating IP pool"))
	}

	fip, err := floatingips.Create(client, &floatingips.CreateOpts{
		Pool: vm.FloatingIPPool,
	}).Extract()

	if err != nil {
		return cleanup(fmt.Errorf("unable to create a floating ip: %s", err))
	}

	err = floatingips.AssociateInstance(client, server.ID, floatingips.AssociateOpts{FloatingIP: fip.IP}).ExtractErr()
	if err != nil {
		errFipDelete := floatingips.Delete(client, fip.ID).ExtractErr()
		err = fmt.Errorf("%s %s", err, errFipDelete)
		return cleanup(fmt.Errorf("unable to associate a floating ip: %s", err))
	}
	vm.FloatingIP = fip

	// Wait until the VM gets ready for SSH
	err = waitUntilSSHReady(vm)
	if err != nil {
		return cleanup(err)
	}

	// Create and attach a volume to this VM, if the volume size is > 0
	if vm.Volume.Size > 0 {
		err = createAndAttachVolume(vm)
		if err != nil {
			return cleanup(err)
		}
	}

	return nil
}
994938
func (p *Provider) Provide(configurationChan chan<- config.Message, pool *safe.Pool) error {
	pool.GoCtx(func(routineCtx context.Context) {
		ctxLog := log.With(routineCtx, log.Str(log.ProviderName, "rancher"))
		logger := log.FromContext(ctxLog)

		operation := func() error {
			client, err := p.createClient(ctxLog)
			if err != nil {
				logger.Errorf("Failed to create the metadata client metadata service: %v", err)
				return err
			}

			updateConfiguration := func(_ string) {
				stacks, err := client.GetStacks()
				if err != nil {
					logger.Errorf("Failed to query Rancher metadata service: %v", err)
					return
				}

				rancherData := p.parseMetadataSourcedRancherData(ctxLog, stacks)

				logger.Printf("Received Rancher data %+v", rancherData)

				configuration := p.buildConfiguration(ctxLog, rancherData)
				configurationChan <- config.Message{
					ProviderName:  "rancher",
					Configuration: configuration,
				}
			}
			updateConfiguration("init")

			if p.Watch {
				if p.IntervalPoll {
					p.intervalPoll(ctxLog, client, updateConfiguration)
				} else {
					// Long polling should be favored for the most accurate configuration updates.
					// Holds the connection until there is either a change in the metadata repository or `p.RefreshSeconds` has elapsed.
					client.OnChangeCtx(ctxLog, p.RefreshSeconds, updateConfiguration)
				}
			}

			return nil
		}

		notify := func(err error, time time.Duration) {
			logger.Errorf("Provider connection error %+v, retrying in %s", err, time)
		}
		err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), notify)
		if err != nil {
			logger.Errorf("Cannot connect to Provider server: %+v", err)
		}
	})

	return nil
}