[STAGING] Add build profiles
[sdnc/core.git] / sliapi / provider / src / main / java / org / openecomp / sdnc / sliapi / sliapiProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              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  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.sdnc.sliapi;
23
24 import java.util.Enumeration;
25 import java.util.LinkedList;
26 import java.util.Properties;
27 import java.util.concurrent.Future;
28
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
31 import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker;
32 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
33 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
34 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
35 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
36 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
37 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
38 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
39 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
40 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.ExecuteGraphInput;
41 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.ExecuteGraphInput.Mode;
42 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.ExecuteGraphInputBuilder;
43 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.ExecuteGraphOutput;
44 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.ExecuteGraphOutputBuilder;
45 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.HealthcheckOutput;
46 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.HealthcheckOutputBuilder;
47 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.SLIAPIService;
48 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.TestResults;
49 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.execute.graph.input.SliParameter;
50 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.test.results.TestResult;
51 import org.opendaylight.yang.gen.v1.org.openecomp.sdnc.sliapi.rev161110.test.results.TestResultBuilder;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
60 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
66 import org.openecomp.sdnc.sli.provider.SvcLogicService;
67 import org.osgi.framework.BundleContext;
68 import org.osgi.framework.FrameworkUtil;
69 import org.osgi.framework.ServiceReference;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 import com.google.common.util.concurrent.Futures;
74
75
76 /**
77  * Defines a base implementation for your provider. This class extends from a helper class
78  * which provides storage for the most commonly used components of the MD-SAL. Additionally the
79  * base class provides some basic logging and initialization / clean up methods.
80  *
81  * To use this, copy and paste (overwrite) the following method into the TestApplicationProviderModule
82  * class which is auto generated under src/main/java in this project
83  * (created only once during first compilation):
84  *
85  * <pre>
86
87     @Override
88     public java.lang.AutoCloseable createInstance() {
89
90          final sliapiProvider provider = new sliapiProvider();
91          provider.setDataBroker( getDataBrokerDependency() );
92          provider.setNotificationService( getNotificationServiceDependency() );
93          provider.setRpcRegistry( getRpcRegistryDependency() );
94          provider.initialize();
95          return new AutoCloseable() {
96
97             @Override
98             public void close() throws Exception {
99                 //TODO: CLOSE ANY REGISTRATION OBJECTS CREATED USING ABOVE BROKER/NOTIFICATION
100                 //SERVIE/RPC REGISTRY
101                 provider.close();
102             }
103         };
104     }
105
106
107     </pre>
108  */
109 public class sliapiProvider implements AutoCloseable, SLIAPIService{
110
111     private final Logger LOG = LoggerFactory.getLogger( sliapiProvider.class );
112     private final String appName = "slitester";
113
114     protected DataBroker dataBroker;
115     protected DOMDataBroker domDataBroker;
116     protected NotificationProviderService notificationService;
117     protected RpcProviderRegistry rpcRegistry;
118
119         protected BindingAwareBroker.RpcRegistration<SLIAPIService> rpcRegistration;
120
121         private static String SLIAPI_NAMESPACE = "org:openecomp:sdnc:sliapi";
122         private static String SLIAPI_REVISION = "2016-11-10";
123
124         private static QName TEST_RESULTS_QNAME = null;
125         private static QName TEST_RESULT_QNAME = null;
126         private static QName TEST_ID_QNAME = null;
127         private static QName RESULTS_QNAME = null;
128
129         static {
130
131                 TEST_RESULTS_QNAME = QName.create(SLIAPI_NAMESPACE, SLIAPI_REVISION, "test-results");
132                 TEST_RESULT_QNAME = QName.create(TEST_RESULTS_QNAME, "test-result");
133                 TEST_ID_QNAME = QName.create(TEST_RESULT_QNAME, "test-identifier");
134                 RESULTS_QNAME = QName.create(TEST_RESULT_QNAME, "results");
135         }
136
137
138     public sliapiProvider() {
139         this.LOG.info( "Creating provider for " + appName );
140     }
141
142     public void initialize(){
143         LOG.info( "Initializing provider for " + appName );
144         //initialization code goes here.
145
146                 rpcRegistration = rpcRegistry.addRpcImplementation(SLIAPIService.class, this);
147         LOG.info( "Initialization complete for " + appName );
148     }
149
150     protected void initializeChild() {
151         //Override if you have custom initialization intelligence
152     }
153
154     @Override
155     public void close() throws Exception {
156         LOG.info( "Closing provider for " + appName );
157         //closing code goes here
158
159             rpcRegistration.close();
160         LOG.info( "Successfully closed provider for " + appName );
161     }
162
163     public void setDataBroker(DataBroker dataBroker) {
164         this.dataBroker = dataBroker;
165                 if (dataBroker instanceof AbstractForwardedDataBroker) {
166                         domDataBroker = ((AbstractForwardedDataBroker) dataBroker).getDelegate();
167                 }
168         if( LOG.isDebugEnabled() ){
169             LOG.debug( "DataBroker set to " + (dataBroker==null?"null":"non-null") + "." );
170         }
171     }
172
173     public void setNotificationService(
174             NotificationProviderService notificationService) {
175         this.notificationService = notificationService;
176         if( LOG.isDebugEnabled() ){
177             LOG.debug( "Notification Service set to " + (notificationService==null?"null":"non-null") + "." );
178         }
179     }
180
181     public void setRpcRegistry(RpcProviderRegistry rpcRegistry) {
182         this.rpcRegistry = rpcRegistry;
183         if( LOG.isDebugEnabled() ){
184             LOG.debug( "RpcRegistry set to " + (rpcRegistry==null?"null":"non-null") + "." );
185         }
186     }
187
188         @Override
189         public Future<RpcResult<ExecuteGraphOutput>> executeGraph(ExecuteGraphInput input) {
190                 RpcResult<ExecuteGraphOutput> rpcResult = null;
191
192                 SvcLogicService svcLogic = getSvcLogicService();
193                 ExecuteGraphOutputBuilder respBuilder = new ExecuteGraphOutputBuilder();
194
195                 String calledModule = input.getModuleName();
196                 String calledRpc = input.getRpcName();
197                 Mode calledMode = input.getMode();
198                 String modeStr = "sync";
199
200                 if (calledMode == Mode.Async) {
201                         modeStr = "async";
202                 }
203
204                 if (svcLogic == null) {
205                         respBuilder.setResponseCode("500");
206                         respBuilder.setResponseText("Could not locate OSGi SvcLogicService service");
207                         respBuilder.setAckFinalIndicator("Y");
208
209                     rpcResult = RpcResultBuilder.<ExecuteGraphOutput> status(true).withResult(respBuilder.build()).build();
210                     return(Futures.immediateFuture(rpcResult));
211                 }
212
213
214                 try {
215                         if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) {
216                                 respBuilder.setResponseCode("404");
217                                 respBuilder.setResponseText("Directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr+" not found");
218                                 respBuilder.setAckFinalIndicator("Y");
219
220                             rpcResult = RpcResultBuilder.<ExecuteGraphOutput> status(true).withResult(respBuilder.build()).build();
221                             return(Futures.immediateFuture(rpcResult));
222                         }
223                 } catch (Exception e) {
224                         LOG.error("Caught exception looking for directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr, e);
225
226                         respBuilder.setResponseCode("500");
227                         respBuilder.setResponseText("Internal error : could not determine if target graph exists");
228                         respBuilder.setAckFinalIndicator("Y");
229
230                     rpcResult = RpcResultBuilder.<ExecuteGraphOutput> status(true).withResult(respBuilder.build()).build();
231                     return(Futures.immediateFuture(rpcResult));
232                 }
233
234                 // Load properties
235                 Properties parms = new Properties();
236
237                 // Pass properties using names from sli-parameters
238                 for (SliParameter sliParm : input.getSliParameter()) {
239
240                         String propValue = "";
241
242                         Boolean boolval = sliParm.isBooleanValue();
243
244                         if (boolval != null) {
245                                 propValue = boolval.toString();
246                         } else {
247                                 Integer intval = sliParm.getIntValue();
248                                 if (intval != null) {
249                                         propValue = intval.toString();
250                                 } else {
251                                         propValue = sliParm.getStringValue();
252                                         if (propValue == null) {
253                                                 propValue = "";
254                                         }
255                                 }
256                         }
257                         parms.setProperty(sliParm.getParameterName(), propValue);
258                 }
259
260                 // Also, pass "meta" properties (i.e. pass SliParameter objects themselves)
261                 ExecuteGraphInputBuilder inputBuilder = new ExecuteGraphInputBuilder(input);
262
263                 SliapiHelper.toProperties(parms, "input", inputBuilder);
264
265                 try {
266                         LOG.info("Calling directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr);
267
268                         if (LOG.isDebugEnabled()) {
269                                 StringBuffer argList = new StringBuffer();
270                                 argList.append("Parameters : {");
271                                 Enumeration e = parms.propertyNames();
272                                 while (e.hasMoreElements()) {
273                                         String propName = (String) e.nextElement();
274                                         argList.append(" ("+propName+","+parms.getProperty(propName)+") ");
275                                 }
276                                 argList.append("}");
277                                 LOG.debug(argList.toString());
278                                 argList = null;
279                         }
280
281
282
283                         Properties respProps = svcLogic.execute(calledModule, calledRpc,
284                                         null, modeStr, parms, domDataBroker);
285
286                         respBuilder.setResponseCode(respProps.getProperty("error-code", "0"));
287                         respBuilder.setResponseText(respProps.getProperty("error-message", ""));
288                         respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y"));
289
290                         TestResultBuilder testResultBuilder = new TestResultBuilder();
291
292                         SliapiHelper.toBuilder(respProps, testResultBuilder);
293
294                         String testIdentifier = testResultBuilder.getTestIdentifier();
295
296                         if ((testIdentifier != null) && (testIdentifier.length() > 0)) {
297
298                                 // Add test results to config tree
299                                 LOG.debug("Saving test results for test id "+testIdentifier);
300
301                                 DomSaveTestResult(testResultBuilder.build(), true, LogicalDatastoreType.CONFIGURATION);
302
303                         }
304
305                 } catch (Exception e) {
306                         LOG.error("Caught exception executing directed graph for"
307                                         + calledModule + ":" + calledRpc + "," + modeStr + ">", e);
308
309                         respBuilder.setResponseCode("500");
310                         respBuilder
311                                         .setResponseText("Internal error : caught exception executing directed graph "
312                                                         + calledModule
313                                                         + "/"
314                                                         + calledRpc
315                                                         + "/"
316                                                         + modeStr);
317                         respBuilder.setAckFinalIndicator("Y");
318
319                 }
320
321                 rpcResult = RpcResultBuilder.<ExecuteGraphOutput> status(true)
322                                 .withResult(respBuilder.build()).build();
323                 return (Futures.immediateFuture(rpcResult));
324         }
325
326
327         private SvcLogicService getSvcLogicService() {
328                 BundleContext bctx = FrameworkUtil.getBundle(SvcLogicService.class).getBundleContext();
329
330                 SvcLogicService svcLogic = null;
331
332         // Get SvcLogicService reference
333                 ServiceReference sref = bctx.getServiceReference(SvcLogicService.NAME);
334                 if (sref  != null)
335                 {
336                         svcLogic =  (SvcLogicService) bctx.getService(sref);
337
338                 }
339                 else
340                 {
341                         LOG.warn("Cannot find service reference for "+SvcLogicService.NAME);
342
343                 }
344
345                 return(svcLogic);
346         }
347
348         @Override
349         public Future<RpcResult<HealthcheckOutput>> healthcheck() {
350
351                 RpcResult<HealthcheckOutput> rpcResult = null;
352                 SvcLogicService svcLogic = getSvcLogicService();
353
354                 HealthcheckOutputBuilder respBuilder = new HealthcheckOutputBuilder();
355
356                 String calledModule = "sli";
357                 String calledRpc = "healthcheck";
358                 String modeStr = "sync";
359
360                 if (svcLogic == null) {
361                         respBuilder.setResponseCode("500");
362                         respBuilder.setResponseText("Could not locate OSGi SvcLogicService service");
363                         respBuilder.setAckFinalIndicator("Y");
364
365                     rpcResult = RpcResultBuilder.<HealthcheckOutput> failed().withResult(respBuilder.build()).build();
366                     return(Futures.immediateFuture(rpcResult));
367                 }
368
369                 try {
370                         if (!svcLogic.hasGraph(calledModule, calledRpc, null, modeStr)) {
371                                 respBuilder.setResponseCode("404");
372                                 respBuilder.setResponseText("Directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr+" not found");
373
374                                 respBuilder.setAckFinalIndicator("Y");
375
376                             rpcResult = RpcResultBuilder.<HealthcheckOutput> status(true).withResult(respBuilder.build()).build();
377                             return(Futures.immediateFuture(rpcResult));
378                         }
379                 } catch (Exception e) {
380                         LOG.error("Caught exception looking for directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr, e);
381
382                         respBuilder.setResponseCode("500");
383                         respBuilder.setResponseText("Internal error : could not determine if target graph exists");
384                         respBuilder.setAckFinalIndicator("Y");
385
386                     rpcResult = RpcResultBuilder.<HealthcheckOutput> failed().withResult(respBuilder.build()).build();
387                     return(Futures.immediateFuture(rpcResult));
388                 }
389
390                 try {
391                         LOG.info("Calling directed graph for "+calledModule+"/"+calledRpc+"/"+modeStr);
392
393                         Properties parms = new Properties();
394
395                         Properties respProps = svcLogic.execute(calledModule, calledRpc,
396                                         null, modeStr, parms);
397
398                         respBuilder.setResponseCode(respProps.getProperty("error-code", "0"));
399                         respBuilder.setResponseText(respProps.getProperty("error-message", ""));
400                         respBuilder.setAckFinalIndicator(respProps.getProperty("ack-final", "Y"));
401
402                 } catch (Exception e) {
403                         LOG.error("Caught exception executing directed graph for"
404                                         + calledModule + ":" + calledRpc + "," + modeStr + ">", e);
405
406                         respBuilder.setResponseCode("500");
407                         respBuilder
408                                         .setResponseText("Internal error : caught exception executing directed graph "
409                                                         + calledModule
410                                                         + "/"
411                                                         + calledRpc
412                                                         + "/"
413                                                         + modeStr);
414                         respBuilder.setAckFinalIndicator("Y");
415
416                 }
417
418                 rpcResult = RpcResultBuilder.<HealthcheckOutput> status(true)
419                                 .withResult(respBuilder.build()).build();
420                 return (Futures.immediateFuture(rpcResult));
421         }
422
423         private void DomSaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) {
424
425
426                 if (domDataBroker == null) {
427                         LOG.error("domDataBroker unset - cannot save test result using DOMDataBroker");
428                         return;
429                 }
430
431                 MapEntryNode resultNode = null;
432
433                 try {
434                         resultNode = toMapEntryNode(entry);
435                 } catch (Exception e) {
436                         LOG.error("Caught exception trying to create map entry node", e);
437                 }
438
439                 if (resultNode == null) {
440                         LOG.error("Could not convert entry to MapEntryNode");
441                         return;
442                 }
443
444
445                 YangInstanceIdentifier testResultsPid = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME).node(QName.create(TEST_RESULTS_QNAME, "test-result")).build();
446                 YangInstanceIdentifier testResultPid = testResultsPid.node(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, resultNode.getIdentifier().getKeyValues()));
447
448
449
450                 int tries = 2;
451                 while(true) {
452                         try {
453                                 DOMDataWriteTransaction wtx = domDataBroker.newWriteOnlyTransaction();
454                                 if (merge) {
455                                         LOG.info("Merging test identifier "+entry.getTestIdentifier());
456                                         wtx.merge(storeType, testResultPid, resultNode);
457                                 } else {
458                                         LOG.info("Putting test identifier "+entry.getTestIdentifier());
459                                         wtx.put(storeType,  testResultPid, resultNode);
460                                 }
461                                 wtx.submit().checkedGet();
462                                 LOG.trace("Update DataStore succeeded");
463                                 break;
464                         } catch (final TransactionCommitFailedException e) {
465                                 if(e instanceof OptimisticLockFailedException) {
466                                         if(--tries <= 0) {
467                                                 LOG.trace("Got OptimisticLockFailedException on last try - failing ");
468                                                 throw new IllegalStateException(e);
469                                         }
470                                         LOG.trace("Got OptimisticLockFailedException - trying again ");
471                                 } else {
472                                         LOG.trace("Update DataStore failed");
473                                         throw new IllegalStateException(e);
474                                 }
475                         }
476                 }
477
478         }
479
480                 private void SaveTestResult(final TestResult entry, boolean merge, LogicalDatastoreType storeType) throws IllegalStateException
481                 {
482                         // Each entry will be identifiable by a unique key, we have to create that identifier
483                         InstanceIdentifier.InstanceIdentifierBuilder<TestResult> testResultIdBuilder =
484                                         InstanceIdentifier.<TestResults>builder(TestResults.class)
485                                         .child(TestResult.class, entry.getKey());
486                         InstanceIdentifier<TestResult> path = testResultIdBuilder.toInstance();
487                         int tries = 2;
488                         while(true) {
489                                 try {
490                                         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
491                                         if (merge) {
492                                                 tx.merge(storeType, path, entry);
493                                         } else {
494                                                 tx.put(storeType, path, entry);
495                                         }
496                                         tx.submit().checkedGet();
497                                         LOG.trace("Update DataStore succeeded");
498                                         break;
499                                 } catch (final TransactionCommitFailedException e) {
500                                         if(e instanceof OptimisticLockFailedException) {
501                                                 if(--tries <= 0) {
502                                                         LOG.trace("Got OptimisticLockFailedException on last try - failing ");
503                                                         throw new IllegalStateException(e);
504                                                 }
505                                                 LOG.trace("Got OptimisticLockFailedException - trying again ");
506                                         } else {
507                                                 LOG.trace("Update DataStore failed");
508                                                 throw new IllegalStateException(e);
509                                         }
510                                 }
511                         }
512                 }
513
514                 private MapEntryNode toMapEntryNode(TestResult testResult) {
515
516
517                         YangInstanceIdentifier testResultId = YangInstanceIdentifier.builder().node(TEST_RESULTS_QNAME).node(TEST_RESULT_QNAME).build();
518
519                         // Construct results list
520                         LinkedList<LeafSetEntryNode<Object>> entryList = new LinkedList<LeafSetEntryNode<Object>>();
521                         for (String result : testResult.getResults()) {
522                                 LeafSetEntryNode<Object> leafSetEntryNode = ImmutableLeafSetEntryNodeBuilder.create()
523                                                                                                                                                                 .withNodeIdentifier(new NodeWithValue(RESULTS_QNAME, result))
524                                                                                                                                                                 .withValue(result)
525                                                                                                                                                                 .build();
526                                 entryList.add(leafSetEntryNode);
527                         }
528                         // Construct results LeafSetNode
529                         LeafSetNode<?> resultsNode = ImmutableLeafSetNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(RESULTS_QNAME)).withValue(entryList).build();
530
531
532
533                         // Construct test result ContainerNode with 2 children - test-identifier leaf and results leaf-set
534                         MapEntryNode testResultNode = ImmutableNodes.mapEntryBuilder()
535                                         .withNodeIdentifier(new NodeIdentifierWithPredicates(TEST_RESULT_QNAME, TEST_ID_QNAME, testResult.getTestIdentifier()))
536                                         .withChild(ImmutableNodes.leafNode(TEST_ID_QNAME, testResult.getTestIdentifier()))
537                                         .withChild(resultsNode)
538                                         .build();
539
540                         return(testResultNode);
541
542                 }
543
544 }