Merge remote-tracking branch 'origin/4.17'

This commit is contained in:
Rohit Yadav 2022-12-12 13:29:28 +05:30
commit 1be7c2f348
8 changed files with 201 additions and 53 deletions

View File

@ -17,16 +17,18 @@
package org.apache.cloudstack.api;
import java.util.List;
import javax.inject.Inject;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.command.user.UserCmd;
import org.apache.cloudstack.api.command.user.vm.ListVMsCmd;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.metrics.MetricsService;
import org.apache.cloudstack.response.VmMetricsResponse;
import javax.inject.Inject;
import java.util.List;
/**
* API supported for backward compatibility. Use the {@link ListVMsUsageHistoryCmd} API instead. <br>
* The reasons for this are: <br>
@ -42,9 +44,8 @@ import java.util.List;
*/
@APICommand(name = ListVMsMetricsCmd.APINAME, description = "Lists VM metrics", responseObject = VmMetricsResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, responseView = ResponseObject.ResponseView.Full,
since = "4.9.3", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User})
@Deprecated(since = "4.17.0")
public class ListVMsMetricsCmd extends ListVMsCmd {
since = "4.9.3", authorized = {RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User})
public class ListVMsMetricsCmd extends ListVMsCmd implements UserCmd {
public static final String APINAME = "listVirtualMachinesMetrics";
@Inject

View File

@ -0,0 +1,73 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 org.apache.cloudstack.api;
import org.apache.cloudstack.acl.RoleType;
import org.apache.cloudstack.api.command.admin.AdminCmd;
import org.apache.cloudstack.api.response.ClusterResponse;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.PodResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.response.VmMetricsResponse;
@APICommand(name = ListVMsMetricsCmd.APINAME, description = "Lists VM metrics", responseObject = VmMetricsResponse.class,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false, responseView = ResponseObject.ResponseView.Full,
authorized = {RoleType.Admin})
public class ListVMsMetricsCmdByAdmin extends ListVMsMetricsCmd implements AdminCmd {
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@Parameter(name=ApiConstants.HOST_ID, type= BaseCmd.CommandType.UUID, entityType= HostResponse.class,
description="the host ID")
private Long hostId;
@Parameter(name=ApiConstants.POD_ID, type= BaseCmd.CommandType.UUID, entityType= PodResponse.class,
description="the pod ID")
private Long podId;
@Parameter(name=ApiConstants.STORAGE_ID, type= BaseCmd.CommandType.UUID, entityType= StoragePoolResponse.class,
description="the storage ID where vm's volumes belong to")
private Long storageId;
@Parameter(name = ApiConstants.CLUSTER_ID, type = BaseCmd.CommandType.UUID, entityType = ClusterResponse.class,
description = "the cluster ID")
private Long clusterId;
/////////////////////////////////////////////////////
/////////////////// Accessors ///////////////////////
/////////////////////////////////////////////////////
public Long getHostId() {
return hostId;
}
public Long getPodId() {
return podId;
}
public Long getStorageId() {
return storageId;
}
public Long getClusterId() {
return clusterId;
}
}

View File

@ -17,6 +17,8 @@
package org.apache.cloudstack.metrics;
import static com.cloud.utils.NumbersUtil.toReadableSize;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
@ -28,14 +30,6 @@ import java.util.Properties;
import javax.inject.Inject;
import com.cloud.server.DbStatsCollection;
import com.cloud.server.StatsCollector;
import com.cloud.usage.UsageJobVO;
import com.cloud.usage.dao.UsageJobDao;
import com.cloud.utils.db.DbProperties;
import com.cloud.utils.db.DbUtil;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.script.Script;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.ListClustersMetricsCmd;
import org.apache.cloudstack.api.ListDbMetricsCmd;
@ -45,6 +39,7 @@ import org.apache.cloudstack.api.ListMgmtsMetricsCmd;
import org.apache.cloudstack.api.ListStoragePoolsMetricsCmd;
import org.apache.cloudstack.api.ListUsageServerMetricsCmd;
import org.apache.cloudstack.api.ListVMsMetricsCmd;
import org.apache.cloudstack.api.ListVMsMetricsCmdByAdmin;
import org.apache.cloudstack.api.ListVMsUsageHistoryCmd;
import org.apache.cloudstack.api.ListVolumesMetricsCmd;
import org.apache.cloudstack.api.ListZonesMetricsCmd;
@ -52,8 +47,8 @@ import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ClusterResponse;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.StatsResponse;
import org.apache.cloudstack.api.response.ManagementServerResponse;
import org.apache.cloudstack.api.response.StatsResponse;
import org.apache.cloudstack.api.response.StoragePoolResponse;
import org.apache.cloudstack.api.response.UserVmResponse;
import org.apache.cloudstack.api.response.VolumeResponse;
@ -76,6 +71,10 @@ import org.apache.cloudstack.storage.datastore.db.ImageStoreDao;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.log4j.Logger;
import com.cloud.agent.api.VmStatsEntryBase;
import com.cloud.alert.AlertManager;
@ -103,13 +102,21 @@ import com.cloud.network.router.VirtualRouter;
import com.cloud.org.Cluster;
import com.cloud.org.Grouping;
import com.cloud.org.Managed;
import com.cloud.server.DbStatsCollection;
import com.cloud.server.ManagementServerHostStats;
import com.cloud.server.StatsCollector;
import com.cloud.usage.UsageJobVO;
import com.cloud.usage.dao.UsageJobDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.utils.Pair;
import com.cloud.utils.db.DbProperties;
import com.cloud.utils.db.DbUtil;
import com.cloud.utils.db.Filter;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.script.Script;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VMInstanceVO;
import com.cloud.vm.VirtualMachine;
@ -119,12 +126,6 @@ import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.dao.VmStatsDao;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.log4j.Logger;
import static com.cloud.utils.NumbersUtil.toReadableSize;
public class MetricsServiceImpl extends MutualExclusiveIdsManagerBase implements MetricsService {
private static final Logger LOGGER = Logger.getLogger(MetricsServiceImpl.class);
@ -878,6 +879,9 @@ public class MetricsServiceImpl extends MutualExclusiveIdsManagerBase implements
cmdList.add(ListVolumesMetricsCmd.class);
cmdList.add(ListZonesMetricsCmd.class);
cmdList.add(ListVMsUsageHistoryCmd.class);
// separate Admin commands
cmdList.add(ListVMsMetricsCmdByAdmin.class);
return cmdList;
}

View File

@ -16,6 +16,8 @@
// under the License.
package com.cloud.api.query;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -65,7 +67,6 @@ import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd;
import org.apache.cloudstack.api.command.admin.storage.ListStorageTagsCmd;
import org.apache.cloudstack.api.command.admin.template.ListTemplatesCmdByAdmin;
import org.apache.cloudstack.api.command.admin.user.ListUsersCmd;
import org.apache.cloudstack.api.command.admin.vm.ListVMsCmdByAdmin;
import org.apache.cloudstack.api.command.admin.zone.ListZonesCmdByAdmin;
import org.apache.cloudstack.api.command.user.account.ListAccountsCmd;
import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd;
@ -972,6 +973,17 @@ public class QueryManagerImpl extends MutualExclusiveIdsManagerBase implements Q
return response;
}
private Object getObjectPossibleMethodValue(Object obj, String methodName) {
Object result = null;
try {
Method m = obj.getClass().getMethod(methodName);
result = m.invoke(obj);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) {}
return result;
}
private Pair<List<UserVmJoinVO>, Integer> searchForUserVMsInternal(ListVMsCmd cmd) {
Account caller = CallContext.current().getCallingAccount();
List<Long> permittedAccounts = new ArrayList<Long>();
@ -1037,16 +1049,14 @@ public class QueryManagerImpl extends MutualExclusiveIdsManagerBase implements Q
Object isHaEnabled = cmd.getHaEnabled();
Object autoScaleVmGroupId = cmd.getAutoScaleVmGroupId();
Object pod = null;
Long clusterId = null;
Object clusterId = null;
Object hostId = null;
Object storageId = null;
if (_accountMgr.isRootAdmin(caller.getId())) {
if (cmd instanceof ListVMsCmdByAdmin) {
pod = ((ListVMsCmdByAdmin) cmd).getPodId();
clusterId = ((ListVMsCmdByAdmin) cmd).getClusterId();
hostId = ((ListVMsCmdByAdmin) cmd).getHostId();
storageId = ((ListVMsCmdByAdmin) cmd).getStorageId();
}
pod = getObjectPossibleMethodValue(cmd, "getPodId");
clusterId = getObjectPossibleMethodValue(cmd, "getClusterId");
hostId = getObjectPossibleMethodValue(cmd, "getHostId");
storageId = getObjectPossibleMethodValue(cmd, "getStorageId");
}
sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE);

View File

@ -698,8 +698,8 @@ public class UnmanagedVMsManagerImpl implements UnmanagedVMsManager {
return new Pair<DiskProfile, StoragePool>(profile, storagePool);
}
private NicProfile importNic(UnmanagedInstanceTO.Nic nic, VirtualMachine vm, Network network, Network.IpAddresses ipAddresses, boolean isDefaultNic, boolean forced) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
Pair<NicProfile, Integer> result = networkOrchestrationService.importNic(nic.getMacAddress(), 0, network, isDefaultNic, vm, ipAddresses, forced);
private NicProfile importNic(UnmanagedInstanceTO.Nic nic, VirtualMachine vm, Network network, Network.IpAddresses ipAddresses, int deviceId, boolean isDefaultNic, boolean forced) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException {
Pair<NicProfile, Integer> result = networkOrchestrationService.importNic(nic.getMacAddress(), deviceId, network, isDefaultNic, vm, ipAddresses, forced);
if (result == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("NIC ID: %s import failed", nic.getNicId()));
}
@ -1016,12 +1016,12 @@ public class UnmanagedVMsManagerImpl implements UnmanagedVMsManager {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, String.format("Failed to import volumes while importing vm: %s. %s", instanceName, StringUtils.defaultString(e.getMessage())));
}
try {
boolean firstNic = true;
int nicIndex = 0;
for (UnmanagedInstanceTO.Nic nic : unmanagedInstance.getNics()) {
Network network = networkDao.findById(allNicNetworkMap.get(nic.getNicId()));
Network.IpAddresses ipAddresses = nicIpAddressMap.get(nic.getNicId());
importNic(nic, userVm, network, ipAddresses, firstNic, forced);
firstNic = false;
importNic(nic, userVm, network, ipAddresses, nicIndex, nicIndex==0, forced);
nicIndex++;
}
} catch (Exception e) {
LOGGER.error(String.format("Failed to import NICs while importing vm: %s", instanceName), e);

View File

@ -188,6 +188,7 @@ setup_interface_sshd() {
setup_sshd $ETH1_IP "eth1"
elif [ "$TYPE" == "vpcrouter" ]; then
init_interfaces "eth0"
setup_interface "0" $ETH0_IP $ETH0_MASK $GW
setup_sshd $ETH0_IP "eth0"

View File

@ -25,11 +25,6 @@ setup_vpcrouter() {
grep -q $NAME /etc/hosts || echo "127.0.0.1 $NAME" >> /etc/hosts;
fi
cat > /etc/network/interfaces << EOF
auto lo eth0
iface lo inet loopback
EOF
echo $NAME > /etc/hostname
echo 'AVAHI_DAEMON_DETECT_LOCAL=0' > /etc/default/avahi-daemon
hostnamectl set-hostname $NAME

View File

@ -60,6 +60,8 @@ class TestUnmanageVM(cloudstackTestCase):
assert False, "get_suitable_test_template() failed to return template with description %s" % cls.services["ostype"]
cls.hypervisorNotSupported = cls.hypervisor.lower() != "vmware"
if cls.hypervisorNotSupported:
return
cls.services["small"]["zoneid"] = cls.zone.id
cls.services["small"]["template"] = cls.template.id
@ -83,6 +85,12 @@ class TestUnmanageVM(cloudstackTestCase):
)
cls._cleanup.append(cls.network_offering)
cls.network_offering.update(cls.apiclient, state='Enabled')
cls.isolated_network_offering = NetworkOffering.create(
cls.apiclient,
cls.services["nw_off_isolated_persistent"],
)
cls._cleanup.append(cls.isolated_network_offering)
cls.isolated_network_offering.update(cls.apiclient, state='Enabled')
@classmethod
def tearDownClass(cls):
@ -91,17 +99,41 @@ class TestUnmanageVM(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
self.created_networks = []
self.virtual_machine = None
self.unmanaged_instance = None
self.imported_vm = None
if self.hypervisorNotSupported:
return
self.services["network"]["networkoffering"] = self.network_offering.id
network_data = self.services["l2-network"]
self.network = Network.create(
self.apiclient,
self.services["l2-network"],
network_data,
zoneid=self.zone.id,
networkofferingid=self.network_offering.id
)
self.cleanup = [
self.network
]
self.unmanaged_instance = None
self.cleanup.append(self.network)
self.created_networks.append(self.network)
network_data['name'] = "Test L2 Network1"
network_data['displaytext'] = "Test L2 Network1"
self.network1 = Network.create(
self.apiclient,
network_data,
zoneid=self.zone.id,
networkofferingid=self.network_offering.id
)
self.cleanup.append(self.network1)
self.created_networks.append(self.network1)
self.network2 = Network.create(
self.apiclient,
self.services["isolated_network"],
zoneid=self.zone.id,
networkofferingid=self.isolated_network_offering.id
)
self.cleanup.append(self.network2)
self.created_networks.append(self.network2)
'''
Fetch vmware datacenter login details
@ -128,6 +160,9 @@ class TestUnmanageVM(cloudstackTestCase):
self.delete_vcenter_vm(self.unmanaged_instance)
except Exception as e:
print("Warning: Exception during cleaning up vCenter VM: %s : %s" % (self.unmanaged_instance, e))
else:
if self.virtual_machine is not None and self.imported_vm is None:
self.cleanup.append(self.virtual_machine)
super(TestUnmanageVM, self).tearDown()
def check_vm_state(self, vm_id):
@ -158,7 +193,8 @@ class TestUnmanageVM(cloudstackTestCase):
3. Verify VM is not listed in CloudStack
4. Verify VM is listed as part of the unmanaged instances
5. Import VM
6. Destroy VM
6. Verify details of imported VM
7. Destroy VM
"""
# 1 - Deploy VM
@ -167,11 +203,18 @@ class TestUnmanageVM(cloudstackTestCase):
self.services["virtual_machine"],
templateid=self.template.id,
serviceofferingid=self.small_offering.id,
networkids=self.network.id,
networkids=[self.network.id, self.network1.id, self.network2.id],
zoneid=self.zone.id
)
vm_id = self.virtual_machine.id
vm_instance_name = self.virtual_machine.instancename
networks = []
for network in self.created_networks:
n = Network.list(
self.apiclient,
id=network.id
)[0]
networks.append(n)
hostid = self.virtual_machine.hostid
hosts = Host.list(
self.apiclient,
@ -212,13 +255,20 @@ class TestUnmanageVM(cloudstackTestCase):
)
# 5 - Import VM
unmanaged_vm_nic = unmanaged_vm.nic[0]
nicnetworklist = [{}]
nicnetworklist[0]["nic"] = unmanaged_vm_nic.id
nicnetworklist[0]["network"] = self.network.id
nicipaddresslist = [{}]
if self.network.type == "Isolated":
nicipaddresslist[0]["nic"] = unmanaged_vm_nic.id
nicipaddresslist[0]["ip4Address"] = "auto"
nicnetworklist = []
nicipaddresslist = []
for nic in unmanaged_vm.nic:
for network in networks:
if int(network.vlan) == int(nic.vlanid):
nicnetworklist.append({
"nic": nic.id,
"network": network.id
})
if network.type == "Isolated":
nicipaddresslist.append({
"nic": nic.id,
"ip4Address": "auto"
})
import_vm_service = {
"nicnetworklist": nicnetworklist,
"nicipaddresslist": nicipaddresslist
@ -232,6 +282,7 @@ class TestUnmanageVM(cloudstackTestCase):
templateid=self.template.id)
self.cleanup.append(self.imported_vm)
self.unmanaged_instance = None
# 6 - Verify details of the imported VM
self.assertEqual(
self.small_offering.id,
self.imported_vm.serviceofferingid,
@ -242,4 +293,17 @@ class TestUnmanageVM(cloudstackTestCase):
self.imported_vm.templateid,
"Imported VM template is different, expected: %s, actual: %s" % (self.template.id, self.imported_vm.templateid)
)
self.assertEqual(
len(nicnetworklist),
len(self.imported_vm.nic),
"Imported VM number of NICs is different, expected: %d, actual: %d" % (len(nicnetworklist), len(self.imported_vm.nic))
)
for nic in self.imported_vm.nic:
index = int(nic.deviceid) # device id of imported nics will be in order of their import
self.assertEqual(
nicnetworklist[index]["network"],
nic.networkid,
"Imported VM NIC with id: %s has wrong network, expected: %s, actual: %s" % (nic.id, nicnetworklist[index]["network"], nic.networkid)
)
self.check_vm_state(self.imported_vm.id)
# 7 - Destroy VM. This will be done during cleanup