Fix some sonar issues
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / EvacuateServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.adapter.iaas.provider.operation.impl;
26
27 import org.onap.appc.Constants;
28 import org.onap.appc.adapter.iaas.ProviderAdapter;
29 import org.onap.appc.adapter.iaas.impl.IdentityURL;
30 import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl;
31 import org.onap.appc.adapter.iaas.impl.RequestContext;
32 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
33 import org.onap.appc.adapter.iaas.impl.VMURL;
34 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
35 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
36 import org.onap.appc.configuration.Configuration;
37 import org.onap.appc.configuration.ConfigurationFactory;
38 import org.onap.appc.exceptions.APPCException;
39 import org.onap.appc.i18n.Msg;
40 import com.att.cdp.exceptions.ContextConnectionException;
41 import com.att.cdp.exceptions.ResourceNotFoundException;
42 import com.att.cdp.exceptions.ZoneException;
43 import com.att.cdp.zones.ComputeService;
44 import com.att.cdp.zones.Context;
45 import com.att.cdp.zones.Provider;
46 import com.att.cdp.zones.model.Hypervisor;
47 import com.att.cdp.zones.model.Hypervisor.Status;
48 import com.att.cdp.zones.model.Hypervisor.State;
49 import com.att.cdp.zones.model.Image;
50 import com.att.cdp.zones.model.ModelObject;
51 import com.att.cdp.zones.model.Server;
52 import com.att.eelf.configuration.EELFLogger;
53 import com.att.eelf.configuration.EELFManager;
54 import com.att.eelf.i18n.EELFResourceManager;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
56 import org.glassfish.grizzly.http.util.HttpStatus;
57 import org.slf4j.MDC;
58
59 import java.io.IOException;
60 import java.text.DateFormat;
61 import java.text.SimpleDateFormat;
62 import java.util.Arrays;
63 import java.util.Date;
64 import java.util.List;
65 import java.util.Map;
66 import java.util.TimeZone;
67 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
68
69 public class EvacuateServer extends ProviderServerOperation {
70
71     private static final String EVACUATE_STATUS = "EVACUATE_STATUS";
72     private static final String EVACUATE_SERVER = "Evacuate Server";
73
74     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
75     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
76
77     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
78     private ProviderAdapterImpl paImpl = null;
79
80     private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String targetHost)
81             throws ZoneException, RequestFailedException {
82
83         Context ctx = server.getContext();
84         Provider provider = ctx.getProvider();
85         ComputeService service = ctx.getComputeService();
86
87         /*
88          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
89          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
90          * to one we can deal with. If not, then we have to fail the request.
91          */
92         try {
93             if (server.getStatus().equals(Server.Status.PENDING)) {
94                 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
95                         Server.Status.SUSPENDED, Server.Status.PAUSED);
96             }
97         } catch (RequestFailedException e) {
98             // evacuate is a special case. If the server is still in a Pending state, we want to
99             // continue with evacuate
100             logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...");
101         }
102
103         setTimeForMetricsLogger();
104
105         String msg;
106         try {
107             while (rc.attempt()) {
108                 try {
109                     logger.debug("Calling CDP moveServer - server id = " + server.getId());
110                     service.moveServer(server.getId(), targetHost);
111                     // Wait for completion, expecting the server to go to a non pending state
112                     waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
113                             Server.Status.SUSPENDED, Server.Status.PAUSED);
114                     break;
115                 } catch (ContextConnectionException e) {
116                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
117                             ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
118                             Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
119                             Integer.toString(rc.getRetryLimit()));
120                     logger.error(msg, e);
121                     metricsLogger.error(msg, e);
122                     rc.delay();
123                 }
124             }
125
126         } catch (ZoneException e) {
127             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
128                     e.getMessage());
129             logger.error(msg);
130             metricsLogger.error(msg);
131             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
132         }
133
134         if (rc.isFailed()) {
135             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
136             logger.error(msg);
137             metricsLogger.error(msg);
138             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_GATEWAY_502, server);
139         }
140         rc.reset();
141     }
142
143
144     /**
145      * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
146      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
147      */
148     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
149         Server server = null;
150         RequestContext rc = new RequestContext(ctx);
151         rc.isAlive();
152
153         setTimeForMetricsLogger();
154
155         String msg;
156         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
157         try {
158             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
159                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
160
161             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
162             String vmUrl = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
163             VMURL vm = VMURL.parseURL(vmUrl);
164
165             if (validateVM(rc, appName, vmUrl, vm)) {
166                 return null;
167             }
168
169             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
170             String identStr = (ident == null) ? null : ident.toString();
171
172             // retrieve the optional parameters
173             String rebuildVm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
174             String targetHostId = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
175
176             Context context = null;
177             try {
178                 context = getContext(rc, vmUrl, identStr);
179                 if (context != null) {
180
181                     server = lookupServer(rc, context, vm.getServerId());
182                     logger.debug(Msg.SERVER_FOUND, vmUrl, context.getTenantName(), server.getStatus().toString());
183
184                     // check target host status
185                     if (isComputeNodeDown(context, targetHostId)) {
186                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
187                                 "Target host " + targetHostId + " status is not UP/ENABLED");
188                         logger.error(msg);
189                         metricsLogger.error(msg);
190                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
191                     }
192
193                     // save hypervisor name before evacuate
194                     String hypervisor = server.getHypervisor().getHostName();
195
196                     evacuateServer(rc, server, targetHostId);
197
198                     server.refreshAll();
199                     String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
200                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
201
202                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate
203                     // failed.
204                     if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
205                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
206                                 "Hypervisor host " + hypervisor
207                                         + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
208                         logger.error(msg);
209                         metricsLogger.error(msg);
210                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
211                     }
212
213                     // check VM status after evacuate
214                     if (server.getStatus() == Server.Status.ERROR) {
215                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
216                                 "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
217                         logger.error(msg);
218                         metricsLogger.error(msg);
219                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
220                     }
221
222                     context.close();
223                     doSuccess(rc);
224                     ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
225
226                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
227                     // This is the default behavior unless the optional parameter is set to FALSE.
228                     if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
229                         List<Image> snapshots = server.getSnapshots();
230                         if (snapshots == null || snapshots.isEmpty()) {
231                             logger.debug("No snapshots available - skipping rebuild after evacuate");
232                         } else if (paImpl != null) {
233                             logger.debug("Executing a rebuild after evacuate");
234                             paImpl.rebuildServer(params, ctx);
235                             // Check error code for rebuild errors. Evacuate had set it to 200 after
236                             // a successful evacuate. Rebuild updates the error code.
237                             String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
238                             if (rebuildErrorCode != null) {
239                                 try {
240                                     int errorCode = Integer.parseInt(rebuildErrorCode);
241                                     if (errorCode != HttpStatus.OK_200.getStatusCode()) {
242                                         logger.debug("Rebuild after evacuate failed - error code=" + errorCode
243                                                 + ", message=" + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
244                                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
245                                                 server.getName(), hypervisor, hypervisorAfterEvacuate,
246                                                 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
247                                         logger.error(msg);
248                                         metricsLogger.error(msg);
249                                         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
250                                         // update error message while keeping the error code the
251                                         // same as before
252                                         doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
253                                     }
254                                 } catch (NumberFormatException e) {
255                                     // ignore
256                                 }
257                             }
258                         }
259                     }
260
261                 }
262             } catch (ResourceNotFoundException e) {
263                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
264                 logger.error(msg);
265                 metricsLogger.error(msg);
266                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
267             } catch (RequestFailedException e) {
268                 doFailure(rc, e.getStatus(), e.getMessage());
269             } catch (IOException | ZoneException e1) {
270                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
271                         Operation.EVACUATE_SERVICE.toString(), vmUrl, context == null ? "Unknown" : context.getTenantName());
272                 logger.error(msg, e1);
273                 metricsLogger.error(msg, e1);
274                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
275             }
276         } catch (RequestFailedException e) {
277             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
278             logger.error(msg);
279             metricsLogger.error(msg);
280             doFailure(rc, e.getStatus(), e.getMessage());
281         }
282
283         return server;
284     }
285
286     /**
287      * Check if a Compute node is down.
288      * 
289      * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
290      * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
291      * 
292      * @param context The current context
293      * 
294      * @param host The host name (short or fully qualified) of a compute node
295      * 
296      * @return true if the node is determined as down, false for all other cases
297      */
298     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
299         ComputeService service = context.getComputeService();
300         boolean nodeDown = false;
301
302         if (host != null && ! host.isEmpty()) {
303             List<Hypervisor> hypervisors = service.getHypervisors();
304             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
305             for (Hypervisor hv : hypervisors) {
306                 if (isHostMatchesHypervisor(host, hv)) {
307                     State hstate = hv.getState();
308                     Status hstatus = hv.getStatus();
309                     logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString()
310                             + "/" + hstatus.toString());
311                     if (hstate != State.UP || hstatus != Status.ENABLED) {
312                         nodeDown = true;
313                     }
314                 }
315             }
316         }
317         return nodeDown;
318     }
319
320     private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
321         return hypervisor.getHostName().startsWith(host);
322     }
323
324     @Override
325     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
326             throws APPCException {
327         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
328         logOperation(Msg.EVACUATING_SERVER, params, context);
329
330         setTimeForMetricsLogger();
331
332         metricsLogger.info("Executing Provider Operation: Evacuate");
333         return evacuateServer(params, context);
334     }
335
336     private void setTimeForMetricsLogger() {
337         long startTime = System.currentTimeMillis();
338         TimeZone tz = TimeZone.getTimeZone("UTC");
339         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
340         df.setTimeZone(tz);
341         long endTime = System.currentTimeMillis();
342         long duration = endTime - startTime;
343         String durationStr = String.valueOf(duration);
344         String endTimeStrUTC = df.format(new Date());
345         MDC.put("EndTimestamp", endTimeStrUTC);
346         MDC.put("ElapsedTime", durationStr);
347         MDC.put("TargetEntity", "cdp");
348         MDC.put("TargetServiceName", "evacuate server");
349         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
350     }
351
352     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
353         paImpl = pai;
354     }
355 }