lower code smells
[appc.git] / appc-oam / appc-oam-bundle / src / main / java / org / onap / appc / oam / AppcOam.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications (C) 2018 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.oam;
27
28 import com.att.eelf.configuration.EELFLogger;
29 import com.att.eelf.configuration.EELFManager;
30 import com.google.common.util.concurrent.Futures;
31 import com.google.common.util.concurrent.ListenableFuture;
32 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
33 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
34 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
35 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
36 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcOamService;
37 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.AppcState;
38 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateInput;
39 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput;
40 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutputBuilder;
41 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsInput;
42 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutput;
43 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetMetricsOutputBuilder;
44 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput;
45 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput;
46 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutputBuilder;
47 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput;
48 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput;
49 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutputBuilder;
50 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput;
51 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput;
52 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutputBuilder;
53 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput;
54 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput;
55 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutputBuilder;
56 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader;
57 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.Metrics;
58 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.MetricsBuilder;
59 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValues;
60 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.get.metrics.output.metrics.KpiValuesBuilder;
61 import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status;
62 import org.opendaylight.yangtools.yang.common.RpcError;
63 import org.opendaylight.yangtools.yang.common.RpcResult;
64 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
65 import org.onap.appc.exceptions.APPCException;
66 import org.onap.appc.i18n.Msg;
67 import org.onap.appc.metricservice.MetricRegistry;
68 import org.onap.appc.metricservice.MetricService;
69 import org.onap.appc.metricservice.metric.Metric;
70 import org.onap.appc.oam.processor.OamMmodeProcessor;
71 import org.onap.appc.oam.processor.OamRestartProcessor;
72 import org.onap.appc.oam.processor.OamStartProcessor;
73 import org.onap.appc.oam.processor.OamStopProcessor;
74 import org.onap.appc.oam.util.AsyncTaskHelper;
75 import org.onap.appc.oam.util.ConfigurationHelper;
76 import org.onap.appc.oam.util.OperationHelper;
77 import org.onap.appc.oam.util.StateHelper;
78 import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader.AppcOperation;
79
80 import java.util.ArrayList;
81 import java.util.List;
82 import java.util.Map;
83
84 /**
85  * RPC class of APP-C OAM API.
86  * <p>Implement all the RPCs defined in AppcOamService through yang model definition.
87  * <p>All RPC methods' JAVADOC are using "inheritDoc" to use the description from the yang model file.
88  */
89 public class AppcOam implements AutoCloseable, AppcOamService {
90     /**
91      * Invalid state message format with fliexible operation, appc name and state values
92      */
93     public static final String INVALID_STATE_MESSAGE_FORMAT = "%s API is not allowed when %s is in the %s state.";
94
95     private final EELFLogger logger = EELFManager.getInstance().getLogger(AppcOam.class);
96
97     private boolean isMetricEnabled = false;
98
99     /**
100      * Represents our RPC implementation registration
101      */
102     private BindingAwareBroker.RpcRegistration<AppcOamService> rpcRegistration;
103
104
105     /**
106      * The yang rpc names with value mapping to AppcOperation
107      */
108     public enum RPC {
109         maintenance_mode(AppcOperation.MaintenanceMode),
110         start(AppcOperation.Start),
111         stop(AppcOperation.Stop),
112         restart(AppcOperation.Restart);
113
114         AppcOperation appcOperation;
115
116         RPC(AppcOperation appcOperation) {
117             this.appcOperation = appcOperation;
118         }
119
120         public AppcOperation getAppcOperation() {
121             return appcOperation;
122         }
123     }
124
125     private AsyncTaskHelper asyncTaskHelper;
126     private ConfigurationHelper configurationHelper;
127     private OperationHelper operationHelper;
128     private StateHelper stateHelper;
129
130     /**
131      * APP-C OAM contructor
132      *
133      * @param dataBroker                  object of The ODL data store broker. Provides access to a conceptual data
134      *                                    tree store
135      *                                    and also provides the ability to subscribe for changes to data under a
136      *                                    given branch
137      *                                    of the tree. Not used in this class.
138      * @param notificationPublishService object of ODL Notification Service that provides publish/subscribe
139      *                                    capabilities for YANG modeled notifications. Not used in this class.
140      * @param rpcProviderRegistry         object of RpcProviderResigstry. Used to register our RPCs.
141      */
142     @SuppressWarnings({"unused", "nls"})
143     public AppcOam(DataBroker dataBroker,
144                    NotificationPublishService notificationPublishService,
145                    RpcProviderRegistry rpcProviderRegistry) {
146
147         configurationHelper = new ConfigurationHelper(logger);
148         String appName = configurationHelper.getAppcName();
149         logger.info(Msg.COMPONENT_INITIALIZING, appName, "oam");
150
151         if (rpcProviderRegistry != null) {
152             rpcRegistration = rpcProviderRegistry.addRpcImplementation(AppcOamService.class, this);
153         }
154
155         isMetricEnabled = configurationHelper.isMetricEnabled();
156
157         initHelpers();
158
159         logger.info(Msg.COMPONENT_INITIALIZED, appName, "oam");
160     }
161
162     /**
163      * Initialize helper classes.
164      * <p>Note: ConfigurationHelper initializetion is in included here
165      * because it is needed for extracting the AppName used in the debug logs within the constructor.
166      */
167     private void initHelpers() {
168         operationHelper = new OperationHelper();
169         asyncTaskHelper = new AsyncTaskHelper(logger);
170         stateHelper = new StateHelper(logger, configurationHelper);
171     }
172
173     /**
174      * Implements the close of the service
175      *
176      * @see AutoCloseable#close()
177      */
178     @SuppressWarnings("nls")
179     @Override
180     public void close() throws Exception {
181         String appName = configurationHelper.getAppcName();
182         logger.info(Msg.COMPONENT_TERMINATING, appName, "oam");
183
184         asyncTaskHelper.close();
185
186         if (rpcRegistration != null) {
187             rpcRegistration.close();
188         }
189         logger.info(Msg.COMPONENT_TERMINATED, appName, "oam");
190     }
191
192     /**
193      * {@inheritDoc}
194      */
195     @Override
196     public ListenableFuture<RpcResult<GetMetricsOutput>> getMetrics(GetMetricsInput getMetricsInput) {
197
198         if (!isMetricEnabled) {
199             logger.error("Metric Service not enabled returning failure");
200             RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput>
201                     status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not enabled").build();
202             return Futures.immediateFuture(result);
203         }
204
205         MetricService metricService;
206         try {
207             metricService = operationHelper.getService(MetricService.class);
208         } catch (APPCException e) {
209             logger.error("MetricService not found", e);
210             RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput>
211                     status(false).withError(RpcError.ErrorType.APPLICATION, "Metric Service not found").build();
212             return Futures.immediateFuture(result);
213         }
214
215         Map<String, MetricRegistry> allMetricRegitry = metricService.getAllRegistry();
216         if (allMetricRegitry == null || allMetricRegitry.isEmpty()) {
217             logger.error("No metrics registered returning failure");
218             RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput>
219                     status(false).withError(RpcError.ErrorType.APPLICATION, "No metrics Registered").build();
220             return Futures.immediateFuture(result);
221         }
222
223         List<Metrics> metricsList = new ArrayList<>();
224
225         logger.debug("Iterating metric registry list");
226         for (MetricRegistry metricRegistry : allMetricRegitry.values()) {
227             logger.debug("Iterating metric registry :" + metricRegistry.toString());
228             Metric[] metrics = metricRegistry.metrics();
229             if (metrics != null && metrics.length > 0) {
230                 logger.debug("Iterating though metrics in registry");
231                 for (Metric metric : metrics) {
232                     logger.debug("Iterating though metrics: " + metric.name());
233                     MetricsBuilder metricsBuilder = new MetricsBuilder();
234                     metricsBuilder.setKpiName(metric.name());
235                     metricsBuilder.setLastResetTime(metric.getLastModified());
236                     List<KpiValues> kpiList = new ArrayList<>();
237                     Map<String, String> metricsOutput = metric.getMetricsOutput();
238                     for (Map.Entry<String, String> kpi : metricsOutput.entrySet()) {
239                         KpiValuesBuilder kpiValuesBuilder = new KpiValuesBuilder();
240                         kpiValuesBuilder.setName(kpi.getKey());
241                         kpiValuesBuilder.setValue(kpi.getValue());
242                         kpiList.add(kpiValuesBuilder.build());
243                     }
244                     metricsBuilder.setKpiValues(kpiList);
245                     metricsList.add(metricsBuilder.build());
246                 }
247             }
248         }
249
250         GetMetricsOutputBuilder outputBuilder = new GetMetricsOutputBuilder();
251         outputBuilder.setMetrics(metricsList);
252         RpcResult<GetMetricsOutput> result = RpcResultBuilder.<GetMetricsOutput>
253                 status(true).withResult(outputBuilder.build()).build();
254         return Futures.immediateFuture(result);
255     }
256
257     /**
258      * {@inheritDoc}
259      */
260     @Override
261     public ListenableFuture<RpcResult<StopOutput>> stop(StopInput stopInput) {
262         logger.debug("Entering Stop with Input : " + stopInput);
263         final CommonHeader commonHeader = stopInput.getCommonHeader();
264
265         OamStopProcessor oamStopProcessor =
266                 getOamStopProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
267         Status status = oamStopProcessor.processRequest(stopInput);
268
269         StopOutputBuilder stopOutputBuilder = new StopOutputBuilder();
270         stopOutputBuilder.setStatus(status);
271         stopOutputBuilder.setCommonHeader(commonHeader);
272         return RpcResultBuilder.success(stopOutputBuilder.build()).buildFuture();
273     }
274
275     /**
276      * {@inheritDoc}
277      */
278     @Override
279     public ListenableFuture<RpcResult<RestartOutput>> restart(RestartInput input) {
280         logger.debug("Entering restart with Input : " + input);
281         final CommonHeader commonHeader = input.getCommonHeader();
282
283         OamRestartProcessor oamRestartProcessor =
284                 getOamRestartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
285         Status status = oamRestartProcessor.processRequest(input);
286
287         RestartOutputBuilder restartOutputBuilder = new RestartOutputBuilder();
288         restartOutputBuilder.setStatus(status);
289         restartOutputBuilder.setCommonHeader(commonHeader);
290
291         return RpcResultBuilder.success(restartOutputBuilder.build()).buildFuture();
292     }
293
294     /**
295      * {@inheritDoc}
296      */
297     @Override
298     public ListenableFuture<RpcResult<MaintenanceModeOutput>> maintenanceMode(MaintenanceModeInput maintenanceModeInput) {
299         logger.debug("Entering MaintenanceMode with Input : " + maintenanceModeInput);
300         final CommonHeader commonHeader = maintenanceModeInput.getCommonHeader();
301
302         OamMmodeProcessor oamMmodeProcessor =
303                 getOamMmodeProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
304         Status status = oamMmodeProcessor.processRequest(maintenanceModeInput);
305
306         MaintenanceModeOutputBuilder maintenanceModeOutputBuilder = new MaintenanceModeOutputBuilder();
307         maintenanceModeOutputBuilder.setStatus(status);
308         maintenanceModeOutputBuilder.setCommonHeader(commonHeader);
309         return RpcResultBuilder.success(maintenanceModeOutputBuilder.build()).buildFuture();
310     }
311
312     /**
313      * {@inheritDoc}
314      */
315     @Override
316     public ListenableFuture<RpcResult<GetAppcStateOutput>> getAppcState(GetAppcStateInput getAppcStateInput) {
317         AppcState appcState = stateHelper.getCurrentOamYangState();
318
319         GetAppcStateOutputBuilder builder = new GetAppcStateOutputBuilder();
320         builder.setState(appcState);
321         return RpcResultBuilder.success(builder.build()).buildFuture();
322     }
323
324     /**
325      * {@inheritDoc}
326      */
327     @Override
328     public ListenableFuture<RpcResult<StartOutput>> start(StartInput startInput) {
329         logger.debug("Input received : " + startInput);
330         final CommonHeader commonHeader = startInput.getCommonHeader();
331
332         OamStartProcessor oamStartProcessor =
333                 getOamStartProcessor(logger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
334         Status status = oamStartProcessor.processRequest(startInput);
335
336         StartOutputBuilder startOutputBuilder = new StartOutputBuilder();
337         startOutputBuilder.setStatus(status);
338         startOutputBuilder.setCommonHeader(commonHeader);
339         StartOutput startOutput = startOutputBuilder.build();
340         return RpcResultBuilder.success(startOutput).buildFuture();
341     }
342
343     protected OamStartProcessor getOamStartProcessor(EELFLogger eelfLogger,
344             ConfigurationHelper configurationHelper,
345             StateHelper stateHelper,
346             AsyncTaskHelper asyncTaskHelper,
347             OperationHelper operationHelper) {
348         return new OamStartProcessor(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
349     }
350
351     protected OamStopProcessor getOamStopProcessor(EELFLogger eelfLogger,
352             ConfigurationHelper configurationHelper,
353             StateHelper stateHelper,
354             AsyncTaskHelper asyncTaskHelper,
355             OperationHelper operationHelper) {
356         return new OamStopProcessor(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
357     }
358
359     protected OamRestartProcessor getOamRestartProcessor(EELFLogger eelfLogger,
360             ConfigurationHelper configurationHelper,
361             StateHelper stateHelper,
362             AsyncTaskHelper asyncTaskHelper,
363             OperationHelper operationHelper) {
364         return new OamRestartProcessor(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
365     }
366
367     protected OamMmodeProcessor getOamMmodeProcessor(EELFLogger eelfLogger,
368             ConfigurationHelper configurationHelper,
369             StateHelper stateHelper,
370             AsyncTaskHelper asyncTaskHelper,
371             OperationHelper operationHelper) {
372         return new OamMmodeProcessor(eelfLogger, configurationHelper, stateHelper, asyncTaskHelper, operationHelper);
373     }
374 }