AAPC-1658 removing unused import
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / RebuildServer.java
1 /*
2 * ============LICENSE_START=======================================================
3 * ONAP : APPC
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Modifications Copyright (C) 2019 IBM
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
14
15 *      http://www.apache.org/licenses/LICENSE-2.0
16
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
22
23 * ============LICENSE_END=========================================================
24 */
25
26 package org.onap.appc.adapter.iaas.provider.operation.impl;
27
28 import com.att.cdp.exceptions.ContextConnectionException;
29 import com.att.cdp.exceptions.ResourceNotFoundException;
30 import com.att.cdp.exceptions.ZoneException;
31 import com.att.cdp.zones.ComputeService;
32 import com.att.cdp.zones.Context;
33 import com.att.cdp.zones.ImageService;
34 import com.att.cdp.zones.Provider;
35 import com.att.cdp.zones.model.Image;
36 import com.att.cdp.zones.model.ModelObject;
37 import com.att.cdp.zones.model.Server;
38 import com.att.cdp.zones.model.ServerBootSource;
39 import com.att.eelf.configuration.EELFLogger;
40 import com.att.eelf.configuration.EELFManager;
41 import com.att.eelf.i18n.EELFResourceManager;
42 import org.glassfish.grizzly.http.util.HttpStatus;
43 import org.onap.appc.Constants;
44 import com.fasterxml.jackson.databind.JsonNode;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import org.onap.appc.adapter.iaas.ProviderAdapter;
47 import org.onap.appc.adapter.iaas.impl.IdentityURL;
48 import org.onap.appc.adapter.iaas.impl.RequestContext;
49 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
50 import org.onap.appc.adapter.iaas.impl.VMURL;
51 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
52 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
53 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Outcome;
54 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
55 import org.onap.appc.configuration.Configuration;
56 import org.onap.appc.configuration.ConfigurationFactory;
57 import org.onap.appc.exceptions.APPCException;
58 import org.onap.appc.i18n.Msg;
59 import org.onap.appc.logging.LoggingConstants;
60 import org.onap.appc.logging.LoggingUtils;
61 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
62 import org.slf4j.MDC;
63 import java.text.SimpleDateFormat;
64 import java.util.Date;
65 import java.util.List;
66 import java.util.Map;
67 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
68 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
69 import com.att.cdp.exceptions.StateException;
70
71 public class RebuildServer extends ProviderServerOperation {
72
73     private static final EELFLogger logger = EELFManager.getInstance().getLogger(RebuildServer.class);
74     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
75     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
76     // the sleep time used by thread.sleep to give "some time for OpenStack to start
77     // processing the request"
78     private long rebuildSleepTime = 10L * 1000L;
79
80     /**
81      * Rebuild the indicated server with the indicated image. This method assumes
82      * the server has been determined to be in the correct state to do the rebuild.
83      *
84      * @param rc
85      *            The request context that manages the state and recovery of the
86      *            request for the life of its processing.
87      * @param server
88      *            the server to be rebuilt
89      * @param image
90      *            The image to be used (or snapshot)
91      * @throws RequestFailedException
92      *             if the server does not change state in the allotted time
93      */
94     @SuppressWarnings("nls")
95     private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
96         logger.debug(Msg.REBUILD_SERVER, server.getId());
97         String msg;
98         Context context = server.getContext();
99         Provider provider = context.getProvider();
100         ComputeService service = context.getComputeService();
101         /*
102          * Set Time for Metrics Logger
103          */
104         setTimeForMetricsLogger();
105         try {
106             while (rc.attempt()) {
107                 try {
108                     server.rebuild(image);
109                     break;
110                 } catch (ContextConnectionException e) {
111                     msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
112                             context.getTenant().getName(), context.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              * We need to provide some time for OpenStack to start processing the request.
122              */
123             try {
124                 Thread.sleep(rebuildSleepTime);
125             } catch (InterruptedException e) {
126                 logger.trace("Sleep threw interrupted exception, should never occur");
127                 metricsLogger.trace("Sleep threw interrupted exception, should never occur");
128                 Thread.currentThread().interrupt();
129             }
130         } catch (ZoneException e) {
131             msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
132                     e.getMessage());
133             logger.error(msg);
134             metricsLogger.error(msg);
135             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
136         }
137         rc.reset();
138         /*
139          * Once we have started the process, now we wait for the final state of stopped.
140          * This should be the final state (since we started the rebuild with the server
141          * stopped).
142          */
143         waitForStateChange(rc, server, Server.Status.READY);
144         if (rc.isFailed()) {
145             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
146             logger.error(msg);
147             metricsLogger.error(msg);
148             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
149         }
150         rc.reset();
151     }
152
153     /**
154      * This method is called to rebuild the provided server.
155      * <p>
156      * If the server was booted from a volume, then the request is failed
157      * immediately and no action is taken. Rebuilding a VM from a bootable volume,
158      * where the bootable volume itself is not rebuilt, serves no purpose.
159      * </p>
160      *
161      * @param rc
162      *            The request context that manages the state and recovery of the
163      *            request for the life of its processing.
164      * @param server
165      *            The server to be rebuilt
166      * @throws ZoneException
167      *             When error occurs
168      * @throws RequestFailedException
169      *             When server status is error
170      */
171     @SuppressWarnings("nls")
172     private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx)
173             throws ZoneException, RequestFailedException {
174         ServerBootSource builtFrom = server.getBootSource();
175         /*
176          * Set Time for Metrics Logger
177          */
178         setTimeForMetricsLogger();
179         String msg;
180         // Throw error if boot source is unknown
181         if (ServerBootSource.UNKNOWN.equals(builtFrom)) {
182             logger.debug("Boot Source Unknown");
183             msg = String.format("Error occured when retrieving server boot source [%s]!!!", server.getId());
184             logger.error(msg);
185             generateEvent(rc, false, msg);
186             metricsLogger.error(msg);
187             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
188         }
189
190         // Throw exception for non image/snap boot source
191         if (ServerBootSource.VOLUME.equals(builtFrom)) {
192             logger.debug("Boot Source Not Supported built from bootable volume");
193             msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]",
194                     server.getId());
195             generateEvent(rc, false, msg);
196             logger.error(msg);
197             metricsLogger.error(msg);
198             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
199         }
200         /*
201          * Pending is a bit of a special case. If we find the server is in a pending
202          * state, then the provider is in the process of changing state of the server.
203          * So, lets try to wait a little bit and see if the state settles down to one we
204          * can deal with. If not, then we have to fail the request.
205          */
206         Context context = server.getContext();
207         Provider provider = context.getProvider();
208         ComputeService service = context.getComputeService();
209         if (server.getStatus().equals(Server.Status.PENDING)) {
210             rc.reset();
211             waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
212                     Server.Status.SUSPENDED, Server.Status.PAUSED);
213         }
214         // Is the skip Hypervisor check attribute populated?
215         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
216         if (skipHypervisorCheck == null && ctx != null) {
217             skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
218         }
219         // Always perform Hypervisor Status checks
220         // unless the skip is set to true
221         if (skipHypervisorCheck == null || (!"true".equalsIgnoreCase(skipHypervisorCheck))) {
222             // Check of the Hypervisor for the VM Server is UP and reachable
223             checkHypervisor(server);
224         }
225         /*
226          * Get the image to use in this priority order: (1) If snapshot-id provided in
227          * the request, use this (2) If any snapshots exist, then the latest snapshot is
228          * used (3) Otherwise the image used to construct the VM is used.
229          */
230         String imageToUse = "";
231         try {
232             ObjectMapper mapper = new ObjectMapper();
233             String payloadStr = configuration.getProperty(Property.PAYLOAD);
234             if (payloadStr == null || payloadStr.isEmpty()) {
235                 payloadStr = ctx.getAttribute(ProviderAdapter.PAYLOAD);
236             }
237             JsonNode payloadNode = mapper.readTree(payloadStr);
238             imageToUse = payloadNode.get(ProviderAdapter.PROPERTY_REQUEST_SNAPSHOT_ID).textValue();
239             logger.debug("Pulled snapshot-id " + imageToUse + " from the payload");
240         } catch (Exception e) {
241             logger.debug("Exception attempting to pull snapshot-id from the payload: " + e.toString());
242         }
243         List<Image> snapshots = server.getSnapshots();
244         ImageService imageService = server.getContext().getImageService();
245         List<Image> imageList = imageService.listImages();
246         if (!imageToUse.isEmpty()) {
247             logger.debug("Using snapshot-id " + imageToUse + " for the rebuild request");
248             boolean imgFound = validateSnapshotId(imageToUse, snapshots, imageList);
249
250             if (!imgFound) {
251                 logger.debug("Image Snapshot Not Found");
252                 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
253                         "Invalid Snapshot-Id");
254                 logger.error(msg);
255                 metricsLogger.error(msg);
256                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
257             }
258         } else if (snapshots != null && !snapshots.isEmpty()) {
259             logger.debug("Using snapshot-id when image is Empty" + imageToUse + " for the rebuild request");
260             imageToUse = snapshots.get(0).getId();
261         } else {
262             imageToUse = server.getImage();
263             rc.reset();
264             try {
265                 while (rc.attempt()) {
266                     try {
267                         /*
268                          * We are just trying to make sure that the image exists. We arent interested in
269                          * the details at this point.
270                          */
271                         imageService.getImage(imageToUse);
272                         break;
273                     } catch (ContextConnectionException e) {
274                         msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(),
275                                 imageService.getURL(), context.getTenant().getName(), context.getTenant().getId(),
276                                 e.getMessage(), Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
277                                 Integer.toString(rc.getRetryLimit()));
278                         logger.error(msg, e);
279                         metricsLogger.error(msg);
280                         rc.delay();
281                     }
282                 }
283             } catch (ZoneException e) {
284                 msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild");
285                 generateEvent(rc, false, msg);
286                 logger.error(msg);
287                 metricsLogger.error(msg);
288                 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
289             }
290         }
291         if (rc.isFailed()) {
292             msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
293             logger.error(msg);
294             metricsLogger.error(msg);
295             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
296         }
297         rc.reset();
298         /*
299          * We determine what to do based on the current state of the server
300          */
301         switch (server.getStatus()) {
302         case DELETED:
303             // Nothing to do, the server is gone
304             msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(),
305                     "rebuilt");
306             generateEvent(rc, false, msg);
307             logger.error(msg);
308             metricsLogger.error(msg);
309             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
310         case RUNNING:
311             // Attempt to stop the server, then rebuild it
312             stopServer(rc, server);
313             rc.reset();
314             rebuildServer(rc, server, imageToUse);
315             rc.reset();
316             startServer(rc, server);
317             generateEvent(rc, true, Outcome.SUCCESS.toString());
318             metricsLogger.info("Server status: RUNNING");
319             break;
320         case ERROR:
321             msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
322                     server.getTenantId(), "rebuild");
323             generateEvent(rc, false, msg);
324             logger.error(msg);
325             metricsLogger.error(msg);
326             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
327         case READY:
328             // Attempt to rebuild the server
329             rebuildServer(rc, server, imageToUse);
330             rc.reset();
331             startServer(rc, server);
332             generateEvent(rc, true, Outcome.SUCCESS.toString());
333             metricsLogger.info("Server status: READY");
334             break;
335         case PAUSED:
336             // if paused, un-pause it, stop it, and rebuild it
337             unpauseServer(rc, server);
338             rc.reset();
339             stopServer(rc, server);
340             rc.reset();
341             rebuildServer(rc, server, imageToUse);
342             rc.reset();
343             startServer(rc, server);
344             generateEvent(rc, true, Outcome.SUCCESS.toString());
345             metricsLogger.info("Server status: PAUSED");
346             break;
347         case SUSPENDED:
348             // Attempt to resume the suspended server, stop it, and rebuild it
349             resumeServer(rc, server);
350             rc.reset();
351             stopServer(rc, server);
352             rc.reset();
353             rebuildServer(rc, server, imageToUse);
354             rc.reset();
355             startServer(rc, server);
356             generateEvent(rc, true, Outcome.SUCCESS.toString());
357             metricsLogger.info("Server status: SUSPENDED");
358             break;
359         default:
360             // Hmmm, unknown status, should never occur
361             msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
362                     server.getTenantId(), server.getStatus().name());
363             generateEvent(rc, false, msg);
364             logger.error(msg);
365             metricsLogger.error(msg);
366             throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
367         }
368     }
369
370     /**
371      * @see org.onap.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map,
372      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
373      */
374     @SuppressWarnings("nls")
375     public Server rebuildServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
376         Server server = null;
377         RequestContext rc = new RequestContext(ctx);
378         rc.isAlive();
379         setTimeForMetricsLogger();
380         String msg;
381         try {
382             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
383                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
384             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
385             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
386             VMURL vm = VMURL.parseURL(vm_url);
387             if (validateVM(rc, appName, vm_url, vm))
388                 return null;
389             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
390             String identStr = (ident == null) ? null : ident.toString();
391             ctx.setAttribute("REBUILD_STATUS", "ERROR");
392             Context context = null;
393             String tenantName = "Unknown";// to be used also in case of exception
394             try {
395                 context = getContext(rc, vm_url, identStr);
396                 if (context != null) {
397                     tenantName = context.getTenantName();// this varaible also is used in case of exception
398                     rc.reset();
399                     server = lookupServer(rc, context, vm.getServerId());
400                     logger.debug(Msg.SERVER_FOUND, vm_url, tenantName, server.getStatus().toString());
401                     // Manually checking image service until new PAL release
402                     if (hasImageAccess(rc, context)) {
403                         rebuildServer(rc, server, ctx);
404                         doSuccess(rc);
405                         ctx.setAttribute("REBUILD_STATUS", "SUCCESS");
406                     } else {
407                         msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
408                                 "Accessing Image Service Failed");
409                         logger.error(msg);
410                         metricsLogger.error(msg);
411                         doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
412                     }
413                     context.close();
414                 } else {
415                     ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND");
416                 }
417             } catch (StateException ex) {
418                 logger.error(ex.getMessage());
419                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
420                 doFailure(rc, HttpStatus.CONFLICT_409, ex.getMessage());
421             } catch (RequestFailedException e) {
422                 doFailure(rc, e.getStatus(), e.getMessage());
423                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
424             } catch (ResourceNotFoundException e) {
425                 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
426                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
427                 logger.error(msg);
428                 metricsLogger.error(msg);
429                 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
430             } catch (Exception e1) {
431                 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
432                         STOP_SERVICE.toString(), vm_url, tenantName);
433                 ctx.setAttribute("REBUILD_STATUS", "ERROR");
434                 logger.error(msg, e1);
435                 metricsLogger.error(msg);
436                 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
437             }
438         } catch (RequestFailedException e) {
439             ctx.setAttribute("REBUILD_STATUS", "ERROR");
440             doFailure(rc, e.getStatus(), e.getMessage());
441         }
442         return server;
443     }
444
445     @Override
446     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
447             throws APPCException {
448         setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME);
449         logOperation(Msg.REBUILDING_SERVER, params, context);
450         setTimeForMetricsLogger();
451         metricsLogger.info("Executing Provider Operation: Rebuild");
452         return rebuildServer(params, context);
453     }
454
455     private void setTimeForMetricsLogger() {
456         String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
457         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
458         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
459         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
460         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
461         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
462         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "rebuild server");
463         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
464                 "org.onap.appc.adapter.iaas.provider.operation.impl.RebuildServer");
465
466     }
467
468     /**
469      * Sets the sleep time used by thread.sleep to give "some time for OpenStack to
470      * start processing the request".
471      *
472      * @param millis
473      *            Time to sleep in milliseconds
474      */
475     public void setRebuildSleepTime(long millis) {
476         this.rebuildSleepTime = millis;
477     }
478
479     private boolean validateSnapshotId(String imageToUse, List<Image> snapshotList, List<Image> imageList) {
480
481         logger.debug("Validating snapshot-id " + imageToUse + " for the rebuild request from payload");
482         boolean imageFound = false;
483         // If image is empty , the validation si not required . Hence return false.
484         // Ideally function should not be called with empty image Id
485         if (imageToUse.isEmpty()) {
486             return imageFound;
487         } else {
488             // The supplied snapshot id can be a snapshot id or an image Id. Check both
489             // available for the vnf.
490             // Check against snapshot id list and image list
491             return findImageExists(snapshotList, imageToUse, "snapshotidList")
492                     || findImageExists(imageList, imageToUse, "imageidList");
493         }
494     }
495
496     boolean findImageExists(List<Image> list, String imageToUse, String source) {
497         boolean imageExists = false;
498         logger.debug("Available Image-ids from :" + source + "Start\n");
499         for (Image img : list) {
500             String imgId = img.getId();
501             logger.debug("Image Id - " + imgId + "\n");
502             if (imgId.equals(imageToUse)) {
503                 logger.debug("Image found in available " + source);
504                 imageExists = true;
505                 break;
506             }
507         }
508         return imageExists;
509
510     }
511 }