EvacuateServer fixes
[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() ..." ,e);
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, e);
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;
177             String tenantName = "Unknown";//to be used also in case of exception
178             try {
179                 context = getContext(rc, vmUrl, identStr);
180                 if (context != null) {
181                     tenantName = context.getTenantName();//this varaible also is used in case of exception
182                     server = lookupServer(rc, context, vm.getServerId());
183                     logger.debug(Msg.SERVER_FOUND, vmUrl, tenantName, server.getStatus().toString());
184
185                     // check target host status
186                     checkHostStatus(server, targetHostId, context);
187
188                     // save hypervisor name before evacuate
189                     String hypervisor = server.getHypervisor().getHostName();
190
191                     evacuateServer(rc, server, targetHostId);
192
193                     server.refreshAll();
194                     String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
195                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
196
197                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate
198                     // failed.
199                     checkHypervisor(server, hypervisor, hypervisorAfterEvacuate);
200
201                     // check VM status after evacuate
202                     checkStatus(server);
203                     context.close();
204                     doSuccess(rc);
205                     ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
206
207                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
208                     // This is the default behavior unless the optional parameter is set to FALSE.
209                     if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
210                         List<Image> snapshots = server.getSnapshots();
211                         if (snapshots == null || snapshots.isEmpty()) {
212                             logger.debug("No snapshots available - skipping rebuild after evacuate");
213                         } else if (paImpl != null) {
214                             logger.debug("Executing a rebuild after evacuate");
215                             paImpl.rebuildServer(params, ctx);
216                             // Check error code for rebuild errors. Evacuate had set it to 200 after
217                             // a successful evacuate. Rebuild updates the error code.
218                             String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
219                             if (rebuildErrorCode != null) {
220                                 try {
221                                     int errorCode = Integer.parseInt(rebuildErrorCode);
222                                     if (errorCode != HttpStatus.OK_200.getStatusCode()) {
223                                         logger.debug("Rebuild after evacuate failed - error code=" + errorCode
224                                                 + ", message=" + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
225                                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
226                                                 server.getName(), hypervisor, hypervisorAfterEvacuate,
227                                                 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
228                                         logger.error(msg);
229                                         metricsLogger.error(msg);
230                                         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
231                                         // update error message while keeping the error code the
232                                         // same as before
233                                         doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
234                                     }
235                                 } catch (NumberFormatException e) {
236                                     // ignore
237                                 }
238                             }
239                         }
240                     }
241
242                 }
243             } catch (ResourceNotFoundException e) {
244                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
245                 logger.error(msg);
246                 metricsLogger.error(msg);
247                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
248             } catch (RequestFailedException e) {
249                 logger.error("Request failed", e);
250                 doFailure(rc, e.getStatus(), e.getMessage());
251             } catch (IOException | ZoneException e1) {
252                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
253                         Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
254                 logger.error(msg, e1);
255                 metricsLogger.error(msg, e1);
256                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
257             }
258         } catch (RequestFailedException e) {
259             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
260             logger.error(msg, e);
261             metricsLogger.error(msg);
262             doFailure(rc, e.getStatus(), e.getMessage());
263         }
264
265         return server;
266     }
267
268     private void checkHostStatus(Server server, String targetHostId, Context context)
269         throws ZoneException, RequestFailedException {
270         if (isComputeNodeDown(context, targetHostId)) {
271             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
272                     "Target host " + targetHostId + " status is not UP/ENABLED");
273             logger.error(msg);
274             metricsLogger.error(msg);
275             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
276         }
277     }
278
279     private void checkHypervisor(Server server, String hypervisor, String hypervisorAfterEvacuate)
280         throws RequestFailedException {
281         if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
282             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
283                     "Hypervisor host " + hypervisor
284                             + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
285             logger.error(msg);
286             metricsLogger.error(msg);
287             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
288         }
289     }
290
291     private void checkStatus(Server server) throws RequestFailedException {
292         if (server.getStatus() == Server.Status.ERROR) {
293             String msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
294                     "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
295             logger.error(msg);
296             metricsLogger.error(msg);
297             throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
298         }
299     }
300
301     /**
302      * Check if a Compute node is down.
303      * 
304      * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
305      * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
306      * 
307      * @param context The current context
308      * 
309      * @param host The host name (short or fully qualified) of a compute node
310      * 
311      * @return true if the node is determined as down, false for all other cases
312      */
313     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
314         ComputeService service = context.getComputeService();
315         boolean nodeDown = false;
316
317         if (host != null && ! host.isEmpty()) {
318             List<Hypervisor> hypervisors = service.getHypervisors();
319             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
320             for (Hypervisor hv : hypervisors) {
321                 nodeDown = isNodeDown(host, nodeDown, hv);
322             }
323         }
324         return nodeDown;
325     }
326
327     private boolean isNodeDown(String host, boolean nodeDown, Hypervisor hv) {
328         if (isHostMatchesHypervisor(host, hv)) {
329             State hstate = hv.getState();
330             Status hstatus = hv.getStatus();
331             logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString()
332                     + "/" + hstatus.toString());
333             if (hstate != State.UP || hstatus != Status.ENABLED) {
334                 return true;
335             }
336         }
337         return nodeDown;
338     }
339
340     private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
341         return hypervisor.getHostName().startsWith(host);
342     }
343
344     @Override
345     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
346             throws APPCException {
347         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
348         logOperation(Msg.EVACUATING_SERVER, params, context);
349
350         setTimeForMetricsLogger();
351
352         metricsLogger.info("Executing Provider Operation: Evacuate");
353         return evacuateServer(params, context);
354     }
355
356     private void setTimeForMetricsLogger() {
357         long startTime = System.currentTimeMillis();
358         TimeZone tz = TimeZone.getTimeZone("UTC");
359         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
360         df.setTimeZone(tz);
361         long endTime = System.currentTimeMillis();
362         long duration = endTime - startTime;
363         String durationStr = String.valueOf(duration);
364         String endTimeStrUTC = df.format(new Date());
365         MDC.put("EndTimestamp", endTimeStrUTC);
366         MDC.put("ElapsedTime", durationStr);
367         MDC.put("TargetEntity", "cdp");
368         MDC.put("TargetServiceName", "evacuate server");
369         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
370     }
371
372     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
373         paImpl = pai;
374     }
375 }