SonarFix- MigrateServer.java
[appc.git] / appc-adapters / appc-iaas-adapter / appc-iaas-adapter-bundle / src / main / java / org / onap / appc / adapter / iaas / provider / operation / impl / MigrateServer.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 import com.att.cdp.exceptions.ContextConnectionException;
26 import com.att.cdp.exceptions.ZoneException;
27 import com.att.cdp.zones.ComputeService;
28 import com.att.cdp.zones.Context;
29 import com.att.cdp.zones.model.ModelObject;
30 import com.att.cdp.zones.model.Server;
31 import com.att.eelf.configuration.EELFLogger;
32 import com.att.eelf.configuration.EELFManager;
33 import com.att.eelf.i18n.EELFResourceManager;
34 import org.glassfish.grizzly.http.util.HttpStatus;
35 import org.onap.appc.Constants;
36 import org.onap.appc.logging.LoggingConstants;
37 import org.onap.appc.logging.LoggingUtils;
38 import org.onap.appc.adapter.iaas.ProviderAdapter;
39 import org.onap.appc.adapter.iaas.impl.IdentityURL;
40 import org.onap.appc.adapter.iaas.impl.RequestContext;
41 import org.onap.appc.adapter.iaas.impl.RequestFailedException;
42 import org.onap.appc.adapter.iaas.impl.VMURL;
43 import org.onap.appc.adapter.iaas.provider.operation.common.constants.Property;
44 import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
45 import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderServerOperation;
46 import org.onap.appc.configuration.Configuration;
47 import org.onap.appc.configuration.ConfigurationFactory;
48 import org.onap.appc.exceptions.APPCException;
49 import org.onap.appc.i18n.Msg;
50 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
51 import org.slf4j.MDC;
52 import java.io.IOException;
53 import java.text.DateFormat;
54 import java.text.SimpleDateFormat;
55 import java.util.Arrays;
56 import java.util.Collection;
57 import java.util.Date;
58 import java.util.Map;
59 import java.util.TimeZone;
60 import static org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation.MIGRATE_SERVICE;
61 import static org.onap.appc.adapter.utils.Constants.ADAPTER_NAME;
62
63 public class MigrateServer extends ProviderServerOperation {
64
65     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MigrateServer.class);
66     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
67     private static final Configuration configuration = ConfigurationFactory.getConfiguration();
68
69     /**
70      * A list of valid initial VM statuses for a migrate operations
71      */
72     private final Collection<Server.Status> migratableStatuses = Arrays.asList(Server.Status.READY,
73             Server.Status.RUNNING, Server.Status.SUSPENDED);
74
75     private String getConnectionExceptionMessage(RequestContext rc, Context ctx, ZoneException e) throws ZoneException {
76         return EELFResourceManager.format(Msg.CONNECTION_FAILED_RETRY, ctx.getProvider().getName(),
77                 ctx.getComputeService().getURL(), ctx.getTenant().getName(), ctx.getTenant().getId(), e.getMessage(),
78                 Long.toString(rc.getRetryDelay()), Integer.toString(rc.getAttempts()),
79                 Integer.toString(rc.getRetryLimit()));
80     }
81
82     private void migrateServer(RequestContext rc, Server server, SvcLogicContext svcCtx)
83             throws ZoneException, RequestFailedException {
84         String msg;
85         Context ctx = server.getContext();
86         ComputeService service = ctx.getComputeService();
87         // Init status will equal final status
88         Server.Status initialStatus = server.getStatus();
89         if (initialStatus == null) {
90             throw new ZoneException("Failed to determine server's starting status");
91         }
92         // We can only migrate certain statuses
93         if (!migratableStatuses.contains(initialStatus)) {
94             throw new ZoneException(String.format("Cannot migrate server that is in %s state. Must be in one of [%s]",
95                     initialStatus, migratableStatuses));
96         }
97         setTimeForMetricsLogger();
98         // Is the skip Hypervisor check attribute populated?
99         String skipHypervisorCheck = configuration.getProperty(Property.SKIP_HYPERVISOR_CHECK);
100         if (skipHypervisorCheck == null && svcCtx != null) {
101             skipHypervisorCheck = svcCtx.getAttribute(ProviderAdapter.SKIP_HYPERVISOR_CHECK);
102         }
103         // Always perform Hypervisor check
104         // unless the skip is set to true
105         if (skipHypervisorCheck == null || (!skipHypervisorCheck.equalsIgnoreCase("true"))) {
106             // Check of the Hypervisor for the VM Server is UP and reachable
107             checkHypervisor(server);
108         }
109
110         boolean inConfirmPhase = false;
111         try {
112             while (rc.attempt()) {
113                 try {
114                     if (!inConfirmPhase) {
115                         // Initial migrate request
116                         service.migrateServer(server.getId());
117                         // Wait for change to verify resize
118                         waitForStateChange(rc, server, Server.Status.READY);
119                         inConfirmPhase = true;
120                     }
121                     if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
122                         msg = "Cannot Perform 'processResize' in  vm_state " + Server.Status.ERROR;
123                         logger.info(msg);
124                         msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, service.getURL());
125                         logger.error(msg);
126                         logger.info(msg);
127                         throw new RequestFailedException("Waiting for State Change", msg, HttpStatus.CONFLICT_409,
128                                 server);
129                     } else {
130                         // Verify resize
131                         logger.debug("MigrateServer: Before  service.processResize");
132                         service.processResize(server);
133                         logger.debug("MigrateServer:before 2nd waitForStateChange Current Status:" + server.getStatus()
134                                 + " Initail Status: " + initialStatus);
135                         // Wait for complete. will go back to init status
136                         waitForStateChange(rc, server, initialStatus);
137                         logger.info("Completed migrate request successfully");
138                         metricsLogger.info("Completed migrate request successfully");
139                         return;
140                     }
141                 } catch (ContextConnectionException e) {
142                     msg = getConnectionExceptionMessage(rc, ctx, e);
143                     // logger.info(msg, e);
144                     if (server.getStatus() != null && server.getStatus().equals(Server.Status.ERROR)) {
145                         throw new RequestFailedException("Migrate Server", msg, HttpStatus.CONFLICT_409, server);
146                     } else {
147                         logger.info("Migrate Server: Going to delay in ConnectionException");
148                         logger.debug("Server Status: " + server.getStatus());
149                         rc.delay();
150                     }
151                 }
152
153             }
154
155         } catch (ZoneException e) {
156             String phase = inConfirmPhase ? "VERIFY MIGRATE" : "REQUEST MIGRATE";
157             msg = EELFResourceManager.format(Msg.MIGRATE_SERVER_FAILED, server.getName(), server.getId(), phase,
158                     e.getMessage());
159
160             logger.error(msg, e);
161             throw new RequestFailedException("Migrate Server", msg, HttpStatus.METHOD_NOT_ALLOWED_405, server);
162         }
163     }
164
165     /**
166      * @see org.onap.appc.adapter.iaas.ProviderAdapter#migrateServer(java.util.Map,
167      *      org.onap.ccsdk.sli.core.sli.SvcLogicContext)
168      */
169     private Server migrateServer(Map<String, String> params, SvcLogicContext ctx) {
170         Server server = null;
171         RequestContext rc = new RequestContext(ctx);
172         rc.isAlive();
173         setTimeForMetricsLogger();
174         try {
175             validateParametersExist(params, ProviderAdapter.PROPERTY_INSTANCE_URL,
176                     ProviderAdapter.PROPERTY_PROVIDER_NAME);
177             String vm_url = params.get(ProviderAdapter.PROPERTY_INSTANCE_URL);
178             String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
179             VMURL vm = VMURL.parseURL(vm_url);
180             if (validateVM(rc, appName, vm_url, vm))
181                 return null;
182             IdentityURL ident = IdentityURL.parseURL(params.get(ProviderAdapter.PROPERTY_IDENTITY_URL));
183             String identStr = (ident == null) ? null : ident.toString();
184             server = conductServerMigration(rc, vm_url, identStr, ctx);
185         } catch (RequestFailedException e) {
186             doFailure(rc, e.getStatus(), e.getMessage());
187         }
188         return server;
189     }
190
191     @Override
192     protected ModelObject executeProviderOperation(Map<String, String> params, SvcLogicContext context)
193             throws APPCException {
194         setMDC(Operation.MIGRATE_SERVICE.toString(), "App-C IaaS Adapter:Migrate", ADAPTER_NAME);
195         logOperation(Msg.MIGRATING_SERVER, params, context);
196         setTimeForMetricsLogger();
197         metricsLogger.info("Executing Provider Operation: Migrate");
198         return migrateServer(params, context);
199     }
200
201     private void setTimeForMetricsLogger() {
202         String timestamp = LoggingUtils.generateTimestampStr(((Date) new Date()).toInstant());
203         MDC.put(LoggingConstants.MDCKeys.BEGIN_TIMESTAMP, timestamp);
204         MDC.put(LoggingConstants.MDCKeys.END_TIMESTAMP, timestamp);
205         MDC.put(LoggingConstants.MDCKeys.ELAPSED_TIME, "0");
206         MDC.put(LoggingConstants.MDCKeys.STATUS_CODE, LoggingConstants.StatusCodes.COMPLETE);
207         MDC.put(LoggingConstants.MDCKeys.TARGET_ENTITY, "cdp");
208         MDC.put(LoggingConstants.MDCKeys.TARGET_SERVICE_NAME, "migrate server");
209         MDC.put(LoggingConstants.MDCKeys.CLASS_NAME,
210                 "org.onap.appc.adapter.iaas.provider.operation.impl.MigrateServer");
211
212     }
213
214     private Server conductServerMigration(RequestContext rc, String vm_url, String identStr, SvcLogicContext ctx)
215             throws RequestFailedException {
216         String msg;
217         Context context = getContext(rc, vm_url, identStr);
218         VMURL vm = VMURL.parseURL(vm_url);
219         Server server = null;
220         try {
221             if (context != null) {
222                 server = lookupServer(rc, context, vm.getServerId());
223                 logger.debug(Msg.SERVER_FOUND, vm_url, context.getTenantName(), server.getStatus().toString());
224                 migrateServer(rc, server, ctx);
225                 server.refreshStatus();
226                 context.close();
227                 doSuccess(rc);
228             }
229         } catch (IOException | ZoneException e1) {
230             msg = EELFResourceManager.format(Msg.SERVER_OPERATION_EXCEPTION, e1, e1.getClass().getSimpleName(),
231                     MIGRATE_SERVICE.toString(), vm_url, context.getTenantName());
232             logger.error(msg, e1);
233             metricsLogger.error(msg);
234             doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, msg);
235         }
236         return server;
237     }
238 }