Merge of new rebased code
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / openecomp / appc / adapter / iaas / provider / operation / impl / base / ProviderStackOperation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-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.openecomp.appc.adapter.iaas.provider.operation.impl.base;
23
24 import org.openecomp.appc.Constants;
25 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
26 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
27 import org.openecomp.appc.adapter.openstack.heat.StackResource;
28 import org.openecomp.appc.i18n.Msg;
29 import com.att.cdp.exceptions.ContextConnectionException;
30 import com.att.cdp.exceptions.ResourceNotFoundException;
31 import com.att.cdp.exceptions.TimeoutException;
32 import com.att.cdp.exceptions.ZoneException;
33 import com.att.cdp.zones.Context;
34 import com.att.cdp.zones.Provider;
35 import com.att.cdp.zones.StackService;
36 import com.att.cdp.zones.model.Stack;
37 import com.att.cdp.zones.spi.AbstractService;
38 import com.att.cdp.zones.spi.RequestState;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import com.att.eelf.i18n.EELFResourceManager;
42 import org.openecomp.sdnc.sli.SvcLogicContext;
43 import com.woorea.openstack.base.client.OpenStackBaseException;
44 import org.glassfish.grizzly.http.util.HttpStatus;
45
46 import java.util.List;
47
48 /**
49  * @since September 29, 2016
50  */
51 public abstract class ProviderStackOperation extends ProviderOperation{
52
53     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ProviderStackOperation.class);
54
55
56     protected void trackRequest(Context context, AbstractService.State... states) {
57         RequestState.clear();
58
59         if (null == states) 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     private boolean checkStatus(String expectedStatus, int pollInterval, String actualStatus) {
91         if (actualStatus.toUpperCase().equals(expectedStatus)) {
92             return true;
93         } else {
94             try {
95                 Thread.sleep(pollInterval * 1000);
96             } catch (InterruptedException ignored) {
97             }
98         }
99         return false;
100     }
101
102     protected boolean waitForStack(Stack stack, StackResource stackResource, String expectedStatus)
103             throws OpenStackBaseException, TimeoutException {
104         int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
105         int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
106         long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;
107
108         while (System.currentTimeMillis() < maxTimeToWait) {
109             String stackStatus = stackResource.show(stack.getName(), stack.getId()).execute().getStackStatus();
110             logger.debug("Stack status : " + stackStatus);
111             if (stackStatus.toUpperCase().contains("FAILED")) return false;
112             if(checkStatus(expectedStatus, pollInterval, stackStatus)) return true;
113         }
114         throw new TimeoutException("Timeout waiting for stack status change");
115     }
116
117     protected Stack lookupStack(RequestContext rc, Context context, String id)
118             throws ZoneException, RequestFailedException {
119         StackService stackService = context.getStackService();
120         Stack stack = null;
121         String msg;
122         Provider provider = context.getProvider();
123         while (rc.attempt()) {
124             try {
125                 List<Stack> stackList = stackService.getStacks();
126                 for (Stack stackObj : stackList) {
127                     if (stackObj.getId().equals(id)) {
128                         stack = stackObj;
129                         break;
130                     }
131                 }
132                 break;
133             } catch (ContextConnectionException e) {
134                 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), stackService.getURL(),
135                         context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
136                         Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
137                         Integer.toString(rc.getRetryLimit()));
138                 logger.error(msg, e);
139                 rc.delay();
140             }
141
142         }
143         if (rc.isFailed()) {
144             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), stackService.getURL());
145             logger.error(msg);
146             doFailure(rc, HttpStatus.BAD_GATEWAY_502, msg);
147             throw new RequestFailedException("Lookup Stack", msg, HttpStatus.BAD_GATEWAY_502, stack);
148         }
149
150         if (stack == null) {
151             throw new ResourceNotFoundException("Stack not found with Id : {" + id + "}");
152         }
153         return stack;
154     }
155
156
157     protected boolean waitForStackStatus(RequestContext rc, Stack stack, Stack.Status expectedStatus) throws ZoneException, RequestFailedException {
158         SvcLogicContext ctx = rc.getSvcLogicContext();
159         Context context = stack.getContext();
160         StackService stackService = context.getStackService();
161
162         int pollInterval = configuration.getIntegerProperty(Constants.PROPERTY_OPENSTACK_POLL_INTERVAL);
163         int timeout = configuration.getIntegerProperty(Constants.PROPERTY_STACK_STATE_CHANGE_TIMEOUT);
164         long maxTimeToWait = System.currentTimeMillis() + (long) timeout * 1000;
165         Stack.Status stackStatus;
166         while (System.currentTimeMillis() < maxTimeToWait) {
167             stackStatus = stackService.getStack(stack.getName(), stack.getId()).getStatus();
168             logger.debug("Stack status : " + stackStatus.toString());
169             if (stackStatus == expectedStatus) {
170                 return true;
171             } else if (stackStatus == Stack.Status.FAILED) {
172                 return false;
173             } else {
174                 try {
175                     Thread.sleep(pollInterval * 1000);
176                 } catch (InterruptedException e) {
177                     logger.trace("Sleep threw interrupted exception, should never occur");
178                 }
179             }
180         }
181
182         ctx.setAttribute("TERMINATE_STATUS", "ERROR");
183         throw new TimeoutException("Timeout waiting for stack status change");
184
185     }
186 }