aboutsummaryrefslogtreecommitdiffstats
path: root/appc-sequence-generator/appc-sequence-generator-bundle/src/main/java/org/onap/appc/seqgen/impl/StartSequenceGenerator.java
blob: 771c497317794fb298a415a8fd5619bbdd4b2e86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/*-
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Copyright (C) 2017 Amdocs
 * =============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * ============LICENSE_END=========================================================
 */


package org.onap.appc.seqgen.impl;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.apache.commons.lang3.StringUtils;
import org.onap.appc.dg.flowbuilder.FlowBuilder;
import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModelException;
import org.onap.appc.dg.flowbuilder.impl.FlowBuilderFactory;
import org.onap.appc.dg.objects.FlowStrategies;
import org.onap.appc.dg.objects.InventoryModel;
import org.onap.appc.dg.objects.VnfcDependencyModel;
import org.onap.appc.dg.objects.VnfcFlowModel;
import org.onap.appc.domainmodel.Vnfc;
import org.onap.appc.domainmodel.Vserver;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.seqgen.SequenceGenerator;
import org.onap.appc.seqgen.objects.ActionIdentifier;
import org.onap.appc.seqgen.objects.Constants;
import org.onap.appc.seqgen.objects.PreCheckOption;
import org.onap.appc.seqgen.objects.Response;
import org.onap.appc.seqgen.objects.SequenceGeneratorInput;
import org.onap.appc.seqgen.objects.Transaction;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static org.onap.appc.seqgen.objects.Constants.Action;
import static org.onap.appc.seqgen.objects.Constants.ActionLevel;
import static org.onap.appc.seqgen.objects.Constants.ResponseAction;
import static org.onap.appc.seqgen.objects.Constants.ResponseMessage;
import static org.onap.appc.seqgen.objects.Constants.PreCheckOperator;
import static org.onap.appc.seqgen.objects.Constants.Capabilties;
import static org.onap.appc.seqgen.objects.Constants.CapabilityLevel;
import static org.onap.appc.seqgen.objects.Constants.RETRY_COUNT_VALUE;
import static org.onap.appc.seqgen.objects.Constants.WAIT_TIME;
import static org.onap.appc.seqgen.objects.Constants.RETRY_COUNT;
import static org.onap.appc.seqgen.objects.Constants.WAIT_TIME_VALUE;;

public class StartSequenceGenerator implements SequenceGenerator {

    private static final EELFLogger logger = EELFManager.getInstance().getLogger(StartSequenceGenerator.class);

    private List<Transaction> generateSequenceWithOutDependency(SequenceGeneratorInput input) throws APPCException {

        List<Transaction> transactionList = new LinkedList<>();
        Integer transactionId = 1;
        List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
        List<Integer> transactionIds = new LinkedList<>();
        for (Vserver vm : vservers) {
            Transaction transaction = new Transaction();
            transaction.setTransactionId(transactionId);
            transactionIds.add(transactionId++);
            transaction.setAction(Action.START.getActionType());
            transaction.setActionLevel(ActionLevel.VM.getAction());
            ActionIdentifier actionIdentifier = new ActionIdentifier();
            actionIdentifier.setvServerId(vm.getId());
            transaction.setActionIdentifier(actionIdentifier);
            transaction.setPayload(input.getRequestInfo().getPayload());
            if(vservers.size()>1){
                Response ignoreResponse = new Response();
                ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
                Map<String, String> ignoreAction = new HashMap<>();
                ignoreAction.put(ResponseAction.IGNORE.getAction(), Boolean.TRUE.toString());
                ignoreResponse.setResponseAction(ignoreAction);
                transaction.addResponse(ignoreResponse);
            }
            transactionList.add(transaction);
        }
        return transactionList;
    }

    private boolean checkSingleTransaction(List<Vnfc> invVnfcList) {
        int vServerCount=0;
        for(Vnfc vnfc : invVnfcList) {
            List<Vserver> vms = vnfc.getVserverList();
            vServerCount=vServerCount+vms.size();
        }
        return vServerCount <= 1;
    }

    private void updateResponse(Transaction transaction) {
        Response ignoreResponse = new Response();
        ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
        Map<String, String> ignoreAction = new HashMap<>();
        ignoreAction.put(ResponseAction.IGNORE.getAction(), Boolean.TRUE.toString());
        ignoreResponse.setResponseAction(ignoreAction);
        transaction.addResponse(ignoreResponse);
    }

    private List<Transaction> generateSequenceWithDependencyModel(VnfcFlowModel flowModel, SequenceGeneratorInput input) throws APPCException {
        Integer waitTime = readWaitTime(input);
        Integer retryCount = readRetryCount(input);
        List<Transaction> transactionList = new LinkedList<>();
        Integer transactionId = 1;
        Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
        while (itr.hasNext()) {
            List<Vnfc> vnfcs = itr.next();
            for (Vnfc vnfc : vnfcs) {
                List<Vserver> vms = vnfc.getVserverList();
                List<Integer> transactionIds = new LinkedList<>();
                if(!vms.isEmpty()) {
                    for (Vserver vm : vms) {
                        Transaction transaction = new Transaction();
                        transaction.setTransactionId(transactionId);
                        transactionIds.add(transactionId++);
                        transaction.setAction(Action.START.getActionType());
                        transaction.setActionLevel(ActionLevel.VM.getAction());
                        ActionIdentifier actionIdentifier = new ActionIdentifier();
                        actionIdentifier.setvServerId(vm.getId());
                        transaction.setActionIdentifier(actionIdentifier);
                        transaction.setPayload(input.getRequestInfo().getPayload());
                        Response ignoreResponse = new Response();
                        ignoreResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
                        Map<String, String> ignoreAction = new HashMap<>();
                        ignoreAction.put(ResponseAction.IGNORE.getAction(), Boolean.TRUE.toString());
                        ignoreResponse.setResponseAction(ignoreAction);
                        transaction.addResponse(ignoreResponse);
                        transactionList.add(transaction);
                    }
                    boolean startApplicationSupported = readApplicationStartCapability(input);
                    if (startApplicationSupported) {
                        Transaction startAppTransaction = new Transaction();
                        startAppTransaction.setTransactionId(transactionId++);
                        startAppTransaction.setAction(Action.START_APPLICATION.getActionType());
                        startAppTransaction.setActionLevel(ActionLevel.VNFC.getAction());
                        ActionIdentifier startActionIdentifier = new ActionIdentifier();
                        startActionIdentifier.setVnfcName(vnfc.getVnfcName());
                        startAppTransaction.setActionIdentifier(startActionIdentifier);
                        startAppTransaction.setPayload(input.getRequestInfo().getPayload());

                        List<PreCheckOption> preCheckOptions = buildPreCheckOptions(transactionIds);
                        startAppTransaction.setPreCheckOperator(PreCheckOperator.ANY.getOperator());
                        startAppTransaction.setPrecheckOptions(preCheckOptions);
                        transactionList.add(startAppTransaction);
                    }
                    boolean healthCheckSupported = readHealthCheckCapabilites(input.getCapability());
                    if (healthCheckSupported) {
                        Transaction healthCheckTransaction = new Transaction();
                        healthCheckTransaction.setTransactionId(transactionId++);
                        healthCheckTransaction.setAction(Action.HEALTH_CHECK.getActionType());
                        healthCheckTransaction.setActionLevel(ActionLevel.VNFC.getAction());
                        ActionIdentifier healthCheckActionIdentifier = new ActionIdentifier();
                        healthCheckActionIdentifier.setVnfcName(vnfc.getVnfcName());
                        healthCheckTransaction.setActionIdentifier(healthCheckActionIdentifier);
                        healthCheckTransaction.setPayload(input.getRequestInfo().getPayload());

                        Response retryResponse = new Response();
                        retryResponse.setResponseMessage(ResponseMessage.UNHEALTHY.getResponse());
                        Map<String, String> retryAction = new HashMap<>();
                        retryAction.put(ResponseAction.RETRY.getAction(), retryCount.toString());
                        retryAction.put(ResponseAction.WAIT.getAction(), waitTime.toString());
                        retryResponse.setResponseAction(retryAction);
                        healthCheckTransaction.addResponse(retryResponse);

                        Response healthyResponse = new Response();
                        healthyResponse.setResponseMessage(ResponseMessage.HEALTHY.getResponse());
                        Map<String, String> healthyAction = new HashMap<>();
                        healthyAction.put(ResponseAction.CONTINUE.getAction().toLowerCase(), Boolean.TRUE.toString());
                        healthyResponse.setResponseAction(healthyAction);
                        healthCheckTransaction.addResponse(healthyResponse);

                        Response failureResponse = new Response();
                        failureResponse.setResponseMessage(ResponseMessage.FAILURE.getResponse());
                        Map<String, String> failureResonseAction = new HashMap<>();
                        failureResonseAction.put(ResponseAction.STOP.getAction(), Boolean.TRUE.toString());
                        failureResponse.setResponseAction(failureResonseAction);
                        healthCheckTransaction.addResponse(failureResponse);
                        transactionList.add(healthCheckTransaction);
                    }
                }
            }
        }
        return transactionList;
    }

    private List<PreCheckOption> buildPreCheckOptions(List<Integer> transactionIds) {
        List<PreCheckOption> preCheckOptions = new LinkedList<>();
        for (Integer vmTransactionId : transactionIds) {
            PreCheckOption option = new PreCheckOption();
            option.setPreTransactionId(vmTransactionId);
            option.setParamName("status");
            option.setParamValue("success");
            preCheckOptions.add(option);
        }
        return preCheckOptions;
    }

    @Override
    public List<Transaction> generateSequence(SequenceGeneratorInput input) throws APPCException {
            if (input.getRequestInfo().getActionLevel().equals(ActionLevel.VNF.getAction()) && input.getDependencyModel() != null) {
                if(isVnfcPresent(input)) {
                    FlowStrategies flowStrategy = readFlowStrategy(input);
                    VnfcFlowModel flowModel = null;
                    try {
                        flowModel = buildFlowModel(input.getInventoryModel()
                                , input.getDependencyModel(), flowStrategy);
                    } catch (InvalidDependencyModelException invalidDependencyModelException) {
                        logger.error("Error Generating Sequence", invalidDependencyModelException);
                        throw  new APPCException(invalidDependencyModelException.getMessage(), invalidDependencyModelException);
                    }
                    logger.debug("Flow Model " + flowModel);
                    return generateSequenceWithDependencyModel(flowModel, input);
                }
                 else throw new APPCException("Vnfc details is missing in the input");
            } else {
                logger.info("Generating sequence without dependency model");
                return generateSequenceWithOutDependency(input);
            }
    }

    private VnfcFlowModel buildFlowModel(InventoryModel inventoryModel, VnfcDependencyModel dependencyModel, FlowStrategies flowStrategy) throws APPCException, InvalidDependencyModelException {
        FlowBuilder flowBuilder = FlowBuilderFactory.getInstance().getFlowBuilder(flowStrategy);
        if (flowBuilder == null) {
            throw new APPCException("Flow Strategy not supported " + flowStrategy);
        }
        return flowBuilder.buildFlowModel(dependencyModel, inventoryModel);
    }

    private FlowStrategies readFlowStrategy(SequenceGeneratorInput sequenceGeneratorInput) {
        Map<String, String> tunableParams = sequenceGeneratorInput.getTunableParams();
        FlowStrategies strategy=null;
        String strategyStr = null;
        if (tunableParams != null) {
            strategyStr = tunableParams.get(Constants.STRATEGY);
            strategy = FlowStrategies.findByString(strategyStr);
        }
        if (strategy == null)
            strategy= FlowStrategies.FORWARD;
        return strategy;
    }

    private boolean readHealthCheckCapabilites(Map<String, List<String>> capabilities) {
        if (capabilities != null) {
            List<String> vnfcCapabilities = capabilities.get(CapabilityLevel.VNFC.getLevel());
            if (vnfcCapabilities != null)
                return vnfcCapabilities.stream()
                        .anyMatch(p -> Capabilties.HEALTH_CHECK.getCapability().equalsIgnoreCase(p));
        }
        return false;
    }

    private boolean readApplicationStartCapability(SequenceGeneratorInput input) {
        Map<String, List<String>> capability = input.getCapability();
        if (capability != null) {
            List<String> vnfcCapabilities = capability.get(CapabilityLevel.VNFC.getLevel());
            if (vnfcCapabilities != null)
                return vnfcCapabilities.stream().anyMatch(p -> Capabilties.START_APPLICATION.getCapability().equalsIgnoreCase(p));
        }
        return false;
    }

    private Integer readRetryCount(SequenceGeneratorInput input) throws APPCException {
        String paramValStr = input.getTunableParams().get(RETRY_COUNT);
        if (StringUtils.isEmpty(paramValStr)) {
            return RETRY_COUNT_VALUE;
        }
        try {
            return Integer.parseInt(paramValStr);
        } catch (NumberFormatException e) {
            String message = "Invalid Number for Retry Count " + paramValStr;
            logger.error(message, e);
            throw new APPCException(message);
        }
    }

    private boolean isVnfcPresent(SequenceGeneratorInput input){
        boolean vnfcPresent=true;
        List<Vserver> vservers = input.getInventoryModel().getVnf().getVservers();
        for (Vserver vm : vservers) {
            if(!(vm.getVnfc()!=null&& vm.getVnfc().getVnfcType()!=null&& vm.getVnfc().getVnfcName()!=null)){
                vnfcPresent=false;break;
            }
        }
        return vnfcPresent;
    }

    private Integer readWaitTime(SequenceGeneratorInput input) throws APPCException {
        String paramValStr = input.getTunableParams().get(WAIT_TIME);
        if (StringUtils.isEmpty(paramValStr)) {
            return WAIT_TIME_VALUE;
        }
        try {
            return Integer.parseInt(paramValStr);
        } catch (NumberFormatException e) {
            String message = "Invalid Number for Wait Time " + paramValStr;
            logger.error(message, e);
            throw new APPCException(message);
        }
    }
}