Evaluate to variable value
[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             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                     if (isComputeNodeDown(context, targetHostId)) {
187                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
188                                 "Target host " + targetHostId + " status is not UP/ENABLED");
189                         logger.error(msg);
190                         metricsLogger.error(msg);
191                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.BAD_REQUEST_400, server);
192                     }
193
194                     // save hypervisor name before evacuate
195                     String hypervisor = server.getHypervisor().getHostName();
196
197                     evacuateServer(rc, server, targetHostId);
198
199                     server.refreshAll();
200                     String hypervisorAfterEvacuate = server.getHypervisor().getHostName();
201                     logger.debug("Hostname before evacuate: " + hypervisor + ", After evacuate: " + hypervisorAfterEvacuate);
202
203                     // check hypervisor host name after evacuate. If it is unchanged, the evacuate
204                     // failed.
205                     if (hypervisor != null && hypervisor.equals(hypervisorAfterEvacuate)) {
206                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
207                                 "Hypervisor host " + hypervisor
208                                         + " after evacuate is the same as before evacuate. Provider (ex. Openstack) recovery actions may be needed.");
209                         logger.error(msg);
210                         metricsLogger.error(msg);
211                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
212                     }
213
214                     // check VM status after evacuate
215                     if (server.getStatus() == Server.Status.ERROR) {
216                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_FAILED, server.getName(), server.getId(),
217                                 "VM is in ERROR state after evacuate. Provider (ex. Openstack) recovery actions may be needed.");
218                         logger.error(msg);
219                         metricsLogger.error(msg);
220                         throw new RequestFailedException(EVACUATE_SERVER, msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
221                     }
222
223                     context.close();
224                     doSuccess(rc);
225                     ctx.setAttribute(EVACUATE_STATUS, "SUCCESS");
226
227                     // If a snapshot exists, do a rebuild to apply the latest snapshot to the evacuated server.
228                     // This is the default behavior unless the optional parameter is set to FALSE.
229                     if (rebuildVm == null || !"false".equalsIgnoreCase(rebuildVm)) {
230                         List<Image> snapshots = server.getSnapshots();
231                         if (snapshots == null || snapshots.isEmpty()) {
232                             logger.debug("No snapshots available - skipping rebuild after evacuate");
233                         } else if (paImpl != null) {
234                             logger.debug("Executing a rebuild after evacuate");
235                             paImpl.rebuildServer(params, ctx);
236                             // Check error code for rebuild errors. Evacuate had set it to 200 after
237                             // a successful evacuate. Rebuild updates the error code.
238                             String rebuildErrorCode = ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_CODE);
239                             if (rebuildErrorCode != null) {
240                                 try {
241                                     int errorCode = Integer.parseInt(rebuildErrorCode);
242                                     if (errorCode != HttpStatus.OK_200.getStatusCode()) {
243                                         logger.debug("Rebuild after evacuate failed - error code=" + errorCode
244                                                 + ", message=" + ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
245                                         msg = EELFResourceManager.format(Msg.EVACUATE_SERVER_REBUILD_FAILED,
246                                                 server.getName(), hypervisor, hypervisorAfterEvacuate,
247                                                 ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_ERROR_MESSAGE));
248                                         logger.error(msg);
249                                         metricsLogger.error(msg);
250                                         ctx.setAttribute(EVACUATE_STATUS, "ERROR");
251                                         // update error message while keeping the error code the
252                                         // same as before
253                                         doFailure(rc, HttpStatus.getHttpStatus(errorCode), msg);
254                                     }
255                                 } catch (NumberFormatException e) {
256                                     // ignore
257                                 }
258                             }
259                         }
260                     }
261
262                 }
263             } catch (ResourceNotFoundException e) {
264                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vmUrl);
265                 logger.error(msg);
266                 metricsLogger.error(msg);
267                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
268             } catch (RequestFailedException e) {
269                 doFailure(rc, e.getStatus(), e.getMessage());
270             } catch (IOException | ZoneException e1) {
271                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
272                         Operation.EVACUATE_SERVICE.toString(), vmUrl, tenantName);
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 nodeDown = false;
302
303         if (host != null && ! host.isEmpty()) {
304             List<Hypervisor> hypervisors = service.getHypervisors();
305             logger.debug("List of Hypervisors retrieved: " + Arrays.toString(hypervisors.toArray()));
306             for (Hypervisor hv : hypervisors) {
307                 if (isHostMatchesHypervisor(host, hv)) {
308                     State hstate = hv.getState();
309                     Status hstatus = hv.getStatus();
310                     logger.debug("Host matching hypervisor: " + hv.getHostName() + ", State/Status: " + hstate.toString()
311                             + "/" + hstatus.toString());
312                     if (hstate != State.UP || hstatus != Status.ENABLED) {
313                         nodeDown = true;
314                     }
315                 }
316             }
317         }
318         return nodeDown;
319     }
320
321     private boolean isHostMatchesHypervisor(String host, Hypervisor hypervisor) {
322         return hypervisor.getHostName().startsWith(host);
323     }
324
325     @Override
326     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
327             throws APPCException {
328         setMDC(Operation.EVACUATE_SERVICE.toString(), "App-C IaaS Adapter:Evacuate", ADAPTER_NAME);
329         logOperation(Msg.EVACUATING_SERVER, params, context);
330
331         setTimeForMetricsLogger();
332
333         metricsLogger.info("Executing Provider Operation: Evacuate");
334         return evacuateServer(params, context);
335     }
336
337     private void setTimeForMetricsLogger() {
338         long startTime = System.currentTimeMillis();
339         TimeZone tz = TimeZone.getTimeZone("UTC");
340         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
341         df.setTimeZone(tz);
342         long endTime = System.currentTimeMillis();
343         long duration = endTime - startTime;
344         String durationStr = String.valueOf(duration);
345         String endTimeStrUTC = df.format(new Date());
346         MDC.put("EndTimestamp", endTimeStrUTC);
347         MDC.put("ElapsedTime", durationStr);
348         MDC.put("TargetEntity", "cdp");
349         MDC.put("TargetServiceName", "evacuate server");
350         MDC.put("ClassName", "org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer");
351     }
352
353     public void setProvideAdapterRef(ProviderAdapterImpl pai) {
354         paImpl = pai;
355     }
356 }