diff options
Diffstat (limited to 'resource-assignment/provider/src/main/java')
81 files changed, 7236 insertions, 0 deletions
diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelper.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelper.java new file mode 100644 index 000000000..040d19273 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelper.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.comp; + +import java.util.Collection; + +public interface LockHelper { + + void lock(String resourceName, String lockRequester, int lockTimeout /* Seconds */); + + void lock(String resourceName, String lockRequester, int lockTimeout /* Seconds */, int lockWait /* Seconds */, int retryCount); + + void unlock(String resourceName, boolean force); + + void lock(Collection<String> resourceNameList, String lockRequester, int lockTimeout /* Seconds */); + + void lock(Collection<String> resourceNameList, String lockRequester, int lockTimeout /* Seconds */, int lockWait /* Seconds */, int retryCount); + + void unlock(Collection<String> resourceNameList, boolean force); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelperImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelperImpl.java new file mode 100644 index 000000000..735d240c0 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/LockHelperImpl.java @@ -0,0 +1,206 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.comp; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.lock.dao.ResourceLockDao; +import org.onap.ccsdk.sli.adaptors.lock.data.ResourceLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LockHelperImpl implements LockHelper { + + private static final Logger log = LoggerFactory.getLogger(LockHelperImpl.class); + + private ResourceLockDao resourceLockDao; + private int retryCount = 10; + private int lockWait = 5; // Seconds + + @Override + public void lock(String resourceName, String lockRequester, int lockTimeout /* Seconds */) { + lock(resourceName, lockRequester, lockTimeout, lockWait, retryCount); + } + + @Override + public void lock(String resourceName, String lockRequester, int lockTimeout /* Seconds */, + int lockWait /* Seconds */, int retryCount) { + lock(Collections.singleton(resourceName), lockRequester, lockTimeout, lockWait, retryCount); + } + + @Override + public void unlock(String resourceName, boolean force) { + unlock(Collections.singleton(resourceName), force); + } + + @Override + public void lock(Collection<String> resourceNameList, String lockRequester, int lockTimeout /* Seconds */) { + lock(resourceNameList, lockRequester, lockTimeout, lockWait, retryCount); + } + + @Override + public void lock(Collection<String> resourceNameList, String lockRequester, int lockTimeout /* Seconds */, + int lockWait /* Seconds */, int retryCount) { + for (int i = 0; true; i++) { + try { + tryLock(resourceNameList, lockRequester, lockTimeout); + log.info("Resources locked: " + resourceNameList); + return; + } catch (ResourceLockedException e) { + if (i >= retryCount) { + throw e; + } + try { + Thread.sleep(lockWait * 1000); + } catch (InterruptedException ex) { + log.error("Interrupted Exception", ex); + } + } + } + } + + @Override + public void unlock(Collection<String> lockNames, boolean force) { + if (lockNames == null || lockNames.isEmpty()) { + return; + } + + try { + for (String name : lockNames) { + ResourceLock l = resourceLockDao.getByResourceName(name); + if (l != null) { + if (force || l.lockCount == 1) { + resourceLockDao.delete(l.id); + } else { + resourceLockDao.decrementLockCount(l.id); + } + } + } + + resourceLockDao.commit(); + + log.info("Resources unlocked: " + lockNames); + } finally { + resourceLockDao.rollback(); + } + } + + public void tryLock(Collection<String> resourceNameList, String lockRequester, int lockTimeout /* Seconds */) { + if (resourceNameList == null || resourceNameList.isEmpty()) { + return; + } + + lockRequester = generateLockRequester(lockRequester, 100); + + // First check if all requested records are available to lock + + Date now = new Date(); + + try { + List<ResourceLock> dbLockList = new ArrayList<>(); + List<String> insertLockNameList = new ArrayList<>(); + for (String name : resourceNameList) { + ResourceLock l = resourceLockDao.getByResourceName(name); + + boolean canLock = l == null || now.getTime() > l.expirationTime.getTime() || + lockRequester != null && lockRequester.equals(l.lockHolder) || l.lockCount <= 0; + if (!canLock) { + throw new ResourceLockedException(l.resourceName, l.lockHolder, lockRequester); + } + + if (l != null) { + if (now.getTime() > l.expirationTime.getTime() || l.lockCount <= 0) { + l.lockCount = 0; + } + dbLockList.add(l); + } else { + insertLockNameList.add(name); + } + } + + // Update the lock info in DB + for (ResourceLock l : dbLockList) { + resourceLockDao.update(l.id, lockRequester, now, new Date(now.getTime() + lockTimeout * 1000), l.lockCount + 1); + } + + // Insert records for those that are not yet there + for (String lockName : insertLockNameList) { + ResourceLock l = new ResourceLock(); + l.resourceName = lockName; + l.lockHolder = lockRequester; + l.lockTime = now; + l.expirationTime = new Date(now.getTime() + lockTimeout * 1000); + l.lockCount = 1; + + try { + resourceLockDao.add(l); + } catch (Exception e) { + log.info("Failed to insert lock record: " + lockName); + throw new ResourceLockedException(l.resourceName, "unknown", lockRequester); + } + } + + resourceLockDao.commit(); + + }finally + + { + resourceLockDao.rollback(); + } + } + + private static String generateLockRequester(String name, int maxLength) { + if (name == null) { + name = ""; + } + int l1 = name.length(); + String tname = Thread.currentThread().getName(); + int l2 = tname.length(); + if (l1 + l2 + 1 > maxLength) { + int maxl1 = maxLength / 2; + if (l1 > maxl1) { + name = name.substring(0, maxl1); + l1 = maxl1; + } + int maxl2 = maxLength - l1 - 1; + if (l2 > maxl2) { + tname = tname.substring(0, 6) + "..." + tname.substring(l2 - maxl2 + 9); + } + } + return tname + '-' + name; + } + + public void setResourceLockDao(ResourceLockDao resourceLockDao) { + this.resourceLockDao = resourceLockDao; + } + + public void setRetryCount(int retryCount) { + this.retryCount = retryCount; + } + + public void setLockWait(int lockWait /* Seconds */) { + this.lockWait = lockWait; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/ResourceLockedException.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/ResourceLockedException.java new file mode 100644 index 000000000..f503332cc --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/ResourceLockedException.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.comp; + +public class ResourceLockedException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private final String lockName; + private final String lockHolder; + private final String lockRequester; + + public ResourceLockedException(String lockName, String lockHolder, String lockRequester) { + this.lockName = lockName; + this.lockHolder = lockHolder; + this.lockRequester = lockRequester; + } + + @Override + public String getMessage() { + return "Failed to lock [" + lockName + "] for [" + lockRequester + "]. Currently locked by [" + lockHolder + + "]."; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/SynchronizedFunction.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/SynchronizedFunction.java new file mode 100644 index 000000000..9cce17a46 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/comp/SynchronizedFunction.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.comp; + +import java.security.SecureRandom; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +public abstract class SynchronizedFunction { + + private Set<String> synchset; + private String lockRequester; + private int lockTimeout; // Seconds + private LockHelper lockHelper; + + protected SynchronizedFunction(LockHelper lockHelper, Collection<String> synchset, int lockTimeout) { + this.lockHelper = lockHelper; + this.synchset = new HashSet<String>(synchset); + this.lockRequester = generateLockRequester(); + this.lockTimeout = lockTimeout; + } + + protected abstract void _exec(); + + public void exec() { + lockHelper.lock(synchset, lockRequester, lockTimeout); + try { + _exec(); + } finally { + lockHelper.unlock(synchset, true); + } + } + + private static String generateLockRequester() { + SecureRandom rand = new SecureRandom(); + return "SynchronizedFunction-" + (int) (rand.nextDouble() * 1000000); + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDao.java new file mode 100644 index 000000000..dc86f70af --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDao.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.dao; + +import java.util.Date; +import org.onap.ccsdk.sli.adaptors.lock.data.ResourceLock; + +public interface ResourceLockDao { + + void add(ResourceLock l); + + void update(long id, String lockHolder, Date lockTime, Date expirationTime, int lockCount); + + ResourceLock getByResourceName(String resourceName); + + void delete(long id); + + void decrementLockCount(long id); + + void commit(); + + void rollback(); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDaoImpl.java new file mode 100644 index 000000000..b8b3a66d6 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/dao/ResourceLockDaoImpl.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.dao; + +import java.util.Date; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.lock.data.ResourceLock; +import org.onap.ccsdk.sli.adaptors.util.db.CachedDataSourceWrap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +public class ResourceLockDaoImpl implements ResourceLockDao { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ResourceLockDaoImpl.class); + + private JdbcTemplate jdbcTemplate; + + @Override + public void add(ResourceLock l) { + jdbcTemplate.update( + "INSERT INTO RESOURCE_LOCK (resource_name, lock_holder, lock_count, lock_time, expiration_time)\n" + + "VALUES (?, ?, ?, ?, ?)", + new Object[] { l.resourceName, l.lockHolder, l.lockCount, l.lockTime, l.expirationTime }); + } + + @Override + public void update(long id, String lockHolder, Date lockTime, Date expirationTime, int lockCount) { + jdbcTemplate.update( + "UPDATE RESOURCE_LOCK SET lock_holder = ?, lock_time = ?, expiration_time = ?, lock_count = ? WHERE resource_lock_id = ?", + new Object[] { lockHolder, lockTime, expirationTime, lockCount, id }); + } + + @Override + public ResourceLock getByResourceName(String resourceName) { + List<ResourceLock> ll = jdbcTemplate.query("SELECT * FROM RESOURCE_LOCK WHERE resource_name = ?", + new Object[] { resourceName }, (RowMapper<ResourceLock>) (rs, rowNum) -> { + ResourceLock rl = new ResourceLock(); + rl.id = rs.getLong("resource_lock_id"); + rl.resourceName = rs.getString("resource_name"); + rl.lockHolder = rs.getString("lock_holder"); + rl.lockCount = rs.getInt("lock_count"); + rl.lockTime = rs.getTimestamp("lock_time"); + rl.expirationTime = rs.getTimestamp("expiration_time"); + return rl; + }); + return ll != null && !ll.isEmpty() ? ll.get(0) : null; + } + + @Override + public void delete(long id) { + jdbcTemplate.update("DELETE FROM RESOURCE_LOCK WHERE resource_lock_id = ?", new Object[] { id }); + } + + @Override + public void decrementLockCount(long id) { + jdbcTemplate.update("UPDATE RESOURCE_LOCK SET lock_count = lock_count - 1 WHERE resource_lock_id = ?", + new Object[] { id }); + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + @Override + public void commit() { + if (jdbcTemplate.getDataSource() instanceof CachedDataSourceWrap) { + CachedDataSourceWrap ds = (CachedDataSourceWrap) jdbcTemplate.getDataSource(); + ds.commit(); + ds.releaseConnection(); + } + } + + @Override + public void rollback() { + if (jdbcTemplate.getDataSource() instanceof CachedDataSourceWrap) { + CachedDataSourceWrap ds = (CachedDataSourceWrap) jdbcTemplate.getDataSource(); + ds.rollback(); + ds.releaseConnection(); + } + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/data/ResourceLock.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/data/ResourceLock.java new file mode 100644 index 000000000..cb434e142 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/lock/data/ResourceLock.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.lock.data; + +import java.util.Date; + +public class ResourceLock { + + public long id; + public String resourceName; + public String lockHolder; + public int lockCount; + public Date lockTime; + public Date expirationTime; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceAllocator.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceAllocator.java new file mode 100644 index 000000000..10f3e02b7 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceAllocator.java @@ -0,0 +1,583 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright (C) 2019 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.onap.ccsdk.sli.adaptors.ra.comp.AllocationData; +import org.onap.ccsdk.sli.adaptors.ra.comp.EndPointAllocator; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceData; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceEntity; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceRequest; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceResponse; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceTarget; +import org.onap.ccsdk.sli.adaptors.rm.comp.ResourceManager; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationStatus; +import org.onap.ccsdk.sli.adaptors.rm.data.ReleaseRequest; +import org.onap.ccsdk.sli.adaptors.util.speed.SpeedUtil; +import org.onap.ccsdk.sli.adaptors.util.str.StrUtil; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResourceAllocator implements SvcLogicResource { + + private static final Logger log = LoggerFactory.getLogger(ResourceAllocator.class); + + private static final String[] INPUT_PREFIX = {"ra-input.", "tmp.resource-allocator."}; + + private ResourceManager resourceManager; + private EndPointAllocator endPointAllocator; + private SpeedUtil speedUtil; + + public ResourceAllocator() { + log.info("ResourceAllocator created."); + } + + @Override + public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) + throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus update(String resource, String key, Map<String, String> parms, String prefix, + SvcLogicContext ctx) throws SvcLogicException { + + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) + throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus delete(String arg0, String arg1, SvcLogicContext arg2) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus save(String arg0, boolean arg1, boolean arg2, String arg3, Map<String, String> arg4, String arg5, + SvcLogicContext arg6) throws SvcLogicException { + return QueryStatus.SUCCESS; + } + + @Override + public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) + throws SvcLogicException { + return allocateResources(ctx, true, prefix); + } + + @Override + public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, + String orderBy, SvcLogicContext ctx) throws SvcLogicException { + + String resourceEntityId = getParam(ctx, + new String[] {"service-instance-id", "resource-entity-id", "reservation-entity-id"}, false, null); + String resourceEntityType = + getParam(ctx, new String[] {"reservation-entity-type", "resource-entity-type"}, false, null); + String resourceEntityVersion = + getParam(ctx, new String[] {"reservation-entity-version", "resource-entity-version"}, false, "1"); + + String resourceTargetId = + getParam(ctx, new String[] {"reservation-target-id", "resource-target-id"}, false, null); + String resourceTargetType = + getParam(ctx, new String[] {"reservation-target-type", "resource-target-type"}, false, null); + String resourceName = getParam(ctx, "resource-name", false, null); + String resourceEntityTypeFilter = getParam(ctx, "resource-entity-type-filter", false, null); + String resourceEntityIdFilter = getParam(ctx, "resource-entity-id-filter", false, null); + String resourceShareGroupFilter = getParam(ctx, "resource-share-group-filter", false, null); + String resourceTargetTypeFilter = getParam(ctx, "resource-target-type-filter", false, null); + String resourceTargetIdFilter = getParam(ctx, "resource-target-id-filter", false, null); + + if (resourceEntityId != null && resourceEntityType != null) { + List<ResourceData> rdlist = endPointAllocator.getResourcesForEntity(resourceEntityType, resourceEntityId, + resourceEntityVersion); + setResourceDataInContext(ctx, prefix, rdlist); + } else if (resourceTargetId != null && resourceTargetType != null && resourceName != null) { + ResourceData rd = endPointAllocator.getResource(resourceTargetType, resourceTargetId, resourceName, + resourceEntityTypeFilter, resourceEntityIdFilter, resourceShareGroupFilter); + if (rd != null) { + setResourceDataInContext(ctx, prefix, Collections.singletonList(rd)); + } + } else if ((resourceTargetTypeFilter != null || resourceTargetIdFilter != null) && resourceName != null) { + List<ResourceData> rdlist = endPointAllocator.getResourcesForTarget(resourceTargetTypeFilter, + resourceTargetIdFilter, resourceName); + setResourceDataInContext(ctx, prefix, rdlist); + } + + return QueryStatus.SUCCESS; + } + + public AllocationStatus query(ResourceEntity sd, ResourceTarget rt, ResourceRequest rr, + List<ResourceResponse> rsList) throws Exception { + + if (sd != null && sd.resourceEntityId != null && sd.resourceEntityType != null) { + List<ResourceData> rdlist = endPointAllocator.getResourcesForEntity(sd.resourceEntityType, + sd.resourceEntityId, sd.resourceEntityVersion); + setResourceDataInResponse(rdlist, rsList); + } else if (rt != null && rt.resourceTargetId != null && rt.resourceTargetType != null && rr != null + && rr.resourceName != null) { + ResourceData rd = endPointAllocator.getResource(rt.resourceTargetType, rt.resourceTargetId, rr.resourceName, + rr.resourceEntityTypeFilter, rr.resourceEntityIdFilter, rr.resourceShareGroupFilter); + setResourceDataInResponse(Collections.singletonList(rd), rsList); + } else if (rr != null && (rr.resourceTargetTypeFilter != null || rr.resourceTargetIdFilter != null) + && rr.resourceName != null) { + List<ResourceData> rdlist = endPointAllocator.getResourcesForTarget(rr.resourceTargetTypeFilter, + rr.resourceTargetIdFilter, rr.resourceName); + setResourceDataInResponse(rdlist, rsList); + } + + return AllocationStatus.Success; + } + + private void setResourceDataInContext(SvcLogicContext ctx, String prefix, List<ResourceData> rdlist) { + if (rdlist == null || rdlist.isEmpty()) { + return; + } + + prefix = prefix == null ? "" : prefix + '.'; + + setAttr(ctx, prefix + "resource-list_length", String.valueOf(rdlist.size())); + + for (int i = 0; i < rdlist.size(); i++) { + ResourceData rd = rdlist.get(i); + + String pp = prefix + "resource-list[" + i + "]."; + + setAttr(ctx, pp + "resource-name", rd.resourceName); + setAttr(ctx, pp + "endpoint-position", rd.endPointPosition); + setAttr(ctx, pp + "resource-target-type", rd.resourceTargetType); + setAttr(ctx, pp + "resource-target-id", rd.resourceTargetId); + setAttr(ctx, pp + "resource-target-value", rd.resourceTargetValue); + setAttr(ctx, pp + "status", rd.status); + + Map<String, String> dataProp = dataToProperties(rd.data); + for (String kk : dataProp.keySet()) { + String value = String.valueOf(dataProp.get(kk)); + setAttr(ctx, pp + kk, value); + } + + if (rd.allocationDataList != null && !rd.allocationDataList.isEmpty()) { + + setAttr(ctx, pp + "allocation-data-list_length", String.valueOf(rd.allocationDataList.size())); + + for (int j = 0; j < rd.allocationDataList.size(); j++) { + AllocationData ad = rd.allocationDataList.get(j); + + String ppp = pp + "allocation-data-list[" + j + "]."; + + setAttr(ctx, ppp + "resource-entity-type", ad.resourceEntityType); + setAttr(ctx, ppp + "resource-entity-id", ad.resourceEntityId); + setAttr(ctx, ppp + "resource-entity-version", ad.resourceEntityVersion); + + if (ad.data != null && !ad.data.isEmpty()) { + for (String kk : ad.data.keySet()) { + String value = String.valueOf(ad.data.get(kk)); + setAttr(ctx, ppp + kk, value); + } + } + } + } + } + } + + @Override + public QueryStatus reserve(String resource, String select, String key, String prefix, SvcLogicContext ctx) + throws SvcLogicException { + return allocateResources(ctx, false, prefix); + } + + public AllocationStatus reserve(ResourceEntity sd, ResourceTarget rt, ResourceRequest rr, + List<ResourceResponse> rsList) throws Exception { + return allocateResources(sd, rt, rr, rsList); + } + + @Override + public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException { + String resourceEntityId = getParam(ctx, + new String[] {"service-instance-id", "resource-entity-id", "reservation-entity-id"}, true, null); + String resourceEntityType = + getParam(ctx, new String[] {"reservation-entity-type", "resource-entity-type"}, true, null); + String resourceEntityVersion = + getParam(ctx, new String[] {"reservation-entity-version", "resource-entity-version"}, false, null); + String resourceTargetId = + getParam(ctx, new String[] {"reservation-target-id", "resource-target-id"}, false, null); + String resourceTargetType = + getParam(ctx, new String[] {"reservation-target-type", "resource-target-type"}, false, null); + String resourceName = getParam(ctx, new String[] {"resource-name"}, false, null); + String limitReleaseAmountStr = getParam(ctx, new String[] {"limit-release-amount"}, false, "-1"); + int limitReleaseAmount = Integer.parseInt(limitReleaseAmountStr); + String rangeReleaseNumbers = getParam(ctx, new String[] {"range-release-numbers"}, false, null); + + + String endPointPosition = getParam(ctx, "endpoint-position", false, null); + + ResourceEntity sd = new ResourceEntity(); + sd.resourceEntityId = resourceEntityId; + sd.resourceEntityType = resourceEntityType; + sd.resourceEntityVersion = resourceEntityVersion; + + ResourceRequest rr = new ResourceRequest(); + rr.endPointPosition = endPointPosition; + rr.resourceName = resourceName; + rr.rangeReleaseNumbers = rangeReleaseNumbers; + rr.limitReleaseAmount = limitReleaseAmount; + + ResourceTarget rt = new ResourceTarget(); + rt.resourceTargetType = resourceTargetType; + rt.resourceTargetId = resourceTargetId; + + try { + this.release(sd, rr, rt); + } catch (Exception e) { + throw new SvcLogicException(e.getMessage()); + } + return QueryStatus.SUCCESS; + } + + public AllocationStatus release(ResourceEntity sd) throws Exception { + return release(sd, null, null); + } + + public AllocationStatus release(ResourceEntity sd, ResourceRequest rr) throws Exception { + return release(sd, rr, null); + } + + public AllocationStatus release(ResourceEntity sd, ResourceRequest rr, ResourceTarget rt) { + + ReleaseRequest releaseRequest = new ReleaseRequest(); + + if (sd != null && sd.resourceEntityVersion != null) { + releaseRequest.resourceSetId = null; + + if (rr != null && rr.endPointPosition != null && !rr.endPointPosition.isEmpty()) { + releaseRequest.resourceSetId = sd.resourceEntityType + "::" + sd.resourceEntityId + "::" + + rr.endPointPosition + "::" + sd.resourceEntityVersion; + } else { + releaseRequest.resourceSetId = + sd.resourceEntityType + "::" + sd.resourceEntityId + "::" + sd.resourceEntityVersion; + } + + } else if (sd != null && (sd.resourceEntityVersion == null || sd.resourceEntityVersion.isEmpty())) { + releaseRequest.resourceUnionId = null; + + if (rr != null && rr.endPointPosition != null && !rr.endPointPosition.isEmpty()) { + releaseRequest.resourceUnionId = + sd.resourceEntityType + "::" + sd.resourceEntityId + "::" + rr.endPointPosition; + } else { + releaseRequest.resourceUnionId = sd.resourceEntityType + "::" + sd.resourceEntityId; + } + } + + if (rt != null && rt.resourceTargetId != null && rt.resourceTargetType != null) { + releaseRequest.assetId = rt.resourceTargetType + "::" + rt.resourceTargetId; + } + + if (rr != null) { + releaseRequest.resourceName = rr.resourceName; + releaseRequest.releaseNumbers = + StrUtil.listInt(rr.rangeReleaseNumbers, "Invalid value for range-release-numbers"); + releaseRequest.releaseAmount = rr.limitReleaseAmount; + } + + log.info("Releasing resources:"); + StrUtil.info(log, releaseRequest); + + resourceManager.releaseResources(releaseRequest); + + return AllocationStatus.Success; + } + + private QueryStatus allocateResources(SvcLogicContext ctx, boolean checkOnly, String prefix) + throws SvcLogicException { + String serviceModel = getParam(ctx, "service-model", true, null); + String requestType = getParam(ctx, "request-type", false, "New"); + + ResourceEntity sd = getResourceEntityData(ctx); + ResourceTarget rt = getResourceTargetData(ctx); + ResourceRequest rr = getResourceRequest(ctx); + + log.info("Starting reserve: " + requestType + ", service-model: " + serviceModel); + StrUtil.info(log, sd); + StrUtil.info(log, rt); + StrUtil.info(log, rr); + + boolean change = "change".equalsIgnoreCase(requestType); + + List<ResourceData> rlist = endPointAllocator.allocateResources(serviceModel, sd, rt, rr, checkOnly, change); + + if (rlist != null && !rlist.isEmpty()) { + setResourceDataInContext(ctx, prefix, rlist); + + for (ResourceData rd : rlist) { + if (!"Success".equals(rd.status)) { + log.info("Capacity not found for: " + sd.resourceEntityType + "::" + sd.resourceEntityId); + return QueryStatus.NOT_FOUND; + } + } + } + return QueryStatus.SUCCESS; + } + + private AllocationStatus allocateResources(ResourceEntity sd, ResourceTarget rt, ResourceRequest rr, + List<ResourceResponse> rsList) throws Exception { + + String serviceModel = rr.serviceModel; + String requestType = rr.requestType == null ? "New" : rr.requestType; + + log.info("Starting reserve: " + requestType + ", service-model: " + serviceModel); + StrUtil.info(log, sd); + StrUtil.info(log, rt); + StrUtil.info(log, rr); + + boolean change = "change".equalsIgnoreCase(requestType); + + List<ResourceData> rlist = endPointAllocator.allocateResources(serviceModel, sd, rt, rr, rr.checkOnly, change); + + if (rlist != null && !rlist.isEmpty()) { + setResourceDataInResponse(rlist, rsList); + + for (ResourceData rd : rlist) { + if (!"Success".equals(rd.status)) { + log.info("Capacity not found for: " + sd.resourceEntityType + "::" + sd.resourceEntityId); + return AllocationStatus.ResourceNotFound; + } + } + } + + return AllocationStatus.Success; + } + + private void setResourceDataInResponse(List<ResourceData> rlist, List<ResourceResponse> rsList) { + for (ResourceData rd : emptyIfNull(rlist)) { + ResourceResponse res = new ResourceResponse(); + res.resourceName = rd.resourceName; + res.endPointPosition = rd.endPointPosition; + res.resourceTargetId = rd.resourceTargetId; + res.resourceTargetType = rd.resourceTargetType; + res.status = rd.status; + if (rd.data != null && !rd.data.isEmpty()) { + for (String kk : rd.data.keySet()) { + if ("allocated".equalsIgnoreCase(kk)) { + res.resourceAllocated = String.valueOf(rd.data.get(kk)); + } + + if ("used".equalsIgnoreCase(kk)) { + res.resourceUsed = String.valueOf(rd.data.get(kk)); + } + + if ("available".equalsIgnoreCase(kk)) { + res.resourceAvailable = String.valueOf(rd.data.get(kk)); + } + + if ("limit".equalsIgnoreCase(kk)) { + res.resourceLimit = String.valueOf(rd.data.get(kk)); + } + + } + } + rsList.add(res); + } + + } + + public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) { + return iterable == null ? Collections.<T>emptyList() : iterable; + } + + private void setAttr(SvcLogicContext ctx, String name, String value) { + ctx.setAttribute(name, value); + log.info("Added context attr: " + name + ": " + value); + } + + private ResourceEntity getResourceEntityData(SvcLogicContext ctx) throws SvcLogicException { + ResourceEntity sd = new ResourceEntity(); + sd.resourceEntityId = getParam(ctx, + new String[] {"service-instance-id", "resource-entity-id", "reservation-entity-id"}, true, null); + sd.resourceEntityType = + getParam(ctx, new String[] {"reservation-entity-type", "resource-entity-type"}, true, null); + sd.resourceEntityVersion = + getParam(ctx, new String[] {"reservation-entity-version", "resource-entity-version"}, false, "1"); + sd.data = getDataParam(ctx, "reservation-entity-data", "resource-entity-data", "service-data"); + return sd; + } + + private ResourceTarget getResourceTargetData(SvcLogicContext ctx) throws SvcLogicException { + ResourceTarget sd = new ResourceTarget(); + sd.resourceTargetId = getParam(ctx, new String[] {"reservation-target-id", "resource-target-id"}, true, null); + sd.resourceTargetType = + getParam(ctx, new String[] {"reservation-target-type", "resource-target-type"}, true, null); + sd.data = getDataParam(ctx, "reservation-target-data", "resource-target-data", "equipment-data"); + return sd; + } + + private ResourceRequest getResourceRequest(SvcLogicContext ctx) throws SvcLogicException { + ResourceRequest rr = new ResourceRequest(); + rr.resourceName = getParam(ctx, "resource-name", false, null); + rr.resourceShareGroup = getParam(ctx, "resource-share-group", false, null); + rr.rangeRequestedNumbers = getParam(ctx, "range-requested-numbers", false, null); + rr.rangeExcludeNumbers = getParam(ctx, "range-exclude-numbers", false, null); + String rangeReverseOrderStr = getParam(ctx, "range-reverse-order", false, "false"); + rr.rangeReverseOrder = Boolean.parseBoolean(rangeReverseOrderStr); + String rangeMinOverrideStr = getParam(ctx, "range-min-override", false, "-1"); + rr.rangeMinOverride = Integer.parseInt(rangeMinOverrideStr); + String rangeMaxOverrideStr = getParam(ctx, "range-max-override", false, "-1"); + rr.rangeMaxOverride = Integer.parseInt(rangeMaxOverrideStr); + String rangeForceNewNumbersStr = getParam(ctx, "range-force-new-numbers", false, "false"); + rr.rangeForceNewNumbers = Boolean.parseBoolean(rangeForceNewNumbersStr); + String rangeNextInSequenceStr = getParam(ctx, "range-next-in-sequence", false, "false"); + rr.rangeNextInSequence = Boolean.parseBoolean(rangeNextInSequenceStr); + String replaceStr = getParam(ctx, "replace", false, "true"); + rr.replace = Boolean.parseBoolean(replaceStr); + rr.applicationId = getParam(ctx, "application-id", false, "SDNC"); + rr.endPointPosition = getParam(ctx, "endpoint-position", false, null); + return rr; + } + + private String getParam(SvcLogicContext ctx, String name, boolean required, String def) throws SvcLogicException { + String v = null; + for (String p : INPUT_PREFIX) { + v = ctx.getAttribute(p + name); + if (v != null && v.trim().length() > 0) { + log.info("Param: " + name + ": " + v.trim()); + return v.trim(); + } + } + if (required) { + throw new SvcLogicException("The following variable is required in DG context: " + name); + } + + log.info("Param: " + name + " not supplied. Using default: " + def); + return def; + } + + private String getParam(SvcLogicContext ctx, String[] names, boolean required, String def) + throws SvcLogicException { + String v = null; + for (String name : names) { + v = getParam(ctx, name, false, def); + if (v != null) { + return v; + } + } + if (required) { + throw new SvcLogicException( + "One of the following variable is required in DG context: " + Arrays.deepToString(names)); + } + + log.info("Param: " + Arrays.deepToString(names) + " not supplied. Using default: " + def); + return def; + } + + private Map<String, String> getDataParam(SvcLogicContext ctx, String... names) { + Map<String, String> data = new HashMap<>(); + Set<String> ctxNames = ctx.getAttributeKeySet(); + for (String n : ctxNames) { + for (String p : INPUT_PREFIX) { + for (String name : names) { + String pp = p + name + '.'; + if (n.startsWith(pp)) { + String nn = n.substring(pp.length()); + String vv = ctx.getAttribute(n); + data.put(nn, vv); + + log.info("Data param: " + nn + ": " + vv); + + if (ctxNames.contains(n + "-unit")) { + try { + long v = Long.parseLong(vv); + String unit = ctx.getAttribute(n + "-unit"); + long kbps = speedUtil.convertToKbps(v, unit); + long mbps = speedUtil.convertToMbps(v, unit); + data.put(nn + "-kbps", String.valueOf(kbps)); + data.put(nn + "-mbps", String.valueOf(mbps)); + + log.info("Data param: " + nn + "-kbps: " + kbps); + log.info("Data param: " + nn + "-mbps: " + mbps); + + } catch (Exception e) { + log.warn("Invalid number for " + n + ": " + vv); + } + } + } + } + } + } + return data; + } + + @SuppressWarnings("unchecked") + public static Map<String, String> dataToProperties(Map<String, Object> data) { + if (data == null || data.isEmpty()) { + return Collections.emptyMap(); + } + + Map<String, String> prop = new HashMap<>(); + Map<String, Object> data1 = new HashMap<>(data); + + while (!data1.isEmpty()) { + for (String key : new ArrayList<>(data1.keySet())) { + Object o = data1.get(key); + data1.remove(key); + + if (o instanceof Boolean || o instanceof Number || o instanceof String) { + prop.put(key, o.toString()); + } else if (o instanceof Map) { + Map<String, Object> mm = (Map<String, Object>) o; + for (String key1 : mm.keySet()) { + data1.put(key + "." + key1, mm.get(key1)); + } + } else if (o instanceof List) { + List<Object> ll = (List<Object>) o; + prop.put(key + "_length", String.valueOf(ll.size())); + for (int i = 0; i < ll.size(); i++) { + data1.put(key + '[' + i + ']', ll.get(i)); + } + } + } + } + return prop; + } + + public void setResourceManager(ResourceManager resourceManager) { + this.resourceManager = resourceManager; + } + + public void setEndPointAllocator(EndPointAllocator endPointAllocator) { + this.endPointAllocator = endPointAllocator; + } + + public void setSpeedUtil(SpeedUtil speedUtil) { + this.speedUtil = speedUtil; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceLockNode.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceLockNode.java new file mode 100644 index 000000000..a7d4b0e27 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/ResourceLockNode.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra; + +import java.security.SecureRandom; +import java.util.Map; +import org.onap.ccsdk.sli.adaptors.lock.comp.LockHelper; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResourceLockNode implements SvcLogicJavaPlugin { + + private static final Logger log = LoggerFactory.getLogger(ResourceLockNode.class); + + private LockHelper lockHelper; + + public void setLockHelper(LockHelper lockHelper) { + this.lockHelper = lockHelper; + } + + public void lockResource(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException { + String resourceName = getParam(paramMap, "resource-name", true, null); + String lockRequester = getParam(paramMap, "lock-requester", false, generateLockRequester()); + String lockTimeoutStr = getParam(paramMap, "lock-timeout", false, "600"); // Default lock timeout: 10 min + int lockTimeout = Integer.parseInt(lockTimeoutStr); + String lockWaitStr = getParam(paramMap, "lock-wait", false, "5"); // Time waiting before next retry. Default: 5 sec + int lockWait = Integer.parseInt(lockWaitStr); + String lockRetryCountStr = getParam(paramMap, "lock-retry-count", false, "10"); // Default: 10 retries + int lockRetryCount = Integer.parseInt(lockRetryCountStr); + + lockHelper.lock(resourceName, lockRequester, lockTimeout, lockWait, lockRetryCount); + } + + public void unlockResource(Map<String, String> paramMap, SvcLogicContext ctx) throws SvcLogicException { + String resourceName = getParam(paramMap, "resource-name", true, null); + + lockHelper.unlock(resourceName, false); + } + + public void lockResource(String resourceName, String lockRequester, int lockTimeout /* sec */) { + lockResource(resourceName, lockRequester, lockTimeout, 5, 10); + } + + public void lockResource(String resourceName, String lockRequester, int lockTimeout /* sec */, int lockWait /* Seconds */, int retryCount) { + if (lockRequester == null) { + lockRequester = generateLockRequester(); + } + if (lockTimeout <= 0) { + lockTimeout = 600; + } + + lockHelper.lock(resourceName, lockRequester, lockTimeout, lockWait, retryCount); + } + + public void unlockResource(String resourceName) { + lockHelper.unlock(resourceName, false); + } + + private String getParam(Map<String, String> paramMap, String name, boolean required, String def) + throws SvcLogicException { + String v = paramMap.get(name); + if (v != null && v.trim().length() > 0) { + log.info("Param: " + name + ": " + v.trim()); + return v.trim(); + } + if (required) { + throw new SvcLogicException("The following node parameter is required: " + name); + } + + log.info("Param: " + name + " not supplied. Using default: " + def); + return def; + } + + private static String generateLockRequester() { + SecureRandom rand = new SecureRandom(); + return "SynchronizedFunction-" + (int) (rand.nextDouble() * 1000000); + } +} + diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/alloc/DbAllocationRule.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/alloc/DbAllocationRule.java new file mode 100644 index 000000000..d15b1508f --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/alloc/DbAllocationRule.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.alloc; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.ra.comp.AllocationRule; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceEntity; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceRequest; +import org.onap.ccsdk.sli.adaptors.ra.comp.ResourceTarget; +import org.onap.ccsdk.sli.adaptors.ra.rule.dao.RangeRuleDao; +import org.onap.ccsdk.sli.adaptors.ra.rule.dao.ResourceRuleDao; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.RangeRule; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.ResourceRule; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationAction; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiResourceAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; +import org.onap.ccsdk.sli.adaptors.util.expr.ExpressionEvaluator; +import org.onap.ccsdk.sli.adaptors.util.str.StrUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DbAllocationRule implements AllocationRule { + + private static final Logger log = LoggerFactory.getLogger(DbAllocationRule.class); + + private ResourceRuleDao resourceRuleDao; + private RangeRuleDao rangeRuleDao; + + @Override + public AllocationRequest buildAllocationRequest(String serviceModel, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change) { + List<ResourceRule> resourceRuleList = resourceRuleDao.getResourceRules(serviceModel, + resourceTarget.resourceTargetType); + List<RangeRule> rangeRuleList = rangeRuleDao.getRangeRules(serviceModel, resourceTarget.resourceTargetType); + + List<AllocationRequest> arlist = new ArrayList<>(); + + for (ResourceRule rr : resourceRuleList) { + if (resourceRequest.resourceName != null && !resourceRequest.resourceName.equals(rr.resourceName)) { + continue; + } + + boolean matches = ExpressionEvaluator.evalBoolean(rr.serviceExpression, resourceEntity.data); + matches = matches && ExpressionEvaluator.evalBoolean(rr.equipmentExpression, resourceTarget.data); + + if (matches) { + AllocationRequest ar1 = buildAllocationRequest(rr, resourceEntity, resourceTarget, resourceRequest, + checkOnly, change); + arlist.add(ar1); + } + } + + for (RangeRule rr : rangeRuleList) { + if (resourceRequest.resourceName != null && !resourceRequest.resourceName.equals(rr.rangeName)) { + continue; + } + if (resourceRequest.endPointPosition != null + && !resourceRequest.endPointPosition.equals(rr.endPointPosition)) { + continue; + } + + if (!ExpressionEvaluator.evalBoolean(rr.equipmentExpression, resourceTarget.data)) { + continue; + } + + AllocationRequest ar1 = buildAllocationRequest(rr, resourceEntity, resourceTarget, resourceRequest, + checkOnly, change); + arlist.add(ar1); + } + + if ((rangeRuleList == null || rangeRuleList.isEmpty()) + && ResourceType.Range.equals(resourceRequest.resourceType)) { + AllocationRequest ar1 = buildAllocationRequest(resourceEntity, resourceTarget, resourceRequest, checkOnly, + change); + arlist.add(ar1); + } + + if (arlist.isEmpty()) { + return null; + } + + if (arlist.size() == 1) { + return arlist.get(0); + } + + MultiResourceAllocationRequest ar = new MultiResourceAllocationRequest(); + ar.stopOnFirstFailure = false; + ar.allocationRequestList = arlist; + return ar; + } + + private AllocationRequest buildAllocationRequest(ResourceEntity resourceEntity, ResourceTarget resourceTarget, + ResourceRequest resourceRequest, boolean checkOnly, boolean change) { + + RangeAllocationRequest ar = new RangeAllocationRequest(); + ar.applicationId = resourceRequest.applicationId; + if (resourceRequest.endPointPosition != null) { + ar.resourceUnionId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId + "::" + + resourceRequest.endPointPosition; + ar.endPointPosition = resourceRequest.endPointPosition; + } else { + ar.resourceUnionId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId; + } + ar.resourceSetId = ar.resourceUnionId + "::" + resourceEntity.resourceEntityVersion; + ar.resourceName = resourceRequest.resourceName; + if (resourceRequest.resourceShareGroup != null) { + ar.resourceShareGroupList = Collections.singleton(resourceRequest.resourceShareGroup); + } + ar.assetId = resourceTarget.resourceTargetType + "::" + resourceTarget.resourceTargetId; + ar.requestedNumbers = StrUtil.listInt(resourceRequest.rangeRequestedNumbers, + "Invalid value for requested-numbers"); + if (ar.requestedNumbers != null) { + ar.requestedCount = ar.requestedNumbers.size(); + } + ar.excludeNumbers = StrUtil.listInt(resourceRequest.rangeExcludeNumbers, "Invalid value for exclude-numbers"); + ar.reverseOrder = resourceRequest.rangeReverseOrder; + ar.missingResourceAction = AllocationAction.Succeed_Allocate; + ar.expiredResourceAction = AllocationAction.Succeed_Allocate; + ar.replace = resourceRequest.replace; + ar.check = true; + ar.allocate = !checkOnly; + ar.rangeList = resourceRequest.rangeOverrideList; + if (ar.rangeList == null || ar.rangeList.isEmpty()) { + if (resourceRequest.rangeMinOverride >= 0 + && resourceRequest.rangeMaxOverride >= resourceRequest.rangeMinOverride) { + ar.rangeList = new ArrayList<>(); + Range range = new Range(); + range.min = resourceRequest.rangeMinOverride; + range.max = resourceRequest.rangeMaxOverride; + ar.rangeList.add(range); + } + } else { + if (resourceRequest.rangeMinOverride >= 0) { + ar.rangeList.get(0).min = resourceRequest.rangeMinOverride; + } + if (resourceRequest.rangeMaxOverride >= 0) { + ar.rangeList.get(ar.rangeList.size() - 1).max = resourceRequest.rangeMaxOverride; + } + } + ar.forceNewNumbers = resourceRequest.rangeForceNewNumbers; + StrUtil.info(log, ar); + return ar; + } + + private AllocationRequest buildAllocationRequest(ResourceRule resourceRule, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change) { + StrUtil.info(log, resourceRule); + + LimitAllocationRequest ar = new LimitAllocationRequest(); + ar.applicationId = resourceRequest.applicationId; + ar.resourceUnionId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId; + ar.resourceSetId = ar.resourceUnionId + "::" + resourceEntity.resourceEntityVersion; + ar.resourceName = resourceRule.resourceName; + if (resourceRequest.resourceShareGroup != null) { + ar.resourceShareGroupList = Collections.singleton(resourceRequest.resourceShareGroup); + } + ar.assetId = resourceTarget.resourceTargetType + "::" + resourceTarget.resourceTargetId; + ar.missingResourceAction = AllocationAction.Succeed_Allocate; + ar.expiredResourceAction = AllocationAction.Succeed_Allocate; + ar.replace = resourceRequest.replace; + ar.strict = false; + ar.checkLimit = ExpressionEvaluator.evalLong( + change ? resourceRule.hardLimitExpression : resourceRule.softLimitExpression, resourceTarget.data); + ar.checkCount = ExpressionEvaluator.evalLong(resourceRule.allocationExpression, resourceEntity.data); + ar.allocateCount = checkOnly ? 0 : ar.checkCount; + return ar; + } + + private AllocationRequest buildAllocationRequest(RangeRule rangeRule, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change) { + StrUtil.info(log, rangeRule); + + RangeAllocationRequest ar = new RangeAllocationRequest(); + ar.applicationId = resourceRequest.applicationId; + if (resourceRequest.endPointPosition != null) { + ar.resourceUnionId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId + "::" + + resourceRequest.endPointPosition; + ar.endPointPosition = resourceRequest.endPointPosition; + } else { + ar.resourceUnionId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId; + } + ar.resourceSetId = ar.resourceUnionId + "::" + resourceEntity.resourceEntityVersion; + ar.resourceName = rangeRule.rangeName; + if (resourceRequest.resourceShareGroup != null) { + ar.resourceShareGroupList = Collections.singleton(resourceRequest.resourceShareGroup); + } + ar.assetId = resourceTarget.resourceTargetType + "::" + resourceTarget.resourceTargetId; + ar.requestedNumbers = StrUtil.listInt(resourceRequest.rangeRequestedNumbers, + "Invalid value for requested-numbers"); + if (ar.requestedNumbers != null) { + ar.requestedCount = ar.requestedNumbers.size(); + } + ar.excludeNumbers = StrUtil.listInt(resourceRequest.rangeExcludeNumbers, "Invalid value for exclude-numbers"); + ar.reverseOrder = resourceRequest.rangeReverseOrder; + ar.missingResourceAction = AllocationAction.Succeed_Allocate; + ar.expiredResourceAction = AllocationAction.Succeed_Allocate; + ar.replace = resourceRequest.replace; + ar.check = true; + ar.allocate = !checkOnly; + ar.rangeList = rangeRule.rangeList; + if (ar.rangeList == null || ar.rangeList.isEmpty()) { + if (resourceRequest.rangeMinOverride >= 0 + && resourceRequest.rangeMaxOverride >= resourceRequest.rangeMinOverride) { + ar.rangeList = new ArrayList<>(); + Range range = new Range(); + range.min = resourceRequest.rangeMinOverride; + range.max = resourceRequest.rangeMaxOverride; + ar.rangeList.add(range); + } + } else { + if (resourceRequest.rangeMinOverride >= 0) { + ar.rangeList.get(0).min = resourceRequest.rangeMinOverride; + } + if (resourceRequest.rangeMaxOverride >= 0) { + ar.rangeList.get(ar.rangeList.size() - 1).max = resourceRequest.rangeMaxOverride; + } + + } + ar.forceNewNumbers = resourceRequest.rangeForceNewNumbers; + ar.nextInSequence = resourceRequest.rangeNextInSequence; + return ar; + } + + public void setResourceRuleDao(ResourceRuleDao resourceRuleDao) { + this.resourceRuleDao = resourceRuleDao; + } + + public void setRangeRuleDao(RangeRuleDao rangeRuleDao) { + this.rangeRuleDao = rangeRuleDao; + } +}
\ No newline at end of file diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java new file mode 100644 index 000000000..3e0e6b140 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationData.java @@ -0,0 +1,11 @@ +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.Map; + +public class AllocationData { + + public String resourceEntityType; + public String resourceEntityId; + public String resourceEntityVersion; + public Map<String, String> data; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationRule.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationRule.java new file mode 100644 index 000000000..0e9737419 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/AllocationRule.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; + +public interface AllocationRule { + + AllocationRequest buildAllocationRequest(String serviceModel, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocator.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocator.java new file mode 100644 index 000000000..abfb8d44f --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocator.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.List; + +public interface EndPointAllocator { + + List<ResourceData> allocateResources(String serviceModel, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change); + + List<ResourceData> getResourcesForEntity(String resourceEntityType, String resourceEntityId, + String resourceEntityVersion); + + ResourceData getResource(String resourceTargetType, String resourceTargetId, String resourceName, + String resourceEntityTypeFilter, String resourceEntityIdFilter, String resourceShareGroupFilter); + + List<ResourceData> getResourcesForTarget(String resourceTargetTypeFilter, String resourceTargetIdFilter, + String resourceName); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocatorImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocatorImpl.java new file mode 100644 index 000000000..36e40d589 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/EndPointAllocatorImpl.java @@ -0,0 +1,368 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * + * Modifications Copyright (C) 2019 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.onap.ccsdk.sli.adaptors.rm.comp.ResourceManager; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationStatus; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitResource; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiResourceAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeResource; +import org.onap.ccsdk.sli.adaptors.rm.data.ReleaseRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; +import org.onap.ccsdk.sli.adaptors.util.str.StrUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EndPointAllocatorImpl implements EndPointAllocator { + + private static final Logger log = LoggerFactory.getLogger(EndPointAllocatorImpl.class); + + private ResourceManager resourceManager; + + private Map<String, List<AllocationRule>> allocationRuleMap; + + @Override + public List<ResourceData> allocateResources(String serviceModel, ResourceEntity resourceEntity, + ResourceTarget resourceTarget, ResourceRequest resourceRequest, boolean checkOnly, boolean change) { + + List<ResourceData> resourceList = new ArrayList<>(); + + if (allocationRuleMap != null) { + List<AllocationRule> allocationRuleList = allocationRuleMap.get(serviceModel); + if (allocationRuleList == null) { + allocationRuleList = allocationRuleMap.get("DEFAULT"); + } + + if (allocationRuleList != null) { + boolean allgood = true; + for (AllocationRule allocationRule : allocationRuleList) { + AllocationRequest ar = allocationRule.buildAllocationRequest(serviceModel, resourceEntity, + resourceTarget, resourceRequest, checkOnly, change); + if (ar != null) { + AllocationOutcome ao = resourceManager.allocateResources(ar); + List<ResourceData> rr = getResourceData(ao); + resourceList.addAll(rr); + + if (ao.status != AllocationStatus.Success) { + allgood = false; + } + } + } + + if (!allgood) { + String resourceSetId = resourceEntity.resourceEntityType + "::" + resourceEntity.resourceEntityId + + "::" + resourceEntity.resourceEntityVersion; + resourceManager.releaseResources(ReleaseRequest.resourceSet(resourceSetId)); + } + } + } + + return resourceList; + } + + private List<ResourceData> getResourceData(AllocationOutcome ao) { + if (ao instanceof MultiResourceAllocationOutcome) { + List<ResourceData> rr = new ArrayList<>(); + for (AllocationOutcome ao1 : ((MultiResourceAllocationOutcome) ao).allocationOutcomeList) { + rr.addAll(getResourceData(ao1)); + } + return rr; + } + + ResourceData rd = new ResourceData(); + rd.data = new HashMap<>(); + + AllocationRequest ar = ao.request; + rd.resourceName = ar.resourceName; + rd.endPointPosition = ar.endPointPosition; + int i1 = ar.assetId.indexOf("::"); + if (i1 > 0) { + rd.resourceTargetType = ar.assetId.substring(0, i1); + rd.resourceTargetId = ar.assetId.substring(i1 + 2); + } else { + rd.resourceTargetType = ""; + rd.resourceTargetId = ar.assetId; + } + rd.status = ao.status.toString(); + + if (ao instanceof LimitAllocationOutcome) { + LimitAllocationOutcome lao = (LimitAllocationOutcome) ao; + rd.data.put("allocated", String.valueOf(lao.allocatedCount)); + rd.data.put("used", String.valueOf(lao.used)); + rd.data.put("limit", String.valueOf(lao.limit)); + rd.data.put("available", String.valueOf(lao.limit - lao.used)); + } else if (ao instanceof RangeAllocationOutcome) { + RangeAllocationOutcome rao = (RangeAllocationOutcome) ao; + rd.data.put("allocated", String.valueOf(StrUtil.listInt(rao.allocated))); + rd.data.put("used", String.valueOf(StrUtil.listInt(rao.used))); + List<Range> rangeList = ((RangeAllocationRequest) rao.request).rangeList; + if (rangeList != null && !rangeList.isEmpty()) { + List<Object> ll = new ArrayList<>(); + for (Range r : rangeList) { + Map<String, Object> mm = new HashMap<>(); + mm.put("min", r.min); + mm.put("max", r.max); + ll.add(mm); + } + rd.data.put("range-list", ll); + } + } + + return Collections.singletonList(rd); + } + + @Override + public List<ResourceData> getResourcesForEntity(String resourceEntityType, String resourceEntityId, + String resourceEntityVersion) { + List<ResourceData> rdlist = new ArrayList<>(); + + String resourceUnionId = resourceEntityType + "::" + resourceEntityId; + List<Resource> rlist = resourceManager.getResourceUnion(resourceUnionId); + + for (Resource r : rlist) { + + // Find the needed allocation item: if resourceEntityVersion is specified, use that, + // otherwise, find the latest allocation item + AllocationItem ai = null; + if (resourceEntityVersion != null) { + String resourceSetId = resourceUnionId + "::" + resourceEntityVersion; + for (AllocationItem ai1 : r.allocationItems) { + if (ai1.resourceSetId.equals(resourceSetId)) { + ai = ai1; + break; + } + } + } else { + Date aitime = null; + for (AllocationItem ai1 : r.allocationItems) { + if (ai1.resourceUnionId.equals(resourceUnionId)) { + if (aitime == null || ai1.allocationTime.after(aitime)) { + ai = ai1; + aitime = ai1.allocationTime; + } + } + } + } + + if (ai != null) { + ResourceData rd = new ResourceData(); + rdlist.add(rd); + + rd.resourceName = r.resourceKey.resourceName; + int i1 = r.resourceKey.assetId.indexOf("::"); + if (i1 > 0) { + rd.resourceTargetType = r.resourceKey.assetId.substring(0, i1); + rd.resourceTargetId = r.resourceKey.assetId.substring(i1 + 2); + + int i2 = r.resourceKey.assetId.lastIndexOf("::"); + if (i2 > i1) { + rd.resourceTargetValue = r.resourceKey.assetId.substring(i2 + 2); + } + } else { + rd.resourceTargetType = ""; + rd.resourceTargetId = r.resourceKey.assetId; + } + + rd.data = new HashMap<>(); + + if (ai instanceof RangeAllocationItem) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + + String ss = String.valueOf(rai.used); + ss = ss.substring(1, ss.length() - 1); + rd.data.put("allocated", ss); + + } else if (ai instanceof LimitAllocationItem) { + LimitAllocationItem lai = (LimitAllocationItem) ai; + + rd.data.put("allocated", String.valueOf(lai.used)); + } + } + } + + return rdlist; + } + + @Override + public List<ResourceData> getResourcesForTarget(String resourceTargetTypeFilter, String resourceTargetIdFilter, + String resourceName) { + List<ResourceData> rdlist = new ArrayList<>(); + + String assetIdFilter = null; + if (resourceTargetTypeFilter != null && resourceTargetIdFilter != null) { + assetIdFilter = resourceTargetTypeFilter + "::" + resourceTargetIdFilter; + } else if (resourceTargetTypeFilter != null) { + assetIdFilter = resourceTargetTypeFilter; + } else if (resourceTargetIdFilter != null) { + assetIdFilter = resourceTargetIdFilter; + } + + List<Resource> rlist = resourceManager.queryResources(resourceName, assetIdFilter); + + for (Resource r : rlist) { + if (r.allocationItems == null || r.allocationItems.isEmpty()) { + continue; + } + + log.info("ResourceName:" + r.resourceKey.resourceName + " assetId:" + r.resourceKey.assetId); + + + rdlist.add(getResourceData(r)); + } + + return rdlist; + } + + @Override + public ResourceData getResource(String resourceTargetType, String resourceTargetId, String resourceName, + String resourceEntityTypeFilter, String resourceEntityIdFilter, String resourceShareGroupFilter) { + String assetId = resourceTargetType + "::" + resourceTargetId; + + String resourceUnionFilter = null; + if (resourceEntityTypeFilter != null && resourceEntityIdFilter != null) { + resourceUnionFilter = resourceEntityTypeFilter + "::" + resourceEntityIdFilter; + } else if (resourceEntityTypeFilter != null) { + resourceUnionFilter = resourceEntityTypeFilter; + } else if (resourceEntityIdFilter != null) { + resourceUnionFilter = resourceEntityIdFilter; + } + + Resource r = null; + if (resourceUnionFilter != null || resourceShareGroupFilter != null) { + r = resourceManager.queryResource(resourceName, assetId, resourceUnionFilter, resourceShareGroupFilter); + } else { + r = resourceManager.getResource(resourceName, assetId); + } + + if (r != null && r.allocationItems != null && !r.allocationItems.isEmpty()) { + log.info("ResourceName:" + r.resourceKey.resourceName + " assetId:" + r.resourceKey.assetId); + return getResourceData(r); + } + + return null; + } + + private ResourceData getResourceData(Resource r) { + ResourceData rd = new ResourceData(); + + rd.resourceName = r.resourceKey.resourceName; + int i1 = r.resourceKey.assetId.indexOf("::"); + if (i1 > 0) { + rd.resourceTargetType = r.resourceKey.assetId.substring(0, i1); + rd.resourceTargetId = r.resourceKey.assetId.substring(i1 + 2); + + int i2 = r.resourceKey.assetId.lastIndexOf("::"); + if (i2 > i1) { + rd.resourceTargetValue = r.resourceKey.assetId.substring(i2 + 2); + } + } else { + rd.resourceTargetType = ""; + rd.resourceTargetId = r.resourceKey.assetId; + } + + rd.data = new HashMap<>(); + + if (r instanceof RangeResource) { + RangeResource rr = (RangeResource) r; + + log.info("rr.used: " + rr.used); + String ss = String.valueOf(rr.used); + ss = ss.substring(1, ss.length() - 1); + rd.data.put("allocated", ss); + + } else if (r instanceof LimitResource) { + LimitResource lr = (LimitResource) r; + + log.info("lr.used: " + lr.used); + rd.data.put("allocated", String.valueOf(lr.used)); + } + + rd.allocationDataList = new ArrayList<>(); + + if (r.allocationItems != null) { + for (AllocationItem ai : r.allocationItems) { + AllocationData ad = new AllocationData(); + rd.allocationDataList.add(ad); + + i1 = ai.resourceUnionId.indexOf("::"); + if (i1 > 0) { + ad.resourceEntityType = ai.resourceUnionId.substring(0, i1); + ad.resourceEntityId = ai.resourceUnionId.substring(i1 + 2); + } else { + ad.resourceEntityType = ""; + ad.resourceEntityId = ai.resourceUnionId; + } + + i1 = ai.resourceSetId.lastIndexOf("::"); + if (i1 > 0) { + ad.resourceEntityVersion = ai.resourceSetId.substring(i1 + 2); + } else { + ad.resourceEntityVersion = ""; + } + + ad.data = new HashMap<>(); + + if (ai instanceof RangeAllocationItem) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + + log.info("rr.used: " + rai.used); + String ss = String.valueOf(rai.used); + ss = ss.substring(1, ss.length() - 1); + ad.data.put("allocated", ss); + + } else if (ai instanceof LimitAllocationItem) { + LimitAllocationItem lai = (LimitAllocationItem) ai; + + log.info("lr.used: " + lai.used); + ad.data.put("allocated", String.valueOf(lai.used)); + } + } + } + + return rd; + } + + public void setResourceManager(ResourceManager resourceManager) { + this.resourceManager = resourceManager; + } + + public void setAllocationRuleMap(Map<String, List<AllocationRule>> allocationRuleMap) { + this.allocationRuleMap = allocationRuleMap; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceData.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceData.java new file mode 100644 index 000000000..d83d4cdb4 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceData.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.List; +import java.util.Map; + +public class ResourceData { + + public String resourceName; + public String resourceTargetId; + public String resourceTargetValue; + public String resourceTargetType; + public String endPointPosition; + public String status; + public Map<String, Object> data; + public List<AllocationData> allocationDataList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceEntity.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceEntity.java new file mode 100644 index 000000000..12fb695b7 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceEntity.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.Map; + +public class ResourceEntity { + + public String resourceEntityId; + public String resourceEntityVersion; + public String resourceEntityType; + public Map<String, String> data; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceRequest.java new file mode 100644 index 000000000..2ebad4c89 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceRequest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; + +public class ResourceRequest { + + public String resourceName; + public String resourceShareGroup; + public String rangeRequestedNumbers; + public String rangeExcludeNumbers; + public boolean rangeReverseOrder; + public int rangeMinOverride; + public int rangeMaxOverride; + public boolean rangeForceNewNumbers; + public boolean rangeNextInSequence; + public boolean replace; + public String requestType; + public String serviceModel; + public boolean checkOnly; + public String applicationId; + public String endPointPosition; + public ResourceType resourceType; + public List<Range> rangeOverrideList; + public String resourceEntityTypeFilter; + public String resourceEntityIdFilter; + public String resourceShareGroupFilter; + public String resourceTargetTypeFilter; + public String resourceTargetIdFilter; + public String rangeReleaseNumbers; + public int limitReleaseAmount; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceResponse.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceResponse.java new file mode 100644 index 000000000..989333c3e --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceResponse.java @@ -0,0 +1,13 @@ +package org.onap.ccsdk.sli.adaptors.ra.comp; + +public class ResourceResponse { + public String resourceName; + public String endPointPosition; + public String resourceTargetType; + public String resourceTargetId; + public String resourceLimit; + public String resourceAvailable; + public String resourceUsed; + public String resourceAllocated; + public String status; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceTarget.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceTarget.java new file mode 100644 index 000000000..95cec330a --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/comp/ResourceTarget.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.comp; + +import java.util.Map; + +public class ResourceTarget { + + public String resourceTargetId; + public String resourceTargetType; + public Map<String, String> data; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDao.java new file mode 100644 index 000000000..a7fcb61f2 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDao.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.dao; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.RangeRule; + +public interface RangeRuleDao { + + List<RangeRule> getRangeRules(String serviceModel, String equipLevel); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDaoImpl.java new file mode 100644 index 000000000..b021620ba --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/RangeRuleDaoImpl.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.dao; + +import java.util.ArrayList; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.RangeRule; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +public class RangeRuleDaoImpl implements RangeRuleDao { + + private static final Logger log = LoggerFactory.getLogger(RangeRuleDaoImpl.class); + + private static final String GET_SQL = "SELECT * FROM RANGE_RULE WHERE service_model = ? AND equipment_level = ?"; + + private JdbcTemplate jdbcTemplate; + + @Override + public List<RangeRule> getRangeRules(String serviceModel, String equipLevel) { + return jdbcTemplate.query(GET_SQL, new Object[] { serviceModel, equipLevel }, + (RowMapper<RangeRule>) (rs, rowNum) -> { + RangeRule rl = new RangeRule(); + rl.id = rs.getLong("range_rule_id"); + rl.rangeName = rs.getString("range_name"); + rl.serviceModel = rs.getString("service_model"); + rl.endPointPosition = rs.getString("end_point_position"); + rl.equipmentLevel = rs.getString("equipment_level"); + rl.equipmentExpression = rs.getString("equipment_expression"); + + String rangesStr = rs.getString("ranges"); + String[] ranges = rangesStr.split(","); + rl.rangeList = new ArrayList<>(); + for (String rangeStr : ranges) { + Range range = new Range(); + String[] nn = rangeStr.split("-"); + if (nn.length >= 1) { + try { + range.min = range.max = Integer.parseInt(nn[0]); + } catch (NumberFormatException e) { + log.warn("Invalid value found in DB for range: " + rangeStr, e); + } + } + if (nn.length >= 2) { + try { + range.max = Integer.parseInt(nn[1]); + } catch (NumberFormatException e) { + log.warn("Invalid value found in DB for range: " + rangeStr, e); + } + } + if (nn.length > 2) { + log.warn("Invalid value found in DB for range: {}", rangeStr); + } + rl.rangeList.add(range); + } + + return rl; + }); + + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +}
\ No newline at end of file diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDao.java new file mode 100644 index 000000000..54fdcbc20 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDao.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.dao; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.ResourceRule; + +public interface ResourceRuleDao { + + List<ResourceRule> getResourceRules(String serviceModel, String equipLevel); + + ResourceRule getResourceRule(String serviceModel, String endPointPosition, String equipLevel, String resourceName); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDaoImpl.java new file mode 100644 index 000000000..451dc57cd --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/dao/ResourceRuleDaoImpl.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.dao; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.ResourceRule; +import org.onap.ccsdk.sli.adaptors.ra.rule.data.ResourceThreshold; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +public class ResourceRuleDaoImpl implements ResourceRuleDao { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ResourceRuleDaoImpl.class); + + private static final String GET1_SQL = + "SELECT * FROM RESOURCE_RULE WHERE service_model = ? AND equipment_level = ?"; + private static final String GET2_SQL = + "SELECT * FROM RESOURCE_RULE WHERE service_model = ? AND end_point_position = ? AND equipment_level = ? AND resource_name = ?"; + private static final String THRESHOLD_SQL = "SELECT * FROM RESOURCE_THRESHOLD WHERE resource_rule_id = ?"; + + private JdbcTemplate jdbcTemplate; + ResourceRuleRowMapper resourceRuleRowMapper = new ResourceRuleRowMapper(); + ResourceThresholdRowMapper resourceThresholdRowMapper = new ResourceThresholdRowMapper(); + + @Override + public List<ResourceRule> getResourceRules(String serviceModel, String equipLevel) { + List<ResourceRule> resourceRuleList = + jdbcTemplate.query(GET1_SQL, new Object[] {serviceModel, equipLevel}, resourceRuleRowMapper); + + for (ResourceRule rr : resourceRuleList) { + rr.thresholdList = jdbcTemplate.query(THRESHOLD_SQL, new Object[] {rr.id}, resourceThresholdRowMapper); + } + + return resourceRuleList; + } + + @Override + public ResourceRule getResourceRule(String serviceModel, String endPointPosition, String equipLevel, + String resourceName) { + List<ResourceRule> resourceRuleList = jdbcTemplate.query(GET2_SQL, + new Object[] {serviceModel, endPointPosition, equipLevel, resourceName}, resourceRuleRowMapper); + + if (resourceRuleList == null || resourceRuleList.isEmpty()) { + return null; + } + + ResourceRule rr = resourceRuleList.get(0); + rr.thresholdList = jdbcTemplate.query(THRESHOLD_SQL, new Object[] {rr.id}, resourceThresholdRowMapper); + + return rr; + } + + private static class ResourceRuleRowMapper implements RowMapper<ResourceRule> { + + @Override + public ResourceRule mapRow(ResultSet rs, int rowNum) throws SQLException { + ResourceRule rl = new ResourceRule(); + rl.id = rs.getLong("resource_rule_id"); + rl.resourceName = rs.getString("resource_name"); + rl.serviceModel = rs.getString("service_model"); + rl.endPointPosition = rs.getString("end_point_position"); + rl.serviceExpression = rs.getString("service_expression"); + rl.equipmentLevel = rs.getString("equipment_level"); + rl.equipmentExpression = rs.getString("equipment_expression"); + rl.allocationExpression = rs.getString("allocation_expression"); + rl.softLimitExpression = rs.getString("soft_limit_expression"); + rl.hardLimitExpression = rs.getString("hard_limit_expression"); + return rl; + } + } + + private static class ResourceThresholdRowMapper implements RowMapper<ResourceThreshold> { + + @Override + public ResourceThreshold mapRow(ResultSet rs, int rowNum) throws SQLException { + ResourceThreshold th = new ResourceThreshold(); + th.expression = rs.getString("threshold_expression"); + th.message = rs.getString("threshold_message"); + return th; + } + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/RangeRule.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/RangeRule.java new file mode 100644 index 000000000..c1ccd8196 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/RangeRule.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.data; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; + +public class RangeRule { + + public long id; + public String rangeName; + public String serviceModel; + public String endPointPosition; + public String equipmentLevel; + public String equipmentExpression; + public List<Range> rangeList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceRule.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceRule.java new file mode 100644 index 000000000..17e0196b2 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceRule.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.data; + +import java.util.List; + +public class ResourceRule { + + public long id; + public String resourceName; + public String serviceModel; + public String endPointPosition; + public String serviceExpression; + public String equipmentLevel; + public String equipmentExpression; + public String allocationExpression; + public String softLimitExpression; + public String hardLimitExpression; + public List<ResourceThreshold> thresholdList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceThreshold.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceThreshold.java new file mode 100644 index 000000000..3f07d9f6b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ResourceThreshold.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.data; + +public class ResourceThreshold { + + public String expression; + public String message; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ThresholdStatus.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ThresholdStatus.java new file mode 100644 index 000000000..5bc8d3450 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/ra/rule/data/ThresholdStatus.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.ra.rule.data; + +public class ThresholdStatus { + + public ResourceRule resourceRule; + public ResourceThreshold resourceThreshold; + public long limitValue; + public long thresholdValue; + public long used; + public long lastAdded; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/AllocationFunction.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/AllocationFunction.java new file mode 100644 index 000000000..485010656 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/AllocationFunction.java @@ -0,0 +1,433 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.comp; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import org.onap.ccsdk.sli.adaptors.lock.comp.LockHelper; +import org.onap.ccsdk.sli.adaptors.lock.comp.ResourceLockedException; +import org.onap.ccsdk.sli.adaptors.lock.comp.SynchronizedFunction; +import org.onap.ccsdk.sli.adaptors.rm.dao.ResourceDao; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationStatus; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelResource; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitResource; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiAssetAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiAssetAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiResourceAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.MultiResourceAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeResource; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceKey; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; +import org.onap.ccsdk.sli.adaptors.rm.util.LabelUtil; +import org.onap.ccsdk.sli.adaptors.rm.util.LimitUtil; +import org.onap.ccsdk.sli.adaptors.rm.util.RangeUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class AllocationFunction extends SynchronizedFunction { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(AllocationFunction.class); + + private ResourceDao resourceDao; + + private AllocationRequest request; + private AllocationOutcome outcome; + + private List<Resource> updateList = new ArrayList<>(); + + public AllocationFunction(LockHelper lockHelper, ResourceDao resourceDao, AllocationRequest request, + int lockTimeout) { + super(lockHelper, getLockNames(request), lockTimeout); + this.resourceDao = resourceDao; + this.request = request; + } + + private static Collection<String> getLockNames(AllocationRequest request) { + Set<String> lockResourceNames = new HashSet<>(); + addLockNames(lockResourceNames, request); + return lockResourceNames; + } + + private static void addLockNames(Set<String> lockResourceNames, AllocationRequest request) { + if (request instanceof MultiAssetAllocationRequest) { + MultiAssetAllocationRequest req = (MultiAssetAllocationRequest) request; + if (req.assetIdList != null) { + lockResourceNames.addAll(req.assetIdList); + } + } else if (request instanceof MultiResourceAllocationRequest) { + MultiResourceAllocationRequest req = (MultiResourceAllocationRequest) request; + if (req.allocationRequestList != null) { + for (AllocationRequest request1 : req.allocationRequestList) { + addLockNames(lockResourceNames, request1); + } + } + } else if (request.assetId != null) { + lockResourceNames.add(request.assetId); + } + } + + @Override + public void _exec() throws ResourceLockedException { + outcome = allocate(request); + + if (outcome!=null && outcome.status == AllocationStatus.Success) { + for (Resource r : updateList) { + resourceDao.saveResource(r); + } + } + } + + private AllocationOutcome allocate(AllocationRequest allocationRequest) throws ResourceLockedException { + if (allocationRequest instanceof MultiAssetAllocationRequest) { + return allocateMultiAsset((MultiAssetAllocationRequest) allocationRequest); + } + if (allocationRequest instanceof MultiResourceAllocationRequest) { + return allocateMultiResource((MultiResourceAllocationRequest) allocationRequest); + } + if (allocationRequest instanceof LimitAllocationRequest) { + return allocateLimit((LimitAllocationRequest) allocationRequest); + } + if (allocationRequest instanceof LabelAllocationRequest) { + return allocateLabel((LabelAllocationRequest) allocationRequest); + } + if (allocationRequest instanceof RangeAllocationRequest) { + return allocateRange((RangeAllocationRequest) allocationRequest); + } + return null; + } + + private MultiAssetAllocationOutcome allocateMultiAsset(MultiAssetAllocationRequest req) { + + return null; + } + + private MultiResourceAllocationOutcome allocateMultiResource(MultiResourceAllocationRequest req) { + MultiResourceAllocationOutcome out = new MultiResourceAllocationOutcome(); + out.request = req; + out.allocationOutcomeList = new ArrayList<>(); + out.status = AllocationStatus.Success; + + if (req.allocationRequestList != null) { + for (AllocationRequest req1 : req.allocationRequestList) { + AllocationOutcome out1 = allocate(req1); + out.allocationOutcomeList.add(out1); + if (out1.status != AllocationStatus.Success) { + out.status = AllocationStatus.Failure; + } + } + } + + return out; + } + + private LimitAllocationOutcome allocateLimit(LimitAllocationRequest req) { + LimitAllocationOutcome out = new LimitAllocationOutcome(); + out.request = req; + + Resource r = resourceDao.getResource(req.assetId, req.resourceName); + if (r == null) { + r = new LimitResource(); + r.resourceKey = new ResourceKey(); + r.resourceKey.assetId = req.assetId; + r.resourceKey.resourceName = req.resourceName; + r.resourceType = ResourceType.Limit; + } else { + if (r.resourceType != ResourceType.Limit) { + out.status = AllocationStatus.ResourceNotFound; + return out; + } + LimitUtil.recalculate((LimitResource) r); + } + + LimitResource l = (LimitResource) r; + if (LimitUtil.checkLimit(l, req)) { + out.status = AllocationStatus.Success; + if (req.allocateCount > 0) { + out.allocatedCount = LimitUtil.allocateLimit(l, req); + updateList.add(l); + } + } else { + out.status = AllocationStatus.Failure; + } + + out.used = l.used; + out.limit = req.checkLimit; + + return out; + } + + private LabelAllocationOutcome allocateLabel(LabelAllocationRequest req) { + LabelAllocationOutcome out = new LabelAllocationOutcome(); + + out.request = req; + + Resource r = resourceDao.getResource(req.assetId, req.resourceName); + if (r == null) { + r = new LabelResource(); + r.resourceKey = new ResourceKey(); + r.resourceKey.assetId = req.assetId; + r.resourceKey.resourceName = req.resourceName; + r.resourceType = ResourceType.Label; + } else { + if (r.resourceType != ResourceType.Label) { + out.status = AllocationStatus.ResourceNotFound; + return out; + } + LabelUtil.recalculate((LabelResource) r); + } + + LabelResource l = (LabelResource) r; + if (LabelUtil.checkLabel(l, req)) { + out.status = AllocationStatus.Success; + out.currentLabel = l.label; + if (req.allocate) { + out.allocatedLabel = LabelUtil.allocateLabel(l, req); + updateList.add(l); + } + } else { + out.status = AllocationStatus.Failure; + } + + return out; + } + + private RangeAllocationOutcome allocateRange(RangeAllocationRequest req) { + RangeAllocationOutcome out = new RangeAllocationOutcome(); + + out.request = req; + + Resource r = resourceDao.getResource(req.assetId, req.resourceName); + if (r == null) { + r = new RangeResource(); + r.resourceKey = new ResourceKey(); + r.resourceKey.assetId = req.assetId; + r.resourceKey.resourceName = req.resourceName; + r.resourceType = ResourceType.Range; + } else { + if (r.resourceType != ResourceType.Range) { + out.status = AllocationStatus.ResourceNotFound; + return out; + } + RangeUtil.recalculate((RangeResource) r); + } + + RangeResource rr = (RangeResource) r; + SortedSet<Integer> foundNumbers = null; + if (!req.check) { + out.status = AllocationStatus.Success; + foundNumbers = req.requestedNumbers; + } else { + if (req.requestedNumbers != null && !req.requestedNumbers.isEmpty()) { + foundNumbers = req.requestedNumbers; + out.status = AllocationStatus.Success; + for (int n : foundNumbers) { + if (!RangeUtil.checkRange(rr, req, n)) { + out.status = AllocationStatus.Failure; + break; + } + } + } else { + foundNumbers = new TreeSet<>(); + int foundCount = 0; + + // First try to reuse the numbers already taken by the same resource union + SortedSet<Integer> uu = RangeUtil.getUsed(rr, req.resourceUnionId); + if (uu != null && !uu.isEmpty() && req.replace && !req.forceNewNumbers) { + if (uu.size() >= req.requestedCount) { + // Just take the first req.requestedCount numbers from uu + Iterator<Integer> i = uu.iterator(); + while (foundCount < req.requestedCount) { + foundNumbers.add(i.next()); + foundCount++; + } + } else { + // Additional numbers are requested. Try to find them starting from + // the minimum we have in uu (the first element) towards the min + // parameter, and then starting from the maximum in uu (the last + // element) towards the max parameter. + // NOTE: In case of request for sequential numbers, the parameters + // alignBlockSize and alignModulus are ignored. It would be harder + // to take them into account, and currently it is not needed. + + // Request may contain multiple ranges. We will find the range from the request + // that contains the currently used numbers (the first one). We will only look + // for additional numbers in that range. + + Range range = null; + if (req.rangeList != null) { + for (Range range1 : req.rangeList) { + if (uu.first() >= range1.min && uu.first() <= range1.max) { + range = range1; + break; + } + } + } + + if (range != null) { + int uumin = uu.first() - 1; + int uumax = uu.last() + 1; + foundNumbers.addAll(uu); + foundCount = uu.size(); + for (int n = uumin; foundCount < req.requestedCount && n >= range.min; n--) { + if (RangeUtil.checkRange(rr, req, n)) { + foundNumbers.add(n); + foundCount++; + } else if (req.sequential) { + break; + } + } + for (int n = uumax; foundCount < req.requestedCount && n <= range.max; n++) { + if (RangeUtil.checkRange(rr, req, n)) { + foundNumbers.add(n); + foundCount++; + } else if (req.sequential) { + break; + } + } + } + + // If we could not find enough numbers trying to reuse currently + // allocated, reset foundNumbers and foundCount, continue with + // the normal allocation of new numbers. + if (foundCount < req.requestedCount) { + foundNumbers = new TreeSet<>(); + foundCount = 0; + } + } + } + + if (req.rangeList != null && !req.rangeList.isEmpty()) { + if (req.nextInSequence) { + // This means we allocate numbers in ascending sequence, not trying from the beginning + // of the range (leaving possible holes in the sequence of allocated numbers) + // To do that, we go through the ranges from the last towards the first (assuming + // ranges are ordered from smallest to the largest numbers), and within each range, from + // the max towards the min and find the first allocated number. Then we take the next numbers + // in the range (that we already checked are available). + + int rangeIndex; + Range range = null; + int n = 0; + boolean foundAllocated = false; + for (rangeIndex = req.rangeList.size() - 1; !foundAllocated && rangeIndex >= 0; rangeIndex--) { + range = req.rangeList.get(rangeIndex); + for (n = range.max; n >= range.min; n--) { + if (!RangeUtil.checkRange(rr, req, n)) { + foundAllocated = true; + break; + } + } + if (foundAllocated) { + break; + } + } + n++; + for (; foundCount < req.requestedCount && n <= range.max; n++) { + foundNumbers.add(n); + foundCount++; + } + if (foundCount < req.requestedCount) { + rangeIndex++; + for (; rangeIndex < req.rangeList.size(); rangeIndex++) { + range = req.rangeList.get(rangeIndex); + for (n = range.min; foundCount < req.requestedCount && n <= range.max; n++) { + foundNumbers.add(n); + foundCount++; + } + } + } + // If we could not find enough numbers by going up in sequence, + // reset foundNumbers and foundCount, and go back to the holes + if (foundCount < req.requestedCount) { + foundNumbers = new TreeSet<>(); + foundCount = 0; + } + } + + if (req.reverseOrder) { + for (int i = req.rangeList.size() - 1; i >= 0; i--) { + Range range = req.rangeList.get(i); + for (int n = range.max; foundCount < req.requestedCount && n >= range.min; n--) { + if (RangeUtil.checkRange(rr, req, n)) { + foundNumbers.add(n); + foundCount++; + } else if (req.sequential) { + foundCount = 0; + } + } + } + } else { + for (Range range : req.rangeList) { + for (int n = range.min; foundCount < req.requestedCount && n <= range.max; n++) { + if (RangeUtil.checkRange(rr, req, n)) { + foundNumbers.add(n); + foundCount++; + } else if (req.sequential) { + foundCount = 0; + } + } + } + } + } + + out.status = foundCount == req.requestedCount ? AllocationStatus.Success : AllocationStatus.Failure; + } + } + + if (out.status == AllocationStatus.Success) { + out.allocated = foundNumbers; + if (req.allocate) { + RangeUtil.allocateRange(rr, out.allocated, req); + updateList.add(rr); + } + } else { + out.allocated = new TreeSet<>(); + } + + out.used = rr.used; + + return out; + } + + public AllocationOutcome getAllocationOutcome() { + return outcome; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ReleaseFunction.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ReleaseFunction.java new file mode 100644 index 000000000..b466b164b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ReleaseFunction.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.comp; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.lock.comp.LockHelper; +import org.onap.ccsdk.sli.adaptors.lock.comp.ResourceLockedException; +import org.onap.ccsdk.sli.adaptors.lock.comp.SynchronizedFunction; +import org.onap.ccsdk.sli.adaptors.rm.dao.ResourceDao; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.ReleaseRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; +import org.onap.ccsdk.sli.adaptors.rm.util.ResourceUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class ReleaseFunction extends SynchronizedFunction { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ReleaseFunction.class); + + private ResourceDao resourceDao; + + private ReleaseRequest releaseRequest; + + public ReleaseFunction(LockHelper lockHelper, ResourceDao resourceDao, ReleaseRequest releaseRequest, + Collection<String> lockNames, int lockTimeout) { + super(lockHelper, lockNames, lockTimeout); + this.resourceDao = resourceDao; + this.releaseRequest = releaseRequest; + } + + @Override + public void _exec() throws ResourceLockedException { + List<Resource> resourceList = new ArrayList<>(); + if (releaseRequest.assetId != null && releaseRequest.resourceName != null) { + Resource r = resourceDao.getResource(releaseRequest.assetId, releaseRequest.resourceName); + if (r != null) { + resourceList.add(r); + } + } else if (releaseRequest.assetId != null) { + if (releaseRequest.resourceSetId != null) { + resourceList = resourceDao.getResourceSetForAsset(releaseRequest.resourceSetId, releaseRequest.assetId); + } else { + resourceList = + resourceDao.getResourceUnionForAsset(releaseRequest.resourceUnionId, releaseRequest.assetId); + } + } else { + if (releaseRequest.resourceSetId != null) { + resourceList = resourceDao.getResourceSet(releaseRequest.resourceSetId); + } else { + resourceList = resourceDao.getResourceUnion(releaseRequest.resourceUnionId); + } + } + + for (Resource r : resourceList) { + boolean updated = false; + if (r.allocationItems != null) { + Iterator<AllocationItem> i = r.allocationItems.iterator(); + while (i.hasNext()) { + AllocationItem ai = i.next(); + if (releaseRequest.resourceSetId != null) { + + if (releaseRequest.resourceSetId.equals(ai.resourceSetId)) { + if (r.resourceType == ResourceType.Limit) { + LimitAllocationItem lai = (LimitAllocationItem) ai; + if (releaseRequest.releaseAmount > 0 && releaseRequest.releaseAmount < lai.used) { + lai.used -= releaseRequest.releaseAmount; + } else { + i.remove(); + } + } else if (r.resourceType == ResourceType.Range) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + if (releaseRequest.releaseNumbers != null && !releaseRequest.releaseNumbers.isEmpty()) { + rai.used.removeAll(releaseRequest.releaseNumbers); + if (rai.used.isEmpty()) { + i.remove(); + } + } else { + i.remove(); + } + } else { + i.remove(); + } + updated = true; + } + + } else if (releaseRequest.resourceUnionId != null) { + + if (releaseRequest.resourceUnionId.equals(ai.resourceUnionId)) { + if (r.resourceType == ResourceType.Limit) { + LimitAllocationItem lai = (LimitAllocationItem) ai; + if (releaseRequest.releaseAmount > 0 && releaseRequest.releaseAmount < lai.used) { + lai.used -= releaseRequest.releaseAmount; + } else { + i.remove(); + } + } else if (r.resourceType == ResourceType.Range) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + if (releaseRequest.releaseNumbers != null && !releaseRequest.releaseNumbers.isEmpty()) { + rai.used.removeAll(releaseRequest.releaseNumbers); + if (rai.used.isEmpty()) { + i.remove(); + } + } else { + i.remove(); + } + } else { + i.remove(); + } + updated = true; + } + + } + } + } + if (updated) { + ResourceUtil.recalculate(r); + resourceDao.saveResource(r); + } + } + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceLoader.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceLoader.java new file mode 100644 index 000000000..2d4df68b5 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceLoader.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.comp; + +import java.util.Collection; + +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; + +public interface ResourceLoader { + + void loadResource(String applicationId, Resource resource, boolean force); + + void loadResources(String applicationId, Collection<Resource> resourceList, boolean force); + + void loadResourcesForAsset(String applicationId, String assetId, Collection<Resource> resourceList, boolean force); + + void deleteResource(String applicationId, String assetId, String resourceName); + + void deleteResourcesForAsset(String applicationId, String assetId); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManager.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManager.java new file mode 100644 index 000000000..9dd54cc39 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManager.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.comp; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.ReleaseRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; + +public interface ResourceManager { + + Resource getResource(String resourceName, String assetId); + + List<Resource> getResourceUnion(String resourceUnionId); + + AllocationOutcome allocateResources(AllocationRequest allocationRequest); + + void releaseResources(ReleaseRequest releaseRequest); + + Resource queryResource(String resourceName, String assetId, String resourceUnionFilter, + String resourceShareGroupFilter); + + List<Resource> queryResources(String resourceName, String assetIdFilter); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManagerImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManagerImpl.java new file mode 100644 index 000000000..83da27071 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/comp/ResourceManagerImpl.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.comp; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.onap.ccsdk.sli.adaptors.lock.comp.LockHelper; +import org.onap.ccsdk.sli.adaptors.rm.dao.ResourceDao; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationOutcome; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.ReleaseRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; +import org.onap.ccsdk.sli.adaptors.rm.util.ResourceUtil; +import org.onap.ccsdk.sli.adaptors.util.str.StrUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResourceManagerImpl implements ResourceManager { + + private static final Logger log = LoggerFactory.getLogger(ResourceManagerImpl.class); + + private LockHelper lockHelper; + private ResourceDao resourceDao; + + private int lockTimeout = 10 * 60; // Default 10 min + + public ResourceManagerImpl() { + log.info("ResourceManager created."); + } + + @Override + public Resource getResource(String resourceName, String assetId) { + Resource r = resourceDao.getResource(assetId, resourceName); + ResourceUtil.recalculate(r); + return r; + } + + @Override + public List<Resource> getResourceUnion(String resourceUnionId) { + List<Resource> rlist = resourceDao.getResourceUnion(resourceUnionId); + for (Resource r : rlist) { + ResourceUtil.recalculate(r); + } + return rlist; + } + + @Override + public AllocationOutcome allocateResources(AllocationRequest allocationRequest) { + if (allocationRequest == null) { + throw new IllegalArgumentException("allocateResources called with null argument"); + } + + AllocationFunction allocationFunction = + new AllocationFunction(lockHelper, resourceDao, allocationRequest, lockTimeout); + allocationFunction.exec(); + AllocationOutcome allocationOutcome = allocationFunction.getAllocationOutcome(); + + StrUtil.info(log, allocationOutcome); + + return allocationOutcome; + } + + @Override + public void releaseResources(ReleaseRequest releaseRequest) { + if (releaseRequest.resourceSetId == null && releaseRequest.resourceUnionId == null) { + return; + } + + Set<String> lockNames = new HashSet<>(); + if (releaseRequest.assetId != null) { + lockNames.add(releaseRequest.assetId); + } else { + List<Resource> resourceList = null; + if (releaseRequest.resourceSetId != null) { + resourceList = resourceDao.getResourceSet(releaseRequest.resourceSetId); + } else { + resourceList = resourceDao.getResourceUnion(releaseRequest.resourceUnionId); + } + + if (resourceList == null || resourceList.isEmpty()) { + return; + } + + lockNames = getLockNames(resourceList); + } + + ReleaseFunction releaseFunction = + new ReleaseFunction(lockHelper, resourceDao, releaseRequest, lockNames, lockTimeout); + releaseFunction.exec(); + } + + @Override + public Resource queryResource(String resourceName, String assetId, String resourceUnionFilter, + String resourceShareGroupFilter) { + Resource r = resourceDao.query(assetId, resourceName, resourceUnionFilter, resourceShareGroupFilter); + ResourceUtil.recalculate(r); + return r; + } + + @Override + public List<Resource> queryResources(String resourceName, String assetIdFilter) { + List<Resource> rlist = resourceDao.query(assetIdFilter, resourceName); + for (Resource r : rlist) { + ResourceUtil.recalculate(r); + } + return rlist; + } + + private Set<String> getLockNames(List<Resource> resourceList) { + Set<String> lockNames = new HashSet<>(); + for (Resource r : resourceList) { + lockNames.add(r.resourceKey.assetId); + } + return lockNames; + } + + public void setResourceDao(ResourceDao resourceDao) { + this.resourceDao = resourceDao; + } + + public void setLockTimeout(int lockTimeout) { + this.lockTimeout = lockTimeout; + } + + public void setLockHelper(LockHelper lockHelper) { + this.lockHelper = lockHelper; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/ResourceDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/ResourceDao.java new file mode 100644 index 000000000..87baf26c1 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/ResourceDao.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao; + +import java.util.List; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; + +public interface ResourceDao { + + Resource getResource(String assetId, String resourceName); + + void saveResource(Resource resource); + + void deleteResource(String assetId, String resourceName); + + List<Resource> getResourceSet(String resourceSetId); + + List<Resource> getResourceUnion(String resourceUnionId); + + List<Resource> getResourceSetForAsset(String resourceSetId, String assetId); + + List<Resource> getResourceUnionForAsset(String resourceUnionId, String assetId); + + Resource query(String assetId, String resourceName, String resourceUnionFilter, String resourceShareGroupFilter); + + List<Resource> query(String assetIdFilter, String resourceName); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItem.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItem.java new file mode 100644 index 000000000..25d8bf97e --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItem.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.Date; + +public class AllocationItem { + + public long id; + public long resourceId; + public String applicationId; + public String resourceSetId, resourceUnionId; + public String resourceShareGroupList; + public long ltUsed; + public String llLabel; + public String rrUsed; + public Date allocationTime; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDao.java new file mode 100644 index 000000000..8e3a12988 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDao.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.List; + +public interface AllocationItemJdbcDao { + + void add(AllocationItem ai); + + List<AllocationItem> getAllocationItems(long resourceId); + + void update(AllocationItem ai); + + void delete(long id); + + List<AllocationItem> queryAllocationItems(long resourceId, String resourceUnionFilter, String resourceShareGroupFilter); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDaoImpl.java new file mode 100644 index 000000000..2a62c63a3 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/AllocationItemJdbcDaoImpl.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Collections; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; + +public class AllocationItemJdbcDaoImpl implements AllocationItemJdbcDao { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ResourceJdbcDaoImpl.class); + + private static final String INSERT_SQL = "INSERT INTO ALLOCATION_ITEM (\n" + + " resource_id, application_id, resource_set_id, resource_union_id, resource_share_group_list,\n" + + " lt_used, ll_label, rr_used, allocation_time)\nVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + + private static final String UPDATE_SQL = "UPDATE ALLOCATION_ITEM SET\n" + + " resource_share_group_list = ?, lt_used = ?, ll_label = ?, rr_used = ?, allocation_time = ?\n" + + "WHERE allocation_item_id = ?"; + + private static final String DELETE_SQL = "DELETE FROM ALLOCATION_ITEM WHERE allocation_item_id = ?"; + + private static final String GET_SQL = "SELECT * FROM ALLOCATION_ITEM WHERE resource_id = ?"; + + private JdbcTemplate jdbcTemplate; + private AllocationItemRowMapper allocationItemRowMapper = new AllocationItemRowMapper(); + + @Override + public void add(final AllocationItem ai) { + PreparedStatementCreator psc = dbc -> { + PreparedStatement ps = dbc.prepareStatement(INSERT_SQL, new String[] { "allocation_item_id" }); + ps.setLong(1, ai.resourceId); + ps.setString(2, ai.applicationId); + ps.setString(3, ai.resourceSetId); + ps.setString(4, ai.resourceUnionId); + ps.setString(5, ai.resourceShareGroupList); + ps.setLong(6, ai.ltUsed); + ps.setString(7, ai.llLabel); + ps.setString(8, ai.rrUsed); + ps.setTimestamp(9, new Timestamp(ai.allocationTime.getTime())); + return ps; + }; + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(psc, keyHolder); + ai.id = keyHolder.getKey().longValue(); + } + + @Override + public void update(AllocationItem ai) { + Long ltUsed = ai.ltUsed <= 0 ? null : ai.ltUsed; + jdbcTemplate.update(UPDATE_SQL, ai.resourceShareGroupList, ltUsed, ai.llLabel, ai.rrUsed, ai.allocationTime, + ai.id); + } + + @Override + public void delete(long id) { + jdbcTemplate.update(DELETE_SQL, id); + } + + @Override + public List<AllocationItem> getAllocationItems(long resourceId) { + if (resourceId <= 0) { + return Collections.emptyList(); + } + + return jdbcTemplate.query(GET_SQL, new Object[] { resourceId }, allocationItemRowMapper); + } + + @Override + public List<AllocationItem> queryAllocationItems(long resourceId, String resourceUnionFilter, + String resourceShareGroupFilter) { + if (resourceId <= 0) { + return Collections.emptyList(); + } + + String sql = GET_SQL; + + if (resourceUnionFilter != null) { + sql += " AND resource_union_id LIKE '" + resourceUnionFilter + "'"; + } + + if (resourceShareGroupFilter != null) { + if (("null").equalsIgnoreCase(resourceShareGroupFilter)) { + sql += " AND resource_share_group_list IS NULL"; + } else { + sql += " AND resource_share_group_list LIKE '" + resourceShareGroupFilter + "'"; + } + } + + return jdbcTemplate.query(sql, new Object[] { resourceId }, allocationItemRowMapper); + } + + private static class AllocationItemRowMapper implements RowMapper<AllocationItem> { + + @Override + public AllocationItem mapRow(ResultSet rs, int n) throws SQLException { + AllocationItem ai = new AllocationItem(); + ai.id = rs.getLong("allocation_item_id"); + ai.resourceId = rs.getLong("resource_id"); + ai.applicationId = rs.getString("application_id"); + ai.resourceSetId = rs.getString("resource_set_id"); + ai.resourceUnionId = rs.getString("resource_union_id"); + ai.resourceShareGroupList = rs.getString("resource_share_group_list"); + ai.ltUsed = rs.getLong("lt_used"); + ai.llLabel = rs.getString("ll_label"); + ai.rrUsed = rs.getString("rr_used"); + ai.allocationTime = rs.getTimestamp("allocation_time"); + return ai; + } + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/Resource.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/Resource.java new file mode 100644 index 000000000..6b764a7e1 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/Resource.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +public class Resource { + + public long id; + public String assetId; + public String name; + public String type; + public long ltUsed; + public String llLabel; + public int llReferenceCount; + public String rrUsed; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceDaoImpl.java new file mode 100644 index 000000000..21f5575fc --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceDaoImpl.java @@ -0,0 +1,462 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import org.onap.ccsdk.sli.adaptors.rm.dao.ResourceDao; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelResource; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitResource; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeResource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceKey; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; +import org.onap.ccsdk.sli.adaptors.util.str.StrUtil; + +public class ResourceDaoImpl implements ResourceDao { + + private ResourceJdbcDao resourceJdbcDao; + private ResourceLoadJdbcDao resourceLoadJdbcDao; + private AllocationItemJdbcDao allocationItemJdbcDao; + + @Override + public org.onap.ccsdk.sli.adaptors.rm.data.Resource getResource(String assetId, String resourceName) { + Resource rEntity = resourceJdbcDao.getResource(assetId, resourceName); + return createResourceWithItems(rEntity); + } + + @Override + public org.onap.ccsdk.sli.adaptors.rm.data.Resource query(String assetId, String resourceName, + String resourceUnionFilter, String resourceShareGroupFilter) { + Resource rEntity = resourceJdbcDao.getResource(assetId, resourceName); + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResource(rEntity); + + if (r != null) { + List<AllocationItem> aiEntityList = allocationItemJdbcDao.queryAllocationItems(rEntity.id, + resourceUnionFilter, resourceShareGroupFilter); + r.allocationItems = new ArrayList<>(); + for (AllocationItem aiEntity : aiEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai = createAllocationItem(r, aiEntity); + r.allocationItems.add(ai); + } + + List<ResourceLoad> rlEntityList = resourceLoadJdbcDao.getResourceLoads(rEntity.id); + r.resourceLoadList = new ArrayList<>(); + for (ResourceLoad rlEntity : rlEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl = createResourceLoad(r, rlEntity); + r.resourceLoadList.add(rl); + } + } + + return r; + } + + @Override + public List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> query(String assetIdFilter, String resourceName) { + List<Resource> rEntityList = resourceJdbcDao.queryResources(assetIdFilter, resourceName); + List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> rlist = new ArrayList<>(); + for (Resource rEntity : rEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResourceWithItems(rEntity); + rlist.add(r); + } + return rlist; + } + + @Override + public void saveResource(org.onap.ccsdk.sli.adaptors.rm.data.Resource resource) { + if (resource == null) { + return; + } + + org.onap.ccsdk.sli.adaptors.rm.dao.jdbc.Resource resourceEntity = + resourceJdbcDao.getResource(resource.resourceKey.assetId, resource.resourceKey.resourceName); + if (resourceEntity == null) { + resourceEntity = createResourceEntity(resource); + resourceJdbcDao.add(resourceEntity); + if (resource.allocationItems != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai : resource.allocationItems) { + AllocationItem aiEntity = createAllocationItemEntity(resourceEntity.id, ai); + allocationItemJdbcDao.add(aiEntity); + } + } + if (resource.resourceLoadList != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl : resource.resourceLoadList) { + ResourceLoad rlEntity = createResourceLoadEntity(resourceEntity.id, rl); + resourceLoadJdbcDao.add(rlEntity); + } + } + } else { + updateResourceEntity(resourceEntity, resource); + resourceJdbcDao.update(resourceEntity); + + List<AllocationItem> oldAiEntityList = allocationItemJdbcDao.getAllocationItems(resourceEntity.id); + if (resource.allocationItems != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem newai : resource.allocationItems) { + AllocationItem foundAiEntity = null; + for (AllocationItem oldAiEntity : oldAiEntityList) { + if (oldAiEntity.resourceSetId.equals(newai.resourceSetId)) { + foundAiEntity = oldAiEntity; + break; + } + } + if (foundAiEntity != null) { + if (allocationItemChanged(foundAiEntity, newai)) { + updateAllocationItemEntity(foundAiEntity, newai); + allocationItemJdbcDao.update(foundAiEntity); + } + } else { + AllocationItem newAiEntity = createAllocationItemEntity(resourceEntity.id, newai); + allocationItemJdbcDao.add(newAiEntity); + } + } + } + for (AllocationItem oldAiEntity : oldAiEntityList) { + boolean found = false; + if (resource.allocationItems != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem newai : resource.allocationItems) { + if (oldAiEntity.resourceSetId.equals(newai.resourceSetId)) { + found = true; + break; + } + } + } + if (!found) { + allocationItemJdbcDao.delete(oldAiEntity.id); + } + } + + List<ResourceLoad> oldRlEntityList = resourceLoadJdbcDao.getResourceLoads(resourceEntity.id); + if (resource.resourceLoadList != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad newrl : resource.resourceLoadList) { + ResourceLoad foundRlEntity = null; + for (ResourceLoad oldRlEntity : oldRlEntityList) { + if (oldRlEntity.applicationId.equals(newrl.applicationId)) { + foundRlEntity = oldRlEntity; + break; + } + } + if (foundRlEntity != null) { + updateResourceLoadEntity(foundRlEntity, newrl); + resourceLoadJdbcDao.update(foundRlEntity); + } else { + ResourceLoad newRlEntity = createResourceLoadEntity(resourceEntity.id, newrl); + resourceLoadJdbcDao.add(newRlEntity); + } + } + } + for (ResourceLoad oldRlEntity : oldRlEntityList) { + boolean found = false; + if (resource.resourceLoadList != null) { + for (org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad newrl : resource.resourceLoadList) { + if (oldRlEntity.applicationId.equals(newrl.applicationId)) { + found = true; + break; + } + } + } + if (!found) { + resourceLoadJdbcDao.delete(oldRlEntity.id); + } + } + } + } + + private boolean allocationItemChanged(AllocationItem aiEntity, + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem newai) { + String newShareGroupList = StrUtil.listStr(newai.resourceShareGroupList); + if (!eq(aiEntity.resourceShareGroupList, newShareGroupList)) { + return true; + } + + if (newai.resourceType == ResourceType.Limit) { + if (aiEntity.ltUsed != ((LimitAllocationItem) newai).used) { + return true; + } + } else if (newai.resourceType == ResourceType.Label) { + if (!eq(aiEntity.llLabel, ((LabelAllocationItem) newai).label)) { + return true; + } + } else if (newai.resourceType == ResourceType.Range) { + String newRrUsed = StrUtil.listInt(((RangeAllocationItem) newai).used); + if (!eq(aiEntity.rrUsed, newRrUsed)) { + return true; + } + } + + return false; + } + + @Override + public void deleteResource(String assetId, String resourceName) { + org.onap.ccsdk.sli.adaptors.rm.dao.jdbc.Resource resourceEntity = + resourceJdbcDao.getResource(assetId, resourceName); + if (resourceEntity != null) { + resourceJdbcDao.delete(resourceEntity.id); + } + } + + @Override + public List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> getResourceSet(String resourceSetId) { + List<Resource> rEntityList = resourceJdbcDao.getResourceSet(resourceSetId); + List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> rlist = new ArrayList<>(); + for (Resource rEntity : rEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResourceWithItems(rEntity); + rlist.add(r); + } + return rlist; + } + + @Override + public List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> getResourceUnion(String resourceUnionId) { + List<Resource> rEntityList = resourceJdbcDao.getResourceUnion(resourceUnionId); + List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> rlist = new ArrayList<>(); + for (Resource rEntity : rEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResourceWithItems(rEntity); + rlist.add(r); + } + return rlist; + } + + @Override + public List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> getResourceSetForAsset(String resourceSetId, + String assetId) { + List<Resource> rEntityList = resourceJdbcDao.getResourceSetForAsset(resourceSetId, assetId); + List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> rlist = new ArrayList<>(); + for (Resource rEntity : rEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResourceWithItems(rEntity); + rlist.add(r); + } + return rlist; + } + + @Override + public List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> getResourceUnionForAsset(String resourceUnionId, + String assetId) { + List<Resource> rEntityList = resourceJdbcDao.getResourceUnionForAsset(resourceUnionId, assetId); + List<org.onap.ccsdk.sli.adaptors.rm.data.Resource> rlist = new ArrayList<>(); + for (Resource rEntity : rEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResourceWithItems(rEntity); + rlist.add(r); + } + return rlist; + } + + private Resource createResourceEntity(org.onap.ccsdk.sli.adaptors.rm.data.Resource resource) { + Resource resourceEntity = new Resource(); + resourceEntity.assetId = resource.resourceKey.assetId; + resourceEntity.name = resource.resourceKey.resourceName; + resourceEntity.type = resource.resourceType.toString(); + if (resource.resourceType == ResourceType.Limit) { + resourceEntity.ltUsed = ((LimitResource) resource).used; + } else if (resource.resourceType == ResourceType.Label) { + resourceEntity.llLabel = ((LabelResource) resource).label; + resourceEntity.llReferenceCount = ((LabelResource) resource).referenceCount; + } else if (resource.resourceType == ResourceType.Range) { + resourceEntity.rrUsed = StrUtil.listInt(((RangeResource) resource).used); + } + + return resourceEntity; + } + + private ResourceLoad createResourceLoadEntity(long resourceId, + org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl) { + ResourceLoad rlEntity = new ResourceLoad(); + rlEntity.resourceId = resourceId; + rlEntity.applicationId = rl.applicationId; + rlEntity.loadTime = rl.resourceLoadTime; + rlEntity.expirationTime = rl.resourceExpirationTime; + return rlEntity; + } + + private void updateResourceLoadEntity(ResourceLoad rlEntity, org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl) { + rlEntity.loadTime = rl.resourceLoadTime; + rlEntity.expirationTime = rl.resourceExpirationTime; + } + + private AllocationItem createAllocationItemEntity(long resourceId, + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai) { + AllocationItem aiEntity = new AllocationItem(); + aiEntity.resourceId = resourceId; + aiEntity.resourceSetId = ai.resourceSetId; + aiEntity.resourceUnionId = ai.resourceUnionId; + aiEntity.resourceShareGroupList = StrUtil.listStr(ai.resourceShareGroupList); + aiEntity.applicationId = ai.applicationId; + aiEntity.allocationTime = ai.allocationTime; + if (ai.resourceType == ResourceType.Limit) { + aiEntity.ltUsed = ((LimitAllocationItem) ai).used; + } else if (ai.resourceType == ResourceType.Label) { + aiEntity.llLabel = ((LabelAllocationItem) ai).label; + } else if (ai.resourceType == ResourceType.Range) { + aiEntity.rrUsed = StrUtil.listInt(((RangeAllocationItem) ai).used); + } + return aiEntity; + } + + private void updateAllocationItemEntity(AllocationItem aiEntity, + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai) { + aiEntity.resourceShareGroupList = StrUtil.listStr(ai.resourceShareGroupList); + aiEntity.allocationTime = ai.allocationTime; + if (ai.resourceType == ResourceType.Limit) { + aiEntity.ltUsed = ((LimitAllocationItem) ai).used; + } else if (ai.resourceType == ResourceType.Label) { + aiEntity.llLabel = ((LabelAllocationItem) ai).label; + } else if (ai.resourceType == ResourceType.Range) { + aiEntity.rrUsed = StrUtil.listInt(((RangeAllocationItem) ai).used); + } + } + + private void updateResourceEntity(Resource resourceEntity, org.onap.ccsdk.sli.adaptors.rm.data.Resource resource) { + if (resource.resourceType == ResourceType.Limit) { + resourceEntity.ltUsed = ((LimitResource) resource).used; + } else if (resource.resourceType == ResourceType.Label) { + resourceEntity.llLabel = ((LabelResource) resource).label; + resourceEntity.llReferenceCount = ((LabelResource) resource).referenceCount; + } else if (resource.resourceType == ResourceType.Range) { + resourceEntity.rrUsed = StrUtil.listInt(((RangeResource) resource).used); + } + } + + private org.onap.ccsdk.sli.adaptors.rm.data.Resource createResourceWithItems(Resource rEntity) { + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = createResource(rEntity); + + if (r != null) { + List<AllocationItem> aiEntityList = allocationItemJdbcDao.getAllocationItems(rEntity.id); + r.allocationItems = new ArrayList<>(); + for (AllocationItem aiEntity : aiEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai = createAllocationItem(r, aiEntity); + r.allocationItems.add(ai); + } + + List<ResourceLoad> rlEntityList = resourceLoadJdbcDao.getResourceLoads(rEntity.id); + r.resourceLoadList = new ArrayList<>(); + for (ResourceLoad rlEntity : rlEntityList) { + org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl = createResourceLoad(r, rlEntity); + r.resourceLoadList.add(rl); + } + } + return r; + } + + private org.onap.ccsdk.sli.adaptors.rm.data.Resource createResource(Resource resourceEntity) { + if (resourceEntity == null) { + return null; + } + + org.onap.ccsdk.sli.adaptors.rm.data.Resource r = null; + ResourceType type = ResourceType.valueOf(resourceEntity.type); + if (type == ResourceType.Limit) { + LimitResource l = new LimitResource(); + l.used = resourceEntity.ltUsed; + r = l; + } else if (type == ResourceType.Label) { + LabelResource l = new LabelResource(); + l.label = resourceEntity.llLabel; + l.referenceCount = resourceEntity.llReferenceCount; + r = l; + } else if (type == ResourceType.Range) { + RangeResource rr = new RangeResource(); + rr.used = StrUtil.listInt(resourceEntity.rrUsed, "Invalid data found in DB in for Resource Id: " + + resourceEntity.id + ": RESOURCE.RR_USED: " + resourceEntity.rrUsed); + r = rr; + } + + if (r != null) { + r.resourceType = type; + r.resourceKey = new ResourceKey(); + r.resourceKey.assetId = resourceEntity.assetId; + r.resourceKey.resourceName = resourceEntity.name; + } + + return r; + } + + private org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem createAllocationItem( + org.onap.ccsdk.sli.adaptors.rm.data.Resource r, AllocationItem aiEntity) { + if (r == null || aiEntity == null) { + return null; + } + + org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem ai = null; + if (r.resourceType == ResourceType.Limit) { + LimitAllocationItem lai = new LimitAllocationItem(); + lai.used = aiEntity.ltUsed; + ai = lai; + } else if (r.resourceType == ResourceType.Label) { + LabelAllocationItem lai = new LabelAllocationItem(); + lai.label = aiEntity.llLabel; + ai = lai; + } else if (r.resourceType == ResourceType.Range) { + RangeAllocationItem rai = new RangeAllocationItem(); + rai.used = StrUtil.listInt(aiEntity.rrUsed, "Invalid data found in DB in for Allocation Item Id: " + + aiEntity.id + ": ALLOCATION_ITEM.RR_USED: " + aiEntity.rrUsed); + ai = rai; + } + + if (ai != null) { + ai.resourceType = r.resourceType; + ai.resourceKey = r.resourceKey; + ai.resourceSetId = aiEntity.resourceSetId; + ai.resourceUnionId = aiEntity.resourceUnionId; + if (aiEntity.resourceShareGroupList != null) { + ai.resourceShareGroupList = new HashSet<>(StrUtil.listStr(aiEntity.resourceShareGroupList)); + } + ai.applicationId = aiEntity.applicationId; + ai.allocationTime = aiEntity.allocationTime; + } + + return ai; + } + + private org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad createResourceLoad( + org.onap.ccsdk.sli.adaptors.rm.data.Resource r, ResourceLoad rlEntity) { + if (rlEntity == null) { + return null; + } + + org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad rl = new org.onap.ccsdk.sli.adaptors.rm.data.ResourceLoad(); + rl.resourceKey = r.resourceKey; + rl.applicationId = rlEntity.applicationId; + rl.resourceLoadTime = rlEntity.loadTime; + rl.resourceExpirationTime = rlEntity.expirationTime; + + return rl; + } + + private static boolean eq(Object o1, Object o2) { + return o1 == null ? o2 == null : o1.equals(o2); + } + + public void setResourceJdbcDao(ResourceJdbcDao resourceJdbcDao) { + this.resourceJdbcDao = resourceJdbcDao; + } + + public void setResourceLoadJdbcDao(ResourceLoadJdbcDao resourceLoadJdbcDao) { + this.resourceLoadJdbcDao = resourceLoadJdbcDao; + } + + public void setAllocationItemJdbcDao(AllocationItemJdbcDao allocationItemJdbcDao) { + this.allocationItemJdbcDao = allocationItemJdbcDao; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDao.java new file mode 100644 index 000000000..d4d9a0543 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDao.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.List; + +public interface ResourceJdbcDao { + + Resource getResource(String assetId, String resourceName); + + List<Resource> queryResources(String assetIdFilter, String resourceName); + + List<Resource> getResourceSet(String resourceSetId); + + List<Resource> getResourceUnion(String resourceUnionId); + + List<Resource> getResourceSetForAsset(String resourceSetId, String assetId); + + List<Resource> getResourceUnionForAsset(String resourceUnionId, String assetId); + + void add(Resource r); + + void delete(long id); + + void update(Resource r); +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDaoImpl.java new file mode 100644 index 000000000..f9de42802 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceJdbcDaoImpl.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * Modifications Copyright (C) 2018 IBM. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Collections; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; + +public class ResourceJdbcDaoImpl implements ResourceJdbcDao { + + private static final String baseSelectResourceQuery = "SELECT * FROM RESOURCE WHERE resource_id IN (\n"; + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ResourceJdbcDaoImpl.class); + + private static final String RESOURCE_SQL = "SELECT * FROM RESOURCE WHERE asset_id = ? AND resource_name = ?"; + + private static final String RESOURCE_QUERY_1_SQL = + "SELECT * FROM RESOURCE WHERE asset_id LIKE ? AND resource_name = ?"; + + private static final String RESOURCE_SET_SQL = baseSelectResourceQuery + + "SELECT DISTINCT resource_id FROM ALLOCATION_ITEM WHERE resource_set_id = ?)"; + + private static final String RESOURCE_UNION_SQL = baseSelectResourceQuery + + "SELECT DISTINCT resource_id FROM ALLOCATION_ITEM WHERE resource_union_id = ?)"; + + private static final String RESOURCE_SET_FOR_ASSET_SQL = baseSelectResourceQuery + + "SELECT DISTINCT resource_id FROM ALLOCATION_ITEM WHERE resource_set_id = ?) AND asset_id = ?"; + + private static final String RESOURCE_UNION_FOR_ASSET_SQL = baseSelectResourceQuery + + "SELECT DISTINCT resource_id FROM ALLOCATION_ITEM WHERE resource_union_id = ?) AND asset_id = ?"; + + private static final String INSERT_SQL = "INSERT INTO RESOURCE (\n" + + " asset_id, resource_name, resource_type, lt_used, ll_label, ll_reference_count, rr_used)\n" + + "VALUES (?, ?, ?, ?, ?, ?, ?)"; + + private static final String UPDATE_SQL = "UPDATE RESOURCE SET\n" + + " lt_used = ?, ll_label = ?, ll_reference_count = ?, rr_used = ?\nWHERE resource_id = ?"; + + private static final String DELETE_SQL = "DELETE FROM RESOURCE WHERE resource_id = ?"; + + private JdbcTemplate jdbcTemplate; + private ResourceRowMapper resourceRowMapper = new ResourceRowMapper(); + + @Override + public Resource getResource(String assetId, String resourceName) { + if (assetId == null || assetId.trim().length() == 0 || resourceName == null + || resourceName.trim().length() == 0) { + return null; + } + + List<Resource> ll = jdbcTemplate.query(RESOURCE_SQL, new Object[] {assetId, resourceName}, resourceRowMapper); + return ll.isEmpty() ? null : ll.get(0); + } + + @Override + public List<Resource> queryResources(String assetIdFilter, String resourceName) { + if (assetIdFilter == null || assetIdFilter.trim().length() == 0 || resourceName == null + || resourceName.trim().length() == 0) { + return Collections.emptyList(); + } + + + return jdbcTemplate.query(RESOURCE_QUERY_1_SQL, new Object[] {assetIdFilter, resourceName}, resourceRowMapper); + } + + @Override + public List<Resource> getResourceSet(String resourceSetId) { + if (resourceSetId == null) { + return Collections.emptyList(); + } + + return jdbcTemplate.query(RESOURCE_SET_SQL, new Object[] {resourceSetId}, resourceRowMapper); + } + + @Override + public List<Resource> getResourceUnion(String resourceUnionId) { + if (resourceUnionId == null) { + return Collections.emptyList(); + } + + return jdbcTemplate.query(RESOURCE_UNION_SQL, new Object[] {resourceUnionId}, resourceRowMapper); + } + + @Override + public List<Resource> getResourceSetForAsset(String resourceSetId, String assetId) { + if (resourceSetId == null) { + return Collections.emptyList(); + } + + return jdbcTemplate.query(RESOURCE_SET_FOR_ASSET_SQL, new Object[] {resourceSetId, assetId}, resourceRowMapper); + } + + @Override + public List<Resource> getResourceUnionForAsset(String resourceUnionId, String assetId) { + if (resourceUnionId == null) { + return Collections.emptyList(); + } + + return jdbcTemplate.query(RESOURCE_UNION_FOR_ASSET_SQL, new Object[] {resourceUnionId, assetId}, + resourceRowMapper); + } + + @Override + public void add(final Resource r) { + PreparedStatementCreator psc = dbc -> { + PreparedStatement ps = dbc.prepareStatement(INSERT_SQL, new String[] {"resource_id"}); + ps.setString(1, r.assetId); + ps.setString(2, r.name); + ps.setString(3, r.type); + ps.setLong(4, r.ltUsed); + ps.setString(5, r.llLabel); + ps.setInt(6, r.llReferenceCount); + ps.setString(7, r.rrUsed); + return ps; + }; + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(psc, keyHolder); + r.id = keyHolder.getKey().longValue(); + } + + @Override + public void update(Resource r) { + Long ltUsed = r.ltUsed <= 0 ? null : r.ltUsed; + Integer llRefCount = r.llReferenceCount <= 0 ? null : r.llReferenceCount; + jdbcTemplate.update(UPDATE_SQL, ltUsed, r.llLabel, llRefCount, r.rrUsed, r.id); + } + + @Override + public void delete(long id) { + jdbcTemplate.update(DELETE_SQL, id); + } + + private static class ResourceRowMapper implements RowMapper<Resource> { + + @Override + public Resource mapRow(ResultSet rs, int arg1) throws SQLException { + Resource r = new Resource(); + r.id = rs.getLong("resource_id"); + r.assetId = rs.getString("asset_id"); + r.name = rs.getString("resource_name"); + r.type = rs.getString("resource_type"); + r.ltUsed = rs.getLong("lt_used"); + r.llLabel = rs.getString("ll_label"); + r.llReferenceCount = rs.getInt("ll_reference_count"); + r.rrUsed = rs.getString("rr_used"); + return r; + } + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoad.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoad.java new file mode 100644 index 000000000..0f45bbfcb --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoad.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.Date; + +public class ResourceLoad { + + public long id; + public long resourceId; + public String applicationId; + public Date loadTime; + public Date expirationTime; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDao.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDao.java new file mode 100644 index 000000000..789670c4b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDao.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.util.List; + +public interface ResourceLoadJdbcDao { + + void add(ResourceLoad rl); + + List<ResourceLoad> getResourceLoads(long resourceId); + + void update(ResourceLoad rl); + + void delete(long id); + +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDaoImpl.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDaoImpl.java new file mode 100644 index 000000000..632a5fbec --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/dao/jdbc/ResourceLoadJdbcDaoImpl.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.dao.jdbc; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.PreparedStatementCreator; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.support.GeneratedKeyHolder; +import org.springframework.jdbc.support.KeyHolder; + +public class ResourceLoadJdbcDaoImpl implements ResourceLoadJdbcDao { + + @SuppressWarnings("unused") + private static final Logger log = LoggerFactory.getLogger(ResourceJdbcDaoImpl.class); + + private static final String INSERT_SQL = "INSERT INTO RESOURCE_LOAD (\n" + + " resource_id, application_id, resource_load_time, resource_expiration_time)\nVALUES (?, ?, ?, ?)"; + + private static final String UPDATE_SQL = "UPDATE RESOURCE_LOAD SET\n" + + " resource_load_time = ?, resource_expiration_time = ?\nWHERE resource_id = ?"; + + private static final String DELETE_SQL = "DELETE FROM RESOURCE_LOAD WHERE resource_load_id = ?"; + + private static final String GET_SQL = "SELECT * FROM RESOURCE_LOAD WHERE resource_id = ?"; + + private JdbcTemplate jdbcTemplate; + private ResourceLoadRowMapper resourceLoadRowMapper = new ResourceLoadRowMapper(); + + @Override + public void add(final ResourceLoad rl) { + PreparedStatementCreator psc = new PreparedStatementCreator() { + + @Override + public PreparedStatement createPreparedStatement(Connection dbc) throws SQLException { + PreparedStatement ps = dbc.prepareStatement(INSERT_SQL, new String[] { "resource_load_id" }); + ps.setLong(1, rl.resourceId); + ps.setString(2, rl.applicationId); + ps.setTimestamp(3, new Timestamp(rl.loadTime.getTime())); + ps.setTimestamp(4, new Timestamp(rl.expirationTime.getTime())); + return ps; + } + }; + KeyHolder keyHolder = new GeneratedKeyHolder(); + jdbcTemplate.update(psc, keyHolder); + rl.id = keyHolder.getKey().longValue(); + } + + @Override + public void update(ResourceLoad rl) { + jdbcTemplate.update(UPDATE_SQL, rl.loadTime, rl.expirationTime, rl.id); + } + + @Override + public void delete(long id) { + jdbcTemplate.update(DELETE_SQL, id); + } + + @Override + public List<ResourceLoad> getResourceLoads(long resourceId) { + if (resourceId <= 0) + return Collections.emptyList(); + + return jdbcTemplate.query(GET_SQL, new Object[] { resourceId }, resourceLoadRowMapper); + } + + private static class ResourceLoadRowMapper implements RowMapper<ResourceLoad> { + + @Override + public ResourceLoad mapRow(ResultSet rs, int n) throws SQLException { + ResourceLoad rl = new ResourceLoad(); + rl.id = rs.getLong("allocation_item_id"); + rl.resourceId = rs.getLong("resource_id"); + rl.applicationId = rs.getString("application_id"); + rl.loadTime = rs.getTimestamp("resource_load_time"); + rl.expirationTime = rs.getTimestamp("resource_expiration_time"); + return rl; + } + } + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationAction.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationAction.java new file mode 100644 index 000000000..edc1916b5 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationAction.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public enum AllocationAction { + Fail, Succeed_DoNothing, Succeed_Allocate +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationItem.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationItem.java new file mode 100644 index 000000000..f8e6a75a1 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationItem.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.Date; +import java.util.Set; + +public abstract class AllocationItem { + + public ResourceKey resourceKey; + public ResourceType resourceType; + public String resourceSetId; + public String resourceUnionId; + public Set<String> resourceShareGroupList; + public String applicationId; + public Date allocationTime; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationOutcome.java new file mode 100644 index 000000000..048f4f4ac --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationOutcome.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class AllocationOutcome { + + public AllocationStatus status = null; + public AllocationRequest request = null; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationRequest.java new file mode 100644 index 000000000..29b493683 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationRequest.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.Set; + +public class AllocationRequest { + + public String applicationId = null; + public String resourceUnionId = null; + public String resourceSetId = null; + public Set<String> resourceShareGroupList = null; + public String resourceName = null; + public String assetId = null; + public AllocationAction missingResourceAction = AllocationAction.Succeed_Allocate; + public AllocationAction expiredResourceAction = AllocationAction.Succeed_Allocate; + public String endPointPosition = null; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationStatus.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationStatus.java new file mode 100644 index 000000000..bef9a1114 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/AllocationStatus.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public enum AllocationStatus { + + Success, Failure, NotTried, ResourceNotFound, ResourceExpired +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/InitAction.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/InitAction.java new file mode 100644 index 000000000..f6fc7c9b3 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/InitAction.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public enum InitAction { + CheckInit("Initialize if needed"), ForceInit("Always Initialize"), NoInit("No initialization"); + + private String str; + + private InitAction(String str) { + this.str = str; + } + + public String getInitActionStr() { + return str; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationItem.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationItem.java new file mode 100644 index 000000000..d41bfd62a --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationItem.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LabelAllocationItem extends AllocationItem { + + public String label; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationOutcome.java new file mode 100644 index 000000000..9c9f9145d --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationOutcome.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LabelAllocationOutcome extends AllocationOutcome { + + public String allocatedLabel = null; + public String currentLabel = null; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationRequest.java new file mode 100644 index 000000000..97751fc01 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelAllocationRequest.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LabelAllocationRequest extends AllocationRequest { + + public String label = null; + public boolean check = false; + public boolean allocate = false; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelResource.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelResource.java new file mode 100644 index 000000000..d09dba267 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LabelResource.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LabelResource extends Resource { + + public static final String BLOCKED = "__BLOCKED__"; + + public String label; + public int referenceCount; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationItem.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationItem.java new file mode 100644 index 000000000..ad1674f7b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationItem.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LimitAllocationItem extends AllocationItem { + + public long used; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationOutcome.java new file mode 100644 index 000000000..d635e3605 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationOutcome.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LimitAllocationOutcome extends AllocationOutcome { + + public long allocatedCount = 0; + public long used = 0; + public long limit = 0; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationRequest.java new file mode 100644 index 000000000..06c0e8393 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitAllocationRequest.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LimitAllocationRequest extends AllocationRequest { + + public long checkCount = 0; + public long allocateCount = 0; + public long checkLimit = -1; + public boolean replace = false; + public boolean strict = false; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitResource.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitResource.java new file mode 100644 index 000000000..2fd9b6cae --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/LimitResource.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class LimitResource extends Resource { + + public long used = 0; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationOutcome.java new file mode 100644 index 000000000..2d7b11c31 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationOutcome.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.List; + +public class MultiAssetAllocationOutcome extends AllocationOutcome { + + public List<String> goodAssetIdList; + public List<AllocationOutcome> allocationOutcomeList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationRequest.java new file mode 100644 index 000000000..366201f35 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiAssetAllocationRequest.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.List; + +public class MultiAssetAllocationRequest extends AllocationRequest { + + public List<String> assetIdList = null; + public AllocationRequest allocationRequest = null; + public int requestedCount = 0; + public boolean sequential = false; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationOutcome.java new file mode 100644 index 000000000..f71c247da --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationOutcome.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.List; + +public class MultiResourceAllocationOutcome extends AllocationOutcome { + + public List<AllocationOutcome> allocationOutcomeList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationRequest.java new file mode 100644 index 000000000..3244c2340 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/MultiResourceAllocationRequest.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.List; + +public class MultiResourceAllocationRequest extends AllocationRequest { + + public List<AllocationRequest> allocationRequestList = null; + public boolean stopOnFirstFailure = true; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Range.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Range.java new file mode 100644 index 000000000..16be77f5b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Range.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class Range { + + public int min = 0; + public int max = 0; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationItem.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationItem.java new file mode 100644 index 000000000..8e62ef653 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationItem.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.SortedSet; + +public class RangeAllocationItem extends AllocationItem { + + public SortedSet<Integer> used; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationOutcome.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationOutcome.java new file mode 100644 index 000000000..3b675c221 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationOutcome.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.SortedSet; + +public class RangeAllocationOutcome extends AllocationOutcome { + + public SortedSet<Integer> allocated = null; + public SortedSet<Integer> used = null; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationRequest.java new file mode 100644 index 000000000..a7948b02c --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeAllocationRequest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.List; +import java.util.SortedSet; + +public class RangeAllocationRequest extends AllocationRequest { + + public List<Range> rangeList = null; + public boolean check = false; + public boolean allocate = false; + public boolean replace = false; + public SortedSet<Integer> requestedNumbers = null; + public SortedSet<Integer> excludeNumbers = null; + public int requestedCount = 1; + public boolean sequential = false; + public boolean reverseOrder = false; + public boolean forceNewNumbers = false; + public boolean nextInSequence = false; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeResource.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeResource.java new file mode 100644 index 000000000..c39cb37ea --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/RangeResource.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.SortedSet; + +public class RangeResource extends Resource { + + public SortedSet<Integer> used; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ReleaseRequest.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ReleaseRequest.java new file mode 100644 index 000000000..dba6a172f --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ReleaseRequest.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.Set; + +public class ReleaseRequest { + + public String resourceUnionId = null; + public String resourceSetId = null; + public String assetId = null; + public String resourceName = null; + public int releaseAmount = 0; + public Set<Integer> releaseNumbers = null; + + public static ReleaseRequest resourceSet(String resourceSetId) { + ReleaseRequest rr = new ReleaseRequest(); + rr.resourceSetId = resourceSetId; + return rr; + } + + public static ReleaseRequest resourceUnion(String resourceUnionId) { + ReleaseRequest rr = new ReleaseRequest(); + rr.resourceUnionId = resourceUnionId; + return rr; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Resource.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Resource.java new file mode 100644 index 000000000..59706f4d5 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/Resource.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.Collection; + +public abstract class Resource { + + public ResourceKey resourceKey; + public ResourceType resourceType; + public Collection<AllocationItem> allocationItems; + public Collection<ResourceLoad> resourceLoadList; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceKey.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceKey.java new file mode 100644 index 000000000..b1f8d5910 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceKey.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public class ResourceKey { + + public String assetId; + public String resourceName; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || !(o instanceof ResourceKey)) + return false; + ResourceKey rk = (ResourceKey) o; + if (assetId == null || resourceName == null) + return false; + return assetId.equals(rk.assetId) && resourceName.equals(rk.resourceName); + } + + @Override + public int hashCode() { + return (int) ((long) System.identityHashCode(assetId) + (long) System.identityHashCode(resourceName)); + } + + @Override + public String toString() { + return "(" + assetId + ", " + resourceName + ")"; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceLoad.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceLoad.java new file mode 100644 index 000000000..1ff1962af --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceLoad.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +import java.util.Date; + +public class ResourceLoad { + + public ResourceKey resourceKey; + public String applicationId; + public Date resourceLoadTime; + public Date resourceExpirationTime; +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceType.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceType.java new file mode 100644 index 000000000..60896e492 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/data/ResourceType.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.data; + +public enum ResourceType { + Limit, Label, Range +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LabelUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LabelUtil.java new file mode 100644 index 000000000..a67a50b31 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LabelUtil.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.util; + +import java.util.ArrayList; +import java.util.Date; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelResource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceKey; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; + +public class LabelUtil { + + public static boolean checkLabel(LabelResource l, LabelAllocationRequest req) { + if (req.check && req.label != null && l.allocationItems != null && !l.allocationItems.isEmpty()) { + for (AllocationItem ai : l.allocationItems) { + LabelAllocationItem lai = (LabelAllocationItem) ai; + if (!eq(req.resourceUnionId, lai.resourceUnionId) && !eq(req.label, lai.label)) { + return false; + } + } + } + return true; + } + + public static String allocateLabel(LabelResource l, LabelAllocationRequest req) { + if (!req.allocate) { + return null; + } + + LabelAllocationItem lai = (LabelAllocationItem) ResourceUtil.getAllocationItem(l, req.resourceSetId); + if (lai == null) { + lai = new LabelAllocationItem(); + lai.resourceType = ResourceType.Label; + lai.resourceKey = new ResourceKey(); + lai.resourceKey.assetId = req.assetId; + lai.resourceKey.resourceName = req.resourceName; + lai.applicationId = req.applicationId; + lai.resourceSetId = req.resourceSetId; + lai.resourceUnionId = req.resourceUnionId; + lai.resourceShareGroupList = req.resourceShareGroupList; + + if (l.allocationItems == null) { + l.allocationItems = new ArrayList<>(); + } + l.allocationItems.add(lai); + } + + lai.label = req.label; + lai.allocationTime = new Date(); + + recalculate(l); + + return lai.label; + } + + public static void recalculate(LabelResource l) { + l.label = null; + l.referenceCount = 0; + if (l.allocationItems != null) { + for (AllocationItem ai : l.allocationItems) { + LabelAllocationItem lai = (LabelAllocationItem) ai; + if (lai.label != null) { + l.referenceCount++; + if (l.label == null) { + l.label = lai.label; + } else if (!l.label.equals(lai.label)) { + l.label = "__BLOCKED__"; + } + } + } + } + } + + private static boolean eq(Object o1, Object o2) { + return o1 == null ? o2 == null : o1.equals(o2); + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LimitUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LimitUtil.java new file mode 100644 index 000000000..2e36c9661 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/LimitUtil.java @@ -0,0 +1,355 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.util; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitResource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceKey; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LimitUtil { + + private static final Logger log = LoggerFactory.getLogger(LimitUtil.class); + + public static boolean checkLimit(LimitResource l, LimitAllocationRequest req) { + if (req.checkCount <= 0) { + return true; + } + + long checkCount = req.checkCount; + long currentUsage = 0; + if (req.resourceSetId != null) { + LimitAllocationItem lai = (LimitAllocationItem) ResourceUtil.getAllocationItem(l, req.resourceSetId); + if (lai != null) { + currentUsage = lai.used; + } + } + if (!req.replace) { + checkCount += currentUsage; + } + + long used = calculateLimitUsage(l, 0, null, null); + long wouldUse = calculateLimitUsage(l, checkCount, req.resourceUnionId, req.resourceShareGroupList); + + // If usage is not increasing by this request, only check the limit if + // strictCheck is true. + if (wouldUse <= used && !req.strict) { + return true; + } + + return wouldUse <= req.checkLimit; + } + + private static long calculateLimitUsage( + LimitResource l, + long checkCount, + String resourceUnionId, + Set<String> resourceShareGroupList) { + if ((l.allocationItems == null || l.allocationItems.isEmpty()) && + (resourceUnionId == null || resourceUnionId.length() == 0)) { + return 0; + } + + long t1 = System.currentTimeMillis(); + boolean logit = false; + String rn = "Resource: " + l.resourceKey.resourceName + " - " + l.resourceKey.assetId; + + // In order to best utilize the resource, we need to take not the sum of all allocation items, but + // instead the maximum usage that could happen at any moment of time (given not all allocation items are active + // at the same time), also taking into account possible resource sharing. + // Thus we need to find all combinations of allocation items that can be active at the same time (allocation + // items with the same first union cannot be active at the same time), compute the usage for each (again, + // taking into account resource sharing), and take the maximum. + // + // Example: + // Let's have the following allocation items: + // ai1: sdid1, vrf1 - usage 5 + // ai2: sdid2, vrf1 - usage 10 + // ai3: sdid3, vrf2 - usage 15 + // ai4: sdid1, vrf3 - usage 20 + // ai5: sdid3, vrf1 - usage 25 + // The following combinations of active allocation items are possible: + // 1) ai1, ai2, ai3 + // 2) ai1, ai2, ai5 + // 3) ai2, ai3, ai4 + // 4) ai2, ai3, ai5 + // Here is how we calculate the usage for combination 1: + // ai1 and ai2 contain the same resource union vrf1, so they share the resource - we take the max of usage, + // so we have: + // max(5, 10) + 15 = 25 + // Similarly, we calculate the usage of the other combinations: + // 2) max(5, 10, 25) = 25 + // 3) 10 + 15 + 20 = 45 + // 4) max(10, 25) + 15 = 40 + // So, the result in this case is: + // max(25, 25, 45, 40) = 45 + // + // We might have a problem with this approach, if we have a lot of combinations. Assuming we have at most 2 + // allocation items with the same resource union (sdid), the number of combinations would be + // 2 ^ n + // where n is the number of allocation items that have the same resource union (sdid). That would be + // the number of change orders currently in progress. + // + // Here is one optimization that we can do: + // If we have allocation items that have all resource unions the same, we don't need to generate combinations + // with each of them, we can just take the one of them with the maximum usage, as it is clear that the others + // will not lead to a bigger usage. + // For example, if we had the following allocation items: + // ai1: sdid1, vrf1 - usage 10 + // ai2: sdid1, vrf1 - usage 20 + // We only need to take the combinations with ai2, as they will always lead to bigger usage than the remaining + // combinations with ai1. + + // First, group the allocation items by the first resource union, using the LimitUsage structure + int regularChangeCount = 0; + Map<String/* resourceUnionId */, List<LimitUsage>> limitUsageMap = new HashMap<>(); + if (l.allocationItems != null) { + for (AllocationItem ai : l.allocationItems) { + LimitAllocationItem lai = (LimitAllocationItem) ai; + boolean regularChange = + addLimitUsage(limitUsageMap, lai.resourceUnionId, lai.resourceShareGroupList, lai.used); + if (regularChange) { + regularChangeCount++; + } + } + } + if (checkCount > 0 && resourceUnionId != null) { + boolean regularChange = addLimitUsage(limitUsageMap, resourceUnionId, resourceShareGroupList, checkCount); + if (regularChange) { + regularChangeCount++; + } + } + + // Generate all the combinations, containing one LimitUsage object for each firstResourceUnion + int significantChangeCount = 0; + List<List<LimitUsage>> allCombinations = new ArrayList<>(); + for (String firstResourceUnion : limitUsageMap.keySet()) { + List<LimitUsage> limitUsageList = limitUsageMap.get(firstResourceUnion); + if (limitUsageList.size() > 1) { + significantChangeCount++; + } + if (allCombinations.isEmpty()) { + for (LimitUsage limitUsage : limitUsageList) { + List<LimitUsage> newCombination = new ArrayList<>(); + newCombination.add(limitUsage); + allCombinations.add(newCombination); + } + } else { + if (limitUsageList.size() == 1) { + // No new combinations are generated - just add this one to all combinations we have until now + for (List<LimitUsage> combination : allCombinations) { + combination.add(limitUsageList.get(0)); + } + } else { + // We have to duplicate each of the current combinations for each element of limitUsageList + List<List<LimitUsage>> newAllCombinations = new ArrayList<>(); + for (List<LimitUsage> combination : allCombinations) { + for (LimitUsage limitUsage : limitUsageList) { + List<LimitUsage> newCombination = new ArrayList<>(combination); + newCombination.add(limitUsage); + newAllCombinations.add(newCombination); + } + } + allCombinations = newAllCombinations; + } + } + } + + // Now, go through all combinations and calculate its usage, get the maximum + long maxUsage = 0; + for (List<LimitUsage> combination : allCombinations) { + long usage = calculateUsage(combination); + if (usage > maxUsage) { + maxUsage = usage; + } + } + + long t2 = System.currentTimeMillis(); + if (logit) { + log.debug(rn + ": Calculating usage completed:"); + log.debug(rn + ": Regular changes: " + regularChangeCount); + log.debug(rn + ": Significant changes: " + significantChangeCount); + log.debug(rn + ": Combinations: " + allCombinations.size()); + log.debug(rn + ": Usage: " + maxUsage); + log.debug(rn + ": Time: " + (t2 - t1)); + } + + return maxUsage; + } + + private static boolean addLimitUsage( + Map<String/* resourceUnionId */, List<LimitUsage>> limitUsageMap, + String resourceUnionId, + Set<String> resourceShareGroupList, + long used) { + List<LimitUsage> limitUsageList = limitUsageMap.get(resourceUnionId); + if (limitUsageList == null) { + limitUsageList = new ArrayList<>(); + limitUsageMap.put(resourceUnionId, limitUsageList); + } + // See if we already have the same shareResourceUnionSet in the list. In such case just update the usage + // to the bigger value. + LimitUsage limitUsage = null; + for (LimitUsage limitUsage1 : limitUsageList) { + if ((limitUsage1.resourceShareGroupList == null || limitUsage1.resourceShareGroupList.isEmpty()) && + (resourceShareGroupList == null || resourceShareGroupList.isEmpty())) { + limitUsage = limitUsage1; + break; + } + if (limitUsage1.resourceShareGroupList != null && + limitUsage1.resourceShareGroupList.equals(resourceShareGroupList)) { + limitUsage = limitUsage1; + break; + } + } + if (limitUsage != null) { + if (limitUsage.usage < used) { + limitUsage.usage = used; + } + return true; + } + + limitUsage = new LimitUsage(); + limitUsage.resourceUnion = resourceUnionId; + limitUsage.resourceShareGroupList = resourceShareGroupList; + limitUsage.usage = used; + limitUsageList.add(limitUsage); + return false; + } + + private static class LimitUsage { + + @SuppressWarnings("unused") + public String resourceUnion; + public Set<String> resourceShareGroupList; + public long usage; + } + + private static boolean hasCommonSharedResource(LimitUsage limitUsage1, LimitUsage limitUsage2) { + if (limitUsage1.resourceShareGroupList == null || limitUsage1.resourceShareGroupList.isEmpty()) { + return false; + } + if (limitUsage2.resourceShareGroupList == null || limitUsage2.resourceShareGroupList.isEmpty()) { + return false; + } + + for (String resourceUnion : limitUsage1.resourceShareGroupList) { + if (limitUsage2.resourceShareGroupList.contains(resourceUnion)) { + return true; + } + } + + return false; + } + + private static long calculateUsage(List<LimitUsage> combination) { + // All LimitUsage objects that have a common value in their sharedResourceUnionSet reuse the resource, so + // split the combination in sets that have common value. Then the usage of each set will be the maximum of + // the usages of the LimitUsage objects in the set. The usage of the combination will be the sum of the usages + // of all sets. + List<List<LimitUsage>> sharedSets = new ArrayList<>(); + for (LimitUsage limitUsage : combination) { + // See if we can put limitUsage in any of the existing sets - is it has a common resource union with + // any of the LimitUsage objects in a set. + boolean found = false; + for (List<LimitUsage> sharedSet : sharedSets) { + for (LimitUsage limitUsage1 : sharedSet) { + if (hasCommonSharedResource(limitUsage, limitUsage1)) { + found = true; + break; + } + } + if (found) { + sharedSet.add(limitUsage); + break; + } + } + if (!found) { + // Start a new set + List<LimitUsage> newSharedSet = new ArrayList<>(); + newSharedSet.add(limitUsage); + sharedSets.add(newSharedSet); + } + } + + long sum = 0; + for (List<LimitUsage> sharedSet : sharedSets) { + float max = 0; + for (LimitUsage limitUsage : sharedSet) { + if (max < limitUsage.usage) { + max = limitUsage.usage; + } + } + sum += max; + } + + return sum; + } + + public static long allocateLimit(LimitResource l, LimitAllocationRequest req) { + if (req.allocateCount <= 0) { + return 0; + } + long uu = l.used; + + LimitAllocationItem lai = (LimitAllocationItem) ResourceUtil.getAllocationItem(l, req.resourceSetId); + if (lai == null) { + lai = new LimitAllocationItem(); + lai.resourceType = ResourceType.Limit; + lai.resourceKey = new ResourceKey(); + lai.resourceKey.assetId = req.assetId; + lai.resourceKey.resourceName = req.resourceName; + lai.applicationId = req.applicationId; + lai.resourceSetId = req.resourceSetId; + lai.resourceUnionId = req.resourceUnionId; + lai.resourceShareGroupList = req.resourceShareGroupList; + lai.used = req.allocateCount; + + if (l.allocationItems == null) { + l.allocationItems = new ArrayList<>(); + } + l.allocationItems.add(lai); + } else { + lai.used = req.replace ? req.allocateCount : lai.used + req.allocateCount; + } + + lai.allocationTime = new Date(); + + recalculate(l); + + return l.used - uu; + } + + public static void recalculate(LimitResource l) { + l.used = calculateLimitUsage(l, 0, null, null); + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/RangeUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/RangeUtil.java new file mode 100644 index 000000000..2e378f1aa --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/RangeUtil.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.util; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.Range; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeAllocationRequest; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeResource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceKey; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; + +public class RangeUtil { + + public static void recalculate(RangeResource r) { + r.used = new TreeSet<>(); + if (r.allocationItems != null) { + for (AllocationItem ai : r.allocationItems) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + if (rai.used != null) { + r.used.addAll(rai.used); + } + } + } + } + + public static boolean checkRange(RangeResource r, RangeAllocationRequest req, int num) { + if (req.excludeNumbers != null && req.excludeNumbers.contains(num)) { + return false; + } + + if (req.rangeList != null && !req.rangeList.isEmpty()) { + boolean good = false; + for (Range range : req.rangeList) { + if (num < range.min || num > range.max) { + continue; + } + + boolean found = false; + if (r.allocationItems != null) { + for (AllocationItem ai : r.allocationItems) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + if (!eq(req.resourceUnionId, rai.resourceUnionId) && rai.used != null + && rai.used.contains(num)) { + if (!overlap(rai.resourceShareGroupList, req.resourceShareGroupList)) { + found = true; + break; + } + } + if (!req.replace && eq(req.resourceSetId, rai.resourceSetId) && rai.used != null + && rai.used.contains(num)) { + found = true; + break; + } + if (req.forceNewNumbers && rai.used.contains(num)) { + found = true; + break; + } + } + } + + if (!found) { + good = true; + break; + } + } + + return good; + } + + return true; + } + + public static SortedSet<Integer> getUsed(RangeResource r, String resourceUnionId) { + SortedSet<Integer> used = new TreeSet<>(); + if (r.allocationItems != null) { + for (AllocationItem ai : r.allocationItems) { + RangeAllocationItem rai = (RangeAllocationItem) ai; + if (eq(resourceUnionId, rai.resourceUnionId) && rai.used != null) { + used.addAll(rai.used); + } + } + } + return used; + } + + public static void allocateRange(RangeResource rr, SortedSet<Integer> requestedNumbers, + RangeAllocationRequest req) { + if (!req.allocate) { + return; + } + + RangeAllocationItem rai = (RangeAllocationItem) ResourceUtil.getAllocationItem(rr, req.resourceSetId); + if (rai == null) { + rai = new RangeAllocationItem(); + rai.resourceType = ResourceType.Range; + rai.resourceKey = new ResourceKey(); + rai.resourceKey.assetId = req.assetId; + rai.resourceKey.resourceName = req.resourceName; + rai.applicationId = req.applicationId; + rai.resourceSetId = req.resourceSetId; + rai.resourceUnionId = req.resourceUnionId; + rai.resourceShareGroupList = req.resourceShareGroupList; + rai.used = requestedNumbers; + + if (rr.allocationItems == null) { + rr.allocationItems = new ArrayList<>(); + } + rr.allocationItems.add(rai); + } else if (req.replace) { + rai.used = requestedNumbers; + } else { + rai.used.addAll(requestedNumbers); + } + + rai.allocationTime = new Date(); + + recalculate(rr); + } + + private static boolean eq(Object o1, Object o2) { + return o1 == null ? o2 == null : o1.equals(o2); + } + + private static boolean overlap(Set<String> s1, Set<String> s2) { + if (s1 == null || s1.isEmpty() || s2 == null || s2.isEmpty()) { + return false; + } + for (String ss1 : s1) { + if (s2.contains(ss1)) { + return true; + } + } + return false; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/ResourceUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/ResourceUtil.java new file mode 100644 index 000000000..3db63804b --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/rm/util/ResourceUtil.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.rm.util; + +import org.onap.ccsdk.sli.adaptors.rm.data.AllocationItem; +import org.onap.ccsdk.sli.adaptors.rm.data.LabelResource; +import org.onap.ccsdk.sli.adaptors.rm.data.LimitResource; +import org.onap.ccsdk.sli.adaptors.rm.data.RangeResource; +import org.onap.ccsdk.sli.adaptors.rm.data.Resource; +import org.onap.ccsdk.sli.adaptors.rm.data.ResourceType; + +public class ResourceUtil { + + public static AllocationItem getAllocationItem(Resource r, String resourceSetId) { + if (r.allocationItems != null) { + for (AllocationItem ai : r.allocationItems) { + if (ai.resourceSetId != null && ai.resourceSetId.equals(resourceSetId)) { + return ai; + } + } + } + return null; + } + + public static void recalculate(Resource r) { + if (r == null) { + return; + } + + if (r.resourceType == ResourceType.Limit) { + LimitUtil.recalculate((LimitResource) r); + } else if (r.resourceType == ResourceType.Range) { + RangeUtil.recalculate((RangeResource) r); + } else if (r.resourceType == ResourceType.Label) { + LabelUtil.recalculate((LabelResource) r); + } + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/CachedDataSourceWrap.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/CachedDataSourceWrap.java new file mode 100644 index 000000000..3fa3952f2 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/CachedDataSourceWrap.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.db; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CachedDataSourceWrap implements DataSource { + + private static final Logger log = LoggerFactory.getLogger(CachedDataSourceWrap.class); + + private ThreadLocal<ConnectionWrap> con = new ThreadLocal<>(); + private ThreadLocal<Boolean> autoCommit = new ThreadLocal<>(); + + private DataSource dataSource; + + @Override + public PrintWriter getLogWriter() throws SQLException { + return dataSource.getLogWriter(); + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + dataSource.setLogWriter(out); + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + dataSource.setLoginTimeout(seconds); + } + + @Override + public int getLoginTimeout() throws SQLException { + return dataSource.getLoginTimeout(); + } + + @Override + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { + return dataSource.getParentLogger(); + } + + @Override + public <T> T unwrap(Class<T> iface) throws SQLException { + return dataSource.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class<?> iface) throws SQLException { + return dataSource.isWrapperFor(iface); + } + + @Override + public Connection getConnection() throws SQLException { + if (con.get() == null) { + Connection c = dataSource.getConnection(); + + ConnectionWrap cc = new ConnectionWrap(c); + con.set(cc); + + autoCommit.set(c.getAutoCommit()); + c.setAutoCommit(false); + + log.info("Got new DB connection: " + c); + } else { + log.info("Using thread DB connection: " + con.get().getCon()); + } + + return con.get(); + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + if (con.get() == null) { + Connection c = dataSource.getConnection(username, password); + + ConnectionWrap cc = new ConnectionWrap(c); + con.set(cc); + + autoCommit.set(c.getAutoCommit()); + c.setAutoCommit(false); + + log.info("Got new DB connection: " + c); + } else { + log.info("Using thread DB connection: " + con.get().getCon()); + } + + return con.get(); + } + + public void releaseConnection() { + if (con.get() != null) { + try { + con.get().setAutoCommit(autoCommit.get()); + con.get().realClose(); + + log.info("DB Connection released: " + con.get().getCon()); + } catch (SQLException e) { + log.warn("Failed to release DB connection", e); + } finally { + con.remove(); + } + } + } + + public void commit() { + if (con.get() != null) { + try { + con.get().commit(); + + log.info("DB Connection committed: " + con.get().getCon()); + } catch (Exception e) { + log.warn("Failed to commit DB connection", e); + } + } + } + + public void rollback() { + if (con.get() != null) { + try { + con.get().rollback(); + + log.info("DB Connection rolled back: " + con.get().getCon()); + } catch (Exception e) { + log.warn("Failed to roll back DB connection", e); + } + } + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/ConnectionWrap.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/ConnectionWrap.java new file mode 100644 index 000000000..7d2554806 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/ConnectionWrap.java @@ -0,0 +1,338 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.db; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +public class ConnectionWrap implements Connection { + + private Connection cc; + + public ConnectionWrap(Connection cc) { + super(); + this.cc = cc; + } + + public Connection getCon() { + return cc; + } + + public void realClose() throws SQLException { + cc.close(); + } + + @Override + public <T> T unwrap(Class<T> iface) throws SQLException { + return cc.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class<?> iface) throws SQLException { + return cc.isWrapperFor(iface); + } + + @Override + public Statement createStatement() throws SQLException { + return cc.createStatement(); + } + + @Override + public PreparedStatement prepareStatement(String sql) throws SQLException { + return cc.prepareStatement(sql); + } + + @Override + public CallableStatement prepareCall(String sql) throws SQLException { + return cc.prepareCall(sql); + } + + @Override + public String nativeSQL(String sql) throws SQLException { + return cc.nativeSQL(sql); + } + + @Override + public void setAutoCommit(boolean autoCommit) throws SQLException { + cc.setAutoCommit(autoCommit); + } + + @Override + public boolean getAutoCommit() throws SQLException { + return cc.getAutoCommit(); + } + + @Override + public void commit() throws SQLException { + cc.commit(); + } + + @Override + public void rollback() throws SQLException { + cc.rollback(); + } + + @Override + public void close() throws SQLException { + } + + @Override + public boolean isClosed() throws SQLException { + return cc.isClosed(); + } + + @Override + public DatabaseMetaData getMetaData() throws SQLException { + return cc.getMetaData(); + } + + @Override + public void setReadOnly(boolean readOnly) throws SQLException { + cc.setReadOnly(readOnly); + } + + @Override + public boolean isReadOnly() throws SQLException { + return cc.isReadOnly(); + } + + @Override + public void setCatalog(String catalog) throws SQLException { + cc.setCatalog(catalog); + } + + @Override + public String getCatalog() throws SQLException { + return cc.getCatalog(); + } + + @Override + public void setTransactionIsolation(int level) throws SQLException { + cc.setTransactionIsolation(level); + } + + @Override + public int getTransactionIsolation() throws SQLException { + return cc.getTransactionIsolation(); + } + + @Override + public SQLWarning getWarnings() throws SQLException { + return cc.getWarnings(); + } + + @Override + public void clearWarnings() throws SQLException { + cc.clearWarnings(); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { + return cc.createStatement(resultSetType, resultSetConcurrency); + } + + @Override + public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) + throws SQLException { + return cc.prepareStatement(sql, resultSetType, resultSetConcurrency); + } + + @Override + public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { + return cc.prepareCall(sql, resultSetType, resultSetConcurrency); + } + + @Override + public Map<String, Class<?>> getTypeMap() throws SQLException { + return cc.getTypeMap(); + } + + @Override + public void setTypeMap(Map<String, Class<?>> map) throws SQLException { + cc.setTypeMap(map); + } + + @Override + public void setHoldability(int holdability) throws SQLException { + cc.setHoldability(holdability); + } + + @Override + public int getHoldability() throws SQLException { + return cc.getHoldability(); + } + + @Override + public Savepoint setSavepoint() throws SQLException { + return cc.setSavepoint(); + } + + @Override + public Savepoint setSavepoint(String name) throws SQLException { + return cc.setSavepoint(name); + } + + @Override + public void rollback(Savepoint savepoint) throws SQLException { + cc.rollback(savepoint); + } + + @Override + public void releaseSavepoint(Savepoint savepoint) throws SQLException { + cc.releaseSavepoint(savepoint); + } + + @Override + public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) + throws SQLException { + return cc.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement( + String sql, + int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return cc.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public CallableStatement prepareCall( + String sql, + int resultSetType, + int resultSetConcurrency, + int resultSetHoldability) throws SQLException { + return cc.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); + } + + @Override + public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { + return cc.prepareStatement(sql, autoGeneratedKeys); + } + + @Override + public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { + return cc.prepareStatement(sql, columnIndexes); + } + + @Override + public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { + return cc.prepareStatement(sql, columnNames); + } + + @Override + public Clob createClob() throws SQLException { + return cc.createClob(); + } + + @Override + public Blob createBlob() throws SQLException { + return cc.createBlob(); + } + + @Override + public NClob createNClob() throws SQLException { + return cc.createNClob(); + } + + @Override + public SQLXML createSQLXML() throws SQLException { + return cc.createSQLXML(); + } + + @Override + public boolean isValid(int timeout) throws SQLException { + return cc.isValid(timeout); + } + + @Override + public void setClientInfo(String name, String value) throws SQLClientInfoException { + cc.setClientInfo(name, value); + } + + @Override + public void setClientInfo(Properties properties) throws SQLClientInfoException { + cc.setClientInfo(properties); + } + + @Override + public String getClientInfo(String name) throws SQLException { + return cc.getClientInfo(name); + } + + @Override + public Properties getClientInfo() throws SQLException { + return cc.getClientInfo(); + } + + @Override + public Array createArrayOf(String typeName, Object[] elements) throws SQLException { + return cc.createArrayOf(typeName, elements); + } + + @Override + public Struct createStruct(String typeName, Object[] attributes) throws SQLException { + return cc.createStruct(typeName, attributes); + } + + @Override + public void setSchema(String schema) throws SQLException { + cc.setSchema(schema); + } + + @Override + public String getSchema() throws SQLException { + return cc.getSchema(); + } + + @Override + public void abort(Executor executor) throws SQLException { + cc.abort(executor); + } + + @Override + public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { + cc.setNetworkTimeout(executor, milliseconds); + } + + @Override + public int getNetworkTimeout() throws SQLException { + return cc.getNetworkTimeout(); + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/DataSourceWrap.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/DataSourceWrap.java new file mode 100644 index 000000000..2aebb83e3 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/db/DataSourceWrap.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.db; + +import java.io.PrintWriter; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; + +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DataSourceWrap implements DataSource { + + private static final Logger log = LoggerFactory.getLogger(DataSourceWrap.class); + + private DataSource dataSource; + + @Override + public PrintWriter getLogWriter() throws SQLException { + return dataSource.getLogWriter(); + } + + @Override + public void setLogWriter(PrintWriter out) throws SQLException { + dataSource.setLogWriter(out); + } + + @Override + public void setLoginTimeout(int seconds) throws SQLException { + dataSource.setLoginTimeout(seconds); + } + + @Override + public int getLoginTimeout() throws SQLException { + return dataSource.getLoginTimeout(); + } + + @Override + public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException { + return dataSource.getParentLogger(); + } + + @Override + public <T> T unwrap(Class<T> iface) throws SQLException { + return dataSource.unwrap(iface); + } + + @Override + public boolean isWrapperFor(Class<?> iface) throws SQLException { + return dataSource.isWrapperFor(iface); + } + + @Override + public Connection getConnection() throws SQLException { + Connection c = dataSource.getConnection(); + + log.debug("getConnection: " + c.getClass().getName()); + + c.setAutoCommit(true); + return c; + } + + @Override + public Connection getConnection(String username, String password) throws SQLException { + Connection c = dataSource.getConnection(username, password); + + log.debug("getConnection: " + c.getClass().getName()); + + c.setAutoCommit(true); + return c; + } + + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/expr/ExpressionEvaluator.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/expr/ExpressionEvaluator.java new file mode 100644 index 000000000..8092a7515 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/expr/ExpressionEvaluator.java @@ -0,0 +1,271 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.expr; + +import java.util.Map; + +public class ExpressionEvaluator { + + public static long evalLong(String expr, Map<String, String> vars) { + return (long) evalFloat(expr, vars); + } + + public static float evalFloat(String expr, Map<String, String> vars) { + expr = expr.trim(); + int sl = expr.length(); + if (sl == 0) { + throw new IllegalArgumentException("Cannot interpret empty string."); + } + + // Remove parentheses if any + if (expr.charAt(0) == '(' && expr.charAt(sl - 1) == ')') { + return evalFloat(expr.substring(1, sl - 1), vars); + } + + // Look for operators in the order of least priority + String[] sss = findOperator(expr, "-", true); + if (sss != null) { + return evalFloat(sss[0], vars) - evalFloat(sss[1], vars); + } + + sss = findOperator(expr, "+", true); + if (sss != null) { + return evalFloat(sss[0], vars) + evalFloat(sss[1], vars); + } + + sss = findOperator(expr, "/", true); + if (sss != null) { + return evalFloat(sss[0], vars) / evalFloat(sss[1], vars); + } + + sss = findOperator(expr, "*", true); + if (sss != null) { + return evalFloat(sss[0], vars) * evalFloat(sss[1], vars); + } + + // Check if expr is a number + try { + return Float.valueOf(expr); + } catch (Exception e) { + } + + // Must be a variable + String v = vars.get(expr); + try { + return Float.valueOf(v); + } catch (Exception e) { + } + return 0; + } + + public static String evalString(String expr, Map<String, String> vars) { + expr = expr.trim(); + int sl = expr.length(); + if (sl == 0) { + throw new IllegalArgumentException("Cannot interpret empty string."); + } + + // Remove parentheses if any + if (expr.charAt(0) == '(' && expr.charAt(sl - 1) == ')') { + return evalString(expr.substring(1, sl - 1), vars); + } + + // Look for operators in the order of least priority + String[] sss = findOperator(expr, "+", true); + if (sss != null) { + return evalString(sss[0], vars) + evalString(sss[1], vars); + } + + // Check if expr is a number + try { + return Float.valueOf(expr).toString(); + } catch (Exception e) { + } + + // Check for quotes + if (expr.charAt(0) == '"' && expr.charAt(sl - 1) == '"') { + return expr.substring(1, sl - 1); + } + if (expr.charAt(0) == '\'' && expr.charAt(sl - 1) == '\'') { + return expr.substring(1, sl - 1); + } + + // Must be a variable + String v = vars.get(expr); + return v != null ? v : ""; + } + + public static boolean evalBoolean(String expr, Map<String, String> vars) { + expr = expr.trim(); + int sl = expr.length(); + if (sl == 0) { + throw new IllegalArgumentException("Cannot interpret empty string."); + } + + if (expr.equalsIgnoreCase("true")) { + return true; + } + + if (expr.equalsIgnoreCase("false")) { + return false; + } + + // Remove parentheses if any + if (expr.charAt(0) == '(' && expr.charAt(sl - 1) == ')') { + return evalBoolean(expr.substring(1, sl - 1), vars); + } + + // Look for operators in the order of least priority + String[] sss = findOperator(expr, "or", true); + if (sss != null) { + return evalBoolean(sss[0], vars) || evalBoolean(sss[1], vars); + } + + sss = findOperator(expr, "and", true); + if (sss != null) { + return evalBoolean(sss[0], vars) && evalBoolean(sss[1], vars); + } + + sss = findOperator(expr, "not", true); + if (sss != null) { + return !evalBoolean(sss[1], vars); + } + + sss = findOperator(expr, "!=", false); + if (sss == null) { + sss = findOperator(expr, "<>", false); + } + if (sss != null) { + return !evalString(sss[0], vars).equals(evalString(sss[1], vars)); + } + + sss = findOperator(expr, "==", false); + if (sss == null) { + sss = findOperator(expr, "=", false); + } + if (sss != null) { + return evalString(sss[0], vars).equals(evalString(sss[1], vars)); + } + + sss = findOperator(expr, ">=", false); + if (sss != null) { + return evalLong(sss[0], vars) >= evalLong(sss[1], vars); + } + + sss = findOperator(expr, ">", false); + if (sss != null) { + return evalLong(sss[0], vars) > evalLong(sss[1], vars); + } + + sss = findOperator(expr, "<=", false); + if (sss != null) { + return evalLong(sss[0], vars) <= evalLong(sss[1], vars); + } + + sss = findOperator(expr, "<", false); + if (sss != null) { + return evalLong(sss[0], vars) < evalLong(sss[1], vars); + } + + throw new IllegalArgumentException("Cannot interpret '" + expr + "': Invalid expression."); + } + + private static String[] findOperator(String s, String op, boolean delimiterRequired) { + int opl = op.length(); + int sl = s.length(); + String delimiters = " \0\t\r\n()"; + int pcount = 0; + int qcount = 0; + for (int i = 0; i < sl; i++) { + char c = s.charAt(i); + if (c == '(' && qcount == 0) { + pcount++; + } else if (c == ')' && qcount == 0) { + pcount--; + if (pcount < 0) { + throw new IllegalArgumentException("Cannot interpret '" + s + "': Parentheses do not match."); + } + } else if (c == '\'') { + qcount = (qcount + 1) % 2; + } else if (i <= sl - opl && pcount == 0 && qcount == 0) { + String ss = s.substring(i, i + opl); + if (ss.equalsIgnoreCase(op)) { + boolean found = true; + if (delimiterRequired) { + // Check for delimiter before and after to make sure it is not part of another word + char chbefore = '\0'; + if (i > 0) { + chbefore = s.charAt(i - 1); + } + char chafter = '\0'; + if (i < sl - opl) { + chafter = s.charAt(i + opl); + } + found = delimiters.indexOf(chbefore) >= 0 && delimiters.indexOf(chafter) >= 0; + } + if (found) { + // We've found the operator, split the string + String[] sss = new String[2]; + sss[0] = s.substring(0, i); + sss[1] = s.substring(i + opl); + return sss; + } + } + } + } + if (pcount > 0) { + throw new IllegalArgumentException("Cannot interpret '" + s + "': Parentheses do not match."); + } + if (qcount > 0) { + throw new IllegalArgumentException("Cannot interpret '" + s + "': No closing '."); + } + return null; + } + + @SuppressWarnings("unused") + private static Object parseObject(String s) { + s = s.trim(); + int sl = s.length(); + if (sl == 0) { + throw new IllegalArgumentException("Cannot interpret empty string."); + } + if (s.equalsIgnoreCase("null")) { + return null; + } + if (s.charAt(0) == '\'') { + if (sl < 2 || s.charAt(sl - 1) != '\'') { + throw new IllegalArgumentException("Cannot interpret '" + s + "': No closing '."); + } + return s.substring(1, sl - 1); + } + // Not in quotes - must be a number + try { + return Long.valueOf(s); + } catch (Exception e) { + } + try { + return Double.valueOf(s); + } catch (Exception e) { + throw new IllegalArgumentException("Cannot interpret '" + s + "': Invalid number."); + } + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/speed/SpeedUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/speed/SpeedUtil.java new file mode 100644 index 000000000..0d1359cf3 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/speed/SpeedUtil.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.speed; + +public class SpeedUtil { + + private long unitFactor = 1000; + + public long convertToKbps(long maxSpeed, String unit) { + if (unit.equalsIgnoreCase("kbps")) { + return maxSpeed; + } + if (unit.equalsIgnoreCase("Mbps")) { + return maxSpeed * unitFactor; + } + if (unit.equalsIgnoreCase("Gbps")) { + return maxSpeed * unitFactor * unitFactor; + } + return 0; + } + + public long convertToMbps(long maxSpeed, String unit) { + if (unit.equalsIgnoreCase("kbps")) { + return maxSpeed / unitFactor; + } + if (unit.equalsIgnoreCase("Mbps")) { + return maxSpeed; + } + if (unit.equalsIgnoreCase("Gbps")) { + return maxSpeed * unitFactor; + } + return 0; + } + + public void setUnitFactor(long unitFactor) { + this.unitFactor = unitFactor; + } +} diff --git a/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/str/StrUtil.java b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/str/StrUtil.java new file mode 100644 index 000000000..126ec94e5 --- /dev/null +++ b/resource-assignment/provider/src/main/java/org/onap/ccsdk/sli/adaptors/util/str/StrUtil.java @@ -0,0 +1,306 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.sli.adaptors.util.str; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StrUtil { + + private static final Logger log = LoggerFactory.getLogger(StrUtil.class); + + public static final String INDENT_STR = " "; + + public static void indent(StringBuilder ss, int ind) { + for (int i = 0; i < ind; i++) + ss.append(INDENT_STR); + } + + public static void info(Logger log, Object o) { + if (log.isInfoEnabled()) { + StringBuilder ss = new StringBuilder(); + struct(ss, o); + log.info(ss.toString()); + } + } + + public static void debug(Logger log, Object o) { + if (log.isDebugEnabled()) { + StringBuilder ss = new StringBuilder(); + struct(ss, o); + log.debug(ss.toString()); + } + } + + public static void struct(StringBuilder ss, Object o) { + struct(ss, o, 0); + } + + public static void struct(StringBuilder ss, Object o, int ind) { + if (o == null) { + ss.append("null"); + return; + } + + if (isSimple(o)) { + ss.append(o); + return; + } + + Class<? extends Object> cls = o.getClass(); + + if (cls.isEnum()) { + ss.append(o); + return; + } + + if (cls.isArray()) { + int n = Array.getLength(o); + if (n == 0) { + ss.append("[]"); + return; + } + + Object o1 = Array.get(o, 0); + if (isSimple(o1)) { + ss.append('[').append(o1); + for (int i = 1; i < n; i++) { + o1 = Array.get(o, i); + ss.append(", ").append(o1); + } + ss.append(']'); + return; + } + + ss.append('\n'); + indent(ss, ind + 1); + ss.append('['); + struct(ss, o1, ind + 1); + for (int i = 1; i < n; i++) { + o1 = Array.get(o, i); + struct(ss, o1, ind + 1); + } + ss.append('\n'); + indent(ss, ind + 1); + ss.append(']'); + return; + } + + if (o instanceof Collection<?>) { + Collection<?> ll = (Collection<?>) o; + + int n = ll.size(); + if (n == 0) { + ss.append("[]"); + return; + } + + Iterator<?> ii = ll.iterator(); + Object o1 = ii.next(); + if (isSimple(o1)) { + ss.append('[').append(o1); + while (ii.hasNext()) { + o1 = ii.next(); + ss.append(", ").append(o1); + } + ss.append(']'); + return; + } + + ss.append('\n'); + indent(ss, ind + 1); + ss.append('['); + struct(ss, o1, ind + 1); + while (ii.hasNext()) { + o1 = ii.next(); + struct(ss, o1, ind + 1); + } + ss.append('\n'); + indent(ss, ind + 1); + ss.append(']'); + return; + + } + + if (o instanceof Map<?, ?>) { + Map<?, ?> mm = (Map<?, ?>) o; + + int n = mm.size(); + if (n == 0) { + ss.append("{}"); + return; + } + + ss.append('{'); + + for (Object k : mm.keySet()) { + ss.append('\n'); + indent(ss, ind + 1); + ss.append(k).append(": "); + + Object o1 = mm.get(k); + struct(ss, o1, ind + 2); + } + + ss.append('\n'); + indent(ss, ind); + ss.append('}'); + + return; + } + + Field[] fields = cls.getFields(); + + if (fields.length == 0) { + ss.append(o); + return; + } + + ss.append('\n'); + indent(ss, ind + 1); + ss.append('<').append(cls.getSimpleName()).append("> {"); + for (Field f : fields) { + ss.append('\n'); + indent(ss, ind + 2); + ss.append(f.getName()).append(": "); + Object v = null; + try { + v = f.get(o); + } catch (IllegalAccessException e) { + v = "*** Cannot obtain value *** : " + e.getMessage(); + } + struct(ss, v, ind + 2); + } + ss.append('\n'); + indent(ss, ind + 1); + ss.append('}'); + } + + public static SortedSet<Integer> listInt(String ss, String warning) { + if (ss == null || ss.length() == 0) + return null; + + SortedSet<Integer> ll = new TreeSet<Integer>(); + String[] str = ss.split(","); + for (String s : str) { + try { + int i1 = s.indexOf('-'); + int start; + int end; + if (i1 > 0) { + String s1 = s.substring(0, i1); + String s2 = s.substring(i1 + 1); + start = Integer.parseInt(s1); + end = Integer.parseInt(s2); + } else + start = end = Integer.parseInt(s); + for (int i = start; i <= end; i++) + ll.add(i); + } catch (NumberFormatException e) { + // Skip this - bad data in DB + log.warn(warning + " [" + s + "].", e); + } + } + return ll; + } + + public static String listInt(SortedSet<Integer> ll) { + if (ll == null || ll.size() == 0) + return null; + + StringBuilder sb = new StringBuilder(2000); + Iterator<Integer> i = ll.iterator(); + int n = i.next(); + int start = n; + int end = n; + boolean first = true; + while (i.hasNext()) { + n = i.next(); + if (n != end + 1) { + if (!first) + sb.append(','); + first = false; + + if (start == end) + sb.append(start); + else if (start == end - 1) + sb.append(start).append(',').append(end); + else + sb.append(start).append('-').append(end); + + start = n; + } + end = n; + } + + if (!first) + sb.append(','); + + if (start == end) + sb.append(start); + else if (start == end - 1) + sb.append(start).append(',').append(end); + else + sb.append(start).append('-').append(end); + + return sb.toString(); + } + + public static List<String> listStr(String s) { + if (s == null || s.length() == 0) + return null; + String[] ss = s.split(","); + return Arrays.asList(ss); + } + + public static String listStr(Collection<String> ll) { + if (ll == null || ll.isEmpty()) + return null; + StringBuilder ss = new StringBuilder(1000); + Iterator<String> i = ll.iterator(); + ss.append(i.next()); + while (i.hasNext()) + ss.append(',').append(i.next()); + return ss.toString(); + } + + private static boolean isSimple(Object o) { + if (o == null) + return true; + + if (o instanceof Number || o instanceof String || o instanceof Boolean || o instanceof Date) + return true; + + return false; + } +} |