8150ff9c5eddf7c2b5e7ec0b9d7706f9a2c79788
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.services.onappf.handler;
22
23 import com.google.gson.JsonObject;
24 import java.io.IOException;
25 import java.nio.charset.StandardCharsets;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.util.ArrayList;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
33 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
34 import org.onap.policy.apex.service.engine.main.ApexMain;
35 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * This class instantiates the Apex Engine based on instruction from PAP.
45  *
46  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
47  */
48 public class ApexEngineHandler {
49     private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
50
51     private ApexMain apexMain;
52
53     /**
54      * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
55      *
56      * @param policies the list of policies
57      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
58      */
59     public ApexEngineHandler(List<ToscaPolicy> policies)  throws ApexStarterException {
60         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
61         LOGGER.debug("Starting apex engine.");
62         try {
63             apexMain = new ApexMain(policyArgsMap);
64         } catch (ApexException e) {
65             throw new ApexStarterException(e);
66         }
67     }
68
69     /**
70      * Updates the Apex Engine with the policy model created from new list of policies.
71      *
72      * @param policies the list of policies
73      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
74      */
75     public void updateApexEngine(List<ToscaPolicy> policies) throws ApexStarterException {
76         if (null == apexMain || !apexMain.isAlive()) {
77             throw new ApexStarterException("Apex Engine not initialized.");
78         }
79         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
80         try {
81             apexMain.updateModel(policyArgsMap);
82         } catch (ApexException e) {
83             throw new ApexStarterException(e);
84         }
85     }
86
87     private Map<ToscaPolicyIdentifier, String[]> createPolicyArgsMap(List<ToscaPolicy> policies)
88         throws ApexStarterException {
89         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = new LinkedHashMap<>();
90         for (ToscaPolicy policy : policies) {
91             Object properties = policy.getProperties().get("content");
92             final StandardCoder standardCoder = new StandardCoder();
93             String policyModel;
94             String apexConfig;
95             try {
96                 JsonObject body = standardCoder.decode(standardCoder.encode(properties), JsonObject.class);
97                 final JsonObject engineServiceParameters = body.get("engineServiceParameters").getAsJsonObject();
98                 policyModel = standardCoder.encode(engineServiceParameters.get("policy_type_impl"));
99                 engineServiceParameters.remove("policy_type_impl");
100                 apexConfig = standardCoder.encode(body);
101             } catch (final CoderException e) {
102                 throw new ApexStarterException(e);
103             }
104
105             final String modelFilePath = createFile(policyModel, "modelFile");
106
107             final String apexConfigFilePath = createFile(apexConfig, "apexConfigFile");
108             final String[] apexArgs = { "-c", apexConfigFilePath, "-m", modelFilePath };
109             policyArgsMap.put(policy.getIdentifier(), apexArgs);
110         }
111         return policyArgsMap;
112     }
113
114     /**
115      * Method to create the policy model file.
116      *
117      * @param fileContent the content of the file
118      * @param fileName the name of the file
119      * @throws ApexStarterException if the file creation failed
120      */
121     private String createFile(final String fileContent, final String fileName) throws ApexStarterException {
122         try {
123             final Path path = Files.createTempFile(fileName, ".json");
124             Files.write(path, fileContent.getBytes(StandardCharsets.UTF_8));
125             return path.toAbsolutePath().toString();
126         } catch (final IOException e) {
127             final String errorMessage = "error creating  from the properties received in PdpUpdate.";
128             LOGGER.error(errorMessage, e);
129             throw new ApexStarterException(errorMessage, e);
130         }
131     }
132
133     /**
134      * Method to get the APEX engine statistics.
135      */
136     public List<AxEngineModel> getEngineStats() {
137         List<AxEngineModel> engineStats = null;
138         if (null != apexMain && apexMain.isAlive()) {
139             engineStats = apexMain.getEngineStats();
140         }
141         return engineStats;
142     }
143
144     /**
145      * Method to check whether the apex engine is running or not.
146      */
147     public boolean isApexEngineRunning() {
148         return null != apexMain && apexMain.isAlive();
149     }
150
151     /**
152      * Method that return the list of running policies in the apex engine.
153      */
154     public List<ToscaPolicyIdentifier> getRunningPolicies() {
155         return new ArrayList<>(apexMain.getApexParametersMap().keySet());
156     }
157
158     /**
159      * Method to shut down the apex engine.
160      */
161     public void shutdown() throws ApexStarterException {
162         try {
163             LOGGER.debug("Shutting down apex engine.");
164             apexMain.shutdown();
165             apexMain = null;
166         } catch (final ApexException e) {
167             throw new ApexStarterException(e);
168         }
169     }
170 }