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