1953939b7606008add21c91692e341795571d72b
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 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.service.engine.main.ApexMain;
34 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
35 import org.onap.policy.common.utils.coder.CoderException;
36 import org.onap.policy.common.utils.coder.StandardCoder;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * This class instantiates the Apex Engine based on instruction from PAP.
44  *
45  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
46  */
47 public class ApexEngineHandler {
48     private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
49
50     private ApexMain apexMain;
51
52     /**
53      * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
54      *
55      * @param policies the list of policies
56      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
57      */
58     public ApexEngineHandler(List<ToscaPolicy> policies)  throws ApexStarterException {
59         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = new LinkedHashMap<>();
60         for (ToscaPolicy policy : policies) {
61             Object properties = policy.getProperties().get("content");
62             final StandardCoder standardCoder = new StandardCoder();
63             String policyModel;
64             String apexConfig;
65             try {
66                 JsonObject body = standardCoder.decode(standardCoder.encode(properties), JsonObject.class);
67                 final JsonObject engineServiceParameters = body.get("engineServiceParameters").getAsJsonObject();
68                 policyModel = standardCoder.encode(engineServiceParameters.get("policy_type_impl"));
69                 engineServiceParameters.remove("policy_type_impl");
70                 apexConfig = standardCoder.encode(body);
71             } catch (final CoderException e) {
72                 throw new ApexStarterException(e);
73             }
74
75             final String modelFilePath = createFile(policyModel, "modelFile");
76
77             final String apexConfigFilePath = createFile(apexConfig, "apexConfigFile");
78             final String[] apexArgs = { "-c", apexConfigFilePath, "-m", modelFilePath };
79             policyArgsMap.put(policy.getIdentifier(), apexArgs);
80         }
81
82         LOGGER.debug("Starting apex engine.");
83         try {
84             apexMain = new ApexMain(policyArgsMap);
85         } catch (ApexException e) {
86             throw new ApexStarterException(e);
87         }
88     }
89
90     /**
91      * Method to create the policy model file.
92      *
93      * @param fileContent the content of the file
94      * @param fileName the name of the file
95      * @throws ApexStarterException if the file creation failed
96      */
97     private String createFile(final String fileContent, final String fileName) throws ApexStarterException {
98         try {
99             final Path path = Files.createTempFile(fileName, ".json");
100             Files.write(path, fileContent.getBytes(StandardCharsets.UTF_8));
101             return path.toAbsolutePath().toString();
102         } catch (final IOException e) {
103             final String errorMessage = "error creating  from the properties received in PdpUpdate.";
104             LOGGER.error(errorMessage, e);
105             throw new ApexStarterException(errorMessage, e);
106         }
107     }
108
109     /**
110      * Method to check whether the apex engine is running or not.
111      */
112     public boolean isApexEngineRunning() {
113         return null != apexMain && apexMain.isAlive();
114     }
115
116     /**
117      * Method that return the list of running policies in the apex engine.
118      */
119     public List<ToscaPolicyIdentifier> getRunningPolicies() {
120         return new ArrayList<>(apexMain.getApexParametersMap().keySet());
121     }
122
123     /**
124      * Method to shut down the apex engine.
125      */
126     public void shutdown() throws ApexStarterException {
127         try {
128             LOGGER.debug("Shutting down apex engine.");
129             apexMain.shutdown();
130             apexMain = null;
131         } catch (final ApexException e) {
132             throw new ApexStarterException(e);
133         }
134     }
135 }