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	"fmt"
22
23	"github.com/vmware/govmomi/vim25"
24	"github.com/vmware/govmomi/vim25/methods"
25	"github.com/vmware/govmomi/vim25/mo"
26	"github.com/vmware/govmomi/vim25/types"
27)
28
29type DistributedVirtualPortgroup struct {
30	Common
31}
32
33func NewDistributedVirtualPortgroup(c *vim25.Client, ref types.ManagedObjectReference) *DistributedVirtualPortgroup {
34	return &DistributedVirtualPortgroup{
35		Common: NewCommon(c, ref),
36	}
37}
38
39// EthernetCardBackingInfo returns the VirtualDeviceBackingInfo for this DistributedVirtualPortgroup
40func (p DistributedVirtualPortgroup) EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error) {
41	var dvp mo.DistributedVirtualPortgroup
42	var dvs mo.DistributedVirtualSwitch
43	prop := "config.distributedVirtualSwitch"
44
45	if err := p.Properties(ctx, p.Reference(), []string{"key", prop}, &dvp); err != nil {
46		return nil, err
47	}
48
49	// "This property should always be set unless the user's setting does not have System.Read privilege on the object referred to by this property."
50	if dvp.Config.DistributedVirtualSwitch == nil {
51		return nil, fmt.Errorf("no System.Read privilege on: %s.%s", p.Reference(), prop)
52	}
53
54	if err := p.Properties(ctx, *dvp.Config.DistributedVirtualSwitch, []string{"uuid"}, &dvs); err != nil {
55		return nil, err
56	}
57
58	backing := &types.VirtualEthernetCardDistributedVirtualPortBackingInfo{
59		Port: types.DistributedVirtualSwitchPortConnection{
60			PortgroupKey: dvp.Key,
61			SwitchUuid:   dvs.Uuid,
62		},
63	}
64
65	return backing, nil
66}
67
68func (p DistributedVirtualPortgroup) Reconfigure(ctx context.Context, spec types.DVPortgroupConfigSpec) (*Task, error) {
69	req := types.ReconfigureDVPortgroup_Task{
70		This: p.Reference(),
71		Spec: spec,
72	}
73
74	res, err := methods.ReconfigureDVPortgroup_Task(ctx, p.Client(), &req)
75	if err != nil {
76		return nil, err
77	}
78
79	return NewTask(p.Client(), res.Returnval), nil
80}
81