github.com/vmware/govmomi@v0.37.1/examples/datastores/main.go (about)

     1  /*
     2  Copyright (c) 2015-2017 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  /*
    18  This example program shows how the `view` and `property` packages can
    19  be used to navigate a vSphere inventory structure using govmomi.
    20  */
    21  
    22  package main
    23  
    24  import (
    25  	"context"
    26  	"fmt"
    27  	"os"
    28  	"text/tabwriter"
    29  
    30  	"github.com/vmware/govmomi/examples"
    31  	"github.com/vmware/govmomi/units"
    32  	"github.com/vmware/govmomi/view"
    33  	"github.com/vmware/govmomi/vim25"
    34  	"github.com/vmware/govmomi/vim25/mo"
    35  )
    36  
    37  func main() {
    38  	examples.Run(func(ctx context.Context, c *vim25.Client) error {
    39  		// Create a view of Datastore objects
    40  		m := view.NewManager(c)
    41  
    42  		v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{"Datastore"}, true)
    43  		if err != nil {
    44  			return err
    45  		}
    46  
    47  		defer v.Destroy(ctx)
    48  
    49  		// Retrieve summary property for all datastores
    50  		// Reference: http://pubs.vmware.com/vsphere-60/topic/com.vmware.wssdk.apiref.doc/vim.Datastore.html
    51  		var dss []mo.Datastore
    52  		err = v.Retrieve(ctx, []string{"Datastore"}, []string{"summary"}, &dss)
    53  		if err != nil {
    54  			return err
    55  		}
    56  
    57  		// Print summary per datastore (see also: govc/datastore/info.go)
    58  
    59  		tw := tabwriter.NewWriter(os.Stdout, 2, 0, 2, ' ', 0)
    60  		fmt.Fprintf(tw, "Name:\tType:\tCapacity:\tFree:\n")
    61  
    62  		for _, ds := range dss {
    63  			fmt.Fprintf(tw, "%s\t", ds.Summary.Name)
    64  			fmt.Fprintf(tw, "%s\t", ds.Summary.Type)
    65  			fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.Capacity))
    66  			fmt.Fprintf(tw, "%s\t", units.ByteSize(ds.Summary.FreeSpace))
    67  			fmt.Fprintf(tw, "\n")
    68  		}
    69  
    70  		_ = tw.Flush()
    71  
    72  		return nil
    73  	})
    74  }