use of com.cloud.network.rules.FirewallRuleVO in project cloudstack by apache.
the class NetworkServiceImpl method getPublicIpPurposeInRules.
private Set<Purpose> getPublicIpPurposeInRules(PublicIp ip, boolean includeRevoked, boolean includingFirewall) {
Set<Purpose> result = new HashSet<Purpose>();
List<FirewallRuleVO> rules = null;
if (includeRevoked) {
rules = _firewallDao.listByIp(ip.getId());
} else {
rules = _firewallDao.listByIpAndNotRevoked(ip.getId());
}
if (rules == null || rules.isEmpty()) {
return null;
}
for (FirewallRuleVO rule : rules) {
if (rule.getPurpose() != Purpose.Firewall || includingFirewall) {
result.add(rule.getPurpose());
}
}
return result;
}
use of com.cloud.network.rules.FirewallRuleVO in project cloudstack by apache.
the class BigSwitchBcfUtils method listACLbyNetwork.
public List<AclData> listACLbyNetwork(Network network) {
List<AclData> aclList = new ArrayList<AclData>();
List<FirewallRuleVO> fwRules;
fwRules = _fwRulesDao.listByNetworkAndPurposeAndNotRevoked(network.getId(), Purpose.Firewall);
List<FirewallRulesCidrsVO> fwCidrList = null;
SubnetUtils utils;
for (FirewallRuleVO rule : fwRules) {
AclData acl = new AclData();
acl.setId(rule.getUuid());
// CloudStack Firewall interface does not have priority
acl.setPriority((int) rule.getId());
acl.setIpProto(rule.getProtocol());
String cidr = null;
Integer port = rule.getSourcePortStart();
fwCidrList = _fwCidrsDao.listByFirewallRuleId(rule.getId());
if (fwCidrList != null) {
if (fwCidrList.size() > 1 || !rule.getSourcePortEnd().equals(port)) {
continue;
} else {
cidr = fwCidrList.get(0).getCidr();
}
}
if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
cidr = "";
} else {
utils = new SubnetUtils(cidr);
if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
continue;
}
}
acl.setSource(acl.new AclNetwork(cidr, port));
acl.setAction("permit");
aclList.add(acl);
}
List<NetworkACLItemVO> aclItems;
List<NetworkACLItemCidrsVO> aclCidrList;
if (network.getNetworkACLId() != null) {
aclItems = _aclItemDao.listByACL(network.getNetworkACLId());
for (NetworkACLItem item : aclItems) {
AclData acl = new AclData();
acl.setId(item.getUuid());
acl.setPriority(item.getNumber());
acl.setIpProto(item.getProtocol());
// currently BCF supports single cidr policy
String cidr = null;
// currently BCF supports single port policy
Integer port = item.getSourcePortStart();
aclCidrList = _aclItemCidrsDao.listByNetworkACLItemId(item.getId());
if (aclCidrList != null) {
if (aclCidrList.size() > 1 || !item.getSourcePortEnd().equals(port)) {
continue;
} else {
cidr = aclCidrList.get(0).getCidr();
}
}
if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
cidr = "";
} else {
utils = new SubnetUtils(cidr);
if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
continue;
}
}
acl.setSource(acl.new AclNetwork(cidr, port));
acl.setAction(item.getAction().name());
aclList.add(acl);
}
}
return aclList;
}
use of com.cloud.network.rules.FirewallRuleVO in project cloudstack by apache.
the class VirtualNetworkApplianceManagerImpl method createDefaultEgressFirewallRule.
private void createDefaultEgressFirewallRule(final List<FirewallRule> rules, final long networkId) {
final NetworkVO network = _networkDao.findById(networkId);
final NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId());
final Boolean defaultEgressPolicy = offering.getEgressDefaultPolicy();
// The default on the router is set to Deny all. So, if the default configuration in the offering is set to true (Allow), we change the Egress here
if (defaultEgressPolicy) {
final List<String> sourceCidr = new ArrayList<String>();
sourceCidr.add(NetUtils.ALL_CIDRS);
final FirewallRule rule = new FirewallRuleVO(null, null, null, null, "all", networkId, network.getAccountId(), network.getDomainId(), Purpose.Firewall, sourceCidr, null, null, null, FirewallRule.TrafficType.Egress, FirewallRule.FirewallRuleType.System);
rules.add(rule);
} else {
s_logger.debug("Egress policy for the Network " + networkId + " is already defined as Deny. So, no need to default the rule to Allow. ");
}
}
use of com.cloud.network.rules.FirewallRuleVO in project cloudstack by apache.
the class UserVmManagerImpl method moveVMToUser.
@DB
@Override
@ActionEvent(eventType = EventTypes.EVENT_VM_MOVE, eventDescription = "move VM to another user", async = false)
public UserVm moveVMToUser(final AssignVMCmd cmd) throws ResourceAllocationException, ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException {
// VERIFICATIONS and VALIDATIONS
// VV 1: verify the two users
Account caller = CallContext.current().getCallingAccount();
if (!_accountMgr.isRootAdmin(caller.getId()) && !_accountMgr.isDomainAdmin(caller.getId())) {
// VMs
throw new InvalidParameterValueException("Only domain admins are allowed to assign VMs and not " + caller.getType());
}
// get and check the valid VM
final UserVmVO vm = _vmDao.findById(cmd.getVmId());
if (vm == null) {
throw new InvalidParameterValueException("There is no vm by that id " + cmd.getVmId());
} else if (vm.getState() == State.Running) {
// running
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM is Running, unable to move the vm " + vm);
}
InvalidParameterValueException ex = new InvalidParameterValueException("VM is Running, unable to move the vm with specified vmId");
ex.addProxyObject(vm.getUuid(), "vmId");
throw ex;
}
final Account oldAccount = _accountService.getActiveAccountById(vm.getAccountId());
if (oldAccount == null) {
throw new InvalidParameterValueException("Invalid account for VM " + vm.getAccountId() + " in domain.");
}
final Account newAccount = _accountMgr.finalizeOwner(caller, cmd.getAccountName(), cmd.getDomainId(), cmd.getProjectId());
if (newAccount == null) {
throw new InvalidParameterValueException("Invalid accountid=" + cmd.getAccountName() + " in domain " + cmd.getDomainId());
}
if (newAccount.getState() == Account.State.disabled) {
throw new InvalidParameterValueException("The new account owner " + cmd.getAccountName() + " is disabled.");
}
//check caller has access to both the old and new account
_accountMgr.checkAccess(caller, null, true, oldAccount);
_accountMgr.checkAccess(caller, null, true, newAccount);
// make sure the accounts are not same
if (oldAccount.getAccountId() == newAccount.getAccountId()) {
throw new InvalidParameterValueException("The new account is the same as the old account. Account id =" + oldAccount.getAccountId());
}
// don't allow to move the vm if there are existing PF/LB/Static Nat
// rules, or vm is assigned to static Nat ip
List<PortForwardingRuleVO> pfrules = _portForwardingDao.listByVm(cmd.getVmId());
if (pfrules != null && pfrules.size() > 0) {
throw new InvalidParameterValueException("Remove the Port forwarding rules for this VM before assigning to another user.");
}
List<FirewallRuleVO> snrules = _rulesDao.listStaticNatByVmId(vm.getId());
if (snrules != null && snrules.size() > 0) {
throw new InvalidParameterValueException("Remove the StaticNat rules for this VM before assigning to another user.");
}
List<LoadBalancerVMMapVO> maps = _loadBalancerVMMapDao.listByInstanceId(vm.getId());
if (maps != null && maps.size() > 0) {
throw new InvalidParameterValueException("Remove the load balancing rules for this VM before assigning to another user.");
}
// check for one on one nat
List<IPAddressVO> ips = _ipAddressDao.findAllByAssociatedVmId(cmd.getVmId());
for (IPAddressVO ip : ips) {
if (ip.isOneToOneNat()) {
throw new InvalidParameterValueException("Remove the one to one nat rule for this VM for ip " + ip.toString());
}
}
DataCenterVO zone = _dcDao.findById(vm.getDataCenterId());
// Get serviceOffering and Volumes for Virtual Machine
final ServiceOfferingVO offering = _serviceOfferingDao.findByIdIncludingRemoved(vm.getId(), vm.getServiceOfferingId());
final List<VolumeVO> volumes = _volsDao.findByInstance(cmd.getVmId());
//Remove vm from instance group
removeInstanceFromInstanceGroup(cmd.getVmId());
// VV 2: check if account/domain is with in resource limits to create a new vm
resourceLimitCheck(newAccount, vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
// VV 3: check if volumes and primary storage space are with in resource limits
_resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.volume, _volsDao.findByInstance(cmd.getVmId()).size());
Long totalVolumesSize = (long) 0;
for (VolumeVO volume : volumes) {
totalVolumesSize += volume.getSize();
}
_resourceLimitMgr.checkResourceLimit(newAccount, ResourceType.primary_storage, totalVolumesSize);
// VV 4: Check if new owner can use the vm template
VirtualMachineTemplate template = _templateDao.findById(vm.getTemplateId());
if (!template.isPublicTemplate()) {
Account templateOwner = _accountMgr.getAccount(template.getAccountId());
_accountMgr.checkAccess(newAccount, null, true, templateOwner);
}
// VV 5: check the new account can create vm in the domain
DomainVO domain = _domainDao.findById(cmd.getDomainId());
_accountMgr.checkAccess(newAccount, domain);
Transaction.execute(new TransactionCallbackNoReturn() {
@Override
public void doInTransactionWithoutResult(TransactionStatus status) {
//generate destroy vm event for usage
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_DESTROY, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
// update resource counts for old account
resourceCountDecrement(oldAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
// OWNERSHIP STEP 1: update the vm owner
vm.setAccountId(newAccount.getAccountId());
vm.setDomainId(cmd.getDomainId());
_vmDao.persist(vm);
// OS 2: update volume
for (VolumeVO volume : volumes) {
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_DELETE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
_resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.volume);
_resourceLimitMgr.decrementResourceCount(oldAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
volume.setAccountId(newAccount.getAccountId());
volume.setDomainId(newAccount.getDomainId());
_volsDao.persist(volume);
_resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.volume);
_resourceLimitMgr.incrementResourceCount(newAccount.getAccountId(), ResourceType.primary_storage, new Long(volume.getSize()));
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VOLUME_CREATE, volume.getAccountId(), volume.getDataCenterId(), volume.getId(), volume.getName(), volume.getDiskOfferingId(), volume.getTemplateId(), volume.getSize(), Volume.class.getName(), volume.getUuid(), volume.isDisplayVolume());
//snapshots: mark these removed in db
List<SnapshotVO> snapshots = _snapshotDao.listByVolumeIdIncludingRemoved(volume.getId());
for (SnapshotVO snapshot : snapshots) {
_snapshotDao.remove(snapshot.getId());
}
}
//update resource count of new account
resourceCountIncrement(newAccount.getAccountId(), vm.isDisplayVm(), new Long(offering.getCpu()), new Long(offering.getRamSize()));
//generate usage events to account for this change
UsageEventUtils.publishUsageEvent(EventTypes.EVENT_VM_CREATE, vm.getAccountId(), vm.getDataCenterId(), vm.getId(), vm.getHostName(), vm.getServiceOfferingId(), vm.getTemplateId(), vm.getHypervisorType().toString(), VirtualMachine.class.getName(), vm.getUuid(), vm.isDisplayVm());
}
});
VirtualMachine vmoi = _itMgr.findById(vm.getId());
VirtualMachineProfileImpl vmOldProfile = new VirtualMachineProfileImpl(vmoi);
// OS 3: update the network
List<Long> networkIdList = cmd.getNetworkIds();
List<Long> securityGroupIdList = cmd.getSecurityGroupIdList();
if (zone.getNetworkType() == NetworkType.Basic) {
if (networkIdList != null && !networkIdList.isEmpty()) {
throw new InvalidParameterValueException("Can't move vm with network Ids; this is a basic zone VM");
}
// cleanup the old security groups
_securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
// cleanup the network for the oldOwner
_networkMgr.cleanupNics(vmOldProfile);
_networkMgr.expungeNics(vmOldProfile);
// security groups will be recreated for the new account, when the
// VM is started
List<NetworkVO> networkList = new ArrayList<NetworkVO>();
// Get default guest network in Basic zone
Network defaultNetwork = _networkModel.getExclusiveGuestNetwork(zone.getId());
if (defaultNetwork == null) {
throw new InvalidParameterValueException("Unable to find a default network to start a vm");
} else {
networkList.add(_networkDao.findById(defaultNetwork.getId()));
}
boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
if (securityGroupIdList != null && isVmWare) {
throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
} else if (!isVmWare && _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork) && _networkModel.canAddDefaultSecurityGroup()) {
if (securityGroupIdList == null) {
securityGroupIdList = new ArrayList<Long>();
}
SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
if (defaultGroup != null) {
// check if security group id list already contains Default
// security group, and if not - add it
boolean defaultGroupPresent = false;
for (Long securityGroupId : securityGroupIdList) {
if (securityGroupId.longValue() == defaultGroup.getId()) {
defaultGroupPresent = true;
break;
}
}
if (!defaultGroupPresent) {
securityGroupIdList.add(defaultGroup.getId());
}
} else {
// create default security group for the account
if (s_logger.isDebugEnabled()) {
s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
}
defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
securityGroupIdList.add(defaultGroup.getId());
}
}
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
NicProfile profile = new NicProfile();
profile.setDefaultNic(true);
networks.put(networkList.get(0), new ArrayList<NicProfile>(Arrays.asList(profile)));
VirtualMachine vmi = _itMgr.findById(vm.getId());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
_networkMgr.allocate(vmProfile, networks);
_securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
s_logger.debug("AssignVM: Basic zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
} else {
if (zone.isSecurityGroupEnabled()) {
// advanced zone with security groups
// cleanup the old security groups
_securityGroupMgr.removeInstanceFromGroups(cmd.getVmId());
Set<NetworkVO> applicableNetworks = new HashSet<NetworkVO>();
String requestedIPv4ForDefaultNic = null;
String requestedIPv6ForDefaultNic = null;
// if networkIdList is null and the first network of vm is shared network, then keep it if possible
if (networkIdList == null || networkIdList.isEmpty()) {
NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
if (defaultNicOld != null) {
NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
if (defaultNetworkOld != null && defaultNetworkOld.getGuestType() == Network.GuestType.Shared && defaultNetworkOld.getAclType() == ACLType.Domain) {
try {
_networkModel.checkNetworkPermissions(newAccount, defaultNetworkOld);
applicableNetworks.add(defaultNetworkOld);
requestedIPv4ForDefaultNic = defaultNicOld.getIPv4Address();
requestedIPv6ForDefaultNic = defaultNicOld.getIPv6Address();
s_logger.debug("AssignVM: use old shared network " + defaultNetworkOld.getName() + " with old ip " + requestedIPv4ForDefaultNic + " on default nic of vm:" + vm.getInstanceName());
} catch (PermissionDeniedException e) {
s_logger.debug("AssignVM: the shared network on old default nic can not be applied to new account");
}
}
}
}
// cleanup the network for the oldOwner
_networkMgr.cleanupNics(vmOldProfile);
_networkMgr.expungeNics(vmOldProfile);
if (networkIdList != null && !networkIdList.isEmpty()) {
// add any additional networks
for (Long networkId : networkIdList) {
NetworkVO network = _networkDao.findById(networkId);
if (network == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
ex.addProxyObject(networkId.toString(), "networkId");
throw ex;
}
_networkModel.checkNetworkPermissions(newAccount, network);
// don't allow to use system networks
NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (networkOffering.isSystemOnly()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
applicableNetworks.add(network);
}
}
// add the new nics
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
int toggle = 0;
NetworkVO defaultNetwork = null;
for (NetworkVO appNet : applicableNetworks) {
NicProfile defaultNic = new NicProfile();
if (toggle == 0) {
defaultNic.setDefaultNic(true);
defaultNic.setRequestedIPv4(requestedIPv4ForDefaultNic);
defaultNic.setRequestedIPv6(requestedIPv6ForDefaultNic);
defaultNetwork = appNet;
toggle++;
}
networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
}
boolean isVmWare = (template.getHypervisorType() == HypervisorType.VMware);
if (securityGroupIdList != null && isVmWare) {
throw new InvalidParameterValueException("Security group feature is not supported for vmWare hypervisor");
} else if (!isVmWare && (defaultNetwork == null || _networkModel.isSecurityGroupSupportedInNetwork(defaultNetwork)) && _networkModel.canAddDefaultSecurityGroup()) {
if (securityGroupIdList == null) {
securityGroupIdList = new ArrayList<Long>();
}
SecurityGroup defaultGroup = _securityGroupMgr.getDefaultSecurityGroup(newAccount.getId());
if (defaultGroup != null) {
// check if security group id list already contains Default
// security group, and if not - add it
boolean defaultGroupPresent = false;
for (Long securityGroupId : securityGroupIdList) {
if (securityGroupId.longValue() == defaultGroup.getId()) {
defaultGroupPresent = true;
break;
}
}
if (!defaultGroupPresent) {
securityGroupIdList.add(defaultGroup.getId());
}
} else {
// create default security group for the account
if (s_logger.isDebugEnabled()) {
s_logger.debug("Couldn't find default security group for the account " + newAccount + " so creating a new one");
}
defaultGroup = _securityGroupMgr.createSecurityGroup(SecurityGroupManager.DEFAULT_GROUP_NAME, SecurityGroupManager.DEFAULT_GROUP_DESCRIPTION, newAccount.getDomainId(), newAccount.getId(), newAccount.getAccountName());
securityGroupIdList.add(defaultGroup.getId());
}
}
VirtualMachine vmi = _itMgr.findById(vm.getId());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
if (applicableNetworks.isEmpty()) {
throw new InvalidParameterValueException("No network is specified, please specify one when you move the vm. For now, please add a network to VM on NICs tab.");
} else {
_networkMgr.allocate(vmProfile, networks);
}
_securityGroupMgr.addInstanceToGroups(vm.getId(), securityGroupIdList);
s_logger.debug("AssignVM: Advanced zone, adding security groups no " + securityGroupIdList.size() + " to " + vm.getInstanceName());
} else {
if (securityGroupIdList != null && !securityGroupIdList.isEmpty()) {
throw new InvalidParameterValueException("Can't move vm with security groups; security group feature is not enabled in this zone");
}
Set<NetworkVO> applicableNetworks = new HashSet<NetworkVO>();
// if networkIdList is null and the first network of vm is shared network, then keep it if possible
if (networkIdList == null || networkIdList.isEmpty()) {
NicVO defaultNicOld = _nicDao.findDefaultNicForVM(vm.getId());
if (defaultNicOld != null) {
NetworkVO defaultNetworkOld = _networkDao.findById(defaultNicOld.getNetworkId());
if (defaultNetworkOld != null && defaultNetworkOld.getGuestType() == Network.GuestType.Shared && defaultNetworkOld.getAclType() == ACLType.Domain) {
try {
_networkModel.checkNetworkPermissions(newAccount, defaultNetworkOld);
applicableNetworks.add(defaultNetworkOld);
} catch (PermissionDeniedException e) {
s_logger.debug("AssignVM: the shared network on old default nic can not be applied to new account");
}
}
}
}
// cleanup the network for the oldOwner
_networkMgr.cleanupNics(vmOldProfile);
_networkMgr.expungeNics(vmOldProfile);
if (networkIdList != null && !networkIdList.isEmpty()) {
// add any additional networks
for (Long networkId : networkIdList) {
NetworkVO network = _networkDao.findById(networkId);
if (network == null) {
InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find specified network id");
ex.addProxyObject(networkId.toString(), "networkId");
throw ex;
}
_networkModel.checkNetworkPermissions(newAccount, network);
// don't allow to use system networks
NetworkOffering networkOffering = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId());
if (networkOffering.isSystemOnly()) {
InvalidParameterValueException ex = new InvalidParameterValueException("Specified Network id is system only and can't be used for vm deployment");
ex.addProxyObject(network.getUuid(), "networkId");
throw ex;
}
applicableNetworks.add(network);
}
} else if (applicableNetworks.isEmpty()) {
NetworkVO defaultNetwork = null;
List<NetworkOfferingVO> requiredOfferings = _networkOfferingDao.listByAvailability(Availability.Required, false);
if (requiredOfferings.size() < 1) {
throw new InvalidParameterValueException("Unable to find network offering with availability=" + Availability.Required + " to automatically create the network as a part of vm creation");
}
if (requiredOfferings.get(0).getState() == NetworkOffering.State.Enabled) {
// get Virtual networks
List<? extends Network> virtualNetworks = _networkModel.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated);
if (virtualNetworks.isEmpty()) {
long physicalNetworkId = _networkModel.findPhysicalNetworkId(zone.getId(), requiredOfferings.get(0).getTags(), requiredOfferings.get(0).getTrafficType());
// Validate physical network
PhysicalNetwork physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
if (physicalNetwork == null) {
throw new InvalidParameterValueException("Unable to find physical network with id: " + physicalNetworkId + " and tag: " + requiredOfferings.get(0).getTags());
}
s_logger.debug("Creating network for account " + newAccount + " from the network offering id=" + requiredOfferings.get(0).getId() + " as a part of deployVM process");
Network newNetwork = _networkMgr.createGuestNetwork(requiredOfferings.get(0).getId(), newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null, null, null, true, null);
// if the network offering has persistent set to true, implement the network
if (requiredOfferings.get(0).getIsPersistent()) {
DeployDestination dest = new DeployDestination(zone, null, null, null);
UserVO callerUser = _userDao.findById(CallContext.current().getCallingUserId());
Journal journal = new Journal.LogJournal("Implementing " + newNetwork, s_logger);
ReservationContext context = new ReservationContextImpl(UUID.randomUUID().toString(), journal, callerUser, caller);
s_logger.debug("Implementing the network for account" + newNetwork + " as a part of" + " network provision for persistent networks");
try {
Pair<? extends NetworkGuru, ? extends Network> implementedNetwork = _networkMgr.implementNetwork(newNetwork.getId(), dest, context);
if (implementedNetwork == null || implementedNetwork.first() == null) {
s_logger.warn("Failed to implement the network " + newNetwork);
}
newNetwork = implementedNetwork.second();
} catch (Exception ex) {
s_logger.warn("Failed to implement network " + newNetwork + " elements and" + " resources as a part of network provision for persistent network due to ", ex);
CloudRuntimeException e = new CloudRuntimeException("Failed to implement network" + " (with specified id) elements and resources as a part of network provision");
e.addProxyObject(newNetwork.getUuid(), "networkId");
throw e;
}
}
defaultNetwork = _networkDao.findById(newNetwork.getId());
} else if (virtualNetworks.size() > 1) {
throw new InvalidParameterValueException("More than 1 default Isolated networks are found " + "for account " + newAccount + "; please specify networkIds");
} else {
defaultNetwork = _networkDao.findById(virtualNetworks.get(0).getId());
}
} else {
throw new InvalidParameterValueException("Required network offering id=" + requiredOfferings.get(0).getId() + " is not in " + NetworkOffering.State.Enabled);
}
applicableNetworks.add(defaultNetwork);
}
// add the new nics
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>();
int toggle = 0;
for (NetworkVO appNet : applicableNetworks) {
NicProfile defaultNic = new NicProfile();
if (toggle == 0) {
defaultNic.setDefaultNic(true);
toggle++;
}
networks.put(appNet, new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
}
VirtualMachine vmi = _itMgr.findById(vm.getId());
VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vmi);
_networkMgr.allocate(vmProfile, networks);
s_logger.debug("AssignVM: Advance virtual, adding networks no " + networks.size() + " to " + vm.getInstanceName());
}
// END IF NON SEC GRP ENABLED
}
// END IF ADVANCED
s_logger.info("AssignVM: vm " + vm.getInstanceName() + " now belongs to account " + newAccount.getAccountName());
return vm;
}
use of com.cloud.network.rules.FirewallRuleVO in project cloudstack by apache.
the class FirewallManagerTest method testApplyFWRules.
@Ignore("Requires database to be set up")
@Test
public void testApplyFWRules() {
List<FirewallRuleVO> ruleList = new ArrayList<FirewallRuleVO>();
FirewallRuleVO rule = new FirewallRuleVO("rule1", 1, 80, "TCP", 1, 2, 1, FirewallRule.Purpose.Firewall, null, null, null, null);
ruleList.add(rule);
FirewallManagerImpl firewallMgr = (FirewallManagerImpl) _firewallMgr;
VirtualRouterElement virtualRouter = mock(VirtualRouterElement.class);
VpcVirtualRouterElement vpcVirtualRouter = mock(VpcVirtualRouterElement.class);
List<FirewallServiceProvider> fwElements = new ArrayList<FirewallServiceProvider>();
fwElements.add(ComponentContext.inject(VirtualRouterElement.class));
fwElements.add(ComponentContext.inject(VpcVirtualRouterElement.class));
firewallMgr._firewallElements = fwElements;
try {
when(virtualRouter.applyFWRules(any(Network.class), any(List.class))).thenReturn(false);
when(vpcVirtualRouter.applyFWRules(any(Network.class), any(List.class))).thenReturn(true);
//Network network, Purpose purpose, List<? extends FirewallRule> rules
firewallMgr.applyRules(mock(Network.class), Purpose.Firewall, ruleList);
verify(vpcVirtualRouter).applyFWRules(any(Network.class), any(List.class));
verify(virtualRouter).applyFWRules(any(Network.class), any(List.class));
} catch (ResourceUnavailableException e) {
Assert.fail("Unreachable code");
}
}
Aggregations