forked from hashicorp/terraform-provider-vsphere
-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_system_helper.go
72 lines (63 loc) · 2.09 KB
/
host_system_helper.go
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
package vsphere
import (
"context"
"fmt"
"github.com/vmware/govmomi"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25/types"
)
// hostSystemOrDefault returns a HostSystem from a specific host name and
// datacenter. If the user is connecting over ESXi, the default host system is
// used.
func hostSystemOrDefault(client *govmomi.Client, name string, dc *object.Datacenter) (*object.HostSystem, error) {
finder := find.NewFinder(client.Client, false)
finder.SetDatacenter(dc)
ctx, cancel := context.WithTimeout(context.Background(), defaultAPITimeout)
defer cancel()
t := client.ServiceContent.About.ApiType
switch t {
case "HostAgent":
return finder.DefaultHostSystem(ctx)
case "VirtualCenter":
if name != "" {
return finder.HostSystem(ctx, name)
}
return finder.DefaultHostSystem(ctx)
}
return nil, fmt.Errorf("unsupported ApiType: %s", t)
}
// hostSystemFromID locates a HostSystem by its managed object reference ID.
func hostSystemFromID(client *govmomi.Client, id string) (*object.HostSystem, error) {
finder := find.NewFinder(client.Client, false)
ref := types.ManagedObjectReference{
Type: "HostSystem",
Value: id,
}
ctx, cancel := context.WithTimeout(context.Background(), defaultAPITimeout)
defer cancel()
ds, err := finder.ObjectReference(ctx, ref)
if err != nil {
return nil, fmt.Errorf("could not find host system with id: %s: %s", id, err)
}
return ds.(*object.HostSystem), nil
}
// hostSystemNameFromID returns the name of a host via its its managed object
// reference ID.
func hostSystemNameFromID(client *govmomi.Client, id string) (string, error) {
hs, err := hostSystemFromID(client, id)
if err != nil {
return "", err
}
return hs.Name(), nil
}
// hostSystemNameOrID is a convenience method mainly for helping displaying friendly
// errors where space is important - it displays either the host name or the ID
// if there was an error fetching it.
func hostSystemNameOrID(client *govmomi.Client, id string) string {
name, err := hostSystemNameFromID(client, id)
if err != nil {
return id
}
return name
}