final Long endIp = IpAddressUtil
.getAddressAsLong(InetAddress.getByName("0.2.0.0"));
NetworkEntity network = new NetworkEntity(portGroup, portGroup, allocType,
netmask, gateway, dns1, dns2);
IpBlockEntity originalBlock = new IpBlockEntity(network,
IpBlockEntity.FREE_BLOCK_OWNER_ID, BlockType.FREE, beginIp, endIp);
networkDao.insert(network);
List<IpBlockEntity> ipBlocks = new ArrayList<IpBlockEntity>();
ipBlocks.add(originalBlock);
networkDao.addIpBlocks(network, ipBlocks);
logger.info(network);
List<List<IpBlockEntity>> allocLists = new ArrayList<List<IpBlockEntity>>();
List<Integer> allocSizes = new ArrayList<Integer>();
List<Long> allocOwners = new ArrayList<Long>();
long totalAssigned = 0L;
Long maxOwnerId = 100L; // min is 0L
int minAllocSize = 1;
int maxAllocSize = 1000;
final Long totalIps = endIp - beginIp + 1;
long nextLogTimeMs = System.currentTimeMillis() + 1000;
logger.info("strart random alloc/free stress test");
/**
* try to alloc until out of IPs
*/
while (true) {
long now = System.currentTimeMillis();
if (nextLogTimeMs < now) {
nextLogTimeMs = now + 1000;
logger.info("allocated: " + totalAssigned + "/" + totalIps + " ("
+ totalAssigned / (double) totalIps + ")");
}
if (Math.random() < 0.8) { // alloc
final Long ownerId = (long) (Math.random() * maxOwnerId) % maxOwnerId;
int rndCount = (int) (Math.random() * maxAllocSize) % maxAllocSize;
final int count = Math.max(minAllocSize, rndCount);
try {
List<IpBlockEntity> allocated = networkDao.alloc(network, ownerId, count);
allocLists.add(allocated);
allocSizes.add(count);
allocOwners.add(ownerId);
totalAssigned += totalAssigned + count;
logger.debug("alloc: "
+ collectionToString(allocLists.get(allocLists.size() - 1)));
} catch (NetworkException ex) {
assertTrue("out of ip resource", network.getFree() < count);
break;
}
} else { // free
if (!allocLists.isEmpty()) {
int idx = (int) (Math.random() * allocLists.size()) % allocLists.size();
final List<IpBlockEntity> toBeFreed = allocLists.remove(idx);
final Long ownerId = allocOwners.remove(idx);
logger.debug("to free: " + collectionToString(toBeFreed));
networkDao.free(network, ownerId, toBeFreed);
totalAssigned -= allocSizes.remove(idx);
}
}
}
// free all by cluster
for (long id = 0; id < maxOwnerId; ++id) {
final Long ownerId = id;
networkDao.free(network, ownerId);
}
originalBlock = new IpBlockEntity(network, IpBlockEntity.FREE_BLOCK_OWNER_ID,
BlockType.FREE, beginIp, endIp);
assertEquals(1, network.getIpBlocks().size());
assertEquals(originalBlock, network.getIpBlocks().get(0));
NetworkEntity net = networkDao.findById(network.getId());