2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.openecomp.appc.adapter.iaas.provider.operation.impl;
27 import com.att.cdp.exceptions.ContextConnectionException;
28 import com.att.cdp.exceptions.ResourceNotFoundException;
29 import com.att.cdp.exceptions.ZoneException;
30 import com.att.cdp.zones.ComputeService;
31 import com.att.cdp.zones.Context;
32 import com.att.cdp.zones.ImageService;
33 import com.att.cdp.zones.Provider;
34 import com.att.cdp.zones.model.Image;
35 import com.att.cdp.zones.model.ModelObject;
36 import com.att.cdp.zones.model.Server;
37 import com.att.cdp.zones.model.ServerBootSource;
38 import com.att.eelf.configuration.EELFLogger;
39 import com.att.eelf.configuration.EELFManager;
40 import com.att.eelf.i18n.EELFResourceManager;
41 import org.glassfish.grizzly.http.util.HttpStatus;
42 import org.openecomp.appc.Constants;
43 import org.openecomp.appc.adapter.iaas.ProviderAdapter;
44 import org.openecomp.appc.adapter.iaas.impl.IdentityURL;
45 import org.openecomp.appc.adapter.iaas.impl.RequestContext;
46 import org.openecomp.appc.adapter.iaas.impl.RequestFailedException;
47 import org.openecomp.appc.adapter.iaas.impl.VMURL;
48 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation;
49 import org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Outcome;
50 import org.openecomp.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
51 import org.openecomp.appc.configuration.Configuration;
52 import org.openecomp.appc.configuration.ConfigurationFactory;
53 import org.openecomp.appc.exceptions.APPCException;
54 import org.openecomp.appc.i18n.Msg;
55 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
57 import java.text.DateFormat;
58 import java.text.SimpleDateFormat;
59 import java.util.Date;
60 import java.util.List;
62 import java.util.TimeZone;
63 import static org.openecomp.appc.adapter.iaas.provider.operation.common.enums.Operation.STOP_SERVICE;
64 import static org.openecomp.appc.adapter.utils.Constants.ADAPTER_NAME;
66 public class RebuildServer extends ProviderServerOperation {
68 private static final EELFLogger logger = EELFManager.getInstance().getLogger(RebuildServer.class);
69 private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
70 private static final Configuration configuration = ConfigurationFactory.getConfiguration();
73 * Rebuild the indicated server with the indicated image. This method assumes the server has been determined to be
74 * in the correct state to do the rebuild.
76 * @param rc The request context that manages the state and recovery of the request for the life of its processing.
77 * @param server the server to be rebuilt
78 * @param image The image to be used (or snapshot)
79 * @throws RequestFailedException if the server does not change state in the allotted time
81 @SuppressWarnings("nls")
82 private void rebuildServer(RequestContext rc, Server server, String image) throws RequestFailedException {
83 logger.debug(Msg.REBUILD_SERVER, server.getId());
86 Context context = server.getContext();
87 Provider provider = context.getProvider();
88 ComputeService service = context.getComputeService();
91 * Set Time for Metrics Logger
93 setTimeForMetricsLogger();
96 while (rc.attempt()) {
98 server.rebuild(image);
100 } catch (ContextConnectionException e) {
101 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(), service.getURL(),
102 context.getTenant().getName(), context.getTenant().getId(), e.getMessage(),
103 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
104 Integer.toString(rc.getRetryLimit()));
105 logger.error(msg, e);
106 metricsLogger.error(msg, e);
112 * We need to provide some time for OpenStack to start processing the request.
115 Thread.sleep(10L * 1000L);
116 } catch (InterruptedException e) {
117 logger.trace("Sleep threw interrupted exception, should never occur");
118 metricsLogger.trace("Sleep threw interrupted exception, should never occur");
120 } catch (ZoneException e) {
121 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
124 metricsLogger.error(msg);
125 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
130 * Once we have started the process, now we wait for the final state of stopped. This should be the final state
131 * (since we started the rebuild with the server stopped).
133 waitForStateChange(rc, server, Server.Status.READY);
136 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
138 metricsLogger.error(msg);
139 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
145 * This method is called to rebuild the provided server.
147 * If the server was booted from a volume, then the request is failed immediately and no action is taken. Rebuilding
148 * a VM from a bootable volume, where the bootable volume itself is not rebuilt, serves no purpose.
151 * @param rc The request context that manages the state and recovery of the request for the life of its processing.
152 * @param server The server to be rebuilt
153 * @throws ZoneException When error occurs
154 * @throws RequestFailedException When server status is error
156 @SuppressWarnings("nls")
157 private void rebuildServer(RequestContext rc, Server server, SvcLogicContext ctx)
158 throws ZoneException, RequestFailedException {
159 ServerBootSource builtFrom = server.getBootSource();
162 * Set Time for Metrics Logger
164 setTimeForMetricsLogger();
167 // Throw exception for non image/snap boot source
168 if (ServerBootSource.VOLUME.equals(builtFrom)) {
169 msg = String.format("Rebuilding is currently not supported for servers built from bootable volumes [%s]",
171 generateEvent(rc, false, msg);
173 metricsLogger.error(msg);
174 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.FORBIDDEN_403, server);
178 * Pending is a bit of a special case. If we find the server is in a pending state, then the provider is in the
179 * process of changing state of the server. So, lets try to wait a little bit and see if the state settles down
180 * to one we can deal with. If not, then we have to fail the request.
182 Context context = server.getContext();
183 Provider provider = context.getProvider();
184 ComputeService service = context.getComputeService();
185 if (server.getStatus().equals(Server.Status.PENDING)) {
187 waitForStateChange(rc, server, Server.Status.READY, Server.Status.RUNNING, Server.Status.ERROR,
188 Server.Status.SUSPENDED, Server.Status.PAUSED);
191 // Is the skip Hypervisor check attribute populated?
192 String skipHypervisorCheck = configuration.getProperty("org.openecomp.appc.iaas.skiphypervisorchek");
193 if (skipHypervisorCheck == null && ctx != null) {
194 skipHypervisorCheck = ctx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
197 // Always perform Hypervisor Status checks
198 // unless the skip is set to true
199 if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
200 // Check of the Hypervisor for the VM Server is UP and reachable
201 checkHypervisor(server);
205 * Get the image to use. This is determined by the presence or absence of snapshot images. If any snapshots
206 * exist, then the latest snapshot is used, otherwise the image used to construct the VM is used.
208 List<Image> snapshots = server.getSnapshots();
210 if (snapshots != null && !snapshots.isEmpty()) {
211 imageToUse = snapshots.get(0).getId();
213 imageToUse = server.getImage();
214 ImageService imageService = server.getContext().getImageService();
217 while (rc.attempt()) {
220 * We are just trying to make sure that the image exists. We arent interested in the details at
223 imageService.getImage(imageToUse);
225 } catch (ContextConnectionException e) {
226 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, provider.getName(),
227 imageService.getURL(), context.getTenant().getName(), context.getTenant().getId(),
228 e.getMessage(), Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
229 Integer.toString(rc.getRetryLimit()));
230 logger.error(msg, e);
231 metricsLogger.error(msg);
235 } catch (ZoneException e) {
236 msg = EELFResourceManager.format(Msg.IMAGE_NOT_FOUND, imageToUse, "rebuild");
237 generateEvent(rc, false, msg);
239 metricsLogger.error(msg);
240 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
244 msg = EELFResourceManager.format(Msg.CONNECTION_FAILED, provider.getName(), service.getURL());
246 metricsLogger.error(msg);
247 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.BAD_GATEWAY_502, server);
252 * We determine what to do based on the current state of the server
254 switch (server.getStatus()) {
256 // Nothing to do, the server is gone
257 msg = EELFResourceManager.format(Msg.SERVER_DELETED, server.getName(), server.getId(),
258 server.getTenantId(), "rebuilt");
259 generateEvent(rc, false, msg);
261 metricsLogger.error(msg);
262 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
265 // Attempt to stop the server, then rebuild it
266 stopServer(rc, server);
268 rebuildServer(rc, server, imageToUse);
270 startServer(rc, server);
271 generateEvent(rc, true, Outcome.SUCCESS.toString());
272 metricsLogger.info("Server status: RUNNING");
276 msg = EELFResourceManager.format(Msg.SERVER_ERROR_STATE, server.getName(), server.getId(),
277 server.getTenantId(), "rebuild");
278 generateEvent(rc, false, msg);
280 metricsLogger.error(msg);
281 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
284 // Attempt to rebuild the server
285 rebuildServer(rc, server, imageToUse);
287 startServer(rc, server);
288 generateEvent(rc, true, Outcome.SUCCESS.toString());
289 metricsLogger.info("Server status: READY");
293 // if paused, un-pause it, stop it, and rebuild it
294 unpauseServer(rc, server);
296 stopServer(rc, server);
298 rebuildServer(rc, server, imageToUse);
300 startServer(rc, server);
301 generateEvent(rc, true, Outcome.SUCCESS.toString());
302 metricsLogger.info("Server status: PAUSED");
306 // Attempt to resume the suspended server, stop it, and rebuild it
307 resumeServer(rc, server);
309 stopServer(rc, server);
311 rebuildServer(rc, server, imageToUse);
313 startServer(rc, server);
314 generateEvent(rc, true, Outcome.SUCCESS.toString());
315 metricsLogger.info("Server status: SUSPENDED");
319 // Hmmm, unknown status, should never occur
320 msg = EELFResourceManager.format(Msg.UNKNOWN_SERVER_STATE, server.getName(), server.getId(),
321 server.getTenantId(), server.getStatus().name());
322 generateEvent(rc, false, msg);
324 metricsLogger.error(msg);
325 throw new RequestFailedException("Rebuild Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
330 * @see org.openecomp.appc.adapter.iaas.ProviderAdapter#rebuildServer(java.util.Map,
331 * org.openecomp.sdnc.sli.SvcLogicContext)
333 @SuppressWarnings("nls")
334 public Server rebuildServer(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
335 Server server = null;
336 RequestContext rc = new RequestContext(ctx);
339 setTimeForMetricsLogger();
343 validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
344 ProviderAdapter.PROPERTY_PROVIDER_NAME);
346 String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
347 String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
348 VMURL vm = VMURL.parseURL(vm_url);
349 if (validateVM(rc, appName, vm_url, vm))
352 IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
353 String identStr = (ident == null) ? null : ident.toString();
354 ctx.setAttribute("REBUILD_STATUS", "ERROR");
356 Context context = null;
358 context = getContext(rc, vm_url, identStr);
359 if (context != null) {
361 server = lookupServer(rc, context, vm.getServerId());
362 logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
364 // Manually checking image service until new PAL release
365 if (hasImageAccess(rc, context)) {
366 rebuildServer(rc, server, ctx);
368 ctx.setAttribute("REBUILD_STATUS", "SUCCESS");
370 msg = EELFResourceManager.format(Msg.REBUILD_SERVER_FAILED, server.getName(), server.getId(),
371 "Accessing Image Service Failed");
373 metricsLogger.error(msg);
374 doFailure(rc, HttpStatus.FORBIDDEN_403, msg);
378 ctx.setAttribute("REBUILD_STATUS", "CONTEXT_NOT_FOUND");
380 } catch (RequestFailedException e) {
381 doFailure(rc, e.getStatus(), e.getMessage());
382 ctx.setAttribute("REBUILD_STATUS", "ERROR");
383 } catch (ResourceNotFoundException e) {
384 msg = EELFResourceManager.format(Msg.SERVER_NOT_FOUND, e, vm_url);
385 ctx.setAttribute("REBUILD_STATUS", "ERROR");
387 metricsLogger.error(msg);
388 doFailure(rc, HttpStatus.NOT_FOUND_404, msg);
389 } catch (Exception e1) {
390 msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
391 STOP_SERVICE.toString(), vm_url, context == null ? "Unknown" : context.getTenantName());
392 ctx.setAttribute("REBUILD_STATUS", "ERROR");
393 logger.error(msg, e1);
394 metricsLogger.error(msg);
395 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
397 } catch (RequestFailedException e) {
398 doFailure(rc, e.getStatus(), e.getMessage());
399 ctx.setAttribute("REBUILD_STATUS", "ERROR");
406 protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
407 throws APPCException {
408 setMDC(Operation.REBUILD_SERVICE.toString(), "App-C IaaS Adapter:Rebuild", ADAPTER_NAME);
409 logOperation(Msg.REBUILDING_SERVER, params, context);
411 setTimeForMetricsLogger();
413 metricsLogger.info("Executing Provider Operation: Rebuild");
415 return rebuildServer(params, context);
418 private void setTimeForMetricsLogger() {
419 long startTime = System.currentTimeMillis();
420 TimeZone tz = TimeZone.getTimeZone("UTC");
421 DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
423 long endTime = System.currentTimeMillis();
424 long duration = endTime - startTime;
425 String durationStr = String.valueOf(duration);
426 String endTimeStrUTC = df.format(new Date());
427 MDC.put("EndTimestamp", endTimeStrUTC);
428 MDC.put("ElapsedTime", durationStr);
429 MDC.put("TargetEntity", "cdp");
430 MDC.put("TargetServiceName", "rebuild server");
431 MDC.put("ClassName", "org.openecomp.appc.adapter.iaas.provider.operation.impl.RebuildServer");