7aa663c58e354fd580d1155f010febf701c7e6ee
[policy/apex-pdp.git] /
1 /*-
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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.services.onappf.handler;
23
24 import java.io.File;
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;
31 import java.util.Map;
32 import java.util.Set;
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;
66
67 /**
68  * This class instantiates the Apex Engine based on instruction from PAP.
69  *
70  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
71  */
72 public class ApexEngineHandler {
73
74     private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
75
76     private Map<ToscaConceptIdentifier, ApexMain> apexMainMap = new LinkedHashMap<>();
77
78     /**
79      * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
80      *
81      * @param policies the list of policies
82      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
83      */
84     public ApexEngineHandler(List<ToscaPolicy> policies) throws ApexStarterException {
85         LOGGER.debug("Starting apex engine.");
86         initiateApexEngineForPolicies(policies);
87     }
88
89     /**
90      * Updates the Apex Engine with the policy model created from new list of policies.
91      *
92
93      * @param polsToDeploy list of policies to deploy which will be modified to remove running policies
94      * @param polsToUndeploy list of policies to undeploy which will be modified to remove policies not running
95      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
96      */
97     public void updateApexEngine(List<ToscaPolicy> polsToDeploy, List<ToscaConceptIdentifier> polsToUndeploy)
98             throws ApexStarterException {
99         Set<ToscaConceptIdentifier> runningPolicies = new HashSet<>(getRunningPolicies());
100         List<ToscaPolicy> policiesToDeploy = polsToDeploy;
101         policiesToDeploy.removeIf(p -> runningPolicies.contains(p.getIdentifier()));
102         List<ToscaConceptIdentifier> policiesToUnDeploy = polsToUndeploy;
103         policiesToUnDeploy.removeIf(p -> !runningPolicies.contains(p));
104         Map<ToscaConceptIdentifier, ApexMain> undeployedPoliciesMainMap = new LinkedHashMap<>();
105         policiesToUnDeploy.forEach(policyId -> {
106             ApexMain apexMain = apexMainMap.get(policyId);
107             try {
108                 apexMain.shutdown();
109                 undeployedPoliciesMainMap.put(policyId, apexMain);
110                 apexMainMap.remove(policyId);
111             } catch (ApexException e) {
112                 LOGGER.error("Shutting down policy {} failed", policyId, e);
113             }
114         });
115         if (!undeployedPoliciesMainMap.isEmpty() && !apexMainMap.isEmpty()) {
116             updateModelAndParameterServices(undeployedPoliciesMainMap);
117         }
118         if (!policiesToDeploy.isEmpty()) {
119             initiateApexEngineForPolicies(policiesToDeploy);
120         }
121         if (apexMainMap.isEmpty()) {
122             ModelService.clear();
123             ParameterService.clear();
124         }
125     }
126
127     /**
128      * Clear the corresponding items from ModelService and ParameterService.
129      *
130      * @param undeployedPoliciesMainMap the policies that are undeployed
131      */
132     private void updateModelAndParameterServices(Map<ToscaConceptIdentifier, ApexMain> undeployedPoliciesMainMap) {
133         Set<String> inputParamKeysToRetain = new HashSet<>();
134         Set<String> outputParamKeysToRetain = new HashSet<>();
135         List<TaskParameters> taskParametersToRetain = new ArrayList<>();
136         List<String> executorParamKeysToRetain = new ArrayList<>();
137         List<String> schemaParamKeysToRetain = new ArrayList<>();
138
139         Map<AxArtifactKey, AxKeyInfo> keyInfoMapToRetain = new HashMap<>();
140         Map<AxArtifactKey, AxContextSchema> schemaMapToRetain = new HashMap<>();
141         Map<AxArtifactKey, AxEvent> eventMapToRetain = new HashMap<>();
142         Map<AxArtifactKey, AxContextAlbum> albumMapToRetain = new HashMap<>();
143         Map<AxArtifactKey, AxTask> taskMapToRetain = new HashMap<>();
144         Map<AxArtifactKey, AxPolicy> policyMapToRetain = new HashMap<>();
145
146         apexMainMap.values().forEach(main -> {
147             inputParamKeysToRetain.addAll(main.getApexParameters().getEventInputParameters().keySet());
148             outputParamKeysToRetain.addAll(main.getApexParameters().getEventOutputParameters().keySet());
149             taskParametersToRetain.addAll(
150                 main.getApexParameters().getEngineServiceParameters().getEngineParameters().getTaskParameters());
151             executorParamKeysToRetain.addAll(main.getApexParameters().getEngineServiceParameters().getEngineParameters()
152                 .getExecutorParameterMap().keySet());
153             schemaParamKeysToRetain.addAll(main.getApexParameters().getEngineServiceParameters().getEngineParameters()
154                 .getContextParameters().getSchemaParameters().getSchemaHelperParameterMap().keySet());
155
156             AxPolicyModel policyModel = main.getActivator().getPolicyModel();
157             keyInfoMapToRetain.putAll(policyModel.getKeyInformation().getKeyInfoMap());
158             schemaMapToRetain.putAll(policyModel.getSchemas().getSchemasMap());
159             eventMapToRetain.putAll(policyModel.getEvents().getEventMap());
160             albumMapToRetain.putAll(policyModel.getAlbums().getAlbumsMap());
161             taskMapToRetain.putAll(policyModel.getTasks().getTaskMap());
162             policyMapToRetain.putAll(policyModel.getPolicies().getPolicyMap());
163         });
164         for (ApexMain main : undeployedPoliciesMainMap.values()) {
165             if (null != main.getApexParameters()) {
166                 handleParametersRemoval(inputParamKeysToRetain, outputParamKeysToRetain, taskParametersToRetain,
167                     executorParamKeysToRetain, schemaParamKeysToRetain, main);
168             }
169             if (null != main.getActivator() && null != main.getActivator().getPolicyModel()) {
170                 handleAxConceptsRemoval(keyInfoMapToRetain, schemaMapToRetain, eventMapToRetain, albumMapToRetain,
171                     taskMapToRetain, policyMapToRetain, main);
172             }
173         }
174     }
175
176     private void handleParametersRemoval(Set<String> inputParamKeysToRetain, Set<String> outputParamKeysToRetain,
177         List<TaskParameters> taskParametersToRetain, List<String> executorParamKeysToRetain,
178         List<String> schemaParamKeysToRetain, ApexMain main) {
179         ApexParameters existingParameters = ParameterService.get(ApexParameterConstants.MAIN_GROUP_NAME);
180         List<String> eventInputParamKeysToRemove = main.getApexParameters().getEventInputParameters().keySet().stream()
181             .filter(key -> !inputParamKeysToRetain.contains(key)).collect(Collectors.toList());
182         List<String> eventOutputParamKeysToRemove = main.getApexParameters().getEventOutputParameters().keySet()
183             .stream().filter(key -> !outputParamKeysToRetain.contains(key)).collect(Collectors.toList());
184         eventInputParamKeysToRemove.forEach(existingParameters.getEventInputParameters()::remove);
185         eventOutputParamKeysToRemove.forEach(existingParameters.getEventOutputParameters()::remove);
186         EngineParameters engineParameters = main.getApexParameters().getEngineServiceParameters().getEngineParameters();
187         final List<TaskParameters> taskParametersToRemove = engineParameters.getTaskParameters().stream()
188             .filter(taskParameter -> !taskParametersToRetain.contains(taskParameter)).collect(Collectors.toList());
189         final List<String> executorParamKeysToRemove = engineParameters.getExecutorParameterMap().keySet().stream()
190             .filter(key -> !executorParamKeysToRetain.contains(key)).collect(Collectors.toList());
191         final List<String> schemaParamKeysToRemove =
192             engineParameters.getContextParameters().getSchemaParameters().getSchemaHelperParameterMap().keySet()
193                 .stream().filter(key -> !schemaParamKeysToRetain.contains(key)).collect(Collectors.toList());
194         EngineParameters aggregatedEngineParameters =
195             existingParameters.getEngineServiceParameters().getEngineParameters();
196         aggregatedEngineParameters.getTaskParameters().removeAll(taskParametersToRemove);
197         executorParamKeysToRemove.forEach(aggregatedEngineParameters.getExecutorParameterMap()::remove);
198         schemaParamKeysToRemove.forEach(aggregatedEngineParameters.getContextParameters().getSchemaParameters()
199             .getSchemaHelperParameterMap()::remove);
200     }
201
202     private void handleAxConceptsRemoval(Map<AxArtifactKey, AxKeyInfo> keyInfoMapToRetain,
203         Map<AxArtifactKey, AxContextSchema> schemaMapToRetain, Map<AxArtifactKey, AxEvent> eventMapToRetain,
204         Map<AxArtifactKey, AxContextAlbum> albumMapToRetain, Map<AxArtifactKey, AxTask> taskMapToRetain,
205         Map<AxArtifactKey, AxPolicy> policyMapToRetain, ApexMain main) {
206         final AxPolicyModel policyModel = main.getActivator().getPolicyModel();
207         final List<AxArtifactKey> keyInfoKeystoRemove = policyModel.getKeyInformation().getKeyInfoMap().keySet()
208             .stream().filter(key -> !keyInfoMapToRetain.containsKey(key)).collect(Collectors.toList());
209         final List<AxArtifactKey> schemaKeystoRemove = policyModel.getSchemas().getSchemasMap().keySet().stream()
210             .filter(key -> !schemaMapToRetain.containsKey(key)).collect(Collectors.toList());
211         final List<AxArtifactKey> eventKeystoRemove = policyModel.getEvents().getEventMap().keySet().stream()
212             .filter(key -> !eventMapToRetain.containsKey(key)).collect(Collectors.toList());
213         final List<AxArtifactKey> albumKeystoRemove = policyModel.getAlbums().getAlbumsMap().keySet().stream()
214             .filter(key -> !albumMapToRetain.containsKey(key)).collect(Collectors.toList());
215         final List<AxArtifactKey> taskKeystoRemove = policyModel.getTasks().getTaskMap().keySet().stream()
216             .filter(key -> !taskMapToRetain.containsKey(key)).collect(Collectors.toList());
217         final List<AxArtifactKey> policyKeystoRemove = policyModel.getPolicies().getPolicyMap().keySet().stream()
218             .filter(key -> !policyMapToRetain.containsKey(key)).collect(Collectors.toList());
219
220         final Map<AxArtifactKey, AxKeyInfo> keyInfoMap = ModelService.getModel(AxKeyInformation.class).getKeyInfoMap();
221         final Map<AxArtifactKey, AxContextSchema> schemasMap =
222             ModelService.getModel(AxContextSchemas.class).getSchemasMap();
223         final Map<AxArtifactKey, AxEvent> eventMap = ModelService.getModel(AxEvents.class).getEventMap();
224         final Map<AxArtifactKey, AxContextAlbum> albumsMap =
225             ModelService.getModel(AxContextAlbums.class).getAlbumsMap();
226         final Map<AxArtifactKey, AxTask> taskMap = ModelService.getModel(AxTasks.class).getTaskMap();
227         final Map<AxArtifactKey, AxPolicy> policyMap = ModelService.getModel(AxPolicies.class).getPolicyMap();
228
229         // replace the ModelService with the right concept definition
230         // this can get corrupted in case of deploying policies with duplicate concept keys
231         keyInfoMap.putAll(keyInfoMapToRetain);
232         schemasMap.putAll(schemaMapToRetain);
233         eventMap.putAll(eventMapToRetain);
234         albumsMap.putAll(albumMapToRetain);
235         taskMap.putAll(taskMapToRetain);
236         policyMap.putAll(policyMapToRetain);
237
238         keyInfoKeystoRemove.forEach(keyInfoMap::remove);
239         schemaKeystoRemove.forEach(schemasMap::remove);
240         eventKeystoRemove.forEach(eventMap::remove);
241         albumKeystoRemove.forEach(albumsMap::remove);
242         taskKeystoRemove.forEach(taskMap::remove);
243         policyKeystoRemove.forEach(policyMap::remove);
244     }
245
246     private void initiateApexEngineForPolicies(List<ToscaPolicy> policies)
247         throws ApexStarterException {
248         Map<ToscaConceptIdentifier, ApexMain> failedPoliciesMainMap = new LinkedHashMap<>();
249         for (ToscaPolicy policy : policies) {
250             String policyName = policy.getIdentifier().getName();
251             final StandardCoder standardCoder = new StandardCoder();
252             ToscaServiceTemplate toscaServiceTemplate = new ToscaServiceTemplate();
253             ToscaTopologyTemplate toscaTopologyTemplate = new ToscaTopologyTemplate();
254             toscaTopologyTemplate.setPolicies(List.of(Map.of(policyName, policy)));
255             toscaServiceTemplate.setToscaTopologyTemplate(toscaTopologyTemplate);
256             File file;
257             try {
258                 file = File.createTempFile(policyName, ".json");
259                 standardCoder.encode(file, toscaServiceTemplate);
260             } catch (CoderException | IOException e) {
261                 throw new ApexStarterException(e);
262             }
263             final String[] apexArgs = {"-p", file.getAbsolutePath()};
264             LOGGER.info("Starting apex engine for policy {}", policy.getIdentifier());
265             ApexMain apexMain = new ApexMain(apexArgs);
266             if (apexMain.isAlive()) {
267                 apexMainMap.put(policy.getIdentifier(), apexMain);
268             } else {
269                 failedPoliciesMainMap.put(policy.getIdentifier(), apexMain);
270                 LOGGER.error("Execution of policy {} failed", policy.getIdentifier());
271             }
272         }
273         if (apexMainMap.isEmpty()) {
274             ModelService.clear();
275             ParameterService.clear();
276             throw new ApexStarterException("Apex Engine failed to start.");
277         } else if (failedPoliciesMainMap.size() > 0) {
278             updateModelAndParameterServices(failedPoliciesMainMap);
279             if (failedPoliciesMainMap.size() == policies.size()) {
280                 throw new ApexStarterException("Updating the APEX engine with new policies failed.");
281             }
282         }
283     }
284
285     /**
286      * Method to get the APEX engine statistics.
287      */
288     public List<AxEngineModel> getEngineStats() {
289         // engineStats from all the apexMain instances running individual tosca policies are combined here.
290         return apexMainMap.values().stream().filter(apexMain -> (null != apexMain && apexMain.isAlive()))
291             .flatMap(m -> m.getEngineStats().stream()).collect(Collectors.toList());
292     }
293
294     /**
295      * Method to check whether the apex engine is running or not.
296      */
297     public boolean isApexEngineRunning() {
298         return apexMainMap.values().stream().anyMatch(apexMain -> (null != apexMain && apexMain.isAlive()));
299     }
300
301     /**
302      * Method that return the list of running policies in the apex engine.
303      */
304     public List<ToscaConceptIdentifier> getRunningPolicies() {
305         return new ArrayList<>(apexMainMap.keySet());
306     }
307
308     /**
309      * Method to shut down the apex engine.
310      */
311     public void shutdown() throws ApexStarterException {
312         try {
313             LOGGER.debug("Shutting down apex engine.");
314             for (ApexMain apexMain : apexMainMap.values()) {
315                 apexMain.shutdown();
316             }
317             apexMainMap.clear();
318             ModelService.clear();
319             ParameterService.clear();
320         } catch (final ApexException e) {
321             throw new ApexStarterException(e);
322         }
323     }
324 }