Applying license changes to all files
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / openecomp / 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.openecomp.appc.adapter.iaas.provider.operation.impl;
26
27 import org.openecomp.appc.Constants;
28 import org.openecomp.appc.adapter.iaas.ProviderAdapter;
29 import org.openecomp.appc.adapter.iaas.impl.IdentityURL;
30 import org.openecomp.appc.adapter.iaas.impl.ProviderAdapterImpl;
31 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
32 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
33 import org.openecomp.appc.adapter.iaas.impl.VMURL;
34 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation;
35 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
36 import org.openecomp.appc.configuration.Configuration;
37 import org.openecomp.appc.configuration.ConfigurationFactory;
38 import org.openecomp.appc.exceptions.APPCException;
39 import org.openecomp.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.openecomp.sdnc.sli.SvcLogicContext;
56 import org.glassfish.grizzly.http.util.HttpStatus;
57 import org.slf4j.MDC;
58
59 import java.text.DateFormat;
60 import java.text.SimpleDateFormat;
61 import java.util.Arrays;
62 import java.util.Date;
63 import java.util.List;
64 import java.util.Map;
65 import java.util.TimeZone;
66
67 import static org.openecomp.appc.adapter.utils.Constants.ADAPTER_NAME;
68
69 public class EvacuateServer extends ProviderServerOperation {
70
71     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
72     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
73     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
74     private ProviderAdapterImpl paImpl = null;
75
76
77     private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String target_host) throws ZoneException, RequestFailedException {
78
79         String msg;
80         Context ctx = server.getContext();
81         Provider provider = ctx.getProvider();
82         ComputeService service = ctx.getComputeService();
83         
84         /*
85          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
86          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
87          * to one we can deal with. If not, then we have to fail the request.
88          */
89         try {
90                 if (server.getStatus().equals(Server.Status.PENDING)) {
91                         waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, Server.Status.SUSPENDED, Server.Status.PAUSED);
92                 }
93         } catch (RequestFailedException e) {
94                 // evacuate is a special case. If the server is still in a Pending state, we want to continue with evacuate
95                 logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...");
96         }
97         
98         /*
99          * Set Time for Metrics Logger
100          */
101         long startTime = System.currentTimeMillis();
102         TimeZone tz = TimeZone.getTimeZone("UTC");
103         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
104         df.setTimeZone(tz);
105         String startTimeStr = df.format(new Date());
106         long endTime = System.currentTimeMillis();
107         long duration = endTime - startTime;
108         String endTimeStr = String.valueOf(endTime);
109         String durationStr = String.valueOf(duration);
110         String endTimeStrUTC = df.format(new Date());
111         MDC.put("EndTimestamp", endTimeStrUTC);
112         MDC.put("ElapsedTime", durationStr);
113         MDC.put("TargetEntity", "cdp");
114         MDC.put("TargetServiceName", "evacuate server");
115         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuteServer"); 
116         
117
118         try {
119             while (rc.attempt()) {
120                 try {
121                         logger.debug("Calling CDP moveServer - server id = " + server.getId());
122                     service.moveServer(server.getId(), target_host);
123                     // Wait for completion, expecting the server to go to a non pending state
124                     waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR, Server.Status.SUSPENDED, Server.Status.PAUSED);
125                     break;
126                 } catch (ContextConnectionException e) {
127                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
128                             ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
129                             Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
130                             Integer.toString(rc.getRetryLimit()));
131                     logger.error(msg, e);
132                     metricsLogger.error(msg,e);
133                     rc.delay();
134                 }
135             }
136
137         } catch (ZoneException e) {
138             msg =
139                     EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(), e.getMessage());
140             logger.error(msg);
141             metricsLogger.error(msg);
142             throw new RequestFailedException("Evacute Server", msg, HttpStatus.BAD_GATEWAY_502, server);
143         }
144
145         if (rc.isFailed()) {
146             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
147             logger.error(msg);
148             metricsLogger.error(msg);
149             throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_GATEWAY_502, server);
150         }
151         rc.reset();
152     }
153
154
155     /**
156      * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map, org.openecomp.sdnc.sli.SvcLogicContext)
157      */
158     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
159         Server server = null;
160         RequestContext rc = new RequestContext(ctx);
161         rc.isAlive();
162
163         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
164         String msg;
165
166         /*
167          * Set Time for Metrics Logger
168          */
169         long startTime = System.currentTimeMillis();
170         TimeZone tz = TimeZone.getTimeZone("UTC");
171         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
172         df.setTimeZone(tz);
173         String startTimeStr = df.format(new Date());
174         long endTime = System.currentTimeMillis();
175         long duration = endTime - startTime;
176         String endTimeStr = String.valueOf(endTime);
177         String durationStr = String.valueOf(duration);
178         String endTimeStrUTC = df.format(new Date());
179         MDC.put("EndTimestamp", endTimeStrUTC);
180         MDC.put("ElapsedTime", durationStr);
181         MDC.put("TargetEntity", "cdp");
182         MDC.put("TargetServiceName", "evacuate server");
183         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
184         
185         ctx.setAttribute("EVACUATE_STATUS", "ERROR");
186         try {
187             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
188                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
189             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
190
191             VMURL vm = VMURL.parseURL(vm_url);
192             if (validateVM(rc, appName, vm_url, vm)) return null;
193             
194             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
195             String identStr = (ident == null) ? null : ident.toString();
196             
197             // retrieve the optional parameters
198             String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
199             String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
200             
201             Context context = null;
202             try {
203                 context = getContext(rc, vm_url, identStr);
204                 if (context != null) {
205                         
206                     server = lookupServer(rc, context, vm.getServerId());
207                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
208                     
209                     // check target host status
210                         if (isComputeNodeDown(context, targethost_id)) {
211                                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
212                                                 "Target host " + targethost_id +" status is not UP/ENABLED");
213                         logger.error(msg);
214                         metricsLogger.error(msg);
215                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server);
216                         }
217                     
218                     // save hypervisor name before evacuate
219                     String hypervisor = server.getHypervisor().getHostName();
220
221                     evacuateServer(rc, server, targethost_id);
222                     
223                     server.refreshAll();
224                     String hypervisor_after_evacuate = server.getHypervisor().getHostName();
225                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisor_after_evacuate);
226                     
227                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate failed.
228                     if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) {
229                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
230                                         "Hypervisor host " + hypervisor + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
231                         logger.error(msg);
232                         metricsLogger.error(msg);
233                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
234   
235                     }
236                     
237                     // check VM status after evacuate
238                     if (server.getStatus() == Server.Status.ERROR) {
239                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
240                                         "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
241                         logger.error(msg);
242                         metricsLogger.error(msg);
243                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
244                     }
245                     
246                     context.close();
247                     doSuccess(rc);
248                     ctx.setAttribute("EVACUATE_STATUS", "SUCCESS");
249                     
250                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
251                     // This is the default behavior unless the optional parameter is set to FALSE.
252                     if ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) {
253                         List<Image> snapshots = server.getSnapshots();
254                         if (snapshots == null || snapshots.isEmpty()) {
255                                 logger.debug("No snapshots available - skipping rebuild after evacuate");
256                         } else if (paImpl != null) {
257                                 logger.debug("Executing a rebuild after evacuate");
258                                 paImpl.rebuildServer(params, ctx);
259                                 // Check error code for rebuild errors. Evacuate had set it to 200 after
260                                 // a successful evacuate. Rebuild updates the error code.
261                                 String rebuildErrorCode = ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_CODE);
262                             if (rebuildErrorCode != null) {
263                                 try {
264                                         int error_code = Integer.parseInt(rebuildErrorCode);
265                                         if (error_code != HttpStatus.OK_200.getStatusCode()) {
266                                                 logger.debug("Rebuild after evacuate failed - error code=" + error_code
267                                                                 + ", message=" + ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
268                                                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED, server.getName(), hypervisor,
269                                                         hypervisor_after_evacuate, ctx.getAttribute(org.openecomp.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
270                                         logger.error(msg);
271                                         metricsLogger.error(msg);
272                                                 ctx.setAttribute("EVACUATE_STATUS", "ERROR");
273                                                 // update error message while keeping the error code the same as before
274                                                 doFailure(rc, HttpStatus.getHttpStatus(error_code), msg);
275                                         }
276                                 } catch (NumberFormatException e) {
277                                         // ignore
278                                 }
279                                         }
280                         }
281                     }
282                     
283                 }
284             } catch (ResourceNotFoundException e) {
285                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
286                 logger.error(msg);
287                 metricsLogger.error(msg);
288                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
289             } catch (RequestFailedException e) {
290                 doFailure(rc, e.getStatus(), e.getMessage());
291             } catch (Throwable t) {
292                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, t, t.getClass().getSimpleName(),
293                         Operation.EVACUATE_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName());
294                 logger.error(msg, t);
295                 metricsLogger.error(msg, t);
296                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
297             }
298         } catch (RequestFailedException e) {
299                 msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
300             logger.error(msg);
301             metricsLogger.error(msg);
302             doFailure(rc, e.getStatus(), e.getMessage());
303         }
304
305         return server;
306     }
307
308     /*
309      * Check if a Compute node is down.
310      * 
311      * This method attempts to find a given host in the list of hypervisors for a given
312      * context. The only case where a node is considered down is if a matching hypervisor
313      * is found and it's state and status are not UP/ENABLED.
314      * 
315      * @param context
316      *                  The current context
317      * @param host
318      *                  The host name (short or fully qualified) of a compute node
319      * @return true if the node is determined as down, false for all other cases
320      */
321     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
322         ComputeService service = context.getComputeService();
323         boolean node_down = false;
324         
325         // Check host status. A node is considered down only if a matching target host is
326         //  found and it's state/status is not UP/ENABLED.
327         if ((host != null) && !(host.isEmpty())) {
328                 List<Hypervisor> hypervisors = service.getHypervisors();
329                 logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
330             for (Hypervisor h : hypervisors) {
331                 if (h.getHostName().startsWith(host)) {
332                         // host matches one of the hypervisors
333                     State hstate = h.getState();
334                     Status hstatus = h.getStatus();
335                     logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: "
336                                                 + hstate.toString() + "/" + hstatus.toString());
337                     if ((hstate != null) && (hstatus != null)) {
338                         if (!(hstate.equals(State.UP)) || !(hstatus.equals(Status.ENABLED))) {
339                                 node_down = true;
340                         }
341                     }
342                 }
343             }
344         }
345         return node_down;
346     }
347     
348     @Override
349     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context) throws APPCException {
350
351         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
352         logOperation(Msg.EVACUATING_SERVER, params, context);
353         
354         /*
355          * Set Time for Metrics Logger
356          */
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         String startTimeStr = df.format(new Date());
362         long endTime = System.currentTimeMillis();
363         long duration = endTime - startTime;
364         String endTimeStr = String.valueOf(endTime);
365         String durationStr = String.valueOf(duration);
366         String endTimeStrUTC = df.format(new Date());
367         MDC.put("EndTimestamp", endTimeStrUTC);
368         MDC.put("ElapsedTime", durationStr);
369         MDC.put("TargetEntity", "cdp");
370         MDC.put("TargetServiceName", "evacuate server");
371         MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.EvacuateServer"); 
372         
373         
374         metricsLogger.info("Executing Provider Operation: Evacuate");
375         return evacuateServer(params, context);
376     }
377     
378     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
379         paImpl = pai;
380     }
381 }