Add github workflow to trigger weekly performance tests
[policy/apex-pdp.git] / services / services-engine / src / main / java / org / onap / policy / apex / service / parameters / ApexParameterHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2022 Nordix Foundation.
5  *  Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved.
6  *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.service.parameters;
25
26 import com.google.gson.GsonBuilder;
27 import com.google.gson.JsonArray;
28 import com.google.gson.JsonElement;
29 import com.google.gson.JsonObject;
30 import java.nio.file.Files;
31 import java.nio.file.Paths;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Optional;
35 import org.onap.policy.apex.core.engine.EngineParameters;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments;
38 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters;
39 import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJsonAdapter;
40 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJsonAdapter;
41 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters;
42 import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJsonAdapter;
43 import org.onap.policy.common.parameters.ParameterException;
44 import org.onap.policy.common.parameters.ParameterService;
45 import org.onap.policy.common.parameters.ValidationResult;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
51
52 /**
53  * This class handles reading, parsing and validating of Apex parameters from JSON files.
54  *
55  * @author Liam Fallon (liam.fallon@ericsson.com)
56  */
57 public class ApexParameterHandler {
58     private static final String EVENT_OUTPUT_PARAMETERS = "eventOutputParameters";
59
60     private static final String EVENT_INPUT_PARAMETERS = "eventInputParameters";
61
62     private static final String ENGINE_SERVICE_PARAMETERS = "engineServiceParameters";
63
64     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexParameterHandler.class);
65
66     private static final String POLICY_TYPE_IMPL = "policy_type_impl";
67     private static final String APEX_POLICY_MODEL = "apexPolicyModel";
68     private static final String METADATA_SET = "metadataSet";
69
70     private String policyModel;
71     private String apexConfig;
72
73     /**
74      * Read the parameters from the parameter file.
75      *
76      * @param arguments the arguments passed to Apex
77      * @return the parameters read from the configuration file
78      * @throws ParameterException on parameter exceptions
79      */
80     public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException {
81
82         ApexParameters parameters = null;
83         String toscaPolicyFilePath = arguments.getToscaPolicyFilePath();
84         // Read the parameters
85         try {
86             parseConfigAndModel(toscaPolicyFilePath);
87             // Register the adapters for our carrier technologies and event protocols with GSON
88             // @formatter:off
89             final var gson = new GsonBuilder()
90                 .registerTypeAdapter(EngineParameters.class,
91                     new EngineServiceParametersJsonAdapter())
92                 .registerTypeAdapter(CarrierTechnologyParameters.class,
93                     new CarrierTechnologyParametersJsonAdapter())
94                 .registerTypeAdapter(EventProtocolParameters.class,
95                     new EventProtocolParametersJsonAdapter())
96                 .create();
97             // @formatter:on
98             parameters = gson.fromJson(apexConfig, ApexParameters.class);
99         } catch (final Exception e) {
100             final String errorMessage = "error reading parameters from \"" + toscaPolicyFilePath + "\"\n" + "("
101                 + e.getClass().getSimpleName() + "):" + e.getMessage();
102             throw new ParameterException(errorMessage, e);
103         }
104
105         // The JSON processing returns null if there is an empty file
106         if (parameters == null) {
107             final String errorMessage = "no parameters found in \"" + toscaPolicyFilePath + "\"";
108             throw new ParameterException(errorMessage);
109         }
110
111         if (null != parameters.getEngineServiceParameters()) {
112             parameters.getEngineServiceParameters().setPolicyModel(policyModel);
113         }
114
115         // Validate the parameters
116         final ValidationResult validationResult = parameters.validate();
117         if (!validationResult.isValid()) {
118             String returnMessage = "validation error(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
119             returnMessage += validationResult.getResult();
120             throw new ParameterException(returnMessage);
121         }
122
123         if (!validationResult.isClean()) {
124             String returnMessage = "validation messages(s) on parameters from \"" + toscaPolicyFilePath + "\"\n";
125             returnMessage += validationResult.getResult();
126
127             LOGGER.info(returnMessage);
128         }
129
130         return parameters;
131     }
132
133     /**
134      * Register all the incoming parameters with the parameter service.
135      *
136      * @param parameters The parameters to register
137      */
138     public void registerParameters(ApexParameters parameters) {
139         ParameterService.register(parameters);
140         ParameterService.register(parameters.getEngineServiceParameters());
141         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters());
142         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters());
143         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
144             .getSchemaParameters());
145         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
146             .getDistributorParameters());
147         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
148             .getLockManagerParameters());
149         ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()
150             .getPersistorParameters());
151     }
152
153     private void parseConfigAndModel(final String toscaPolicyFilePath) throws ApexException {
154         policyModel = null;
155         apexConfig = null;
156         final var standardCoder = new StandardCoder();
157         var apexConfigJsonObject = new JsonObject();
158         try {
159             var toscaServiceTemplate = standardCoder
160                 .decode(Files.readString(Paths.get(toscaPolicyFilePath)), ToscaServiceTemplate.class);
161             for (Entry<String, Object> property : toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
162                 .entrySet().iterator().next().getValue().getProperties().entrySet()) {
163                 JsonElement body = null;
164                 if ("javaProperties".equals(property.getKey())) {
165                     body = standardCoder.convert(property.getValue(), JsonArray.class);
166                 } else if (EVENT_INPUT_PARAMETERS.equals(property.getKey())
167                     || ENGINE_SERVICE_PARAMETERS.equals(property.getKey())
168                     || EVENT_OUTPUT_PARAMETERS.equals(property.getKey())) {
169                     body = standardCoder.convert(property.getValue(), JsonObject.class);
170                     if (ENGINE_SERVICE_PARAMETERS.equals(property.getKey())) {
171                         policyModel = extractPolicyModel(standardCoder, body);
172                     }
173                 }
174                 apexConfigJsonObject.add(property.getKey(), body);
175             }
176             apexConfig = standardCoder.encode(apexConfigJsonObject);
177
178             // populate policyModel from metadata if present
179             Optional<Map<String, Object>> metadata =
180                 Optional.ofNullable(toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0)
181                     .entrySet().iterator().next().getValue().getMetadata());
182             if (metadata.isPresent() && metadata.get().containsKey(METADATA_SET)) {
183                 JsonElement body = standardCoder.convert(metadata.get(), JsonObject.class);
184                 policyModel = extractPolicyModel(standardCoder, body);
185             }
186         } catch (Exception e) {
187             throw new ApexException("Parsing config and model from the tosca policy failed.", e);
188         }
189     }
190
191     private String extractPolicyModel(StandardCoder standardCoder, JsonElement body) throws CoderException {
192         JsonElement policyTypeImplObject = null;
193         // Check for "policy_type_impl, if not present check for "metadataSet"
194         if (body.getAsJsonObject().has(POLICY_TYPE_IMPL)) {
195             policyTypeImplObject = ((JsonObject) body).get(POLICY_TYPE_IMPL);
196         } else if (body.getAsJsonObject().has(METADATA_SET))  {
197             policyTypeImplObject = ((JsonObject) body).get(METADATA_SET);
198         }
199         if (null == policyTypeImplObject) {
200             return null;
201         }
202
203         // "policy_type_impl" found
204         if (policyTypeImplObject instanceof JsonObject) {
205
206             // Check for "apexPolicyModel", this is used to encapsulate policy models sometimes
207             JsonElement policyModelObject = ((JsonObject) policyTypeImplObject).get(APEX_POLICY_MODEL);
208
209             if (policyModelObject != null) {
210                 // Policy model encased in an "apexPolicyModel" object
211                 return standardCoder.encode(policyModelObject);
212             } else {
213                 // No encasement
214                 return standardCoder.encode(policyTypeImplObject);
215             }
216         } else {
217             return policyTypeImplObject.getAsString();
218         }
219     }
220 }