Skip to content

Commit 3dec825

Browse files
committed
get hosts for dc
1 parent e8c409b commit 3dec825

File tree

7 files changed

+270
-31
lines changed

7 files changed

+270
-31
lines changed

plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/VmwareDatacenterService.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@
2222
import com.cloud.dc.VsphereStoragePolicy;
2323
import com.cloud.exception.DiscoveryException;
2424
import com.cloud.exception.ResourceInUseException;
25+
import com.cloud.hypervisor.vmware.mo.HostMO;
2526
import com.cloud.storage.StoragePool;
2627
import com.cloud.utils.Pair;
2728
import com.cloud.utils.component.PluggableService;
2829
import com.cloud.utils.exception.CloudRuntimeException;
2930
import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
3031
import org.apache.cloudstack.api.command.admin.zone.ImportVsphereStoragePoliciesCmd;
3132
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcVmsCmd;
33+
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcHostsCmd;
3234
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcsCmd;
3335
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePoliciesCmd;
3436
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePolicyCompatiblePoolsCmd;
@@ -54,5 +56,7 @@ public interface VmwareDatacenterService extends PluggableService {
5456

5557
List<StoragePool> listVsphereStoragePolicyCompatibleStoragePools(ListVsphereStoragePolicyCompatiblePoolsCmd cmd);
5658

59+
List<HostMO> listHostsInDatacenter(ListVmwareDcHostsCmd cmd);
60+
5761
Pair<String, List<UnmanagedInstanceTO>> listVMsInDatacenter(ListVmwareDcVmsCmd cmd);
5862
}

plugins/hypervisors/vmware/src/main/java/com/cloud/hypervisor/vmware/manager/VmwareManagerImpl.java

Lines changed: 85 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@
4848
import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
4949
import org.apache.cloudstack.api.command.admin.zone.ImportVsphereStoragePoliciesCmd;
5050
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcVmsCmd;
51+
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcHostsCmd;
52+
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcItems;
5153
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcsCmd;
5254
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePoliciesCmd;
5355
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePolicyCompatiblePoolsCmd;
@@ -179,6 +181,7 @@
179181
import com.vmware.vim25.InvalidLoginFaultMsg;
180182
import com.vmware.vim25.RuntimeFaultFaultMsg;
181183
import com.vmware.vim25.InvalidPropertyFaultMsg;
184+
import org.jetbrains.annotations.NotNull;
182185

183186
public class VmwareManagerImpl extends ManagerBase implements VmwareManager, VmwareStorageMount, Listener, VmwareDatacenterService, Configurable {
184187
private static final Logger s_logger = Logger.getLogger(VmwareManagerImpl.class);
@@ -1093,6 +1096,7 @@ public List<Class<?>> getCommands() {
10931096
cmdList.add(ListVsphereStoragePoliciesCmd.class);
10941097
cmdList.add(ListVsphereStoragePolicyCompatiblePoolsCmd.class);
10951098
cmdList.add(ListVmwareDcVmsCmd.class);
1099+
cmdList.add(ListVmwareDcHostsCmd.class);
10961100
return cmdList;
10971101
}
10981102

@@ -1561,15 +1565,79 @@ public List<StoragePool> listVsphereStoragePolicyCompatibleStoragePools(ListVsph
15611565
return compatiblePools;
15621566
}
15631567

1568+
@Override
1569+
public List<HostMO> listHostsInDatacenter(ListVmwareDcHostsCmd cmd) {
1570+
Integer maxObjects = cmd.getBatchSize();
1571+
String token = cmd.getToken();
1572+
1573+
VcenterData vmwaredc = getVcenterData(cmd);
1574+
1575+
try {
1576+
VmwareContext context = getVmwareContext(vmwaredc);
1577+
DatacenterMO dcMo = getDatacenterMO(context, vmwaredc);
1578+
return dcMo.getAllHostsOnDatacenter();
1579+
} catch (RuntimeFaultFaultMsg | URISyntaxException | VmwareClientException | InvalidLocaleFaultMsg |
1580+
InvalidLoginFaultMsg | InvalidPropertyFaultMsg e) {
1581+
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
1582+
vmwaredc.vcenter, vmwaredc.datacenterName, e.getMessage());
1583+
s_logger.error(errorMsg, e);
1584+
throw new CloudRuntimeException(errorMsg);
1585+
}
1586+
1587+
}
1588+
15641589
@Override
15651590
public Pair<String, List<UnmanagedInstanceTO>> listVMsInDatacenter(ListVmwareDcVmsCmd cmd) {
1591+
Integer maxObjects = cmd.getBatchSize();
1592+
String token = cmd.getToken();
1593+
1594+
VcenterData vmwaredc = getVcenterData(cmd);
1595+
1596+
try {
1597+
VmwareContext context = getVmwareContext(vmwaredc);
1598+
1599+
DatacenterMO dcMo = getDatacenterMO(context, vmwaredc);
1600+
return dcMo.getVmsOnDatacenter(maxObjects, token);
1601+
} catch (InvalidParameterValueException | VmwareClientException | InvalidLocaleFaultMsg | InvalidLoginFaultMsg |
1602+
RuntimeFaultFaultMsg | URISyntaxException | InvalidPropertyFaultMsg | InvocationTargetException |
1603+
NoSuchMethodException | IllegalAccessException e) {
1604+
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
1605+
vmwaredc.vcenter, vmwaredc.datacenterName, e.getMessage());
1606+
s_logger.error(errorMsg, e);
1607+
throw new CloudRuntimeException(errorMsg);
1608+
}
1609+
}
1610+
1611+
@NotNull
1612+
private static DatacenterMO getDatacenterMO(VmwareContext context, VcenterData vmwaredc) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
1613+
DatacenterMO dcMo = new DatacenterMO(context, vmwaredc.datacenterName);
1614+
ManagedObjectReference dcMor = dcMo.getMor();
1615+
if (dcMor == null) {
1616+
String msg = String.format("Unable to find VMware datacenter %s in vCenter %s",
1617+
vmwaredc.datacenterName, vmwaredc.vcenter);
1618+
s_logger.error(msg);
1619+
throw new InvalidParameterValueException(msg);
1620+
}
1621+
return dcMo;
1622+
}
1623+
1624+
@NotNull
1625+
private static VmwareContext getVmwareContext(VcenterData vmwaredc) throws RuntimeFaultFaultMsg, URISyntaxException, VmwareClientException, InvalidLocaleFaultMsg, InvalidLoginFaultMsg {
1626+
s_logger.debug(String.format("Connecting to the VMware datacenter %s at vCenter %s to retrieve VMs",
1627+
vmwaredc.datacenterName, vmwaredc.vcenter));
1628+
String serviceUrl = String.format("https://%s/sdk/vimService", vmwaredc.vcenter);
1629+
VmwareClient vimClient = new VmwareClient(vmwaredc.vcenter);
1630+
vimClient.connect(serviceUrl, vmwaredc.username, vmwaredc.password);
1631+
VmwareContext context = new VmwareContext(vimClient, vmwaredc.vcenter);
1632+
return context;
1633+
}
1634+
1635+
@NotNull
1636+
private VcenterData getVcenterData(ListVmwareDcItems cmd) {
15661637
String vcenter = cmd.getVcenter();
15671638
String datacenterName = cmd.getDatacenterName();
15681639
String username = cmd.getUsername();
15691640
String password = cmd.getPassword();
1570-
Integer maxObjects = cmd.getBatchSize();
1571-
String token = cmd.getToken();
1572-
15731641
Long existingVcenterId = cmd.getExistingVcenterId();
15741642

15751643
if ((existingVcenterId == null && StringUtils.isBlank(vcenter)) ||
@@ -1591,31 +1659,21 @@ public Pair<String, List<UnmanagedInstanceTO>> listVMsInDatacenter(ListVmwareDcV
15911659
username = vmwareDc.getUser();
15921660
password = vmwareDc.getPassword();
15931661
}
1662+
VcenterData vmwaredc = new VcenterData(vcenter, datacenterName, username, password);
1663+
return vmwaredc;
1664+
}
15941665

1595-
s_logger.debug(String.format("Connecting to the VMware datacenter %s at vCenter %s to retrieve VMs",
1596-
datacenterName, vcenter));
1597-
String serviceUrl = String.format("https://%s/sdk/vimService", vcenter);
1598-
VmwareClient vimClient = new VmwareClient(vcenter);
1599-
try {
1600-
vimClient.connect(serviceUrl, username, password);
1601-
VmwareContext context = new VmwareContext(vimClient, vcenter);
1666+
private static class VcenterData {
1667+
public final String vcenter;
1668+
public final String datacenterName;
1669+
public final String username;
1670+
public final String password;
16021671

1603-
DatacenterMO dcMo = new DatacenterMO(context, datacenterName);
1604-
ManagedObjectReference dcMor = dcMo.getMor();
1605-
if (dcMor == null) {
1606-
String msg = String.format("Unable to find VMware datacenter %s in vCenter %s",
1607-
datacenterName, vcenter);
1608-
s_logger.error(msg);
1609-
throw new InvalidParameterValueException(msg);
1610-
}
1611-
return dcMo.getVmsOnDatacenter(maxObjects, token);
1612-
} catch (InvalidParameterValueException | VmwareClientException | InvalidLocaleFaultMsg | InvalidLoginFaultMsg |
1613-
RuntimeFaultFaultMsg | URISyntaxException | InvalidPropertyFaultMsg | InvocationTargetException |
1614-
NoSuchMethodException | IllegalAccessException e) {
1615-
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
1616-
vcenter, datacenterName, e.getMessage());
1617-
s_logger.error(errorMsg, e);
1618-
throw new CloudRuntimeException(errorMsg);
1672+
public VcenterData(String vcenter, String datacenterName, String username, String password) {
1673+
this.vcenter = vcenter;
1674+
this.datacenterName = datacenterName;
1675+
this.username = username;
1676+
this.password = password;
16191677
}
16201678
}
16211679

@@ -1671,7 +1729,7 @@ private void startTemplateCleanJobSchedule() {
16711729
}
16721730

16731731
/**
1674-
* This task is to clean-up templates from primary storage that are otherwise not cleaned by the {@link com.cloud.storage.StorageManagerImpl.StorageGarbageCollector}.
1732+
* This task is to clean-up templates from primary storage that are otherwise not cleaned by the {@see com.cloud.storage.StorageManagerImpl.StorageGarbageCollector}.
16751733
* it is called at regular intervals when storage.template.cleanup.enabled == true
16761734
* It collect all templates that
16771735
* - are deleted from cloudstack
Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
package org.apache.cloudstack.api.command.admin.zone;
18+
19+
import com.cloud.exception.ConcurrentOperationException;
20+
import com.cloud.exception.InsufficientCapacityException;
21+
import com.cloud.exception.NetworkRuleConflictException;
22+
import com.cloud.exception.ResourceAllocationException;
23+
import com.cloud.exception.ResourceUnavailableException;
24+
import com.cloud.hypervisor.Hypervisor;
25+
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
26+
import com.cloud.hypervisor.vmware.mo.HostMO;
27+
import com.cloud.user.Account;
28+
import com.cloud.utils.exception.CloudRuntimeException;
29+
30+
import com.vmware.vim25.InvalidPropertyFaultMsg;
31+
import com.vmware.vim25.RuntimeFaultFaultMsg;
32+
33+
import org.apache.cloudstack.api.APICommand;
34+
import org.apache.cloudstack.api.ApiConstants;
35+
import org.apache.cloudstack.api.ApiErrorCode;
36+
import org.apache.cloudstack.api.BaseCmd;
37+
import org.apache.cloudstack.api.BaseResponse;
38+
import org.apache.cloudstack.api.Parameter;
39+
import org.apache.cloudstack.api.ServerApiException;
40+
import org.apache.cloudstack.api.response.HostResponse;
41+
import org.apache.cloudstack.api.response.VmwareDatacenterResponse;
42+
import org.apache.commons.collections.CollectionUtils;
43+
import org.apache.commons.lang3.StringUtils;
44+
45+
import javax.inject.Inject;
46+
import java.lang.reflect.InvocationTargetException;
47+
import java.util.ArrayList;
48+
import java.util.List;
49+
50+
@APICommand(name = "listVmwareDcHosts", responseObject = VmwareRequestReponse.class,
51+
description = "Lists the VMs in a VMware Datacenter",
52+
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
53+
public class ListVmwareDcHostsCmd extends BaseCmd implements ListVmwareDcItems {
54+
55+
@Inject
56+
public VmwareDatacenterService _vmwareDatacenterService;
57+
58+
@Parameter(name = ApiConstants.EXISTING_VCENTER_ID,
59+
type = CommandType.UUID,
60+
entityType = VmwareDatacenterResponse.class,
61+
description = "UUID of a linked existing vCenter")
62+
private Long existingVcenterId;
63+
64+
@Parameter(name = ApiConstants.VCENTER,
65+
type = CommandType.STRING,
66+
description = "The name/ip of vCenter. Make sure it is IP address or full qualified domain name for host running vCenter server.")
67+
private String vcenter;
68+
69+
@Parameter(name = ApiConstants.DATACENTER_NAME, type = CommandType.STRING, description = "Name of VMware datacenter.")
70+
private String datacenterName;
71+
72+
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "The Username required to connect to resource.")
73+
private String username;
74+
75+
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "The password for specified username.")
76+
private String password;
77+
78+
@Parameter(name = ApiConstants.BATCH_SIZE, type = CommandType.INTEGER, description = "The maximum number of results to return.")
79+
private Integer batchSize;
80+
81+
@Parameter(name = ApiConstants.TOKEN, type = CommandType.STRING,
82+
description = "For listVmwareDcVms, if the maximum number of results (the `batchsize`) is exceeded, " +
83+
" a token is returned. This token can be used in subsequent calls to retrieve more results." +
84+
" As long as a token is returned, more results can be retrieved.")
85+
private String token;
86+
87+
public String getVcenter() {
88+
return vcenter;
89+
}
90+
91+
public String getUsername() {
92+
return username;
93+
}
94+
95+
public String getPassword() {
96+
return password;
97+
}
98+
99+
public Integer getBatchSize() {
100+
return batchSize;
101+
}
102+
103+
public String getToken() {
104+
return token;
105+
}
106+
107+
public String getDatacenterName() {
108+
return datacenterName;
109+
}
110+
111+
public Long getExistingVcenterId() {
112+
return existingVcenterId;
113+
}
114+
115+
@Override
116+
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
117+
checkParameters();
118+
try {
119+
List<HostMO> hosts = _vmwareDatacenterService.listHostsInDatacenter(this);
120+
List<BaseResponse> baseResponseList = new ArrayList<>();
121+
if (CollectionUtils.isNotEmpty(hosts)) {
122+
for (HostMO vmwareHost : hosts) {
123+
HostResponse resp = createHostResponse(vmwareHost);
124+
baseResponseList.add(resp);
125+
}
126+
}
127+
VmwareRequestReponse<BaseResponse> response = new VmwareRequestReponse<>();
128+
response.setResponses(baseResponseList, baseResponseList.size());
129+
response.setResponseName(getCommandName());
130+
setResponseObject(response);
131+
} catch (CloudRuntimeException | InvalidPropertyFaultMsg | RuntimeFaultFaultMsg | InvocationTargetException |
132+
NoSuchMethodException | IllegalAccessException e) {
133+
String errorMsg = String.format("Error retrieving VMs from VMware VC: %s", e.getMessage());
134+
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
135+
}
136+
}
137+
138+
private HostResponse createHostResponse(HostMO hostInstance) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
139+
HostResponse response = new HostResponse();
140+
response.setHypervisor(Hypervisor.HypervisorType.VMware.toString());
141+
response.setName(hostInstance.getHostName());
142+
return response;
143+
}
144+
145+
146+
private void checkParameters() {
147+
if ((existingVcenterId == null && vcenter == null) || (existingVcenterId != null && vcenter != null)) {
148+
throw new ServerApiException(ApiErrorCode.PARAM_ERROR,
149+
"Please provide an existing vCenter ID or a vCenter IP/Name, parameters are mutually exclusive");
150+
}
151+
if (existingVcenterId == null && StringUtils.isAnyBlank(vcenter, datacenterName, username, password)) {
152+
throw new ServerApiException(ApiErrorCode.PARAM_ERROR,
153+
"Please set all the information for a vCenter IP/Name, datacenter, username and password");
154+
}
155+
}
156+
157+
@Override
158+
public long getEntityOwnerId() {
159+
return Account.ACCOUNT_ID_SYSTEM;
160+
}
161+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.apache.cloudstack.api.command.admin.zone;
2+
3+
public interface ListVmwareDcItems {
4+
String getVcenter();
5+
6+
String getDatacenterName();
7+
8+
String getUsername();
9+
10+
String getPassword();
11+
12+
Long getExistingVcenterId();
13+
}

plugins/hypervisors/vmware/src/main/java/org/apache/cloudstack/api/command/admin/zone/ListVmwareDcVmsCmd.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
@APICommand(name = "listVmwareDcVms", responseObject = VmwareRequestReponse.class,
4646
description = "Lists the VMs in a VMware Datacenter",
4747
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
48-
public class ListVmwareDcVmsCmd extends BaseCmd {
48+
public class ListVmwareDcVmsCmd extends BaseCmd implements ListVmwareDcItems {
4949

5050
@Inject
5151
public VmwareDatacenterService _vmwareDatacenterService;

vmware-base/src/main/java/com/cloud/hypervisor/vmware/mo/DatacenterMO.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ public Pair<String, List<UnmanagedInstanceTO>> getVmsOnDatacenter(Integer maxObj
180180
return retval;
181181
}
182182

183-
public List<HostMO> getAllHostsOnDatacenter() throws Exception {
183+
public List<HostMO> getAllHostsOnDatacenter() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
184184
List<HostMO> hosts = new ArrayList<>();
185185

186186
List<ObjectContent> ocs = getHostPropertiesOnDatacenterHostFolder(new String[] {"name"});
@@ -224,7 +224,7 @@ public ManagedObjectReference getVmFolder() throws Exception {
224224
return _context.getVimClient().getDynamicProperty(_mor, "vmFolder");
225225
}
226226

227-
public List<ObjectContent> getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception {
227+
public List<ObjectContent> getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
228228
PropertySpec pSpec = new PropertySpec();
229229
pSpec.setType("HostSystem");
230230
pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));

0 commit comments

Comments
 (0)