use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method finalizeVirtualMachineProfile.
@Override
public boolean finalizeVirtualMachineProfile(final VirtualMachineProfile profile, final DeployDestination dest, final ReservationContext context) {
boolean dnsProvided = true;
boolean dhcpProvided = true;
boolean publicNetwork = false;
final DataCenterVO dc = _dcDao.findById(dest.getDataCenter().getId());
_dcDao.loadDetails(dc);
// 1) Set router details
final DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
final Map<String, String> details = _vmDetailsDao.listDetailsKeyPairs(router.getId());
router.setDetails(details);
// 2) Prepare boot loader elements related with Control network
final StringBuilder buf = profile.getBootArgsBuilder();
buf.append(" template=domP");
buf.append(" name=").append(profile.getHostName());
if (Boolean.valueOf(_configDao.getValue("system.vm.random.password"))) {
buf.append(" vmpassword=").append(_configDao.getValue("system.vm.password"));
}
NicProfile controlNic = null;
String defaultDns1 = null;
String defaultDns2 = null;
String defaultIp6Dns1 = null;
String defaultIp6Dns2 = null;
for (final NicProfile nic : profile.getNics()) {
final int deviceId = nic.getDeviceId();
boolean ipv4 = false, ipv6 = false;
if (nic.getIPv4Address() != null) {
ipv4 = true;
buf.append(" eth").append(deviceId).append("ip=").append(nic.getIPv4Address());
buf.append(" eth").append(deviceId).append("mask=").append(nic.getIPv4Netmask());
}
if (nic.getIPv6Address() != null) {
ipv6 = true;
buf.append(" eth").append(deviceId).append("ip6=").append(nic.getIPv6Address());
buf.append(" eth").append(deviceId).append("ip6prelen=").append(NetUtils.getIp6CidrSize(nic.getIPv6Cidr()));
}
if (nic.isDefaultNic()) {
if (ipv4) {
buf.append(" gateway=").append(nic.getIPv4Gateway());
}
if (ipv6) {
buf.append(" ip6gateway=").append(nic.getIPv6Gateway());
}
defaultDns1 = nic.getIPv4Dns1();
defaultDns2 = nic.getIPv4Dns2();
defaultIp6Dns1 = nic.getIPv6Dns1();
defaultIp6Dns2 = nic.getIPv6Dns2();
}
if (nic.getTrafficType() == TrafficType.Management) {
buf.append(" localgw=").append(dest.getPod().getGateway());
} else if (nic.getTrafficType() == TrafficType.Control) {
controlNic = nic;
buf.append(createRedundantRouterArgs(controlNic, router));
// DOMR control command is sent over management server in VMware
if (dest.getHost().getHypervisorType() == HypervisorType.VMware || dest.getHost().getHypervisorType() == HypervisorType.Hyperv) {
s_logger.info("Check if we need to add management server explicit route to DomR. pod cidr: " + dest.getPod().getCidrAddress() + "/" + dest.getPod().getCidrSize() + ", pod gateway: " + dest.getPod().getGateway() + ", management host: " + ApiServiceConfiguration.ManagementHostIPAdr.value());
if (s_logger.isInfoEnabled()) {
s_logger.info("Add management server explicit route to DomR.");
}
// always add management explicit route, for basic
// networking setup, DomR may have two interfaces while both
// are on the same subnet
_mgmtCidr = _configDao.getValue(Config.ManagementNetwork.key());
if (NetUtils.isValidCIDR(_mgmtCidr)) {
buf.append(" mgmtcidr=").append(_mgmtCidr);
buf.append(" localgw=").append(dest.getPod().getGateway());
}
if (dc.getNetworkType() == NetworkType.Basic) {
// ask domR to setup SSH on guest network
buf.append(" sshonguest=true");
}
}
} else if (nic.getTrafficType() == TrafficType.Guest) {
dnsProvided = _networkModel.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dns, Provider.VirtualRouter);
dhcpProvided = _networkModel.isProviderSupportServiceInNetwork(nic.getNetworkId(), Service.Dhcp, Provider.VirtualRouter);
// build bootloader parameter for the guest
buf.append(createGuestBootLoadArgs(nic, defaultDns1, defaultDns2, router));
} else if (nic.getTrafficType() == TrafficType.Public) {
publicNetwork = true;
}
}
if (controlNic == null) {
throw new CloudRuntimeException("Didn't start a control port");
}
final String rpValue = _configDao.getValue(Config.NetworkRouterRpFilter.key());
if (rpValue != null && rpValue.equalsIgnoreCase("true")) {
_disableRpFilter = true;
} else {
_disableRpFilter = false;
}
String rpFilter = " ";
String type = null;
if (router.getVpcId() != null) {
type = "vpcrouter";
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
} else if (!publicNetwork) {
type = "dhcpsrvr";
} else {
type = "router";
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
}
if (_disableRpFilter) {
rpFilter = " disable_rp_filter=true";
}
buf.append(" type=" + type + rpFilter);
final String domain_suffix = dc.getDetail(ZoneConfig.DnsSearchOrder.getName());
if (domain_suffix != null) {
buf.append(" dnssearchorder=").append(domain_suffix);
}
if (profile.getHypervisorType() == HypervisorType.VMware || profile.getHypervisorType() == HypervisorType.Hyperv) {
buf.append(" extra_pubnics=" + _routerExtraPublicNics);
}
/*
* If virtual router didn't provide DNS service but provide DHCP
* service, we need to override the DHCP response to return DNS server
* rather than virtual router itself.
*/
if (dnsProvided || dhcpProvided) {
if (defaultDns1 != null) {
buf.append(" dns1=").append(defaultDns1);
}
if (defaultDns2 != null) {
buf.append(" dns2=").append(defaultDns2);
}
if (defaultIp6Dns1 != null) {
buf.append(" ip6dns1=").append(defaultIp6Dns1);
}
if (defaultIp6Dns2 != null) {
buf.append(" ip6dns2=").append(defaultIp6Dns2);
}
boolean useExtDns = !dnsProvided;
/* For backward compatibility */
useExtDns = useExtDns || UseExternalDnsServers.valueIn(dc.getId());
if (useExtDns) {
buf.append(" useextdns=true");
}
}
if (Boolean.valueOf(_configDao.getValue(Config.BaremetalProvisionDoneNotificationEnabled.key()))) {
final QueryBuilder<UserVO> acntq = QueryBuilder.create(UserVO.class);
acntq.and(acntq.entity().getUsername(), SearchCriteria.Op.EQ, "baremetal-system-account");
final UserVO user = acntq.find();
if (user == null) {
s_logger.warn(String.format("global setting[baremetal.provision.done.notification] is enabled but user baremetal-system-account is not found. Baremetal provision done notification will not be enabled"));
} else {
buf.append(String.format(" baremetalnotificationsecuritykey=%s", user.getSecretKey()));
buf.append(String.format(" baremetalnotificationapikey=%s", user.getApiKey()));
buf.append(" host=").append(ApiServiceConfiguration.ManagementHostIPAdr.value());
buf.append(" port=").append(_configDao.getValue(Config.BaremetalProvisionDoneNotificationPort.key()));
}
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Boot Args for " + profile + ": " + buf.toString());
}
return true;
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method upgradeRouter.
@Override
@DB
public VirtualRouter upgradeRouter(final UpgradeRouterCmd cmd) {
final Long routerId = cmd.getId();
final Long serviceOfferingId = cmd.getServiceOfferingId();
final Account caller = CallContext.current().getCallingAccount();
final DomainRouterVO router = _routerDao.findById(routerId);
if (router == null) {
throw new InvalidParameterValueException("Unable to find router with id " + routerId);
}
_accountMgr.checkAccess(caller, null, true, router);
if (router.getServiceOfferingId() == serviceOfferingId) {
s_logger.debug("Router: " + routerId + "already has service offering: " + serviceOfferingId);
return _routerDao.findById(routerId);
}
final ServiceOffering newServiceOffering = _entityMgr.findById(ServiceOffering.class, serviceOfferingId);
if (newServiceOffering == null) {
throw new InvalidParameterValueException("Unable to find service offering with id " + serviceOfferingId);
}
// it cannot be used for user vms
if (!newServiceOffering.getSystemUse()) {
throw new InvalidParameterValueException("Cannot upgrade router vm to a non system service offering " + serviceOfferingId);
}
// Check that the router is stopped
if (!router.getState().equals(VirtualMachine.State.Stopped)) {
s_logger.warn("Unable to upgrade router " + router.toString() + " in state " + router.getState());
throw new InvalidParameterValueException("Unable to upgrade router " + router.toString() + " in state " + router.getState() + "; make sure the router is stopped and not in an error state before upgrading.");
}
final ServiceOfferingVO currentServiceOffering = _serviceOfferingDao.findById(router.getServiceOfferingId());
// offering
if (currentServiceOffering.getUseLocalStorage() != newServiceOffering.getUseLocalStorage()) {
throw new InvalidParameterValueException("Can't upgrade, due to new local storage status : " + newServiceOffering.getUseLocalStorage() + " is different from " + "curruent local storage status: " + currentServiceOffering.getUseLocalStorage());
}
router.setServiceOfferingId(serviceOfferingId);
if (_routerDao.update(routerId, router)) {
return _routerDao.findById(routerId);
} else {
throw new CloudRuntimeException("Unable to upgrade router " + routerId);
}
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method getRouterAlerts.
protected void getRouterAlerts() {
try {
final List<DomainRouterVO> routers = _routerDao.listByStateAndManagementServer(VirtualMachine.State.Running, mgmtSrvrId);
s_logger.debug("Found " + routers.size() + " running routers. ");
for (final DomainRouterVO router : routers) {
final String serviceMonitoringFlag = SetServiceMonitor.valueIn(router.getDataCenterId());
// Monitor service is not enabled in the corresponding Zone
if (!Boolean.parseBoolean(serviceMonitoringFlag) || router.getVpcId() != null) {
continue;
}
String controlIP = getRouterControlIP(router);
if (controlIP != null && !controlIP.equals("0.0.0.0")) {
OpRouterMonitorServiceVO opRouterMonitorServiceVO = _opRouterMonitorServiceDao.findById(router.getId());
GetRouterAlertsCommand command = null;
if (opRouterMonitorServiceVO == null) {
// To
command = new GetRouterAlertsCommand(new String("1970-01-01 00:00:00"));
// avoid
// sending
// null
// value
} else {
command = new GetRouterAlertsCommand(opRouterMonitorServiceVO.getLastAlertTimestamp());
}
command.setAccessDetail(NetworkElementCommand.ROUTER_IP, controlIP);
try {
final Answer origAnswer = _agentMgr.easySend(router.getHostId(), command);
GetRouterAlertsAnswer answer = null;
if (origAnswer == null) {
s_logger.warn("Unable to get alerts from router " + router.getHostName());
continue;
}
if (origAnswer instanceof GetRouterAlertsAnswer) {
answer = (GetRouterAlertsAnswer) origAnswer;
} else {
s_logger.warn("Unable to get alerts from router " + router.getHostName());
continue;
}
if (!answer.getResult()) {
s_logger.warn("Unable to get alerts from router " + router.getHostName() + " " + answer.getDetails());
continue;
}
final String[] alerts = answer.getAlerts();
if (alerts != null) {
final String lastAlertTimeStamp = answer.getTimeStamp();
final SimpleDateFormat sdfrmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdfrmt.setLenient(false);
try {
sdfrmt.parse(lastAlertTimeStamp);
} catch (final ParseException e) {
s_logger.warn("Invalid last alert timestamp received while collecting alerts from router: " + router.getInstanceName());
continue;
}
for (final String alert : alerts) {
_alertMgr.sendAlert(AlertType.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterId(), router.getPodIdToDeployIn(), "Monitoring Service on VR " + router.getInstanceName(), alert);
}
if (opRouterMonitorServiceVO == null) {
opRouterMonitorServiceVO = new OpRouterMonitorServiceVO(router.getId(), router.getHostName(), lastAlertTimeStamp);
_opRouterMonitorServiceDao.persist(opRouterMonitorServiceVO);
} else {
opRouterMonitorServiceVO.setLastAlertTimestamp(lastAlertTimeStamp);
_opRouterMonitorServiceDao.update(opRouterMonitorServiceVO.getId(), opRouterMonitorServiceVO);
}
}
} catch (final Exception e) {
s_logger.warn("Error while collecting alerts from router: " + router.getInstanceName(), e);
continue;
}
}
}
} catch (final Exception e) {
s_logger.warn("Error while collecting alerts from router", e);
}
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method finalizeSshAndVersionAndNetworkUsageOnStart.
protected void finalizeSshAndVersionAndNetworkUsageOnStart(final Commands cmds, final VirtualMachineProfile profile, final DomainRouterVO router, final NicProfile controlNic) {
final DomainRouterVO vr = _routerDao.findById(profile.getId());
cmds.addCommand("checkSsh", new CheckSshCommand(profile.getInstanceName(), controlNic.getIPv4Address(), 3922));
// Update router template/scripts version
final GetDomRVersionCmd command = new GetDomRVersionCmd();
command.setAccessDetail(NetworkElementCommand.ROUTER_IP, controlNic.getIPv4Address());
command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName());
cmds.addCommand("getDomRVersion", command);
// Network usage command to create iptables rules
final boolean forVpc = vr.getVpcId() != null;
if (!forVpc) {
cmds.addCommand("networkUsage", new NetworkUsageCommand(controlNic.getIPv4Address(), router.getHostName(), "create", forVpc));
}
}
use of com.cloud.vm.DomainRouterVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method prepareStop.
@Override
public void prepareStop(final VirtualMachineProfile profile) {
// Collect network usage before stopping Vm
final DomainRouterVO router = _routerDao.findById(profile.getVirtualMachine().getId());
if (router == null) {
return;
}
final String privateIP = router.getPrivateIpAddress();
if (privateIP != null) {
final boolean forVpc = router.getVpcId() != null;
final List<? extends Nic> routerNics = _nicDao.listByVmId(router.getId());
for (final Nic routerNic : routerNics) {
final Network network = _networkModel.getNetwork(routerNic.getNetworkId());
// VR
if (forVpc && network.getTrafficType() == TrafficType.Public || !forVpc && network.getTrafficType() == TrafficType.Guest && network.getGuestType() == Network.GuestType.Isolated) {
final NetworkUsageCommand usageCmd = new NetworkUsageCommand(privateIP, router.getHostName(), forVpc, routerNic.getIPv4Address());
final String routerType = router.getType().toString();
final UserStatisticsVO previousStats = _userStatsDao.findBy(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
NetworkUsageAnswer answer = null;
try {
answer = (NetworkUsageAnswer) _agentMgr.easySend(router.getHostId(), usageCmd);
} catch (final Exception e) {
s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId(), e);
continue;
}
if (answer != null) {
if (!answer.getResult()) {
s_logger.warn("Error while collecting network stats from router: " + router.getInstanceName() + " from host: " + router.getHostId() + "; details: " + answer.getDetails());
continue;
}
try {
if (answer.getBytesReceived() == 0 && answer.getBytesSent() == 0) {
s_logger.debug("Recieved and Sent bytes are both 0. Not updating user_statistics");
continue;
}
final NetworkUsageAnswer answerFinal = answer;
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
final UserStatisticsVO stats = _userStatsDao.lock(router.getAccountId(), router.getDataCenterId(), network.getId(), forVpc ? routerNic.getIPv4Address() : null, router.getId(), routerType);
if (stats == null) {
s_logger.warn("unable to find stats for account: " + router.getAccountId());
return;
}
if (previousStats != null && (previousStats.getCurrentBytesReceived() != stats.getCurrentBytesReceived() || previousStats.getCurrentBytesSent() != stats.getCurrentBytesSent())) {
s_logger.debug("Router stats changed from the time NetworkUsageCommand was sent. " + "Ignoring current answer. Router: " + answerFinal.getRouterName() + " Rcvd: " + answerFinal.getBytesReceived() + "Sent: " + answerFinal.getBytesSent());
return;
}
if (stats.getCurrentBytesReceived() > answerFinal.getBytesReceived()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesReceived() + " Stored: " + stats.getCurrentBytesReceived());
}
stats.setNetBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
}
stats.setCurrentBytesReceived(answerFinal.getBytesReceived());
if (stats.getCurrentBytesSent() > answerFinal.getBytesSent()) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Received # of bytes that's less than the last one. " + "Assuming something went wrong and persisting it. Router: " + answerFinal.getRouterName() + " Reported: " + answerFinal.getBytesSent() + " Stored: " + stats.getCurrentBytesSent());
}
stats.setNetBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
}
stats.setCurrentBytesSent(answerFinal.getBytesSent());
if (!_dailyOrHourly) {
// update agg bytes
stats.setAggBytesSent(stats.getNetBytesSent() + stats.getCurrentBytesSent());
stats.setAggBytesReceived(stats.getNetBytesReceived() + stats.getCurrentBytesReceived());
}
_userStatsDao.update(stats.getId(), stats);
}
});
} catch (final Exception e) {
s_logger.warn("Unable to update user statistics for account: " + router.getAccountId() + " Rx: " + answer.getBytesReceived() + "; Tx: " + answer.getBytesSent());
}
}
}
}
}
}
Aggregations