github.com/vmware/govmomi@v0.37.1/govc/flags/storage_pod.go (about)

     1  /*
     2  Copyright (c) 2014-2022 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  package flags
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  	"os"
    24  
    25  	"github.com/vmware/govmomi/object"
    26  )
    27  
    28  type StoragePodFlag struct {
    29  	common
    30  
    31  	*DatacenterFlag
    32  
    33  	Name string
    34  
    35  	sp *object.StoragePod
    36  }
    37  
    38  var storagePodFlagKey = flagKey("storagePod")
    39  
    40  func NewStoragePodFlag(ctx context.Context) (*StoragePodFlag, context.Context) {
    41  	if v := ctx.Value(storagePodFlagKey); v != nil {
    42  		return v.(*StoragePodFlag), ctx
    43  	}
    44  
    45  	v := &StoragePodFlag{}
    46  	v.DatacenterFlag, ctx = NewDatacenterFlag(ctx)
    47  	ctx = context.WithValue(ctx, storagePodFlagKey, v)
    48  	return v, ctx
    49  }
    50  
    51  func (f *StoragePodFlag) Register(ctx context.Context, fs *flag.FlagSet) {
    52  	f.RegisterOnce(func() {
    53  		f.DatacenterFlag.Register(ctx, fs)
    54  
    55  		env := "GOVC_DATASTORE_CLUSTER"
    56  		value := os.Getenv(env)
    57  		usage := fmt.Sprintf("Datastore cluster [%s]", env)
    58  		fs.StringVar(&f.Name, "datastore-cluster", value, usage)
    59  	})
    60  }
    61  
    62  func (f *StoragePodFlag) Process(ctx context.Context) error {
    63  	return f.DatacenterFlag.Process(ctx)
    64  }
    65  
    66  func (f *StoragePodFlag) Isset() bool {
    67  	return f.Name != ""
    68  }
    69  
    70  func (f *StoragePodFlag) StoragePod() (*object.StoragePod, error) {
    71  	ctx := context.TODO()
    72  	if f.sp != nil {
    73  		return f.sp, nil
    74  	}
    75  
    76  	finder, err := f.Finder()
    77  	if err != nil {
    78  		return nil, err
    79  	}
    80  
    81  	if f.Isset() {
    82  		f.sp, err = finder.DatastoreCluster(ctx, f.Name)
    83  		if err != nil {
    84  			return nil, err
    85  		}
    86  	} else {
    87  		f.sp, err = finder.DefaultDatastoreCluster(ctx)
    88  		if err != nil {
    89  			return nil, err
    90  		}
    91  	}
    92  
    93  	return f.sp, nil
    94  }