1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
|
/*
Copyright (c) 2017 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package object
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"strings"
"text/tabwriter"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/internal"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/view"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
type find struct {
*flags.DatacenterFlag
ref bool
long bool
parent bool
kind kinds
name string
maxdepth int
}
var alias = []struct {
name string
kind string
}{
{"a", "VirtualApp"},
{"c", "ClusterComputeResource"},
{"d", "Datacenter"},
{"f", "Folder"},
{"g", "DistributedVirtualPortgroup"},
{"h", "HostSystem"},
{"m", "VirtualMachine"},
{"n", "Network"},
{"o", "OpaqueNetwork"},
{"p", "ResourcePool"},
{"r", "ComputeResource"},
{"s", "Datastore"},
{"w", "DistributedVirtualSwitch"},
}
func aliasHelp() string {
var help bytes.Buffer
for _, a := range alias {
fmt.Fprintf(&help, " %s %s\n", a.name, a.kind)
}
return help.String()
}
type kinds []string
func (e *kinds) String() string {
return fmt.Sprint(*e)
}
func (e *kinds) Set(value string) error {
*e = append(*e, e.alias(value))
return nil
}
func (e *kinds) alias(value string) string {
if len(value) != 1 {
return value
}
for _, a := range alias {
if a.name == value {
return a.kind
}
}
return value
}
func (e *kinds) wanted(kind string) bool {
if len(*e) == 0 {
return true
}
for _, k := range *e {
if kind == k {
return true
}
}
return false
}
func init() {
cli.Register("find", &find{})
}
func (cmd *find) Register(ctx context.Context, f *flag.FlagSet) {
cmd.DatacenterFlag, ctx = flags.NewDatacenterFlag(ctx)
cmd.DatacenterFlag.Register(ctx, f)
f.Var(&cmd.kind, "type", "Resource type")
f.StringVar(&cmd.name, "name", "*", "Resource name")
f.IntVar(&cmd.maxdepth, "maxdepth", -1, "Max depth")
f.BoolVar(&cmd.ref, "i", false, "Print the managed object reference")
f.BoolVar(&cmd.long, "l", false, "Long listing format")
f.BoolVar(&cmd.parent, "p", false, "Find parent objects")
}
func (cmd *find) Usage() string {
return "[ROOT] [KEY VAL]..."
}
func (cmd *find) Description() string {
atable := aliasHelp()
return fmt.Sprintf(`Find managed objects.
ROOT can be an inventory path or ManagedObjectReference.
ROOT defaults to '.', an alias for the root folder or DC if set.
Optional KEY VAL pairs can be used to filter results against object instance properties.
Use the govc 'object.collect' command to view possible object property keys.
The '-type' flag value can be a managed entity type or one of the following aliases:
%s
Examples:
govc find
govc find -l / # include object type in output
govc find /dc1 -type c
govc find vm -name my-vm-*
govc find . -type n
govc find -p /folder-a/dc-1/host/folder-b/cluster-a -type Datacenter # prints /folder-a/dc-1
govc find . -type m -runtime.powerState poweredOn
govc find . -type m -datastore $(govc find -i datastore -name vsanDatastore)
govc find . -type s -summary.type vsan
govc find . -type s -customValue *:prod # Key:Value
govc find . -type h -hardware.cpuInfo.numCpuCores 16`, atable)
}
// rootMatch returns true if the root object path should be printed
func (cmd *find) rootMatch(ctx context.Context, root object.Reference, client *vim25.Client, filter property.Filter) bool {
ref := root.Reference()
if !cmd.kind.wanted(ref.Type) {
return false
}
if len(filter) == 1 && filter["name"] == "*" {
return true
}
var content []types.ObjectContent
pc := property.DefaultCollector(client)
_ = pc.RetrieveWithFilter(ctx, []types.ManagedObjectReference{ref}, filter.Keys(), &content, filter)
return content != nil
}
type findResult []string
func (r findResult) Write(w io.Writer) error {
for i := range r {
fmt.Fprintln(w, r[i])
}
return nil
}
func (r findResult) Dump() interface{} {
return []string(r)
}
type findResultLong []string
func (r findResultLong) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)
for i := range r {
fmt.Fprintln(tw, r[i])
}
return tw.Flush()
}
func (cmd *find) writeResult(paths []string) error {
if cmd.long {
return cmd.WriteResult(findResultLong(paths))
}
return cmd.WriteResult(findResult(paths))
}
func (cmd *find) Run(ctx context.Context, f *flag.FlagSet) error {
client, err := cmd.Client()
if err != nil {
return err
}
finder, err := cmd.Finder()
if err != nil {
return err
}
root := client.ServiceContent.RootFolder
rootPath := "/"
arg := f.Arg(0)
props := f.Args()
if len(props) > 0 {
if strings.HasPrefix(arg, "-") {
arg = "."
} else {
props = props[1:]
}
}
if len(props)%2 != 0 {
return flag.ErrHelp
}
dc, err := cmd.DatacenterIfSpecified()
if err != nil {
return err
}
switch arg {
case rootPath:
case "", ".":
if dc == nil {
arg = rootPath
} else {
arg = "."
root = dc.Reference()
rootPath = dc.InventoryPath
}
default:
path := arg
if !strings.Contains(arg, "/") {
// Force list mode
p := "."
if dc != nil {
p = dc.InventoryPath
}
path = strings.Join([]string{p, arg}, "/")
}
l, ferr := finder.ManagedObjectList(ctx, path)
if ferr != nil {
return err
}
switch len(l) {
case 0:
return fmt.Errorf("%s not found", arg)
case 1:
root = l[0].Object.Reference()
rootPath = l[0].Path
default:
return fmt.Errorf("%q matches %d objects", arg, len(l))
}
}
filter := property.Filter{}
if len(props)%2 != 0 {
return flag.ErrHelp
}
for i := 0; i < len(props); i++ {
key := props[i]
if !strings.HasPrefix(key, "-") {
return flag.ErrHelp
}
key = key[1:]
i++
val := props[i]
if xf := f.Lookup(key); xf != nil {
// Support use of -flag following the ROOT arg (flag package does not do this)
if err = xf.Value.Set(val); err != nil {
return err
}
} else {
filter[key] = val
}
}
filter["name"] = cmd.name
var paths []string
printPath := func(o types.ManagedObjectReference, p string) {
if cmd.ref && !cmd.long {
paths = append(paths, o.String())
return
}
path := strings.Replace(p, rootPath, arg, 1)
if cmd.long {
id := strings.TrimPrefix(o.Type, "Vmware")
if cmd.ref {
id = o.String()
}
path = id + "\t" + path
}
paths = append(paths, path)
}
recurse := false
switch cmd.maxdepth {
case -1:
recurse = true
case 0:
case 1:
default:
return flag.ErrHelp // TODO: ?
}
if cmd.parent {
entities, err := mo.Ancestors(ctx, client, client.ServiceContent.PropertyCollector, root)
if err != nil {
return err
}
for i := len(entities) - 1; i >= 0; i-- {
if cmd.rootMatch(ctx, entities[i], client, filter) {
printPath(entities[i].Reference(), internal.InventoryPath(entities[:i+1]))
}
}
return cmd.writeResult(paths)
}
if cmd.rootMatch(ctx, root, client, filter) {
printPath(root, arg)
}
if cmd.maxdepth == 0 {
return cmd.writeResult(paths)
}
m := view.NewManager(client)
v, err := m.CreateContainerView(ctx, root, cmd.kind, recurse)
if err != nil {
return err
}
defer func() {
_ = v.Destroy(ctx)
}()
objs, err := v.Find(ctx, cmd.kind, filter)
if err != nil {
return err
}
for _, o := range objs {
var path string
if cmd.long || !cmd.ref {
e, err := finder.Element(ctx, o)
if err != nil {
if soap.IsSoapFault(err) {
_, ok := soap.ToSoapFault(err).VimFault().(types.ManagedObjectNotFound)
if ok {
continue // object was deleted after v.Find() returned
}
}
return err
}
path = e.Path
}
printPath(o, path)
}
return cmd.writeResult(paths)
}
|