use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.
the class ResourceManagerImpl method createHostVO.
protected HostVO createHostVO(final StartupCommand[] cmds, final ServerResource resource, final Map<String, String> details, List<String> hostTags, final ResourceStateAdapter.Event stateEvent) {
boolean newHost = false;
StartupCommand startup = cmds[0];
HostVO host = getNewHost(cmds);
if (host == null) {
host = new HostVO(startup.getGuid());
newHost = true;
}
String dataCenter = startup.getDataCenter();
String pod = startup.getPod();
final String cluster = startup.getCluster();
if (pod != null && dataCenter != null && pod.equalsIgnoreCase("default") && dataCenter.equalsIgnoreCase("default")) {
final List<HostPodVO> pods = _podDao.listAllIncludingRemoved();
for (final HostPodVO hpv : pods) {
if (checkCIDR(hpv, startup.getPrivateIpAddress(), startup.getPrivateNetmask())) {
pod = hpv.getName();
dataCenter = _dcDao.findById(hpv.getDataCenterId()).getName();
break;
}
}
}
long dcId = -1;
DataCenterVO dc = _dcDao.findByName(dataCenter);
if (dc == null) {
try {
dcId = Long.parseLong(dataCenter);
dc = _dcDao.findById(dcId);
} catch (final NumberFormatException e) {
s_logger.debug("Cannot parse " + dataCenter + " into Long.");
}
}
if (dc == null) {
throw new IllegalArgumentException("Host " + startup.getPrivateIpAddress() + " sent incorrect data center: " + dataCenter);
}
dcId = dc.getId();
HostPodVO p = _podDao.findByName(pod, dcId);
if (p == null) {
try {
final long podId = Long.parseLong(pod);
p = _podDao.findById(podId);
} catch (final NumberFormatException e) {
s_logger.debug("Cannot parse " + pod + " into Long.");
}
}
/*
* ResourceStateAdapter is responsible for throwing Exception if Pod is
* null and non-null is required. for example, XcpServerDiscoever.
* Others, like PxeServer, ExternalFireware don't require Pod
*/
final Long podId = p == null ? null : p.getId();
Long clusterId = null;
if (cluster != null) {
try {
clusterId = Long.valueOf(cluster);
} catch (final NumberFormatException e) {
if (podId != null) {
ClusterVO c = _clusterDao.findBy(cluster, podId.longValue());
if (c == null) {
c = new ClusterVO(dcId, podId.longValue(), cluster);
c = _clusterDao.persist(c);
}
clusterId = c.getId();
}
}
}
if (startup instanceof StartupRoutingCommand) {
final StartupRoutingCommand ssCmd = (StartupRoutingCommand) startup;
final List<String> implicitHostTags = ssCmd.getHostTags();
if (!implicitHostTags.isEmpty()) {
if (hostTags == null) {
hostTags = _hostTagsDao.gethostTags(host.getId());
}
if (hostTags != null) {
implicitHostTags.removeAll(hostTags);
hostTags.addAll(implicitHostTags);
} else {
hostTags = implicitHostTags;
}
}
}
host.setDataCenterId(dc.getId());
host.setPodId(podId);
host.setClusterId(clusterId);
host.setPrivateIpAddress(startup.getPrivateIpAddress());
host.setPrivateNetmask(startup.getPrivateNetmask());
host.setPrivateMacAddress(startup.getPrivateMacAddress());
host.setPublicIpAddress(startup.getPublicIpAddress());
host.setPublicMacAddress(startup.getPublicMacAddress());
host.setPublicNetmask(startup.getPublicNetmask());
host.setStorageIpAddress(startup.getStorageIpAddress());
host.setStorageMacAddress(startup.getStorageMacAddress());
host.setStorageNetmask(startup.getStorageNetmask());
host.setVersion(startup.getVersion());
host.setName(startup.getName());
host.setManagementServerId(_nodeId);
host.setStorageUrl(startup.getIqn());
host.setLastPinged(System.currentTimeMillis() >> 10);
host.setHostTags(hostTags);
host.setDetails(details);
if (startup.getStorageIpAddressDeux() != null) {
host.setStorageIpAddressDeux(startup.getStorageIpAddressDeux());
host.setStorageMacAddressDeux(startup.getStorageMacAddressDeux());
host.setStorageNetmaskDeux(startup.getStorageNetmaskDeux());
}
if (resource != null) {
/* null when agent is connected agent */
host.setResource(resource.getClass().getName());
}
host = (HostVO) dispatchToStateAdapters(stateEvent, true, host, cmds, resource, details, hostTags);
if (host == null) {
throw new CloudRuntimeException("No resource state adapter response");
}
if (newHost) {
host = _hostDao.persist(host);
} else {
_hostDao.update(host.getId(), host);
}
if (startup instanceof StartupRoutingCommand) {
final StartupRoutingCommand ssCmd = (StartupRoutingCommand) startup;
updateSupportsClonedVolumes(host, ssCmd.getSupportsClonedVolumes());
}
try {
resourceStateTransitTo(host, ResourceState.Event.InternalCreated, _nodeId);
/* Agent goes to Connecting status */
_agentMgr.agentStatusTransitTo(host, Status.Event.AgentConnected, _nodeId);
} catch (final Exception e) {
s_logger.debug("Cannot transmit host " + host.getId() + " to Creating state", e);
_agentMgr.agentStatusTransitTo(host, Status.Event.Error, _nodeId);
try {
resourceStateTransitTo(host, ResourceState.Event.Error, _nodeId);
} catch (final NoTransitionException e1) {
s_logger.debug("Cannot transmit host " + host.getId() + "to Error state", e);
}
}
return host;
}
use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.
the class VolumeObject method stateTransit.
@Override
public boolean stateTransit(Volume.Event event) {
boolean result = false;
try {
volumeVO = volumeDao.findById(volumeVO.getId());
if (volumeVO != null) {
result = _volStateMachine.transitTo(volumeVO, event, null, volumeDao);
volumeVO = volumeDao.findById(volumeVO.getId());
}
} catch (NoTransitionException e) {
String errorMessage = "Failed to transit volume: " + getVolumeId() + ", due to: " + e.toString();
s_logger.debug(errorMessage);
throw new CloudRuntimeException(errorMessage);
}
return result;
}
use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.
the class NetworkOrchestrator method destroyNetwork.
@Override
@DB
public boolean destroyNetwork(final long networkId, final ReservationContext context, final boolean forced) {
final Account callerAccount = context.getAccount();
NetworkVO network = _networksDao.findById(networkId);
if (network == null) {
s_logger.debug("Unable to find network with id: " + networkId);
return false;
}
// Make sure that there are no user vms in the network that are not Expunged/Error
final List<UserVmVO> userVms = _userVmDao.listByNetworkIdAndStates(networkId);
for (final UserVmVO vm : userVms) {
if (!(vm.getState() == VirtualMachine.State.Expunging && vm.getRemoved() != null)) {
s_logger.warn("Can't delete the network, not all user vms are expunged. Vm " + vm + " is in " + vm.getState() + " state");
return false;
}
}
// Don't allow to delete network via api call when it has vms assigned to it
final int nicCount = getActiveNicsInNetwork(networkId);
if (nicCount > 0) {
s_logger.debug("The network id=" + networkId + " has active Nics, but shouldn't.");
// at this point we have already determined that there are no active user vms in network
// if the op_networks table shows active nics, it's a bug in releasing nics updating op_networks
_networksDao.changeActiveNicsBy(networkId, -1 * nicCount);
}
//In Basic zone, make sure that there are no non-removed console proxies and SSVMs using the network
final DataCenter zone = _entityMgr.findById(DataCenter.class, network.getDataCenterId());
if (zone.getNetworkType() == NetworkType.Basic) {
final List<VMInstanceVO> systemVms = _vmDao.listNonRemovedVmsByTypeAndNetwork(network.getId(), Type.ConsoleProxy, Type.SecondaryStorageVm);
if (systemVms != null && !systemVms.isEmpty()) {
s_logger.warn("Can't delete the network, not all consoleProxy/secondaryStorage vms are expunged");
return false;
}
}
// Shutdown network first
shutdownNetwork(networkId, context, false);
// get updated state for the network
network = _networksDao.findById(networkId);
if (network.getState() != Network.State.Allocated && network.getState() != Network.State.Setup && !forced) {
s_logger.debug("Network is not not in the correct state to be destroyed: " + network.getState());
return false;
}
boolean success = true;
if (!cleanupNetworkResources(networkId, callerAccount, context.getCaller().getId())) {
s_logger.warn("Unable to delete network id=" + networkId + ": failed to cleanup network resources");
return false;
}
// get providers to destroy
final List<Provider> providersToDestroy = getNetworkProviders(network.getId());
for (final NetworkElement element : networkElements) {
if (providersToDestroy.contains(element.getProvider())) {
try {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Sending destroy to " + element);
}
if (!element.destroy(network, context)) {
success = false;
s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName());
}
} catch (final ResourceUnavailableException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final ConcurrentOperationException e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
} catch (final Exception e) {
s_logger.warn("Unable to complete destroy of the network due to element: " + element.getName(), e);
success = false;
}
}
}
if (success) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Network id=" + networkId + " is destroyed successfully, cleaning up corresponding resources now.");
}
final NetworkVO networkFinal = network;
try {
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) {
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName());
guru.trash(networkFinal, _networkOfferingDao.findById(networkFinal.getNetworkOfferingId()));
if (!deleteVlansInNetwork(networkFinal.getId(), context.getCaller().getId(), callerAccount)) {
s_logger.warn("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
throw new CloudRuntimeException("Failed to delete network " + networkFinal + "; was unable to cleanup corresponding ip ranges");
} else {
// commit transaction only when ips and vlans for the network are released successfully
try {
stateTransitTo(networkFinal, Event.DestroyNetwork);
} catch (final NoTransitionException e) {
s_logger.debug(e.getMessage());
}
if (_networksDao.remove(networkFinal.getId())) {
final NetworkDomainVO networkDomain = _networkDomainDao.getDomainNetworkMapByNetworkId(networkFinal.getId());
if (networkDomain != null) {
_networkDomainDao.remove(networkDomain.getId());
}
final NetworkAccountVO networkAccount = _networkAccountDao.getAccountNetworkMapByNetworkId(networkFinal.getId());
if (networkAccount != null) {
_networkAccountDao.remove(networkAccount.getId());
}
}
final NetworkOffering ntwkOff = _entityMgr.findById(NetworkOffering.class, networkFinal.getNetworkOfferingId());
final boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, networkFinal.getAclType());
if (updateResourceCount) {
_resourceLimitMgr.decrementResourceCount(networkFinal.getAccountId(), ResourceType.network, networkFinal.getDisplayNetwork());
}
}
}
});
if (_networksDao.findById(network.getId()) == null) {
// remove its related ACL permission
final Pair<Class<?>, Long> networkMsg = new Pair<Class<?>, Long>(Network.class, networkFinal.getId());
_messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg);
}
return true;
} catch (final CloudRuntimeException e) {
s_logger.error("Failed to delete network", e);
return false;
}
}
return success;
}
use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.
the class NetworkOrchestrator method implementNetwork.
@Override
@DB
public Pair<NetworkGuru, NetworkVO> implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
final Pair<NetworkGuru, NetworkVO> implemented = new Pair<NetworkGuru, NetworkVO>(null, null);
NetworkVO network = _networksDao.findById(networkId);
final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName());
if (isNetworkImplemented(network)) {
s_logger.debug("Network id=" + networkId + " is already implemented");
implemented.set(guru, network);
return implemented;
}
// Acquire lock only when network needs to be implemented
network = _networksDao.acquireInLockTable(networkId, NetworkLockTimeout.value());
if (network == null) {
// see NetworkVO.java
final ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration");
ex.addProxyObject(_entityMgr.findById(Network.class, networkId).getUuid());
throw ex;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is acquired for network id " + networkId + " as a part of network implement");
}
try {
if (isNetworkImplemented(network)) {
s_logger.debug("Network id=" + networkId + " is already implemented");
implemented.set(guru, network);
return implemented;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Asking " + guru.getName() + " to implement " + network);
}
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
network.setReservationId(context.getReservationId());
if (isSharedNetworkWithServices(network)) {
network.setState(Network.State.Implementing);
} else {
stateTransitTo(network, Event.ImplementNetwork);
}
final Network result = guru.implement(network, offering, dest, context);
network.setCidr(result.getCidr());
network.setBroadcastUri(result.getBroadcastUri());
network.setGateway(result.getGateway());
network.setMode(result.getMode());
network.setPhysicalNetworkId(result.getPhysicalNetworkId());
_networksDao.update(networkId, network);
// implement network elements and re-apply all the network rules
implementNetworkElementsAndResources(dest, context, network, offering);
if (isSharedNetworkWithServices(network)) {
network.setState(Network.State.Implemented);
} else {
stateTransitTo(network, Event.OperationSucceeded);
}
network.setRestartRequired(false);
_networksDao.update(network.getId(), network);
implemented.set(guru, network);
return implemented;
} catch (final NoTransitionException e) {
s_logger.error(e.getMessage());
return null;
} catch (final CloudRuntimeException e) {
s_logger.error("Caught exception: " + e.getMessage());
return null;
} finally {
if (implemented.first() == null) {
s_logger.debug("Cleaning up because we're unable to implement the network " + network);
try {
if (isSharedNetworkWithServices(network)) {
network.setState(Network.State.Shutdown);
_networksDao.update(networkId, network);
} else {
stateTransitTo(network, Event.OperationFailed);
}
} catch (final NoTransitionException e) {
s_logger.error(e.getMessage());
}
try {
shutdownNetwork(networkId, context, false);
} catch (final Exception e) {
// Don't throw this exception as it would hide the original thrown exception, just log
s_logger.error("Exception caught while shutting down a network as part of a failed implementation", e);
}
}
_networksDao.releaseFromLockTable(networkId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Lock is released for network id " + networkId + " as a part of network implement");
}
}
}
use of com.cloud.utils.fsm.NoTransitionException in project cloudstack by apache.
the class VirtualMachineManagerImpl method orchestrateStorageMigration.
private void orchestrateStorageMigration(final String vmUuid, final StoragePool destPool) {
final VMInstanceVO vm = _vmDao.findByUuid(vmUuid);
if (destPool == null) {
throw new CloudRuntimeException("Unable to migrate vm: missing destination storage pool");
}
try {
stateTransitTo(vm, VirtualMachine.Event.StorageMigrationRequested, null);
} catch (final NoTransitionException e) {
s_logger.debug("Unable to migrate vm: " + e.toString());
throw new CloudRuntimeException("Unable to migrate vm: " + e.toString());
}
final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm);
boolean migrationResult = false;
try {
migrationResult = volumeMgr.storageMigration(profile, destPool);
if (migrationResult) {
if (destPool.getPodId() != null && !destPool.getPodId().equals(vm.getPodIdToDeployIn())) {
final DataCenterDeployment plan = new DataCenterDeployment(vm.getDataCenterId(), destPool.getPodId(), null, null, null, null);
final VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, null, null, null, null);
_networkMgr.reallocate(vmProfile, plan);
}
//when start the vm next time, don;'t look at last_host_id, only choose the host based on volume/storage pool
vm.setLastHostId(null);
vm.setPodIdToDeployIn(destPool.getPodId());
// unregister the VM from the source host and cleanup the associated VM files.
if (vm.getHypervisorType().equals(HypervisorType.VMware)) {
Long srcClusterId = null;
Long srcHostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId();
if (srcHostId != null) {
HostVO srcHost = _hostDao.findById(srcHostId);
srcClusterId = srcHost.getClusterId();
}
final Long destClusterId = destPool.getClusterId();
if (srcClusterId != null && destClusterId != null && !srcClusterId.equals(destClusterId)) {
final String srcDcName = _clusterDetailsDao.getVmwareDcName(srcClusterId);
final String destDcName = _clusterDetailsDao.getVmwareDcName(destClusterId);
if (srcDcName != null && destDcName != null && !srcDcName.equals(destDcName)) {
s_logger.debug("Since VM's storage was successfully migrated across VMware Datacenters, unregistering VM: " + vm.getInstanceName() + " from source host: " + srcHostId);
final UnregisterVMCommand uvc = new UnregisterVMCommand(vm.getInstanceName());
uvc.setCleanupVmFiles(true);
try {
_agentMgr.send(srcHostId, uvc);
} catch (final AgentUnavailableException | OperationTimedoutException e) {
throw new CloudRuntimeException("Failed to unregister VM: " + vm.getInstanceName() + " from source host: " + srcHostId + " after successfully migrating VM's storage across VMware Datacenters");
}
}
}
}
} else {
s_logger.debug("Storage migration failed");
}
} catch (final ConcurrentOperationException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (final InsufficientVirtualNetworkCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (final InsufficientAddressCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (final InsufficientCapacityException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} catch (final StorageUnavailableException e) {
s_logger.debug("Failed to migration: " + e.toString());
throw new CloudRuntimeException("Failed to migration: " + e.toString());
} finally {
try {
stateTransitTo(vm, VirtualMachine.Event.AgentReportStopped, null);
} catch (final NoTransitionException e) {
s_logger.debug("Failed to change vm state: " + e.toString());
throw new CloudRuntimeException("Failed to change vm state: " + e.toString());
}
}
}
Aggregations