github.com/vmware/govmomi@v0.51.0/examples/hosts/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  
    28  		// Create a view of HostSystem objects
    29  		m := view.NewManager(c)
    30  
    31  		v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"HostSystem"}, true)
    32  		if err != nil {
    33  			return err
    34  		}
    35  
    36  		defer v.Destroy(ctx)
    37  
    38  		// Retrieve summary property for all hosts
    39  		// Reference: https://developer.broadcom.com/xapis/vsphere-web-services-api/latest/vim.HostSystem.html
    40  		var hss []mo.HostSystem
    41  		err = v.Retrieve(ctx, []string{"HostSystem"}, []string{"summary"}, &hss)
    42  		if err != nil {
    43  			return err
    44  		}
    45  
    46  		// Print summary per host (see also: govc/host/info.go)
    47  
    48  		tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
    49  		fmt.Fprintf(tw, "Name:\tUsed CPU:\tTotal CPU:\tFree CPU:\tUsed Memory:\tTotal Memory:\tFree Memory:\t\n")
    50  
    51  		for _, hs := range hss {
    52  			totalCPU := int64(hs.Summary.Hardware.CpuMhz) * int64(hs.Summary.Hardware.NumCpuCores)
    53  			freeCPU := int64(totalCPU) - int64(hs.Summary.QuickStats.OverallCpuUsage)
    54  			freeMemory := int64(hs.Summary.Hardware.MemorySize) - (int64(hs.Summary.QuickStats.OverallMemoryUsage) * 1024 * 1024)
    55  			fmt.Fprintf(tw, "%s\t", hs.Summary.Config.Name)
    56  			fmt.Fprintf(tw, "%d\t", hs.Summary.QuickStats.OverallCpuUsage)
    57  			fmt.Fprintf(tw, "%d\t", totalCPU)
    58  			fmt.Fprintf(tw, "%d\t", freeCPU)
    59  			fmt.Fprintf(tw, "%s\t", (units.ByteSize(hs.Summary.QuickStats.OverallMemoryUsage))*1024*1024)
    60  			fmt.Fprintf(tw, "%s\t", units.ByteSize(hs.Summary.Hardware.MemorySize))
    61  			fmt.Fprintf(tw, "%d\t", freeMemory)
    62  			fmt.Fprintf(tw, "\n")
    63  		}
    64  
    65  		_ = tw.Flush()
    66  
    67  		return nil
    68  	})
    69  }