github.com/vmware/govmomi@v0.51.0/examples/datastores/main.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  /*
     6  This example program shows how the `view` and `property` packages can
     7  be used to navigate a vSphere inventory structure using govmomi.
     8  */
     9  
    10  package main
    11  
    12  import (
    13  	"context"
    14  	"fmt"
    15  	"os"
    16  	"text/tabwriter"
    17  
    18  	"github.com/vmware/govmomi/examples"
    19  	"github.com/vmware/govmomi/units"
    20  	"github.com/vmware/govmomi/view"
    21  	"github.com/vmware/govmomi/vim25"
    22  	"github.com/vmware/govmomi/vim25/mo"
    23  )
    24  
    25  func main() {
    26  	examples.Run(func(ctx context.Context, c *vim25.Client) error {
    27  		// Create a view of Datastore objects
    28  		m := view.NewManager(c)
    29  
    30  		v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"Datastore"}, true)
    31  		if err != nil {
    32  			return err
    33  		}
    34  
    35  		defer v.Destroy(ctx)
    36  
    37  		// Retrieve summary property for all datastores
    38  		// Reference: https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vim.Datastore.html
    39  		var dss []mo.Datastore
    40  		err = v.Retrieve(ctx, []string{"Datastore"}, []string{"summary"}, &dss)
    41  		if err != nil {
    42  			return err
    43  		}
    44  
    45  		// Print summary per datastore (see also: govc/datastore/info.go)
    46  
    47  		tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
    48  		fmt.Fprintf(tw, "Name:\tType:\tCapacity:\tFree:\n")
    49  
    50  		for _, ds := range dss {
    51  			fmt.Fprintf(tw, "%s\t", ds.Summary.Name)
    52  			fmt.Fprintf(tw, "%s\t", ds.Summary.Type)
    53  			fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.Capacity))
    54  			fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.FreeSpace))
    55  			fmt.Fprintf(tw, "\n")
    56  		}
    57  
    58  		_ = tw.Flush()
    59  
    60  		return nil
    61  	})
    62  }