APEX standalone support for ToscaPolicy format
[policy/apex-pdp.git] / services / services-onappf / src / main / java / org / onap / policy / apex / services / onappf / handler / ApexEngineHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2020 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.LinkedHashMap;
28 import java.util.List;
29 import java.util.Map;
30 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
31 import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
32 import org.onap.policy.apex.service.engine.main.ApexMain;
33 import org.onap.policy.apex.services.onappf.exception.ApexStarterException;
34 import org.onap.policy.common.utils.coder.CoderException;
35 import org.onap.policy.common.utils.coder.StandardCoder;
36 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
37 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;
38 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
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
50     private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class);
51
52     private ApexMain apexMain;
53
54     /**
55      * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine.
56      *
57      * @param policies the list of policies
58      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
59      */
60     public ApexEngineHandler(List<ToscaPolicy> policies)  throws ApexStarterException {
61         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
62         LOGGER.debug("Starting apex engine.");
63         try {
64             apexMain = new ApexMain(policyArgsMap);
65         } catch (ApexException e) {
66             throw new ApexStarterException(e);
67         }
68     }
69
70     /**
71      * Updates the Apex Engine with the policy model created from new list of policies.
72      *
73      * @param policies the list of policies
74      * @throws ApexStarterException if the apex engine instantiation failed using the policies passed
75      */
76     public void updateApexEngine(List<ToscaPolicy> policies) throws ApexStarterException {
77         if (null == apexMain || !apexMain.isAlive()) {
78             throw new ApexStarterException("Apex Engine not initialized.");
79         }
80         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = createPolicyArgsMap(policies);
81         try {
82             apexMain.updateModel(policyArgsMap);
83         } catch (ApexException e) {
84             throw new ApexStarterException(e);
85         }
86     }
87
88     private Map<ToscaPolicyIdentifier, String[]> createPolicyArgsMap(List<ToscaPolicy> policies)
89         throws ApexStarterException {
90         Map<ToscaPolicyIdentifier, String[]> policyArgsMap = new LinkedHashMap<>();
91         for (ToscaPolicy policy : policies) {
92             String policyName = policy.getIdentifier().getName();
93             final StandardCoder standardCoder = new StandardCoder();
94             ToscaServiceTemplate toscaServiceTemplate = new ToscaServiceTemplate();
95             ToscaTopologyTemplate toscaTopologyTemplate = new ToscaTopologyTemplate();
96             toscaTopologyTemplate.setPolicies(List.of(Map.of(policyName, policy)));
97             toscaServiceTemplate.setToscaTopologyTemplate(toscaTopologyTemplate);
98             File file;
99             try {
100                 file = File.createTempFile(policyName, ".json");
101                 standardCoder.encode(file, toscaServiceTemplate);
102             } catch (CoderException | IOException e) {
103                 throw new ApexStarterException(e);
104             }
105             final String[] apexArgs = {"-p", file.getAbsolutePath()};
106             policyArgsMap.put(policy.getIdentifier(), apexArgs);
107         }
108         return policyArgsMap;
109     }
110
111     /**
112      * Method to get the APEX engine statistics.
113      */
114     public List<AxEngineModel> getEngineStats() {
115         List<AxEngineModel> engineStats = null;
116         if (null != apexMain && apexMain.isAlive()) {
117             engineStats = apexMain.getEngineStats();
118         }
119         return engineStats;
120     }
121
122     /**
123      * Method to check whether the apex engine is running or not.
124      */
125     public boolean isApexEngineRunning() {
126         return null != apexMain && apexMain.isAlive();
127     }
128
129     /**
130      * Method that return the list of running policies in the apex engine.
131      */
132     public List<ToscaPolicyIdentifier> getRunningPolicies() {
133         return new ArrayList<>(apexMain.getApexParametersMap().keySet());
134     }
135
136     /**
137      * Method to shut down the apex engine.
138      */
139     public void shutdown() throws ApexStarterException {
140         try {
141             LOGGER.debug("Shutting down apex engine.");
142             apexMain.shutdown();
143             apexMain = null;
144         } catch (final ApexException e) {
145             throw new ApexStarterException(e);
146         }
147     }
148 }