use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.
the class NetworkOrchestrator method reallocate.
@DB
@Override
public boolean reallocate(final VirtualMachineProfile vm, final DataCenterDeployment dest) throws InsufficientCapacityException, ConcurrentOperationException {
final VMInstanceVO vmInstance = _vmDao.findById(vm.getId());
final Zone dc = _zoneRepository.findById(vmInstance.getDataCenterId()).orElse(null);
if (dc.getNetworkType() == com.cloud.model.enumeration.NetworkType.Basic) {
final List<NicVO> nics = _nicDao.listByVmId(vmInstance.getId());
final NetworkVO network = _networksDao.findById(nics.get(0).getNetworkId());
final LinkedHashMap<Network, List<? extends NicProfile>> profiles = new LinkedHashMap<>();
profiles.put(network, new ArrayList<>());
Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientCapacityException>() {
@Override
public void doInTransactionWithoutResult(final TransactionStatus status) throws InsufficientCapacityException {
cleanupNics(vm);
allocate(vm, profiles);
}
});
}
return true;
}
use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.
the class NetworkOrchestrator method shutdownNetworkResources.
private boolean shutdownNetworkResources(final long networkId, final Account caller, final long callerUserId) {
// This method cleans up network rules on the backend w/o touching them in the DB
boolean success = true;
final Network network = _networksDao.findById(networkId);
// Mark all PF rules as revoked and apply them on the backend (not in the DB)
final List<PortForwardingRuleVO> pfRules = _portForwardingRulesDao.listByNetwork(networkId);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + pfRules.size() + " port forwarding rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final PortForwardingRuleVO pfRule : pfRules) {
s_logger.trace("Marking pf rule " + pfRule + " with Revoke state");
pfRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(pfRules, true, false)) {
s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup pf rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
// Mark all static rules as revoked and apply them on the backend (not in the DB)
final List<FirewallRuleVO> firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(networkId, Purpose.StaticNat);
final List<StaticNatRule> staticNatRules = new ArrayList<>();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallStaticNatRules.size() + " static nat rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) {
s_logger.trace("Marking static nat rule " + firewallStaticNatRule + " with Revoke state");
final IpAddress ip = _ipAddressDao.findById(firewallStaticNatRule.getSourceIpAddressId());
final FirewallRuleVO ruleVO = _firewallDao.findById(firewallStaticNatRule.getId());
if (ip == null || !ip.isOneToOneNat() || ip.getAssociatedWithVmId() == null) {
throw new InvalidParameterValueException("Source ip address of the rule id=" + firewallStaticNatRule.getId() + " is not static nat enabled");
}
// String dstIp = _networkModel.getIpInNetwork(ip.getAssociatedWithVmId(), firewallStaticNatRule.getNetworkId());
ruleVO.setState(FirewallRule.State.Revoke);
staticNatRules.add(new StaticNatRuleImpl(ruleVO, ip.getVmIp()));
}
try {
if (!_firewallMgr.applyRules(staticNatRules, true, false)) {
s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup static nat rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
try {
if (!_lbMgr.revokeLoadBalancersForNetwork(networkId, Scheme.Public)) {
s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup public lb rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
// revoke all firewall rules for the network w/o applying them on the DB
final List<FirewallRuleVO> firewallRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Ingress);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallRules.size() + " firewall ingress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
for (final FirewallRuleVO firewallRule : firewallRules) {
s_logger.trace("Marking firewall ingress rule " + firewallRule + " with Revoke state");
firewallRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(firewallRules, true, false)) {
s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall ingress rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
final List<FirewallRuleVO> firewallEgressRules = _firewallDao.listByNetworkPurposeTrafficType(networkId, Purpose.Firewall, FirewallRule.TrafficType.Egress);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing " + firewallEgressRules.size() + " firewall egress rules for network id=" + networkId + " as a part of shutdownNetworkRules");
}
try {
// delete default egress rule
final Zone zone = _zoneRepository.findById(network.getDataCenterId()).orElse(null);
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Firewall) && (network.getGuestType() == GuestType.Isolated || network.getGuestType() == GuestType.Shared && zone.getNetworkType() == com.cloud.model.enumeration.NetworkType.Advanced)) {
// add default egress rule to accept the traffic
_firewallMgr.applyDefaultEgressFirewallRule(network.getId(), _networkModel.getNetworkEgressDefaultPolicy(networkId), false);
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall default egress rule as a part of shutdownNetworkRules due to ", ex);
success = false;
}
for (final FirewallRuleVO firewallRule : firewallEgressRules) {
s_logger.trace("Marking firewall egress rule " + firewallRule + " with Revoke state");
firewallRule.setState(FirewallRule.State.Revoke);
}
try {
if (!_firewallMgr.applyRules(firewallEgressRules, true, false)) {
s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup firewall egress rules as a part of shutdownNetworkRules due to ", ex);
success = false;
}
if (network.getVpcId() != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Releasing Network ACL Items for network id=" + networkId + " as a part of shutdownNetworkRules");
}
try {
// revoke all Network ACLs for the network w/o applying them in the DB
if (!_networkACLMgr.revokeACLItemsForNetwork(networkId)) {
s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException ex) {
s_logger.warn("Failed to cleanup network ACLs as a part of shutdownNetworkRules due to ", ex);
success = false;
}
}
// release all static nats for the network
if (!_rulesMgr.applyStaticNatForNetwork(networkId, false, caller, true)) {
s_logger.warn("Failed to disable static nats as part of shutdownNetworkRules for network id " + networkId);
success = false;
}
// Get all ip addresses, mark as releasing and release them on the backend
final List<IPAddressVO> userIps = _ipAddressDao.listByAssociatedNetwork(networkId, null);
final List<PublicIp> publicIpsToRelease = new ArrayList<>();
if (userIps != null && !userIps.isEmpty()) {
for (final IPAddressVO userIp : userIps) {
userIp.setState(IpAddress.State.Releasing);
final PublicIp publicIp = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
publicIpsToRelease.add(publicIp);
}
}
try {
if (!_ipAddrMgr.applyIpAssociations(network, true, true, publicIpsToRelease)) {
s_logger.warn("Unable to apply ip address associations for " + network + " as a part of shutdownNetworkRules");
success = false;
}
} catch (final ResourceUnavailableException e) {
throw new CloudRuntimeException("We should never get to here because we used true when applyIpAssociations", e);
}
return success;
}
use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.
the class VirtualMachineManagerImpl method orchestrateAddVmToNetwork.
@ReflectionUse
private Pair<JobInfo.Status, String> orchestrateAddVmToNetwork(final VmWorkAddVmToNetwork work) throws Exception {
final VMInstanceVO vm = _entityMgr.findById(VMInstanceVO.class, work.getVmId());
if (vm == null) {
s_logger.info("Unable to find vm " + work.getVmId());
}
assert vm != null;
final Network network = _networkDao.findById(work.getNetworkId());
final NicProfile nic = orchestrateAddVmToNetwork(vm, network, work.getRequestedNicProfile());
return new Pair<>(JobInfo.Status.SUCCEEDED, _jobMgr.marshallResultObject(nic));
}
use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.
the class SecondaryStorageManagerImpl method createSecStorageVmInstance.
protected Map<String, Object> createSecStorageVmInstance(final long dataCenterId, final SecondaryStorageVmRole role) {
final DataStore secStore = this._dataStoreMgr.getImageStore(dataCenterId);
if (secStore == null) {
final String msg = "No secondary storage available in zone " + dataCenterId + ", cannot create secondary storage vm";
logger.warn(msg);
throw new CloudRuntimeException(msg);
}
final long id = this._secStorageVmDao.getNextInSequence(Long.class, "id");
final String name = VirtualMachineName.getSystemVmName(id, this._instance, "s").intern();
final Account systemAcct = this._accountMgr.getSystemAccount();
final DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
final Zone zone = this.zoneRepository.findById(plan.getDataCenterId()).orElse(null);
final NetworkVO defaultNetwork = getDefaultNetworkForCreation(zone);
final List<? extends NetworkOffering> offerings;
if (this._sNwMgr.isStorageIpRangeAvailable(dataCenterId)) {
offerings = this._networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork, NetworkOffering.SystemStorageNetwork);
} else {
offerings = this._networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
}
final LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<>(offerings.size() + 1);
final NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
try {
networks.put(this._networkMgr.setupNetwork(systemAcct, this._networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0), new ArrayList<>(Arrays.asList(defaultNic)));
for (final NetworkOffering offering : offerings) {
networks.put(this._networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<>());
}
} catch (final ConcurrentOperationException e) {
logger.info("Unable to setup due to concurrent operation.", e);
return new HashMap<>();
}
final HypervisorType availableHypervisor = this._resourceMgr.getAvailableHypervisor(dataCenterId);
final String templateName = retrieveTemplateName(dataCenterId);
final VMTemplateVO template = this._templateDao.findRoutingTemplate(availableHypervisor, templateName, dataCenterId);
if (template == null) {
throw new CloudRuntimeException("Not able to find the System templates or not downloaded in zone " + dataCenterId);
}
ServiceOfferingVO serviceOffering = this._serviceOffering;
if (serviceOffering == null) {
serviceOffering = this._offeringDao.findDefaultSystemOffering(ServiceOffering.ssvmDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
}
SecondaryStorageVmVO secStorageVm = new SecondaryStorageVmVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId(), this._accountMgr.getSystemUser().getId(), role, serviceOffering.getOfferHA(), template.getOptimiseFor(), template.getManufacturerString(), template.getCpuFlags(), template.getMacLearning(), false, template.getMaintenancePolicy());
secStorageVm.setDynamicallyScalable(template.isDynamicallyScalable());
secStorageVm = this._secStorageVmDao.persist(secStorageVm);
try {
this._itMgr.allocate(name, template, serviceOffering, networks, plan, null);
secStorageVm = this._secStorageVmDao.findById(secStorageVm.getId());
} catch (final InsufficientCapacityException e) {
logger.warn("InsufficientCapacity", e);
throw new CloudRuntimeException("Insufficient capacity exception", e);
}
final Map<String, Object> context = new HashMap<>();
context.put("secStorageVmId", secStorageVm.getId());
return context;
}
use of com.cloud.legacymodel.network.Network in project cosmic by MissionCriticalCloud.
the class AccountManagerImpl method checkAccess.
@Override
public void checkAccess(final Account caller, final AccessType accessType, final boolean sameOwner, final String apiName, final ControlledEntity... entities) {
// check for the same owner
Long ownerId = null;
ControlledEntity prevEntity = null;
if (sameOwner) {
for (final ControlledEntity entity : entities) {
if (sameOwner) {
if (ownerId == null) {
ownerId = entity.getAccountId();
} else if (ownerId.longValue() != entity.getAccountId()) {
throw new PermissionDeniedException("Entity " + entity + " and entity " + prevEntity + " belong to different accounts");
}
prevEntity = entity;
}
}
}
if (caller.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(caller.getId())) {
// no need to make permission checks if the system/root admin makes the call
if (s_logger.isTraceEnabled()) {
s_logger.trace("No need to make permission check for System/RootAdmin account, returning true");
}
return;
}
final HashMap<Long, List<ControlledEntity>> domains = new HashMap<>();
for (final ControlledEntity entity : entities) {
long domainId = entity.getDomainId();
if (entity.getAccountId() != -1 && domainId == -1) {
// If account exists domainId should too so calculate
// it. This condition might be hit for templates or entities which miss domainId in their tables
final Account account = ApiDBUtils.findAccountById(entity.getAccountId());
domainId = account != null ? account.getDomainId() : -1;
}
if (entity.getAccountId() != -1 && domainId != -1 && !(entity instanceof VirtualMachineTemplate) && !(entity instanceof Network && accessType != null && accessType == AccessType.UseEntry) && !(entity instanceof AffinityGroup)) {
List<ControlledEntity> toBeChecked = domains.get(entity.getDomainId());
// for templates, we don't have to do cross domains check
if (toBeChecked == null) {
toBeChecked = new ArrayList<>();
domains.put(domainId, toBeChecked);
}
toBeChecked.add(entity);
}
boolean granted = false;
for (final SecurityChecker checker : _securityCheckers) {
if (checker.checkAccess(caller, entity, accessType, apiName)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Access to " + entity + " granted to " + caller + " by " + checker.getName());
}
granted = true;
break;
}
}
if (!granted) {
assert false : "How can all of the security checkers pass on checking this check: " + entity;
throw new PermissionDeniedException("There's no way to confirm " + caller + " has access to " + entity);
}
}
for (final Map.Entry<Long, List<ControlledEntity>> domain : domains.entrySet()) {
for (final SecurityChecker checker : _securityCheckers) {
final Domain d = _domainMgr.getDomain(domain.getKey());
if (d == null || d.getRemoved() != null) {
throw new PermissionDeniedException("Domain is not found.", caller, domain.getValue());
}
try {
checker.checkAccess(caller, d);
} catch (final PermissionDeniedException e) {
e.addDetails(caller, domain.getValue());
throw e;
}
}
}
// check that resources belong to the same account
}
Aggregations