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