github.com/vmware/govmomi@v0.51.0/cli/vm/question.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package vm
     6  
     7  import (
     8  	"context"
     9  	"errors"
    10  	"flag"
    11  	"fmt"
    12  
    13  	"github.com/vmware/govmomi/cli"
    14  	"github.com/vmware/govmomi/cli/flags"
    15  	"github.com/vmware/govmomi/property"
    16  	"github.com/vmware/govmomi/vim25/mo"
    17  	"github.com/vmware/govmomi/vim25/types"
    18  )
    19  
    20  type question struct {
    21  	*flags.VirtualMachineFlag
    22  
    23  	answer string
    24  }
    25  
    26  func init() {
    27  	cli.Register("vm.question", &question{})
    28  }
    29  
    30  func (cmd *question) Register(ctx context.Context, f *flag.FlagSet) {
    31  	cmd.VirtualMachineFlag, ctx = flags.NewVirtualMachineFlag(ctx)
    32  	cmd.VirtualMachineFlag.Register(ctx, f)
    33  
    34  	f.StringVar(&cmd.answer, "answer", "", "Answer to question")
    35  }
    36  
    37  func (cmd *question) Process(ctx context.Context) error {
    38  	if err := cmd.VirtualMachineFlag.Process(ctx); err != nil {
    39  		return err
    40  	}
    41  	return nil
    42  }
    43  
    44  func (cmd *question) Run(ctx context.Context, f *flag.FlagSet) error {
    45  	c, err := cmd.Client()
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	vm, err := cmd.VirtualMachine()
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	if vm == nil {
    56  		return errors.New("no VM specified")
    57  	}
    58  
    59  	var mvm mo.VirtualMachine
    60  
    61  	pc := property.DefaultCollector(c)
    62  	err = pc.RetrieveOne(ctx, vm.Reference(), []string{"runtime.question"}, &mvm)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	q := mvm.Runtime.Question
    68  	if q == nil {
    69  		fmt.Printf("No pending question\n")
    70  		return nil
    71  	}
    72  
    73  	// Print question if no answer is specified
    74  	if cmd.answer == "" {
    75  		fmt.Printf("Question:\n%s\n\n", q.Text)
    76  		fmt.Printf("Possible answers:\n")
    77  		for _, e := range q.Choice.ChoiceInfo {
    78  			ed := e.(*types.ElementDescription)
    79  			fmt.Printf("%s) %s\n", ed.Key, ed.Description.Label)
    80  		}
    81  		return nil
    82  	}
    83  
    84  	// Answer question
    85  	return vm.Answer(ctx, q.Id, cmd.answer)
    86  }