Exemplo n.º 1
1
func (cmd *esxcli) Run(f *flag.FlagSet) error {
	c, err := cmd.Client()
	if err != nil {
		return nil
	}

	host, err := cmd.HostSystem()
	if err != nil {
		return err
	}

	e, err := NewExecutor(c, host)
	if err != nil {
		return err
	}

	res, err := e.Run(f.Args())
	if err != nil {
		return err
	}

	if len(res.Values) == 0 {
		return nil
	}

	// TODO: OutputFlag / format options
	switch res.Info.Hints.Formatter() {
	case "table":
		cmd.formatTable(res)
	default:
		cmd.formatSimple(res)
	}

	return nil
}
Exemplo n.º 2
0
func (cmd *destroy) Run(f *flag.FlagSet) error {
	vms, err := cmd.VirtualMachines(f.Args())
	if err != nil {
		return err
	}

	for _, vm := range vms {
		task, err := vm.PowerOff(context.TODO())
		if err != nil {
			return err
		}

		// Ignore error since the VM may already been in powered off state.
		// vm.Destroy will fail if the VM is still powered on.
		_ = task.Wait(context.TODO())

		task, err = vm.Destroy(context.TODO())
		if err != nil {
			return err
		}

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

	return nil
}
Exemplo n.º 3
0
func (cmd *change) Run(f *flag.FlagSet) error {
	ctx := context.TODO()

	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	for _, path := range f.Args() {
		clusters, err := finder.ClusterComputeResourceList(ctx, path)
		if err != nil {
			return err
		}

		for _, cluster := range clusters {
			task, err := cluster.Reconfigure(ctx, &cmd.ClusterConfigSpecEx, true)
			if err != nil {
				return err
			}

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

	return nil
}
Exemplo n.º 4
0
func (cmd *ovfx) Prepare(f *flag.FlagSet) (string, error) {
	var err error

	args := f.Args()
	if len(args) != 1 {
		return "", errors.New("no file specified")
	}

	cmd.Client, err = cmd.DatastoreFlag.Client()
	if err != nil {
		return "", err
	}

	cmd.Datacenter, err = cmd.DatastoreFlag.Datacenter()
	if err != nil {
		return "", err
	}

	cmd.Datastore, err = cmd.DatastoreFlag.Datastore()
	if err != nil {
		return "", err
	}

	cmd.ResourcePool, err = cmd.ResourcePoolFlag.ResourcePool()
	if err != nil {
		return "", err
	}

	return f.Arg(0), nil
}
Exemplo n.º 5
0
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
	if len(f.Args()) < 1 {
		return flag.ErrHelp
	}
	datacentersToDestroy := f.Args()

	client, err := cmd.ClientFlag.Client()
	if err != nil {
		return err
	}

	finder := find.NewFinder(client, false)
	for _, datacenterToDestroy := range datacentersToDestroy {
		foundDatacenters, err := finder.DatacenterList(context.TODO(), datacenterToDestroy)
		if err != nil {
			return err
		}
		for _, foundDatacenter := range foundDatacenters {
			task, err := foundDatacenter.Destroy(context.TODO())
			if err != nil {
				return err
			}

			if err := task.Wait(context.TODO()); err != nil {
				return err
			}
		}
	}
	return nil
}
Exemplo n.º 6
0
func (cmd *set) Run(ctx context.Context, f *flag.FlagSet) error {
	c, err := cmd.Client()
	if err != nil {
		return err
	}

	refs, err := cmd.ManagedObjects(ctx, f.Args())
	if err != nil {
		return err
	}

	m := object.NewAuthorizationManager(c)
	rl, err := m.RoleList(ctx)
	if err != nil {
		return err
	}

	role := rl.ByName(cmd.role)
	if role == nil {
		return fmt.Errorf("role '%s' not found", cmd.role)
	}
	cmd.Permission.RoleId = role.RoleId

	perms := []types.Permission{cmd.Permission}

	for _, ref := range refs {
		err = m.SetEntityPermissions(ctx, ref, perms)
		if err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 7
0
func (cmd *disconnect) Run(ctx context.Context, f *flag.FlagSet) error {
	vm, err := cmd.VirtualMachine()
	if err != nil {
		return err
	}

	if vm == nil {
		return flag.ErrHelp
	}

	devices, err := vm.Device(context.TODO())
	if err != nil {
		return err
	}

	for _, name := range f.Args() {
		device := devices.Find(name)
		if device == nil {
			return fmt.Errorf("device '%s' not found", name)
		}

		if err = devices.Disconnect(device); err != nil {
			return err
		}

		if err = vm.EditDevice(context.TODO(), device); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 8
0
func (cmd *ls) Run(f *flag.FlagSet) error {
	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	lr := listResult{
		Elements: nil,
		Long:     cmd.Long,
	}

	args := f.Args()
	if len(args) == 0 {
		args = []string{"."}
	}

	for _, arg := range args {
		es, err := finder.ManagedObjectListChildren(context.TODO(), arg)
		if err != nil {
			return err
		}

		lr.Elements = append(lr.Elements, es...)
	}

	return cmd.WriteResult(lr)
}
Exemplo n.º 9
0
func (cmd *create) Run(f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	for _, arg := range f.Args() {
		dir := path.Dir(arg)
		base := path.Base(arg)
		parents, err := finder.ResourcePoolList(context.TODO(), dir)
		if err != nil {
			if _, ok := err.(*find.NotFoundError); ok {
				return fmt.Errorf("cannot create resource pool '%s': parent not found", base)
			}
			return err
		}

		for _, parent := range parents {
			_, err = parent.Create(context.TODO(), base, cmd.ResourceConfigSpec)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
Exemplo n.º 10
0
Arquivo: mv.go Projeto: vmware/vic
func (cmd *mv) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() < 2 {
		return flag.ErrHelp
	}

	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	n := f.NArg() - 1

	folder, err := finder.Folder(ctx, f.Arg(n))
	if err != nil {
		return err
	}

	objs, err := cmd.ManagedObjects(ctx, f.Args()[:n])
	if err != nil {
		return err
	}

	task, err := folder.MoveInto(ctx, objs)
	if err != nil {
		return err
	}

	logger := cmd.ProgressLogger(fmt.Sprintf("moving %d objects to %s... ", len(objs), folder.InventoryPath))
	_, err = task.WaitForResult(ctx, logger)
	logger.Wait()

	return err
}
Exemplo n.º 11
0
func (cmd *execCmd) Run(fs *flag.FlagSet) {
	cmd.InitClient(false)
	cmd.exitStatus = 0

	cmd.ValidateFlags()

	args := fs.Args()
	if len(args) < 1 {
		fmt.Println("no command to exec")
		os.Exit(1)
		return
	}
	var c *exec.Cmd
	if len(args) > 2 {
		c = exec.Command(args[0], args[1:]...)
	} else {
		c = exec.Command(args[0])
	}
	attachCmd(c)
	err := c.Start()
	if err != nil {
		panic(err)
	}

	cmd.RegisterWithExitHook(map[string]string(*cmd.services), false)

	exitCh := exitStatusCh(c)
	cmd.exitStatus = int(<-exitCh)
	close(cmd.exitSignalCh)
	time.Sleep(time.Second)
}
Exemplo n.º 12
0
func (cmd *download) Run(ctx context.Context, f *flag.FlagSet) error {
	args := f.Args()
	if len(args) != 2 {
		return errors.New("invalid arguments")
	}

	ds, err := cmd.Datastore()
	if err != nil {
		return err
	}

	p := soap.DefaultDownload

	src := args[0]
	dst := args[1]

	if dst == "-" {
		f, _, err := ds.Download(ctx, src, &p)
		if err != nil {
			return err
		}
		_, err = io.Copy(os.Stdout, f)
		return err
	}

	if cmd.OutputFlag.TTY {
		logger := cmd.ProgressLogger("Downloading... ")
		p.Progress = logger
		defer logger.Wait()
	}

	return ds.DownloadFile(ctx, src, dst, &p)
}
Exemplo n.º 13
0
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	for _, arg := range f.Args() {
		folders, err := finder.FolderList(ctx, arg)
		if err != nil {
			return err
		}

		for _, folder := range folders {
			task, err := folder.Destroy(ctx)
			if err != nil {
				return err
			}

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

	return nil
}
Exemplo n.º 14
0
func (cmd *destroy) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	client, err := cmd.ClientFlag.Client()
	if err != nil {
		return err
	}

	finder := find.NewFinder(client, false)

	for _, path := range f.Args() {
		dcs, err := finder.DatacenterList(ctx, path)
		if err != nil {
			return err
		}

		for _, dc := range dcs {
			task, err := dc.Destroy(ctx)
			if err != nil {
				return err
			}

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

	return nil
}
Exemplo n.º 15
0
func verifyFlags(opts *Options, fs *flag.FlagSet) {

	if len(fs.Args()) == 0 && opts.showText == "" {
		fs.Usage()
		os.Exit(1)
	}
}
Exemplo n.º 16
0
Arquivo: ls.go Projeto: EricYT/govmomi
func (cmd *ls) Run(f *flag.FlagSet) error {
	ds, err := cmd.Datastore()
	if err != nil {
		return err
	}

	b, err := ds.Browser(context.TODO())
	if err != nil {
		return err
	}

	args := f.Args()
	if len(args) == 0 {
		args = []string{""}
	}

	result := &listOutput{
		rs:   make([]types.HostDatastoreBrowserSearchResults, 0),
		long: cmd.long,
	}

	for _, arg := range args {
		spec := types.HostDatastoreBrowserSearchSpec{
			MatchPattern: []string{"*"},
		}

		if cmd.long {
			spec.Details = &types.FileQueryFlags{
				FileType:     true,
				FileSize:     true,
				FileOwner:    types.NewBool(true), // TODO: omitempty is generated, but seems to be required
				Modification: true,
			}
		}

		for i := 0; ; i++ {
			r, err := cmd.ListPath(b, arg, spec)
			if err != nil {
				// Treat the argument as a match pattern if not found as directory
				if i == 0 && types.IsFileNotFound(err) {
					spec.MatchPattern[0] = path.Base(arg)
					arg = path.Dir(arg)
					continue
				}

				return err
			}

			// Treat an empty result against match pattern as file not found
			if i == 1 && len(r.File) == 0 {
				return fmt.Errorf("File %s/%s was not found", r.FolderPath, spec.MatchPattern[0])
			}

			result.add(r)
			break
		}
	}

	return cmd.WriteResult(result)
}
Exemplo n.º 17
0
Arquivo: ls.go Projeto: vmware/vic
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
	c, err := cmd.Client()
	if err != nil {
		return err
	}

	refs, err := cmd.ManagedObjects(ctx, f.Args())
	if err != nil {
		return err
	}

	m := object.NewAuthorizationManager(c)
	rl, err := m.RoleList(ctx)
	if err != nil {
		return err
	}

	tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)

	for _, ref := range refs {
		perms, err := m.RetrieveEntityPermissions(ctx, ref, true)
		if err != nil {
			return err
		}

		for _, perm := range perms {
			fmt.Fprintf(tw, "%s\t%s\n", perm.Principal, rl.ById(perm.RoleId).Name)
		}
	}

	return tw.Flush()
}
Exemplo n.º 18
0
func (cmd *massSnapshotCreate) Run(ctx context.Context, f *flag.FlagSet) error {
	if f.NArg() != 1 {
		return flag.ErrHelp
	}

	_, err := cmd.Client()
	if err != nil {
		return err
	}

	vms, err := cmd.VirtualMachines(f.Args())
	if err != nil {
		if _, ok := err.(*find.NotFoundError); ok {
			// Continue with empty VM slice
		} else {
			return err
		}
	}

	var t *object.Task
	//refs := make([]types.ManagedObjectReference, 0, len(vms))
	for _, vm := range vms {
		fmt.Printf("Making a snapshot")
		t, err = vm.CreateSnapshot(ctx, "mysnapshot", "description", cmd.memory, cmd.quiesce)
		if err != nil {
			return err
		}
		t.Wait(ctx)
		//refs = append(refs, vm.Reference())
	}
	return nil
}
Exemplo n.º 19
0
Arquivo: vnc.go Projeto: vmware/vic
func (cmd *vnc) Run(ctx context.Context, f *flag.FlagSet) error {
	vms, err := cmd.loadVMs(f.Args())
	if err != nil {
		return err
	}

	// Actuate settings in VMs
	for _, vm := range vms {
		switch {
		case cmd.Enable:
			vm.enable(cmd.Port, cmd.Password)
		case cmd.Disable:
			vm.disable()
		}
	}

	// Reconfigure VMs to reflect updates
	for _, vm := range vms {
		err = vm.reconfigure()
		if err != nil {
			return err
		}
	}

	return cmd.WriteResult(vncResult(vms))
}
Exemplo n.º 20
0
func ParseServiceFlags(scfg *ServiceConfig, flagset *flag.FlagSet, argv []string) (config *ServiceConfig, args []string) {

	rpcAddr := flagset.String("l", GetDefaultBindAddr(), "host:port to listen on for RPC")
	adminAddr := flagset.String("admin", GetDefaultBindAddr(), "host:port to listen on for admin")

	err := flagset.Parse(argv)
	args = flagset.Args()
	if err == flag.ErrHelp {
		// -help was given, pass it on to caller who
		// may decide to quit instead of continuing
		args = append(args, "-help")
	}

	rpcBA, err := BindAddrFromString(*rpcAddr)
	if err != nil {
		panic(err)
	}
	adminBA, err := BindAddrFromString(*adminAddr)
	if err != nil {
		panic(err)
	}

	scfg.ServiceAddr = rpcBA
	scfg.AdminAddr = adminBA

	return scfg, args
}
Exemplo n.º 21
0
func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error {
	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	lr := listResult{
		Elements: nil,
		Long:     cmd.Long,
	}

	args := f.Args()
	if len(args) == 0 {
		args = []string{"."}
	}

	for _, arg := range args {
		es, err := finder.ManagedObjectListChildren(context.TODO(), arg)
		if err != nil {
			return err
		}

		for _, e := range es {
			if cmd.typeMatch(e.Object.Reference()) {
				lr.Elements = append(lr.Elements, e)
			}
		}
	}

	return cmd.WriteResult(lr)
}
Exemplo n.º 22
0
func (cmd *partition) Run(f *flag.FlagSet) error {
	ctx := context.TODO()

	if f.NArg() != 1 {
		return fmt.Errorf("specify device path")
	}

	path := f.Args()[0]

	host, err := cmd.HostSystem()
	if err != nil {
		return err
	}

	ss, err := host.ConfigManager().StorageSystem(ctx)
	if err != nil {
		return err
	}

	var hss mo.HostStorageSystem
	err = ss.Properties(ctx, ss.Reference(), nil, &hss)
	if err != nil {
		return nil
	}

	info, err := ss.RetrieveDiskPartitionInfo(ctx, path)
	if err != nil {
		return err
	}

	return cmd.WriteResult(partitionInfo(*info))
}
Exemplo n.º 23
0
func virtualRouterCreate(client *contrail.Client, flagSet *flag.FlagSet) {
	if flagSet.NArg() < 1 {
		flagSet.Usage()
		os.Exit(2)
	}

	if len(virtualRouterCreateOpts.ipAddress) == 0 {
		fmt.Fprintf(os.Stderr,
			"The ip-address option must be specified")
		os.Exit(2)
	}
	matched, err := regexp.MatchString(config.IpAddressPattern,
		virtualRouterCreateOpts.ipAddress)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	if !matched {
		fmt.Fprintf(os.Stderr, "Invalid IP address specified: %s\n",
			virtualRouterCreateOpts.ipAddress)
		os.Exit(2)
	}

	name := flagSet.Args()[0]
	vrouter := new(types.VirtualRouter)
	vrouter.SetName(name)
	vrouter.SetVirtualRouterIpAddress(virtualRouterCreateOpts.ipAddress)
	client.Create(vrouter)
}
Exemplo n.º 24
0
func (cmd *power) Run(f *flag.FlagSet) error {
	vms, err := cmd.VirtualMachines(f.Args())
	if err != nil {
		return err
	}

	for _, vm := range vms {
		var task *object.Task

		switch {
		case cmd.On:
			fmt.Fprintf(cmd, "Powering on %s... ", vm.Reference())
			task, err = vm.PowerOn(context.TODO())
		case cmd.Off:
			fmt.Fprintf(cmd, "Powering off %s... ", vm.Reference())
			task, err = vm.PowerOff(context.TODO())
		case cmd.Reset:
			fmt.Fprintf(cmd, "Reset %s... ", vm.Reference())
			task, err = vm.Reset(context.TODO())
		case cmd.Suspend:
			fmt.Fprintf(cmd, "Suspend %s... ", vm.Reference())
			task, err = vm.Suspend(context.TODO())
		case cmd.Reboot:
			fmt.Fprintf(cmd, "Reboot guest %s... ", vm.Reference())
			err = vm.RebootGuest(context.TODO())

			if err != nil && cmd.Force && isToolsUnavailable(err) {
				task, err = vm.Reset(context.TODO())
			}
		case cmd.Shutdown:
			fmt.Fprintf(cmd, "Shutdown guest %s... ", vm.Reference())
			err = vm.ShutdownGuest(context.TODO())

			if err != nil && cmd.Force && isToolsUnavailable(err) {
				task, err = vm.PowerOff(context.TODO())
			}
		}

		if err != nil {
			return err
		}

		if task != nil {
			err = task.Wait(context.TODO())
		}
		if err == nil {
			fmt.Fprintf(cmd, "OK\n")
			continue
		}

		if cmd.Force {
			fmt.Fprintf(cmd, "Error: %s\n", err)
			continue
		}

		return err
	}

	return nil
}
Exemplo n.º 25
0
Arquivo: remove.go Projeto: vmware/vic
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
	vm, err := cmd.VirtualMachine()
	if err != nil {
		return err
	}

	if vm == nil {
		return flag.ErrHelp
	}

	devices, err := vm.Device(ctx)
	if err != nil {
		return err
	}

	for _, name := range f.Args() {
		device := devices.Find(name)
		if device == nil {
			return fmt.Errorf("device '%s' not found", name)
		}

		if err = vm.RemoveDevice(ctx, cmd.keepFiles, device); err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 26
0
Arquivo: remove.go Projeto: vmware/vic
func (cmd *remove) Run(ctx context.Context, f *flag.FlagSet) error {
	ds, err := cmd.Datastore()
	if err != nil {
		return err
	}

	hosts, err := cmd.HostSystems(f.Args())
	if err != nil {
		return err
	}

	for _, host := range hosts {
		hds, err := host.ConfigManager().DatastoreSystem(ctx)
		if err != nil {
			return err
		}

		err = hds.Remove(ctx, ds)
		if err != nil {
			return err
		}
	}

	return nil
}
Exemplo n.º 27
0
func (cmd *change) Run(f *flag.FlagSet) error {
	if f.NArg() == 0 {
		return flag.ErrHelp
	}

	finder, err := cmd.Finder()
	if err != nil {
		return err
	}

	cmd.SetAllocation(func(a types.BaseResourceAllocationInfo) {
		ra := a.GetResourceAllocationInfo()
		if ra.Shares.Level == "" {
			ra.Shares = nil
		}
	})

	for _, arg := range f.Args() {
		pools, err := finder.ResourcePoolList(context.TODO(), arg)
		if err != nil {
			return err
		}

		for _, pool := range pools {
			err := pool.UpdateConfig(context.TODO(), cmd.name, &cmd.ResourceConfigSpec)
			if err != nil {
				return err
			}
		}
	}

	return nil
}
Exemplo n.º 28
0
func (cmd *download) Run(f *flag.FlagSet) error {
	args := f.Args()
	if len(args) != 2 {
		return errors.New("invalid arguments")
	}

	c, err := cmd.Client()
	if err != nil {
		return err
	}

	u, err := cmd.DatastoreURL(args[0])
	if err != nil {
		return err
	}

	p := soap.DefaultDownload
	if cmd.OutputFlag.TTY {
		logger := cmd.ProgressLogger("Downloading... ")
		p.Progress = logger
		defer logger.Wait()
	}

	return c.Client.DownloadFile(args[1], u, &p)
}
Exemplo n.º 29
0
Arquivo: upload.go Projeto: vmware/vic
func (cmd *upload) Run(ctx context.Context, f *flag.FlagSet) error {
	args := f.Args()
	if len(args) != 2 {
		return errors.New("invalid arguments")
	}

	ds, err := cmd.Datastore()
	if err != nil {
		return err
	}

	p := soap.DefaultUpload

	src := args[0]
	dst := args[1]

	if src == "-" {
		return ds.Upload(ctx, os.Stdin, dst, &p)
	}

	if cmd.OutputFlag.TTY {
		logger := cmd.ProgressLogger("Uploading... ")
		p.Progress = logger
		defer logger.Wait()
	}

	return ds.UploadFile(ctx, src, dst, &p)
}
Exemplo n.º 30
0
func (cmd *info) Run(f *flag.FlagSet) error {
	vm, err := cmd.VirtualMachine()
	if err != nil {
		return err
	}

	if vm == nil {
		return flag.ErrHelp
	}

	devices, err := vm.Device(context.TODO())
	if err != nil {
		return err
	}

	res := infoResult{
		list: devices,
	}

	if f.NArg() == 0 {
		res.Devices = devices
	} else {
		for _, name := range f.Args() {
			device := devices.Find(name)
			if device == nil {
				return fmt.Errorf("device '%s' not found", name)
			}

			res.Devices = append(res.Devices, device)
		}
	}

	return cmd.WriteResult(&res)
}