// Creates the main directory used to house the VMs files and folders
// during the build
342049
func (s *StepCreateBuildDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packer.Ui)

	ui.Say("Creating build directory...")

	var err error
	if s.TempPath == "" {
		s.buildDir, err = tmp.Dir("hyperv")
	} else {
		s.buildDir, err = ioutil.TempDir(s.TempPath, "hyperv")
	}

	if err != nil {
		err = fmt.Errorf("Error creating build directory: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	log.Printf("Created build directory: %s", s.buildDir)

	// Record the build directory location for later steps
	state.Put("build_dir", s.buildDir)

	return multistep.ActionContinue
}
916117
func CreateUploaderDir(dir string) error {
	err := os.MkdirAll(filepath.Join(dir, teleport.LogsDir, teleport.ComponentUpload,
		events.SessionLogsDir, defaults.Namespace), teleport.SharedDirMode)
	if err != nil {
		return trace.ConvertSystemError(err)
	}

	return nil
}
935767
func (s *rootfsFilesystemSource) CreateFilesystems(ctx context.ProviderCallContext, args []storage.FilesystemParams) ([]storage.CreateFilesystemsResult, error) {
	results := make([]storage.CreateFilesystemsResult, len(args))
	for i, arg := range args {
		filesystem, err := s.createFilesystem(arg)
		if err != nil {
			results[i].Error = err
			continue
		}
		results[i].Filesystem = filesystem
	}
	return results, nil
}
682278
func main() {
	var svcPath, svcImportPath string
	flag.StringVar(&svcPath, "path", "service",
		"The `path` to generate service clients in to.",
	)
	flag.StringVar(&svcImportPath, "svc-import-path",
		"github.com/aws/aws-sdk-go/service",
		"The Go `import path` to generate client to be under.",
	)
	flag.Usage = usage
	flag.Parse()

	if len(os.Getenv("AWS_SDK_CODEGEN_DEBUG")) != 0 {
		api.LogDebug(os.Stdout)
	}

	// Make sure all paths are based on platform's pathing not Unix
	globs := flag.Args()
	for i, g := range globs {
		globs[i] = filepath.FromSlash(g)
	}
	svcPath = filepath.FromSlash(svcPath)

	modelPaths, err := api.ExpandModelGlobPath(globs...)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to glob file pattern", err)
		os.Exit(1)
	}
	modelPaths, _ = api.TrimModelServiceVersions(modelPaths)

	apis, err := api.LoadAPIs(modelPaths, svcImportPath)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to load API models", err)
		os.Exit(1)
	}
	if len(apis) == 0 {
		fmt.Fprintf(os.Stderr, "expected to load models, but found none")
		os.Exit(1)
	}

	if v := os.Getenv("SERVICES"); len(v) != 0 {
		svcs := strings.Split(v, ",")
		for pkgName, a := range apis {
			var found bool
			for _, include := range svcs {
				if a.PackageName() == include {
					found = true
					break
				}
			}
			if !found {
				delete(apis, pkgName)
			}
		}
	}

	var wg sync.WaitGroup
	servicePaths := map[string]struct{}{}
	for _, a := range apis {
		if _, ok := excludeServices[a.PackageName()]; ok {
			continue
		}

		// Create the output path for the model.
		pkgDir := filepath.Join(svcPath, a.PackageName())
		os.MkdirAll(filepath.Join(pkgDir, a.InterfacePackageName()), 0775)

		if _, ok := servicePaths[pkgDir]; ok {
			fmt.Fprintf(os.Stderr,
				"attempted to generate a client into %s twice. Second model package, %v\n",
				pkgDir, a.PackageName())
			os.Exit(1)
		}
		servicePaths[pkgDir] = struct{}{}

		g := &generateInfo{
			API:        a,
			PackageDir: pkgDir,
		}

		wg.Add(1)
		go func() {
			defer wg.Done()
			writeServiceFiles(g, pkgDir)
		}()
	}

	wg.Wait()
}
731404
func HomeDir() string {
	if runtime.GOOS == "windows" {

		// First prefer the HOME environmental variable
		if home := os.Getenv("HOME"); len(home) > 0 {
			if _, err := os.Stat(home); err == nil {
				return home
			}
		}
		if homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH"); len(homeDrive) > 0 && len(homePath) > 0 {
			homeDir := homeDrive + homePath
			if _, err := os.Stat(homeDir); err == nil {
				return homeDir
			}
		}
		if userProfile := os.Getenv("USERPROFILE"); len(userProfile) > 0 {
			if _, err := os.Stat(userProfile); err == nil {
				return userProfile
			}
		}
	}
	return os.Getenv("HOME")
}
1330886
func (m *Model) Create() error {
	m.Service = New(NewServiceInstance(m.ServiceContent, m.RootFolder))

	ctx := context.Background()
	client := m.Service.client
	root := object.NewRootFolder(client)

	// After all hosts are created, this var is used to mount the host datastores.
	var hosts []*object.HostSystem
	hostMap := make(map[string][]*object.HostSystem)

	// We need to defer VM creation until after the datastores are created.
	var vms []func() error
	// 1 DVS per DC, added to all hosts
	var dvs *object.DistributedVirtualSwitch
	// 1 NIC per VM, backed by a DVPG if Model.Portgroup > 0
	vmnet := esx.EthernetCard.Backing

	// addHost adds a cluster host or a stanalone host.
	addHost := func(name string, f func(types.HostConnectSpec) (*object.Task, error)) (*object.HostSystem, error) {
		spec := types.HostConnectSpec{
			HostName: name,
		}

		task, err := f(spec)
		if err != nil {
			return nil, err
		}

		info, err := task.WaitForResult(context.Background(), nil)
		if err != nil {
			return nil, err
		}

		host := object.NewHostSystem(client, info.Result.(types.ManagedObjectReference))
		hosts = append(hosts, host)

		if dvs != nil {
			config := &types.DVSConfigSpec{
				Host: []types.DistributedVirtualSwitchHostMemberConfigSpec{{
					Operation: string(types.ConfigSpecOperationAdd),
					Host:      host.Reference(),
				}},
			}

			_, _ = dvs.Reconfigure(ctx, config)
		}

		return host, nil
	}

	// addMachine returns a func to create a VM.
	addMachine := func(prefix string, host *object.HostSystem, pool *object.ResourcePool, folders *object.DatacenterFolders) {
		nic := esx.EthernetCard
		nic.Backing = vmnet
		ds := types.ManagedObjectReference{}

		f := func() error {
			for i := 0; i < m.Machine; i++ {
				name := m.fmtName(prefix+"_VM", i)

				config := types.VirtualMachineConfigSpec{
					Name:    name,
					GuestId: string(types.VirtualMachineGuestOsIdentifierOtherGuest),
					Files: &types.VirtualMachineFileInfo{
						VmPathName: "[LocalDS_0]",
					},
				}

				if pool == nil {
					pool, _ = host.ResourcePool(ctx)
				}

				var devices object.VirtualDeviceList

				scsi, _ := devices.CreateSCSIController("pvscsi")
				ide, _ := devices.CreateIDEController()
				cdrom, _ := devices.CreateCdrom(ide.(*types.VirtualIDEController))
				disk := devices.CreateDisk(scsi.(types.BaseVirtualController), ds,
					config.Files.VmPathName+" "+path.Join(name, "disk1.vmdk"))
				disk.CapacityInKB = 1024

				devices = append(devices, scsi, cdrom, disk, &nic)

				config.DeviceChange, _ = devices.ConfigSpec(types.VirtualDeviceConfigSpecOperationAdd)

				task, err := folders.VmFolder.CreateVM(ctx, config, pool, host)
				if err != nil {
					return err
				}

				info, err := task.WaitForResult(ctx, nil)
				if err != nil {
					return err
				}

				vm := object.NewVirtualMachine(client, info.Result.(types.ManagedObjectReference))

				if m.Autostart {
					_, _ = vm.PowerOn(ctx)
				}
			}

			return nil
		}

		vms = append(vms, f)
	}

	nfolder := 0

	for ndc := 0; ndc < m.Datacenter; ndc++ {
		dcName := m.fmtName("DC", ndc)
		folder := root
		fName := m.fmtName("F", nfolder)

		// If Datacenter > Folder, don't create folders for the first N DCs.
		if nfolder < m.Folder && ndc >= (m.Datacenter-m.Folder) {
			f, err := folder.CreateFolder(ctx, fName)
			if err != nil {
				return err
			}
			folder = f
		}

		dc, err := folder.CreateDatacenter(ctx, dcName)
		if err != nil {
			return err
		}

		folders, err := dc.Folders(ctx)
		if err != nil {
			return err
		}

		if m.Pod > 0 {
			for pod := 0; pod < m.Pod; pod++ {
				_, _ = folders.DatastoreFolder.CreateStoragePod(ctx, m.fmtName(dcName+"_POD", pod))
			}
		}

		if folder != root {
			// Create sub-folders and use them to create any resources that follow
			subs := []**object.Folder{&folders.DatastoreFolder, &folders.HostFolder, &folders.NetworkFolder, &folders.VmFolder}

			for _, sub := range subs {
				f, err := (*sub).CreateFolder(ctx, fName)
				if err != nil {
					return err
				}

				*sub = f
			}

			nfolder++
		}

		if m.Portgroup > 0 {
			var spec types.DVSCreateSpec
			spec.ConfigSpec = &types.VMwareDVSConfigSpec{}
			spec.ConfigSpec.GetDVSConfigSpec().Name = m.fmtName("DVS", 0)

			task, err := folders.NetworkFolder.CreateDVS(ctx, spec)
			if err != nil {
				return err
			}

			info, err := task.WaitForResult(ctx, nil)
			if err != nil {
				return err
			}

			dvs = object.NewDistributedVirtualSwitch(client, info.Result.(types.ManagedObjectReference))

			for npg := 0; npg < m.Portgroup; npg++ {
				name := m.fmtName(dcName+"_DVPG", npg)

				task, err = dvs.AddPortgroup(ctx, []types.DVPortgroupConfigSpec{{Name: name}})
				if err != nil {
					return err
				}

				err = task.Wait(ctx)
				if err != nil {
					return err
				}

				// Use the 1st DVPG for the VMs eth0 backing
				if npg == 0 {
					// AddPortgroup_Task does not return the moid, so we look it up by name
					net := Map.Get(folders.NetworkFolder.Reference()).(*Folder)
					pg := Map.FindByName(name, net.ChildEntity)

					vmnet, _ = object.NewDistributedVirtualPortgroup(client, pg.Reference()).EthernetCardBackingInfo(ctx)
				}
			}
		}

		for nhost := 0; nhost < m.Host; nhost++ {
			name := m.fmtName(dcName+"_H", nhost)

			host, err := addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) {
				return folders.HostFolder.AddStandaloneHost(ctx, spec, true, nil, nil)
			})
			if err != nil {
				return err
			}

			addMachine(name, host, nil, folders)
		}

		for ncluster := 0; ncluster < m.Cluster; ncluster++ {
			clusterName := m.fmtName(dcName+"_C", ncluster)

			cluster, err := folders.HostFolder.CreateCluster(ctx, clusterName, types.ClusterConfigSpecEx{})
			if err != nil {
				return err
			}

			for nhost := 0; nhost < m.ClusterHost; nhost++ {
				name := m.fmtName(clusterName+"_H", nhost)

				_, err = addHost(name, func(spec types.HostConnectSpec) (*object.Task, error) {
					return cluster.AddHost(ctx, spec, true, nil, nil)
				})
				if err != nil {
					return err
				}
			}

			pool, err := cluster.ResourcePool(ctx)
			if err != nil {
				return err
			}

			prefix := clusterName + "_RP"

			addMachine(prefix+"0", nil, pool, folders)

			for npool := 1; npool <= m.Pool; npool++ {
				spec := types.DefaultResourceConfigSpec()

				_, err = pool.Create(ctx, m.fmtName(prefix, npool), spec)
				if err != nil {
					return err
				}
			}

			prefix = clusterName + "_APP"

			for napp := 0; napp < m.App; napp++ {
				rspec := types.DefaultResourceConfigSpec()
				vspec := NewVAppConfigSpec()
				name := m.fmtName(prefix, napp)

				vapp, err := pool.CreateVApp(ctx, name, rspec, vspec, nil)
				if err != nil {
					return err
				}

				addMachine(name, nil, vapp.ResourcePool, folders)
			}
		}

		hostMap[dcName] = hosts
		hosts = nil
	}

	if m.ServiceContent.RootFolder == esx.RootFolder.Reference() {
		// ESX model
		host := object.NewHostSystem(client, esx.HostSystem.Reference())

		dc := object.NewDatacenter(client, esx.Datacenter.Reference())
		folders, err := dc.Folders(ctx)
		if err != nil {
			return err
		}

		hostMap[dc.Reference().Value] = append(hosts, host)

		addMachine(host.Reference().Value, host, nil, folders)
	}

	for dc, dchosts := range hostMap {
		for i := 0; i < m.Datastore; i++ {
			err := m.createLocalDatastore(dc, m.fmtName("LocalDS_", i), dchosts)
			if err != nil {
				return err
			}
		}
	}

	for _, createVM := range vms {
		err := createVM()
		if err != nil {
			return err
		}
	}

	// Turn on delay AFTER we're done building the service content
	m.Service.delay = &m.DelayConfig

	return nil
}
485826
func (s stage) createFilesystems(config types.Config) error {
	fss := config.Storage.Filesystems
	s.Logger.Info("fss: %v", fss)

	if len(fss) == 0 {
		return nil
	}

	s.Logger.PushPrefix("createFilesystems")
	defer s.Logger.PopPrefix()

	devs := []string{}
	for _, fs := range fss {
		devs = append(devs, string(fs.Device))
	}

	if err := s.waitOnDevicesAndCreateAliases(devs, "filesystems"); err != nil {
		return err
	}

	// Create filesystems concurrently up to GOMAXPROCS
	concurrency := runtime.GOMAXPROCS(-1)
	work := make(chan types.Filesystem, len(fss))
	results := make(chan error)

	for i := 0; i < concurrency; i++ {
		go func() {
			for fs := range work {
				results <- s.createFilesystem(fs)
			}
		}()
	}

	for _, fs := range fss {
		work <- fs
	}
	close(work)

	// Return combined errors
	var errs []string
	for range fss {
		if err := <-results; err != nil {
			errs = append(errs, err.Error())
		}
	}

	if len(errs) > 0 {
		return errors.New(strings.Join(errs, "\n"))
	}

	return nil
}
195362
func CreateSharedVolumesPath(root string) (string, error) {
	sharedVolPath := SharedVolumesPath(root)

	if err := os.MkdirAll(sharedVolPath, SharedVolumePerm); err != nil {
		return "", errwrap.Wrap(errors.New("could not create shared volumes directory"), err)
	}
	// In case it already existed and we didn't make it, ensure permissions are
	// what the caller expects them to be.
	if err := os.Chmod(sharedVolPath, SharedVolumePerm); err != nil {
		return "", errwrap.Wrap(fmt.Errorf("could not change permissions of %q", sharedVolPath), err)
	}

	return sharedVolPath, nil
}
1152674
func CreateUVMScratch(imagePath, destDirectory, vmID string) error {
	sourceScratch := filepath.Join(imagePath, `UtilityVM\SystemTemplate.vhdx`)
	targetScratch := filepath.Join(destDirectory, "sandbox.vhdx")
	logrus.Debugf("uvm::CreateUVMScratch %s from %s", targetScratch, sourceScratch)
	if err := copyfile.CopyFile(sourceScratch, targetScratch, true); err != nil {
		return err
	}
	if err := wclayer.GrantVmAccess(vmID, targetScratch); err != nil {
		os.Remove(targetScratch)
		return err
	}
	return nil
}
829007
func (virtualDisk *VirtualDisk) Create(ctx context.Context, datastore *vclib.Datastore) (string, error) {
	if virtualDisk.VolumeOptions.DiskFormat == "" {
		virtualDisk.VolumeOptions.DiskFormat = vclib.ThinDiskType
	}
	if !virtualDisk.VolumeOptions.VerifyVolumeOptions() {
		klog.Error("VolumeOptions verification failed. volumeOptions: ", virtualDisk.VolumeOptions)
		return "", vclib.ErrInvalidVolumeOptions
	}
	if virtualDisk.VolumeOptions.StoragePolicyID != "" && virtualDisk.VolumeOptions.StoragePolicyName != "" {
		return "", fmt.Errorf("Storage Policy ID and Storage Policy Name both set, Please set only one parameter")
	}
	return getDiskManager(virtualDisk, VirtualDiskCreateOperation).Create(ctx, datastore)
}
782416
func createAppConfigDir(dirPath string) error {
	// check
	if _, err := ioutil.ReadDir(dirPath); err == nil {
		return nil
	}

	// create dir
	return os.Mkdir(dirPath, os.FileMode(0755))
}
769325
func (m VirtualDiskManager) CreateVirtualDisk(
	ctx context.Context,
	name string, datacenter *Datacenter,
	spec types.BaseVirtualDiskSpec) (*Task, error) {

	req := types.CreateVirtualDisk_Task{
		This: m.Reference(),
		Name: name,
		Spec: spec,
	}

	if datacenter != nil {
		ref := datacenter.Reference()
		req.Datacenter = &ref
	}

	res, err := methods.CreateVirtualDisk_Task(ctx, m.c, &req)
	if err != nil {
		return nil, err
	}

	return NewTask(m.c, res.Returnval), nil
}
233399
func BuildDir(path string) option {
	return func(c *sass) error {
		c.ctx.BuildDir = path
		return nil
	}
}
874443
func (c *ServerConn) MakeDir(path string) error {
	_, _, err := c.cmd(StatusPathCreated, "MKD %s", path)
	return err
}
1250213
func (c *Client) EnsureVMFolder(ctx context.Context, folderPath string) (*object.Folder, error) {
	finder, datacenter, err := c.finder(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	folders, err := datacenter.Folders(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}

	createFolder := func(parent *object.Folder, name string) (*object.Folder, error) {
		folder, err := parent.CreateFolder(ctx, name)
		if err != nil && soap.IsSoapFault(err) {
			switch soap.ToSoapFault(err).VimFault().(type) {
			case types.DuplicateName:
				return finder.Folder(ctx, parent.InventoryPath+"/"+name)
			}
		}
		return folder, err
	}

	parentFolder := folders.VmFolder
	for _, name := range strings.Split(folderPath, "/") {
		folder, err := createFolder(parentFolder, name)
		if err != nil {
			return nil, errors.Annotatef(
				err, "creating folder %q in %q",
				name, parentFolder.InventoryPath,
			)
		}
		parentFolder = folder
	}
	return parentFolder, nil
}
478982
func Setup(ctx *build.Context, fs vfs.VFS) {
	ctx.JoinPath = path.Join
	ctx.SplitPathList = filepath.SplitList
	ctx.IsAbsPath = func(p string) bool {
		return p != "" && p[0] == '/'
	}
	ctx.IsDir = func(p string) bool {
		stat, err := fs.Stat(p)
		return err == nil && stat.IsDir()
	}
	ctx.HasSubdir = func(root, dir string) (string, bool) {
		root = path.Clean(root)
		if !strings.HasSuffix(root, separator) {
			root += separator
		}
		dir = path.Clean(dir)
		if !strings.HasPrefix(dir, root) {
			return "", false
		}
		return dir[len(root):], true
	}
	ctx.ReadDir = fs.ReadDir
	ctx.OpenFile = func(p string) (io.ReadCloser, error) {
		return fs.Open(p)
	}
}
189796
func (lfs localFileSystem) Mkdir(path string, perm os.FileMode) error {
	return villa.Path(path).MkdirAll(perm)
}