1a79f8c41b4e89e57eefe9f587ce01b6a54fa90c
[ccsdk/sli.git] /
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.onap.ccsdk.sli.northbound.asdcapi;
23
24 import java.util.Properties;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ExecutorService;
27 import java.util.concurrent.Executors;
28
29 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
30 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
31 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
32 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
33 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
34 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
35 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
36 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
37 import org.opendaylight.yang.gen.v1.http.xmlns.onap.org.asdc.license.model._1._0.rev160427.vf.license.model.grouping.VfLicenseModel;
38 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.ASDCAPIService;
39 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.Artifacts;
40 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.ArtifactsBuilder;
41 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelUpdateInput;
42 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelUpdateInputBuilder;
43 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelUpdateOutput;
44 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelUpdateOutputBuilder;
45 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelVersions;
46 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.VfLicenseModelVersionsBuilder;
47 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.artifacts.Artifact;
48 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.artifacts.ArtifactBuilder;
49 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.artifacts.ArtifactKey;
50 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.vf.license.model.versions.VfLicenseModelVersion;
51 import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev170201.vf.license.model.versions.VfLicenseModelVersionBuilder;
52 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
53 import org.opendaylight.yangtools.yang.common.RpcResult;
54 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import com.google.common.base.Optional;
59 import com.google.common.util.concurrent.CheckedFuture;
60 import com.google.common.util.concurrent.Futures;
61 import com.google.common.util.concurrent.ListenableFuture;
62
63 /**
64  * Defines a base implementation for your provider. This class extends from a helper class
65  * which provides storage for the most commonly used components of the MD-SAL. Additionally the
66  * base class provides some basic logging and initialization / clean up methods.
67  *
68  * To use this, copy and paste (overwrite) the following method into the TestApplicationProviderModule
69  * class which is auto generated under src/main/java in this project
70  * (created only once during first compilation):
71  *
72  * <pre>
73
74     @Override
75     public java.lang.AutoCloseable createInstance() {
76
77          final asdcApiProvider provider = new asdcApiProvider();
78          provider.setDataBroker( getDataBrokerDependency() );
79          provider.setNotificationService( getNotificationServiceDependency() );
80          provider.setRpcRegistry( getRpcRegistryDependency() );
81          provider.initialize();
82          return new AutoCloseable() {
83
84             @Override
85             public void close() throws Exception {
86                 //TODO: CLOSE ANY REGISTRATION OBJECTS CREATED USING ABOVE BROKER/NOTIFICATION
87                 //SERVIE/RPC REGISTRY
88                 provider.close();
89             }
90         };
91     }
92
93
94     </pre>
95  */
96 public class AsdcApiProvider implements AutoCloseable, ASDCAPIService {
97
98     private static final Logger LOG = LoggerFactory.getLogger(AsdcApiProvider.class);
99
100     private static final String ACTIVE_VERSION = "active";
101
102     private static final String APPLICATION_NAME = "asdcApi";
103
104     private final ExecutorService executor;
105     protected DataBroker dataBroker;
106     protected NotificationPublishService notificationService;
107     protected RpcProviderRegistry rpcRegistry;
108     private final AsdcApiSliClient asdcApiSliClient;
109
110     protected BindingAwareBroker.RpcRegistration<ASDCAPIService> rpcRegistration;
111
112     public AsdcApiProvider(final DataBroker dataBroker,
113                            final NotificationPublishService notificationPublishService,
114                            final RpcProviderRegistry rpcProviderRegistry,
115                            final AsdcApiSliClient asdcApiSliClient) {
116
117         LOG.info("Creating provider for {}", APPLICATION_NAME);
118         executor = Executors.newFixedThreadPool(1);
119         this.dataBroker = dataBroker;
120         notificationService = notificationPublishService;
121         rpcRegistry = rpcProviderRegistry;
122         this.asdcApiSliClient= asdcApiSliClient;
123         initialize();
124     }
125
126     public void initialize(){
127         LOG.info("Initializing {} for {}", this.getClass().getName(), APPLICATION_NAME);
128
129         createContainers();
130
131         if (rpcRegistration == null) {
132             if (rpcRegistry != null) {
133                 rpcRegistration = rpcRegistry.addRpcImplementation(
134                         ASDCAPIService.class, this);
135                 LOG.info("Initialization complete for {}", APPLICATION_NAME);
136             } else {
137                 LOG.warn("Error initializing {} : rpcRegistry unset", APPLICATION_NAME);
138             }
139         }
140     }
141
142     private void createContainers() {
143
144         if (dataBroker != null) {
145         final WriteTransaction t = dataBroker.newReadWriteTransaction();
146
147         // Create the vf-model-license-versions and artifacts containers
148         t.merge(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(VfLicenseModelVersions.class),
149         new VfLicenseModelVersionsBuilder().build());
150
151         t.merge(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Artifacts.class), new ArtifactsBuilder().build());
152
153
154         try {
155             CheckedFuture<Void, TransactionCommitFailedException> checkedFuture = t.submit();
156             checkedFuture.get();
157             LOG.info("Create Containers succeeded!: ");
158
159         } catch (InterruptedException | ExecutionException e) {
160             LOG.error("Create Containers Failed: ", e);
161         }
162         } else {
163             LOG.warn("createContainers : cannot find dataBroker to create containers");
164         }
165     }
166     protected void initializeChild() {
167         //Override if you have custom initialization intelligence
168     }
169
170     @Override
171     public void close() throws Exception {
172         LOG.info( "Closing provider for " + APPLICATION_NAME);
173         executor.shutdown();
174         rpcRegistration.close();
175         LOG.info( "Successfully closed provider for " + APPLICATION_NAME);
176     }
177
178     protected boolean artifactVersionExists(String aName, String aVersion) {
179         InstanceIdentifier artifactInstanceId =
180                 InstanceIdentifier.<Artifacts>builder(Artifacts.class)
181                 .child(Artifact.class, new ArtifactKey(aName, aVersion)).build();
182         Optional<Artifact> data = null;
183         try(ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction()) {
184             data = (Optional<Artifact>) readTx.read(LogicalDatastoreType.CONFIGURATION, artifactInstanceId).get();
185         } catch (InterruptedException | ExecutionException e) {
186             LOG.error("Caught Exception reading MD-SAL for ["+aName+","+ aVersion+"] " ,e);
187             return false;
188         }
189
190         return data.isPresent();
191     }
192
193     protected void addArtifactVersion(String aName, String aVersion) {
194
195
196         try {
197             ArtifactBuilder aBuilder = new ArtifactBuilder();
198
199             aBuilder.setArtifactName(aName);
200             aBuilder.setArtifactVersion(aVersion);
201
202             Artifact artifact = aBuilder.build();
203
204             InstanceIdentifier.InstanceIdentifierBuilder<Artifact> aIdBuilder = InstanceIdentifier
205                     .<Artifacts> builder(Artifacts.class)
206                     .child(Artifact.class, artifact.key());
207
208             InstanceIdentifier<Artifact> path = aIdBuilder.build();
209
210             WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
211
212             tx.merge(LogicalDatastoreType.CONFIGURATION, path,
213                     artifact);
214             tx.submit().checkedGet();
215         } catch (Exception e) {
216             LOG.error("Caught exception trying to add artifact entry", e);
217         }
218
219     }
220
221
222     private void applyVfLicenseModelUpdate(VfLicenseModelUpdateInput input) {
223
224     String aName = input.getArtifactName();
225     String aVersion = input.getArtifactVersion();
226     VfLicenseModel vfLicenseModel = input.getVfLicenseModel();
227
228
229     // Add new version (version = artifact-version)
230     try {
231
232         VfLicenseModelVersionBuilder vBuilder = new VfLicenseModelVersionBuilder();
233         vBuilder.setArtifactName(aName);
234         vBuilder.setArtifactVersion(aVersion);
235         vBuilder.setVfLicenseModel(vfLicenseModel);
236
237         VfLicenseModelVersion version = vBuilder.build();
238
239         InstanceIdentifier.InstanceIdentifierBuilder<VfLicenseModelVersion> versionIdBuilder = InstanceIdentifier
240                 .<VfLicenseModelVersions> builder(VfLicenseModelVersions.class)
241                 .child(VfLicenseModelVersion.class, version.key());
242
243         InstanceIdentifier<VfLicenseModelVersion> path = versionIdBuilder.build();
244
245         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
246   tx.merge(LogicalDatastoreType.CONFIGURATION, path,
247                 version);
248         tx.submit().checkedGet();
249     } catch (Exception e) {
250         LOG.error(
251                 "Caught exception trying to save entry to MD-SAL",
252                 e);
253     }
254
255
256     // Add "active" version (version = "active")
257     try {
258
259         VfLicenseModelVersionBuilder vBuilder = new VfLicenseModelVersionBuilder();
260         vBuilder.setArtifactName(aName);
261         vBuilder.setArtifactVersion(ACTIVE_VERSION);
262         vBuilder.setVfLicenseModel(vfLicenseModel);
263
264         VfLicenseModelVersion version = vBuilder.build();
265         InstanceIdentifier.InstanceIdentifierBuilder<VfLicenseModelVersion> versionIdBuilder = InstanceIdentifier
266                 .<VfLicenseModelVersions> builder(VfLicenseModelVersions.class)
267                 .child(VfLicenseModelVersion.class, version.key());
268
269         InstanceIdentifier<VfLicenseModelVersion> path = versionIdBuilder.build();
270
271         WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
272
273         tx.merge(LogicalDatastoreType.CONFIGURATION, path,
274                 version);
275         tx.submit().checkedGet();
276     } catch (Exception e) {
277         LOG.error(
278                 "Caught exception trying to save entry to MD-SAL",
279                 e);
280     }
281
282 }
283
284 @Override
285 public ListenableFuture<RpcResult<VfLicenseModelUpdateOutput>> vfLicenseModelUpdate(VfLicenseModelUpdateInput input) {
286     final String svcOperation = "vf-license-model-update";
287
288     Properties parms = new Properties();
289
290     LOG.info( svcOperation +" called." );
291
292     if(input == null ) {
293         LOG.debug("exiting " +svcOperation+ " because of invalid input");
294         return null;
295     }
296
297     VfLicenseModelUpdateInputBuilder inputBuilder = new VfLicenseModelUpdateInputBuilder(input);
298
299     VfLicenseModelUpdateInput inputVfLic = inputBuilder.build();
300
301     String errorMessage = "Success";
302     String errorCode = "200";
303
304     // If this artifact already exists, reject this update
305     if (artifactVersionExists(inputVfLic.getArtifactName(), inputVfLic.getArtifactVersion())) {
306         errorCode = "409";
307         errorMessage = "Artifact version already exists";
308     } else {
309         // Translate input object into SLI-consumable properties
310         LOG.info("Adding INPUT data for "+svcOperation+" input: " + inputVfLic);
311         AsdcApiUtil.toProperties(parms, inputVfLic);
312
313
314         // Call directed graph
315         Properties respProps = null;
316         try
317         {
318             if (asdcApiSliClient.hasGraph("ASDC-API", svcOperation , null, "sync"))
319             {
320
321                 try
322                 {
323                     respProps = asdcApiSliClient.execute("ASDC-API", svcOperation, null, "sync", parms);
324                 }
325                 catch (Exception e)
326                 {
327                     LOG.error("Caught exception executing service logic for "+ svcOperation, e);
328                 }
329             } else {
330                 errorMessage = "No service logic active for ASDC-API: '" + svcOperation + "'";
331                 errorCode = "503";
332             }
333         }
334         catch (Exception e)
335         {
336             errorCode = "500";
337             errorMessage = e.getMessage();
338             LOG.error("Caught exception looking for service logic", e);
339         }
340
341
342         if (respProps != null)
343         {
344             errorCode = respProps.getProperty("error-code");
345             errorMessage = respProps.getProperty("error-message", "");
346         }
347     }
348
349
350     if ("200".equals(errorCode)) {
351         LOG.info("ASDC update succeeded");
352
353         // Update config tree
354         applyVfLicenseModelUpdate(inputVfLic);
355         addArtifactVersion(inputVfLic.getArtifactName(), inputVfLic.getArtifactVersion());
356
357     } else {
358         LOG.info("ASDC update failed ("+errorCode+" : "+errorMessage);
359     }
360
361     // Send response
362     VfLicenseModelUpdateOutputBuilder respBuilder = new VfLicenseModelUpdateOutputBuilder();
363     respBuilder.setAsdcApiResponseCode(errorCode);
364     if (errorMessage != null && errorMessage.length() > 0) {
365         respBuilder.setAsdcApiResponseText(errorMessage);
366     }
367
368     RpcResult<VfLicenseModelUpdateOutput> rpcResult;
369
370
371     rpcResult = RpcResultBuilder.<VfLicenseModelUpdateOutput> status(true).withResult(respBuilder.build()).build();
372
373
374
375     return Futures.immediateFuture(rpcResult);
376 }
377
378
379 }