Second part of onap rename
[appc.git] / appc-sequence-generator / appc-sequence-generator-bundle / src / main / java / org / onap / appc / seqgen / provider / SequenceGeneratorProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property.  All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.appc.seqgen.provider;
22
23 import com.att.eelf.configuration.EELFLogger;
24 import com.att.eelf.configuration.EELFManager;
25 import com.google.common.util.concurrent.Futures;
26 import org.apache.commons.lang.StringUtils;
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
29 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
30 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
31 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceInput;
32 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutput;
33 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.GenerateSequenceOutputBuilder;
34 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.SequenceGeneratorService;
35 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.dependency.info.dependency.info.Vnfcs;
36 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.inventory.info.inventory.info.vnf.info.Vm;
37 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.StatusBuilder;
38 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.Transactions;
39 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.TransactionsBuilder;
40 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.ActionIdentifier;
41 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.*;
42 import org.opendaylight.yang.gen.v1.org.onap.appc.sequencegenerator.rev170706.response.transactions.responses.ResponseActionBuilder;
43 import org.opendaylight.yangtools.yang.common.RpcResult;
44 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
45 import org.onap.appc.dg.objects.InventoryModel;
46 import org.onap.appc.dg.objects.Node;
47 import org.onap.appc.dg.objects.VnfcDependencyModel;
48 import org.onap.appc.domainmodel.Vnf;
49 import org.onap.appc.domainmodel.Vserver;
50 import org.onap.appc.domainmodel.lcm.VNFOperation;
51 import org.onap.appc.exceptions.APPCException;
52 import org.onap.appc.seqgen.SequenceGenerator;
53 import org.onap.appc.seqgen.impl.SequenceGeneratorFactory;
54 import org.onap.appc.seqgen.objects.*;
55
56 import java.util.*;
57 import java.util.concurrent.ExecutorService;
58 import java.util.concurrent.Executors;
59 import java.util.concurrent.Future;
60
61
62 public class SequenceGeneratorProvider implements AutoCloseable,SequenceGeneratorService{
63     protected DataBroker dataBroker;
64     protected RpcProviderRegistry rpcRegistry;
65     protected NotificationProviderService notificationService;
66     protected BindingAwareBroker.RpcRegistration<SequenceGeneratorService> rpcRegistration;
67     private final EELFLogger log = EELFManager.getInstance().getLogger(SequenceGeneratorProvider.class);
68     private final ExecutorService executor;
69     private final static String APP_NAME = "SequenceGeneratorProvider";
70
71     public SequenceGeneratorProvider(DataBroker dataBroker2, NotificationProviderService notificationProviderService
72             , RpcProviderRegistry rpcRegistry2) {
73         log.info("Creating provider for " + APP_NAME);
74         executor = Executors.newFixedThreadPool(1);
75         this.dataBroker = dataBroker2;
76         this.notificationService = notificationProviderService;
77
78         this.rpcRegistry = rpcRegistry2;
79
80         if (this.rpcRegistry != null) {
81             rpcRegistration = rpcRegistry.addRpcImplementation(SequenceGeneratorService.class, this);
82         }
83         log.info("Initialization complete for " + APP_NAME);
84     }
85
86     @Override
87     public void close() throws Exception {
88         log.info("Closing provider for " + APP_NAME);
89         if(this.executor != null){
90             executor.shutdown();
91         }
92         if(this.rpcRegistration != null){
93             rpcRegistration.close();
94         }
95         log.info("Successfully closed provider for " + APP_NAME);
96     }
97
98     @Override
99     public Future<RpcResult<GenerateSequenceOutput>> generateSequence(GenerateSequenceInput input) {
100         RpcResult<GenerateSequenceOutput> rpcResult=null;
101         log.debug("Received input = " + input );
102         try {
103             SequenceGenerator seqGenerator = SequenceGeneratorFactory.getInstance()
104                     .createSequenceGenerator(VNFOperation.findByString(input.getRequestInfo().getAction().name()));
105             SequenceGeneratorInput seqGenInput = buildSeqGenInput(input);
106             List<Transaction> transactions = seqGenerator.generateSequence(seqGenInput);
107             rpcResult = buildSuccessResponse(transactions);
108         } catch (APPCException e) {
109             log.error("Error Generating Sequence",e);
110             rpcResult = buildFailureResponse(e.getMessage());
111         }
112         return Futures.immediateFuture(rpcResult);
113     }
114
115     private RpcResult<GenerateSequenceOutput> buildSuccessResponse(List<Transaction> transactions) {
116
117         List<Transactions> transactionList = new LinkedList<>();
118         for(Transaction transaction:transactions){
119             ActionIdentifier actionIdentifier = null;
120             if(transaction.getActionIdentifier() != null){
121                 actionIdentifier = new ActionIdentifierBuilder()
122                         .setVnfId(transaction.getActionIdentifier().getVnfId())
123                         .setVnfcName(transaction.getActionIdentifier().getVnfcName())
124                         .setVserverId(transaction.getActionIdentifier().getvServerId())
125                         .build();
126             }
127
128             List<PrecheckOptions> precheckOptions = new LinkedList<>();
129             if(transaction.getPrecheckOptions()!=null){
130                 for(PreCheckOption option:transaction.getPrecheckOptions()){
131                     PrecheckOptions precheckOption = new PrecheckOptionsBuilder()
132                             .setParamName(option.getParamName())
133                             .setParamValue(option.getParamValue())
134                             .setPreTransactionId(option.getPreTransactionId())
135                             .setRule(option.getRule())
136                             .build();
137                     precheckOptions.add(precheckOption);
138                 }
139             }
140
141             List<Responses> responseList = getResponses(transaction);
142
143             Transactions transactionObj
144                     = new TransactionsBuilder()
145                     .setActionIdentifier(actionIdentifier)
146                     .setAction(transaction.getAction())
147                     .setActionLevel(transaction.getActionLevel())
148                     .setPrecheckOperator(transaction.getPreCheckOperator())
149                     .setPayload(transaction.getPayload())
150                     .setTransactionId(transaction.getTransactionId())
151                     .setPrecheckOptions(precheckOptions)
152                     .setResponses(responseList)
153                     .build();
154             transactionList.add(transactionObj);
155         }
156
157         GenerateSequenceOutputBuilder builder = new GenerateSequenceOutputBuilder()
158                 .setTransactions(transactionList);
159
160         return RpcResultBuilder
161                 .<GenerateSequenceOutput> status(true)
162                 .withResult(builder.build()).build();
163     }
164
165     private List<Responses> getResponses(Transaction transaction) {
166         List<Responses> responseList = new LinkedList<>();
167         for(Response resp : transaction.getResponses()){
168             Map<String,String> responseActions = resp.getResponseAction();
169             ResponseActionBuilder responseActionBuilder = new ResponseActionBuilder();
170             if(responseActions.get(Constants.ResponseAction.WAIT.getAction())!=null){
171                 responseActionBuilder = responseActionBuilder.setWait(Integer.parseInt(responseActions.get(Constants.ResponseAction.WAIT.getAction())));
172             }
173             if(responseActions.get(Constants.ResponseAction.RETRY.getAction())!=null){
174                 responseActionBuilder = responseActionBuilder.setRetry(Integer.parseInt(responseActions.get(Constants.ResponseAction.RETRY.getAction())));
175             }
176             if(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase())!=null){
177                 responseActionBuilder = responseActionBuilder
178                         .setContinue(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.CONTINUE.getAction().toLowerCase())));
179             }
180             if(responseActions.get(Constants.ResponseAction.IGNORE.getAction()) !=null){
181                 responseActionBuilder = responseActionBuilder.setIgnore(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.IGNORE.getAction())));
182             }
183             if(responseActions.get(Constants.ResponseAction.STOP.getAction()) !=null){
184                 responseActionBuilder = responseActionBuilder.setStop(Boolean.parseBoolean(responseActions.get(Constants.ResponseAction.STOP.getAction())));
185             }
186             Responses response = new ResponsesBuilder()
187                     .setResponseMessage(resp.getResponseMessage())
188                     .setResponseAction(responseActionBuilder.build())
189                     .build();
190             responseList.add(response);
191         }
192         return responseList;
193     }
194
195     private SequenceGeneratorInput buildSeqGenInput(GenerateSequenceInput input) throws APPCException {
196
197         validateMandatory(input);
198
199         RequestInfoBuilder requestInfobuilder = new RequestInfoBuilder()
200                 .action(input.getRequestInfo().getAction().name())
201                 .actionLevel(input.getRequestInfo().getActionLevel().getName().toLowerCase())
202                 .payload(input.getRequestInfo().getPayload());
203
204         if(input.getRequestInfo().getActionIdentifier() !=null){
205             requestInfobuilder = requestInfobuilder
206                     .actionIdentifier()
207                     .vnfId(input.getRequestInfo().getActionIdentifier().getVnfId())
208                     .vnfcName(input.getRequestInfo().getActionIdentifier().getVnfcName())
209                     .vServerId(input.getRequestInfo().getActionIdentifier().getVserverId());
210         }
211
212         RequestInfo requestInfo = requestInfobuilder.build();
213
214         InventoryModel inventoryModel = readInventoryModel(input);
215
216         VnfcDependencyModel dependencyModel = readDependencyModel(input);
217
218         SequenceGeneratorInputBuilder builder = new SequenceGeneratorInputBuilder()
219                 .requestInfo(requestInfo)
220                 .inventoryModel(inventoryModel)
221                 .dependendcyModel(dependencyModel);
222
223         if(input.getCapabilities() !=null){
224             if(input.getCapabilities().getVnf()!=null){
225                 builder = builder.capability("vnf",input.getCapabilities().getVnf());
226             }
227             if(input.getCapabilities().getVnfc()!=null){
228                 builder = builder.capability("vnfc",input.getCapabilities().getVnfc());
229             }
230             if(input.getCapabilities().getVm()!=null){
231                 builder = builder.capability("vm",input.getCapabilities().getVm());
232             }
233             if(input.getCapabilities().getVfModule()!=null){
234                 builder = builder.capability("vf-module",input.getCapabilities().getVfModule());
235             }
236         }
237
238         if(input.getTunableParameters() != null){
239             builder = builder.tunableParameter(Constants.RETRY_COUNT,String.valueOf(input.getTunableParameters().getRetryCount()))
240                     .tunableParameter(Constants.WAIT_TIME,String.valueOf(input.getTunableParameters().getWaitTime()));
241             if(input.getTunableParameters().getStrategy() !=null){
242                 builder  = builder.tunableParameter(Constants.STRATEGY,input.getTunableParameters().getStrategy().name());
243             }
244         }
245         return builder.build();
246     }
247
248
249     private void validateMandatory(GenerateSequenceInput input) throws APPCException {
250         if(input.getRequestInfo() ==null){
251             throw new APPCException("Request Info is not present in the request");
252         }
253         if(input.getRequestInfo().getAction() ==null){
254             throw new APPCException("Action is not present in the request");
255         }
256         if(input.getInventoryInfo() ==null){
257             throw new APPCException("inventoryInfo is not provided in the input");
258         }
259     }
260
261     private VnfcDependencyModel readDependencyModel(GenerateSequenceInput input) {
262         if(input.getDependencyInfo() == null || input.getDependencyInfo().getVnfcs() ==null || input.getDependencyInfo().getVnfcs().isEmpty()){
263             return null;
264         }
265         List<Vnfcs> vnfcs = input.getDependencyInfo().getVnfcs();
266         Set<Node<org.onap.appc.domainmodel.Vnfc>> dependencies = new HashSet<>();
267         for(Vnfcs vnfcObj:vnfcs){
268             org.onap.appc.domainmodel.Vnfc vnfc;
269             Node<org.onap.appc.domainmodel.Vnfc> currentNode = readNode(vnfcObj.getVnfcType(),dependencies);
270             if(currentNode == null){
271                 vnfc = new org.onap.appc.domainmodel.Vnfc(vnfcObj.getVnfcType(),vnfcObj.getResilience());
272                 currentNode = new Node<>(vnfc);
273                 dependencies.add(currentNode);
274             }
275             else{
276                 currentNode.getChild().setResilienceType(vnfcObj.getResilience());
277                 currentNode.getChild().setMandatory(vnfcObj.isMandatory());
278             }
279             for(String parentVnfcType:vnfcObj.getParents()){
280                 Node<org.onap.appc.domainmodel.Vnfc> parentNode = readNode(parentVnfcType,dependencies);
281                 if(parentNode == null){
282                     org.onap.appc.domainmodel.Vnfc parentVnfc = new org.onap.appc.domainmodel.Vnfc(parentVnfcType,null);
283                     parentNode = new Node<>(parentVnfc);
284                     currentNode.addParent(parentVnfc);
285                     dependencies.add(parentNode);
286                 }
287                 else{
288                     currentNode.addParent(parentNode.getChild());
289                 }
290             }
291         }
292         return new VnfcDependencyModel(dependencies);
293     }
294
295     private Node<org.onap.appc.domainmodel.Vnfc> readNode(String vnfcType, Set<Node<org.onap.appc.domainmodel.Vnfc>> dependencies) {
296         for(Node<org.onap.appc.domainmodel.Vnfc> node : dependencies){
297             if(node.getChild().getVnfcType().equalsIgnoreCase(vnfcType)){
298                 return node;
299             }
300         }
301         return null;
302     }
303
304     private InventoryModel readInventoryModel(GenerateSequenceInput input) throws APPCException {
305         if (input.getInventoryInfo().getVnfInfo()== null) {
306             throw new APPCException("vnfInfo is not provided in the input");
307         }
308
309         Vnf vnf = new Vnf(input.getInventoryInfo().getVnfInfo().getVnfId(),
310                 input.getInventoryInfo().getVnfInfo().getVnfType(),null);
311
312         Map<org.onap.appc.domainmodel.Vnfc,List<Vserver>> map = new HashMap<>();
313         for(Vm vm:input.getInventoryInfo().getVnfInfo().getVm()){
314             if(StringUtils.isBlank(vm.getVserverId())){
315                 throw new APPCException("vserver-id not found ");
316             }
317             if(StringUtils.isBlank(vm.getVnfc().getVnfcType())){
318                 throw new APPCException("vnfc-type not found for vserver " + vm.getVserverId());
319             }
320             if(StringUtils.isBlank(vm.getVnfc().getVnfcName())){
321                 throw new APPCException("vnfc-name not found for vserver " + vm.getVserverId());
322             }
323
324             org.onap.appc.domainmodel.Vnfc vnfc = new org.onap.appc.domainmodel.Vnfc(vm.getVnfc().getVnfcType(),null,vm.getVnfc().getVnfcName());
325             List<Vserver> vms = map.get(vnfc);
326             if(vms ==null){
327                 vms = new LinkedList<>();
328                 map.put(vnfc,vms);
329             }
330             vms.add(new Vserver(null,null,vm.getVserverId(),null,null));
331         }
332         for(Map.Entry<org.onap.appc.domainmodel.Vnfc,List<Vserver>> entry:map.entrySet()){
333             org.onap.appc.domainmodel.Vnfc vnfc = entry.getKey();
334             List<Vserver> vmList = entry.getValue();
335             vnfc.addVms(vmList);
336             vnf.addVnfc(vnfc);
337         }
338         return new InventoryModel(vnf);
339     }
340
341     private RpcResult<GenerateSequenceOutput> buildFailureResponse(String errorMessage){
342         GenerateSequenceOutputBuilder sequenceGeneratorOutputBuilder=new GenerateSequenceOutputBuilder();
343         StatusBuilder statusBuilder =new StatusBuilder();
344         statusBuilder.setCode(401);
345         statusBuilder.setMessage(errorMessage);
346         sequenceGeneratorOutputBuilder.setStatus(statusBuilder.build());
347         return RpcResultBuilder
348                 .<GenerateSequenceOutput> status(true)
349                 .withResult(sequenceGeneratorOutputBuilder.build())
350                 .build();
351     }
352 }