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