2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2021 Nordix Foundation.
4 * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.services.onappf.handler;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.LinkedHashMap;
30 import java.util.List;
33 import java.util.stream.Collectors;
34 import org.onap.policy.apex.core.engine.EngineParameters;
35 import org.onap.policy.apex.core.engine.TaskParameters;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo;
39 import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation;
40 import org.onap.policy.apex.model.basicmodel.service.ModelService;
41 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
42 import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
43 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
44 import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
45 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
46 import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
47 import org.onap.policy.apex.model.eventmodel.concepts.AxEvents;
48 import org.onap.policy.apex.model.policymodel.concepts.AxPolicies;
49 import org.onap.policy.apex.model.policymodel.concepts.AxPolicy;
50 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
51 import org.onap.policy.apex.model.policymodel.concepts.AxTask;
52 import org.onap.policy.apex.model.policymodel.concepts.AxTasks;
53 import org.onap.policy.apex.service.engine.main.ApexMain;
54 import org.onap.policy.apex.service.parameters.ApexParameterConstants;
55 import org.onap.policy.apex.service.parameters.ApexParameters;
56 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
57 import org.onap.policy.common.parameters.ParameterService;
58 import org.onap.policy.common.utils.coder.CoderException;
59 import org.onap.policy.common.utils.coder.StandardCoder;
60 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
62 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
63 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
68 * This class instantiates the Apex Engine based on instruction from PAP.
70 * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
72 public class ApexEngineHandler {
74 private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
76 private Map<ToscaConceptIdentifier, ApexMain> apexMainMap = new LinkedHashMap<>();
79 * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
81 * @param policies the list of policies
82 * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
84 public ApexEngineHandler(List<ToscaPolicy> policies) throws ApexStarterException {
85 LOGGER.debug("Starting apex engine.");
86 initiateApexEngineForPolicies(policies);
90 * Updates the Apex Engine with the policy model created from new list of policies.
92 * @param policies the list of policies
93 * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
95 public void updateApexEngine(List<ToscaPolicy> policies) throws ApexStarterException {
96 List<ToscaConceptIdentifier> runningPolicies = getRunningPolicies();
97 List<ToscaPolicy> policiesToDeploy = policies.stream()
98 .filter(policy -> !runningPolicies.contains(policy.getIdentifier())).collect(Collectors.toList());
99 List<ToscaConceptIdentifier> policiesToUnDeploy = runningPolicies.stream()
100 .filter(polId -> policies.stream().noneMatch(policy -> policy.getIdentifier().equals(polId)))
101 .collect(Collectors.toList());
102 Map<ToscaConceptIdentifier, ApexMain> undeployedPoliciesMainMap = new LinkedHashMap<>();
103 policiesToUnDeploy.forEach(policyId -> {
104 ApexMain apexMain = apexMainMap.get(policyId);
107 undeployedPoliciesMainMap.put(policyId, apexMain);
108 apexMainMap.remove(policyId);
109 } catch (ApexException e) {
110 LOGGER.error("Shutting down policy {} failed", policyId, e);
113 if (!undeployedPoliciesMainMap.isEmpty()) {
114 updateModelAndParameterServices(undeployedPoliciesMainMap);
116 if (!policiesToDeploy.isEmpty()) {
117 initiateApexEngineForPolicies(policiesToDeploy);
119 if (apexMainMap.isEmpty()) {
120 ModelService.clear();
121 ParameterService.clear();
126 * Clear the corresponding items from ModelService and ParameterService.
128 * @param undeployedPoliciesMainMap the policies that are undeployed
130 private void updateModelAndParameterServices(Map<ToscaConceptIdentifier, ApexMain> undeployedPoliciesMainMap) {
131 Set<String> inputParamKeysToRetain = new HashSet<>();
132 Set<String> outputParamKeysToRetain = new HashSet<>();
133 List<TaskParameters> taskParametersToRetain = new ArrayList<>();
134 List<String> executorParamKeysToRetain = new ArrayList<>();
135 List<String> schemaParamKeysToRetain = new ArrayList<>();
137 Map<AxArtifactKey, AxKeyInfo> keyInfoMapToRetain = new HashMap<>();
138 Map<AxArtifactKey, AxContextSchema> schemaMapToRetain = new HashMap<>();
139 Map<AxArtifactKey, AxEvent> eventMapToRetain = new HashMap<>();
140 Map<AxArtifactKey, AxContextAlbum> albumMapToRetain = new HashMap<>();
141 Map<AxArtifactKey, AxTask> taskMapToRetain = new HashMap<>();
142 Map<AxArtifactKey, AxPolicy> policyMapToRetain = new HashMap<>();
144 apexMainMap.values().forEach(main -> {
145 inputParamKeysToRetain.addAll(main.getApexParameters().getEventInputParameters().keySet());
146 outputParamKeysToRetain.addAll(main.getApexParameters().getEventOutputParameters().keySet());
147 taskParametersToRetain.addAll(
148 main.getApexParameters().getEngineServiceParameters().getEngineParameters().getTaskParameters());
149 executorParamKeysToRetain.addAll(main.getApexParameters().getEngineServiceParameters().getEngineParameters()
150 .getExecutorParameterMap().keySet());
151 schemaParamKeysToRetain.addAll(main.getApexParameters().getEngineServiceParameters().getEngineParameters()
152 .getContextParameters().getSchemaParameters().getSchemaHelperParameterMap().keySet());
154 AxPolicyModel policyModel = main.getActivator().getPolicyModel();
155 keyInfoMapToRetain.putAll(policyModel.getKeyInformation().getKeyInfoMap());
156 schemaMapToRetain.putAll(policyModel.getSchemas().getSchemasMap());
157 eventMapToRetain.putAll(policyModel.getEvents().getEventMap());
158 albumMapToRetain.putAll(policyModel.getAlbums().getAlbumsMap());
159 taskMapToRetain.putAll(policyModel.getTasks().getTaskMap());
160 policyMapToRetain.putAll(policyModel.getPolicies().getPolicyMap());
162 for (ApexMain main : undeployedPoliciesMainMap.values()) {
163 if (null != main.getApexParameters()) {
164 handleParametersRemoval(inputParamKeysToRetain, outputParamKeysToRetain, taskParametersToRetain,
165 executorParamKeysToRetain, schemaParamKeysToRetain, main);
167 if (null != main.getActivator() && null != main.getActivator().getPolicyModel()) {
168 handleAxConceptsRemoval(keyInfoMapToRetain, schemaMapToRetain, eventMapToRetain, albumMapToRetain,
169 taskMapToRetain, policyMapToRetain, main);
174 private void handleParametersRemoval(Set<String> inputParamKeysToRetain, Set<String> outputParamKeysToRetain,
175 List<TaskParameters> taskParametersToRetain, List<String> executorParamKeysToRetain,
176 List<String> schemaParamKeysToRetain, ApexMain main) {
177 ApexParameters existingParameters = ParameterService.get(ApexParameterConstants.MAIN_GROUP_NAME);
178 List<String> eventInputParamKeysToRemove = main.getApexParameters().getEventInputParameters().keySet().stream()
179 .filter(key -> !inputParamKeysToRetain.contains(key)).collect(Collectors.toList());
180 List<String> eventOutputParamKeysToRemove = main.getApexParameters().getEventOutputParameters().keySet()
181 .stream().filter(key -> !outputParamKeysToRetain.contains(key)).collect(Collectors.toList());
182 eventInputParamKeysToRemove.forEach(existingParameters.getEventInputParameters()::remove);
183 eventOutputParamKeysToRemove.forEach(existingParameters.getEventOutputParameters()::remove);
184 EngineParameters engineParameters = main.getApexParameters().getEngineServiceParameters().getEngineParameters();
185 final List<TaskParameters> taskParametersToRemove = engineParameters.getTaskParameters().stream()
186 .filter(taskParameter -> !taskParametersToRetain.contains(taskParameter)).collect(Collectors.toList());
187 final List<String> executorParamKeysToRemove = engineParameters.getExecutorParameterMap().keySet().stream()
188 .filter(key -> !executorParamKeysToRetain.contains(key)).collect(Collectors.toList());
189 final List<String> schemaParamKeysToRemove =
190 engineParameters.getContextParameters().getSchemaParameters().getSchemaHelperParameterMap().keySet()
191 .stream().filter(key -> !schemaParamKeysToRetain.contains(key)).collect(Collectors.toList());
192 EngineParameters aggregatedEngineParameters =
193 existingParameters.getEngineServiceParameters().getEngineParameters();
194 aggregatedEngineParameters.getTaskParameters().removeAll(taskParametersToRemove);
195 executorParamKeysToRemove.forEach(aggregatedEngineParameters.getExecutorParameterMap()::remove);
196 schemaParamKeysToRemove.forEach(aggregatedEngineParameters.getContextParameters().getSchemaParameters()
197 .getSchemaHelperParameterMap()::remove);
200 private void handleAxConceptsRemoval(Map<AxArtifactKey, AxKeyInfo> keyInfoMapToRetain,
201 Map<AxArtifactKey, AxContextSchema> schemaMapToRetain, Map<AxArtifactKey, AxEvent> eventMapToRetain,
202 Map<AxArtifactKey, AxContextAlbum> albumMapToRetain, Map<AxArtifactKey, AxTask> taskMapToRetain,
203 Map<AxArtifactKey, AxPolicy> policyMapToRetain, ApexMain main) {
204 final AxPolicyModel policyModel = main.getActivator().getPolicyModel();
205 final List<AxArtifactKey> keyInfoKeystoRemove = policyModel.getKeyInformation().getKeyInfoMap().keySet()
206 .stream().filter(key -> !keyInfoMapToRetain.containsKey(key)).collect(Collectors.toList());
207 final List<AxArtifactKey> schemaKeystoRemove = policyModel.getSchemas().getSchemasMap().keySet().stream()
208 .filter(key -> !schemaMapToRetain.containsKey(key)).collect(Collectors.toList());
209 final List<AxArtifactKey> eventKeystoRemove = policyModel.getEvents().getEventMap().keySet().stream()
210 .filter(key -> !eventMapToRetain.containsKey(key)).collect(Collectors.toList());
211 final List<AxArtifactKey> albumKeystoRemove = policyModel.getAlbums().getAlbumsMap().keySet().stream()
212 .filter(key -> !albumMapToRetain.containsKey(key)).collect(Collectors.toList());
213 final List<AxArtifactKey> taskKeystoRemove = policyModel.getTasks().getTaskMap().keySet().stream()
214 .filter(key -> !taskMapToRetain.containsKey(key)).collect(Collectors.toList());
215 final List<AxArtifactKey> policyKeystoRemove = policyModel.getPolicies().getPolicyMap().keySet().stream()
216 .filter(key -> !policyMapToRetain.containsKey(key)).collect(Collectors.toList());
218 final Map<AxArtifactKey, AxKeyInfo> keyInfoMap = ModelService.getModel(AxKeyInformation.class).getKeyInfoMap();
219 final Map<AxArtifactKey, AxContextSchema> schemasMap =
220 ModelService.getModel(AxContextSchemas.class).getSchemasMap();
221 final Map<AxArtifactKey, AxEvent> eventMap = ModelService.getModel(AxEvents.class).getEventMap();
222 final Map<AxArtifactKey, AxContextAlbum> albumsMap =
223 ModelService.getModel(AxContextAlbums.class).getAlbumsMap();
224 final Map<AxArtifactKey, AxTask> taskMap = ModelService.getModel(AxTasks.class).getTaskMap();
225 final Map<AxArtifactKey, AxPolicy> policyMap = ModelService.getModel(AxPolicies.class).getPolicyMap();
227 // replace the ModelService with the right concept definition
228 // this can get corrupted in case of deploying policies with duplicate concept keys
229 keyInfoMap.putAll(keyInfoMapToRetain);
230 schemasMap.putAll(schemaMapToRetain);
231 eventMap.putAll(eventMapToRetain);
232 albumsMap.putAll(albumMapToRetain);
233 taskMap.putAll(taskMapToRetain);
234 policyMap.putAll(policyMapToRetain);
236 keyInfoKeystoRemove.forEach(keyInfoMap::remove);
237 schemaKeystoRemove.forEach(schemasMap::remove);
238 eventKeystoRemove.forEach(eventMap::remove);
239 albumKeystoRemove.forEach(albumsMap::remove);
240 taskKeystoRemove.forEach(taskMap::remove);
241 policyKeystoRemove.forEach(policyMap::remove);
244 private void initiateApexEngineForPolicies(List<ToscaPolicy> policies)
245 throws ApexStarterException {
246 Map<ToscaConceptIdentifier, ApexMain> failedPoliciesMainMap = new LinkedHashMap<>();
247 for (ToscaPolicy policy : policies) {
248 String policyName = policy.getIdentifier().getName();
249 final StandardCoder standardCoder = new StandardCoder();
250 ToscaServiceTemplate toscaServiceTemplate = new ToscaServiceTemplate();
251 ToscaTopologyTemplate toscaTopologyTemplate = new ToscaTopologyTemplate();
252 toscaTopologyTemplate.setPolicies(List.of(Map.of(policyName, policy)));
253 toscaServiceTemplate.setToscaTopologyTemplate(toscaTopologyTemplate);
256 file = File.createTempFile(policyName, ".json");
257 standardCoder.encode(file, toscaServiceTemplate);
258 } catch (CoderException | IOException e) {
259 throw new ApexStarterException(e);
261 final String[] apexArgs = {"-p", file.getAbsolutePath()};
262 LOGGER.info("Starting apex engine for policy {}", policy.getIdentifier());
263 ApexMain apexMain = new ApexMain(apexArgs);
264 if (apexMain.isAlive()) {
265 apexMainMap.put(policy.getIdentifier(), apexMain);
267 failedPoliciesMainMap.put(policy.getIdentifier(), apexMain);
268 LOGGER.error("Execution of policy {} failed", policy.getIdentifier());
271 if (apexMainMap.isEmpty()) {
272 ModelService.clear();
273 ParameterService.clear();
274 throw new ApexStarterException("Apex Engine failed to start.");
275 } else if (failedPoliciesMainMap.size() > 0) {
276 updateModelAndParameterServices(failedPoliciesMainMap);
277 if (failedPoliciesMainMap.size() == policies.size()) {
278 throw new ApexStarterException("Updating the APEX engine with new policies failed.");
284 * Method to get the APEX engine statistics.
286 public List<AxEngineModel> getEngineStats() {
287 // engineStats from all the apexMain instances running individual tosca policies are combined here.
288 return apexMainMap.values().stream().filter(apexMain -> (null != apexMain && apexMain.isAlive()))
289 .flatMap(m -> m.getEngineStats().stream()).collect(Collectors.toList());
293 * Method to check whether the apex engine is running or not.
295 public boolean isApexEngineRunning() {
296 return apexMainMap.values().stream().anyMatch(apexMain -> (null != apexMain && apexMain.isAlive()));
300 * Method that return the list of running policies in the apex engine.
302 public List<ToscaConceptIdentifier> getRunningPolicies() {
303 return new ArrayList<>(apexMainMap.keySet());
307 * Method to shut down the apex engine.
309 public void shutdown() throws ApexStarterException {
311 LOGGER.debug("Shutting down apex engine.");
312 for (ApexMain apexMain : apexMainMap.values()) {
316 ModelService.clear();
317 ParameterService.clear();
318 } catch (final ApexException e) {
319 throw new ApexStarterException(e);