72987de0a788366988c404247cb822367ac4ffe6
[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 java.util.Map.Entry;
33 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
34 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
35 import org.onap.policy.apex.service.engine.main.ApexMain;
36 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
37 import org.onap.policy.common.utils.coder.CoderException;
38 import org.onap.policy.common.utils.coder.StandardCoder;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
40 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * This class instantiates the Apex Engine based on instruction from PAP.
46  *
47  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
48  */
49 public class ApexEngineHandler {
50     private static final String POLICY_TYPE_IMPL = "policy_type_impl";
51
52     private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
53
54     private ApexMain apexMain;
55
56     /**
57      * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
58      *
59      * @param policies the list of policies
60      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
61      */
62     public ApexEngineHandler(List<ToscaPolicy> policies)  throws ApexStarterException {
63         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
64         LOGGER.debug("Starting apex engine.");
65         try {
66             apexMain = new ApexMain(policyArgsMap);
67         } catch (ApexException e) {
68             throw new ApexStarterException(e);
69         }
70     }
71
72     /**
73      * Updates the Apex Engine with the policy model created from new list of policies.
74      *
75      * @param policies the list of policies
76      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
77      */
78     public void updateApexEngine(List<ToscaPolicy> policies) throws ApexStarterException {
79         if (null == apexMain || !apexMain.isAlive()) {
80             throw new ApexStarterException("Apex Engine not initialized.");
81         }
82         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
83         try {
84             apexMain.updateModel(policyArgsMap);
85         } catch (ApexException e) {
86             throw new ApexStarterException(e);
87         }
88     }
89
90     private Map<ToscaPolicyIdentifier, String[]> createPolicyArgsMap(List<ToscaPolicy> policies)
91         throws ApexStarterException {
92         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = new LinkedHashMap<>();
93         for (ToscaPolicy policy : policies) {
94             final StandardCoder standardCoder = new StandardCoder();
95             String policyModel = "";
96             String apexConfig;
97             JsonObject apexConfigJsonObject = new JsonObject();
98             try {
99                 for (Entry<String, Object> property : policy.getProperties().entrySet()) {
100                     JsonObject body = standardCoder.decode(standardCoder.encode(property.getValue()), JsonObject.class);
101                     if ("engineServiceParameters".equals(property.getKey())) {
102                         policyModel = standardCoder.encode(body.get(POLICY_TYPE_IMPL));
103                         body.remove(POLICY_TYPE_IMPL);
104                     }
105                     apexConfigJsonObject.add(property.getKey(), body);
106                 }
107                 apexConfig = standardCoder.encode(apexConfigJsonObject);
108             } catch (CoderException e) {
109                 throw new ApexStarterException(e);
110             }
111
112             final String modelFilePath = createFile(policyModel, "modelFile");
113
114             final String apexConfigFilePath = createFile(apexConfig, "apexConfigFile");
115             final String[] apexArgs = { "-c", apexConfigFilePath, "-m", modelFilePath };
116             policyArgsMap.put(policy.getIdentifier(), apexArgs);
117         }
118         return policyArgsMap;
119     }
120
121     /**
122      * Method to create the policy model file.
123      *
124      * @param fileContent the content of the file
125      * @param fileName the name of the file
126      * @throws ApexStarterException if the file creation failed
127      */
128     private String createFile(final String fileContent, final String fileName) throws ApexStarterException {
129         try {
130             final Path path = Files.createTempFile(fileName, ".json");
131             Files.write(path, fileContent.getBytes(StandardCharsets.UTF_8));
132             return path.toAbsolutePath().toString();
133         } catch (final IOException e) {
134             final String errorMessage = "error creating  from the properties received in PdpUpdate.";
135             LOGGER.error(errorMessage, e);
136             throw new ApexStarterException(errorMessage, e);
137         }
138     }
139
140     /**
141      * Method to get the APEX engine statistics.
142      */
143     public List<AxEngineModel> getEngineStats() {
144         List<AxEngineModel> engineStats = null;
145         if (null != apexMain && apexMain.isAlive()) {
146             engineStats = apexMain.getEngineStats();
147         }
148         return engineStats;
149     }
150
151     /**
152      * Method to check whether the apex engine is running or not.
153      */
154     public boolean isApexEngineRunning() {
155         return null != apexMain && apexMain.isAlive();
156     }
157
158     /**
159      * Method that return the list of running policies in the apex engine.
160      */
161     public List<ToscaPolicyIdentifier> getRunningPolicies() {
162         return new ArrayList<>(apexMain.getApexParametersMap().keySet());
163     }
164
165     /**
166      * Method to shut down the apex engine.
167      */
168     public void shutdown() throws ApexStarterException {
169         try {
170             LOGGER.debug("Shutting down apex engine.");
171             apexMain.shutdown();
172             apexMain = null;
173         } catch (final ApexException e) {
174             throw new ApexStarterException(e);
175         }
176     }
177 }