use of com.cloud.vm.NicVO in project cloudstack by apache.
the class NetworkOrchestratorTest method testRemoveDhcpServiceWithNic.
@Test
public void testRemoveDhcpServiceWithNic() {
// make local mocks
VirtualMachineProfile vm = mock(VirtualMachineProfile.class);
NicVO nic = mock(NicVO.class);
NetworkVO network = mock(NetworkVO.class);
// make sure that release dhcp will be called
when(vm.getType()).thenReturn(Type.User);
when(testOrchastrator._networkModel.areServicesSupportedInNetwork(network.getId(), Service.Dhcp)).thenReturn(true);
when(network.getTrafficType()).thenReturn(TrafficType.Guest);
when(network.getGuestType()).thenReturn(GuestType.Shared);
when(testOrchastrator._nicDao.listByNetworkIdTypeAndGatewayAndBroadcastUri(nic.getNetworkId(), VirtualMachine.Type.User, nic.getIPv4Gateway(), nic.getBroadcastUri())).thenReturn(new ArrayList<NicVO>());
when(network.getGuruName()).thenReturn(guruName);
when(testOrchastrator._networksDao.findById(nic.getNetworkId())).thenReturn(network);
testOrchastrator.removeNic(vm, nic);
verify(nic, times(1)).setState(Nic.State.Deallocating);
verify(testOrchastrator._networkModel, times(2)).getElementImplementingProvider(dhcpProvider);
verify(testOrchastrator._ntwkSrvcDao, times(2)).getProviderForServiceInNetwork(network.getId(), Service.Dhcp);
verify(testOrchastrator._networksDao, times(2)).findById(nic.getNetworkId());
}
use of com.cloud.vm.NicVO in project cloudstack by apache.
the class ExternalDeviceUsageManagerImpl method updateExternalLoadBalancerNetworkUsageStats.
@Override
public void updateExternalLoadBalancerNetworkUsageStats(long loadBalancerRuleId) {
LoadBalancerVO lb = _loadBalancerDao.findById(loadBalancerRuleId);
if (lb == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, LB rule is not found");
}
return;
}
long networkId = lb.getNetworkId();
Network network = _networkDao.findById(networkId);
if (network == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, Network is not found");
}
return;
}
ExternalLoadBalancerDeviceVO lbDeviceVO = getExternalLoadBalancerForNetwork(network);
if (lbDeviceVO == null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Cannot update usage stats, No external LB device found");
}
return;
}
// Get network stats from the external load balancer
ExternalNetworkResourceUsageAnswer lbAnswer = null;
HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId());
if (externalLoadBalancer != null) {
ExternalNetworkResourceUsageCommand cmd = new ExternalNetworkResourceUsageCommand();
lbAnswer = (ExternalNetworkResourceUsageAnswer) _agentMgr.easySend(externalLoadBalancer.getId(), cmd);
if (lbAnswer == null || !lbAnswer.getResult()) {
String details = (lbAnswer != null) ? lbAnswer.getDetails() : "details unavailable";
String msg = "Unable to get external load balancer stats for network" + networkId + " due to: " + details + ".";
s_logger.error(msg);
return;
}
}
long accountId = lb.getAccountId();
AccountVO account = _accountDao.findById(accountId);
if (account == null) {
s_logger.debug("Skipping stats update for external LB for account with ID " + accountId);
return;
}
String publicIp = _networkModel.getIp(lb.getSourceIpAddressId()).getAddress().addr();
DataCenterVO zone = _dcDao.findById(network.getDataCenterId());
String statsEntryIdentifier = "account " + account.getAccountName() + ", zone " + zone.getName() + ", network ID " + networkId + ", host ID " + externalLoadBalancer.getName();
long newCurrentBytesSent = 0;
long newCurrentBytesReceived = 0;
if (publicIp != null) {
long[] bytesSentAndReceived = null;
statsEntryIdentifier += ", public IP: " + publicIp;
boolean inline = _networkModel.isNetworkInlineMode(network);
if (externalLoadBalancer.getType().equals(Host.Type.ExternalLoadBalancer) && inline) {
// Look up stats for the guest IP address that's mapped to the public IP address
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(publicIp);
if (mapping != null) {
NicVO nic = _nicDao.findById(mapping.getNicId());
String loadBalancingIpAddress = nic.getIPv4Address();
bytesSentAndReceived = lbAnswer.ipBytes.get(loadBalancingIpAddress);
if (bytesSentAndReceived != null) {
bytesSentAndReceived[0] = 0;
}
}
} else {
bytesSentAndReceived = lbAnswer.ipBytes.get(publicIp);
}
if (bytesSentAndReceived == null) {
s_logger.debug("Didn't get an external network usage answer for public IP " + publicIp);
} else {
newCurrentBytesSent += bytesSentAndReceived[0];
newCurrentBytesReceived += bytesSentAndReceived[1];
}
commitStats(networkId, externalLoadBalancer, accountId, publicIp, zone, statsEntryIdentifier, newCurrentBytesSent, newCurrentBytesReceived);
}
}
use of com.cloud.vm.NicVO in project cloudstack by apache.
the class ExternalFirewallDeviceManagerImpl method manageGuestNetworkWithExternalFirewall.
@Override
public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network network) throws ResourceUnavailableException, InsufficientCapacityException {
if (network.getTrafficType() != TrafficType.Guest) {
s_logger.trace("External firewall can only be used for add/remove guest networks.");
return false;
}
long zoneId = network.getDataCenterId();
DataCenterVO zone = _dcDao.findById(zoneId);
HostVO externalFirewall = null;
if (add) {
GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap");
try {
if (deviceMapLock.lock(120)) {
try {
ExternalFirewallDeviceVO device = findSuitableFirewallForNetwork(network);
long externalFirewallId = device.getId();
NetworkExternalFirewallVO networkFW = new NetworkExternalFirewallVO(network.getId(), externalFirewallId);
_networkExternalFirewallDao.persist(networkFW);
externalFirewall = _hostDao.findById(device.getHostId());
} finally {
deviceMapLock.unlock();
}
}
} finally {
deviceMapLock.releaseRef();
}
} else {
ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network);
if (fwDeviceVO == null) {
s_logger.warn("Network shutdown requested on external firewall element, which did not implement the network." + " Either network implement failed half way through or already network shutdown is completed.");
return true;
}
externalFirewall = _hostDao.findById(fwDeviceVO.getHostId());
}
Account account = _accountDao.findByIdIncludingRemoved(network.getAccountId());
NetworkOffering offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
boolean sharedSourceNat = offering.getSharedSourceNat();
IPAddressVO sourceNatIp = null;
if (!sharedSourceNat) {
// Get the source NAT IP address for this network
List<? extends IpAddress> sourceNatIps = _networkModel.listPublicIpsAssignedToAccount(network.getAccountId(), zoneId, true);
for (IpAddress ipAddress : sourceNatIps) {
if (ipAddress.getAssociatedWithNetworkId().longValue() == network.getId()) {
sourceNatIp = _ipAddressDao.findById(ipAddress.getId());
break;
}
}
if (sourceNatIp == null) {
String errorMsg = "External firewall was unable to find the source NAT IP address for network " + network.getName();
s_logger.error(errorMsg);
return true;
}
}
// Send a command to the external firewall to implement or shutdown the guest network
long guestVlanTag = Long.parseLong(BroadcastDomainType.getValue(network.getBroadcastUri()));
String guestVlanGateway = network.getGateway();
String guestVlanCidr = network.getCidr();
String sourceNatIpAddress = null;
String publicVlanTag = null;
if (sourceNatIp != null) {
sourceNatIpAddress = sourceNatIp.getAddress().addr();
VlanVO publicVlan = _vlanDao.findById(sourceNatIp.getVlanId());
publicVlanTag = publicVlan.getVlanTag();
}
// Get network rate
Integer networkRate = _networkModel.getNetworkRate(network.getId(), null);
IpAddressTO ip = new IpAddressTO(account.getAccountId(), sourceNatIpAddress, add, false, !sharedSourceNat, publicVlanTag, null, null, null, networkRate, false);
IpAddressTO[] ips = new IpAddressTO[1];
ips[0] = ip;
IpAssocCommand cmd = new IpAssocCommand(ips);
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, guestVlanGateway);
cmd.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, guestVlanCidr);
cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag));
Answer answer = _agentMgr.easySend(externalFirewall.getId(), cmd);
List<String> reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId());
if (answer == null || !answer.getResult()) {
String action = add ? "implement" : "shutdown";
String answerDetails = (answer != null) ? answer.getDetails() : "answer was null";
String msg = "External firewall was unable to " + action + " the guest network on the external firewall in zone " + zone.getName() + " due to " + answerDetails;
s_logger.error(msg);
if (!add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
// If we failed the implementation as well, then just return, no complain
s_logger.error("Skip the shutdown of guest network on SRX because it seems we didn't implement it as well");
return true;
}
throw new ResourceUnavailableException(msg, DataCenter.class, zoneId);
}
if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) {
// Insert a new NIC for this guest network to reserve the gateway address
_networkMgr.savePlaceholderNic(network, network.getGateway(), null, null);
}
// Delete any mappings used for inline external load balancers in this network
List<NicVO> nicsInNetwork = _nicDao.listByNetworkId(network.getId());
for (NicVO nic : nicsInNetwork) {
InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByNicId(nic.getId());
if (mapping != null) {
_nicDao.expunge(mapping.getNicId());
_inlineLoadBalancerNicMapDao.expunge(mapping.getId());
}
}
// on network shutdown, delete placeHolder nics used for the firewall device
if (!add) {
List<NicVO> nics = _nicDao.listByNetworkId(network.getId());
for (NicVO nic : nics) {
if (nic.getVmType() == null && nic.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && nic.getIPv4Address().equals(network.getGateway())) {
s_logger.debug("Removing placeholder nic " + nic + " for the network " + network);
_nicDao.remove(nic.getId());
}
}
freeFirewallForNetwork(network);
}
String action = add ? "implemented" : "shut down";
s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag);
return true;
}
use of com.cloud.vm.NicVO in project cloudstack by apache.
the class NetworkModelImpl method listNetworksUsedByVm.
@Override
public List<NetworkVO> listNetworksUsedByVm(long vmId, boolean isSystem) {
List<NetworkVO> networks = new ArrayList<NetworkVO>();
List<NicVO> nics = _nicDao.listByVmId(vmId);
if (nics != null) {
for (Nic nic : nics) {
NetworkVO network = _networksDao.findByIdIncludingRemoved(nic.getNetworkId());
if (isNetworkSystem(network) == isSystem) {
networks.add(network);
}
}
}
return networks;
}
use of com.cloud.vm.NicVO in project cloudstack by apache.
the class BaremetalKickStartServiceImpl method preparePxeInAdvancedZone.
private boolean preparePxeInAdvancedZone(VirtualMachineProfile profile, NicProfile nic, Network network, DeployDestination dest, ReservationContext context) throws Exception {
DomainRouterVO vr = getVirtualRouter(network);
List<NicVO> nics = _nicDao.listByVmId(vr.getId());
NicVO mgmtNic = null;
for (NicVO nicvo : nics) {
if (ControlNetworkGuru.class.getSimpleName().equals(nicvo.getReserver())) {
mgmtNic = nicvo;
break;
}
}
if (mgmtNic == null) {
throw new CloudRuntimeException(String.format("cannot find management nic on virtual router[id:%s]", vr.getId()));
}
String internalServerIp = _configDao.getValue(Config.BaremetalInternalStorageServer.key());
if (internalServerIp == null) {
throw new CloudRuntimeException(String.format("please specify 'baremetal.internal.storage.server.ip', which is the http server/nfs server storing kickstart files and ISO files, in global setting"));
}
List<String> tuple = parseKickstartUrl(profile);
String cmd = String.format("/opt/cloud/bin/prepare_pxe.sh %s %s %s %s %s %s", tuple.get(1), tuple.get(2), profile.getTemplate().getUuid(), String.format("01-%s", nic.getMacAddress().replaceAll(":", "-")).toLowerCase(), tuple.get(0), nic.getMacAddress().toLowerCase());
s_logger.debug(String.format("prepare pxe on virtual router[ip:%s], cmd: %s", mgmtNic.getIPv4Address(), cmd));
Pair<Boolean, String> ret = SshHelper.sshExecute(mgmtNic.getIPv4Address(), 3922, "root", getSystemVMKeyFile(), null, cmd);
if (!ret.first()) {
throw new CloudRuntimeException(String.format("failed preparing PXE in virtual router[id:%s], because %s", vr.getId(), ret.second()));
}
//String internalServerIp = "10.223.110.231";
cmd = String.format("/opt/cloud/bin/baremetal_snat.sh %s %s %s", mgmtNic.getIPv4Address(), internalServerIp, mgmtNic.getIPv4Gateway());
s_logger.debug(String.format("prepare SNAT on virtual router[ip:%s], cmd: %s", mgmtNic.getIPv4Address(), cmd));
ret = SshHelper.sshExecute(mgmtNic.getIPv4Address(), 3922, "root", getSystemVMKeyFile(), null, cmd);
if (!ret.first()) {
throw new CloudRuntimeException(String.format("failed preparing PXE in virtual router[id:%s], because %s", vr.getId(), ret.second()));
}
return true;
}
Aggregations