2 * ============LICENSE_START=======================================================
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
15 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.adapter.iaas.provider.operation.impl;
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;
63 import java.text.DateFormat;
64 import java.text.SimpleDateFormat;
65 import java.util.Date;
66 import java.util.List;
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;
72 public class RebuildServer extends ProviderServerOperation {
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;
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.
86 * The request context that manages the state and recovery of the
87 * request for the life of its processing.
89 * the server to be rebuilt
91 * The image to be used (or snapshot)
92 * @throws RequestFailedException
93 * if the server does not change state in the allotted time
95 @SuppressWarnings("nls")
96 private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
97 logger.debug(Msg.REBUILD_SERVER, server.getId());
99 Context context = server.getContext();
100 Provider provider = context.getProvider();
101 ComputeService service = context.getComputeService();
103 * Set Time for Metrics Logger
105 setTimeForMetricsLogger();
107 while (rc.attempt()) {
109 server.rebuild(image);
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);
122 * We need to provide some time for OpenStack to start processing the request.
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();
131 } catch (ZoneException e) {
132 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
135 metricsLogger.error(msg);
136 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
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
144 waitForStateChange(rc, server, Server.Status.READY);
146 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
148 metricsLogger.error(msg);
149 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
155 * This method is called to rebuild the provided server.
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.
163 * The request context that manages the state and recovery of the
164 * request for the life of its processing.
166 * The server to be rebuilt
167 * @throws ZoneException
169 * @throws RequestFailedException
170 * When server status is error
172 @SuppressWarnings("nls")
173 private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx)
174 throws ZoneException, RequestFailedException {
175 ServerBootSource builtFrom = server.getBootSource();
177 * Set Time for Metrics Logger
179 setTimeForMetricsLogger();
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());
186 generateEvent(rc, false, msg);
187 metricsLogger.error(msg);
188 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.INTERNAL_SERVER_ERROR_500, server);
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]",
196 generateEvent(rc, false, msg);
198 metricsLogger.error(msg);
199 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
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.
207 Context context = server.getContext();
208 Provider provider = context.getProvider();
209 ComputeService service = context.getComputeService();
210 if (server.getStatus().equals(Server.Status.PENDING)) {
212 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
213 Server.Status.SUSPENDED, Server.Status.PAUSED);
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);
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);
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.
231 String imageToUse = "";
233 ObjectMapper mapper = new ObjectMapper();
234 String payloadStr = configuration.getProperty(Property.PAYLOAD);
235 if (payloadStr == null || payloadStr.isEmpty()) {
236 payloadStr = ctx.getAttribute(ProviderAdapter.PAYLOAD);
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());
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);
252 logger.debug("Image Snapshot Not Found");
253 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
254 "Invalid Snapshot-Id");
256 metricsLogger.error(msg);
257 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
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();
263 imageToUse = server.getImage();
266 while (rc.attempt()) {
269 * We are just trying to make sure that the image exists. We arent interested in
270 * the details at this point.
272 imageService.getImage(imageToUse);
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);
284 } catch (ZoneException e) {
285 msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild");
286 generateEvent(rc, false, msg);
288 metricsLogger.error(msg);
289 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
293 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
295 metricsLogger.error(msg);
296 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
300 * We determine what to do based on the current state of the server
302 switch (server.getStatus()) {
304 // Nothing to do, the server is gone
305 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(), server.getTenantId(),
307 generateEvent(rc, false, msg);
309 metricsLogger.error(msg);
310 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
312 // Attempt to stop the server, then rebuild it
313 stopServer(rc, server);
315 rebuildServer(rc, server, imageToUse);
317 startServer(rc, server);
318 generateEvent(rc, true, Outcome.SUCCESS.toString());
319 metricsLogger.info("Server status: RUNNING");
322 msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
323 server.getTenantId(), "rebuild");
324 generateEvent(rc, false, msg);
326 metricsLogger.error(msg);
327 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
329 // Attempt to rebuild the server
330 rebuildServer(rc, server, imageToUse);
332 startServer(rc, server);
333 generateEvent(rc, true, Outcome.SUCCESS.toString());
334 metricsLogger.info("Server status: READY");
337 // if paused, un-pause it, stop it, and rebuild it
338 unpauseServer(rc, server);
340 stopServer(rc, server);
342 rebuildServer(rc, server, imageToUse);
344 startServer(rc, server);
345 generateEvent(rc, true, Outcome.SUCCESS.toString());
346 metricsLogger.info("Server status: PAUSED");
349 // Attempt to resume the suspended server, stop it, and rebuild it
350 resumeServer(rc, server);
352 stopServer(rc, server);
354 rebuildServer(rc, server, imageToUse);
356 startServer(rc, server);
357 generateEvent(rc, true, Outcome.SUCCESS.toString());
358 metricsLogger.info("Server status: SUSPENDED");
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);
366 metricsLogger.error(msg);
367 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
372 * @see org.onap.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map,
373 * org.onap.ccsdk.sli.core.sli.SvcLogicContext)
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);
380 setTimeForMetricsLogger();
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))
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
396 context = getContext(rc, vm_url, identStr);
397 if (context != null) {
398 tenantName = context.getTenantName();// this varaible also is used in case of exception
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);
406 ctx.setAttribute("REBUILD_STATUS", "SUCCESS");
408 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
409 "Accessing Image Service Failed");
411 metricsLogger.error(msg);
412 doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
416 ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND");
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");
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);
439 } catch (RequestFailedException e) {
440 ctx.setAttribute("REBUILD_STATUS", "ERROR");
441 doFailure(rc, e.getStatus(), e.getMessage());
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);
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");
470 * Sets the sleep time used by thread.sleep to give "some time for OpenStack to
471 * start processing the request".
474 * Time to sleep in milliseconds
476 public void setRebuildSleepTime(long millis) {
477 this.rebuildSleepTime = millis;
480 private boolean validateSnapshotId(String imageToUse, List<Image> snapshotList, List<Image> imageList) {
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()) {
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");
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);