use of com.cloud.network.Network in project cloudstack by apache.
the class MidoNetElementTest method testImplement.
/*
* Test the standard case of implement with no errors.
*/
public void testImplement() {
//mock
MidonetApi api = mock(MidonetApi.class, RETURNS_DEEP_STUBS);
//mockAccountDao
AccountDao mockAccountDao = mock(AccountDao.class);
AccountVO mockAccountVO = mock(AccountVO.class);
when(mockAccountDao.findById(anyLong())).thenReturn(mockAccountVO);
when(mockAccountVO.getUuid()).thenReturn("1");
MidoNetElement elem = new MidoNetElement();
elem.setMidonetApi(api);
elem.setAccountDao(mockAccountDao);
//mockRPort
RouterPort mockRPort = mock(RouterPort.class);
when(mockRPort.getId()).thenReturn(UUID.fromString("550e8400-e29b-41d4-a716-446655440000"));
//mockBPort
BridgePort mockBPort = mock(BridgePort.class);
when(mockBPort.link(any(UUID.class))).thenReturn(mockBPort);
//mockPort
Port mockPort = mock(Port.class);
ResourceCollection<Port> peerPorts = new ResourceCollection<Port>(new ArrayList<Port>());
peerPorts.add(mockPort);
//mockBridge
Bridge mockBridge = mock(Bridge.class, RETURNS_DEEP_STUBS);
when(api.addBridge().tenantId(anyString()).name(anyString()).create()).thenReturn(mockBridge);
when(mockBridge.addInteriorPort().create()).thenReturn(mockBPort);
when(mockBridge.getPeerPorts()).thenReturn(peerPorts);
//mockRouter
Router mockRouter = mock(Router.class, RETURNS_DEEP_STUBS);
when(api.addRouter().tenantId(anyString()).name(anyString()).create()).thenReturn(mockRouter);
when(mockRouter.addInteriorRouterPort().create()).thenReturn(mockRPort);
//mockNetwork
Network mockNetwork = mock(Network.class);
when(mockNetwork.getAccountId()).thenReturn((long) 1);
when(mockNetwork.getGateway()).thenReturn("1.2.3.4");
when(mockNetwork.getCidr()).thenReturn("1.2.3.0/24");
when(mockNetwork.getId()).thenReturn((long) 2);
when(mockNetwork.getBroadcastDomainType()).thenReturn(Networks.BroadcastDomainType.Mido);
when(mockNetwork.getTrafficType()).thenReturn(Networks.TrafficType.Public);
boolean result = false;
try {
result = elem.implement(mockNetwork, null, null, null);
} catch (ConcurrentOperationException e) {
fail(e.getMessage());
} catch (InsufficientCapacityException e) {
fail(e.getMessage());
} catch (ResourceUnavailableException e) {
fail(e.getMessage());
}
assertEquals(result, true);
}
use of com.cloud.network.Network in project cloudstack by apache.
the class ConfigurationManagerImpl method searchForNetworkOfferings.
@Override
public Pair<List<? extends NetworkOffering>, Integer> searchForNetworkOfferings(final ListNetworkOfferingsCmd cmd) {
Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm"));
isAscending = isAscending == null ? Boolean.TRUE : isAscending;
final Filter searchFilter = new Filter(NetworkOfferingVO.class, "sortKey", isAscending, null, null);
final Account caller = CallContext.current().getCallingAccount();
final SearchCriteria<NetworkOfferingVO> sc = _networkOfferingDao.createSearchCriteria();
final Long id = cmd.getId();
final Object name = cmd.getNetworkOfferingName();
final Object displayText = cmd.getDisplayText();
final Object trafficType = cmd.getTrafficType();
final Object isDefault = cmd.getIsDefault();
final Object specifyVlan = cmd.getSpecifyVlan();
final Object availability = cmd.getAvailability();
final Object state = cmd.getState();
final Long zoneId = cmd.getZoneId();
DataCenter zone = null;
final Long networkId = cmd.getNetworkId();
final String guestIpType = cmd.getGuestIpType();
final List<String> supportedServicesStr = cmd.getSupportedServices();
final Object specifyIpRanges = cmd.getSpecifyIpRanges();
final String tags = cmd.getTags();
final Boolean isTagged = cmd.isTagged();
final Boolean forVpc = cmd.getForVpc();
if (zoneId != null) {
zone = _entityMgr.findById(DataCenter.class, zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Unable to find the zone by id=" + zoneId);
}
}
final Object keyword = cmd.getKeyword();
if (keyword != null) {
final SearchCriteria<NetworkOfferingVO> ssc = _networkOfferingDao.createSearchCriteria();
ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%");
ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%");
sc.addAnd("name", SearchCriteria.Op.SC, ssc);
}
if (name != null) {
sc.addAnd("name", SearchCriteria.Op.EQ, name);
}
if (guestIpType != null) {
sc.addAnd("guestType", SearchCriteria.Op.EQ, guestIpType);
}
if (displayText != null) {
sc.addAnd("displayText", SearchCriteria.Op.LIKE, "%" + displayText + "%");
}
if (trafficType != null) {
sc.addAnd("trafficType", SearchCriteria.Op.EQ, trafficType);
}
if (isDefault != null) {
sc.addAnd("isDefault", SearchCriteria.Op.EQ, isDefault);
}
// only root admin can list network offering with specifyVlan = true
if (specifyVlan != null) {
sc.addAnd("specifyVlan", SearchCriteria.Op.EQ, specifyVlan);
}
if (availability != null) {
sc.addAnd("availability", SearchCriteria.Op.EQ, availability);
}
if (state != null) {
sc.addAnd("state", SearchCriteria.Op.EQ, state);
}
if (specifyIpRanges != null) {
sc.addAnd("specifyIpRanges", SearchCriteria.Op.EQ, specifyIpRanges);
}
if (zone != null) {
if (zone.getNetworkType() == NetworkType.Basic) {
// basic zone, and shouldn't display networkOfferings
return new Pair<List<? extends NetworkOffering>, Integer>(new ArrayList<NetworkOffering>(), 0);
}
}
// Don't return system network offerings to the user
sc.addAnd("systemOnly", SearchCriteria.Op.EQ, false);
// if networkId is specified, list offerings available for upgrade only
// (for this network)
Network network = null;
if (networkId != null) {
// check if network exists and the caller can operate with it
network = _networkModel.getNetwork(networkId);
if (network == null) {
throw new InvalidParameterValueException("Unable to find the network by id=" + networkId);
}
// Don't allow to update system network
final NetworkOffering offering = _networkOfferingDao.findByIdIncludingRemoved(network.getNetworkOfferingId());
if (offering.isSystemOnly()) {
throw new InvalidParameterValueException("Can't update system networks");
}
_accountMgr.checkAccess(caller, null, true, network);
final List<Long> offeringIds = _networkModel.listNetworkOfferingsForUpgrade(networkId);
if (!offeringIds.isEmpty()) {
sc.addAnd("id", SearchCriteria.Op.IN, offeringIds.toArray());
} else {
return new Pair<List<? extends NetworkOffering>, Integer>(new ArrayList<NetworkOffering>(), 0);
}
}
if (id != null) {
sc.addAnd("id", SearchCriteria.Op.EQ, id);
}
if (tags != null) {
sc.addAnd("tags", SearchCriteria.Op.EQ, tags);
}
if (isTagged != null) {
if (isTagged) {
sc.addAnd("tags", SearchCriteria.Op.NNULL);
} else {
sc.addAnd("tags", SearchCriteria.Op.NULL);
}
}
final List<NetworkOfferingVO> offerings = _networkOfferingDao.search(sc, searchFilter);
final Boolean sourceNatSupported = cmd.getSourceNatSupported();
final List<String> pNtwkTags = new ArrayList<String>();
boolean checkForTags = false;
if (zone != null) {
final List<PhysicalNetworkVO> pNtwks = _physicalNetworkDao.listByZoneAndTrafficType(zoneId, TrafficType.Guest);
if (pNtwks.size() > 1) {
checkForTags = true;
// go through tags
for (final PhysicalNetworkVO pNtwk : pNtwks) {
final List<String> pNtwkTag = pNtwk.getTags();
if (pNtwkTag == null || pNtwkTag.isEmpty()) {
throw new CloudRuntimeException("Tags are not defined for physical network in the zone id=" + zoneId);
}
pNtwkTags.addAll(pNtwkTag);
}
}
}
// filter by supported services
final boolean listBySupportedServices = supportedServicesStr != null && !supportedServicesStr.isEmpty() && !offerings.isEmpty();
final boolean checkIfProvidersAreEnabled = zoneId != null;
final boolean parseOfferings = listBySupportedServices || sourceNatSupported != null || checkIfProvidersAreEnabled || forVpc != null || network != null;
if (parseOfferings) {
final List<NetworkOfferingVO> supportedOfferings = new ArrayList<NetworkOfferingVO>();
Service[] supportedServices = null;
if (listBySupportedServices) {
supportedServices = new Service[supportedServicesStr.size()];
int i = 0;
for (final String supportedServiceStr : supportedServicesStr) {
final Service service = Service.getService(supportedServiceStr);
if (service == null) {
throw new InvalidParameterValueException("Invalid service specified " + supportedServiceStr);
} else {
supportedServices[i] = service;
}
i++;
}
}
for (final NetworkOfferingVO offering : offerings) {
boolean addOffering = true;
List<Service> checkForProviders = new ArrayList<Service>();
if (checkForTags) {
if (!pNtwkTags.contains(offering.getTags())) {
continue;
}
}
if (listBySupportedServices) {
addOffering = addOffering && _networkModel.areServicesSupportedByNetworkOffering(offering.getId(), supportedServices);
}
if (checkIfProvidersAreEnabled) {
if (supportedServices != null && supportedServices.length > 0) {
checkForProviders = Arrays.asList(supportedServices);
} else {
checkForProviders = _networkModel.listNetworkOfferingServices(offering.getId());
}
addOffering = addOffering && _networkModel.areServicesEnabledInZone(zoneId, offering, checkForProviders);
}
if (sourceNatSupported != null) {
addOffering = addOffering && _networkModel.areServicesSupportedByNetworkOffering(offering.getId(), Network.Service.SourceNat) == sourceNatSupported;
}
if (forVpc != null) {
addOffering = addOffering && isOfferingForVpc(offering) == forVpc.booleanValue();
} else if (network != null) {
addOffering = addOffering && isOfferingForVpc(offering) == (network.getVpcId() != null);
}
if (addOffering) {
supportedOfferings.add(offering);
}
}
// Now apply pagination
final List<? extends NetworkOffering> wPagination = StringUtils.applyPagination(supportedOfferings, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
final Pair<List<? extends NetworkOffering>, Integer> listWPagination = new Pair<List<? extends NetworkOffering>, Integer>(wPagination, offerings.size());
return listWPagination;
}
return new Pair<List<? extends NetworkOffering>, Integer>(supportedOfferings, supportedOfferings.size());
} else {
final List<? extends NetworkOffering> wPagination = StringUtils.applyPagination(offerings, cmd.getStartIndex(), cmd.getPageSizeVal());
if (wPagination != null) {
final Pair<List<? extends NetworkOffering>, Integer> listWPagination = new Pair<List<? extends NetworkOffering>, Integer>(wPagination, offerings.size());
return listWPagination;
}
return new Pair<List<? extends NetworkOffering>, Integer>(offerings, offerings.size());
}
}
use of com.cloud.network.Network in project cloudstack by apache.
the class ConfigurationManagerImpl method createVlanAndPublicIpRange.
@Override
@DB
public Vlan createVlanAndPublicIpRange(final long zoneId, final long networkId, final long physicalNetworkId, final boolean forVirtualNetwork, final Long podId, final String startIP, final String endIP, final String vlanGateway, final String vlanNetmask, String vlanId, Domain domain, final Account vlanOwner, final String startIPv6, final String endIPv6, final String vlanIp6Gateway, final String vlanIp6Cidr) {
final Network network = _networkModel.getNetwork(networkId);
boolean ipv4 = false, ipv6 = false;
if (startIP != null) {
ipv4 = true;
}
if (startIPv6 != null) {
ipv6 = true;
}
if (!ipv4 && !ipv6) {
throw new InvalidParameterValueException("Please specify IPv4 or IPv6 address.");
}
// Validate the zone
final DataCenterVO zone = _zoneDao.findById(zoneId);
if (zone == null) {
throw new InvalidParameterValueException("Please specify a valid zone.");
}
// ACL check
checkZoneAccess(CallContext.current().getCallingAccount(), zone);
// Validate the physical network
if (_physicalNetworkDao.findById(physicalNetworkId) == null) {
throw new InvalidParameterValueException("Please specify a valid physical network id");
}
// Validate the pod
if (podId != null) {
final Pod pod = _podDao.findById(podId);
if (pod == null) {
throw new InvalidParameterValueException("Please specify a valid pod.");
}
if (pod.getDataCenterId() != zoneId) {
throw new InvalidParameterValueException("Pod id=" + podId + " doesn't belong to zone id=" + zoneId);
}
// pod vlans can be created in basic zone only
if (zone.getNetworkType() != NetworkType.Basic || network.getTrafficType() != TrafficType.Guest) {
throw new InvalidParameterValueException("Pod id can be specified only for the networks of type " + TrafficType.Guest + " in zone of type " + NetworkType.Basic);
}
}
// 2) if vlan is missing, default it to the guest network's vlan
if (network.getTrafficType() == TrafficType.Guest) {
String networkVlanId = null;
boolean connectivityWithoutVlan = false;
if (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.Connectivity)) {
Map<Capability, String> connectivityCapabilities = _networkModel.getNetworkServiceCapabilities(network.getId(), Service.Connectivity);
connectivityWithoutVlan = MapUtils.isNotEmpty(connectivityCapabilities) && connectivityCapabilities.containsKey(Capability.NoVlan);
}
final URI uri = network.getBroadcastUri();
if (connectivityWithoutVlan) {
networkVlanId = network.getBroadcastDomainType().toUri(network.getUuid()).toString();
} else if (uri != null) {
// Do not search for the VLAN tag when the network doesn't support VLAN
if (uri.toString().startsWith("vlan")) {
final String[] vlan = uri.toString().split("vlan:\\/\\/");
networkVlanId = vlan[1];
// For pvlan
networkVlanId = networkVlanId.split("-")[0];
}
}
if (vlanId != null && !connectivityWithoutVlan) {
// network's vlanId
if (networkVlanId != null && !NetUtils.isSameIsolationId(networkVlanId, vlanId)) {
throw new InvalidParameterValueException("Vlan doesn't match vlan of the network");
}
} else {
vlanId = networkVlanId;
}
} else if (network.getTrafficType() == TrafficType.Public && vlanId == null) {
throw new InvalidParameterValueException("Unable to determine vlan id or untagged vlan for public network");
}
if (vlanId == null) {
vlanId = Vlan.UNTAGGED;
}
final VlanType vlanType = forVirtualNetwork ? VlanType.VirtualNetwork : VlanType.DirectAttached;
if ((domain != null || vlanOwner != null) && zone.getNetworkType() != NetworkType.Advanced) {
throw new InvalidParameterValueException("Vlan owner can be defined only in the zone of type " + NetworkType.Advanced);
}
if (ipv4) {
// Make sure the gateway is valid
if (!NetUtils.isValidIp(vlanGateway)) {
throw new InvalidParameterValueException("Please specify a valid gateway");
}
// Make sure the netmask is valid
if (!NetUtils.isValidNetmask(vlanNetmask)) {
throw new InvalidParameterValueException("Please specify a valid netmask");
}
}
if (ipv6) {
if (!NetUtils.isValidIpv6(vlanIp6Gateway)) {
throw new InvalidParameterValueException("Please specify a valid IPv6 gateway");
}
if (!NetUtils.isValidIp6Cidr(vlanIp6Cidr)) {
throw new InvalidParameterValueException("Please specify a valid IPv6 CIDR");
}
}
if (ipv4) {
final String newCidr = NetUtils.getCidrFromGatewayAndNetmask(vlanGateway, vlanNetmask);
//Make sure start and end ips are with in the range of cidr calculated for this gateway and netmask {
if (!NetUtils.isIpWithtInCidrRange(vlanGateway, newCidr) || !NetUtils.isIpWithtInCidrRange(startIP, newCidr) || !NetUtils.isIpWithtInCidrRange(endIP, newCidr)) {
throw new InvalidParameterValueException("Please specify a valid IP range or valid netmask or valid gateway");
}
// Check if the new VLAN's subnet conflicts with the guest network
// in
// the specified zone (guestCidr is null for basic zone)
// when adding shared network with same cidr of zone guest cidr,
// if the specified vlan is not present in zone, physical network, allow to create the network as the isolation is based on VLAN.
final String guestNetworkCidr = zone.getGuestNetworkCidr();
if (guestNetworkCidr != null && NetUtils.isNetworksOverlap(newCidr, guestNetworkCidr) && _zoneDao.findVnet(zoneId, physicalNetworkId, vlanId).isEmpty() != true) {
throw new InvalidParameterValueException("The new IP range you have specified has overlapped with the guest network in zone: " + zone.getName() + "along with existing Vlan also. Please specify a different gateway/netmask");
}
// Check if there are any errors with the IP range
checkPublicIpRangeErrors(zoneId, vlanId, vlanGateway, vlanNetmask, startIP, endIP);
checkConflictsWithPortableIpRange(zoneId, vlanId, vlanGateway, vlanNetmask, startIP, endIP);
// Throw an exception if this subnet overlaps with subnet on other VLAN,
// if this is ip range extension, gateway, network mask should be same and ip range should not overlap
final List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
for (final VlanVO vlan : vlans) {
final String otherVlanGateway = vlan.getVlanGateway();
final String otherVlanNetmask = vlan.getVlanNetmask();
// Continue if it's not IPv4
if (otherVlanGateway == null || otherVlanNetmask == null) {
continue;
}
if (vlan.getNetworkId() == null) {
continue;
}
final String otherCidr = NetUtils.getCidrFromGatewayAndNetmask(otherVlanGateway, otherVlanNetmask);
if (!NetUtils.isNetworksOverlap(newCidr, otherCidr)) {
continue;
}
// from here, subnet overlaps
if (!vlanId.equals(vlan.getVlanTag())) {
boolean overlapped = false;
if (network.getTrafficType() == TrafficType.Public) {
overlapped = true;
} else {
final Long nwId = vlan.getNetworkId();
if (nwId != null) {
final Network nw = _networkModel.getNetwork(nwId);
if (nw != null && nw.getTrafficType() == TrafficType.Public) {
overlapped = true;
}
}
}
if (overlapped) {
throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " in zone " + zone.getName() + " has overlapped with the subnet. Please specify a different gateway/netmask.");
}
} else {
final String[] otherVlanIpRange = vlan.getIpRange().split("\\-");
final String otherVlanStartIP = otherVlanIpRange[0];
String otherVlanEndIP = null;
if (otherVlanIpRange.length > 1) {
otherVlanEndIP = otherVlanIpRange[1];
}
// extend IP range
if (!vlanGateway.equals(otherVlanGateway) || !vlanNetmask.equals(vlan.getVlanNetmask())) {
throw new InvalidParameterValueException("The IP range has already been added with gateway " + otherVlanGateway + " ,and netmask " + otherVlanNetmask + ", Please specify the gateway/netmask if you want to extend ip range");
}
if (!NetUtils.is31PrefixCidr(newCidr)) {
if (NetUtils.ipRangesOverlap(startIP, endIP, otherVlanStartIP, otherVlanEndIP)) {
throw new InvalidParameterValueException("The IP range already has IPs that overlap with the new range." + " Please specify a different start IP/end IP.");
}
}
}
}
}
String ipv6Range = null;
if (ipv6) {
ipv6Range = startIPv6;
if (endIPv6 != null) {
ipv6Range += "-" + endIPv6;
}
final List<VlanVO> vlans = _vlanDao.listByZone(zone.getId());
for (final VlanVO vlan : vlans) {
if (vlan.getIp6Gateway() == null) {
continue;
}
if (NetUtils.isSameIsolationId(vlanId, vlan.getVlanTag())) {
if (NetUtils.isIp6RangeOverlap(ipv6Range, vlan.getIp6Range())) {
throw new InvalidParameterValueException("The IPv6 range with tag: " + vlan.getVlanTag() + " already has IPs that overlap with the new range. Please specify a different start IP/end IP.");
}
if (!vlanIp6Gateway.equals(vlan.getIp6Gateway())) {
throw new InvalidParameterValueException("The IP range with tag: " + vlan.getVlanTag() + " has already been added with gateway " + vlan.getIp6Gateway() + ". Please specify a different tag.");
}
}
}
}
// Check if the vlan is being used
if (_zoneDao.findVnet(zoneId, physicalNetworkId, vlanId).size() > 0) {
throw new InvalidParameterValueException("The VLAN tag " + vlanId + " is already being used for dynamic vlan allocation for the guest network in zone " + zone.getName());
}
String ipRange = null;
if (ipv4) {
ipRange = startIP;
if (endIP != null) {
ipRange += "-" + endIP;
}
}
// Everything was fine, so persist the VLAN
final VlanVO vlan = commitVlanAndIpRange(zoneId, networkId, physicalNetworkId, podId, startIP, endIP, vlanGateway, vlanNetmask, vlanId, domain, vlanOwner, vlanIp6Gateway, vlanIp6Cidr, ipv4, zone, vlanType, ipv6Range, ipRange);
return vlan;
}
use of com.cloud.network.Network in project cloudstack by apache.
the class ConsoleProxyManagerImpl method createProxyInstance.
protected Map<String, Object> createProxyInstance(long dataCenterId, VMTemplateVO template) throws ConcurrentOperationException {
long id = _consoleProxyDao.getNextInSequence(Long.class, "id");
String name = VirtualMachineName.getConsoleProxyName(id, _instance);
DataCenterVO dc = _dcDao.findById(dataCenterId);
Account systemAcct = _accountMgr.getSystemAccount();
DataCenterDeployment plan = new DataCenterDeployment(dataCenterId);
NetworkVO defaultNetwork = getDefaultNetworkForCreation(dc);
List<? extends NetworkOffering> offerings = _networkModel.getSystemAccountNetworkOfferings(NetworkOffering.SystemControlNetwork, NetworkOffering.SystemManagementNetwork);
LinkedHashMap<Network, List<? extends NicProfile>> networks = new LinkedHashMap<Network, List<? extends NicProfile>>(offerings.size() + 1);
NicProfile defaultNic = new NicProfile();
defaultNic.setDefaultNic(true);
defaultNic.setDeviceId(2);
networks.put(_networkMgr.setupNetwork(systemAcct, _networkOfferingDao.findById(defaultNetwork.getNetworkOfferingId()), plan, null, null, false).get(0), new ArrayList<NicProfile>(Arrays.asList(defaultNic)));
for (NetworkOffering offering : offerings) {
networks.put(_networkMgr.setupNetwork(systemAcct, offering, plan, null, null, false).get(0), new ArrayList<NicProfile>());
}
ServiceOfferingVO serviceOffering = _serviceOffering;
if (serviceOffering == null) {
serviceOffering = _offeringDao.findDefaultSystemOffering(ServiceOffering.consoleProxyDefaultOffUniqueName, ConfigurationManagerImpl.SystemVMUseLocalStorage.valueIn(dataCenterId));
}
ConsoleProxyVO proxy = new ConsoleProxyVO(id, serviceOffering.getId(), name, template.getId(), template.getHypervisorType(), template.getGuestOSId(), dataCenterId, systemAcct.getDomainId(), systemAcct.getId(), _accountMgr.getSystemUser().getId(), 0, serviceOffering.getOfferHA());
proxy.setDynamicallyScalable(template.isDynamicallyScalable());
proxy = _consoleProxyDao.persist(proxy);
try {
_itMgr.allocate(name, template, serviceOffering, networks, plan, null);
} catch (InsufficientCapacityException e) {
s_logger.warn("InsufficientCapacity", e);
throw new CloudRuntimeException("Insufficient capacity exception", e);
}
Map<String, Object> context = new HashMap<String, Object>();
context.put("dc", dc);
HostPodVO pod = _podDao.findById(proxy.getPodIdToDeployIn());
context.put("pod", pod);
context.put("proxyVmId", proxy.getId());
return context;
}
use of com.cloud.network.Network in project cloudstack by apache.
the class NetworkACLServiceImpl method listNetworkACLItems.
@Override
public Pair<List<? extends NetworkACLItem>, Integer> listNetworkACLItems(final ListNetworkACLsCmd cmd) {
final Long networkId = cmd.getNetworkId();
final Long id = cmd.getId();
Long aclId = cmd.getAclId();
final String trafficType = cmd.getTrafficType();
final String protocol = cmd.getProtocol();
final String action = cmd.getAction();
final Map<String, String> tags = cmd.getTags();
final Account caller = CallContext.current().getCallingAccount();
final Filter filter = new Filter(NetworkACLItemVO.class, "id", false, cmd.getStartIndex(), cmd.getPageSizeVal());
final SearchBuilder<NetworkACLItemVO> sb = _networkACLItemDao.createSearchBuilder();
sb.and("id", sb.entity().getId(), Op.EQ);
sb.and("aclId", sb.entity().getAclId(), Op.EQ);
sb.and("trafficType", sb.entity().getTrafficType(), Op.EQ);
sb.and("protocol", sb.entity().getProtocol(), Op.EQ);
sb.and("action", sb.entity().getAction(), Op.EQ);
if (tags != null && !tags.isEmpty()) {
final SearchBuilder<ResourceTagVO> tagSearch = _resourceTagDao.createSearchBuilder();
for (int count = 0; count < tags.size(); count++) {
tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), Op.EQ);
tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), Op.EQ);
tagSearch.cp();
}
tagSearch.and("resourceType", tagSearch.entity().getResourceType(), Op.EQ);
sb.groupBy(sb.entity().getId());
sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER);
}
if (aclId == null) {
//Join with network_acl table when aclId is not specified to list acl_items within permitted VPCs
final SearchBuilder<NetworkACLVO> vpcSearch = _networkACLDao.createSearchBuilder();
vpcSearch.and("vpcId", vpcSearch.entity().getVpcId(), Op.IN);
sb.join("vpcSearch", vpcSearch, sb.entity().getAclId(), vpcSearch.entity().getId(), JoinBuilder.JoinType.INNER);
}
final SearchCriteria<NetworkACLItemVO> sc = sb.create();
if (id != null) {
sc.setParameters("id", id);
}
if (networkId != null) {
final Network network = _networkDao.findById(networkId);
aclId = network.getNetworkACLId();
if (aclId == null) {
//Return empty list
return new Pair(new ArrayList<NetworkACLItem>(), 0);
}
}
if (trafficType != null) {
sc.setParameters("trafficType", trafficType);
}
if (aclId != null) {
// Get VPC and check access
final NetworkACL acl = _networkACLDao.findById(aclId);
if (acl.getVpcId() != 0) {
final Vpc vpc = _vpcDao.findById(acl.getVpcId());
if (vpc == null) {
throw new InvalidParameterValueException("Unable to find VPC associated with acl");
}
_accountMgr.checkAccess(caller, null, true, vpc);
}
sc.setParameters("aclId", aclId);
} else {
//ToDo: Add accountId to network_acl_item table for permission check
// aclId is not specified
// List permitted VPCs and filter aclItems
final List<Long> permittedAccounts = new ArrayList<Long>();
Long domainId = cmd.getDomainId();
boolean isRecursive = cmd.isRecursive();
final String accountName = cmd.getAccountName();
final Long projectId = cmd.getProjectId();
final boolean listAll = cmd.listAll();
final Ternary<Long, Boolean, ListProjectResourcesCriteria> domainIdRecursiveListProject = new Ternary<Long, Boolean, ListProjectResourcesCriteria>(domainId, isRecursive, null);
_accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, false);
domainId = domainIdRecursiveListProject.first();
isRecursive = domainIdRecursiveListProject.second();
final ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third();
final SearchBuilder<VpcVO> sbVpc = _vpcDao.createSearchBuilder();
_accountMgr.buildACLSearchBuilder(sbVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
final SearchCriteria<VpcVO> scVpc = sbVpc.create();
_accountMgr.buildACLSearchCriteria(scVpc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria);
final List<VpcVO> vpcs = _vpcDao.search(scVpc, null);
final List<Long> vpcIds = new ArrayList<Long>();
for (final VpcVO vpc : vpcs) {
vpcIds.add(vpc.getId());
}
//Add vpc_id 0 to list acl_items in default ACL
vpcIds.add(0L);
sc.setJoinParameters("vpcSearch", "vpcId", vpcIds.toArray());
}
if (protocol != null) {
sc.setParameters("protocol", protocol);
}
if (action != null) {
sc.setParameters("action", action);
}
if (tags != null && !tags.isEmpty()) {
int count = 0;
sc.setJoinParameters("tagSearch", "resourceType", ResourceObjectType.NetworkACL.toString());
for (final String key : tags.keySet()) {
sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key);
sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key));
count++;
}
}
final Pair<List<NetworkACLItemVO>, Integer> result = _networkACLItemDao.searchAndCount(sc, filter);
final List<NetworkACLItemVO> aclItemVOs = result.first();
for (final NetworkACLItemVO item : aclItemVOs) {
_networkACLItemDao.loadCidrs(item);
}
return new Pair<List<? extends NetworkACLItem>, Integer>(aclItemVOs, result.second());
}
Aggregations