Sonar Fixes - ProviderStackOperation.java
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / base / ProviderStackOperation.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  * Modifications Copyright (C) 2019 IBM.
9  * =============================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * 
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.iaas.provider.operation.impl.base;
26
27 import org.onap.appc.Constants;
28 import org.onap.appc.adapter.iaas.impl.RequestContext;
29 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
30 import org.onap.appc.adapter.openstack.heat.StackResource;
31 import org.onap.appc.i18n.Msg;
32 import com.att.cdp.exceptions.ContextConnectionException;
33 import com.att.cdp.exceptions.ResourceNotFoundException;
34 import com.att.cdp.exceptions.TimeoutException;
35 import com.att.cdp.exceptions.ZoneException;
36 import com.att.cdp.zones.Context;
37 import com.att.cdp.zones.Provider;
38 import com.att.cdp.zones.StackService;
39 import com.att.cdp.zones.model.Stack;
40 import com.att.cdp.zones.spi.AbstractService;
41 import com.att.cdp.zones.spi.RequestState;
42 import com.att.eelf.configuration.EELFLogger;
43 import com.att.eelf.configuration.EELFManager;
44 import com.att.eelf.i18n.EELFResourceManager;
45 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
46 import com.woorea.openstack.base.client.OpenStackBaseException;
47 import org.glassfish.grizzly.http.util.HttpStatus;
48 import java.util.List;
49
50 public abstract class ProviderStackOperation extends ProviderOperation {
51
52     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderStackOperation.class);
53
54
55     protected void trackRequest(Context context, AbstractService.State... states) {
56         RequestState.clear();
57
58         if (null == states)
59             return;
60         for (AbstractService.State state : states) {
61             RequestState.put(state.getName(), state.getValue());
62         }
63
64         Thread currentThread = Thread.currentThread();
65         StackTraceElement[] stack = currentThread.getStackTrace();
66         if (stack != null && stack.length > 0) {
67             int index = 0;
68             StackTraceElement element;
69             for (; index < stack.length; index++) {
70                 element = stack[index];
71                 if ("trackRequest".equals(element.getMethodName())) { //$NON-NLS-1$
72                     break;
73                 }
74             }
75             index++;
76
77             if (index < stack.length) {
78                 element = stack[index];
79                 RequestState.put(RequestState.METHOD, element.getMethodName());
80                 RequestState.put(RequestState.CLASS, element.getClassName());
81                 RequestState.put(RequestState.LINE_NUMBER, Integer.toString(element.getLineNumber()));
82                 RequestState.put(RequestState.THREAD, currentThread.getName());
83                 RequestState.put(RequestState.PROVIDER, context.getProvider().getName());
84                 RequestState.put(RequestState.TENANT, context.getTenantName());
85                 RequestState.put(RequestState.PRINCIPAL, context.getPrincipal());
86             }
87         }
88     }
89
90     /*
91      * Changed the 'pollInterval' type as long. Thread.sleep method needs 'long millis' as an argument
92      */
93     private boolean checkStatus(String expectedStatus, long pollInterval, String actualStatus) {
94         if (actualStatus.toUpperCase().equals(expectedStatus)) {
95             return true;
96         } else {
97             try {
98                 Thread.sleep(pollInterval * 1000);
99             } catch (InterruptedException ex) {
100                 logger.trace(ex.getMessage(), ex);
101                 Thread.currentThread().interrupt();
102             }
103         }
104         return false;
105     }
106
107     protected boolean waitForStack(Stack stack, StackResource stackResource, String expectedStatus)
108             throws OpenStackBaseException, TimeoutException {
109         int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
110         int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
111         long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;
112
113         while (System.currentTimeMillis() < maxTimeToWait) {
114             String stackStatus = stackResource.show(stack.getName(), stack.getId()).execute().getStackStatus();
115             logger.debug("Stack status : " + stackStatus);
116             if (stackStatus.toUpperCase().contains("FAILED"))
117                 return false;
118             if (checkStatus(expectedStatus, pollInterval, stackStatus))
119                 return true;
120         }
121         throw new TimeoutException("Timeout waiting for stack status change");
122     }
123
124     protected Stack lookupStack(RequestContext rc, Context context, String id)
125             throws ZoneException, RequestFailedException {
126         StackService stackService = context.getStackService();
127         Stack stack = null;
128         String msg;
129         Provider provider = context.getProvider();
130         while (rc.attempt()) {
131             try {
132                 List<Stack> stackList = stackService.getStacks();
133                 for (Stack stackObj : stackList) {
134                     if (stackObj.getId().equals(id)) {
135                         stack = stackObj;
136                         break;
137                     }
138                 }
139                 break;
140             } catch (ContextConnectionException e) {
141                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), stackService.getURL(),
142                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
143                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
144                         Integer.toString(rc.getRetryLimit()));
145                 logger.error(msg, e);
146                 rc.delay();
147             }
148
149         }
150         if (rc.isFailed()) {
151             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), stackService.getURL());
152             logger.error(msg);
153             doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
154             throw new RequestFailedException("Lookup Stack", msg, HttpStatus.BAD_GATEWAY_502, stack);
155         }
156
157         if (stack == null) {
158             throw new ResourceNotFoundException("Stack not found with Id : {" + id + "}");
159         }
160         return stack;
161     }
162
163
164     protected boolean waitForStackStatus(RequestContext rc, Stack stack, Stack.Status expectedStatus)
165             throws ZoneException, RequestFailedException {
166         SvcLogicContext ctx = rc.getSvcLogicContext();
167         Context context = stack.getContext();
168         StackService stackService = context.getStackService();
169         /*
170          * Changed the 'pollInterval' type as long. Thread.sleep method needs 'long millis' as an argument
171          */
172         long pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
173         int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
174         long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;
175         Stack.Status stackStatus;
176         while (System.currentTimeMillis() < maxTimeToWait) {
177             stackStatus = stackService.getStack(stack.getName(), stack.getId()).getStatus();
178             logger.debug("Stack status : " + stackStatus.toString());
179             if (stackStatus == expectedStatus) {
180                 return true;
181             } else if (stackStatus == Stack.Status.FAILED) {
182                 return false;
183             } else {
184                 try {
185                     Thread.sleep(pollInterval * 1000);
186                 } catch (InterruptedException e) {
187                     logger.trace("Sleep threw interrupted exception, should never occur", e);
188                     Thread.currentThread().interrupt();
189                 }
190             }
191         }
192
193         ctx.setAttribute("TERMINATE_STATUS", "ERROR");
194         throw new TimeoutException("Timeout waiting for stack status change");
195
196     }
197 }