First part of onap rename
[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 import java.text.DateFormat;
59 import java.text.SimpleDateFormat;
60 import java.util.Arrays;
61 import java.util.Date;
62 import java.util.List;
63 import java.util.Map;
64 import java.util.TimeZone;
65 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
66
67 public class EvacuateServer extends ProviderServerOperation {
68
69     private static final EELFLogger logger = EELFManager.getInstance().getLogger(EvacuateServer.class);
70     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
71     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
72     private ProviderAdapterImpl paImpl = null;
73
74
75     private void evacuateServer(RequestContext rc, @SuppressWarnings("unused") Server server, String target_host)
76             throws ZoneException, RequestFailedException {
77
78         Context ctx = server.getContext();
79         Provider provider = ctx.getProvider();
80         ComputeService service = ctx.getComputeService();
81
82         /*
83          * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
84          * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
85          * to one we can deal with. If not, then we have to fail the request.
86          */
87         try {
88             if (server.getStatus().equals(Server.Status.PENDING)) {
89                 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
90                         Server.Status.SUSPENDED, Server.Status.PAUSED);
91             }
92         } catch (RequestFailedException e) {
93             // evacuate is a special case. If the server is still in a Pending state, we want to
94             // continue with evacuate
95             logger.info("Evacuate server - ignore RequestFailedException from waitForStateChange() ...");
96         }
97
98         SetTimeForMetricsLogger();
99
100         String msg;
101         try {
102             while (rc.attempt()) {
103                 try {
104                     logger.debug("Calling CDP moveServer - server id = " + server.getId());
105                     service.moveServer(server.getId(), target_host);
106                     // Wait for completion, expecting the server to go to a non pending state
107                     waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
108                             Server.Status.SUSPENDED, Server.Status.PAUSED);
109                     break;
110                 } catch (ContextConnectionException e) {
111                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
112                             ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
113                             Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
114                             Integer.toString(rc.getRetryLimit()));
115                     logger.error(msg, e);
116                     metricsLogger.error(msg, e);
117                     rc.delay();
118                 }
119             }
120
121         } catch (ZoneException e) {
122             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
123                     e.getMessage());
124             logger.error(msg);
125             metricsLogger.error(msg);
126             throw new RequestFailedException("Evacute Server", msg, HttpStatus.BAD_GATEWAY_502, server);
127         }
128
129         if (rc.isFailed()) {
130             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
131             logger.error(msg);
132             metricsLogger.error(msg);
133             throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_GATEWAY_502, server);
134         }
135         rc.reset();
136     }
137
138
139     /**
140      * @see org.onap.appc.adapter.iaas.ProviderAdapter#evacuateServer(java.util.Map,
141      *      org.openecomp.sdnc.sli.SvcLogicContext)
142      */
143     private Server evacuateServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
144         Server server = null;
145         RequestContext rc = new RequestContext(ctx);
146         rc.isAlive();
147
148         SetTimeForMetricsLogger();
149
150         String msg;
151         ctx.setAttribute("EVACUATE_STATUS", "ERROR");
152         try {
153             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
154                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
155
156             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
157             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
158             VMURL vm = VMURL.parseURL(vm_url);
159             if (validateVM(rc, appName, vm_url, vm))
160                 return null;
161
162             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
163             String identStr = (ident == null) ? null : ident.toString();
164
165             // retrieve the optional parameters
166             String rebuild_vm = params.get(ProviderAdapter.PROPERTY_REBUILD_VM);
167             String targethost_id = params.get(ProviderAdapter.PROPERTY_TARGETHOST_ID);
168
169             Context context = null;
170             try {
171                 context = getContext(rc, vm_url, identStr);
172                 if (context != null) {
173
174                     server = lookupServer(rc, context, vm.getServerId());
175                     logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
176
177                     // check target host status
178                     if (isComputeNodeDown(context, targethost_id)) {
179                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
180                                 "Target host " + targethost_id + " status is not UP/ENABLED");
181                         logger.error(msg);
182                         metricsLogger.error(msg);
183                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.BAD_REQUEST_400, server);
184                     }
185
186                     // save hypervisor name before evacuate
187                     String hypervisor = server.getHypervisor().getHostName();
188
189                     evacuateServer(rc, server, targethost_id);
190
191                     server.refreshAll();
192                     String hypervisor_after_evacuate = server.getHypervisor().getHostName();
193                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: "
194                             + hypervisor_after_evacuate);
195
196                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate
197                     // failed.
198                     if ((hypervisor != null) && (hypervisor.equals(hypervisor_after_evacuate))) {
199                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
200                                 "Hypervisor host " + hypervisor
201                                         + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
202                         logger.error(msg);
203                         metricsLogger.error(msg);
204                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500,
205                                 server);
206
207                     }
208
209                     // check VM status after evacuate
210                     if (server.getStatus() == Server.Status.ERROR) {
211                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
212                                 "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
213                         logger.error(msg);
214                         metricsLogger.error(msg);
215                         throw new RequestFailedException("Evacuate Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500,
216                                 server);
217                     }
218
219                     context.close();
220                     doSuccess(rc);
221                     ctx.setAttribute("EVACUATE_STATUS", "SUCCESS");
222
223                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the
224                     // evacuated server.
225                     // This is the default behavior unless the optional parameter is set to FALSE.
226                     if ((rebuild_vm == null) || !(rebuild_vm.equalsIgnoreCase("false"))) {
227                         List<Image> snapshots = server.getSnapshots();
228                         if (snapshots == null || snapshots.isEmpty()) {
229                             logger.debug("No snapshots available - skipping rebuild after evacuate");
230                         } else if (paImpl != null) {
231                             logger.debug("Executing a rebuild after evacuate");
232                             paImpl.rebuildServer(params, ctx);
233                             // Check error code for rebuild errors. Evacuate had set it to 200 after
234                             // a successful evacuate. Rebuild updates the error code.
235                             String rebuildErrorCode =
236                                     ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
237                             if (rebuildErrorCode != null) {
238                                 try {
239                                     int error_code = Integer.parseInt(rebuildErrorCode);
240                                     if (error_code != HttpStatus.OK_200.getStatusCode()) {
241                                         logger.debug("Rebuild after evacuate failed - error code=" + error_code
242                                                 + ", message=" + ctx.getAttribute(
243                                                         org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
244                                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
245                                                 server.getName(), hypervisor, hypervisor_after_evacuate,
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(error_code), 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, vm_url);
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 (Exception e1) {
270                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
271                         Operation.EVACUATE_SERVICE.toString(), vm_url,
272                         context == null ? "Unknown" : context.getTenantName());
273                 logger.error(msg, e1);
274                 metricsLogger.error(msg, e1);
275                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
276             }
277         } catch (RequestFailedException e) {
278             msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, "n/a", "n/a", e.getMessage());
279             logger.error(msg);
280             metricsLogger.error(msg);
281             doFailure(rc, e.getStatus(), e.getMessage());
282         }
283
284         return server;
285     }
286
287     /*
288      * Check if a Compute node is down.
289      * 
290      * This method attempts to find a given host in the list of hypervisors for a given context. The only case where a
291      * node is considered down is if a matching hypervisor is found and it's state and status are not UP/ENABLED.
292      * 
293      * @param context The current context
294      * 
295      * @param host The host name (short or fully qualified) of a compute node
296      * 
297      * @return true if the node is determined as down, false for all other cases
298      */
299     private boolean isComputeNodeDown(Context context, String host) throws ZoneException {
300         ComputeService service = context.getComputeService();
301         boolean node_down = false;
302
303         // Check host status. A node is considered down only if a matching target host is
304         // found and it's state/status is not UP/ENABLED.
305         if ((host != null) && !(host.isEmpty())) {
306             List<Hypervisor> hypervisors = service.getHypervisors();
307             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
308             for (Hypervisor h : hypervisors) {
309                 if (h.getHostName().startsWith(host)) {
310                     // host matches one of the hypervisors
311                     State hstate = h.getState();
312                     Status hstatus = h.getStatus();
313                     logger.debug("Host matching hypervisor: " + h.getHostName() + ", State/Status: " + hstate.toString()
314                             + "/" + hstatus.toString());
315                     if (hstate != State.UP || hstatus != Status.ENABLED) {
316                         node_down = true;
317                     }
318                 }
319             }
320         }
321         return node_down;
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 }