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