/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
/**
* Remove a context album from a distributor.
*
- * @param contextAlbum The album to remove
+ * @param axContextAlbumKey The key of album to remove
* @throws ContextException if the album cannot be removed
*/
- void removeContextAlbum(AxContextAlbum contextAlbum) throws ContextException;
+ void removeContextAlbum(AxArtifactKey axContextAlbumKey) throws ContextException;
/**
* Flush all context albums owned by the distributor to the distribution mechanism.
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
-
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.context.Distributor;
* {@inheritDoc}.
*/
@Override
- public void removeContextAlbum(final AxContextAlbum contextAlbum) throws ContextException {
+ public void removeContextAlbum(final AxArtifactKey axContextAlbumKey) throws ContextException {
synchronized (albumMaps) {
- // Check if the map already exists, if not return
- if (!albumMaps.containsKey(contextAlbum.getKey())) {
- LOGGER.warn("map remove failed, supplied map is null");
+ // Remove the map from the distributor
+ if (null == albumMaps.remove(axContextAlbumKey)) {
throw new ContextException("map update failed, supplied map is null");
}
-
- // Remove the map from the distributor
- albumMaps.remove(contextAlbum.getKey());
}
}
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<profiles>
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.core.engine.context;
import com.google.common.collect.Maps;
-
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
-
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.context.Distributor;
* in the new model.
*
* @param newPolicyModel The new incoming Apex model to use for context
+ * @param isSubsequentInstance if the current worker instance being updated is not the first one
* @throws ContextException On errors on context setting
*/
- public void update(final AxPolicyModel newPolicyModel) throws ContextException {
+ public void update(final AxPolicyModel newPolicyModel, boolean isSubsequentInstance) throws ContextException {
if (newPolicyModel == null) {
throw new ContextException("internal context update failed, supplied model is null");
}
-
+ // context is shared between all the engine instances
+ // during model update context album only needs to be updated for the first instance.
+ // remaining engine instances can just copy the context
+ if (isSubsequentInstance) {
+ contextAlbums.clear();
+ for (AxArtifactKey contextAlbumKey : ModelService.getModel(AxContextAlbums.class).getAlbumsMap().keySet()) {
+ contextAlbums.put(contextAlbumKey, contextDistributor.createContextAlbum(contextAlbumKey));
+ }
+ key = newPolicyModel.getKey();
+ return;
+ }
// Get the differences between the existing context and the new context
final KeyedMapDifference<AxArtifactKey, AxContextAlbum> contextDifference =
new ContextComparer().compare(ModelService.getModel(AxContextAlbums.class), newPolicyModel.getAlbums());
+ newContextAlbum.getItemSchema().getId() + "\" on incoming model");
}
}
-
+
// Remove maps that are no longer used
for (final Entry<AxArtifactKey, AxContextAlbum> removedContextAlbumEntry : contextDifference.getLeftOnly()
.entrySet()) {
- contextDistributor.removeContextAlbum(removedContextAlbumEntry.getValue());
+ contextDistributor.removeContextAlbum(removedContextAlbumEntry.getKey());
contextAlbums.remove(removedContextAlbumEntry.getKey());
}
// Set up the new context albums
for (final AxArtifactKey contextAlbumKey : contextDifference.getRightOnly().keySet()) {
+ // In case if a context album is part of previous and current model, but needs to be cleared
+ // for example, due to a major version change
+ if (contextAlbums.containsKey(contextAlbumKey)) {
+ contextDistributor.removeContextAlbum(contextAlbumKey);
+ }
contextAlbums.put(contextAlbumKey, contextDistributor.createContextAlbum(contextAlbumKey));
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.policy.apex.core.engine.engine;
import java.util.Map;
-
import org.onap.policy.apex.core.engine.event.EnEvent;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
* transferred if there is common context in the old and new models.
*
* @param apexModel the apex model
+ * @param isSubsequentInstance if the current worker instance being updated is not the first one
* @throws ApexException on model update errors
*/
- void updateModel(AxPolicyModel apexModel) throws ApexException;
+ void updateModel(AxPolicyModel apexModel, boolean isSubsequentInstance) throws ApexException;
/**
* Starts an Apex engine so that it can receive events.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
-
import org.onap.policy.apex.context.ContextAlbum;
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.core.engine.context.ApexInternalContext;
* {@inheritDoc}.
*/
@Override
- public void updateModel(final AxPolicyModel apexModel) throws ApexException {
+ public void updateModel(final AxPolicyModel apexModel, final boolean isSubsequentInstance) throws ApexException {
if (apexModel != null) {
LOGGER.entry("updateModel()->" + key.getId() + ", apexPolicyModel=" + apexModel.getKey().getId());
} else {
/// New internal context
internalContext = new ApexInternalContext(apexModel);
} else {
- // Exiting internal context which must be updated
- internalContext.update(apexModel);
+ // Existing internal context which must be updated
+ internalContext.update(apexModel, isSubsequentInstance);
}
} catch (final ContextException e) {
LOGGER.warn(UPDATE_MODEL + key.getId() + ", error setting the context for engine \"" + key.getId() + "\"",
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.apex.core.engine.context;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
@Test
public void testAlbumUpdate() throws ContextException {
ApexInternalContext context = new ApexInternalContext(policyModel);
-
- try {
- context.update(null);
- fail("test should throw an exception");
- } catch (ContextException ce) {
- assertEquals("internal context update failed, supplied model is null", ce.getMessage());
- }
+ assertThatThrownBy(() -> context.update(null, false))
+ .hasMessage("internal context update failed, supplied model is null");
assertEquals(policyModel.getKey().getId(), context.getKey().getId());
assertEquals(1, context.getContextAlbums().size());
- try {
- context.update(incompatiblePolicyModel);
- fail("test should throw an exception here");
- } catch (ContextException ce) {
- assertEquals("internal context update failed on context album \"Album:0.0.1\" "
- + "in model \"PolicyModel:0.0.1\", "
- + "schema \"Schema:0.0.1\" on existing context model does not equal "
- + "schema \"IncompatibleSchema:0.0.1\" on incoming model", ce.getMessage());
- }
+ assertThatThrownBy(() -> context.update(incompatiblePolicyModel, false)).hasMessage(
+ "internal context update failed on context album \"Album:0.0.1\" " + "in model \"PolicyModel:0.0.1\", "
+ + "schema \"Schema:0.0.1\" on existing context model does not equal "
+ + "schema \"IncompatibleSchema:0.0.1\" on incoming model");
assertEquals(policyModel.getKey().getId(), context.getKey().getId());
- context.update(newVersionPolicyModel);
+ context.update(newVersionPolicyModel, false);
assertEquals(newVersionPolicyModel.getKey().getId(), context.getKey().getId());
- context.update(newPolicyModel);
+ context.update(newPolicyModel, true);
assertEquals(newPolicyModel.getKey().getId(), context.getKey().getId());
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.apex.core.engine.engine.impl;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
-
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.onap.policy.apex.core.engine.executor.StateMachineExecutor;
import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
-import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
}
@Test
- public void testSanity() {
+ public void testSanity() throws ApexException {
AxArtifactKey engineKey = new AxArtifactKey("Engine:0.0.1");
ApexEngineImpl engine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(engineKey);
assertNotNull(engine);
assertEquals(engineKey, engine.getKey());
- try {
- engine.start();
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("start()<-Engine:0.0.1,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.start()).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, "
+ + "engine has not been initialized, its model is not loaded");
- try {
- engine.stop();
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("stop()<-Engine:0.0.1,STOPPED, cannot stop engine, " + "engine is already stopped",
- ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.stop())
+ .hasMessage("stop()<-Engine:0.0.1,STOPPED, cannot stop engine, " + "engine is already stopped");
assertEquals(AxEngineState.STOPPED, engine.getState());
assertEquals(0, engine.getEngineContext().size());
assertEquals(engineKey, engine.getEngineStatus().getKey());
assertNull(engine.getInternalContext());
- try {
- engine.clear();
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.clear();
- try {
- engine.addEventListener(null, null);
- fail("test should throw an exception");
- } catch (ApexRuntimeException ae) {
- assertEquals("addEventListener()<-Engine:0.0.1,STOPPED, listenerName is null", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.addEventListener(null, null))
+ .hasMessage("addEventListener()<-Engine:0.0.1,STOPPED, listenerName is null");
- try {
- engine.addEventListener("myListener", null);
- fail("test should throw an exception");
- } catch (ApexRuntimeException ae) {
- assertEquals("addEventListener()<-Engine:0.0.1,STOPPED, listener is null", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.addEventListener("myListener", null))
+ .hasMessage("addEventListener()<-Engine:0.0.1,STOPPED, listener is null");
- try {
- engine.removeEventListener(null);
- fail("test should throw an exception");
- } catch (ApexRuntimeException ae) {
- assertEquals("removeEventListener()<-Engine:0.0.1,STOPPED, listenerName is null", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.removeEventListener(null))
+ .hasMessage("removeEventListener()<-Engine:0.0.1,STOPPED, listenerName is null");
- try {
- engine.addEventListener("myListener", new DummyListener());
- engine.removeEventListener("myListener");
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ engine.addEventListener("myListener", new DummyListener());
+ engine.removeEventListener("myListener");
assertNull(engine.createEvent(null));
assertFalse(engine.handleEvent(null));
- try {
- engine.updateModel(null);
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("updateModel()<-Engine:0.0.1, Apex model is not defined, it has a null value",
- ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.updateModel(null, false))
+ .hasMessage("updateModel()<-Engine:0.0.1, Apex model is not defined, it has a null value");
- try {
- engine.updateModel(policyModel);
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModel, false);
// Force a context exception
ModelService.registerModel(AxPolicyModel.class, new AxPolicyModel());
- try {
- engine.updateModel(incompatiblePolicyModel);
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("updateModel()<-Engine:0.0.1, error setting the context for engine \"Engine:0.0.1\"",
- ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.updateModel(incompatiblePolicyModel, false))
+ .hasMessage("updateModel()<-Engine:0.0.1, error setting the context for engine \"Engine:0.0.1\"");
- try {
- engine.updateModel(policyModel);
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModel, false);
assertNotNull(engine.getInternalContext());
assertEquals(1, engine.getEngineContext().size());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
- try {
- engine.start();
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("start()<-Engine:0.0.1,READY, cannot start engine, engine not in state STOPPED",
- ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.start())
+ .hasMessage("start()<-Engine:0.0.1,READY, cannot start engine, engine not in state STOPPED");
- try {
- engine.clear();
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("clear()<-Engine:0.0.1,READY, cannot clear engine, engine is not stopped", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.clear())
+ .hasMessage("clear()<-Engine:0.0.1,READY, cannot clear engine, engine is not stopped");
- try {
- engine.stop();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.stop();
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.clear();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.clear();
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.start();
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("start()<-Engine:0.0.1,STOPPED, cannot start engine, "
- + "engine has not been initialized, its model is not loaded", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.start()).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, "
+ + "engine has not been initialized, its model is not loaded");
- try {
- engine.updateModel(policyModel);
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModel, false);
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
assertNull(engine.createEvent(null));
assertTrue(engine.handleEvent(event));
assertEquals(AxEngineState.READY, engine.getState());
- try {
- engine.stop();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.stop();
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.addEventListener("myListener", new DummyListener());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ engine.addEventListener("myListener", new DummyListener());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
- try {
- engine.updateModel(policyModel);
- fail("test should throw an exception");
- } catch (ApexException ae) {
- assertEquals("updateModel()<-Engine:0.0.1, cannot update model, "
- + "engine should be stopped but is in state READY", ae.getMessage());
- }
+ assertThatThrownBy(() -> engine.updateModel(policyModel, false)).hasMessage(
+ "updateModel()<-Engine:0.0.1, cannot update model, engine should be stopped but is in state READY");
assertTrue(engine.handleEvent(event));
assertEquals(AxEngineState.READY, engine.getState());
- try {
- engine.stop();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.stop();
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.addEventListener("badListener", new DummyEnEventListener());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ engine.addEventListener("badListener", new DummyEnEventListener());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
assertFalse(engine.handleEvent(event));
assertEquals(AxEngineState.READY, engine.getState());
- try {
- engine.stop();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.stop();
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.removeEventListener("badListener");
- engine.addEventListener("slowListener", new DummySlowEnEventListener());
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ engine.removeEventListener("badListener");
+ engine.addEventListener("slowListener", new DummySlowEnEventListener());
}
@Test
- public void testState() throws InterruptedException {
+ public void testState() throws InterruptedException, ApexException {
AxArtifactKey engineKey = new AxArtifactKey("Engine:0.0.1");
ApexEngineImpl engine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(engineKey);
assertNotNull(engine);
assertEquals(engineKey, engine.getKey());
- try {
- engine.updateModel(policyModel);
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModel, false);
+ assertEquals(AxEngineState.STOPPED, engine.getState());
DummySlowEnEventListener slowListener = new DummySlowEnEventListener();
- try {
- engine.addEventListener("slowListener", slowListener);
- } catch (Exception e) {
- fail("test should not throw an exception");
- }
+ engine.addEventListener("slowListener", slowListener);
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
assertEquals(AxEngineState.READY, engine.getState());
// 1 second is less than the 3 second wait on engine stopping
slowListener.setWaitTime(1000);
(new Thread() {
+ @Override
public void run() {
assertTrue(engine.handleEvent(event));
assertEquals(AxEngineState.STOPPED, engine.getState());
// 4 seconds is more than the 3 second wait on engine stopping
slowListener.setWaitTime(4000);
(new Thread() {
+ @Override
public void run() {
assertTrue(engine.handleEvent(event));
assertEquals(AxEngineState.STOPPED, engine.getState());
@Test
public void testStateMachineError() throws InterruptedException, IllegalArgumentException, IllegalAccessException,
- NoSuchFieldException, SecurityException {
+ NoSuchFieldException, SecurityException, ApexException {
AxArtifactKey engineKey = new AxArtifactKey("Engine:0.0.1");
ApexEngineImpl engine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(engineKey);
assertNotNull(engine);
assertEquals(engineKey, engine.getKey());
- try {
- engine.updateModel(policyModel);
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModel, false);
+ assertEquals(AxEngineState.STOPPED, engine.getState());
final Field smHandlerField = engine.getClass().getDeclaredField("stateMachineHandler");
smHandlerField.setAccessible(true);
smHandlerField.set(engine, smHandlerMock);
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
assertEquals(AxEngineState.READY, engine.getState());
@Test
public void testStateMachineHandler() throws InterruptedException, IllegalArgumentException, IllegalAccessException,
- NoSuchFieldException, SecurityException {
+ NoSuchFieldException, SecurityException, ApexException {
AxArtifactKey engineKey = new AxArtifactKey("Engine:0.0.1");
ApexEngineImpl engine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(engineKey);
assertNotNull(engine);
assertEquals(engineKey, engine.getKey());
- try {
- engine.updateModel(policyModelWithStates);
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.updateModel(policyModelWithStates, false);
+ assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
AxArtifactKey eventKey = new AxArtifactKey("Event:0.0.1");
EnEvent event = engine.createEvent(eventKey);
assertEquals(eventKey, event.getKey());
- try {
- engine.stop();
- assertEquals(AxEngineState.STOPPED, engine.getState());
- } catch (ApexException ae) {
- fail("test should not throw an exception");
- }
-
+ engine.stop();
assertEquals(AxEngineState.STOPPED, engine.getState());
- try {
- engine.start();
- assertEquals(AxEngineState.READY, engine.getState());
- } catch (ApexException e) {
- fail("test should not throw an exception");
- }
+ assertEquals(AxEngineState.STOPPED, engine.getState());
+
+ engine.start();
+ assertEquals(AxEngineState.READY, engine.getState());
assertEquals(AxEngineState.READY, engine.getState());
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final ApexEngineImpl apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key);
final TestApexActionListener listener = new TestApexActionListener("Test");
apexEngine.addEventListener("listener", listener);
- apexEngine.updateModel(apexPolicyModel);
+ apexEngine.updateModel(apexPolicyModel, false);
apexEngine.start();
final AxEvent axEvent = getTriggerEvent(apexPolicyModel);
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import java.io.IOException;
import java.util.Random;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@Before
public void beforeTest() {
schemaParameters = new SchemaParameters();
-
+
schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters());
ParameterService.register(schemaParameters);
-
+
contextParameters = new ContextParameters();
contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME);
ParameterService.register(contextParameters.getDistributorParameters());
ParameterService.register(contextParameters.getLockManagerParameters());
ParameterService.register(contextParameters.getPersistorParameters());
-
+
engineParameters = new EngineParameters();
engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
@After
public void afterTest() {
ParameterService.deregister(engineParameters);
-
+
ParameterService.deregister(contextParameters.getDistributorParameters());
ParameterService.deregister(contextParameters.getLockManagerParameters());
ParameterService.deregister(contextParameters.getPersistorParameters());
final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
apexEngine1.addEventListener("listener", listener1);
- apexEngine1.updateModel(apexPolicyModel);
+ apexEngine1.updateModel(apexPolicyModel, false);
apexEngine1.start();
final EnEvent triggerEvent =
apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1"));
final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
apexEngine1.addEventListener("listener1", listener1);
- apexEngine1.updateModel(apexPolicyModel);
+ apexEngine1.updateModel(apexPolicyModel, false);
apexEngine1.start();
final EnEvent triggerEvent =
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
apexEngine1.addEventListener("listener", listener1);
- apexEngine1.updateModel(apexPolicyModel);
+ apexEngine1.updateModel(apexPolicyModel, false);
apexEngine1.start();
final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
final double rval = rand.nextGaussian();
final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
apexEngine1.addEventListener("listener1", listener1);
- apexEngine1.updateModel(apexPolicyModel);
+ apexEngine1.updateModel(apexPolicyModel, false);
apexEngine1.start();
final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
final TestSaleAuthListener listener = new TestSaleAuthListener("Test");
apexEngine.addEventListener("listener", listener);
- apexEngine.updateModel(apexPolicyModel);
+ apexEngine.updateModel(apexPolicyModel, false);
apexEngine.start();
final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1"));
final TestSaleAuthListener listener = new TestSaleAuthListener("Test");
apexEngine.addEventListener("listener", listener);
- apexEngine.updateModel(apexPolicyModel);
+ apexEngine.updateModel(apexPolicyModel, false);
apexEngine.start();
final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1"));
package org.onap.policy.apex.service.engine.main;
+import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;
import lombok.Getter;
+import lombok.Setter;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
// The parameters of the Apex activator when running with multiple policies
@Getter
+ @Setter
private Map<ToscaPolicyIdentifier, ApexParameters> apexParametersMap;
+ @Getter
+ Map<ToscaPolicyIdentifier, AxPolicyModel> policyModelsMap;
+
// Event unmarshalers are used to receive events asynchronously into Apex
private final Map<String, ApexEventUnmarshaller> unmarshallerMap = new LinkedHashMap<>();
.mapToInt(p -> p.getEngineServiceParameters().getInstanceCount()).sum();
apexParameters.getEngineServiceParameters().setInstanceCount(totalInstanceCount);
instantiateEngine(apexParameters);
- Map<ToscaPolicyIdentifier, AxPolicyModel> policyModelsMap = new LinkedHashMap<>();
- Map<String, EventHandlerParameters> inputParametersMap = new LinkedHashMap<>();
- Map<String, EventHandlerParameters> outputParametersMap = new LinkedHashMap<>();
-
- for (Entry<ToscaPolicyIdentifier, ApexParameters> apexParamsEntry : apexParametersMap.entrySet()) {
- ApexParameters apexParams = apexParamsEntry.getValue();
- boolean duplicateInputParameterExist =
- apexParams.getEventInputParameters().keySet().stream().anyMatch(inputParametersMap::containsKey);
- boolean duplicateOutputParameterExist =
- apexParams.getEventOutputParameters().keySet().stream().anyMatch(outputParametersMap::containsKey);
- if (duplicateInputParameterExist || duplicateOutputParameterExist) {
- LOGGER.error("I/O Parameters for " + apexParamsEntry.getKey().getName() + ":"
- + apexParamsEntry.getKey().getVersion()
- + " has duplicates. So this policy is not executed");
- apexParametersMap.remove(apexParamsEntry.getKey());
- continue;
- } else {
- inputParametersMap.putAll(apexParams.getEventInputParameters());
- outputParametersMap.putAll(apexParams.getEventOutputParameters());
- }
- // Check if a policy model file has been specified
- if (apexParams.getEngineServiceParameters().getPolicyModelFileName() != null) {
- LOGGER.debug("deploying policy model in \""
- + apexParams.getEngineServiceParameters().getPolicyModelFileName()
- + "\" to the apex engines . . .");
-
- final String policyModelString = TextFileUtils
- .getTextFileAsString(apexParams.getEngineServiceParameters().getPolicyModelFileName());
- AxPolicyModel policyModel = EngineServiceImpl
- .createModel(apexParams.getEngineServiceParameters().getEngineKey(), policyModelString);
- policyModelsMap.put(apexParamsEntry.getKey(), policyModel);
- }
- }
- AxPolicyModel finalPolicyModel = aggregatePolicyModels(policyModelsMap);
- // Set the policy model in the engine
- apexEngineService.updateModel(apexParameters.getEngineServiceParameters().getEngineKey(),
- finalPolicyModel, true);
- setUpMarshallerAndUnmarshaller(apexParameters.getEngineServiceParameters(), inputParametersMap,
- outputParametersMap);
- setUpmarshalerPairings(inputParametersMap);
+ setUpModelMarhsallerAndUnmarshaller(apexParameters);
} catch (final Exception e) {
LOGGER.debug(APEX_ENGINE_FAILED_MSG, e);
throw new ApexActivatorException(APEX_ENGINE_FAILED_MSG, e);
LOGGER.debug("Apex engine started as a service");
}
+ private void setUpModelMarhsallerAndUnmarshaller(ApexParameters apexParameters) throws IOException, ApexException {
+ policyModelsMap = new LinkedHashMap<>();
+ Map<String, EventHandlerParameters> inputParametersMap = new LinkedHashMap<>();
+ Map<String, EventHandlerParameters> outputParametersMap = new LinkedHashMap<>();
+
+ for (Entry<ToscaPolicyIdentifier, ApexParameters> apexParamsEntry : apexParametersMap.entrySet()) {
+ ApexParameters apexParams = apexParamsEntry.getValue();
+ boolean duplicateInputParameterExist =
+ apexParams.getEventInputParameters().keySet().stream().anyMatch(inputParametersMap::containsKey);
+ boolean duplicateOutputParameterExist =
+ apexParams.getEventOutputParameters().keySet().stream().anyMatch(outputParametersMap::containsKey);
+ if (duplicateInputParameterExist || duplicateOutputParameterExist) {
+ LOGGER.error("I/O Parameters for {}:{} has duplicates. So this policy is not executed.",
+ apexParamsEntry.getKey().getName(), apexParamsEntry.getKey().getVersion());
+ apexParametersMap.remove(apexParamsEntry.getKey());
+ continue;
+ }
+ inputParametersMap.putAll(apexParams.getEventInputParameters());
+ outputParametersMap.putAll(apexParams.getEventOutputParameters());
+ // Check if a policy model file has been specified
+ if (apexParams.getEngineServiceParameters().getPolicyModelFileName() != null) {
+ LOGGER.debug("deploying policy model in \"{}\" to the apex engines . . .",
+ apexParams.getEngineServiceParameters().getPolicyModelFileName());
+
+ final String policyModelString =
+ TextFileUtils.getTextFileAsString(apexParams.getEngineServiceParameters().getPolicyModelFileName());
+ AxPolicyModel policyModel = EngineServiceImpl
+ .createModel(apexParams.getEngineServiceParameters().getEngineKey(), policyModelString);
+ policyModelsMap.put(apexParamsEntry.getKey(), policyModel);
+ }
+ }
+ AxPolicyModel finalPolicyModel = aggregatePolicyModels(policyModelsMap);
+ // Set the policy model in the engine
+ apexEngineService.updateModel(apexParameters.getEngineServiceParameters().getEngineKey(), finalPolicyModel,
+ true);
+ setUpMarshallerAndUnmarshaller(apexParameters.getEngineServiceParameters(), inputParametersMap,
+ outputParametersMap);
+ setUpMarshalerPairings(inputParametersMap);
+ }
+
private AxPolicyModel aggregatePolicyModels(Map<ToscaPolicyIdentifier, AxPolicyModel> policyModelsMap) {
Map.Entry<ToscaPolicyIdentifier, AxPolicyModel> firstEntry = policyModelsMap.entrySet().iterator().next();
+ ToscaPolicyIdentifier tempId = new ToscaPolicyIdentifier(firstEntry.getKey());
+ AxPolicyModel tempModel = new AxPolicyModel(firstEntry.getValue());
Stream<Entry<ToscaPolicyIdentifier, AxPolicyModel>> policyModelStream =
policyModelsMap.entrySet().stream().skip(1);
Entry<ToscaPolicyIdentifier, AxPolicyModel> finalPolicyModelEntry =
entry1.setValue(
PolicyModelMerger.getMergedPolicyModel(entry1.getValue(), entry2.getValue(), true, true));
} catch (ApexModelException exc) {
- LOGGER.error("Policy model for " + entry2.getKey().getName() + ":" + entry2.getKey().getVersion()
- + " is having duplicates. So this policy is not executed", exc.getMessage());
+ LOGGER.error("Policy model for {} : {} is having duplicates. So this policy is not executed.",
+ entry2.getKey().getName(), entry2.getKey().getVersion(), exc);
apexParametersMap.remove(entry2.getKey());
+ policyModelsMap.remove(entry2.getKey());
}
return entry1;
}));
- return finalPolicyModelEntry.getValue();
+ AxPolicyModel finalPolicyModel = new AxPolicyModel(finalPolicyModelEntry.getValue());
+ policyModelsMap.put(tempId, tempModel); // put back the original first entry into the policyModelsMap
+ return finalPolicyModel;
}
private void setUpMarshallerAndUnmarshaller(EngineServiceParameters engineServiceParameters,
* paired marshaler
* @param inputParametersMap the apex parameters
*/
- private void setUpmarshalerPairings(Map<String, EventHandlerParameters> inputParametersMap) {
+ private void setUpMarshalerPairings(Map<String, EventHandlerParameters> inputParametersMap) {
for (final Entry<String, EventHandlerParameters> inputParameters : inputParametersMap.entrySet()) {
final ApexEventUnmarshaller unmarshaller = unmarshallerMap.get(inputParameters.getKey());
}
}
+ /**
+ * Updates the APEX Engine with the model created from new Policies.
+ *
+ * @param apexParamsMap the apex parameters map for the Apex service
+ * @throws ApexException on errors
+ */
+ public void updateModel(Map<ToscaPolicyIdentifier, ApexParameters> apexParamsMap) throws ApexException {
+ try {
+ shutdownMarshallerAndUnmarshaller();
+ ApexParameters apexParameters = apexParamsMap.values().iterator().next();
+ setUpModelMarhsallerAndUnmarshaller(apexParameters);
+ } catch (final Exception e) {
+ LOGGER.debug(APEX_ENGINE_FAILED_MSG, e);
+ throw new ApexActivatorException(APEX_ENGINE_FAILED_MSG, e);
+ }
+ }
+
/**
* Terminate the Apex engine.
*
*/
public void terminate() throws ApexException {
// Shut down all marshalers and unmarshalers
- for (final ApexEventMarshaller marshaller : marshallerMap.values()) {
- marshaller.stop();
- }
- marshallerMap.clear();
-
- for (final ApexEventUnmarshaller unmarshaller : unmarshallerMap.values()) {
- unmarshaller.stop();
- }
- unmarshallerMap.clear();
+ shutdownMarshallerAndUnmarshaller();
// Check if the engine service handler has been shut down already
if (engineServiceHandler != null) {
ModelService.clear();
ParameterService.clear();
}
+
+ /**
+ * Shuts down all marshallers and unmarshallers.
+ */
+ private void shutdownMarshallerAndUnmarshaller() {
+ marshallerMap.values().forEach(ApexEventMarshaller::stop);
+ marshallerMap.clear();
+ unmarshallerMap.values().forEach(ApexEventUnmarshaller::stop);
+ unmarshallerMap.clear();
+ }
}
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.TreeMap;
import lombok.Getter;
import lombok.Setter;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
+import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
+import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
+import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
+import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.service.parameters.ApexParameterHandler;
import org.onap.policy.apex.service.parameters.ApexParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
LOGGER.exit("Started Apex");
}
+ /**
+ * Updates the APEX Engine with the model created from new Policies.
+ *
+ * @param policyArgsMap the map with command line arguments as value and policy-id as key
+ * @throws ApexException on errors
+ */
+ public void updateModel(Map<ToscaPolicyIdentifier, String[]> policyArgsMap) throws ApexException {
+ apexParametersMap.clear();
+ AxContextAlbums albums = ModelService.getModel(AxContextAlbums.class);
+ Map<AxArtifactKey, AxContextAlbum> albumsMap = new TreeMap<>();
+ for (Entry<ToscaPolicyIdentifier, String[]> policyArgsEntry : policyArgsMap.entrySet()) {
+ findAlbumsToHold(albumsMap, policyArgsEntry.getKey());
+ try {
+ apexParametersMap.put(policyArgsEntry.getKey(), populateApexParameters(policyArgsEntry.getValue()));
+ } catch (ApexException e) {
+ LOGGER.error("Invalid arguments specified for policy - {}:{}", policyArgsEntry.getKey().getName(),
+ policyArgsEntry.getKey().getVersion(), e);
+ }
+ }
+ try {
+ if (albumsMap.isEmpty()) {
+ // clear context since none of the policies' context albums has to be retained
+ // this could be because all policies have a major version change,
+ // or a full set of new policies are received in the update message
+ activator.terminate();
+ // ParameterService is cleared when activator is terminated. Register the engine parameters in this case
+ new ApexParameterHandler().registerParameters(apexParametersMap.values().iterator().next());
+ activator = new ApexActivator(apexParametersMap);
+ activator.initialize();
+ setAlive(true);
+ } else {
+ albums.setAlbumsMap(albumsMap);
+ activator.setApexParametersMap(apexParametersMap);
+ activator.updateModel(apexParametersMap);
+ }
+ } catch (final ApexException e) {
+ LOGGER.error(APEX_SERVICE_FAILED_MSG, e);
+ activator.terminate();
+ throw new ApexException(e.getMessage());
+ }
+ }
+
+ /**
+ * Find the context albums which should be retained when updating the policies.
+ *
+ * @param albumsMap the albums which should be kept during model update
+ * @param policyId the policy id of current policy
+ */
+ private void findAlbumsToHold(Map<AxArtifactKey, AxContextAlbum> albumsMap, ToscaPolicyIdentifier policyId) {
+ for (Entry<ToscaPolicyIdentifier, AxPolicyModel> policyModelsEntry : activator.getPolicyModelsMap()
+ .entrySet()) {
+ // If a policy with the same major version is received in PDP_UPDATE,
+ // context for that policy has to be retained. For this, take such policies' albums
+ if (policyModelsEntry.getKey().getName().equals(policyId.getName())
+ && policyModelsEntry.getKey().getVersion().split("\\.")[0]
+ .equals(policyId.getVersion().split("\\.")[0])) {
+ albumsMap.putAll(policyModelsEntry.getValue().getAlbums().getAlbumsMap());
+ }
+ }
+ }
+
private ApexParameters populateApexParameters(String[] args) throws ApexException {
// Check the arguments
final ApexCommandLineArguments arguments = new ApexCommandLineArguments();
private AxArtifactKey engineServiceKey = null;
// The Apex engine workers this engine service is handling
- private final Map<AxArtifactKey, EngineService> engineWorkerMap = Collections
- .synchronizedMap(new LinkedHashMap<AxArtifactKey, EngineService>());
+ private final Map<AxArtifactKey, EngineWorker> engineWorkerMap = Collections
+ .synchronizedMap(new LinkedHashMap<AxArtifactKey, EngineWorker>());
// Event queue for events being sent into the Apex engines, it used by all engines within a
// group.
}
// Update the engines
- for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
+ boolean isSubsequentInstance = false;
+ for (final Entry<AxArtifactKey, EngineWorker> engineWorkerEntry : engineWorkerMap.entrySet()) {
LOGGER.info("Registering apex model on engine {}", engineWorkerEntry.getKey().getId());
- engineWorkerEntry.getValue().updateModel(engineWorkerEntry.getKey(), apexModel, forceFlag);
+ EngineWorker engineWorker = engineWorkerEntry.getValue();
+ if (isSubsequentInstance) {
+ // set subsequentInstance flag as true if the current engine worker instance is not the first one
+ // first engine instance will have this flag as false
+ engineWorker.setSubsequentInstance(true);
+ }
+ engineWorker.updateModel(engineWorkerEntry.getKey(), apexModel, forceFlag);
+ isSubsequentInstance = true;
}
// start all engines on this engine service if it was not stopped before the update
}
// Check if all engines are running
final StringBuilder notRunningEngineIdBuilder = new StringBuilder();
- for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
+ for (final Entry<AxArtifactKey, EngineWorker> engineWorkerEntry : engineWorkerMap.entrySet()) {
if (engineWorkerEntry.getValue().getState() != AxEngineState.READY
&& engineWorkerEntry.getValue().getState() != AxEngineState.EXECUTING) {
notRunningEngineIdBuilder.append(engineWorkerEntry.getKey().getId());
}
// Check if all engines are stopped
final StringBuilder notStoppedEngineIdBuilder = new StringBuilder();
- for (final Entry<AxArtifactKey, EngineService> engineWorkerEntry : engineWorkerMap.entrySet()) {
+ for (final Entry<AxArtifactKey, EngineWorker> engineWorkerEntry : engineWorkerMap.entrySet()) {
if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) {
notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId());
notStoppedEngineIdBuilder.append('(');
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
-
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;
-
+import lombok.Setter;
import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.context.SchemaHelper;
// Converts ApexEvent instances to and from EnEvent instances
private ApexEvent2EnEventConverter apexEnEventConverter = null;
+ @Setter
+ private boolean isSubsequentInstance;
+
/**
* Constructor that creates an Apex engine, an event processor for events to be sent to that engine, and an
* {@link ApexModelReader} instance to read Apex models using JAXB.
}
}
}
-
// Update the Apex model in the Apex engine
- engine.updateModel(apexModel);
+ engine.updateModel(apexModel, isSubsequentInstance);
LOGGER.debug("engine model {} added to the engine-{}", apexModel.getKey().getId(), engineWorkerKey);
LOGGER.exit();
/**
* Debug the event if debug is enabled.
- *
+ *
* @param event the event to debug
*/
private void debugEventIfDebugEnabled(ApexEvent event) {
/**
* Register all the incoming parameters with the parameter service.
- *
+ *
* @param parameters The parameters to register
*/
- private void registerParameters(ApexParameters parameters) {
+ public void registerParameters(ApexParameters parameters) {
ParameterService.register(parameters);
ParameterService.register(parameters.getEngineServiceParameters());
ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters());
* @throws ApexStarterException if the apex engine instantiation failed using the policies passed
*/
public ApexEngineHandler(List<ToscaPolicy> policies) throws ApexStarterException {
+ Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
+ LOGGER.debug("Starting apex engine.");
+ try {
+ apexMain = new ApexMain(policyArgsMap);
+ } catch (ApexException e) {
+ throw new ApexStarterException(e);
+ }
+ }
+
+ /**
+ * Updates the Apex Engine with the policy model created from new list of policies.
+ *
+ * @param policies the list of policies
+ * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
+ */
+ public void updateApexEngine(List<ToscaPolicy> policies) throws ApexStarterException {
+ if (null == apexMain || !apexMain.isAlive()) {
+ throw new ApexStarterException("Apex Engine not initialized.");
+ }
+ Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
+ try {
+ apexMain.updateModel(policyArgsMap);
+ } catch (ApexException e) {
+ throw new ApexStarterException(e);
+ }
+ }
+
+ private Map<ToscaPolicyIdentifier, String[]> createPolicyArgsMap(List<ToscaPolicy> policies)
+ throws ApexStarterException {
Map<ToscaPolicyIdentifier, String[]> policyArgsMap = new LinkedHashMap<>();
for (ToscaPolicy policy : policies) {
Object properties = policy.getProperties().get("content");
final String[] apexArgs = { "-c", apexConfigFilePath, "-m", modelFilePath };
policyArgsMap.put(policy.getIdentifier(), apexArgs);
}
-
- LOGGER.debug("Starting apex engine.");
- try {
- apexMain = new ApexMain(policyArgsMap);
- } catch (ApexException e) {
- throw new ApexStarterException(e);
- }
+ return policyArgsMap;
}
/**
PdpResponseDetails pdpResponseDetails = null;
try {
if (null != apexEngineHandler && apexEngineHandler.isApexEngineRunning()) {
- apexEngineHandler.shutdown();
+ apexEngineHandler.updateApexEngine(pdpUpdateMsg.getPolicies());
+ } else {
+ apexEngineHandler = new ApexEngineHandler(pdpUpdateMsg.getPolicies());
+ Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler);
}
- apexEngineHandler = new ApexEngineHandler(pdpUpdateMsg.getPolicies());
- Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler);
if (apexEngineHandler.isApexEngineRunning()) {
List<ToscaPolicyIdentifier> runningPolicies = apexEngineHandler.getRunningPolicies();
if (new HashSet<>(runningPolicies)
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<profiles>
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(key);
final TestApexActionListener listener = new TestApexActionListener("Test");
apexEngine.addEventListener("listener", listener);
- apexEngine.updateModel(apexPolicyModel);
+ apexEngine.updateModel(apexPolicyModel, false);
apexEngine.start();
for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
assertNotNull(apexPolicyModel);
final ApexEngine apexEngine = new ApexEngineFactory().createApexEngine(apexPolicyModel.getKey());
- apexEngine.updateModel(apexPolicyModel);
+ apexEngine.updateModel(apexPolicyModel, false);
apexEngine.start();
final EnEvent event = apexEngine.createEvent(new AxArtifactKey("Event0000", "0.0.1"));
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
package org.onap.policy.apex.testsuites.integration.executor.handling;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import java.io.IOException;
(ApexEngineImpl) new ApexEngineFactory().createApexEngine(new AxArtifactKey("TestApexEngine", "0.0.1"));
final TestApexActionListener listener = new TestApexActionListener("Test");
apexEngine.addEventListener("listener", listener);
- apexEngine.updateModel(apexModelSample);
+ apexEngine.updateModel(apexModelSample, false);
apexEngine.start();
apexEngine.stop();
final AxPolicyModel someSpuriousModel = new AxPolicyModel(new AxArtifactKey("SomeSpuriousModel", "0.0.1"));
assertNotNull(someSpuriousModel);
- try {
- apexEngine.updateModel(null);
- fail("null model should throw an exception");
- } catch (final ApexException e) {
- assertEquals("updateModel()<-TestApexEngine:0.0.1, Apex model is not defined, it has a null value",
- e.getMessage());
- }
+ assertThatThrownBy(() -> apexEngine.updateModel(null, false))
+ .hasMessage("updateModel()<-TestApexEngine:0.0.1, Apex model is not defined, it has a null value");
assertEquals(apexEngine.getInternalContext().getContextAlbums().size(),
apexModelSample.getAlbums().getAlbumsMap().size());
for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) {
contextAlbum.getAlbumDefinition().equals(apexModelSample.getAlbums().get(contextAlbum.getKey())));
}
- apexEngine.updateModel(someSpuriousModel);
+ apexEngine.updateModel(someSpuriousModel, false);
assertEquals(apexEngine.getInternalContext().getContextAlbums().size(),
someSpuriousModel.getAlbums().getAlbumsMap().size());
for (final ContextAlbum contextAlbum : apexEngine.getInternalContext().getContextAlbums().values()) {
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2019 Nordix Foundation.
* ================================================================================
* 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.
- *
+ *
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
assertNotNull(model1);
assertEquals(2, model1.getPolicies().getPolicyMap().size());
- apexEngine.updateModel(model1);
+ apexEngine.updateModel(model1, false);
apexEngine.start();
sendEvent(apexEngine, listener, "Event0000", true);
sendEvent(apexEngine, listener, "Event0100", true);
assertNotNull(model2);
model2.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy0", "0.0.1"));
assertEquals(1, model2.getPolicies().getPolicyMap().size());
- apexEngine.updateModel(model2);
+ apexEngine.updateModel(model2, false);
apexEngine.start();
sendEvent(apexEngine, listener, "Event0000", false);
sendEvent(apexEngine, listener, "Event0100", true);
assertNotNull(model3);
model3.getPolicies().getPolicyMap().remove(new AxArtifactKey("Policy1", "0.0.1"));
assertEquals(1, model3.getPolicies().getPolicyMap().size());
- apexEngine.updateModel(model3);
+ apexEngine.updateModel(model3, false);
apexEngine.start();
sendEvent(apexEngine, listener, "Event0000", true);
sendEvent(apexEngine, listener, "Event0100", false);
final AxPolicyModel model4 = new SampleDomainModelFactory().getSamplePolicyModel("MVEL");
assertNotNull(model4);
assertEquals(2, model4.getPolicies().getPolicyMap().size());
- apexEngine.updateModel(model4);
+ apexEngine.updateModel(model4, false);
apexEngine.start();
sendEvent(apexEngine, listener, "Event0100", true);
sendEvent(apexEngine, listener, "Event0000", true);
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
-
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
server.start();
- if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 2000, 1L)) {
+ if (!NetworkUtil.isTcpPortOpen("localHost", PORT, 60, 500L)) {
throw new IllegalStateException("port " + PORT + " is still not in use");
}