Changed to unmaintained
[appc.git] / appc-sequence-generator / appc-sequence-generator-bundle / src / main / java / org / onap / appc / seqgen / impl / StopSequenceGenerator.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 Copyright (C) 2019 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.seqgen.impl;
27
28 import org.onap.appc.dg.flowbuilder.FlowBuilder;
29 import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory;
30 import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModelException;
31 import org.onap.appc.dg.objects.FlowStrategies;
32 import org.onap.appc.dg.objects.InventoryModel;
33 import org.onap.appc.dg.objects.VnfcDependencyModel;
34 import org.onap.appc.dg.objects.VnfcFlowModel;
35 import org.onap.appc.domainmodel.Vnfc;
36 import org.onap.appc.domainmodel.Vserver;
37 import org.onap.appc.exceptions.APPCException;
38 import org.onap.appc.seqgen.SequenceGenerator;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import org.onap.appc.seqgen.objects.ActionIdentifier;
42 import org.onap.appc.seqgen.objects.CapabilityModel;
43 import org.onap.appc.seqgen.objects.Constants;
44 import org.onap.appc.seqgen.objects.Response;
45 import org.onap.appc.seqgen.objects.SequenceGeneratorInput;
46 import org.onap.appc.seqgen.objects.Transaction;
47
48 import java.util.HashMap;
49 import java.util.Iterator;
50 import java.util.LinkedList;
51 import java.util.List;
52 import java.util.Map;
53
54 import static org.onap.appc.seqgen.objects.Constants.Action;
55 import static org.onap.appc.seqgen.objects.Constants.ActionLevel;
56 import static org.onap.appc.seqgen.objects.Constants.ResponseAction;
57 import static org.onap.appc.seqgen.objects.Constants.ResponseMessage;
58 import static org.onap.appc.seqgen.objects.Constants.Capabilties;
59
60 public class StopSequenceGenerator implements SequenceGenerator {
61
62     private static final EELFLogger logger = EELFManager.getInstance().getLogger(StopSequenceGenerator.class);
63
64     @Override
65     public List<Transaction> generateSequence(SequenceGeneratorInput input) throws Exception {
66         if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null ) {
67             if(isVnfcPresent(input)) {
68                 FlowStrategies flowStrategy = readFlowStrategy(input);
69                 VnfcFlowModel flowModel = null;
70                 try {
71                         flowModel = buildFlowModel(input.getInventoryModel(), input.getDependencyModel(), flowStrategy);
72                     } catch (InvalidDependencyModelException invalidDependencyModelException) {
73                         logger.error("Error Generating Sequence", invalidDependencyModelException);
74                         throw  new APPCException(invalidDependencyModelException.getMessage(), invalidDependencyModelException);
75                 }
76                 logger.debug("Flow Model " + flowModel);
77                 return generateSequenceWithDependencyModel(flowModel, input);
78             }
79                 else throw  new APPCException("Vnfc details missing in the input");
80             } else {
81                 logger.info("Generating sequence without dependency model");
82                 return generateSequenceWithOutDependency(input);
83             }
84     }
85
86     private List<Transaction> generateSequenceWithOutDependency(SequenceGeneratorInput input) throws Exception{
87         String payload = null;
88         PayloadGenerator payloadGenerator = new PayloadGenerator();
89         List<Transaction> transactionList = new LinkedList<>();
90         Integer transactionId = 1;
91         List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
92         List<Integer> transactionIds = new LinkedList<>();
93         for (Vserver vm : vservers) {
94             // check vm-Stop-capabilities for this vm's vnfc-function-code (before incrementing transactionId)
95             if (!vmSupportsStop(input, vm)) {
96                 continue;
97             }
98             Transaction transaction = new Transaction();
99             transaction.setTransactionId(transactionId);
100             transactionIds.add(transactionId++);
101             transaction.setAction(Action.STOP.getActionType());
102             transaction.setActionLevel(ActionLevel.VM.getAction());
103             ActionIdentifier actionIdentifier = new ActionIdentifier();
104             actionIdentifier.setvServerId(vm.getId());
105             transaction.setActionIdentifier(actionIdentifier);
106             String vmId = vm.getId();
107             String url = vm.getUrl();
108             payload = payloadGenerator.getPayload(input, vmId, url);
109             transaction.setPayload(payload);
110             if(vservers.size()>1){
111                 Response failureResponse = new Response();
112                 failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
113                 Map<String,String> failureAction = new HashMap<>();
114                 failureAction.put(ResponseAction.STOP.getAction(),Boolean.TRUE.toString());
115                 failureResponse.setResponseAction(failureAction);
116                 transaction.addResponse(failureResponse);
117             }
118             transactionList.add(transaction);
119        }
120        return transactionList;
121     }
122
123     private List<Transaction> generateSequenceWithDependencyModel(VnfcFlowModel flowModel,
124             SequenceGeneratorInput input) throws Exception {
125         List<Transaction> transactionList = new LinkedList<>();
126         Integer transactionId = 1;
127         List<Integer> transactionIds = new LinkedList<>();
128         Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
129         while (itr.hasNext()){
130             List<Vnfc> vnfcs = itr.next();
131             for(Vnfc vnfc:vnfcs){
132                 boolean stopApplicationSupported = readApplicationStopCapability(input);
133                 if(stopApplicationSupported && !vnfc.getVserverList().isEmpty()){
134                     Transaction stopAppTransaction = new Transaction();
135                     stopAppTransaction.setTransactionId(transactionId++);
136                     stopAppTransaction.setAction(Action.STOP_APPLICATION.getActionType());
137                     stopAppTransaction.setActionLevel(ActionLevel.VNFC.getAction());
138                     ActionIdentifier stopActionIdentifier = new ActionIdentifier();
139                     stopActionIdentifier .setVnfcName(vnfc.getVnfcName());
140                     stopAppTransaction.setActionIdentifier(stopActionIdentifier );
141                     stopAppTransaction.setPayload(input.getRequestInfo().getPayload());
142                     Response failureResponse = new Response();
143                     failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
144                     Map<String,String> failureAction = new HashMap<>();
145                     failureAction.put(ResponseAction.STOP.getAction(),Boolean.TRUE.toString());
146                     failureResponse.setResponseAction(failureAction);
147                     stopAppTransaction.addResponse(failureResponse);
148                     transactionList.add(stopAppTransaction);
149                 }
150                 List<Vserver> vms = vnfc.getVserverList();
151                 for(Vserver vm:vms){
152                     if (!vmSupportsStop(input, vm)) {
153                         continue;
154                     }
155                     Transaction transaction = new Transaction();
156                     transaction.setTransactionId(transactionId);
157                     transactionIds.add(transactionId++);
158                     transaction.setAction(Action.STOP.getActionType());
159                     transaction.setActionLevel(ActionLevel.VM.getAction());
160                     ActionIdentifier actionIdentifier = new ActionIdentifier();
161                     actionIdentifier.setvServerId(vm.getId());
162                     transaction.setActionIdentifier(actionIdentifier);
163                     transaction.setPayload(input.getRequestInfo().getPayload());
164                     Response failureResponse = new Response();
165                     failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
166                     Map<String,String> failureAction = new HashMap<>();
167                     failureAction.put(ResponseAction.STOP.getAction(),Boolean.TRUE.toString());
168                     failureResponse.setResponseAction(failureAction);
169                     transaction.addResponse(failureResponse);
170                     transactionList.add(transaction);
171                 }
172             }
173         }
174         return transactionList;
175     }
176
177     private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, 
178             FlowStrategies flowStrategy) throws APPCException, InvalidDependencyModelException {
179         FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy);
180         if (flowBuilder == null) {
181             throw new APPCException("Flow Strategy not supported " + flowStrategy);
182         }
183         return flowBuilder.buildFlowModel(dependencyModel, inventoryModel);
184     }
185
186     private FlowStrategies readFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput)  {
187         Map<String, String> tunableParams = sequenceGeneratorInput.getTunableParams();
188         FlowStrategies strategy = null;
189         String strategyStr = null;
190         if (tunableParams != null) {
191             strategyStr = tunableParams.get(Constants.STRATEGY);
192             strategy = FlowStrategies.findByString(strategyStr);
193         }
194         if (strategy == null)
195              strategy= FlowStrategies.REVERSE;
196         return strategy;
197     }
198
199     private boolean isVnfcPresent(SequenceGeneratorInput input){
200         boolean vnfcPresent=true;
201         List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
202         for (Vserver vm : vservers) {
203             if(!(vm.getVnfc()!=null&& vm.getVnfc().getVnfcType()!=null&& vm.getVnfc().getVnfcName()!=null)){
204                 vnfcPresent=false;
205                 break;
206             }
207         }
208         return vnfcPresent;
209     }
210
211     private boolean readApplicationStopCapability(SequenceGeneratorInput input) {
212         CapabilityModel capability = input.getCapability();
213         if (capability == null) {
214             return true;
215         }
216         List<String> vnfcCapabilities = capability.getVnfcCapabilities();
217         if(vnfcCapabilities != null)
218             return vnfcCapabilities.stream()
219                     .anyMatch(p -> Capabilties.STOP_APPLICATION.getCapability().equalsIgnoreCase(p));
220
221         return false;
222     }
223
224     private boolean vmSupportsStop(SequenceGeneratorInput input, Vserver vm) {
225         boolean vmSupported = true;
226         if (input.getCapability() == null) {
227             logger.info("vmSupportsStop: " + "Capabilities model is null, returning vmSupported=" + vmSupported);
228             return vmSupported;
229         }
230         Map<String, List<String>> vmCapabilities = input.getCapability().getVmCapabilities();
231         if (vmCapabilities != null) {
232             if (!vmCapabilities.isEmpty()) {
233                 List<String> vmCapsForThisAction = vmCapabilities.get(Action.STOP.getActionType());
234                 if (vmCapsForThisAction != null) {
235                     vmSupported = false;
236                     if (!vmCapsForThisAction.isEmpty()) {
237                         if (vm.getVnfc() != null) {
238                             String vnfcFunctionCode = vm.getVnfc().getVnfcFunctionCode();
239                             if (vnfcFunctionCode != null && !vnfcFunctionCode.isEmpty()) {
240                                 for (String s : vmCapabilities.get(Action.STOP.getActionType()) ) {
241                                     if (s.equalsIgnoreCase(vnfcFunctionCode)) {
242                                         vmSupported = true;
243                                         logger.info("vmSupportsStop: vnfcFunctionCode=" + vnfcFunctionCode + " found in vmCapabilities");
244                                         break;
245                                     }
246                                 }
247                             } else {
248                                 logger.info("vmSupportsStop: " + "Inventory vnfcFunctionCode is null or empty");
249                             }
250                         } else {
251                             logger.info("vmSupportsStop: " + "Inventory vnfc is null or empty");
252                         } 
253                     } else {
254                         logger.info("vmSupportsStop: " + "Given action in vm entry in Capabilities model is empty");
255                     }
256                 } else {
257                     logger.info("vmSupportsStop: " + "Given action in vm entry in Capabilities model is null");
258                 }
259             } else {
260                 logger.info("vmSupportsStop: " + "Vm entry in Capabilities model is empty");
261             }
262         } else {
263             logger.info("vmSupportsStop: " + "Vm entry in Capabilities model is null");
264         }
265
266         logger.info("vmSupportsStop: " + "returning vmSupported=" + vmSupported + ", " + ((vmSupported)?"including":"excluding") + " vm=" + vm.getId());
267         return vmSupported;
268     }
269 }