// ProvisionerHarvestMode reports the harvesting methodology the
// provisioner should take.
429377
func (c *Config) ProvisionerHarvestMode() HarvestMode {
	if v, ok := c.defined[ProvisionerHarvestModeKey].(string); ok {
		if method, err := ParseHarvestMode(v); err != nil {
			// This setting should have already been validated. Don't
			// burden the caller with handling any errors.
			panic(err)
		} else {
			return method
		}
	} else {
		return HarvestDestroyed
	}
}
1214211
func (c *Client) ProvisionResource(req *ct.ResourceReq) (*ct.Resource, error) {
	if req.ProviderID == "" {
		return nil, errors.New("controller: missing provider id")
	}
	res := &ct.Resource{}
	err := c.Post(fmt.Sprintf("/providers/%s/resources", req.ProviderID), req, res)
	return res, err
}
1080220
func (k *kubernetesClient) EnsureStorageProvisioner(cfg caas.StorageProvisioner) (*caas.StorageProvisioner, error) {
	// First see if the named storage class exists.
	sc, err := k.getStorageClass(cfg.Name)
	if err == nil {
		return &caas.StorageProvisioner{
			Name:        sc.Name,
			Provisioner: sc.Provisioner,
			Parameters:  sc.Parameters,
		}, nil
	}
	if !k8serrors.IsNotFound(err) {
		return nil, errors.Annotatef(err, "getting storage class %q", cfg.Name)
	}
	// If it's not found but there's no provisioner specified, we can't
	// create it so just return not found.
	if cfg.Provisioner == "" {
		return nil, errors.NewNotFound(nil,
			fmt.Sprintf("storage class %q doesn't exist, but no storage provisioner has been specified",
				cfg.Name))
	}

	// Create the storage class with the specified provisioner.
	var reclaimPolicy *core.PersistentVolumeReclaimPolicy
	if cfg.ReclaimPolicy != "" {
		policy := core.PersistentVolumeReclaimPolicy(cfg.ReclaimPolicy)
		reclaimPolicy = &policy
	}
	storageClasses := k.client().StorageV1().StorageClasses()
	sc = &k8sstorage.StorageClass{
		ObjectMeta: v1.ObjectMeta{
			Name: qualifiedStorageClassName(cfg.Namespace, cfg.Name),
		},
		Provisioner:   cfg.Provisioner,
		ReclaimPolicy: reclaimPolicy,
		Parameters:    cfg.Parameters,
	}
	if cfg.Namespace != "" {
		sc.Labels = map[string]string{labelModel: k.namespace}
	}
	_, err = storageClasses.Create(sc)
	if err != nil {
		return nil, errors.Annotatef(err, "creating storage class %q", cfg.Name)
	}
	return &caas.StorageProvisioner{
		Name:        sc.Name,
		Provisioner: sc.Provisioner,
		Parameters:  sc.Parameters,
	}, nil
}
733151
func (vm *VM) Provision() error {
	services, err := vm.listHostedServices()
	if err != nil {
		return fmt.Errorf(errGetListService, err)
	}

	// Always try to reuse the existing hosted service. Create a new one if it
	// doesn't exist
	if !vm.serviceExist(services) {
		err = vm.createHostedService()
		if err != nil {
			return err
		}
	}

	// Create the VM
	role := vmutils.NewVMConfiguration(vm.Name, vm.Size)
	imageURL := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s.vhd", vm.StorageAccount, vm.StorageContainer, vm.Name)
	vmutils.ConfigureDeploymentFromPlatformImage(
		&role,
		vm.SourceImage,
		imageURL,
		"")

	// Assign the first subnet in virtual network to the VM
	subnet, err := vm.getFirstSubnet()
	if err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	err = vmutils.ConfigureWithSubnet(&role, subnet)
	if err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	vmclient, err := vm.getVMClient()
	if err != nil {
		return fmt.Errorf(errGetClient, err)
	}

	err = vmutils.ConfigureForLinux(&role, vm.Name, vm.SSHCreds.SSHUser, vm.SSHCreds.SSHPassword)
	if err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	err = vmutils.ConfigureWithPublicSSH(&role)
	if err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	if vm.ConfigureHTTP {
		err = vmutils.ConfigureWithExternalPort(&role, "HTTP", 80, 80, virtualmachine.InputEndpointProtocolTCP)
		if err != nil {
			return fmt.Errorf(errProvisionVM, err)
		}
	}

	operationID, err := vmclient.CreateDeployment(role, vm.ServiceName, vm.getDeploymentOptions())
	if err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	if err := client.WaitForOperation(operationID, nil); err != nil {
		return fmt.Errorf(errProvisionVM, err)
	}

	// Use GetSSH to pull the VM status now
	cli, err := vm.GetSSH(ssh.Options{KeepAlive: 2})
	if err != nil {
		return err
	}

	return cli.WaitForSSH(SSHTimeout)
}
987716
func NewStorageProviderRegistryForModel(
	model *state.Model,
	newEnv NewEnvironFunc,
	newBroker NewCAASBrokerFunc,
) (_ storage.ProviderRegistry, err error) {
	var reg storage.ProviderRegistry
	if model.Type() == state.ModelTypeIAAS {
		if reg, err = newEnv(model.State()); err != nil {
			return nil, errors.Trace(err)
		}
	} else {
		if reg, err = newBroker(model.State()); err != nil {
			return nil, errors.Trace(err)
		}
	}
	return NewStorageProviderRegistry(reg), nil
}
19928
func (n *NodeValidatableResource) EvalTree() EvalNode {
	addr := n.ResourceAddr()
	config := n.Config

	// Declare the variables will be used are used to pass values along
	// the evaluation sequence below. These are written to via pointers
	// passed to the EvalNodes.
	var provider providers.Interface
	var providerSchema *ProviderSchema
	var configVal cty.Value

	seq := &EvalSequence{
		Nodes: []EvalNode{
			&EvalGetProvider{
				Addr:   n.ResolvedProvider,
				Output: &provider,
				Schema: &providerSchema,
			},
			&EvalValidateResource{
				Addr:           addr.Resource,
				Provider:       &provider,
				ProviderSchema: &providerSchema,
				Config:         config,
				ConfigVal:      &configVal,
			},
		},
	}

	if managed := n.Config.Managed; managed != nil {
		hasCount := n.Config.Count != nil

		// Validate all the provisioners
		for _, p := range managed.Provisioners {
			var provisioner provisioners.Interface
			var provisionerSchema *configschema.Block

			if p.Connection == nil {
				p.Connection = config.Managed.Connection
			} else if config.Managed.Connection != nil {
				p.Connection.Config = configs.MergeBodies(config.Managed.Connection.Config, p.Connection.Config)
			}

			seq.Nodes = append(
				seq.Nodes,
				&EvalGetProvisioner{
					Name:   p.Type,
					Output: &provisioner,
					Schema: &provisionerSchema,
				},
				&EvalValidateProvisioner{
					ResourceAddr:     addr.Resource,
					Provisioner:      &provisioner,
					Schema:           &provisionerSchema,
					Config:           p,
					ResourceHasCount: hasCount,
				},
			)
		}
	}

	return seq
}
1353701
func (b *Bundler) provisionVendorZip(pathDownload, pathCache, pathVendor string) (err error) {
	// Download source
	if _, errStat := os.Stat(pathCache); os.IsNotExist(errStat) {
		if err = astilectron.Download(b.ctx, b.Client, pathDownload, pathCache); err != nil {
			err = errors.Wrapf(err, "downloading %s into %s failed", pathDownload, pathCache)
			return
		}
	} else {
		astilog.Debugf("%s already exists, skipping download of %s", pathCache, pathDownload)
	}

	// Check context error
	if b.ctx.Err() != nil {
		return b.ctx.Err()
	}

	// Copy
	astilog.Debugf("Copying %s to %s", pathCache, pathVendor)
	if err = astios.Copy(b.ctx, pathCache, pathVendor); err != nil {
		err = errors.Wrapf(err, "copying %s to %s failed", pathCache, pathVendor)
		return
	}

	// Check context error
	if b.ctx.Err() != nil {
		return b.ctx.Err()
	}
	return
}
167766
func (p *ProvisionerAPI) ContainerManagerConfig(args params.ContainerManagerConfigParams) (params.ContainerManagerConfig, error) {
	var result params.ContainerManagerConfig
	cfg := make(map[string]string)
	cfg[container.ConfigModelUUID] = p.st.ModelUUID()

	switch args.Type {
	case instance.LXD:
		// TODO(jam): DefaultMTU needs to be handled here
	}

	mConfig, err := p.m.ModelConfig()
	if err != nil {
		return result, err
	}
	if url, set := mConfig.ContainerImageMetadataURL(); set {
		cfg[config.ContainerImageMetadataURLKey] = url
	}
	cfg[config.ContainerImageStreamKey] = mConfig.ContainerImageStream()

	result.ManagerConfig = cfg
	return result, nil
}
1143633
func Provision() error {
	// Get the bucketName
	bucketName := os.Getenv("S3_BUCKET")
	if bucketName == "" {
		return errors.New("Provision requires env.S3_BUCKET to be defined")
	}
	return SpartaCommand("provision", "--s3Bucket", bucketName)
}
933159
func (p *defaultProvisioner) provisionElectronFinishDarwin(appName string, paths Paths) (err error) {
	// Log
	astilog.Debug("Finishing provisioning electron for darwin system")

	// Custom app icon
	if paths.AppIconDarwinSrc() != "" {
		if err = p.provisionElectronFinishDarwinCopy(paths); err != nil {
			return errors.Wrap(err, "copying for darwin system finish failed")
		}
	}

	// Custom app name
	if appName != "" {
		// Replace
		if err = p.provisionElectronFinishDarwinReplace(appName, paths); err != nil {
			return errors.Wrap(err, "replacing for darwin system finish failed")
		}

		// Rename
		if err = p.provisionElectronFinishDarwinRename(appName, paths); err != nil {
			return errors.Wrap(err, "renaming for darwin system finish failed")
		}
	}
	return
}
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
}
123114
func (c *config) LoadProvisioner(name string) (packer.Provisioner, error) {
	log.Printf("Loading provisioner: %s\n", name)
	bin, ok := c.Provisioners[name]
	if !ok {
		log.Printf("Provisioner not found: %s\n", name)
		return nil, nil
	}

	return c.pluginClient(bin).Provisioner()
}
69782
func (p *glusterfileProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {

	sourceVolID := ""
	volID := ""
	var glusterfs *v1.GlusterfsVolumeSource

	smartclone := true
	if options.PVC.Spec.Selector != nil {
		return nil, fmt.Errorf("claim Selector is not supported")
	}

	if !util.AccessModesContainedInAll(p.GetAccessModes(), options.PVC.Spec.AccessModes) {
		return nil, fmt.Errorf("invalid AccessModes %v: only AccessModes %v are supported", options.PVC.Spec.AccessModes, p.GetAccessModes())
	}

	klog.V(1).Infof("VolumeOptions %v", options)
	p.options = options
	gidAllocate := true
	for k, v := range options.Parameters {
		switch dstrings.ToLower(k) {
		case "smartclone":
			smartclone = dstrings.ToLower(v) == "true"
		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, fmt.Errorf("allocator error: %v", err)
		}
		gid = &allocate

	}

	cfg, parseErr := p.parseClassParameters(options.Parameters, p.client)

	if parseErr != nil {
		return nil, fmt.Errorf("failed to parse storage class parameters: %v", parseErr)
	}

	klog.V(4).Infof("creating volume with configuration %+v", *cfg)

	modeAnn := "url:" + cfg.url + "," + "user:" + cfg.user + "," + "secret:" + cfg.secretName + "," + "secretnamespace:" + cfg.secretNamespace
	klog.V(1).Infof("Allocated GID %d for PVC %s", *gid, options.PVC.Name)

	gidStr := strconv.FormatInt(int64(*gid), 10)

	volSize := options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	volSizeBytes := volSize.Value()
	volszInt := int(util.RoundUpToGiB(volSizeBytes))

	if smartclone && (options.PVC.Annotations[CloneRequestAnn] != "") {
		if sourcePVCRef, ok := options.PVC.Annotations[CloneRequestAnn]; ok {
			var ns string
			parts := dstrings.SplitN(sourcePVCRef, "/", 2)
			if len(parts) < 2 {
				ns = options.PVC.Namespace
			} else {
				ns = parts[0]
			}
			sourcePVCName := parts[len(parts)-1]
			sourcePVC, err := p.getPVC(ns, sourcePVCName)
			if err != nil {
				return nil, fmt.Errorf("Unable to get PVC %s/%s", ns, sourcePVCName)
			}
			if sourceVolID, ok = sourcePVC.Annotations[heketiVolIDAnn]; ok {
				klog.Infof("Requesting clone of heketi volumeID %s", sourceVolID)
				cGlusterfs, sizeGiB, cVolID, createCloneErr := p.createVolumeClone(sourceVolID, cfg)
				if createCloneErr != nil {
					klog.Errorf("failed to create clone of %v: %v", sourceVolID, createCloneErr)
					return nil, fmt.Errorf("failed to create clone of %v: %v", sourceVolID, createCloneErr)
				}
				if cGlusterfs != nil {
					glusterfs = cGlusterfs
				}
				volID = cVolID
				klog.Infof("glusterfs volume source %v with size %d retrieved", cGlusterfs, sizeGiB)
				err = p.annotateClonedPVC(cVolID, options.PVC, sourceVolID)
				if err != nil {
					klog.Errorf("Failed to annotate cloned PVC: %v", err)
					return nil, fmt.Errorf("failed to annotate cloned PVC %s :%v", options.PVC, err)
					//todo: cleanup?
				}
			} else {
				return nil, fmt.Errorf("PVC %s/%s missing %s annotation",
					ns, sourcePVCName, heketiVolIDAnn)
			}
		}
	} else {
		nGlusterfs, sizeGiB, nVolID, createErr := p.CreateVolume(gid, cfg, volszInt)
		if createErr != nil {
			klog.Errorf("failed to create volume: %v", createErr)
			return nil, fmt.Errorf("failed to create volume: %v", createErr)
		}
		klog.Infof("glusterfs volume source %v with size %d retrieved", nGlusterfs, sizeGiB)
		if nGlusterfs != nil {
			glusterfs = nGlusterfs
		}
		volID = nVolID
		annotations := make(map[string]string, 2)
		annotations[heketiVolIDAnn] = nVolID
		annotateErr := p.annotatePVC(options.PVC.Namespace, options.PVC.Name, annotations)
		if annotateErr != nil {
			klog.Errorf("annotating PVC %v failed: %v", options.PVC.Name, annotateErr)

		}
		klog.V(1).Infof("successfully created Gluster File volume %+v with size %d and volID %s", glusterfs, sizeGiB, volID)
	}

	if glusterfs == nil {
		klog.Errorf("retrieved glusterfs volume source is nil")
		return nil, fmt.Errorf("retrieved glusterfs volume source is nil")
	}

	mode := v1.PersistentVolumeFilesystem
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: options.PVName,
			Annotations: map[string]string{
				gidAnn:                   gidStr,
				glusterTypeAnn:           "file",
				"Description":            descAnn,
				heketiVolIDAnn:           volID,
				restStr:                  modeAnn,
				v1.MountOptionAnnotation: mountStr,
			},
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
			AccessModes:                   options.PVC.Spec.AccessModes,
			VolumeMode:                    &mode,
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
			},
			PersistentVolumeSource: v1.PersistentVolumeSource{
				Glusterfs: glusterfs,
			},
		},
	}

	return pv, nil
}
536504
func (r *runtimeVerbose) pathFromVendor(from string) string {
	pathItems := strings.Split(from, "/")
	if r.IsWindows {
		pathItems = strings.Split(from, "\\")
	}

	index := -1
	for i, v := range pathItems {
		if v == "vendor" {
			index = i
		}
	}
	strlen := 0
	for i, v := range pathItems {
		if i <= index {
			strlen += len(v) + 1
		}
	}

	return filepath.Dir(from[strlen:])
}
937169
func (d *DockerMonitor) setupHostMode(puID string, runtimeInfo policy.RuntimeReader, dockerInfo *types.ContainerJSON) (err error) {

	pausePUID := puID
	if dockerInfo.HostConfig.NetworkMode == constants.DockerHostMode {
		if err = d.netcls.Creategroup(puID); err != nil {
			return err
		}

		// Clean the cgroup on exit, if we have failed t activate.
		defer func() {
			if err != nil {
				if derr := d.netcls.DeleteCgroup(puID); derr != nil {
					zap.L().Warn("Failed to clean cgroup",
						zap.String("puID", puID),
						zap.Error(derr),
						zap.Error(err),
					)
				}
			}
		}()

		markval := runtimeInfo.Options().CgroupMark
		if markval == "" {
			return errors.New("mark value not found")
		}

		mark, _ := strconv.ParseUint(markval, 10, 32)
		if err := d.netcls.AssignMark(puID, mark); err != nil {
			return err
		}
	} else {
		// Add the container pid that is linked to hostnet to
		// the cgroup of the parent container.

		pausePUID = getPausePUID(policyExtensions(runtimeInfo))
	}

	return d.netcls.AddProcess(pausePUID, dockerInfo.State.Pid)
}
1277422
func (p *defaultProvisioner) provisionPackage(ctx context.Context, paths Paths, s *ProvisionStatusPackage, m mover, name, version, pathUnzipSrc, pathDirectory string, finish func() error) (err error) {
	// Package has already been provisioned
	if s != nil && s.Version == version {
		astilog.Debugf("%s has already been provisioned to version %s, moving on...", name, version)
		return
	}
	astilog.Debugf("Provisioning %s...", name)

	// Remove previous install
	astilog.Debugf("Removing directory %s", pathDirectory)
	if err = os.RemoveAll(pathDirectory); err != nil && !os.IsNotExist(err) {
		return errors.Wrapf(err, "removing %s failed", pathDirectory)
	}

	// Move
	if err = m(ctx, paths); err != nil {
		return errors.Wrapf(err, "moving %s failed", name)
	}

	// Create directory
	astilog.Debugf("Creating directory %s", pathDirectory)
	if err = os.MkdirAll(pathDirectory, 0755); err != nil {
		return errors.Wrapf(err, "mkdirall %s failed", pathDirectory)
	}

	// Unzip
	if err = Unzip(ctx, pathUnzipSrc, pathDirectory); err != nil {
		return errors.Wrapf(err, "unzipping %s into %s failed", pathUnzipSrc, pathDirectory)
	}

	// Finish
	if finish != nil {
		if err = finish(); err != nil {
			return errors.Wrap(err, "finishing failed")
		}
	}
	return
}
369898
func (env *environment) provision(nomadPath string) (*envResults, error) {
	tfArgs := []string{"apply", "-auto-approve", "-input=false", "-no-color",
		"-state", env.tfState,
		"-var", fmt.Sprintf("nomad_binary=%s", path.Join(nomadPath, "nomad")),
		env.tfPath,
	}

	// Setup the 'terraform apply' command
	ctx := context.Background()
	cmd := exec.CommandContext(ctx, env.tf, tfArgs...)

	// Funnel the stdout/stderr to logging
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return nil, fmt.Errorf("failed to get stderr pipe: %v", err)
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, fmt.Errorf("failed to get stdout pipe: %v", err)
	}

	// Run 'terraform apply'
	cmd.Start()
	go tfLog(env.logger.Named("tf.stderr"), stderr)
	go tfLog(env.logger.Named("tf.stdout"), stdout)

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

	cmdChan := make(chan error)
	go func() {
		cmdChan <- cmd.Wait()
	}()

	// if an interrupt is received before terraform finished, forward signal to
	// child pid
	select {
	case sig := <-sigChan:
		env.logger.Error("interrupt received, forwarding signal to child process",
			"pid", cmd.Process.Pid)
		cmd.Process.Signal(sig)
		if err := procWaitTimeout(cmd.Process, 5*time.Second); err != nil {
			env.logger.Error("child process did not exit in time, killing forcefully",
				"pid", cmd.Process.Pid)
			cmd.Process.Kill()
		}
		return nil, fmt.Errorf("interrupt received")
	case err := <-cmdChan:
		if err != nil {
			return nil, fmt.Errorf("terraform exited with a non-zero status: %v", err)
		}
	}

	// Setup and run 'terraform output' to get the module output
	cmd = exec.CommandContext(ctx, env.tf, "output", "-json", "-state", env.tfState)
	out, err := cmd.Output()
	if err != nil {
		return nil, fmt.Errorf("terraform exited with a non-zero status: %v", err)
	}

	// Parse the json and pull out results
	tfOutput := make(map[string]map[string]interface{})
	err = json.Unmarshal(out, &tfOutput)
	if err != nil {
		return nil, fmt.Errorf("failed to parse terraform output: %v", err)
	}

	results := &envResults{}
	if nomadAddr, ok := tfOutput["nomad_addr"]; ok {
		results.nomadAddr = nomadAddr["value"].(string)
	} else {
		return nil, fmt.Errorf("'nomad_addr' field expected in terraform output, but was missing")
	}

	return results, nil
}