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