// Provision returns a new machineId and nil if the provision process is done successfully
// The func will manual provision a linux machine using as it's default protocol SSH
347528
func ProvisionMachine(args manual.ProvisionMachineArgs) (machineId string, err error) {
	defer func() {
		if machineId != "" && err != nil {
			logger.Errorf("provisioning failed, removing machine %v: %v", machineId, err)
			if cleanupErr := args.Client.ForceDestroyMachines(machineId); cleanupErr != nil {
				logger.Errorf("error cleaning up machine: %s", cleanupErr)
			}
			machineId = ""
		}
	}()

	// Create the "ubuntu" user and initialise passwordless sudo. We populate
	// the ubuntu user's authorized_keys file with the public keys in the current
	// user's ~/.ssh directory. The authenticationworker will later update the
	// ubuntu user's authorized_keys.
	if err = InitUbuntuUser(args.Host, args.User,
		args.AuthorizedKeys, args.Stdin, args.Stdout); err != nil {
		return "", err
	}

	machineParams, err := gatherMachineParams(args.Host)
	if err != nil {
		return "", err
	}

	// Inform Juju that the machine exists.
	machineId, err = manual.RecordMachineInState(args.Client, *machineParams)
	if err != nil {
		return "", err
	}

	provisioningScript, err := args.Client.ProvisioningScript(params.ProvisioningScriptParams{
		MachineId:              machineId,
		Nonce:                  machineParams.Nonce,
		DisablePackageCommands: !args.EnableOSRefreshUpdate && !args.EnableOSUpgrade,
	})

	if err != nil {
		logger.Errorf("cannot obtain provisioning script")
		return "", err
	}

	// Finally, provision the machine agent.
	err = runProvisionScript(provisioningScript, args.Host, args.Stderr)
	if err != nil {
		return machineId, err
	}

	logger.Infof("Provisioned machine %v", machineId)
	return machineId, nil
}
1225282
func (p *Provider) CreateMachine() (machine *iaas.Machine, err error) {
	err = p.Client.Create(p.Host)
	if err != nil {
		return
	}
	config, err := getConfig(p.Client.GetMachinesDir(), p.Name)
	if err != nil {
		return
	}
	ip, err := p.Host.Driver.GetIP()
	if err != nil {
		return
	}

	machine = &iaas.Machine{
		ID:        "",
		IP:        ip,
		Image:     config.Driver.MachineImage,
		Kind:      config.DriverName,
		Name:      p.Name,
		SSHKeysID: []int{},
		CertsDir:  p.ClientPath + "/certs",
	}
	return
}
450108
func (r *hostPathProvisioner) Provision(selectedNode *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (*v1.PersistentVolume, error) {
	if util.CheckPersistentVolumeClaimModeBlock(r.options.PVC) {
		return nil, fmt.Errorf("%s does not support block volume provisioning", r.plugin.GetPluginName())
	}

	fullpath := fmt.Sprintf("/tmp/hostpath_pv/%s", uuid.NewUUID())

	capacity := r.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
	pv := &v1.PersistentVolume{
		ObjectMeta: metav1.ObjectMeta{
			Name: r.options.PVName,
			Annotations: map[string]string{
				util.VolumeDynamicallyCreatedByKey: "hostpath-dynamic-provisioner",
			},
		},
		Spec: v1.PersistentVolumeSpec{
			PersistentVolumeReclaimPolicy: r.options.PersistentVolumeReclaimPolicy,
			AccessModes:                   r.options.PVC.Spec.AccessModes,
			Capacity: v1.ResourceList{
				v1.ResourceName(v1.ResourceStorage): capacity,
			},
			PersistentVolumeSource: v1.PersistentVolumeSource{
				HostPath: &v1.HostPathVolumeSource{
					Path: fullpath,
				},
			},
		},
	}
	if len(r.options.PVC.Spec.AccessModes) == 0 {
		pv.Spec.AccessModes = r.plugin.GetAccessModes()
	}

	return pv, os.MkdirAll(pv.Spec.HostPath.Path, 0750)
}
1245653
func (n *NodeAbstractResource) ProvisionedBy() []string {
	// If we have no configuration, then we have no provisioners
	if n.Config == nil || n.Config.Managed == nil {
		return nil
	}

	// Build the list of provisioners we need based on the configuration.
	// It is okay to have duplicates here.
	result := make([]string, len(n.Config.Managed.Provisioners))
	for i, p := range n.Config.Managed.Provisioners {
		result[i] = p.Type
	}

	return result
}
520964
func getServer(vm *VM) (*servers.Server, error) {
	if vm.InstanceID == "" {
		// Probably need to call Provision first.
		return nil, ErrNoInstanceID
	}

	client, err := getComputeClient(vm)
	if err != nil {
		return nil, err
	}

	status, err := servers.Get(client, vm.InstanceID).Extract()
	if status != nil && err != nil {
		return nil, fmt.Errorf("failed to retrieve the server for VM")
	}

	return status, nil
}
451936
func (m *Machine) Enable() {
	if !m.State.Enabled {
		m.State = State{
			Enabled:    true,
			Generation: m.nextGen(),
			LastRewind: m.Now,
		}
		m.scheduleTick(m.Now)
	}
}
458485
func (svc *googleService) provision() error {
	zone, err := svc.service.Zones.Get(svc.vm.Project, svc.vm.Zone).Do()
	if err != nil {
		return err
	}

	machineType, err := svc.service.MachineTypes.Get(svc.vm.Project, zone.Name, svc.vm.MachineType).Do()
	if err != nil {
		return err
	}

	network, err := svc.service.Networks.Get(svc.vm.Project, svc.vm.Network).Do()
	if err != nil {
		return err
	}

	// validate network
	if !network.AutoCreateSubnetworks && len(network.Subnetworks) > 0 {
		// Network appears to be in "custom" mode, so a subnetwork is required
		// libretto doesn't handle the network creation
		if svc.vm.Subnetwork == "" {
			return fmt.Errorf("a subnetwork must be specified")
		}
	}

	subnetworkSelfLink := ""
	if svc.vm.Subnetwork != "" {
		subnetwork, err := svc.service.Subnetworks.Get(svc.vm.Project, svc.vm.region(), svc.vm.Subnetwork).Do()
		if err != nil {
			return err
		}
		subnetworkSelfLink = subnetwork.SelfLink
	}

	accessconfig := googlecloud.AccessConfig{
		Name: "External NAT for Libretto",
		Type: "ONE_TO_ONE_NAT",
	}

	md := svc.getSSHKey()

	disks, err := svc.createDisks()
	if err != nil {
		return err
	}

	instance := &googlecloud.Instance{
		Name:        svc.vm.Name,
		Description: svc.vm.Description,
		Disks:       disks,
		MachineType: machineType.SelfLink,
		Metadata: &googlecloud.Metadata{
			Items: []*googlecloud.MetadataItems{
				{
					Key:   "sshKeys",
					Value: &md,
				},
			},
		},
		NetworkInterfaces: []*googlecloud.NetworkInterface{
			{
				AccessConfigs: []*googlecloud.AccessConfig{
					&accessconfig,
				},
				Network:    network.SelfLink,
				Subnetwork: subnetworkSelfLink,
				NetworkIP:  svc.vm.PrivateIPAddress,
			},
		},
		Scheduling: &googlecloud.Scheduling{
			Preemptible: svc.vm.Preemptible,
		},
		ServiceAccounts: []*googlecloud.ServiceAccount{
			{
				Email:  "default",
				Scopes: svc.vm.Scopes,
			},
		},
		Tags: &googlecloud.Tags{
			Items: svc.vm.Tags,
		},
	}

	op, err := svc.service.Instances.Insert(svc.vm.Project, zone.Name, instance).Do()
	if err != nil {
		return err
	}

	if err = svc.waitForOperationReady(op.Name); err != nil {
		return err
	}

	_, err = svc.getInstance()
	return err
}
883150
func machineID() (string, error) {
	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Cryptography`, registry.QUERY_VALUE|registry.WOW64_64KEY)
	if err != nil {
		return "", err
	}
	defer k.Close()

	s, _, err := k.GetStringValue("MachineGuid")
	if err != nil {
		return "", err
	}
	return s, nil
}
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
}
1374084
func (p *Provider) CreateMachine() (machine *iaas.Machine, err error) {
	err = p.Client.Create(p.Host)
	if err != nil {
		return
	}
	config, err := getConfig(p.Client.GetMachinesDir(), p.Name)
	if err != nil {
		return
	}

	machine = &iaas.Machine{
		ID:        config.Driver.InstanceID,
		IP:        config.Driver.IPAddress,
		Image:     config.Driver.AMI,
		Kind:      config.DriverName,
		Name:      p.Name,
		SSHKeysID: []int{config.Driver.SSHKeyID},
		CertsDir:  p.ClientPath + "/certs",
	}
	return
}
712651
func (m *MachinesClient) Create(ctx context.Context, machine *envelope.Machine,
	memberships []envelope.Membership, token *MachineTokenCreationSegment) (*apitypes.MachineSegment, error) {

	segment := MachineCreationSegment{
		MachineSegment: apitypes.MachineSegment{
			Machine:     machine,
			Memberships: memberships,
		},
		Tokens: []MachineTokenCreationSegment{*token},
	}

	resp := &apitypes.MachineSegment{}
	err := m.client.RoundTrip(ctx, "POST", "/machines", nil, &segment, &resp)
	return resp, err
}
1311320
func (vm *VM) Provision() (err error) {
	if err := SetupSession(vm); err != nil {
		return fmt.Errorf("Error setting up vSphere session: %s", err)
	}

	// Cancel the sdk context
	defer func() {
		vm.client.Logout(vm.ctx)
		vm.cancel()
	}()

	// Get a reference to the datacenter with host and vm folders populated
	dcMo, err := GetDatacenter(vm)
	if err != nil {
		return fmt.Errorf("Failed to retrieve datacenter: %s", err)
	}

	// Upload a template to all the datastores if `UseLocalTemplates` is set.
	// Otherwise pick a random datastore out of the list that was passed in.
	var datastores = vm.Datastores
	if !vm.UseLocalTemplates {
		n := util.Random(1, len(vm.Datastores))
		datastores = []string{vm.Datastores[n-1]}
	}

	usableDatastores := []string{}
	for _, d := range datastores {
		template := createTemplateName(vm.Template, d)
		// Does the VM template already exist?
		e, err := Exists(vm, dcMo, template)
		if err != nil {
			return fmt.Errorf("failed to check if the template already exists: %s", err)
		}

		// If it does exist, return an error if the skip existing flag is not set
		if e {
			if !vm.SkipExisting {
				return fmt.Errorf("template already exists: %s", vm.Template)
			}
		} else {
			// Upload the template if  it does not exist. If it exists and SkipExisting is true,
			// use the existing template
			if err := uploadTemplate(vm, dcMo, d); err != nil {
				return err
			}
		}
		// Upload successful or the template was found with the SkipExisting flag set to true
		usableDatastores = append(usableDatastores, d)
	}

	// Does the VM already exist?
	e, err := Exists(vm, dcMo, vm.Name)
	if err != nil {
		return fmt.Errorf("failed to check if the vm already exists: %s", err)
	}
	if e {
		return ErrorVMExists
	}

	err = cloneFromTemplate(vm, dcMo, usableDatastores)
	if err != nil {
		return fmt.Errorf("error while cloning vm from template: %s", err)
	}
	return
}
866972
func (p *defaultProvisioner) ProvisionStatus(paths Paths) (s ProvisionStatus, err error) {
	// Open the file
	var f *os.File
	s.Electron = make(map[string]*ProvisionStatusPackage)
	if f, err = os.Open(paths.ProvisionStatus()); err != nil {
		if !os.IsNotExist(err) {
			err = errors.Wrapf(err, "opening file %s failed", paths.ProvisionStatus())
		} else {
			err = nil
		}
		return
	}
	defer f.Close()

	// Unmarshal
	if errLocal := json.NewDecoder(f).Decode(&s); errLocal != nil {
		// For backward compatibility purposes, if there's an unmarshal error we delete the status file and make the
		// assumption that provisioning has to be done all over again
		astilog.Error(errors.Wrapf(errLocal, "json decoding from %s failed", paths.ProvisionStatus()))
		astilog.Debugf("Removing %s", f.Name())
		if errLocal = os.RemoveAll(f.Name()); errLocal != nil {
			astilog.Error(errors.Wrapf(errLocal, "removing %s failed", f.Name()))
		}
		return
	}
	return
}
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
}
1178771
func (sbtp SingleBinaryThrustProvisioner) Provision() error {
	err := sbtp.extractToPath(spawn.GetDownloadPath())
	if err != nil {
		return err
	}
	return spawn.Bootstrap()
}
887247
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, "docker"))
		logger := log.FromContext(ctxLog)

		operation := func() error {
			var err error
			ctx, cancel := context.WithCancel(ctxLog)
			defer cancel()

			ctx = log.With(ctx, log.Str(log.ProviderName, "docker"))

			dockerClient, err := p.createClient()
			if err != nil {
				logger.Errorf("Failed to create a client for docker, error: %s", err)
				return err
			}

			serverVersion, err := dockerClient.ServerVersion(ctx)
			if err != nil {
				logger.Errorf("Failed to retrieve information of the docker client and server host: %s", err)
				return err
			}
			logger.Debugf("Provider connection established with docker %s (API %s)", serverVersion.Version, serverVersion.APIVersion)
			var dockerDataList []dockerData
			if p.SwarmMode {
				dockerDataList, err = p.listServices(ctx, dockerClient)
				if err != nil {
					logger.Errorf("Failed to list services for docker swarm mode, error %s", err)
					return err
				}
			} else {
				dockerDataList, err = p.listContainers(ctx, dockerClient)
				if err != nil {
					logger.Errorf("Failed to list containers for docker, error %s", err)
					return err
				}
			}

			configuration := p.buildConfiguration(ctxLog, dockerDataList)
			configurationChan <- config.Message{
				ProviderName:  "docker",
				Configuration: configuration,
			}
			if p.Watch {
				if p.SwarmMode {
					errChan := make(chan error)
					// TODO: This need to be change. Linked to Swarm events docker/docker#23827
					ticker := time.NewTicker(time.Second * time.Duration(p.SwarmModeRefreshSeconds))
					pool.GoCtx(func(ctx context.Context) {

						ctx = log.With(ctx, log.Str(log.ProviderName, "docker"))
						logger := log.FromContext(ctx)

						defer close(errChan)
						for {
							select {
							case <-ticker.C:
								services, err := p.listServices(ctx, dockerClient)
								if err != nil {
									logger.Errorf("Failed to list services for docker, error %s", err)
									errChan <- err
									return
								}

								configuration := p.buildConfiguration(ctx, services)
								if configuration != nil {
									configurationChan <- config.Message{
										ProviderName:  "docker",
										Configuration: configuration,
									}
								}

							case <-ctx.Done():
								ticker.Stop()
								return
							}
						}
					})
					if err, ok := <-errChan; ok {
						return err
					}
					// channel closed

				} else {
					f := filters.NewArgs()
					f.Add("type", "container")
					options := dockertypes.EventsOptions{
						Filters: f,
					}

					startStopHandle := func(m eventtypes.Message) {
						logger.Debugf("Provider event received %+v", m)
						containers, err := p.listContainers(ctx, dockerClient)
						if err != nil {
							logger.Errorf("Failed to list containers for docker, error %s", err)
							// Call cancel to get out of the monitor
							return
						}

						configuration := p.buildConfiguration(ctx, containers)
						if configuration != nil {
							message := config.Message{
								ProviderName:  "docker",
								Configuration: configuration,
							}
							select {
							case configurationChan <- message:
							case <-ctx.Done():
							}

						}
					}

					eventsc, errc := dockerClient.Events(ctx, options)
					for {
						select {
						case event := <-eventsc:
							if event.Action == "start" ||
								event.Action == "die" ||
								strings.HasPrefix(event.Action, "health_status") {
								startStopHandle(event)
							}
						case err := <-errc:
							if err == io.EOF {
								logger.Debug("Provider event stream closed")
							}
							return err
						case <-ctx.Done():
							return nil
						}
					}
				}
			}
			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 docker server %+v", err)
		}
	})

	return nil
}
976721
func (repo *LocalRepository) Setup(instance *Instance) error {
	err := repo.EnsureDirectoriesExist(instance)
	if err != nil {
		repo.Logger.Error("ensure-dirs-exist", err, lager.Data{
			"instance_id": instance.ID,
		})
		return err
	}

	err = repo.Lock(instance)
	if err != nil {
		repo.Logger.Error("lock-shared-instance", err, lager.Data{
			"instance_id": instance.ID,
		})
		return err
	}

	err = repo.WriteConfigFile(instance)
	if err != nil {
		repo.Logger.Error("write-config-file", err, lager.Data{
			"instance_id": instance.ID,
		})
		return err
	}

	repo.Logger.Info("provision-instance", lager.Data{
		"instance_id": instance.ID,
		"plan":        "shared-vm",
		"message":     "Successfully provisioned Redis instance",
	})

	return nil
}