1/*
2Copyright (c) 2015 VMware, Inc. All Rights Reserved.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package object
18
19import (
20	"context"
21	"path"
22
23	"github.com/vmware/govmomi/property"
24	"github.com/vmware/govmomi/vim25"
25	"github.com/vmware/govmomi/vim25/methods"
26	"github.com/vmware/govmomi/vim25/mo"
27	"github.com/vmware/govmomi/vim25/types"
28)
29
30type ComputeResource struct {
31	Common
32}
33
34func NewComputeResource(c *vim25.Client, ref types.ManagedObjectReference) *ComputeResource {
35	return &ComputeResource{
36		Common: NewCommon(c, ref),
37	}
38}
39
40func (c ComputeResource) Hosts(ctx context.Context) ([]*HostSystem, error) {
41	var cr mo.ComputeResource
42
43	err := c.Properties(ctx, c.Reference(), []string{"host"}, &cr)
44	if err != nil {
45		return nil, err
46	}
47
48	if len(cr.Host) == 0 {
49		return nil, nil
50	}
51
52	var hs []mo.HostSystem
53	pc := property.DefaultCollector(c.Client())
54	err = pc.Retrieve(ctx, cr.Host, []string{"name"}, &hs)
55	if err != nil {
56		return nil, err
57	}
58
59	var hosts []*HostSystem
60
61	for _, h := range hs {
62		host := NewHostSystem(c.Client(), h.Reference())
63		host.InventoryPath = path.Join(c.InventoryPath, h.Name)
64		hosts = append(hosts, host)
65	}
66
67	return hosts, nil
68}
69
70func (c ComputeResource) Datastores(ctx context.Context) ([]*Datastore, error) {
71	var cr mo.ComputeResource
72
73	err := c.Properties(ctx, c.Reference(), []string{"datastore"}, &cr)
74	if err != nil {
75		return nil, err
76	}
77
78	var dss []*Datastore
79	for _, ref := range cr.Datastore {
80		ds := NewDatastore(c.c, ref)
81		dss = append(dss, ds)
82	}
83
84	return dss, nil
85}
86
87func (c ComputeResource) ResourcePool(ctx context.Context) (*ResourcePool, error) {
88	var cr mo.ComputeResource
89
90	err := c.Properties(ctx, c.Reference(), []string{"resourcePool"}, &cr)
91	if err != nil {
92		return nil, err
93	}
94
95	return NewResourcePool(c.c, *cr.ResourcePool), nil
96}
97
98func (c ComputeResource) Reconfigure(ctx context.Context, spec types.BaseComputeResourceConfigSpec, modify bool) (*Task, error) {
99	req := types.ReconfigureComputeResource_Task{
100		This:   c.Reference(),
101		Spec:   spec,
102		Modify: modify,
103	}
104
105	res, err := methods.ReconfigureComputeResource_Task(ctx, c.c, &req)
106	if err != nil {
107		return nil, err
108	}
109
110	return NewTask(c.c, res.Returnval), nil
111}
112